aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorChristoph Wurst <christoph@winzerhof-wurst.at>2024-09-16 10:07:44 +0200
committerChristoph Wurst <christoph@winzerhof-wurst.at>2024-09-16 10:07:44 +0200
commitcc8fc27f0b9e6048ef7b8ae58d18c5e78a6f5351 (patch)
tree4799795e3b18f826fb03aa9949462d1c7f450803
parent20798012dcdb02fb18128a78d4670bd3924121b9 (diff)
parent0a7b4b597e6dc6824f5ccedfe40ca4fd86dea07d (diff)
downloadnextcloud-server-refactor/class-string-constant.tar.gz
nextcloud-server-refactor/class-string-constant.zip
Merge remote-tracking branch 'origin/master' into refactor/class-string-constantrefactor/class-string-constant
-rw-r--r--.git-blame-ignore-revs31
-rw-r--r--.github/ISSUE_TEMPLATE/BUG_REPORT.yml1
-rw-r--r--apps/comments/tests/Unit/Activity/ListenerTest.php2
-rw-r--r--apps/comments/tests/Unit/AppInfo/ApplicationTest.php2
-rw-r--r--apps/comments/tests/Unit/Collaboration/CommentersSorterTest.php2
-rw-r--r--apps/comments/tests/Unit/Controller/NotificationsTest.php8
-rw-r--r--apps/comments/tests/Unit/EventHandlerTest.php4
-rw-r--r--apps/comments/tests/Unit/Notification/ListenerTest.php6
-rw-r--r--apps/comments/tests/Unit/Notification/NotifierTest.php14
-rw-r--r--apps/dav/lib/CalDAV/CalDavBackend.php30
-rw-r--r--apps/dav/lib/Connector/Sabre/Node.php2
-rw-r--r--apps/dav/tests/unit/BackgroundJob/OutOfOfficeEventDispatcherJobTest.php6
-rw-r--r--apps/dav/tests/unit/CalDAV/AppCalendar/AppCalendarTest.php4
-rw-r--r--apps/dav/tests/unit/CalDAV/AppCalendar/CalendarObjectTest.php26
-rw-r--r--apps/dav/tests/unit/CalDAV/CachedSubscriptionProviderTest.php4
-rw-r--r--apps/dav/tests/unit/CalDAV/CalDavBackendTest.php10
-rw-r--r--apps/dav/tests/unit/CalDAV/CalendarTest.php2
-rw-r--r--apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php30
-rw-r--r--apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php6
-rw-r--r--apps/dav/tests/unit/CalDAV/WebcalCaching/ConnectionTest.php2
-rw-r--r--apps/dav/tests/unit/Controller/UpcomingEventsControllerTest.php4
-rw-r--r--apps/dav/tests/unit/Service/AbsenceServiceTest.php16
-rw-r--r--apps/encryption/tests/Command/FixEncryptedVersionTest.php20
-rw-r--r--apps/encryption/tests/Command/TestEnableMasterKey.php2
-rw-r--r--apps/encryption/tests/Controller/RecoveryControllerTest.php6
-rw-r--r--apps/encryption/tests/Controller/SettingsControllerTest.php8
-rw-r--r--apps/encryption/tests/Controller/StatusControllerTest.php2
-rw-r--r--apps/encryption/tests/Crypto/CryptTest.php38
-rw-r--r--apps/encryption/tests/Crypto/DecryptAllTest.php4
-rw-r--r--apps/encryption/tests/Crypto/EncryptAllTest.php14
-rw-r--r--apps/encryption/tests/Crypto/EncryptionTest.php24
-rw-r--r--apps/encryption/tests/EncryptedStorageTest.php2
-rw-r--r--apps/encryption/tests/HookManagerTest.php4
-rw-r--r--apps/encryption/tests/Hooks/UserHooksTest.php16
-rw-r--r--apps/encryption/tests/KeyManagerTest.php60
-rw-r--r--apps/encryption/tests/RecoveryTest.php22
-rw-r--r--apps/encryption/tests/SessionTest.php24
-rw-r--r--apps/encryption/tests/Settings/AdminTest.php6
-rw-r--r--apps/encryption/tests/Users/SetupTest.php4
-rw-r--r--apps/encryption/tests/UtilTest.php14
-rw-r--r--apps/federatedfilesharing/tests/AddressHandlerTest.php10
-rw-r--r--apps/federatedfilesharing/tests/Controller/MountPublicLinkControllerTest.php2
-rw-r--r--apps/federatedfilesharing/tests/Controller/RequestHandlerControllerTest.php6
-rw-r--r--apps/federatedfilesharing/tests/FederatedShareProviderTest.php1978
-rw-r--r--apps/federatedfilesharing/tests/NotificationsTest.php2
-rw-r--r--apps/federatedfilesharing/tests/Settings/AdminTest.php6
-rw-r--r--apps/federatedfilesharing/tests/TokenHandlerTest.php2
-rw-r--r--apps/federation/tests/BackgroundJob/GetSharedSecretTest.php6
-rw-r--r--apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php6
-rw-r--r--apps/federation/tests/DAV/FedAuthTest.php2
-rw-r--r--apps/federation/tests/DbHandlerTest.php24
-rw-r--r--apps/federation/tests/Middleware/AddServerMiddlewareTest.php2
-rw-r--r--apps/federation/tests/Settings/AdminTest.php6
-rw-r--r--apps/federation/tests/SyncFederationAddressbooksTest.php6
-rw-r--r--apps/federation/tests/TrustedServersTest.php4
-rw-r--r--apps/files/l10n/es.js45
-rw-r--r--apps/files/l10n/es.json45
-rw-r--r--apps/files/l10n/pt_BR.js1
-rw-r--r--apps/files/l10n/pt_BR.json1
-rw-r--r--apps/files/tests/Activity/Filter/GenericTest.php14
-rw-r--r--apps/files/tests/Activity/ProviderTest.php4
-rw-r--r--apps/files/tests/Activity/Setting/GenericTest.php16
-rw-r--r--apps/files/tests/BackgroundJob/DeleteOrphanedItemsJobTest.php8
-rw-r--r--apps/files/tests/BackgroundJob/ScanFilesTest.php4
-rw-r--r--apps/files/tests/Command/DeleteOrphanedFilesTest.php2
-rw-r--r--apps/files/tests/Controller/ApiControllerTest.php22
-rw-r--r--apps/files/tests/Controller/ViewControllerTest.php4
-rw-r--r--apps/files/tests/HelperTest.php4
-rw-r--r--apps/files/tests/Service/TagServiceTest.php4
-rw-r--r--apps/files_external/l10n/ar.js4
-rw-r--r--apps/files_external/l10n/ar.json4
-rw-r--r--apps/files_external/l10n/de_DE.js2
-rw-r--r--apps/files_external/l10n/de_DE.json2
-rw-r--r--apps/files_external/l10n/pt_BR.js5
-rw-r--r--apps/files_external/l10n/pt_BR.json5
-rw-r--r--apps/files_external/lib/Controller/StoragesController.php2
-rw-r--r--apps/files_external/tests/Auth/AuthMechanismTest.php4
-rw-r--r--apps/files_external/tests/Auth/Password/GlobalAuth.php6
-rw-r--r--apps/files_external/tests/Backend/BackendTest.php6
-rw-r--r--apps/files_external/tests/Backend/LegacyBackendTest.php194
-rw-r--r--apps/files_external/tests/Command/ApplicableTest.php14
-rw-r--r--apps/files_external/tests/Command/ListCommandTest.php2
-rw-r--r--apps/files_external/tests/Config/UserPlaceholderHandlerTest.php4
-rw-r--r--apps/files_external/tests/Controller/AjaxControllerTest.php10
-rw-r--r--apps/files_external/tests/Controller/GlobalStoragesControllerTest.php2
-rw-r--r--apps/files_external/tests/Controller/StoragesControllerTest.php20
-rw-r--r--apps/files_external/tests/Controller/UserStoragesControllerTest.php4
-rw-r--r--apps/files_external/tests/DefinitionParameterTest.php4
-rw-r--r--apps/files_external/tests/FrontendDefinitionTraitTest.php6
-rw-r--r--apps/files_external/tests/LegacyDependencyCheckPolyfillTest.php72
-rw-r--r--apps/files_external/tests/Listener/StorePasswordListenerTest.php14
-rw-r--r--apps/files_external/tests/OwnCloudFunctionsTest.php2
-rw-r--r--apps/files_external/tests/PersonalMountTest.php2
-rw-r--r--apps/files_external/tests/Service/BackendServiceTest.php16
-rw-r--r--apps/files_external/tests/Service/DBConfigServiceTest.php38
-rw-r--r--apps/files_external/tests/Service/GlobalStoragesServiceTest.php12
-rw-r--r--apps/files_external/tests/Service/StoragesServiceTest.php18
-rw-r--r--apps/files_external/tests/Service/UserGlobalStoragesServiceTest.php40
-rw-r--r--apps/files_external/tests/Service/UserStoragesServiceTest.php10
-rw-r--r--apps/files_external/tests/Settings/AdminTest.php6
-rw-r--r--apps/files_external/tests/Settings/SectionTest.php6
-rw-r--r--apps/files_external/tests/Storage/Amazons3MultiPartTest.php4
-rw-r--r--apps/files_external/tests/Storage/Amazons3Test.php4
-rw-r--r--apps/files_external/tests/Storage/FtpTest.php2
-rw-r--r--apps/files_external/tests/Storage/SFTP_KeyTest.php12
-rw-r--r--apps/files_external/tests/Storage/SftpTest.php2
-rw-r--r--apps/files_external/tests/Storage/SmbTest.php14
-rw-r--r--apps/files_external/tests/Storage/SwiftTest.php2
-rw-r--r--apps/files_external/tests/Storage/WebdavTest.php2
-rw-r--r--apps/files_external/tests/StorageConfigTest.php2
-rw-r--r--apps/files_sharing/l10n/cs.js11
-rw-r--r--apps/files_sharing/l10n/cs.json11
-rw-r--r--apps/files_sharing/l10n/pt_BR.js16
-rw-r--r--apps/files_sharing/l10n/pt_BR.json16
-rw-r--r--apps/files_sharing/lib/External/Manager.php2
-rw-r--r--apps/files_sharing/tests/ApiTest.php66
-rw-r--r--apps/files_sharing/tests/CacheTest.php22
-rw-r--r--apps/files_sharing/tests/CapabilitiesTest.php44
-rw-r--r--apps/files_sharing/tests/Collaboration/ShareRecipientSorterTest.php4
-rw-r--r--apps/files_sharing/tests/Command/CleanupRemoteStoragesTest.php2
-rw-r--r--apps/files_sharing/tests/Controller/ExternalShareControllerTest.php14
-rw-r--r--apps/files_sharing/tests/Controller/PublicPreviewControllerTest.php16
-rw-r--r--apps/files_sharing/tests/Controller/ShareAPIControllerTest.php124
-rw-r--r--apps/files_sharing/tests/Controller/ShareControllerTest.php18
-rw-r--r--apps/files_sharing/tests/Controller/ShareInfoControllerTest.php12
-rw-r--r--apps/files_sharing/tests/Controller/ShareesAPIControllerTest.php14
-rw-r--r--apps/files_sharing/tests/DeleteOrphanedSharesJobTest.php2
-rw-r--r--apps/files_sharing/tests/EtagPropagationTest.php50
-rw-r--r--apps/files_sharing/tests/ExpireSharesJobTest.php4
-rw-r--r--apps/files_sharing/tests/External/CacheTest.php6
-rw-r--r--apps/files_sharing/tests/External/ManagerTest.php26
-rw-r--r--apps/files_sharing/tests/External/ScannerTest.php4
-rw-r--r--apps/files_sharing/tests/ExternalStorageTest.php4
-rw-r--r--apps/files_sharing/tests/GroupEtagPropagationTest.php8
-rw-r--r--apps/files_sharing/tests/HelperTest.php2
-rw-r--r--apps/files_sharing/tests/LockingTest.php6
-rw-r--r--apps/files_sharing/tests/Middleware/OCSShareAPIMiddlewareTest.php4
-rw-r--r--apps/files_sharing/tests/Middleware/ShareInfoMiddlewareTest.php20
-rw-r--r--apps/files_sharing/tests/Middleware/SharingCheckMiddlewareTest.php18
-rw-r--r--apps/files_sharing/tests/Migration/SetPasswordColumnTest.php2
-rw-r--r--apps/files_sharing/tests/MountProviderTest.php4
-rw-r--r--apps/files_sharing/tests/ShareTest.php10
-rw-r--r--apps/files_sharing/tests/SharedMountTest.php16
-rw-r--r--apps/files_sharing/tests/SharedStorageTest.php30
-rw-r--r--apps/files_sharing/tests/SizePropagationTest.php4
-rw-r--r--apps/files_sharing/tests/UnshareChildrenTest.php2
-rw-r--r--apps/files_sharing/tests/UpdaterTest.php8
-rw-r--r--apps/files_sharing/tests/WatcherTest.php4
-rw-r--r--apps/files_trashbin/tests/CapabilitiesTest.php2
-rw-r--r--apps/files_trashbin/tests/Command/CleanUpTest.php10
-rw-r--r--apps/files_trashbin/tests/Command/ExpireTest.php2
-rw-r--r--apps/files_trashbin/tests/Controller/PreviewControllerTest.php10
-rw-r--r--apps/files_trashbin/tests/ExpirationTest.php4
-rw-r--r--apps/files_trashbin/tests/StorageTest.php36
-rw-r--r--apps/files_trashbin/tests/TrashbinTest.php24
-rw-r--r--apps/files_versions/tests/Command/CleanupTest.php6
-rw-r--r--apps/files_versions/tests/Command/ExpireTest.php2
-rw-r--r--apps/files_versions/tests/Controller/PreviewControllerTest.php12
-rw-r--r--apps/files_versions/tests/ExpirationTest.php2
-rw-r--r--apps/files_versions/tests/StorageTest.php2
-rw-r--r--apps/files_versions/tests/VersioningTest.php38
-rw-r--r--apps/files_versions/tests/Versions/VersionManagerTest.php8
-rw-r--r--apps/oauth2/tests/Controller/LoginRedirectorControllerTest.php6
-rw-r--r--apps/oauth2/tests/Controller/OauthApiControllerTest.php24
-rw-r--r--apps/oauth2/tests/Controller/SettingsControllerTest.php6
-rw-r--r--apps/oauth2/tests/Db/AccessTokenMapperTest.php4
-rw-r--r--apps/oauth2/tests/Db/ClientMapperTest.php10
-rw-r--r--apps/oauth2/tests/Settings/AdminTest.php6
-rw-r--r--apps/provisioning_api/tests/CapabilitiesTest.php2
-rw-r--r--apps/provisioning_api/tests/Controller/AppConfigControllerTest.php18
-rw-r--r--apps/provisioning_api/tests/Controller/AppsControllerTest.php12
-rw-r--r--apps/provisioning_api/tests/Controller/GroupsControllerTest.php38
-rw-r--r--apps/provisioning_api/tests/Controller/UsersControllerTest.php178
-rw-r--r--apps/provisioning_api/tests/Middleware/ProvisioningApiMiddlewareTest.php4
-rw-r--r--apps/settings/l10n/ar.js3
-rw-r--r--apps/settings/l10n/ar.json3
-rw-r--r--apps/settings/l10n/cs.js4
-rw-r--r--apps/settings/l10n/cs.json4
-rw-r--r--apps/settings/l10n/de.js3
-rw-r--r--apps/settings/l10n/de.json3
-rw-r--r--apps/settings/l10n/de_DE.js3
-rw-r--r--apps/settings/l10n/de_DE.json3
-rw-r--r--apps/settings/l10n/en_GB.js3
-rw-r--r--apps/settings/l10n/en_GB.json3
-rw-r--r--apps/settings/l10n/es.js26
-rw-r--r--apps/settings/l10n/es.json26
-rw-r--r--apps/settings/l10n/ga.js3
-rw-r--r--apps/settings/l10n/ga.json3
-rw-r--r--apps/settings/l10n/gl.js3
-rw-r--r--apps/settings/l10n/gl.json3
-rw-r--r--apps/settings/l10n/ja.js3
-rw-r--r--apps/settings/l10n/ja.json3
-rw-r--r--apps/settings/l10n/pt_BR.js3
-rw-r--r--apps/settings/l10n/pt_BR.json3
-rw-r--r--apps/settings/l10n/ru.js3
-rw-r--r--apps/settings/l10n/ru.json3
-rw-r--r--apps/settings/l10n/tr.js3
-rw-r--r--apps/settings/l10n/tr.json3
-rw-r--r--apps/settings/l10n/zh_HK.js3
-rw-r--r--apps/settings/l10n/zh_HK.json3
-rw-r--r--apps/settings/l10n/zh_TW.js3
-rw-r--r--apps/settings/l10n/zh_TW.json3
-rw-r--r--apps/settings/tests/Activity/SecurityFilterTest.php12
-rw-r--r--apps/settings/tests/Activity/SecurityProviderTest.php6
-rw-r--r--apps/settings/tests/Activity/SecuritySettingTest.php12
-rw-r--r--apps/settings/tests/AppInfo/ApplicationTest.php4
-rw-r--r--apps/settings/tests/Controller/AdminSettingsControllerTest.php2
-rw-r--r--apps/settings/tests/Controller/AppSettingsControllerTest.php6
-rw-r--r--apps/settings/tests/Controller/AuthSettingsControllerTest.php18
-rw-r--r--apps/settings/tests/Controller/CheckSetupControllerTest.php10
-rw-r--r--apps/settings/tests/Controller/DelegationControllerTest.php2
-rw-r--r--apps/settings/tests/Controller/MailSettingsControllerTest.php6
-rw-r--r--apps/settings/tests/Controller/TwoFactorSettingsControllerTest.php4
-rw-r--r--apps/settings/tests/Controller/UsersControllerTest.php18
-rw-r--r--apps/settings/tests/Mailer/NewUserMailHelperTest.php8
-rw-r--r--apps/settings/tests/Middleware/SubadminMiddlewareTest.php12
-rw-r--r--apps/settings/tests/Settings/Admin/MailTest.php6
-rw-r--r--apps/settings/tests/Settings/Admin/SecurityTest.php8
-rw-r--r--apps/settings/tests/Settings/Personal/Security/AuthtokensTest.php2
-rw-r--r--apps/settings/tests/Settings/Personal/Security/PasswordTest.php2
-rw-r--r--apps/settings/tests/SetupChecks/AppDirsWithDifferentOwnerTest.php4
-rw-r--r--apps/sharebymail/tests/CapabilitiesTest.php2
-rw-r--r--apps/sharebymail/tests/ShareByMailProviderTest.php62
-rw-r--r--apps/systemtags/tests/Activity/SettingTest.php14
-rw-r--r--apps/systemtags/tests/Settings/AdminTest.php6
-rw-r--r--apps/theming/tests/CapabilitiesTest.php2
-rw-r--r--apps/theming/tests/Controller/IconControllerTest.php10
-rw-r--r--apps/theming/tests/Controller/ThemingControllerTest.php36
-rw-r--r--apps/theming/tests/Controller/UserThemeControllerTest.php4
-rw-r--r--apps/theming/tests/IconBuilderTest.php12
-rw-r--r--apps/theming/tests/ImageManagerTest.php26
-rw-r--r--apps/theming/tests/Service/ThemesServiceTest.php18
-rw-r--r--apps/theming/tests/ServicesTest.php2
-rw-r--r--apps/theming/tests/Settings/AdminSectionTest.php8
-rw-r--r--apps/theming/tests/Settings/AdminTest.php8
-rw-r--r--apps/theming/tests/Settings/PersonalTest.php6
-rw-r--r--apps/theming/tests/Themes/AccessibleThemeTestCase.php2
-rw-r--r--apps/theming/tests/Themes/DarkHighContrastThemeTest.php12
-rw-r--r--apps/theming/tests/Themes/DarkThemeTest.php14
-rw-r--r--apps/theming/tests/Themes/DefaultThemeTest.php16
-rw-r--r--apps/theming/tests/Themes/DyslexiaFontTest.php16
-rw-r--r--apps/theming/tests/Themes/HighContrastThemeTest.php12
-rw-r--r--apps/theming/tests/ThemingDefaultsTest.php88
-rw-r--r--apps/theming/tests/UtilTest.php46
-rw-r--r--apps/twofactor_backupcodes/tests/Db/BackupCodeMapperTest.php6
-rw-r--r--apps/twofactor_backupcodes/tests/Service/BackupCodeStorageTest.php2
-rw-r--r--apps/twofactor_backupcodes/tests/Unit/Activity/ProviderTest.php6
-rw-r--r--apps/twofactor_backupcodes/tests/Unit/BackgroundJob/CheckBackupCodeTest.php8
-rw-r--r--apps/twofactor_backupcodes/tests/Unit/BackgroundJob/RememberBackupCodesJobTest.php10
-rw-r--r--apps/twofactor_backupcodes/tests/Unit/Controller/SettingsControllerTest.php2
-rw-r--r--apps/twofactor_backupcodes/tests/Unit/Event/CodesGeneratedTest.php2
-rw-r--r--apps/twofactor_backupcodes/tests/Unit/Listener/ActivityPublisherTest.php4
-rw-r--r--apps/twofactor_backupcodes/tests/Unit/Listener/ClearNotificationsTest.php4
-rw-r--r--apps/twofactor_backupcodes/tests/Unit/Listener/ProviderDisabledTest.php6
-rw-r--r--apps/twofactor_backupcodes/tests/Unit/Listener/ProviderEnabledTest.php6
-rw-r--r--apps/twofactor_backupcodes/tests/Unit/Listener/RegistryUpdaterTest.php4
-rw-r--r--apps/twofactor_backupcodes/tests/Unit/Migration/CheckBackupCodeTest.php4
-rw-r--r--apps/twofactor_backupcodes/tests/Unit/Notification/NotifierTest.php6
-rw-r--r--apps/twofactor_backupcodes/tests/Unit/Provider/BackupCodesProviderTest.php16
-rw-r--r--apps/twofactor_backupcodes/tests/Unit/Service/BackupCodeStorageTest.php16
-rw-r--r--apps/updatenotification/tests/BackgroundJob/ResetTokenTest.php6
-rw-r--r--apps/updatenotification/tests/BackgroundJob/UpdateAvailableNotificationsTest.php16
-rw-r--r--apps/updatenotification/tests/Controller/AdminControllerTest.php2
-rw-r--r--apps/updatenotification/tests/Notification/NotifierTest.php2
-rw-r--r--apps/updatenotification/tests/Settings/AdminTest.php12
-rw-r--r--apps/updatenotification/tests/UpdateCheckerTest.php6
-rw-r--r--apps/user_ldap/l10n/es.js2
-rw-r--r--apps/user_ldap/l10n/es.json2
-rw-r--r--apps/user_ldap/lib/LoginListener.php12
-rw-r--r--apps/user_ldap/lib/Service/UpdateGroupsService.php6
-rw-r--r--apps/user_ldap/lib/SetupChecks/LdapConnection.php8
-rw-r--r--apps/user_ldap/lib/User/User.php3
-rw-r--r--apps/user_ldap/tests/AccessTest.php48
-rw-r--r--apps/user_ldap/tests/ConfigurationTest.php6
-rw-r--r--apps/user_ldap/tests/ConnectionTest.php10
-rw-r--r--apps/user_ldap/tests/GroupLDAPPluginTest.php26
-rw-r--r--apps/user_ldap/tests/Group_LDAPTest.php82
-rw-r--r--apps/user_ldap/tests/HelperTest.php6
-rw-r--r--apps/user_ldap/tests/Jobs/CleanUpTest.php12
-rw-r--r--apps/user_ldap/tests/Jobs/SyncTest.php6
-rw-r--r--apps/user_ldap/tests/LDAPProviderTest.php1730
-rw-r--r--apps/user_ldap/tests/LDAPTest.php4
-rw-r--r--apps/user_ldap/tests/Mapping/AbstractMappingTest.php22
-rw-r--r--apps/user_ldap/tests/Migration/AbstractUUIDFixTest.php8
-rw-r--r--apps/user_ldap/tests/Migration/UUIDFixInsertTest.php8
-rw-r--r--apps/user_ldap/tests/Settings/AdminTest.php6
-rw-r--r--apps/user_ldap/tests/Settings/SectionTest.php8
-rw-r--r--apps/user_ldap/tests/User/DeletedUsersIndexTest.php4
-rw-r--r--apps/user_ldap/tests/User/ManagerTest.php10
-rw-r--r--apps/user_ldap/tests/User/OfflineUserTest.php2
-rw-r--r--apps/user_ldap/tests/User/UserTest.php62
-rw-r--r--apps/user_ldap/tests/UserLDAPPluginTest.php34
-rw-r--r--apps/user_ldap/tests/User_LDAPTest.php106
-rw-r--r--apps/user_ldap/tests/User_ProxyTest.php6
-rw-r--r--apps/user_ldap/tests/WizardTest.php14
-rw-r--r--apps/user_status/tests/Unit/BackgroundJob/ClearOldStatusesBackgroundJobTest.php2
-rw-r--r--apps/user_status/tests/Unit/Connector/UserStatusTest.php4
-rw-r--r--apps/user_status/tests/Unit/Controller/PredefinedStatusControllerTest.php2
-rw-r--r--apps/weather_status/lib/Service/WeatherStatusService.php2
-rw-r--r--apps/webhook_listeners/tests/Db/WebhookListenerMapperTest.php10
-rw-r--r--apps/webhook_listeners/tests/Service/PHPMongoQueryTest.php2
-rw-r--r--apps/workflowengine/tests/Check/AbstractStringCheckTest.php8
-rw-r--r--apps/workflowengine/tests/Check/FileMimeTypeTest.php16
-rw-r--r--apps/workflowengine/tests/Check/RequestRemoteAddressTest.php8
-rw-r--r--apps/workflowengine/tests/Check/RequestTimeTest.php8
-rw-r--r--apps/workflowengine/tests/Check/RequestUserAgentTest.php2
-rw-r--r--apps/workflowengine/tests/ManagerTest.php26
-rw-r--r--build/psalm-baseline-ocp.xml8
-rw-r--r--build/psalm-baseline.xml11
-rw-r--r--core/l10n/es.js11
-rw-r--r--core/l10n/es.json11
-rw-r--r--core/l10n/pt_BR.js5
-rw-r--r--core/l10n/pt_BR.json5
-rw-r--r--core/l10n/uk.js6
-rw-r--r--core/l10n/uk.json6
-rw-r--r--lib/l10n/es.js3
-rw-r--r--lib/l10n/es.json3
-rw-r--r--lib/l10n/pt_BR.js33
-rw-r--r--lib/l10n/pt_BR.json33
-rw-r--r--lib/private/Log/LogDetails.php2
-rw-r--r--lib/private/Security/Bruteforce/Backend/MemoryCacheBackend.php2
-rw-r--r--lib/private/Security/RateLimiting/Backend/MemoryCacheBackend.php2
-rw-r--r--lib/private/User/Database.php2
-rw-r--r--lib/public/Files/LockNotAcquiredException.php2
-rw-r--r--lib/public/HintException.php2
-rw-r--r--tests/Core/Command/Config/App/DeleteConfigTest.php2
-rw-r--r--tests/Core/Command/Config/App/GetConfigTest.php2
-rw-r--r--tests/Core/Command/Config/App/SetConfigTest.php2
-rw-r--r--tests/Core/Command/Config/ImportTest.php12
-rw-r--r--tests/Core/Command/Config/ListConfigsTest.php2
-rw-r--r--tests/Core/Command/Config/System/DeleteConfigTest.php4
-rw-r--r--tests/Core/Command/Config/System/GetConfigTest.php2
-rw-r--r--tests/Core/Command/Config/System/SetConfigTest.php8
-rw-r--r--tests/Core/Command/Encryption/ChangeKeyStorageRootTest.php724
-rw-r--r--tests/Core/Command/Encryption/DecryptAllTest.php6
-rw-r--r--tests/Core/Command/Encryption/DisableTest.php2
-rw-r--r--tests/Core/Command/Encryption/EnableTest.php2
-rw-r--r--tests/Core/Command/Encryption/EncryptAllTest.php6
-rw-r--r--tests/Core/Command/Encryption/SetDefaultModuleTest.php4
-rw-r--r--tests/Core/Command/Group/AddTest.php4
-rw-r--r--tests/Core/Command/Group/AddUserTest.php6
-rw-r--r--tests/Core/Command/Group/DeleteTest.php8
-rw-r--r--tests/Core/Command/Group/InfoTest.php4
-rw-r--r--tests/Core/Command/Group/ListCommandTest.php4
-rw-r--r--tests/Core/Command/Group/RemoveUserTest.php6
-rw-r--r--tests/Core/Command/Log/FileTest.php8
-rw-r--r--tests/Core/Command/Log/ManageTest.php20
-rw-r--r--tests/Core/Command/Maintenance/DataFingerprintTest.php2
-rw-r--r--tests/Core/Command/Maintenance/Mimetype/UpdateDBTest.php8
-rw-r--r--tests/Core/Command/Maintenance/ModeTest.php2
-rw-r--r--tests/Core/Command/Maintenance/UpdateTheme.php2
-rw-r--r--tests/Core/Command/Preview/RepairTest.php2
-rw-r--r--tests/Core/Command/SystemTag/AddTest.php4
-rw-r--r--tests/Core/Command/SystemTag/DeleteTest.php4
-rw-r--r--tests/Core/Command/SystemTag/EditTest.php6
-rw-r--r--tests/Core/Command/SystemTag/ListCommandTest.php2
-rw-r--r--tests/Core/Command/TwoFactorAuth/CleanupTest.php2
-rw-r--r--tests/Core/Command/TwoFactorAuth/DisableTest.php6
-rw-r--r--tests/Core/Command/TwoFactorAuth/EnableTest.php6
-rw-r--r--tests/Core/Command/TwoFactorAuth/EnforceTest.php12
-rw-r--r--tests/Core/Command/TwoFactorAuth/StateTest.php6
-rw-r--r--tests/Core/Command/User/AuthTokens/DeleteTest.php12
-rw-r--r--tests/Core/Command/User/DeleteTest.php4
-rw-r--r--tests/Core/Command/User/DisableTest.php4
-rw-r--r--tests/Core/Command/User/EnableTest.php4
-rw-r--r--tests/Core/Command/User/LastSeenTest.php4
-rw-r--r--tests/Core/Command/User/SettingTest.php12
-rw-r--r--tests/Core/Controller/AppPasswordControllerTest.php14
-rw-r--r--tests/Core/Controller/AutoCompleteControllerTest.php2
-rw-r--r--tests/Core/Controller/AvatarControllerTest.php1132
-rw-r--r--tests/Core/Controller/ChangePasswordControllerTest.php10
-rw-r--r--tests/Core/Controller/ClientFlowLoginControllerTest.php20
-rw-r--r--tests/Core/Controller/ClientFlowLoginV2ControllerTest.php26
-rw-r--r--tests/Core/Controller/ContactsMenuControllerTest.php6
-rw-r--r--tests/Core/Controller/CssControllerTest.php10
-rw-r--r--tests/Core/Controller/GuestAvatarControllerTest.php2
-rw-r--r--tests/Core/Controller/JsControllerTest.php10
-rw-r--r--tests/Core/Controller/LoginControllerTest.php24
-rw-r--r--tests/Core/Controller/LostControllerTest.php36
-rw-r--r--tests/Core/Controller/NavigationControllerTest.php8
-rw-r--r--tests/Core/Controller/OCSControllerTest.php14
-rw-r--r--tests/Core/Controller/PreviewControllerTest.php18
-rw-r--r--tests/Core/Controller/TwoFactorChallengeControllerTest.php18
-rw-r--r--tests/Core/Controller/UserControllerTest.php2
-rw-r--r--tests/Core/Controller/WipeControllerTest.php4
-rw-r--r--tests/Core/Data/LoginFlowV2CredentialsTest.php6
-rw-r--r--tests/Core/Middleware/TwoFactorMiddlewareTest.php18
-rw-r--r--tests/Core/Service/LoginFlowV2ServiceUnitTest.php26
-rw-r--r--tests/Test/Repair/Owncloud/CleanPreviewsBackgroundJobTest.php10
-rw-r--r--tests/Test/Repair/Owncloud/CleanPreviewsTest.php6
-rw-r--r--tests/Test/Repair/Owncloud/UpdateLanguageCodesTest.php4
-rw-r--r--tests/lib/Accounts/AccountManagerTest.php6
-rw-r--r--tests/lib/Accounts/AccountPropertyCollectionTest.php16
-rw-r--r--tests/lib/Accounts/AccountPropertyTest.php14
-rw-r--r--tests/lib/Accounts/AccountTest.php12
-rw-r--r--tests/lib/Accounts/HooksTest.php2
-rw-r--r--tests/lib/Activity/ManagerTest.php20
-rw-r--r--tests/lib/AllConfigTest.php30
-rw-r--r--tests/lib/App/AppManagerTest.php50
-rw-r--r--tests/lib/App/AppStore/Bundles/BundleBase.php6
-rw-r--r--tests/lib/App/AppStore/Bundles/BundleFetcherTest.php6
-rw-r--r--tests/lib/App/AppStore/Fetcher/AppDiscoverFetcherTest.php6
-rw-r--r--tests/lib/App/AppStore/Fetcher/AppFetcherTest.php10
-rw-r--r--tests/lib/App/AppStore/Fetcher/CategoryFetcherTest.php4
-rw-r--r--tests/lib/App/AppStore/Fetcher/FetcherBase.php18
-rw-r--r--tests/lib/App/AppStore/Version/VersionParserTest.php6
-rw-r--r--tests/lib/App/AppStore/Version/VersionTest.php4
-rw-r--r--tests/lib/App/CompareVersionTest.php6
-rw-r--r--tests/lib/App/DependencyAnalyzerTest.php12
-rw-r--r--tests/lib/App/InfoParserTest.php4
-rw-r--r--tests/lib/App/PlatformRepositoryTest.php2
-rw-r--r--tests/lib/AppConfigTest.php8
-rw-r--r--tests/lib/AppFramework/AppTest.php442
-rw-r--r--tests/lib/AppFramework/Controller/ApiControllerTest.php2
-rw-r--r--tests/lib/AppFramework/Controller/AuthPublicShareControllerTest.php8
-rw-r--r--tests/lib/AppFramework/Controller/ControllerTest.php14
-rw-r--r--tests/lib/AppFramework/Controller/OCSControllerTest.php10
-rw-r--r--tests/lib/AppFramework/Controller/PublicShareControllerTest.php4
-rw-r--r--tests/lib/AppFramework/Db/EntityTest.php46
-rw-r--r--tests/lib/AppFramework/Db/QBMapperTest.php6
-rw-r--r--tests/lib/AppFramework/DependencyInjection/DIContainerTest.php12
-rw-r--r--tests/lib/AppFramework/DependencyInjection/DIIntergrationTests.php8
-rw-r--r--tests/lib/AppFramework/Http/ContentSecurityPolicyTest.php126
-rw-r--r--tests/lib/AppFramework/Http/DataResponseTest.php8
-rw-r--r--tests/lib/AppFramework/Http/DispatcherTest.php20
-rw-r--r--tests/lib/AppFramework/Http/DownloadResponseTest.php4
-rw-r--r--tests/lib/AppFramework/Http/EmptyContentSecurityPolicyTest.php120
-rw-r--r--tests/lib/AppFramework/Http/EmptyFeaturePolicyTest.php26
-rw-r--r--tests/lib/AppFramework/Http/FeaturePolicyTest.php26
-rw-r--r--tests/lib/AppFramework/Http/FileDisplayResponseTest.php186
-rw-r--r--tests/lib/AppFramework/Http/HttpTest.php6
-rw-r--r--tests/lib/AppFramework/Http/JSONResponseTest.php14
-rw-r--r--tests/lib/AppFramework/Http/OutputTest.php6
-rw-r--r--tests/lib/AppFramework/Http/PublicTemplateResponseTest.php10
-rw-r--r--tests/lib/AppFramework/Http/RedirectResponseTest.php4
-rw-r--r--tests/lib/AppFramework/Http/RequestTest.php140
-rw-r--r--tests/lib/AppFramework/Http/ResponseTest.php42
-rw-r--r--tests/lib/AppFramework/Http/StreamResponseTest.php8
-rw-r--r--tests/lib/AppFramework/Http/TemplateResponseTest.php12
-rw-r--r--tests/lib/AppFramework/Middleware/AdditionalScriptsMiddlewareTest.php10
-rw-r--r--tests/lib/AppFramework/Middleware/CompressionMiddlewareTest.php10
-rw-r--r--tests/lib/AppFramework/Middleware/MiddlewareDispatcherTest.php22
-rw-r--r--tests/lib/AppFramework/Middleware/NotModifiedMiddlewareTest.php2
-rw-r--r--tests/lib/AppFramework/Middleware/OCSMiddlewareTest.php8
-rw-r--r--tests/lib/AppFramework/Middleware/PublicShare/PublicShareMiddlewareTest.php24
-rw-r--r--tests/lib/AppFramework/Middleware/Security/CORSMiddlewareTest.php6
-rw-r--r--tests/lib/AppFramework/Middleware/Security/CSPMiddlewareTest.php6
-rw-r--r--tests/lib/AppFramework/Middleware/Security/FeaturePolicyMiddlewareTest.php4
-rw-r--r--tests/lib/AppFramework/Middleware/Security/PasswordConfirmationMiddlewareTest.php10
-rw-r--r--tests/lib/AppFramework/Middleware/Security/SameSiteCookieMiddlewareTest.php12
-rw-r--r--tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php12
-rw-r--r--tests/lib/AppFramework/Routing/RoutingTest.php42
-rw-r--r--tests/lib/AppFramework/Utility/ControllerMethodReflectorTest.php32
-rw-r--r--tests/lib/AppFramework/Utility/SimpleContainerTest.php510
-rw-r--r--tests/lib/AppTest.php14
-rw-r--r--tests/lib/Archive/TestBase.php18
-rw-r--r--tests/lib/Authentication/Events/RemoteWipeFinishedTest.php2
-rw-r--r--tests/lib/Authentication/Events/RemoteWipeStartedTest.php2
-rw-r--r--tests/lib/Authentication/Listeners/RemoteWipeActivityListenerTest.php8
-rw-r--r--tests/lib/Authentication/Listeners/RemoteWipeEmailListenerTest.php18
-rw-r--r--tests/lib/Authentication/Listeners/RemoteWipeNotificationsListenerTest.php6
-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.php4
-rw-r--r--tests/lib/Authentication/Login/EmailLoginCommandTest.php12
-rw-r--r--tests/lib/Authentication/Login/FinishRememberedLoginCommandTest.php6
-rw-r--r--tests/lib/Authentication/Login/LoggedInCheckCommandTest.php4
-rw-r--r--tests/lib/Authentication/Login/PreLoginHookCommandTest.php2
-rw-r--r--tests/lib/Authentication/Login/SetUserTimezoneCommandTest.php4
-rw-r--r--tests/lib/Authentication/Login/TwoFactorCommandTest.php16
-rw-r--r--tests/lib/Authentication/Login/UidLoginCommandTest.php4
-rw-r--r--tests/lib/Authentication/Login/UpdateLastPasswordConfirmCommandTest.php2
-rw-r--r--tests/lib/Authentication/Login/UserDisabledCheckCommandTest.php6
-rw-r--r--tests/lib/Authentication/LoginCredentials/CredentialsTest.php6
-rw-r--r--tests/lib/Authentication/LoginCredentials/StoreTest.php20
-rw-r--r--tests/lib/Authentication/Token/ManagerTest.php50
-rw-r--r--tests/lib/Authentication/Token/PublicKeyTokenMapperTest.php28
-rw-r--r--tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php50
-rw-r--r--tests/lib/Authentication/Token/PublicKeyTokenTest.php4
-rw-r--r--tests/lib/Authentication/Token/RemoteWipeTest.php6
-rw-r--r--tests/lib/Authentication/TwoFactorAuth/Db/ProviderUserAssignmentDaoTest.php12
-rw-r--r--tests/lib/Authentication/TwoFactorAuth/EnforcementStateTest.php8
-rw-r--r--tests/lib/Authentication/TwoFactorAuth/ManagerTest.php44
-rw-r--r--tests/lib/Authentication/TwoFactorAuth/MandatoryTwoFactorTest.php18
-rw-r--r--tests/lib/Authentication/TwoFactorAuth/ProviderLoaderTest.php6
-rw-r--r--tests/lib/Authentication/TwoFactorAuth/ProviderManagerTest.php12
-rw-r--r--tests/lib/Authentication/TwoFactorAuth/ProviderSetTest.php10
-rw-r--r--tests/lib/Authentication/TwoFactorAuth/RegistryTest.php10
-rw-r--r--tests/lib/AutoLoaderTest.php14
-rw-r--r--tests/lib/Avatar/AvatarManagerTest.php8
-rw-r--r--tests/lib/Avatar/GuestAvatarTest.php4
-rw-r--r--tests/lib/Avatar/UserAvatarTest.php24
-rw-r--r--tests/lib/BackgroundJob/JobListTest.php22
-rw-r--r--tests/lib/BackgroundJob/JobTest.php4
-rw-r--r--tests/lib/BackgroundJob/QueuedJobTest.php2
-rw-r--r--tests/lib/BackgroundJob/TimedJobTest.php6
-rw-r--r--tests/lib/Cache/CappedMemoryCacheTest.php6
-rw-r--r--tests/lib/Cache/FileCacheTest.php6
-rw-r--r--tests/lib/Cache/TestCache.php4
-rw-r--r--tests/lib/Calendar/ManagerTest.php12
-rw-r--r--tests/lib/CapabilitiesManagerTest.php14
-rw-r--r--tests/lib/Collaboration/Collaborators/GroupPluginTest.php2
-rw-r--r--tests/lib/Collaboration/Collaborators/LookupPluginTest.php10
-rw-r--r--tests/lib/Collaboration/Collaborators/MailPluginTest.php4
-rw-r--r--tests/lib/Collaboration/Collaborators/RemotePluginTest.php6
-rw-r--r--tests/lib/Collaboration/Collaborators/SearchResultTest.php4
-rw-r--r--tests/lib/Collaboration/Collaborators/SearchTest.php2
-rw-r--r--tests/lib/Collaboration/Collaborators/UserPluginTest.php6
-rw-r--r--tests/lib/Command/AsyncBusTest.php360
-rw-r--r--tests/lib/Command/Integrity/SignAppTest.php14
-rw-r--r--tests/lib/Command/Integrity/SignCoreTest.php12
-rw-r--r--tests/lib/Comments/CommentTest.php12
-rw-r--r--tests/lib/Comments/ManagerTest.php88
-rw-r--r--tests/lib/ConfigTest.php18
-rw-r--r--tests/lib/Contacts/ContactsMenu/ActionFactoryTest.php4
-rw-r--r--tests/lib/Contacts/ContactsMenu/ActionProviderStoreTest.php6
-rw-r--r--tests/lib/Contacts/ContactsMenu/Actions/LinkActionTest.php12
-rw-r--r--tests/lib/Contacts/ContactsMenu/ContactsStoreTest.php34
-rw-r--r--tests/lib/Contacts/ContactsMenu/EntryTest.php12
-rw-r--r--tests/lib/Contacts/ContactsMenu/ManagerTest.php10
-rw-r--r--tests/lib/Contacts/ContactsMenu/Providers/EMailproviderTest.php4
-rw-r--r--tests/lib/ContactsManagerTest.php20
-rw-r--r--tests/lib/DB/ConnectionFactoryTest.php2
-rw-r--r--tests/lib/DB/MigrationsTest.php48
-rw-r--r--tests/lib/DB/MigratorTest.php14
-rw-r--r--tests/lib/DB/OCPostgreSqlPlatformTest.php2
-rw-r--r--tests/lib/DB/QueryBuilder/ExpressionBuilderDBTest.php10
-rw-r--r--tests/lib/DB/QueryBuilder/ExpressionBuilderTest.php30
-rw-r--r--tests/lib/DB/QueryBuilder/FunctionBuilderTest.php32
-rw-r--r--tests/lib/DB/QueryBuilder/Partitioned/PartitionedQueryBuilderTest.php10
-rw-r--r--tests/lib/DB/QueryBuilder/QueryBuilderTest.php74
-rw-r--r--tests/lib/DB/QueryBuilder/QuoteHelperTest.php4
-rw-r--r--tests/lib/DB/QueryBuilder/Sharded/SharedQueryBuilderTest.php14
-rw-r--r--tests/lib/DateTimeFormatterTest.php10
-rw-r--r--tests/lib/Diagnostics/EventLoggerTest.php2
-rw-r--r--tests/lib/Diagnostics/QueryLoggerTest.php2
-rw-r--r--tests/lib/DirectEditing/ManagerTest.php12
-rw-r--r--tests/lib/Encryption/DecryptAllTest.php14
-rw-r--r--tests/lib/Encryption/EncryptionWrapperTest.php2
-rw-r--r--tests/lib/Encryption/Keys/StorageTest.php1226
-rw-r--r--tests/lib/Encryption/ManagerTest.php20
-rw-r--r--tests/lib/Encryption/UpdateTest.php6
-rw-r--r--tests/lib/Encryption/UtilTest.php16
-rw-r--r--tests/lib/ErrorHandlerTest.php2
-rw-r--r--tests/lib/Federation/CloudIdTest.php2
-rw-r--r--tests/lib/Files/AppData/AppDataTest.php6
-rw-r--r--tests/lib/Files/AppData/FactoryTest.php2
-rw-r--r--tests/lib/Files/Cache/CacheTest.php52
-rw-r--r--tests/lib/Files/Cache/HomeCacheTest.php4
-rw-r--r--tests/lib/Files/Cache/LocalRootScannerTest.php4
-rw-r--r--tests/lib/Files/Cache/PropagatorTest.php10
-rw-r--r--tests/lib/Files/Cache/ScannerTest.php36
-rw-r--r--tests/lib/Files/Cache/SearchBuilderTest.php2
-rw-r--r--tests/lib/Files/Cache/UpdaterLegacyTest.php16
-rw-r--r--tests/lib/Files/Cache/UpdaterTest.php18
-rw-r--r--tests/lib/Files/Cache/WatcherTest.php10
-rw-r--r--tests/lib/Files/Cache/Wrapper/CacheJailTest.php26
-rw-r--r--tests/lib/Files/Cache/Wrapper/CachePermissionsMaskTest.php6
-rw-r--r--tests/lib/Files/Config/UserMountCacheTest.php30
-rw-r--r--tests/lib/Files/EtagTest.php2
-rw-r--r--tests/lib/Files/FileInfoTest.php4
-rw-r--r--tests/lib/Files/FilesystemTest.php952
-rw-r--r--tests/lib/Files/Mount/ManagerTest.php4
-rw-r--r--tests/lib/Files/Mount/MountPointTest.php4
-rw-r--r--tests/lib/Files/Mount/MountTest.php88
-rw-r--r--tests/lib/Files/Mount/ObjectHomeMountProviderTest.php14
-rw-r--r--tests/lib/Files/Mount/ObjectStorePreviewCacheMountProviderTest.php4
-rw-r--r--tests/lib/Files/Mount/RootMountProviderTest.php6
-rw-r--r--tests/lib/Files/Node/FileTest.php20
-rw-r--r--tests/lib/Files/Node/FolderTest.php46
-rw-r--r--tests/lib/Files/Node/HookConnectorTest.php6
-rw-r--r--tests/lib/Files/Node/IntegrationTest.php4
-rw-r--r--tests/lib/Files/Node/NodeTest.php54
-rw-r--r--tests/lib/Files/Node/RootTest.php12
-rw-r--r--tests/lib/Files/ObjectStore/AzureTest.php2
-rw-r--r--tests/lib/Files/ObjectStore/MapperTest.php2
-rw-r--r--tests/lib/Files/ObjectStore/ObjectStoreScannerTest.php6
-rw-r--r--tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php24
-rw-r--r--tests/lib/Files/ObjectStore/ObjectStoreTest.php14
-rw-r--r--tests/lib/Files/ObjectStore/S3Test.php8
-rw-r--r--tests/lib/Files/ObjectStore/SwiftTest.php2
-rw-r--r--tests/lib/Files/PathVerificationTest.php10
-rw-r--r--tests/lib/Files/Search/QueryOptimizer/CombinedTests.php10
-rw-r--r--tests/lib/Files/Search/QueryOptimizer/FlattenNestedBoolTest.php2
-rw-r--r--tests/lib/Files/Search/QueryOptimizer/MergeDistributiveOperationsTest.php10
-rw-r--r--tests/lib/Files/Search/QueryOptimizer/OrEqualsToInTest.php10
-rw-r--r--tests/lib/Files/Search/SearchIntegrationTest.php2
-rw-r--r--tests/lib/Files/SimpleFS/InMemoryFileTest.php18
-rw-r--r--tests/lib/Files/SimpleFS/SimpleFileTest.php22
-rw-r--r--tests/lib/Files/SimpleFS/SimpleFolderTest.php16
-rw-r--r--tests/lib/Files/Storage/CommonTest.php10
-rw-r--r--tests/lib/Files/Storage/HomeTest.php172
-rw-r--r--tests/lib/Files/Storage/LocalTest.php24
-rw-r--r--tests/lib/Files/Storage/Storage.php1334
-rw-r--r--tests/lib/Files/Storage/StorageFactoryTest.php6
-rw-r--r--tests/lib/Files/Storage/Wrapper/AvailabilityTest.php12
-rw-r--r--tests/lib/Files/Storage/Wrapper/EncodingTest.php26
-rw-r--r--tests/lib/Files/Storage/Wrapper/EncryptionTest.php2064
-rw-r--r--tests/lib/Files/Storage/Wrapper/JailTest.php4
-rw-r--r--tests/lib/Files/Storage/Wrapper/KnownMtimeTest.php2
-rw-r--r--tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php32
-rw-r--r--tests/lib/Files/Storage/Wrapper/QuotaTest.php458
-rw-r--r--tests/lib/Files/Storage/Wrapper/WrapperTest.php66
-rw-r--r--tests/lib/Files/Stream/EncryptionTest.php742
-rw-r--r--tests/lib/Files/Stream/HashWrapperTest.php2
-rw-r--r--tests/lib/Files/Stream/QuotaTest.php28
-rw-r--r--tests/lib/Files/Type/DetectionTest.php2
-rw-r--r--tests/lib/Files/Type/LoaderTest.php8
-rw-r--r--tests/lib/Files/Utils/ScannerTest.php12
-rw-r--r--tests/lib/Files/ViewTest.php162
-rw-r--r--tests/lib/GlobalScale/ConfigTest.php4
-rw-r--r--tests/lib/Group/Backend.php10
-rw-r--r--tests/lib/Group/GroupTest.php950
-rw-r--r--tests/lib/Group/ManagerTest.php60
-rw-r--r--tests/lib/Group/MetaDataTest.php8
-rw-r--r--tests/lib/HelperStorageTest.php14
-rw-r--r--tests/lib/Hooks/BasicEmitterTest.php36
-rw-r--r--tests/lib/Http/Client/DnsPinMiddlewareTest.php16
-rw-r--r--tests/lib/Http/Client/NegativeDnsCacheTest.php2
-rw-r--r--tests/lib/Http/Client/ResponseTest.php8
-rw-r--r--tests/lib/ImageTest.php38
-rw-r--r--tests/lib/InfoXmlTest.php2
-rw-r--r--tests/lib/InstallerTest.php20
-rw-r--r--tests/lib/IntegrityCheck/CheckerTest.php2306
-rw-r--r--tests/lib/IntegrityCheck/Helpers/AppLocatorTest.php4
-rw-r--r--tests/lib/IntegrityCheck/Helpers/EnvironmentHelperTest.php4
-rw-r--r--tests/lib/IntegrityCheck/Helpers/FileAccessHelperTest.php10
-rw-r--r--tests/lib/L10N/L10nTest.php22
-rw-r--r--tests/lib/L10N/LanguageIteratorTest.php2
-rw-r--r--tests/lib/LargeFileHelperGetFileSizeTest.php4
-rw-r--r--tests/lib/LargeFileHelperTest.php8
-rw-r--r--tests/lib/LegacyHelperTest.php14
-rw-r--r--tests/lib/Lock/DBLockingProviderTest.php4
-rw-r--r--tests/lib/Lock/LockingProvider.php46
-rw-r--r--tests/lib/Lock/NonCachingDBLockingProviderTest.php2
-rw-r--r--tests/lib/Lockdown/Filesystem/NoFSTest.php2
-rw-r--r--tests/lib/Lockdown/Filesystem/NullCacheTest.php40
-rw-r--r--tests/lib/Lockdown/Filesystem/NullStorageTest.php72
-rw-r--r--tests/lib/Lockdown/LockdownManagerTest.php6
-rw-r--r--tests/lib/Log/ExceptionSerializerTest.php4
-rw-r--r--tests/lib/Log/FileTest.php4
-rw-r--r--tests/lib/Log/LogFactoryTest.php10
-rw-r--r--tests/lib/LoggerTest.php4
-rw-r--r--tests/lib/Mail/EMailTemplateTest.php8
-rw-r--r--tests/lib/Mail/MailerTest.php22
-rw-r--r--tests/lib/Mail/MessageTest.php30
-rw-r--r--tests/lib/Memcache/APCuTest.php4
-rw-r--r--tests/lib/Memcache/Cache.php42
-rw-r--r--tests/lib/Memcache/CasTraitTest.php4
-rw-r--r--tests/lib/Memcache/FactoryTest.php4
-rw-r--r--tests/lib/Memcache/MemcachedTest.php2
-rw-r--r--tests/lib/Memcache/RedisTest.php6
-rw-r--r--tests/lib/MemoryInfoTest.php4
-rw-r--r--tests/lib/Migration/BackgroundRepairTest.php8
-rw-r--r--tests/lib/NaturalSortTest.php4
-rw-r--r--tests/lib/NavigationManagerTest.php16
-rw-r--r--tests/lib/Notification/ActionTest.php18
-rw-r--r--tests/lib/Notification/NotificationTest.php62
-rw-r--r--tests/lib/OCS/DiscoveryServiceTest.php4
-rw-r--r--tests/lib/OCS/ProviderTest.php8
-rw-r--r--tests/lib/Preview/BackgroundCleanupJobTest.php6
-rw-r--r--tests/lib/Preview/GeneratorTest.php14
-rw-r--r--tests/lib/Preview/Provider.php2
-rw-r--r--tests/lib/PublicNamespace/UtilTest.php2
-rw-r--r--tests/lib/Remote/Api/OCSTest.php6
-rw-r--r--tests/lib/Remote/InstanceTest.php8
-rw-r--r--tests/lib/Repair/CleanTagsTest.php2
-rw-r--r--tests/lib/Repair/ClearFrontendCachesTest.php2
-rw-r--r--tests/lib/Repair/ClearGeneratedAvatarCacheTest.php2
-rw-r--r--tests/lib/Repair/OldGroupMembershipSharesTest.php2
-rw-r--r--tests/lib/Repair/RepairCollationTest.php2
-rw-r--r--tests/lib/Repair/RepairDavSharesTest.php2
-rw-r--r--tests/lib/Repair/RepairInvalidSharesTest.php4
-rw-r--r--tests/lib/Repair/RepairMimeTypesTest.php8
-rw-r--r--tests/lib/RepairTest.php8
-rw-r--r--tests/lib/RichObjectStrings/DefinitionsTest.php4
-rw-r--r--tests/lib/RichObjectStrings/ValidatorTest.php2
-rw-r--r--tests/lib/Security/Bruteforce/ThrottlerTest.php4
-rw-r--r--tests/lib/Security/CSP/AddContentSecurityPolicyEventTest.php2
-rw-r--r--tests/lib/Security/CSP/ContentSecurityPolicyManagerTest.php6
-rw-r--r--tests/lib/Security/CSP/ContentSecurityPolicyNonceManagerTest.php4
-rw-r--r--tests/lib/Security/CSRF/CsrfTokenGeneratorTest.php4
-rw-r--r--tests/lib/Security/CSRF/CsrfTokenManagerTest.php16
-rw-r--r--tests/lib/Security/CSRF/CsrfTokenTest.php6
-rw-r--r--tests/lib/Security/CSRF/TokenStorage/SessionStorageTest.php14
-rw-r--r--tests/lib/Security/CertificateManagerTest.php14
-rw-r--r--tests/lib/Security/CertificateTest.php20
-rw-r--r--tests/lib/Security/CredentialsManagerTest.php2
-rw-r--r--tests/lib/Security/CryptoTest.php16
-rw-r--r--tests/lib/Security/Events/GenerateSecurePasswordEventTest.php6
-rw-r--r--tests/lib/Security/Events/ValidatePasswordPolicyEventTest.php4
-rw-r--r--tests/lib/Security/FeaturePolicy/AddFeaturePolicyEventTest.php2
-rw-r--r--tests/lib/Security/FeaturePolicy/FeaturePolicyManagerTest.php4
-rw-r--r--tests/lib/Security/HasherTest.php24
-rw-r--r--tests/lib/Security/IdentityProof/KeyTest.php4
-rw-r--r--tests/lib/Security/IdentityProof/ManagerTest.php10
-rw-r--r--tests/lib/Security/IdentityProof/SignerTest.php8
-rw-r--r--tests/lib/Security/Normalizer/IpAddressTest.php4
-rw-r--r--tests/lib/Security/RateLimiting/Backend/MemoryCacheBackendTest.php8
-rw-r--r--tests/lib/Security/RateLimiting/LimiterTest.php8
-rw-r--r--tests/lib/Security/SecureRandomTest.php10
-rw-r--r--tests/lib/Security/TrustedDomainHelperTest.php6
-rw-r--r--tests/lib/Security/VerificationToken/VerificationTokenTest.php20
-rw-r--r--tests/lib/ServerTest.php350
-rw-r--r--tests/lib/Session/CryptoWrappingTest.php2
-rw-r--r--tests/lib/Session/MemoryTest.php2
-rw-r--r--tests/lib/Session/Session.php16
-rw-r--r--tests/lib/Settings/ManagerTest.php18
-rw-r--r--tests/lib/Settings/SectionTest.php6
-rw-r--r--tests/lib/SetupTest.php10
-rw-r--r--tests/lib/Share/HelperTest.php4
-rw-r--r--tests/lib/Share/ShareTest.php4
-rw-r--r--tests/lib/Share20/DefaultShareProviderTest.php94
-rw-r--r--tests/lib/Share20/LegacyHooksTest.php12
-rw-r--r--tests/lib/Share20/ManagerTest.php9380
-rw-r--r--tests/lib/Share20/ShareByMailProviderTest.php4
-rw-r--r--tests/lib/Share20/ShareHelperTest.php8
-rw-r--r--tests/lib/Share20/ShareTest.php14
-rw-r--r--tests/lib/SubAdminTest.php28
-rw-r--r--tests/lib/Support/Subscription/RegistryTest.php22
-rw-r--r--tests/lib/SystemTag/SystemTagManagerTest.php36
-rw-r--r--tests/lib/SystemTag/SystemTagObjectMapperTest.php34
-rw-r--r--tests/lib/TagsTest.php24
-rw-r--r--tests/lib/TaskProcessing/TaskProcessingTest.php28
-rw-r--r--tests/lib/TempManagerTest.php22
-rw-r--r--tests/lib/Template/CSSResourceLocatorTest.php2
-rw-r--r--tests/lib/Template/JSCombinerTest.php36
-rw-r--r--tests/lib/Template/JSResourceLocatorTest.php6
-rw-r--r--tests/lib/Template/ResourceLocatorTest.php6
-rw-r--r--tests/lib/TemplateFunctionsTest.php50
-rw-r--r--tests/lib/TextProcessing/TextProcessingTest.php14
-rw-r--r--tests/lib/Updater/ChangesCheckTest.php16
-rw-r--r--tests/lib/Updater/ReleaseMetadataTest.php4
-rw-r--r--tests/lib/Updater/VersionCheckTest.php14
-rw-r--r--tests/lib/UpdaterTest.php2
-rw-r--r--tests/lib/UrlGeneratorTest.php22
-rw-r--r--tests/lib/User/Backend.php6
-rw-r--r--tests/lib/User/DatabaseTest.php10
-rw-r--r--tests/lib/User/ManagerTest.php56
-rw-r--r--tests/lib/User/SessionTest.php50
-rw-r--r--tests/lib/User/UserTest.php68
-rw-r--r--tests/lib/UtilCheckServerTest.php16
-rw-r--r--tests/lib/UtilTest.php42
743 files changed, 18483 insertions, 18193 deletions
diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs
index f8b3ad05ee8..3a8302b6098 100644
--- a/.git-blame-ignore-revs
+++ b/.git-blame-ignore-revs
@@ -1,15 +1,16 @@
-# .git-blame-ignore-revs
-
-# SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
-# SPDX-License-Identifier: AGPL-3.0-or-later
-
-# Format control structures
-caff1023ea72bb2ea94130e18a2a6e2ccf819e5f
-# Update to coding-standard 1.1.1
-aa5f037af71c915424c6dcfd5ad2dc82797dc0d6
-# Update to coding-standard 1.2.3
-af6de04e9e141466dc229e444ff3f146f4a34765
-0bd284cb81b6866338aaaa67aa1d81ef9bfbb2ab
-8af7ecb2576071f170ecbb0aa2311b26581e40e2
-# Automated refactorings
-275a8ce1dc69e3ae6e27a34d3c8501c1e3078f09
+# .git-blame-ignore-revs
+
+# SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
+# SPDX-License-Identifier: AGPL-3.0-or-later
+
+# Format control structures
+caff1023ea72bb2ea94130e18a2a6e2ccf819e5f
+# Update to coding-standard 1.1.1
+aa5f037af71c915424c6dcfd5ad2dc82797dc0d6
+# Update to coding-standard 1.2.3
+af6de04e9e141466dc229e444ff3f146f4a34765
+0bd284cb81b6866338aaaa67aa1d81ef9bfbb2ab
+8af7ecb2576071f170ecbb0aa2311b26581e40e2
+# Automated refactorings
+275a8ce1dc69e3ae6e27a34d3c8501c1e3078f09
+49dd79eabb2b8902559a7a4e8f8fcad54f46b604
diff --git a/.github/ISSUE_TEMPLATE/BUG_REPORT.yml b/.github/ISSUE_TEMPLATE/BUG_REPORT.yml
index b9516564af0..b2dfff8d1e5 100644
--- a/.github/ISSUE_TEMPLATE/BUG_REPORT.yml
+++ b/.github/ISSUE_TEMPLATE/BUG_REPORT.yml
@@ -72,6 +72,7 @@ body:
options:
- "28"
- "29"
+ - "30"
- "master"
validations:
required: true
diff --git a/apps/comments/tests/Unit/Activity/ListenerTest.php b/apps/comments/tests/Unit/Activity/ListenerTest.php
index c1606aee745..19dcae4c8ab 100644
--- a/apps/comments/tests/Unit/Activity/ListenerTest.php
+++ b/apps/comments/tests/Unit/Activity/ListenerTest.php
@@ -65,7 +65,7 @@ class ListenerTest extends TestCase {
);
}
- public function testCommentEvent() {
+ public function testCommentEvent(): void {
$this->appManager->expects($this->any())
->method('isInstalled')
->with('activity')
diff --git a/apps/comments/tests/Unit/AppInfo/ApplicationTest.php b/apps/comments/tests/Unit/AppInfo/ApplicationTest.php
index 3da14ec3865..fa23936425c 100644
--- a/apps/comments/tests/Unit/AppInfo/ApplicationTest.php
+++ b/apps/comments/tests/Unit/AppInfo/ApplicationTest.php
@@ -30,7 +30,7 @@ class ApplicationTest extends TestCase {
parent::tearDown();
}
- public function test() {
+ public function test(): void {
$app = new Application();
$c = $app->getContainer();
diff --git a/apps/comments/tests/Unit/Collaboration/CommentersSorterTest.php b/apps/comments/tests/Unit/Collaboration/CommentersSorterTest.php
index 334f24aec83..c0de0016c31 100644
--- a/apps/comments/tests/Unit/Collaboration/CommentersSorterTest.php
+++ b/apps/comments/tests/Unit/Collaboration/CommentersSorterTest.php
@@ -28,7 +28,7 @@ class CommentersSorterTest extends TestCase {
* @dataProvider sortDataProvider
* @param $data
*/
- public function testSort($data) {
+ public function testSort($data): void {
$commentMocks = [];
foreach ($data['actors'] as $actorType => $actors) {
foreach ($actors as $actorId => $noOfComments) {
diff --git a/apps/comments/tests/Unit/Controller/NotificationsTest.php b/apps/comments/tests/Unit/Controller/NotificationsTest.php
index 03eba79e6c8..ccd808895c8 100644
--- a/apps/comments/tests/Unit/Controller/NotificationsTest.php
+++ b/apps/comments/tests/Unit/Controller/NotificationsTest.php
@@ -63,7 +63,7 @@ class NotificationsTest extends TestCase {
);
}
- public function testViewGuestRedirect() {
+ public function testViewGuestRedirect(): void {
$this->commentsManager->expects($this->never())
->method('get');
@@ -96,7 +96,7 @@ class NotificationsTest extends TestCase {
$this->assertSame('link-to-login', $response->getRedirectURL());
}
- public function testViewSuccess() {
+ public function testViewSuccess(): void {
$comment = $this->createMock(IComment::class);
$comment->expects($this->any())
->method('getObjectType')
@@ -146,7 +146,7 @@ class NotificationsTest extends TestCase {
$this->assertInstanceOf(RedirectResponse::class, $response);
}
- public function testViewInvalidComment() {
+ public function testViewInvalidComment(): void {
$this->commentsManager->expects($this->any())
->method('get')
->with('42')
@@ -174,7 +174,7 @@ class NotificationsTest extends TestCase {
$this->assertInstanceOf(NotFoundResponse::class, $response);
}
- public function testViewNoFile() {
+ public function testViewNoFile(): void {
$comment = $this->createMock(IComment::class);
$comment->expects($this->any())
->method('getObjectType')
diff --git a/apps/comments/tests/Unit/EventHandlerTest.php b/apps/comments/tests/Unit/EventHandlerTest.php
index 6459924ee8a..83ce1af57da 100644
--- a/apps/comments/tests/Unit/EventHandlerTest.php
+++ b/apps/comments/tests/Unit/EventHandlerTest.php
@@ -36,7 +36,7 @@ class EventHandlerTest extends TestCase {
$this->eventHandler = new CommentsEventListener($this->activityListener, $this->notificationListener);
}
- public function testNotFiles() {
+ public function testNotFiles(): void {
/** @var IComment|\PHPUnit\Framework\MockObject\MockObject $comment */
$comment = $this->getMockBuilder(IComment::class)->getMock();
$comment->expects($this->once())
@@ -69,7 +69,7 @@ class EventHandlerTest extends TestCase {
* @dataProvider handledProvider
* @param string $eventType
*/
- public function testHandled($eventType) {
+ public function testHandled($eventType): void {
/** @var IComment|\PHPUnit\Framework\MockObject\MockObject $comment */
$comment = $this->getMockBuilder(IComment::class)->getMock();
$comment->expects($this->once())
diff --git a/apps/comments/tests/Unit/Notification/ListenerTest.php b/apps/comments/tests/Unit/Notification/ListenerTest.php
index 3d2b2e59b96..f7ebbfaa12c 100644
--- a/apps/comments/tests/Unit/Notification/ListenerTest.php
+++ b/apps/comments/tests/Unit/Notification/ListenerTest.php
@@ -55,7 +55,7 @@ class ListenerTest extends TestCase {
* @param string $eventType
* @param string $notificationMethod
*/
- public function testEvaluate($eventType, $notificationMethod) {
+ public function testEvaluate($eventType, $notificationMethod): void {
/** @var IComment|\PHPUnit\Framework\MockObject\MockObject $comment */
$comment = $this->getMockBuilder(IComment::class)->getMock();
$comment->expects($this->any())
@@ -123,7 +123,7 @@ class ListenerTest extends TestCase {
* @dataProvider eventProvider
* @param string $eventType
*/
- public function testEvaluateNoMentions($eventType) {
+ public function testEvaluateNoMentions($eventType): void {
/** @var IComment|\PHPUnit\Framework\MockObject\MockObject $comment */
$comment = $this->getMockBuilder(IComment::class)->getMock();
$comment->expects($this->any())
@@ -160,7 +160,7 @@ class ListenerTest extends TestCase {
$this->listener->evaluate($event);
}
- public function testEvaluateUserDoesNotExist() {
+ public function testEvaluateUserDoesNotExist(): void {
/** @var IComment|\PHPUnit\Framework\MockObject\MockObject $comment */
$comment = $this->getMockBuilder(IComment::class)->getMock();
$comment->expects($this->any())
diff --git a/apps/comments/tests/Unit/Notification/NotifierTest.php b/apps/comments/tests/Unit/Notification/NotifierTest.php
index a01c08a6760..87b87e646af 100644
--- a/apps/comments/tests/Unit/Notification/NotifierTest.php
+++ b/apps/comments/tests/Unit/Notification/NotifierTest.php
@@ -72,7 +72,7 @@ class NotifierTest extends TestCase {
$this->comment = $this->createMock(IComment::class);
}
- public function testPrepareSuccess() {
+ public function testPrepareSuccess(): void {
$fileName = 'Gre\'thor.odp';
$displayName = 'Huraga';
$message = '@Huraga mentioned you in a comment on "Gre\'thor.odp"';
@@ -190,7 +190,7 @@ class NotifierTest extends TestCase {
$this->notifier->prepare($this->notification, $this->lc);
}
- public function testPrepareSuccessDeletedUser() {
+ public function testPrepareSuccessDeletedUser(): void {
$fileName = 'Gre\'thor.odp';
$message = 'You were mentioned on "Gre\'thor.odp", in a comment by an account that has since been deleted';
@@ -305,7 +305,7 @@ class NotifierTest extends TestCase {
}
- public function testPrepareDifferentApp() {
+ public function testPrepareDifferentApp(): void {
$this->expectException(UnknownNotificationException::class);
$this->folder
@@ -342,7 +342,7 @@ class NotifierTest extends TestCase {
}
- public function testPrepareNotFound() {
+ public function testPrepareNotFound(): void {
$this->expectException(UnknownNotificationException::class);
$this->folder
@@ -380,7 +380,7 @@ class NotifierTest extends TestCase {
}
- public function testPrepareDifferentSubject() {
+ public function testPrepareDifferentSubject(): void {
$this->expectException(UnknownNotificationException::class);
$displayName = 'Huraga';
@@ -437,7 +437,7 @@ class NotifierTest extends TestCase {
}
- public function testPrepareNotFiles() {
+ public function testPrepareNotFiles(): void {
$this->expectException(UnknownNotificationException::class);
$displayName = 'Huraga';
@@ -495,7 +495,7 @@ class NotifierTest extends TestCase {
}
- public function testPrepareUnresolvableFileID() {
+ public function testPrepareUnresolvableFileID(): void {
$this->expectException(AlreadyProcessedException::class);
$displayName = 'Huraga';
diff --git a/apps/dav/lib/CalDAV/CalDavBackend.php b/apps/dav/lib/CalDAV/CalDavBackend.php
index 43a22651747..bea8a913e40 100644
--- a/apps/dav/lib/CalDAV/CalDavBackend.php
+++ b/apps/dav/lib/CalDAV/CalDavBackend.php
@@ -329,8 +329,8 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription
'id' => $row['id'],
'uri' => $row['uri'],
'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
- '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
- '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
+ '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
+ '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
@@ -411,8 +411,8 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription
'id' => $row['id'],
'uri' => $uri,
'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
- '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
- '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
+ '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
+ '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
@@ -461,8 +461,8 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription
'id' => $row['id'],
'uri' => $row['uri'],
'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
- '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
- '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
+ '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
+ '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
];
@@ -513,8 +513,8 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription
'id' => $row['id'],
'uri' => $row['publicuri'],
'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
- '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
- '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
+ '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
+ '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
@@ -578,8 +578,8 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription
'id' => $row['id'],
'uri' => $row['publicuri'],
'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
- '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
- '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
+ '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
+ '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
@@ -632,8 +632,8 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription
'id' => $row['id'],
'uri' => $row['uri'],
'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
- '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
- '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
+ '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
+ '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
];
@@ -680,7 +680,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription
'id' => $row['id'],
'uri' => $row['uri'],
'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
- '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
+ '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?? 0,
'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
@@ -726,7 +726,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription
'source' => $row['source'],
'lastmodified' => $row['lastmodified'],
'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
- '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
+ '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
];
return $this->rowToSubscription($row, $subscription);
@@ -2560,7 +2560,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription
'lastmodified' => $row['lastmodified'],
'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
- '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
+ '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
];
$subscriptions[] = $this->rowToSubscription($row, $subscription);
diff --git a/apps/dav/lib/Connector/Sabre/Node.php b/apps/dav/lib/Connector/Sabre/Node.php
index 1d3773220f8..3ca542fee73 100644
--- a/apps/dav/lib/Connector/Sabre/Node.php
+++ b/apps/dav/lib/Connector/Sabre/Node.php
@@ -392,7 +392,7 @@ abstract class Node implements \Sabre\DAV\INode {
return $this->node;
}
- protected function sanitizeMtime($mtimeFromRequest) {
+ protected function sanitizeMtime(string $mtimeFromRequest): int {
return MtimeSanitizer::sanitizeMtime($mtimeFromRequest);
}
}
diff --git a/apps/dav/tests/unit/BackgroundJob/OutOfOfficeEventDispatcherJobTest.php b/apps/dav/tests/unit/BackgroundJob/OutOfOfficeEventDispatcherJobTest.php
index b42334523f8..5ddd9eba6f8 100644
--- a/apps/dav/tests/unit/BackgroundJob/OutOfOfficeEventDispatcherJobTest.php
+++ b/apps/dav/tests/unit/BackgroundJob/OutOfOfficeEventDispatcherJobTest.php
@@ -62,7 +62,7 @@ class OutOfOfficeEventDispatcherJobTest extends TestCase {
);
}
- public function testDispatchStartEvent() {
+ public function testDispatchStartEvent(): void {
$this->timezoneService->method('getUserTimezone')->with('user')->willReturn('Europe/Berlin');
$absence = new Absence();
@@ -94,7 +94,7 @@ class OutOfOfficeEventDispatcherJobTest extends TestCase {
]);
}
- public function testDispatchStopEvent() {
+ public function testDispatchStopEvent(): void {
$this->timezoneService->method('getUserTimezone')->with('user')->willReturn('Europe/Berlin');
$absence = new Absence();
@@ -126,7 +126,7 @@ class OutOfOfficeEventDispatcherJobTest extends TestCase {
]);
}
- public function testDoesntDispatchUnknownEvent() {
+ public function testDoesntDispatchUnknownEvent(): void {
$this->timezoneService->method('getUserTimezone')->with('user')->willReturn('Europe/Berlin');
$absence = new Absence();
diff --git a/apps/dav/tests/unit/CalDAV/AppCalendar/AppCalendarTest.php b/apps/dav/tests/unit/CalDAV/AppCalendar/AppCalendarTest.php
index b8983350348..f7fa114ff28 100644
--- a/apps/dav/tests/unit/CalDAV/AppCalendar/AppCalendarTest.php
+++ b/apps/dav/tests/unit/CalDAV/AppCalendar/AppCalendarTest.php
@@ -52,7 +52,7 @@ class AppCalendarTest extends TestCase {
$this->appCalendar->delete();
}
- public function testCreateFile() {
+ public function testCreateFile(): void {
$this->writeableCalendar->expects($this->exactly(3))
->method('createFromString')
->withConsecutive(['some-name', 'data'], ['other-name', ''], ['name', 'some data']);
@@ -69,7 +69,7 @@ class AppCalendarTest extends TestCase {
fclose($fp);
}
- public function testCreateFile_readOnly() {
+ public function testCreateFile_readOnly(): void {
// If writing is not supported
$this->expectException(\Sabre\DAV\Exception\Forbidden::class);
$this->expectExceptionMessage('Creating a new entry is not allowed');
diff --git a/apps/dav/tests/unit/CalDAV/AppCalendar/CalendarObjectTest.php b/apps/dav/tests/unit/CalDAV/AppCalendar/CalendarObjectTest.php
index 92288f5dfb0..a913c2dde6f 100644
--- a/apps/dav/tests/unit/CalDAV/AppCalendar/CalendarObjectTest.php
+++ b/apps/dav/tests/unit/CalDAV/AppCalendar/CalendarObjectTest.php
@@ -33,15 +33,15 @@ class CalendarObjectTest extends TestCase {
$this->calendarObject = new CalendarObject($this->calendar, $this->backend, $this->vobject);
}
- public function testGetOwner() {
+ public function testGetOwner(): void {
$this->assertEquals($this->calendarObject->getOwner(), 'owner');
}
- public function testGetGroup() {
+ public function testGetGroup(): void {
$this->assertEquals($this->calendarObject->getGroup(), 'group');
}
- public function testGetACL() {
+ public function testGetACL(): void {
$this->calendar->expects($this->exactly(2))
->method('getPermissions')
->willReturnOnConsecutiveCalls(Constants::PERMISSION_READ, Constants::PERMISSION_ALL);
@@ -70,17 +70,17 @@ class CalendarObjectTest extends TestCase {
]);
}
- public function testSetACL() {
+ public function testSetACL(): void {
$this->expectException(\Sabre\DAV\Exception\Forbidden::class);
$this->calendarObject->setACL([]);
}
- public function testPut_readOnlyBackend() {
+ public function testPut_readOnlyBackend(): void {
$this->expectException(\Sabre\DAV\Exception\Forbidden::class);
$this->calendarObject->put('foo');
}
- public function testPut_noPermissions() {
+ public function testPut_noPermissions(): void {
$this->expectException(\Sabre\DAV\Exception\Forbidden::class);
$backend = $this->createMock(ICreateFromString::class);
@@ -93,7 +93,7 @@ class CalendarObjectTest extends TestCase {
$calendarObject->put('foo');
}
- public function testPut() {
+ public function testPut(): void {
$backend = $this->createMock(ICreateFromString::class);
$calendarObject = new CalendarObject($this->calendar, $backend, $this->vobject);
@@ -110,19 +110,19 @@ class CalendarObjectTest extends TestCase {
$calendarObject->put('foo');
}
- public function testGet() {
+ public function testGet(): void {
$this->vobject->expects($this->once())
->method('serialize')
->willReturn('foo');
$this->assertEquals($this->calendarObject->get(), 'foo');
}
- public function testDelete_notWriteable() {
+ public function testDelete_notWriteable(): void {
$this->expectException(\Sabre\DAV\Exception\Forbidden::class);
$this->calendarObject->delete();
}
- public function testDelete_noPermission() {
+ public function testDelete_noPermission(): void {
$backend = $this->createMock(ICreateFromString::class);
$calendarObject = new CalendarObject($this->calendar, $backend, $this->vobject);
@@ -130,7 +130,7 @@ class CalendarObjectTest extends TestCase {
$calendarObject->delete();
}
- public function testDelete() {
+ public function testDelete(): void {
$backend = $this->createMock(ICreateFromString::class);
$calendarObject = new CalendarObject($this->calendar, $backend, $this->vobject);
@@ -153,7 +153,7 @@ class CalendarObjectTest extends TestCase {
$calendarObject->delete();
}
- public function testGetName() {
+ public function testGetName(): void {
$this->vobject->expects($this->exactly(2))
->method('getBaseComponent')
->willReturnOnConsecutiveCalls((object)['UID' => 'someid'], (object)['UID' => 'someid', 'X-FILENAME' => 'real-filename.ics']);
@@ -162,7 +162,7 @@ class CalendarObjectTest extends TestCase {
$this->assertEquals($this->calendarObject->getName(), 'real-filename.ics');
}
- public function testSetName() {
+ public function testSetName(): void {
$this->expectException(\Sabre\DAV\Exception\Forbidden::class);
$this->calendarObject->setName('Some name');
}
diff --git a/apps/dav/tests/unit/CalDAV/CachedSubscriptionProviderTest.php b/apps/dav/tests/unit/CalDAV/CachedSubscriptionProviderTest.php
index 22998eec3d9..be47b2bf640 100644
--- a/apps/dav/tests/unit/CalDAV/CachedSubscriptionProviderTest.php
+++ b/apps/dav/tests/unit/CalDAV/CachedSubscriptionProviderTest.php
@@ -47,7 +47,7 @@ class CachedSubscriptionProviderTest extends TestCase {
$this->provider = new CachedSubscriptionProvider($this->backend);
}
- public function testGetCalendars() {
+ public function testGetCalendars(): void {
$calendars = $this->provider->getCalendars(
'user-principal-123',
[]
@@ -58,7 +58,7 @@ class CachedSubscriptionProviderTest extends TestCase {
$this->assertInstanceOf(CachedSubscriptionImpl::class, $calendars[1]);
}
- public function testGetCalendarsFilterByUri() {
+ public function testGetCalendarsFilterByUri(): void {
$calendars = $this->provider->getCalendars(
'user-principal-123',
['subscription-1']
diff --git a/apps/dav/tests/unit/CalDAV/CalDavBackendTest.php b/apps/dav/tests/unit/CalDAV/CalDavBackendTest.php
index ac4045ea757..c82ca350c90 100644
--- a/apps/dav/tests/unit/CalDAV/CalDavBackendTest.php
+++ b/apps/dav/tests/unit/CalDAV/CalDavBackendTest.php
@@ -1490,7 +1490,7 @@ EOD;
self::assertSame(0, $deleted);
}
- public function testSearchAndExpandRecurrences() {
+ public function testSearchAndExpandRecurrences(): void {
$calendarId = $this->createTestCalendar();
$calendarInfo = [
'id' => $calendarId,
@@ -1646,7 +1646,7 @@ EOD;
self::assertEquals([$uri2], $changesAfter['deleted']);
}
- public function testSearchWithLimitAndTimeRange() {
+ public function testSearchWithLimitAndTimeRange(): void {
$calendarId = $this->createTestCalendar();
$calendarInfo = [
'id' => $calendarId,
@@ -1703,7 +1703,7 @@ EOD;
);
}
- public function testSearchWithLimitAndTimeRangeShouldNotReturnMoreObjectsThenLimit() {
+ public function testSearchWithLimitAndTimeRangeShouldNotReturnMoreObjectsThenLimit(): void {
$calendarId = $this->createTestCalendar();
$calendarInfo = [
'id' => $calendarId,
@@ -1753,7 +1753,7 @@ EOD;
);
}
- public function testSearchWithLimitAndTimeRangeShouldReturnObjectsInTheSameOrder() {
+ public function testSearchWithLimitAndTimeRangeShouldReturnObjectsInTheSameOrder(): void {
$calendarId = $this->createTestCalendar();
$calendarInfo = [
'id' => $calendarId,
@@ -1810,7 +1810,7 @@ EOD;
);
}
- public function testSearchShouldReturnObjectsInTheSameOrderMissingDate() {
+ public function testSearchShouldReturnObjectsInTheSameOrderMissingDate(): void {
$calendarId = $this->createTestCalendar();
$calendarInfo = [
'id' => $calendarId,
diff --git a/apps/dav/tests/unit/CalDAV/CalendarTest.php b/apps/dav/tests/unit/CalDAV/CalendarTest.php
index a2854823cbc..6433af8c340 100644
--- a/apps/dav/tests/unit/CalDAV/CalendarTest.php
+++ b/apps/dav/tests/unit/CalDAV/CalendarTest.php
@@ -442,7 +442,7 @@ EOD;
];
}
- public function testRemoveVAlarms() {
+ public function testRemoveVAlarms(): void {
$publicObjectData = <<<EOD
BEGIN:VCALENDAR
VERSION:2.0
diff --git a/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php b/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php
index 104f7cd7f51..36ce091fc69 100644
--- a/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php
+++ b/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php
@@ -202,7 +202,7 @@ class IMipPluginTest extends TestCase {
$this->plugin->setVCalendar($oldVCalendar);
$this->service->expects(self::once())
->method('getLastOccurrence')
- ->willReturn('1496912700');
+ ->willReturn(1496912700);
$this->mailer->expects(self::once())
->method('validateMailAddress')
->with('frodo@hobb.it')
@@ -248,7 +248,7 @@ class IMipPluginTest extends TestCase {
->willReturn('yes');
$this->service->expects(self::once())
->method('createInvitationToken')
- ->with($message, $newVevent, '1496912700')
+ ->with($message, $newVevent, 1496912700)
->willReturn('token');
$this->service->expects(self::once())
->method('addResponseButtons')
@@ -305,7 +305,7 @@ class IMipPluginTest extends TestCase {
$this->plugin->setVCalendar($oldVCalendar);
$this->service->expects(self::once())
->method('getLastOccurrence')
- ->willReturn('1496912700');
+ ->willReturn(1496912700);
$this->mailer->expects(self::once())
->method('validateMailAddress')
->with('the-shire@hobb.it')
@@ -406,7 +406,7 @@ class IMipPluginTest extends TestCase {
$this->plugin->setVCalendar($oldVCalendar);
$this->service->expects(self::once())
->method('getLastOccurrence')
- ->willReturn('1496912700');
+ ->willReturn(1496912700);
$this->mailer->expects(self::once())
->method('validateMailAddress')
->with('frodo@hobb.it')
@@ -452,7 +452,7 @@ class IMipPluginTest extends TestCase {
->willReturn('yes');
$this->service->expects(self::once())
->method('createInvitationToken')
- ->with($message, $newVevent, '1496912700')
+ ->with($message, $newVevent, 1496912700)
->willReturn('token');
$this->service->expects(self::once())
->method('addResponseButtons')
@@ -467,7 +467,7 @@ class IMipPluginTest extends TestCase {
$this->assertEquals('1.1', $message->getScheduleStatus());
}
- public function testEmailValidationFailed() {
+ public function testEmailValidationFailed(): void {
$message = new Message();
$message->method = 'REQUEST';
$message->message = new VCalendar();
@@ -485,7 +485,7 @@ class IMipPluginTest extends TestCase {
$this->service->expects(self::once())
->method('getLastOccurrence')
- ->willReturn('1496912700');
+ ->willReturn(1496912700);
$this->mailer->expects(self::once())
->method('validateMailAddress')
->with('frodo@hobb.it')
@@ -537,7 +537,7 @@ class IMipPluginTest extends TestCase {
$this->plugin->setVCalendar($oldVcalendar);
$this->service->expects(self::once())
->method('getLastOccurrence')
- ->willReturn('1496912700');
+ ->willReturn(1496912700);
$this->mailer->expects(self::once())
->method('validateMailAddress')
->with('frodo@hobb.it')
@@ -583,7 +583,7 @@ class IMipPluginTest extends TestCase {
->willReturn('yes');
$this->service->expects(self::once())
->method('createInvitationToken')
- ->with($message, $newVevent, '1496912700')
+ ->with($message, $newVevent, 1496912700)
->willReturn('token');
$this->service->expects(self::once())
->method('addResponseButtons')
@@ -650,7 +650,7 @@ class IMipPluginTest extends TestCase {
// construct service mock returns
$this->service->expects(self::once())
->method('getLastOccurrence')
- ->willReturn('1496912700');
+ ->willReturn(1496912700);
$this->service->expects(self::once())
->method('getCurrentAttendee')
->with($message)
@@ -676,7 +676,7 @@ class IMipPluginTest extends TestCase {
->willReturn(true);
$this->service->expects(self::once())
->method('createInvitationToken')
- ->with($message, $event, '1496912700')
+ ->with($message, $event, 1496912700)
->willReturn('token');
$this->service->expects(self::once())
->method('addResponseButtons')
@@ -703,7 +703,7 @@ class IMipPluginTest extends TestCase {
->method('findServiceByAddress')
->with('user1', 'gandalf@wiz.ard')
->willReturn($this->mailService);
-
+
$this->plugin->schedule($message);
$this->assertEquals('1.1', $message->getScheduleStatus());
}
@@ -737,7 +737,7 @@ class IMipPluginTest extends TestCase {
}
$this->service->expects(self::once())
->method('getLastOccurrence')
- ->willReturn('1496912700');
+ ->willReturn(1496912700);
$this->mailer->expects(self::once())
->method('validateMailAddress')
->with('frodo@hobb.it')
@@ -784,7 +784,7 @@ class IMipPluginTest extends TestCase {
->willReturn('yes');
$this->service->expects(self::once())
->method('createInvitationToken')
- ->with($message, $newVevent, '1496912700')
+ ->with($message, $newVevent, 1496912700)
->willReturn('token');
$this->service->expects(self::once())
->method('addResponseButtons')
@@ -830,7 +830,7 @@ class IMipPluginTest extends TestCase {
}
$this->service->expects(self::once())
->method('getLastOccurrence')
- ->willReturn('1496912700');
+ ->willReturn(1496912700);
$this->mailer->expects(self::once())
->method('validateMailAddress')
->with('frodo@hobb.it')
diff --git a/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php b/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php
index aa2903b519f..8d98a765fc1 100644
--- a/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php
+++ b/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php
@@ -400,7 +400,7 @@ class PluginTest extends TestCase {
*
* Should generate 2 messages for attendees User 2 and User External
*/
- public function testCalendarObjectChangePersonalCalendarCreate() {
+ public function testCalendarObjectChangePersonalCalendarCreate(): void {
// define place holders
/** @var Message[] $iTipMessages */
@@ -504,7 +504,7 @@ class PluginTest extends TestCase {
*
* Should generate 3 messages for attendees User 2 (Sharee), User 3 (Non-Sharee) and User External
*/
- public function testCalendarObjectChangeSharedCalendarSharerCreate() {
+ public function testCalendarObjectChangeSharedCalendarSharerCreate(): void {
// define place holders
/** @var Message[] $iTipMessages */
@@ -620,7 +620,7 @@ class PluginTest extends TestCase {
*
* Should generate 3 messages for attendees User 1 (Sharer/Owner), User 3 (Non-Sharee) and User External
*/
- public function testCalendarObjectChangeSharedCalendarShreeCreate() {
+ public function testCalendarObjectChangeSharedCalendarShreeCreate(): void {
// define place holders
/** @var Message[] $iTipMessages */
diff --git a/apps/dav/tests/unit/CalDAV/WebcalCaching/ConnectionTest.php b/apps/dav/tests/unit/CalDAV/WebcalCaching/ConnectionTest.php
index ee903a5e0fa..0d836e44949 100644
--- a/apps/dav/tests/unit/CalDAV/WebcalCaching/ConnectionTest.php
+++ b/apps/dav/tests/unit/CalDAV/WebcalCaching/ConnectionTest.php
@@ -37,7 +37,7 @@ class ConnectionTest extends TestCase {
/**
* @dataProvider runLocalURLDataProvider
*/
- public function testLocalUrl($source) {
+ public function testLocalUrl($source): void {
$subscription = [
'id' => 42,
'uri' => 'sub123',
diff --git a/apps/dav/tests/unit/Controller/UpcomingEventsControllerTest.php b/apps/dav/tests/unit/Controller/UpcomingEventsControllerTest.php
index 9e5c03bb245..bab0ef77bd0 100644
--- a/apps/dav/tests/unit/Controller/UpcomingEventsControllerTest.php
+++ b/apps/dav/tests/unit/Controller/UpcomingEventsControllerTest.php
@@ -28,7 +28,7 @@ class UpcomingEventsControllerTest extends TestCase {
$this->service = $this->createMock(UpcomingEventsService::class);
}
- public function testGetEventsAnonymously() {
+ public function testGetEventsAnonymously(): void {
$controller = new UpcomingEventsController(
$this->request,
null,
@@ -41,7 +41,7 @@ class UpcomingEventsControllerTest extends TestCase {
self::assertSame(401, $response->getStatus());
}
- public function testGetEventsByLocation() {
+ public function testGetEventsByLocation(): void {
$controller = new UpcomingEventsController(
$this->request,
'u1',
diff --git a/apps/dav/tests/unit/Service/AbsenceServiceTest.php b/apps/dav/tests/unit/Service/AbsenceServiceTest.php
index 1bc5f53f18c..5cff29a6f61 100644
--- a/apps/dav/tests/unit/Service/AbsenceServiceTest.php
+++ b/apps/dav/tests/unit/Service/AbsenceServiceTest.php
@@ -62,7 +62,7 @@ class AbsenceServiceTest extends TestCase {
);
}
- public function testCreateAbsenceEmitsScheduledEvent() {
+ public function testCreateAbsenceEmitsScheduledEvent(): void {
$tz = new DateTimeZone('Europe/Berlin');
$user = $this->createMock(IUser::class);
$user->method('getUID')
@@ -117,7 +117,7 @@ class AbsenceServiceTest extends TestCase {
);
}
- public function testUpdateAbsenceEmitsChangedEvent() {
+ public function testUpdateAbsenceEmitsChangedEvent(): void {
$tz = new DateTimeZone('Europe/Berlin');
$user = $this->createMock(IUser::class);
$user->method('getUID')
@@ -181,7 +181,7 @@ class AbsenceServiceTest extends TestCase {
);
}
- public function testCreateAbsenceSchedulesBothJobs() {
+ public function testCreateAbsenceSchedulesBothJobs(): void {
$tz = new DateTimeZone('Europe/Berlin');
$startDateString = '2023-01-05';
$startDate = new DateTimeImmutable($startDateString, $tz);
@@ -230,7 +230,7 @@ class AbsenceServiceTest extends TestCase {
);
}
- public function testCreateAbsenceSchedulesOnlyEndJob() {
+ public function testCreateAbsenceSchedulesOnlyEndJob(): void {
$tz = new DateTimeZone('Europe/Berlin');
$endDateString = '2023-01-10';
$endDate = new DateTimeImmutable($endDateString, $tz);
@@ -271,7 +271,7 @@ class AbsenceServiceTest extends TestCase {
);
}
- public function testCreateAbsenceSchedulesNoJob() {
+ public function testCreateAbsenceSchedulesNoJob(): void {
$tz = new DateTimeZone('Europe/Berlin');
$user = $this->createMock(IUser::class);
$user->method('getUID')
@@ -306,7 +306,7 @@ class AbsenceServiceTest extends TestCase {
);
}
- public function testUpdateAbsenceSchedulesBothJobs() {
+ public function testUpdateAbsenceSchedulesBothJobs(): void {
$tz = new DateTimeZone('Europe/Berlin');
$startDateString = '2023-01-05';
$startDate = new DateTimeImmutable($startDateString, $tz);
@@ -362,7 +362,7 @@ class AbsenceServiceTest extends TestCase {
);
}
- public function testUpdateSchedulesOnlyEndJob() {
+ public function testUpdateSchedulesOnlyEndJob(): void {
$tz = new DateTimeZone('Europe/Berlin');
$endDateString = '2023-01-10';
$endDate = new DateTimeImmutable($endDateString, $tz);
@@ -410,7 +410,7 @@ class AbsenceServiceTest extends TestCase {
);
}
- public function testUpdateAbsenceSchedulesNoJob() {
+ public function testUpdateAbsenceSchedulesNoJob(): void {
$tz = new DateTimeZone('Europe/Berlin');
$user = $this->createMock(IUser::class);
$user->method('getUID')
diff --git a/apps/encryption/tests/Command/FixEncryptedVersionTest.php b/apps/encryption/tests/Command/FixEncryptedVersionTest.php
index 8ec59c3db93..38e86779593 100644
--- a/apps/encryption/tests/Command/FixEncryptedVersionTest.php
+++ b/apps/encryption/tests/Command/FixEncryptedVersionTest.php
@@ -75,7 +75,7 @@ class FixEncryptedVersionTest extends TestCase {
* In this test the encrypted version of the file is less than the original value
* but greater than zero
*/
- public function testEncryptedVersionLessThanOriginalValue() {
+ public function testEncryptedVersionLessThanOriginalValue(): void {
$this->util->expects($this->once())->method('isMasterKeyEnabled')
->willReturn(true);
@@ -143,7 +143,7 @@ Fixed the file: \"/$this->userId/files/world.txt\" with version 4", $output);
* In this test the encrypted version of the file is greater than the original value
* but greater than zero
*/
- public function testEncryptedVersionGreaterThanOriginalValue() {
+ public function testEncryptedVersionGreaterThanOriginalValue(): void {
$this->util->expects($this->once())->method('isMasterKeyEnabled')
->willReturn(true);
@@ -202,7 +202,7 @@ The file \"/$this->userId/files/world.txt\" is: OK
Fixed the file: \"/$this->userId/files/world.txt\" with version 4", $output);
}
- public function testVersionIsRestoredToOriginalIfNoFixIsFound() {
+ public function testVersionIsRestoredToOriginalIfNoFixIsFound(): void {
$this->util->expects($this->once())->method('isMasterKeyEnabled')
->willReturn(true);
@@ -232,7 +232,7 @@ Fixed the file: \"/$this->userId/files/world.txt\" with version 4", $output);
$this->assertEquals(15, $encryptedVersion);
}
- public function testRepairUnencryptedFileWhenVersionIsSet() {
+ public function testRepairUnencryptedFileWhenVersionIsSet(): void {
$this->util->expects($this->once())->method('isMasterKeyEnabled')
->willReturn(true);
@@ -275,7 +275,7 @@ Fixed the file: \"/$this->userId/files/hello.txt\" with version 0 (unencrypted)"
/**
* Test commands with a file path
*/
- public function testExecuteWithFilePathOption() {
+ public function testExecuteWithFilePathOption(): void {
$this->util->expects($this->once())->method('isMasterKeyEnabled')
->willReturn(true);
@@ -299,7 +299,7 @@ The file \"/$this->userId/files/hello.txt\" is: OK", $output);
/**
* Test commands with a directory path
*/
- public function testExecuteWithDirectoryPathOption() {
+ public function testExecuteWithDirectoryPathOption(): void {
$this->util->expects($this->once())->method('isMasterKeyEnabled')
->willReturn(true);
@@ -321,7 +321,7 @@ The file \"/$this->userId/files/sub/hello.txt\" is: OK", $output);
$this->assertStringNotContainsString('world.txt', $output);
}
- public function testExecuteWithNoUser() {
+ public function testExecuteWithNoUser(): void {
$this->util->expects($this->once())->method('isMasterKeyEnabled')
->willReturn(true);
@@ -335,7 +335,7 @@ The file \"/$this->userId/files/sub/hello.txt\" is: OK", $output);
$this->assertStringContainsString('Either a user id or --all needs to be provided', $output);
}
- public function testExecuteWithBadUser() {
+ public function testExecuteWithBadUser(): void {
$this->util->expects($this->once())->method('isMasterKeyEnabled')
->willReturn(true);
@@ -352,7 +352,7 @@ The file \"/$this->userId/files/sub/hello.txt\" is: OK", $output);
/**
* Test commands with a directory path
*/
- public function testExecuteWithNonExistentPath() {
+ public function testExecuteWithNonExistentPath(): void {
$this->util->expects($this->once())->method('isMasterKeyEnabled')
->willReturn(true);
@@ -369,7 +369,7 @@ The file \"/$this->userId/files/sub/hello.txt\" is: OK", $output);
/**
* Test commands without master key
*/
- public function testExecuteWithNoMasterKey() {
+ public function testExecuteWithNoMasterKey(): void {
\OC::$server->getConfig()->setAppValue('encryption', 'useMasterKey', '0');
$this->util->expects($this->once())->method('isMasterKeyEnabled')
->willReturn(false);
diff --git a/apps/encryption/tests/Command/TestEnableMasterKey.php b/apps/encryption/tests/Command/TestEnableMasterKey.php
index 47bc978627d..2ed29becf2a 100644
--- a/apps/encryption/tests/Command/TestEnableMasterKey.php
+++ b/apps/encryption/tests/Command/TestEnableMasterKey.php
@@ -58,7 +58,7 @@ class TestEnableMasterKey extends TestCase {
* @param bool $isAlreadyEnabled
* @param string $answer
*/
- public function testExecute($isAlreadyEnabled, $answer) {
+ public function testExecute($isAlreadyEnabled, $answer): void {
$this->util->expects($this->once())->method('isMasterKeyEnabled')
->willReturn($isAlreadyEnabled);
diff --git a/apps/encryption/tests/Controller/RecoveryControllerTest.php b/apps/encryption/tests/Controller/RecoveryControllerTest.php
index 955e9c7c964..8398a22039b 100644
--- a/apps/encryption/tests/Controller/RecoveryControllerTest.php
+++ b/apps/encryption/tests/Controller/RecoveryControllerTest.php
@@ -45,7 +45,7 @@ class RecoveryControllerTest extends TestCase {
* @param $expectedMessage
* @param $expectedStatus
*/
- public function testAdminRecovery($recoveryPassword, $passConfirm, $enableRecovery, $expectedMessage, $expectedStatus) {
+ public function testAdminRecovery($recoveryPassword, $passConfirm, $enableRecovery, $expectedMessage, $expectedStatus): void {
$this->recoveryMock->expects($this->any())
->method('enableAdminRecovery')
->willReturn(true);
@@ -81,7 +81,7 @@ class RecoveryControllerTest extends TestCase {
* @param $expectedMessage
* @param $expectedStatus
*/
- public function testChangeRecoveryPassword($password, $confirmPassword, $oldPassword, $expectedMessage, $expectedStatus) {
+ public function testChangeRecoveryPassword($password, $confirmPassword, $oldPassword, $expectedMessage, $expectedStatus): void {
$this->recoveryMock->expects($this->any())
->method('changeRecoveryKeyPassword')
->with($password, $oldPassword)
@@ -111,7 +111,7 @@ class RecoveryControllerTest extends TestCase {
* @param $expectedMessage
* @param $expectedStatus
*/
- public function testUserSetRecovery($enableRecovery, $expectedMessage, $expectedStatus) {
+ public function testUserSetRecovery($enableRecovery, $expectedMessage, $expectedStatus): void {
$this->recoveryMock->expects($this->any())
->method('setRecoveryForUser')
->with($enableRecovery)
diff --git a/apps/encryption/tests/Controller/SettingsControllerTest.php b/apps/encryption/tests/Controller/SettingsControllerTest.php
index ee49972001c..dcad23cd759 100644
--- a/apps/encryption/tests/Controller/SettingsControllerTest.php
+++ b/apps/encryption/tests/Controller/SettingsControllerTest.php
@@ -115,7 +115,7 @@ class SettingsControllerTest extends TestCase {
/**
* test updatePrivateKeyPassword() if wrong new password was entered
*/
- public function testUpdatePrivateKeyPasswordWrongNewPassword() {
+ public function testUpdatePrivateKeyPasswordWrongNewPassword(): void {
$oldPassword = 'old';
$newPassword = 'new';
@@ -140,7 +140,7 @@ class SettingsControllerTest extends TestCase {
/**
* test updatePrivateKeyPassword() if wrong old password was entered
*/
- public function testUpdatePrivateKeyPasswordWrongOldPassword() {
+ public function testUpdatePrivateKeyPasswordWrongOldPassword(): void {
$oldPassword = 'old';
$newPassword = 'new';
@@ -166,7 +166,7 @@ class SettingsControllerTest extends TestCase {
/**
* test updatePrivateKeyPassword() with the correct old and new password
*/
- public function testUpdatePrivateKeyPassword() {
+ public function testUpdatePrivateKeyPassword(): void {
$oldPassword = 'old';
$newPassword = 'new';
@@ -227,7 +227,7 @@ class SettingsControllerTest extends TestCase {
$data['message']);
}
- public function testSetEncryptHomeStorage() {
+ public function testSetEncryptHomeStorage(): void {
$value = true;
$this->utilMock->expects($this->once())->method('setEncryptHomeStorage')->with($value);
$this->controller->setEncryptHomeStorage($value);
diff --git a/apps/encryption/tests/Controller/StatusControllerTest.php b/apps/encryption/tests/Controller/StatusControllerTest.php
index 26210946cce..c88b0497abf 100644
--- a/apps/encryption/tests/Controller/StatusControllerTest.php
+++ b/apps/encryption/tests/Controller/StatusControllerTest.php
@@ -60,7 +60,7 @@ class StatusControllerTest extends TestCase {
* @param string $status
* @param string $expectedStatus
*/
- public function testGetStatus($status, $expectedStatus) {
+ public function testGetStatus($status, $expectedStatus): void {
$this->sessionMock->expects($this->once())
->method('getStatus')->willReturn($status);
$result = $this->controller->getStatus();
diff --git a/apps/encryption/tests/Crypto/CryptTest.php b/apps/encryption/tests/Crypto/CryptTest.php
index 301ffaeaef3..a9869af99d9 100644
--- a/apps/encryption/tests/Crypto/CryptTest.php
+++ b/apps/encryption/tests/Crypto/CryptTest.php
@@ -53,7 +53,7 @@ class CryptTest extends TestCase {
/**
* test getOpenSSLConfig without any additional parameters
*/
- public function testGetOpenSSLConfigBasic() {
+ public function testGetOpenSSLConfigBasic(): void {
$this->config->expects($this->once())
->method('getSystemValue')
->with($this->equalTo('openssl'), $this->equalTo([]))
@@ -68,7 +68,7 @@ class CryptTest extends TestCase {
/**
* test getOpenSSLConfig with additional parameters defined in config.php
*/
- public function testGetOpenSSLConfig() {
+ public function testGetOpenSSLConfig(): void {
$this->config->expects($this->once())
->method('getSystemValue')
->with($this->equalTo('openssl'), $this->equalTo([]))
@@ -88,7 +88,7 @@ class CryptTest extends TestCase {
*
* @dataProvider dataTestGenerateHeader
*/
- public function testGenerateHeader($keyFormat, $expected) {
+ public function testGenerateHeader($keyFormat, $expected): void {
$this->config->expects($this->once())
->method('getSystemValueString')
->with($this->equalTo('cipher'), $this->equalTo('AES-256-CTR'))
@@ -107,7 +107,7 @@ class CryptTest extends TestCase {
* test generateHeader with invalid key format
*
*/
- public function testGenerateHeaderInvalid() {
+ public function testGenerateHeaderInvalid(): void {
$this->expectException(\InvalidArgumentException::class);
$this->crypt->generateHeader('unknown');
@@ -124,7 +124,7 @@ class CryptTest extends TestCase {
];
}
- public function testGetCipherWithInvalidCipher() {
+ public function testGetCipherWithInvalidCipher(): void {
$this->config->expects($this->once())
->method('getSystemValueString')
->with($this->equalTo('cipher'), $this->equalTo('AES-256-CTR'))
@@ -142,7 +142,7 @@ class CryptTest extends TestCase {
* @param string $configValue
* @param string $expected
*/
- public function testGetCipher($configValue, $expected) {
+ public function testGetCipher($configValue, $expected): void {
$this->config->expects($this->once())
->method('getSystemValueString')
->with($this->equalTo('cipher'), $this->equalTo('AES-256-CTR'))
@@ -172,7 +172,7 @@ class CryptTest extends TestCase {
/**
* test concatIV()
*/
- public function testConcatIV() {
+ public function testConcatIV(): void {
$result = self::invokePrivate(
$this->crypt,
'concatIV',
@@ -186,7 +186,7 @@ class CryptTest extends TestCase {
/**
* @dataProvider dataTestSplitMetaData
*/
- public function testSplitMetaData($data, $expected) {
+ public function testSplitMetaData($data, $expected): void {
$this->config->method('getSystemValueBool')
->with('encryption_skip_signature_check', false)
->willReturn(true);
@@ -213,7 +213,7 @@ class CryptTest extends TestCase {
/**
* @dataProvider dataTestHasSignature
*/
- public function testHasSignature($data, $expected) {
+ public function testHasSignature($data, $expected): void {
$this->config->method('getSystemValueBool')
->with('encryption_skip_signature_check', false)
->willReturn(true);
@@ -232,7 +232,7 @@ class CryptTest extends TestCase {
/**
* @dataProvider dataTestHasSignatureFail
*/
- public function testHasSignatureFail($cipher) {
+ public function testHasSignatureFail($cipher): void {
$this->expectException(\OCP\Encryption\Exceptions\GenericEncryptionException::class);
$data = 'encryptedContent00iv001234567890123456xx';
@@ -251,7 +251,7 @@ class CryptTest extends TestCase {
/**
* test addPadding()
*/
- public function testAddPadding() {
+ public function testAddPadding(): void {
$result = self::invokePrivate($this->crypt, 'addPadding', ['data']);
$this->assertSame('dataxxx', $result);
}
@@ -263,7 +263,7 @@ class CryptTest extends TestCase {
* @param $data
* @param $expected
*/
- public function testRemovePadding($data, $expected) {
+ public function testRemovePadding($data, $expected): void {
$result = self::invokePrivate($this->crypt, 'removePadding', [$data]);
$this->assertSame($expected, $result);
}
@@ -283,7 +283,7 @@ class CryptTest extends TestCase {
/**
* test parseHeader()
*/
- public function testParseHeader() {
+ public function testParseHeader(): void {
$header = 'HBEGIN:foo:bar:cipher:AES-256-CFB:encoding:binary:HEND';
$result = self::invokePrivate($this->crypt, 'parseHeader', [$header]);
@@ -328,7 +328,7 @@ class CryptTest extends TestCase {
*
* @depends testEncrypt
*/
- public function testDecrypt($data) {
+ public function testDecrypt($data): void {
$result = self::invokePrivate(
$this->crypt,
'decrypt',
@@ -342,7 +342,7 @@ class CryptTest extends TestCase {
*
* @dataProvider dataTestGetKeySize
*/
- public function testGetKeySize($cipher, $expected) {
+ public function testGetKeySize($cipher, $expected): void {
$result = $this->invokePrivate($this->crypt, 'getKeySize', [$cipher]);
$this->assertSame($expected, $result);
}
@@ -351,7 +351,7 @@ class CryptTest extends TestCase {
* test exception if cipher is unknown
*
*/
- public function testGetKeySizeFailure() {
+ public function testGetKeySizeFailure(): void {
$this->expectException(\InvalidArgumentException::class);
$this->invokePrivate($this->crypt, 'getKeySize', ['foo']);
@@ -372,7 +372,7 @@ class CryptTest extends TestCase {
/**
* @dataProvider dataTestDecryptPrivateKey
*/
- public function testDecryptPrivateKey($header, $privateKey, $expectedCipher, $isValidKey, $expected) {
+ public function testDecryptPrivateKey($header, $privateKey, $expectedCipher, $isValidKey, $expected): void {
$this->config->method('getSystemValueBool')
->withConsecutive(['encryption.legacy_format_support', false],
['encryption.use_legacy_base64_encoding', false])
@@ -430,7 +430,7 @@ class CryptTest extends TestCase {
];
}
- public function testIsValidPrivateKey() {
+ public function testIsValidPrivateKey(): void {
$res = openssl_pkey_new();
openssl_pkey_export($res, $privateKey);
@@ -445,7 +445,7 @@ class CryptTest extends TestCase {
);
}
- public function testMultiKeyEncrypt() {
+ public function testMultiKeyEncrypt(): void {
$res = openssl_pkey_new();
openssl_pkey_export($res, $privateKey);
$publicKeyPem = openssl_pkey_get_details($res)['key'];
diff --git a/apps/encryption/tests/Crypto/DecryptAllTest.php b/apps/encryption/tests/Crypto/DecryptAllTest.php
index 2a46e542804..0d8543153ef 100644
--- a/apps/encryption/tests/Crypto/DecryptAllTest.php
+++ b/apps/encryption/tests/Crypto/DecryptAllTest.php
@@ -58,7 +58,7 @@ class DecryptAllTest extends TestCase {
);
}
- public function testUpdateSession() {
+ public function testUpdateSession(): void {
$this->session->expects($this->once())->method('prepareDecryptAll')
->with('user1', 'key1');
@@ -71,7 +71,7 @@ class DecryptAllTest extends TestCase {
* @param string $user
* @param string $recoveryKeyId
*/
- public function testGetPrivateKey($user, $recoveryKeyId, $masterKeyId) {
+ public function testGetPrivateKey($user, $recoveryKeyId, $masterKeyId): void {
$password = 'passwd';
$recoveryKey = 'recoveryKey';
$userKey = 'userKey';
diff --git a/apps/encryption/tests/Crypto/EncryptAllTest.php b/apps/encryption/tests/Crypto/EncryptAllTest.php
index a63b826bf3c..f58ea2119e6 100644
--- a/apps/encryption/tests/Crypto/EncryptAllTest.php
+++ b/apps/encryption/tests/Crypto/EncryptAllTest.php
@@ -135,7 +135,7 @@ class EncryptAllTest extends TestCase {
);
}
- public function testEncryptAll() {
+ public function testEncryptAll(): void {
/** @var EncryptAll | \PHPUnit\Framework\MockObject\MockObject $encryptAll */
$encryptAll = $this->getMockBuilder(EncryptAll::class)
->setConstructorArgs(
@@ -164,7 +164,7 @@ class EncryptAllTest extends TestCase {
$encryptAll->encryptAll($this->inputInterface, $this->outputInterface);
}
- public function testEncryptAllWithMasterKey() {
+ public function testEncryptAllWithMasterKey(): void {
/** @var EncryptAll | \PHPUnit\Framework\MockObject\MockObject $encryptAll */
$encryptAll = $this->getMockBuilder(EncryptAll::class)
->setConstructorArgs(
@@ -194,7 +194,7 @@ class EncryptAllTest extends TestCase {
$encryptAll->encryptAll($this->inputInterface, $this->outputInterface);
}
- public function testCreateKeyPairs() {
+ public function testCreateKeyPairs(): void {
/** @var EncryptAll | \PHPUnit\Framework\MockObject\MockObject $encryptAll */
$encryptAll = $this->getMockBuilder(EncryptAll::class)
->setConstructorArgs(
@@ -244,7 +244,7 @@ class EncryptAllTest extends TestCase {
$this->assertSame('', $userPasswords['user2']);
}
- public function testEncryptAllUsersFiles() {
+ public function testEncryptAllUsersFiles(): void {
/** @var EncryptAll | \PHPUnit\Framework\MockObject\MockObject $encryptAll */
$encryptAll = $this->getMockBuilder(EncryptAll::class)
->setConstructorArgs(
@@ -280,7 +280,7 @@ class EncryptAllTest extends TestCase {
$this->invokePrivate($encryptAll, 'encryptAllUsersFiles');
}
- public function testEncryptUsersFiles() {
+ public function testEncryptUsersFiles(): void {
/** @var EncryptAll | \PHPUnit\Framework\MockObject\MockObject $encryptAll */
$encryptAll = $this->getMockBuilder(EncryptAll::class)
->setConstructorArgs(
@@ -343,7 +343,7 @@ class EncryptAllTest extends TestCase {
$this->invokePrivate($encryptAll, 'encryptUsersFiles', ['user1', $progressBar, '']);
}
- public function testGenerateOneTimePassword() {
+ public function testGenerateOneTimePassword(): void {
$password = $this->invokePrivate($this->encryptAll, 'generateOneTimePassword', ['user1']);
$this->assertTrue(is_string($password));
$this->assertSame(8, strlen($password));
@@ -357,7 +357,7 @@ class EncryptAllTest extends TestCase {
* @dataProvider dataTestEncryptFile
* @param $isEncrypted
*/
- public function testEncryptFile($isEncrypted) {
+ public function testEncryptFile($isEncrypted): void {
$fileInfo = $this->createMock(FileInfo::class);
$fileInfo->expects($this->any())->method('isEncrypted')
->willReturn($isEncrypted);
diff --git a/apps/encryption/tests/Crypto/EncryptionTest.php b/apps/encryption/tests/Crypto/EncryptionTest.php
index df9020579ce..d9b0052a5b8 100644
--- a/apps/encryption/tests/Crypto/EncryptionTest.php
+++ b/apps/encryption/tests/Crypto/EncryptionTest.php
@@ -102,7 +102,7 @@ class EncryptionTest extends TestCase {
/**
* test if public key from one of the recipients is missing
*/
- public function testEndUser1() {
+ public function testEndUser1(): void {
$this->sessionMock->expects($this->once())
->method('decryptAllModeActivated')
->willReturn(false);
@@ -115,7 +115,7 @@ class EncryptionTest extends TestCase {
* test if public key from owner is missing
*
*/
- public function testEndUser2() {
+ public function testEndUser2(): void {
$this->sessionMock->expects($this->once())
->method('decryptAllModeActivated')
->willReturn(false);
@@ -167,7 +167,7 @@ class EncryptionTest extends TestCase {
/**
* @dataProvider dataProviderForTestGetPathToRealFile
*/
- public function testGetPathToRealFile($path, $expected) {
+ public function testGetPathToRealFile($path, $expected): void {
$this->assertSame($expected,
self::invokePrivate($this->instance, 'getPathToRealFile', [$path])
);
@@ -185,7 +185,7 @@ class EncryptionTest extends TestCase {
/**
* @dataProvider dataTestBegin
*/
- public function testBegin($mode, $header, $legacyCipher, $defaultCipher, $fileKey, $expected) {
+ public function testBegin($mode, $header, $legacyCipher, $defaultCipher, $fileKey, $expected): void {
$this->sessionMock->expects($this->once())
->method('decryptAllModeActivated')
->willReturn(false);
@@ -239,7 +239,7 @@ class EncryptionTest extends TestCase {
/**
* test begin() if decryptAll mode was activated
*/
- public function testBeginDecryptAll() {
+ public function testBeginDecryptAll(): void {
$path = '/user/files/foo.txt';
$fileKey = 'fileKey';
@@ -263,7 +263,7 @@ class EncryptionTest extends TestCase {
* in this case we can initialize the encryption without a username/password
* and continue
*/
- public function testBeginInitMasterKey() {
+ public function testBeginInitMasterKey(): void {
$this->sessionMock->expects($this->once())
->method('decryptAllModeActivated')
->willReturn(false);
@@ -282,7 +282,7 @@ class EncryptionTest extends TestCase {
* @param string $fileKey
* @param boolean $expected
*/
- public function testUpdate($fileKey, $expected) {
+ public function testUpdate($fileKey, $expected): void {
$this->keyManagerMock->expects($this->once())
->method('getFileKey')->willReturn($fileKey);
@@ -310,7 +310,7 @@ class EncryptionTest extends TestCase {
];
}
- public function testUpdateNoUsers() {
+ public function testUpdateNoUsers(): void {
$this->invokePrivate($this->instance, 'rememberVersion', [['path' => 2]]);
$this->keyManagerMock->expects($this->never())->method('getFileKey');
@@ -329,7 +329,7 @@ class EncryptionTest extends TestCase {
* Test case if the public key is missing. Nextcloud should still encrypt
* the file for the remaining users
*/
- public function testUpdateMissingPublicKey() {
+ public function testUpdateMissingPublicKey(): void {
$this->keyManagerMock->expects($this->once())
->method('getFileKey')->willReturn('fileKey');
@@ -369,7 +369,7 @@ class EncryptionTest extends TestCase {
*
* @dataProvider dataTestShouldEncrypt
*/
- public function testShouldEncrypt($path, $shouldEncryptHomeStorage, $isHomeStorage, $expected) {
+ public function testShouldEncrypt($path, $shouldEncryptHomeStorage, $isHomeStorage, $expected): void {
$this->utilMock->expects($this->once())->method('shouldEncryptHomeStorage')
->willReturn($shouldEncryptHomeStorage);
@@ -402,14 +402,14 @@ class EncryptionTest extends TestCase {
}
- public function testDecrypt() {
+ public function testDecrypt(): void {
$this->expectException(\OC\Encryption\Exceptions\DecryptionFailedException::class);
$this->expectExceptionMessage('Cannot decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
$this->instance->decrypt('abc');
}
- public function testPrepareDecryptAll() {
+ public function testPrepareDecryptAll(): void {
/** @var \Symfony\Component\Console\Input\InputInterface $input */
$input = $this->createMock(InputInterface::class);
/** @var \Symfony\Component\Console\Output\OutputInterface $output */
diff --git a/apps/encryption/tests/EncryptedStorageTest.php b/apps/encryption/tests/EncryptedStorageTest.php
index 26d5d9c4941..7671eab4992 100644
--- a/apps/encryption/tests/EncryptedStorageTest.php
+++ b/apps/encryption/tests/EncryptedStorageTest.php
@@ -30,7 +30,7 @@ class EncryptedStorageTest extends TestCase {
use EncryptionTrait;
use UserTrait;
- public function testMoveFromEncrypted() {
+ public function testMoveFromEncrypted(): void {
$this->createUser('test1', 'test2');
$this->setupForUser('test1', 'test2');
diff --git a/apps/encryption/tests/HookManagerTest.php b/apps/encryption/tests/HookManagerTest.php
index 4a662f3bc4a..ad1fac3407f 100644
--- a/apps/encryption/tests/HookManagerTest.php
+++ b/apps/encryption/tests/HookManagerTest.php
@@ -20,7 +20,7 @@ class HookManagerTest extends TestCase {
private static $instance;
- public function testRegisterHookWithArray() {
+ public function testRegisterHookWithArray(): void {
self::$instance->registerHook([
$this->getMockBuilder(IHook::class)->disableOriginalConstructor()->getMock(),
$this->getMockBuilder(IHook::class)->disableOriginalConstructor()->getMock(),
@@ -41,7 +41,7 @@ class HookManagerTest extends TestCase {
}
- public function testRegisterHooksWithInstance() {
+ public function testRegisterHooksWithInstance(): void {
$mock = $this->getMockBuilder(IHook::class)->disableOriginalConstructor()->getMock();
/** @var \OCA\Encryption\Hooks\Contracts\IHook $mock */
self::$instance->registerHook($mock);
diff --git a/apps/encryption/tests/Hooks/UserHooksTest.php b/apps/encryption/tests/Hooks/UserHooksTest.php
index 5c67a5313b6..3bb0b559fdf 100644
--- a/apps/encryption/tests/Hooks/UserHooksTest.php
+++ b/apps/encryption/tests/Hooks/UserHooksTest.php
@@ -76,7 +76,7 @@ class UserHooksTest extends TestCase {
private $params = ['uid' => 'testUser', 'password' => 'password'];
- public function testLogin() {
+ public function testLogin(): void {
$this->userSetupMock->expects($this->once())
->method('setupUser')
->willReturnOnConsecutiveCalls(true, false);
@@ -88,14 +88,14 @@ class UserHooksTest extends TestCase {
$this->assertNull($this->instance->login($this->params));
}
- public function testLogout() {
+ public function testLogout(): void {
$this->sessionMock->expects($this->once())
->method('clear');
$this->instance->logout();
$this->addToAssertionCount(1);
}
- public function testPostCreateUser() {
+ public function testPostCreateUser(): void {
$this->userSetupMock->expects($this->once())
->method('setupUser');
@@ -103,7 +103,7 @@ class UserHooksTest extends TestCase {
$this->addToAssertionCount(1);
}
- public function testPostDeleteUser() {
+ public function testPostDeleteUser(): void {
$this->keyManagerMock->expects($this->once())
->method('deletePublicKey')
->with('testUser');
@@ -112,7 +112,7 @@ class UserHooksTest extends TestCase {
$this->addToAssertionCount(1);
}
- public function testPrePasswordReset() {
+ public function testPrePasswordReset(): void {
$params = ['uid' => 'user1'];
$expected = ['user1' => true];
$this->instance->prePasswordReset($params);
@@ -121,7 +121,7 @@ class UserHooksTest extends TestCase {
$this->assertSame($expected, $passwordResetUsers);
}
- public function testPostPasswordReset() {
+ public function testPostPasswordReset(): void {
$params = ['uid' => 'user1', 'password' => 'password'];
$this->invokePrivate($this->instance, 'passwordResetUsers', [['user1' => true]]);
$this->keyManagerMock->expects($this->once())->method('backupUserKeys')
@@ -139,7 +139,7 @@ class UserHooksTest extends TestCase {
/**
* @dataProvider dataTestPreSetPassphrase
*/
- public function testPreSetPassphrase($canChange) {
+ public function testPreSetPassphrase($canChange): void {
/** @var UserHooks | \PHPUnit\Framework\MockObject\MockObject $instance */
$instance = $this->getMockBuilder(UserHooks::class)
->setConstructorArgs(
@@ -269,7 +269,7 @@ class UserHooksTest extends TestCase {
$this->assertNull($this->instance->setPassphrase($this->params));
}
- public function testSetPassphraseResetUserMode() {
+ public function testSetPassphraseResetUserMode(): void {
$params = ['uid' => 'user1', 'password' => 'password'];
$this->invokePrivate($this->instance, 'passwordResetUsers', [[$params['uid'] => true]]);
$this->sessionMock->expects($this->never())->method('getPrivateKey');
diff --git a/apps/encryption/tests/KeyManagerTest.php b/apps/encryption/tests/KeyManagerTest.php
index b408c9e180b..a9919e8eab4 100644
--- a/apps/encryption/tests/KeyManagerTest.php
+++ b/apps/encryption/tests/KeyManagerTest.php
@@ -95,7 +95,7 @@ class KeyManagerTest extends TestCase {
);
}
- public function testDeleteShareKey() {
+ public function testDeleteShareKey(): void {
$this->keyStorageMock->expects($this->any())
->method('deleteFileKey')
->with($this->equalTo('/path'), $this->equalTo('keyId.shareKey'))
@@ -106,7 +106,7 @@ class KeyManagerTest extends TestCase {
);
}
- public function testGetPrivateKey() {
+ public function testGetPrivateKey(): void {
$this->keyStorageMock->expects($this->any())
->method('getUserKey')
->with($this->equalTo($this->userId), $this->equalTo('privateKey'))
@@ -118,7 +118,7 @@ class KeyManagerTest extends TestCase {
);
}
- public function testGetPublicKey() {
+ public function testGetPublicKey(): void {
$this->keyStorageMock->expects($this->any())
->method('getUserKey')
->with($this->equalTo($this->userId), $this->equalTo('publicKey'))
@@ -130,7 +130,7 @@ class KeyManagerTest extends TestCase {
);
}
- public function testRecoveryKeyExists() {
+ public function testRecoveryKeyExists(): void {
$this->keyStorageMock->expects($this->any())
->method('getSystemUserKey')
->with($this->equalTo($this->systemKeyId . '.publicKey'))
@@ -140,7 +140,7 @@ class KeyManagerTest extends TestCase {
$this->assertTrue($this->instance->recoveryKeyExists());
}
- public function testCheckRecoveryKeyPassword() {
+ public function testCheckRecoveryKeyPassword(): void {
$this->keyStorageMock->expects($this->any())
->method('getSystemUserKey')
->with($this->equalTo($this->systemKeyId . '.privateKey'))
@@ -153,7 +153,7 @@ class KeyManagerTest extends TestCase {
$this->assertTrue($this->instance->checkRecoveryPassword('pass'));
}
- public function testSetPublicKey() {
+ public function testSetPublicKey(): void {
$this->keyStorageMock->expects($this->any())
->method('setUserKey')
->with(
@@ -168,7 +168,7 @@ class KeyManagerTest extends TestCase {
);
}
- public function testSetPrivateKey() {
+ public function testSetPrivateKey(): void {
$this->keyStorageMock->expects($this->any())
->method('setUserKey')
->with(
@@ -186,7 +186,7 @@ class KeyManagerTest extends TestCase {
/**
* @dataProvider dataTestUserHasKeys
*/
- public function testUserHasKeys($key, $expected) {
+ public function testUserHasKeys($key, $expected): void {
$this->keyStorageMock->expects($this->exactly(2))
->method('getUserKey')
->with($this->equalTo($this->userId), $this->anything())
@@ -206,7 +206,7 @@ class KeyManagerTest extends TestCase {
}
- public function testUserHasKeysMissingPrivateKey() {
+ public function testUserHasKeysMissingPrivateKey(): void {
$this->expectException(\OCA\Encryption\Exceptions\PrivateKeyMissingException::class);
$this->keyStorageMock->expects($this->exactly(2))
@@ -222,7 +222,7 @@ class KeyManagerTest extends TestCase {
}
- public function testUserHasKeysMissingPublicKey() {
+ public function testUserHasKeysMissingPublicKey(): void {
$this->expectException(\OCA\Encryption\Exceptions\PublicKeyMissingException::class);
$this->keyStorageMock->expects($this->exactly(2))
@@ -242,7 +242,7 @@ class KeyManagerTest extends TestCase {
*
* @param bool $useMasterKey
*/
- public function testInit($useMasterKey) {
+ public function testInit($useMasterKey): void {
/** @var \OCA\Encryption\KeyManager|\PHPUnit\Framework\MockObject\MockObject $instance */
$instance = $this->getMockBuilder(KeyManager::class)
->setConstructorArgs(
@@ -297,7 +297,7 @@ class KeyManagerTest extends TestCase {
}
- public function testSetRecoveryKey() {
+ public function testSetRecoveryKey(): void {
$this->keyStorageMock->expects($this->exactly(2))
->method('setSystemUserKey')
->willReturn(true);
@@ -313,7 +313,7 @@ class KeyManagerTest extends TestCase {
);
}
- public function testSetSystemPrivateKey() {
+ public function testSetSystemPrivateKey(): void {
$this->keyStorageMock->expects($this->exactly(1))
->method('setSystemUserKey')
->with($this->equalTo('keyId.privateKey'), $this->equalTo('key'))
@@ -325,7 +325,7 @@ class KeyManagerTest extends TestCase {
);
}
- public function testGetSystemPrivateKey() {
+ public function testGetSystemPrivateKey(): void {
$this->keyStorageMock->expects($this->exactly(1))
->method('getSystemUserKey')
->with($this->equalTo('keyId.privateKey'))
@@ -337,7 +337,7 @@ class KeyManagerTest extends TestCase {
);
}
- public function testGetEncryptedFileKey() {
+ public function testGetEncryptedFileKey(): void {
$this->keyStorageMock->expects($this->once())
->method('getFileKey')
->with('/', 'fileKey')
@@ -375,7 +375,7 @@ class KeyManagerTest extends TestCase {
* @param $privateKey
* @param $expected
*/
- public function testGetFileKey($uid, $isMasterKeyEnabled, $privateKey, $encryptedFileKey, $expected) {
+ public function testGetFileKey($uid, $isMasterKeyEnabled, $privateKey, $encryptedFileKey, $expected): void {
$path = '/foo.txt';
if ($isMasterKeyEnabled) {
@@ -446,7 +446,7 @@ class KeyManagerTest extends TestCase {
);
}
- public function testDeletePrivateKey() {
+ public function testDeletePrivateKey(): void {
$this->keyStorageMock->expects($this->once())
->method('deleteUserKey')
->with('user1', 'privateKey')
@@ -457,7 +457,7 @@ class KeyManagerTest extends TestCase {
[$this->userId]));
}
- public function testDeleteAllFileKeys() {
+ public function testDeleteAllFileKeys(): void {
$this->keyStorageMock->expects($this->once())
->method('deleteAllFileKeys')
->willReturn(true);
@@ -475,7 +475,7 @@ class KeyManagerTest extends TestCase {
* @param string $uid
* @param array $expectedKeys
*/
- public function testAddSystemKeys($accessList, $publicKeys, $uid, $expectedKeys) {
+ public function testAddSystemKeys($accessList, $publicKeys, $uid, $expectedKeys): void {
$publicShareKeyId = 'publicShareKey';
$recoveryKeyId = 'recoveryKey';
@@ -521,11 +521,11 @@ class KeyManagerTest extends TestCase {
];
}
- public function testGetMasterKeyId() {
+ public function testGetMasterKeyId(): void {
$this->assertSame('systemKeyId', $this->instance->getMasterKeyId());
}
- public function testGetPublicMasterKey() {
+ public function testGetPublicMasterKey(): void {
$this->keyStorageMock->expects($this->once())->method('getSystemUserKey')
->with('systemKeyId.publicKey', \OCA\Encryption\Crypto\Encryption::ID)
->willReturn(true);
@@ -535,7 +535,7 @@ class KeyManagerTest extends TestCase {
);
}
- public function testGetMasterKeyPassword() {
+ public function testGetMasterKeyPassword(): void {
$this->configMock->expects($this->once())->method('getSystemValue')->with('secret')
->willReturn('password');
@@ -545,7 +545,7 @@ class KeyManagerTest extends TestCase {
}
- public function testGetMasterKeyPasswordException() {
+ public function testGetMasterKeyPasswordException(): void {
$this->expectException(\Exception::class);
$this->configMock->expects($this->once())->method('getSystemValue')->with('secret')
@@ -559,7 +559,7 @@ class KeyManagerTest extends TestCase {
*
* @param $masterKey
*/
- public function testValidateMasterKey($masterKey) {
+ public function testValidateMasterKey($masterKey): void {
/** @var \OCA\Encryption\KeyManager | \PHPUnit\Framework\MockObject\MockObject $instance */
$instance = $this->getMockBuilder(KeyManager::class)
->setConstructorArgs(
@@ -607,7 +607,7 @@ class KeyManagerTest extends TestCase {
$instance->validateMasterKey();
}
- public function testValidateMasterKeyLocked() {
+ public function testValidateMasterKeyLocked(): void {
/** @var \OCA\Encryption\KeyManager | \PHPUnit_Framework_MockObject_MockObject $instance */
$instance = $this->getMockBuilder(KeyManager::class)
->setConstructorArgs(
@@ -650,7 +650,7 @@ class KeyManagerTest extends TestCase {
];
}
- public function testGetVersionWithoutFileInfo() {
+ public function testGetVersionWithoutFileInfo(): void {
$view = $this->getMockBuilder(View::class)
->disableOriginalConstructor()->getMock();
$view->expects($this->once())
@@ -662,7 +662,7 @@ class KeyManagerTest extends TestCase {
$this->assertSame(0, $this->instance->getVersion('/admin/files/myfile.txt', $view));
}
- public function testGetVersionWithFileInfo() {
+ public function testGetVersionWithFileInfo(): void {
$view = $this->getMockBuilder(View::class)
->disableOriginalConstructor()->getMock();
$fileInfo = $this->getMockBuilder(FileInfo::class)
@@ -679,7 +679,7 @@ class KeyManagerTest extends TestCase {
$this->assertSame(1337, $this->instance->getVersion('/admin/files/myfile.txt', $view));
}
- public function testSetVersionWithFileInfo() {
+ public function testSetVersionWithFileInfo(): void {
$view = $this->getMockBuilder(View::class)
->disableOriginalConstructor()->getMock();
$cache = $this->getMockBuilder(ICache::class)
@@ -709,7 +709,7 @@ class KeyManagerTest extends TestCase {
$this->instance->setVersion('/admin/files/myfile.txt', 5, $view);
}
- public function testSetVersionWithoutFileInfo() {
+ public function testSetVersionWithoutFileInfo(): void {
$view = $this->getMockBuilder(View::class)
->disableOriginalConstructor()->getMock();
$view->expects($this->once())
@@ -721,7 +721,7 @@ class KeyManagerTest extends TestCase {
$this->instance->setVersion('/admin/files/myfile.txt', 5, $view);
}
- public function testBackupUserKeys() {
+ public function testBackupUserKeys(): void {
$this->keyStorageMock->expects($this->once())->method('backupUserKeys')
->with('OC_DEFAULT_MODULE', 'test', 'user1');
$this->instance->backupUserKeys('test', 'user1');
diff --git a/apps/encryption/tests/RecoveryTest.php b/apps/encryption/tests/RecoveryTest.php
index a4f4ff7fd02..4b28d408844 100644
--- a/apps/encryption/tests/RecoveryTest.php
+++ b/apps/encryption/tests/RecoveryTest.php
@@ -53,7 +53,7 @@ class RecoveryTest extends TestCase {
*/
private $instance;
- public function testEnableAdminRecoverySuccessful() {
+ public function testEnableAdminRecoverySuccessful(): void {
$this->keyManagerMock->expects($this->exactly(2))
->method('recoveryKeyExists')
->willReturnOnConsecutiveCalls(false, true);
@@ -80,7 +80,7 @@ class RecoveryTest extends TestCase {
$this->assertTrue($this->instance->enableAdminRecovery('password'));
}
- public function testEnableAdminRecoveryCouldNotCheckPassword() {
+ public function testEnableAdminRecoveryCouldNotCheckPassword(): void {
$this->keyManagerMock->expects($this->exactly(2))
->method('recoveryKeyExists')
->willReturnOnConsecutiveCalls(false, true);
@@ -107,7 +107,7 @@ class RecoveryTest extends TestCase {
$this->assertFalse($this->instance->enableAdminRecovery('password'));
}
- public function testEnableAdminRecoveryCouldNotCreateKey() {
+ public function testEnableAdminRecoveryCouldNotCreateKey(): void {
$this->keyManagerMock->expects($this->once())
->method('recoveryKeyExists')
->willReturn(false);
@@ -119,7 +119,7 @@ class RecoveryTest extends TestCase {
$this->assertFalse($this->instance->enableAdminRecovery('password'));
}
- public function testChangeRecoveryKeyPasswordSuccessful() {
+ public function testChangeRecoveryKeyPasswordSuccessful(): void {
$this->assertFalse($this->instance->changeRecoveryKeyPassword('password',
'passwordOld'));
@@ -137,7 +137,7 @@ class RecoveryTest extends TestCase {
'passwordOld'));
}
- public function testChangeRecoveryKeyPasswordCouldNotDecryptPrivateRecoveryKey() {
+ public function testChangeRecoveryKeyPasswordCouldNotDecryptPrivateRecoveryKey(): void {
$this->assertFalse($this->instance->changeRecoveryKeyPassword('password', 'passwordOld'));
$this->keyManagerMock->expects($this->once())
@@ -150,7 +150,7 @@ class RecoveryTest extends TestCase {
$this->assertFalse($this->instance->changeRecoveryKeyPassword('password', 'passwordOld'));
}
- public function testDisableAdminRecovery() {
+ public function testDisableAdminRecovery(): void {
$this->keyManagerMock->expects($this->exactly(2))
->method('checkRecoveryPassword')
->willReturnOnConsecutiveCalls(true, false);
@@ -162,7 +162,7 @@ class RecoveryTest extends TestCase {
$this->assertFalse($this->instance->disableAdminRecovery('password'));
}
- public function testIsRecoveryEnabledForUser() {
+ public function testIsRecoveryEnabledForUser(): void {
$this->configMock->expects($this->exactly(2))
->method('getUserValue')
->willReturnOnConsecutiveCalls('1', '0');
@@ -171,13 +171,13 @@ class RecoveryTest extends TestCase {
$this->assertFalse($this->instance->isRecoveryEnabledForUser('admin'));
}
- public function testIsRecoveryKeyEnabled() {
+ public function testIsRecoveryKeyEnabled(): void {
$this->assertFalse($this->instance->isRecoveryKeyEnabled());
self::$tempStorage['recoveryAdminEnabled'] = '1';
$this->assertTrue($this->instance->isRecoveryKeyEnabled());
}
- public function testSetRecoveryFolderForUser() {
+ public function testSetRecoveryFolderForUser(): void {
$this->viewMock->expects($this->exactly(2))
->method('getDirectoryContent')
->willReturn([]);
@@ -185,7 +185,7 @@ class RecoveryTest extends TestCase {
$this->assertTrue($this->instance->setRecoveryForUser('1'));
}
- public function testRecoverUserFiles() {
+ public function testRecoverUserFiles(): void {
$this->viewMock->expects($this->once())
->method('getDirectoryContent')
->willReturn([]);
@@ -197,7 +197,7 @@ class RecoveryTest extends TestCase {
$this->addToAssertionCount(1);
}
- public function testRecoverFile() {
+ public function testRecoverFile(): void {
$this->keyManagerMock->expects($this->once())
->method('getEncryptedFileKey')
->willReturn(true);
diff --git a/apps/encryption/tests/SessionTest.php b/apps/encryption/tests/SessionTest.php
index 61e57f66611..10c699898fc 100644
--- a/apps/encryption/tests/SessionTest.php
+++ b/apps/encryption/tests/SessionTest.php
@@ -21,7 +21,7 @@ class SessionTest extends TestCase {
private $sessionMock;
- public function testThatGetPrivateKeyThrowsExceptionWhenNotSet() {
+ public function testThatGetPrivateKeyThrowsExceptionWhenNotSet(): void {
$this->expectException(\OCA\Encryption\Exceptions\PrivateKeyMissingException::class);
$this->expectExceptionMessage('Private Key missing for user: please try to log-out and log-in again');
@@ -31,7 +31,7 @@ class SessionTest extends TestCase {
/**
* @depends testThatGetPrivateKeyThrowsExceptionWhenNotSet
*/
- public function testSetAndGetPrivateKey() {
+ public function testSetAndGetPrivateKey(): void {
$this->instance->setPrivateKey('dummyPrivateKey');
$this->assertEquals('dummyPrivateKey', $this->instance->getPrivateKey());
}
@@ -39,7 +39,7 @@ class SessionTest extends TestCase {
/**
* @depends testSetAndGetPrivateKey
*/
- public function testIsPrivateKeySet() {
+ public function testIsPrivateKeySet(): void {
$this->instance->setPrivateKey('dummyPrivateKey');
$this->assertTrue($this->instance->isPrivateKeySet());
@@ -50,21 +50,21 @@ class SessionTest extends TestCase {
self::$tempStorage['privateKey'] = 'dummyPrivateKey';
}
- public function testDecryptAllModeActivated() {
+ public function testDecryptAllModeActivated(): void {
$this->instance->prepareDecryptAll('user1', 'usersKey');
$this->assertTrue($this->instance->decryptAllModeActivated());
$this->assertSame('user1', $this->instance->getDecryptAllUid());
$this->assertSame('usersKey', $this->instance->getDecryptAllKey());
}
- public function testDecryptAllModeDeactivated() {
+ public function testDecryptAllModeDeactivated(): void {
$this->assertFalse($this->instance->decryptAllModeActivated());
}
/**
* @expectExceptionMessage 'Please activate decrypt all mode first'
*/
- public function testGetDecryptAllUidException() {
+ public function testGetDecryptAllUidException(): void {
$this->expectException(\Exception::class);
$this->instance->getDecryptAllUid();
@@ -73,7 +73,7 @@ class SessionTest extends TestCase {
/**
* @expectExceptionMessage 'No uid found while in decrypt all mode'
*/
- public function testGetDecryptAllUidException2() {
+ public function testGetDecryptAllUidException2(): void {
$this->expectException(\Exception::class);
$this->instance->prepareDecryptAll(null, 'key');
@@ -83,7 +83,7 @@ class SessionTest extends TestCase {
/**
* @expectExceptionMessage 'Please activate decrypt all mode first'
*/
- public function testGetDecryptAllKeyException() {
+ public function testGetDecryptAllKeyException(): void {
$this->expectException(\OCA\Encryption\Exceptions\PrivateKeyMissingException::class);
$this->instance->getDecryptAllKey();
@@ -92,7 +92,7 @@ class SessionTest extends TestCase {
/**
* @expectExceptionMessage 'No key found while in decrypt all mode'
*/
- public function testGetDecryptAllKeyException2() {
+ public function testGetDecryptAllKeyException2(): void {
$this->expectException(\OCA\Encryption\Exceptions\PrivateKeyMissingException::class);
$this->instance->prepareDecryptAll('user', null);
@@ -100,7 +100,7 @@ class SessionTest extends TestCase {
}
- public function testSetAndGetStatusWillSetAndReturn() {
+ public function testSetAndGetStatusWillSetAndReturn(): void {
// Check if get status will return 0 if it has not been set before
$this->assertEquals(0, $this->instance->getStatus());
@@ -120,7 +120,7 @@ class SessionTest extends TestCase {
* @param int $status
* @param bool $expected
*/
- public function testIsReady($status, $expected) {
+ public function testIsReady($status, $expected): void {
/** @var Session | \PHPUnit\Framework\MockObject\MockObject $instance */
$instance = $this->getMockBuilder(Session::class)
->setConstructorArgs([$this->sessionMock])
@@ -167,7 +167,7 @@ class SessionTest extends TestCase {
}
- public function testClearWillRemoveValues() {
+ public function testClearWillRemoveValues(): void {
$this->instance->setPrivateKey('privateKey');
$this->instance->setStatus('initStatus');
$this->instance->prepareDecryptAll('user', 'key');
diff --git a/apps/encryption/tests/Settings/AdminTest.php b/apps/encryption/tests/Settings/AdminTest.php
index 80f7803badd..4ddaeb1b84d 100644
--- a/apps/encryption/tests/Settings/AdminTest.php
+++ b/apps/encryption/tests/Settings/AdminTest.php
@@ -51,7 +51,7 @@ class AdminTest extends TestCase {
);
}
- public function testGetForm() {
+ public function testGetForm(): void {
$this->config
->method('getAppValue')
->will($this->returnCallback(function ($app, $key, $default) {
@@ -73,11 +73,11 @@ class AdminTest extends TestCase {
$this->assertEquals($expected, $this->admin->getForm());
}
- public function testGetSection() {
+ public function testGetSection(): void {
$this->assertSame('security', $this->admin->getSection());
}
- public function testGetPriority() {
+ public function testGetPriority(): void {
$this->assertSame(11, $this->admin->getPriority());
}
}
diff --git a/apps/encryption/tests/Users/SetupTest.php b/apps/encryption/tests/Users/SetupTest.php
index 96d2357269e..92f24a0627c 100644
--- a/apps/encryption/tests/Users/SetupTest.php
+++ b/apps/encryption/tests/Users/SetupTest.php
@@ -42,7 +42,7 @@ class SetupTest extends TestCase {
}
- public function testSetupSystem() {
+ public function testSetupSystem(): void {
$this->keyManagerMock->expects($this->once())->method('validateShareKey');
$this->keyManagerMock->expects($this->once())->method('validateMasterKey');
@@ -55,7 +55,7 @@ class SetupTest extends TestCase {
* @param bool $hasKeys
* @param bool $expected
*/
- public function testSetupUser($hasKeys, $expected) {
+ public function testSetupUser($hasKeys, $expected): void {
$this->keyManagerMock->expects($this->once())->method('userHasKeys')
->with('uid')->willReturn($hasKeys);
diff --git a/apps/encryption/tests/UtilTest.php b/apps/encryption/tests/UtilTest.php
index 3bfc0efb516..6f2eec1ebf4 100644
--- a/apps/encryption/tests/UtilTest.php
+++ b/apps/encryption/tests/UtilTest.php
@@ -37,12 +37,12 @@ class UtilTest extends TestCase {
/** @var Util */
private $instance;
- public function testSetRecoveryForUser() {
+ public function testSetRecoveryForUser(): void {
$this->instance->setRecoveryForUser('1');
$this->assertArrayHasKey('recoveryEnabled', self::$tempStorage);
}
- public function testIsRecoveryEnabledForUser() {
+ public function testIsRecoveryEnabledForUser(): void {
$this->assertTrue($this->instance->isRecoveryEnabledForUser('admin'));
// Assert recovery will return default value if not set
@@ -50,7 +50,7 @@ class UtilTest extends TestCase {
$this->assertEquals(0, $this->instance->isRecoveryEnabledForUser('admin'));
}
- public function testUserHasFiles() {
+ public function testUserHasFiles(): void {
$this->filesMock->expects($this->once())
->method('file_exists')
->willReturn(true);
@@ -126,7 +126,7 @@ class UtilTest extends TestCase {
* @param string $value
* @param bool $expect
*/
- public function testIsMasterKeyEnabled($value, $expect) {
+ public function testIsMasterKeyEnabled($value, $expect): void {
$this->configMock->expects($this->once())->method('getAppValue')
->with('encryption', 'useMasterKey', '1')->willReturn($value);
$this->assertSame($expect,
@@ -146,7 +146,7 @@ class UtilTest extends TestCase {
* @param string $returnValue return value from getAppValue()
* @param bool $expected
*/
- public function testShouldEncryptHomeStorage($returnValue, $expected) {
+ public function testShouldEncryptHomeStorage($returnValue, $expected): void {
$this->configMock->expects($this->once())->method('getAppValue')
->with('encryption', 'encryptHomeStorage', '1')
->willReturn($returnValue);
@@ -167,7 +167,7 @@ class UtilTest extends TestCase {
* @param $value
* @param $expected
*/
- public function testSetEncryptHomeStorage($value, $expected) {
+ public function testSetEncryptHomeStorage($value, $expected): void {
$this->configMock->expects($this->once())->method('setAppValue')
->with('encryption', 'encryptHomeStorage', $expected);
$this->instance->setEncryptHomeStorage($value);
@@ -180,7 +180,7 @@ class UtilTest extends TestCase {
];
}
- public function testGetStorage() {
+ public function testGetStorage(): void {
$return = $this->getMockBuilder(Storage::class)
->disableOriginalConstructor()
->getMock();
diff --git a/apps/federatedfilesharing/tests/AddressHandlerTest.php b/apps/federatedfilesharing/tests/AddressHandlerTest.php
index 3fb2a938a66..e235314e008 100644
--- a/apps/federatedfilesharing/tests/AddressHandlerTest.php
+++ b/apps/federatedfilesharing/tests/AddressHandlerTest.php
@@ -96,7 +96,7 @@ class AddressHandlerTest extends \Test\TestCase {
* @param string $expectedUser
* @param string $expectedUrl
*/
- public function testSplitUserRemote($remote, $expectedUser, $expectedUrl) {
+ public function testSplitUserRemote($remote, $expectedUser, $expectedUrl): void {
$this->contactsManager->expects($this->any())
->method('search')
->willReturn([]);
@@ -129,7 +129,7 @@ class AddressHandlerTest extends \Test\TestCase {
*
* @param string $id
*/
- public function testSplitUserRemoteError($id) {
+ public function testSplitUserRemoteError($id): void {
$this->expectException(\OCP\HintException::class);
$this->addressHandler->splitUserRemote($id);
@@ -144,7 +144,7 @@ class AddressHandlerTest extends \Test\TestCase {
* @param string $server2
* @param bool $expected
*/
- public function testCompareAddresses($user1, $server1, $user2, $server2, $expected) {
+ public function testCompareAddresses($user1, $server1, $user2, $server2, $expected): void {
$this->assertSame($expected,
$this->addressHandler->compareAddresses($user1, $server1, $user2, $server2)
);
@@ -176,7 +176,7 @@ class AddressHandlerTest extends \Test\TestCase {
* @param string $url
* @param string $expectedResult
*/
- public function testRemoveProtocolFromUrl($url, $expectedResult) {
+ public function testRemoveProtocolFromUrl($url, $expectedResult): void {
$result = $this->addressHandler->removeProtocolFromUrl($url);
$this->assertSame($expectedResult, $result);
}
@@ -195,7 +195,7 @@ class AddressHandlerTest extends \Test\TestCase {
* @param string $url
* @param bool $expectedResult
*/
- public function testUrlContainProtocol($url, $expectedResult) {
+ public function testUrlContainProtocol($url, $expectedResult): void {
$result = $this->addressHandler->urlContainProtocol($url);
$this->assertSame($expectedResult, $result);
}
diff --git a/apps/federatedfilesharing/tests/Controller/MountPublicLinkControllerTest.php b/apps/federatedfilesharing/tests/Controller/MountPublicLinkControllerTest.php
index 1fcca4e19cf..f365055c428 100644
--- a/apps/federatedfilesharing/tests/Controller/MountPublicLinkControllerTest.php
+++ b/apps/federatedfilesharing/tests/Controller/MountPublicLinkControllerTest.php
@@ -130,7 +130,7 @@ class MountPublicLinkControllerTest extends \Test\TestCase {
$createSuccessful,
$expectedReturnData,
$permissions
- ) {
+ ): void {
$this->federatedShareProvider->expects($this->any())
->method('isOutgoingServer2serverShareEnabled')
->willReturn($outgoingSharesAllowed);
diff --git a/apps/federatedfilesharing/tests/Controller/RequestHandlerControllerTest.php b/apps/federatedfilesharing/tests/Controller/RequestHandlerControllerTest.php
index b9616d6f7e1..51350fddfa0 100644
--- a/apps/federatedfilesharing/tests/Controller/RequestHandlerControllerTest.php
+++ b/apps/federatedfilesharing/tests/Controller/RequestHandlerControllerTest.php
@@ -130,7 +130,7 @@ class RequestHandlerControllerTest extends \Test\TestCase {
);
}
- public function testCreateShare() {
+ public function testCreateShare(): void {
$this->cloudFederationFactory->expects($this->once())->method('getCloudFederationShare')
->with(
$this->user2,
@@ -160,7 +160,7 @@ class RequestHandlerControllerTest extends \Test\TestCase {
$this->assertInstanceOf(DataResponse::class, $result);
}
- public function testDeclineShare() {
+ public function testDeclineShare(): void {
$id = 42;
$notification = [
@@ -183,7 +183,7 @@ class RequestHandlerControllerTest extends \Test\TestCase {
}
- public function testAcceptShare() {
+ public function testAcceptShare(): void {
$id = 42;
$notification = [
diff --git a/apps/federatedfilesharing/tests/FederatedShareProviderTest.php b/apps/federatedfilesharing/tests/FederatedShareProviderTest.php
index 1ae206d9234..a687c5738e1 100644
--- a/apps/federatedfilesharing/tests/FederatedShareProviderTest.php
+++ b/apps/federatedfilesharing/tests/FederatedShareProviderTest.php
@@ -1,989 +1,989 @@
-<?php
-
-/**
- * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
- * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
- * SPDX-License-Identifier: AGPL-3.0-only
- */
-namespace OCA\FederatedFileSharing\Tests;
-
-use OC\Federation\CloudIdManager;
-use OCA\FederatedFileSharing\AddressHandler;
-use OCA\FederatedFileSharing\FederatedShareProvider;
-use OCA\FederatedFileSharing\Notifications;
-use OCA\FederatedFileSharing\TokenHandler;
-use OCP\Contacts\IManager as IContactsManager;
-use OCP\EventDispatcher\IEventDispatcher;
-use OCP\Federation\ICloudFederationProviderManager;
-use OCP\Federation\ICloudIdManager;
-use OCP\Files\File;
-use OCP\Files\IRootFolder;
-use OCP\ICacheFactory;
-use OCP\IConfig;
-use OCP\IDBConnection;
-use OCP\IL10N;
-use OCP\IURLGenerator;
-use OCP\IUserManager;
-use OCP\Share\IManager;
-use OCP\Share\IShare;
-use PHPUnit\Framework\MockObject\MockObject;
-use Psr\Log\LoggerInterface;
-
-/**
- * Class FederatedShareProviderTest
- *
- * @package OCA\FederatedFileSharing\Tests
- * @group DB
- */
-class FederatedShareProviderTest extends \Test\TestCase {
- /** @var IDBConnection */
- protected $connection;
- /** @var AddressHandler|MockObject */
- protected $addressHandler;
- /** @var Notifications|MockObject */
- protected $notifications;
- /** @var TokenHandler|MockObject */
- protected $tokenHandler;
- /** @var IL10N */
- protected $l;
- /** @var LoggerInterface */
- protected $logger;
- /** @var IRootFolder|MockObject */
- protected $rootFolder;
- /** @var IConfig|MockObject */
- protected $config;
- /** @var IUserManager|MockObject */
- protected $userManager;
- /** @var \OCP\GlobalScale\IConfig|MockObject */
- protected $gsConfig;
-
- /** @var IManager */
- protected $shareManager;
- /** @var FederatedShareProvider */
- protected $provider;
- /** @var IContactsManager|MockObject */
- protected $contactsManager;
-
- /** @var ICloudIdManager */
- private $cloudIdManager;
-
- /** @var MockObject|ICloudFederationProviderManager */
- private $cloudFederationProviderManager;
-
- protected function setUp(): void {
- parent::setUp();
-
- $this->connection = \OC::$server->getDatabaseConnection();
- $this->notifications = $this->getMockBuilder(\OCA\FederatedFileSharing\Notifications::class)
- ->disableOriginalConstructor()
- ->getMock();
- $this->tokenHandler = $this->getMockBuilder(\OCA\FederatedFileSharing\TokenHandler::class)
- ->disableOriginalConstructor()
- ->getMock();
- $this->l = $this->getMockBuilder(IL10N::class)->getMock();
- $this->l->method('t')
- ->willReturnCallback(function ($text, $parameters = []) {
- return vsprintf($text, $parameters);
- });
- $this->logger = $this->getMockBuilder(LoggerInterface::class)->getMock();
- $this->rootFolder = $this->getMockBuilder(\OCP\Files\IRootFolder::class)->getMock();
- $this->config = $this->getMockBuilder(IConfig::class)->getMock();
- $this->userManager = $this->getMockBuilder(IUserManager::class)->getMock();
- //$this->addressHandler = new AddressHandler(\OC::$server->getURLGenerator(), $this->l);
- $this->addressHandler = $this->getMockBuilder(\OCA\FederatedFileSharing\AddressHandler::class)->disableOriginalConstructor()->getMock();
- $this->contactsManager = $this->createMock(IContactsManager::class);
- $this->cloudIdManager = new CloudIdManager(
- $this->contactsManager,
- $this->createMock(IURLGenerator::class),
- $this->userManager,
- $this->createMock(ICacheFactory::class),
- $this->createMock(IEventDispatcher::class)
- );
- $this->gsConfig = $this->createMock(\OCP\GlobalScale\IConfig::class);
-
- $this->userManager->expects($this->any())->method('userExists')->willReturn(true);
-
- $this->cloudFederationProviderManager = $this->createMock(ICloudFederationProviderManager::class);
-
- $this->provider = new FederatedShareProvider(
- $this->connection,
- $this->addressHandler,
- $this->notifications,
- $this->tokenHandler,
- $this->l,
- $this->rootFolder,
- $this->config,
- $this->userManager,
- $this->cloudIdManager,
- $this->gsConfig,
- $this->cloudFederationProviderManager,
- $this->logger,
- );
-
- $this->shareManager = \OC::$server->getShareManager();
- }
-
- protected function tearDown(): void {
- $this->connection->getQueryBuilder()->delete('share')->execute();
-
- parent::tearDown();
- }
-
- public function dataTestCreate() {
- return [
- [null, null],
- [new \DateTime('2020-03-01T01:02:03'), '2020-03-01 01:02:03'],
- ];
- }
-
- /**
- * @dataProvider dataTestCreate
- */
- public function testCreate($expirationDate, $expectedDataDate) {
- $share = $this->shareManager->newShare();
-
- /** @var File|MockObject $node */
- $node = $this->getMockBuilder(File::class)->getMock();
- $node->method('getId')->willReturn(42);
- $node->method('getName')->willReturn('myFile');
-
- $share->setSharedWith('user@server.com')
- ->setSharedBy('sharedBy')
- ->setShareOwner('shareOwner')
- ->setPermissions(19)
- ->setShareType(IShare::TYPE_REMOTE)
- ->setExpirationDate($expirationDate)
- ->setNode($node);
-
- $this->tokenHandler->method('generateToken')->willReturn('token');
-
- $this->addressHandler->expects($this->any())->method('generateRemoteURL')
- ->willReturn('http://localhost/');
- $this->addressHandler->expects($this->any())->method('splitUserRemote')
- ->willReturn(['user', 'server.com']);
-
- $this->notifications->expects($this->once())
- ->method('sendRemoteShare')
- ->with(
- $this->equalTo('token'),
- $this->equalTo('user@server.com'),
- $this->equalTo('myFile'),
- $this->anything(),
- 'shareOwner',
- 'shareOwner@http://localhost',
- 'sharedBy',
- 'sharedBy@http://localhost'
- )
- ->willReturn(true);
-
- $this->rootFolder->expects($this->never())->method($this->anything());
-
- $this->contactsManager->expects($this->any())
- ->method('search')
- ->willReturn([]);
-
- $share = $this->provider->create($share);
-
- $qb = $this->connection->getQueryBuilder();
- $stmt = $qb->select('*')
- ->from('share')
- ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
- ->execute();
-
- $data = $stmt->fetch();
- $stmt->closeCursor();
-
- $expected = [
- 'share_type' => IShare::TYPE_REMOTE,
- 'share_with' => 'user@server.com',
- 'uid_owner' => 'shareOwner',
- 'uid_initiator' => 'sharedBy',
- 'item_type' => 'file',
- 'item_source' => 42,
- 'file_source' => 42,
- 'permissions' => 19,
- 'accepted' => 0,
- 'token' => 'token',
- 'expiration' => $expectedDataDate,
- ];
- foreach (array_keys($expected) as $key) {
- $this->assertEquals($expected[$key], $data[$key], "Assert that value for key '$key' is the same");
- }
-
- $this->assertEquals($data['id'], $share->getId());
- $this->assertEquals(IShare::TYPE_REMOTE, $share->getShareType());
- $this->assertEquals('user@server.com', $share->getSharedWith());
- $this->assertEquals('sharedBy', $share->getSharedBy());
- $this->assertEquals('shareOwner', $share->getShareOwner());
- $this->assertEquals('file', $share->getNodeType());
- $this->assertEquals(42, $share->getNodeId());
- $this->assertEquals(19, $share->getPermissions());
- $this->assertEquals('token', $share->getToken());
- $this->assertEquals($expirationDate, $share->getExpirationDate());
- }
-
- public function testCreateCouldNotFindServer() {
- $share = $this->shareManager->newShare();
-
- $node = $this->getMockBuilder(File::class)->getMock();
- $node->method('getId')->willReturn(42);
- $node->method('getName')->willReturn('myFile');
-
- $share->setSharedWith('user@server.com')
- ->setSharedBy('sharedBy')
- ->setShareOwner('shareOwner')
- ->setPermissions(19)
- ->setShareType(IShare::TYPE_REMOTE)
- ->setNode($node);
-
- $this->tokenHandler->method('generateToken')->willReturn('token');
-
- $this->addressHandler->expects($this->any())->method('generateRemoteURL')
- ->willReturn('http://localhost/');
- $this->addressHandler->expects($this->any())->method('splitUserRemote')
- ->willReturn(['user', 'server.com']);
-
- $this->notifications->expects($this->once())
- ->method('sendRemoteShare')
- ->with(
- $this->equalTo('token'),
- $this->equalTo('user@server.com'),
- $this->equalTo('myFile'),
- $this->anything(),
- 'shareOwner',
- 'shareOwner@http://localhost',
- 'sharedBy',
- 'sharedBy@http://localhost'
- )->willReturn(false);
-
- $this->rootFolder->method('getById')
- ->with('42')
- ->willReturn([$node]);
-
- $this->contactsManager->expects($this->any())
- ->method('search')
- ->willReturn([]);
-
- try {
- $share = $this->provider->create($share);
- $this->fail();
- } catch (\Exception $e) {
- $this->assertEquals('Sharing myFile failed, could not find user@server.com, maybe the server is currently unreachable or uses a self-signed certificate.', $e->getMessage());
- }
-
- $qb = $this->connection->getQueryBuilder();
- $stmt = $qb->select('*')
- ->from('share')
- ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
- ->execute();
-
- $data = $stmt->fetch();
- $stmt->closeCursor();
-
- $this->assertFalse($data);
- }
-
- public function testCreateException() {
- $share = $this->shareManager->newShare();
-
- $node = $this->getMockBuilder(File::class)->getMock();
- $node->method('getId')->willReturn(42);
- $node->method('getName')->willReturn('myFile');
-
- $share->setSharedWith('user@server.com')
- ->setSharedBy('sharedBy')
- ->setShareOwner('shareOwner')
- ->setPermissions(19)
- ->setShareType(IShare::TYPE_REMOTE)
- ->setNode($node);
-
- $this->tokenHandler->method('generateToken')->willReturn('token');
-
- $this->addressHandler->expects($this->any())->method('generateRemoteURL')
- ->willReturn('http://localhost/');
- $this->addressHandler->expects($this->any())->method('splitUserRemote')
- ->willReturn(['user', 'server.com']);
-
- $this->notifications->expects($this->once())
- ->method('sendRemoteShare')
- ->with(
- $this->equalTo('token'),
- $this->equalTo('user@server.com'),
- $this->equalTo('myFile'),
- $this->anything(),
- 'shareOwner',
- 'shareOwner@http://localhost',
- 'sharedBy',
- 'sharedBy@http://localhost'
- )->willThrowException(new \Exception('dummy'));
-
- $this->rootFolder->method('getById')
- ->with('42')
- ->willReturn([$node]);
-
- $this->contactsManager->expects($this->any())
- ->method('search')
- ->willReturn([]);
-
- try {
- $share = $this->provider->create($share);
- $this->fail();
- } catch (\Exception $e) {
- $this->assertEquals('Sharing myFile failed, could not find user@server.com, maybe the server is currently unreachable or uses a self-signed certificate.', $e->getMessage());
- }
-
- $qb = $this->connection->getQueryBuilder();
- $stmt = $qb->select('*')
- ->from('share')
- ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
- ->execute();
-
- $data = $stmt->fetch();
- $stmt->closeCursor();
-
- $this->assertFalse($data);
- }
-
- public function testCreateShareWithSelf() {
- $share = $this->shareManager->newShare();
-
- $node = $this->getMockBuilder(File::class)->getMock();
- $node->method('getId')->willReturn(42);
- $node->method('getName')->willReturn('myFile');
-
- $this->addressHandler->expects($this->any())->method('compareAddresses')
- ->willReturn(true);
-
- $shareWith = 'sharedBy@localhost';
-
- $share->setSharedWith($shareWith)
- ->setSharedBy('sharedBy')
- ->setShareOwner('shareOwner')
- ->setPermissions(19)
- ->setNode($node);
-
- $this->contactsManager->expects($this->any())
- ->method('search')
- ->willReturn([]);
-
- $this->rootFolder->expects($this->never())->method($this->anything());
-
- try {
- $share = $this->provider->create($share);
- $this->fail();
- } catch (\Exception $e) {
- $this->assertEquals('Not allowed to create a federated share to the same account', $e->getMessage());
- }
-
- $qb = $this->connection->getQueryBuilder();
- $stmt = $qb->select('*')
- ->from('share')
- ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
- ->execute();
-
- $data = $stmt->fetch();
- $stmt->closeCursor();
-
- $this->assertFalse($data);
- }
-
- public function testCreateAlreadyShared() {
- $share = $this->shareManager->newShare();
-
- $node = $this->getMockBuilder(File::class)->getMock();
- $node->method('getId')->willReturn(42);
- $node->method('getName')->willReturn('myFile');
-
-
- $this->addressHandler->expects($this->any())->method('splitUserRemote')
- ->willReturn(['user', 'server.com']);
-
- $share->setSharedWith('user@server.com')
- ->setSharedBy('sharedBy')
- ->setShareOwner('shareOwner')
- ->setPermissions(19)
- ->setShareType(IShare::TYPE_REMOTE)
- ->setNode($node);
-
- $this->tokenHandler->method('generateToken')->willReturn('token');
-
- $this->addressHandler->expects($this->any())->method('generateRemoteURL')
- ->willReturn('http://localhost/');
-
- $this->notifications->expects($this->once())
- ->method('sendRemoteShare')
- ->with(
- $this->equalTo('token'),
- $this->equalTo('user@server.com'),
- $this->equalTo('myFile'),
- $this->anything(),
- 'shareOwner',
- 'shareOwner@http://localhost',
- 'sharedBy',
- 'sharedBy@http://localhost'
- )->willReturn(true);
-
- $this->rootFolder->expects($this->never())->method($this->anything());
-
- $this->contactsManager->expects($this->any())
- ->method('search')
- ->willReturn([]);
-
- $this->provider->create($share);
-
- try {
- $this->provider->create($share);
- } catch (\Exception $e) {
- $this->assertEquals('Sharing myFile failed, because this item is already shared with the account user@server.com', $e->getMessage());
- }
- }
-
- /**
- * @dataProvider dataTestUpdate
- */
- public function testUpdate($owner, $sharedBy, $expirationDate) {
- $this->provider = $this->getMockBuilder(\OCA\FederatedFileSharing\FederatedShareProvider::class)
- ->setConstructorArgs(
- [
- $this->connection,
- $this->addressHandler,
- $this->notifications,
- $this->tokenHandler,
- $this->l,
- $this->rootFolder,
- $this->config,
- $this->userManager,
- $this->cloudIdManager,
- $this->gsConfig,
- $this->cloudFederationProviderManager,
- $this->logger,
- ]
- )->setMethods(['sendPermissionUpdate'])->getMock();
-
- $share = $this->shareManager->newShare();
-
- $node = $this->getMockBuilder(File::class)->getMock();
- $node->method('getId')->willReturn(42);
- $node->method('getName')->willReturn('myFile');
-
- $this->addressHandler->expects($this->any())->method('splitUserRemote')
- ->willReturn(['user', 'server.com']);
-
- $share->setSharedWith('user@server.com')
- ->setSharedBy($sharedBy)
- ->setShareOwner($owner)
- ->setPermissions(19)
- ->setShareType(IShare::TYPE_REMOTE)
- ->setExpirationDate(new \DateTime('2019-02-01T01:02:03'))
- ->setNode($node);
-
- $this->tokenHandler->method('generateToken')->willReturn('token');
- $this->addressHandler->expects($this->any())->method('generateRemoteURL')
- ->willReturn('http://localhost/');
-
- $this->notifications->expects($this->once())
- ->method('sendRemoteShare')
- ->with(
- $this->equalTo('token'),
- $this->equalTo('user@server.com'),
- $this->equalTo('myFile'),
- $this->anything(),
- $owner,
- $owner . '@http://localhost',
- $sharedBy,
- $sharedBy . '@http://localhost'
- )->willReturn(true);
-
- if ($owner === $sharedBy) {
- $this->provider->expects($this->never())->method('sendPermissionUpdate');
- } else {
- $this->provider->expects($this->once())->method('sendPermissionUpdate');
- }
-
- $this->rootFolder->expects($this->never())->method($this->anything());
-
- $this->contactsManager->expects($this->any())
- ->method('search')
- ->willReturn([]);
-
- $share = $this->provider->create($share);
-
- $share->setPermissions(1);
- $share->setExpirationDate($expirationDate);
- $this->provider->update($share);
-
- $share = $this->provider->getShareById($share->getId());
-
- $this->assertEquals(1, $share->getPermissions());
- $this->assertEquals($expirationDate, $share->getExpirationDate());
- }
-
- public function dataTestUpdate() {
- return [
- ['sharedBy', 'shareOwner', new \DateTime('2020-03-01T01:02:03')],
- ['shareOwner', 'shareOwner', null],
- ];
- }
-
- public function testGetSharedBy() {
- $node = $this->getMockBuilder(File::class)->getMock();
- $node->method('getId')->willReturn(42);
- $node->method('getName')->willReturn('myFile');
-
- $this->addressHandler->expects($this->never())->method('splitUserRemote');
-
- $this->addressHandler->method('generateRemoteURL')
- ->willReturn('remoteurl.com');
-
- $this->tokenHandler->method('generateToken')->willReturn('token');
- $this->notifications
- ->method('sendRemoteShare')
- ->willReturn(true);
-
- $this->rootFolder->expects($this->never())->method($this->anything());
-
- $this->contactsManager->expects($this->any())
- ->method('search')
- ->willReturn([]);
-
- $share = $this->shareManager->newShare();
- $share->setSharedWith('user@server.com')
- ->setSharedBy('sharedBy')
- ->setShareOwner('shareOwner')
- ->setPermissions(19)
- ->setShareType(IShare::TYPE_REMOTE)
- ->setNode($node);
- $this->provider->create($share);
-
- $share2 = $this->shareManager->newShare();
- $share2->setSharedWith('user2@server.com')
- ->setSharedBy('sharedBy2')
- ->setShareOwner('shareOwner')
- ->setPermissions(19)
- ->setShareType(IShare::TYPE_REMOTE)
- ->setNode($node);
- $this->provider->create($share2);
-
- $shares = $this->provider->getSharesBy('sharedBy', IShare::TYPE_REMOTE, null, false, -1, 0);
-
- $this->assertCount(1, $shares);
- $this->assertEquals('user@server.com', $shares[0]->getSharedWith());
- $this->assertEquals('sharedBy', $shares[0]->getSharedBy());
- }
-
- public function testGetSharedByWithNode() {
- $node = $this->getMockBuilder(File::class)->getMock();
- $node->method('getId')->willReturn(42);
- $node->method('getName')->willReturn('myFile');
-
- $this->tokenHandler->method('generateToken')->willReturn('token');
- $this->notifications
- ->method('sendRemoteShare')
- ->willReturn(true);
-
- $this->rootFolder->expects($this->never())->method($this->anything());
-
- $this->addressHandler->method('generateRemoteURL')
- ->willReturn('remoteurl.com');
-
- $this->contactsManager->expects($this->any())
- ->method('search')
- ->willReturn([]);
-
- $share = $this->shareManager->newShare();
- $share->setSharedWith('user@server.com')
- ->setSharedBy('sharedBy')
- ->setShareOwner('shareOwner')
- ->setPermissions(19)
- ->setShareType(IShare::TYPE_REMOTE)
- ->setNode($node);
- $this->provider->create($share);
-
- $node2 = $this->getMockBuilder(File::class)->getMock();
- $node2->method('getId')->willReturn(43);
- $node2->method('getName')->willReturn('myOtherFile');
-
- $share2 = $this->shareManager->newShare();
- $share2->setSharedWith('user@server.com')
- ->setSharedBy('sharedBy')
- ->setShareOwner('shareOwner')
- ->setPermissions(19)
- ->setShareType(IShare::TYPE_REMOTE)
- ->setNode($node2);
- $this->provider->create($share2);
-
- $shares = $this->provider->getSharesBy('sharedBy', IShare::TYPE_REMOTE, $node2, false, -1, 0);
-
- $this->assertCount(1, $shares);
- $this->assertEquals(43, $shares[0]->getNodeId());
- }
-
- public function testGetSharedByWithReshares() {
- $node = $this->getMockBuilder(File::class)->getMock();
- $node->method('getId')->willReturn(42);
- $node->method('getName')->willReturn('myFile');
-
- $this->tokenHandler->method('generateToken')->willReturn('token');
- $this->notifications
- ->method('sendRemoteShare')
- ->willReturn(true);
-
- $this->rootFolder->expects($this->never())->method($this->anything());
-
- $this->addressHandler->method('generateRemoteURL')
- ->willReturn('remoteurl.com');
-
- $this->contactsManager->expects($this->any())
- ->method('search')
- ->willReturn([]);
-
- $share = $this->shareManager->newShare();
- $share->setSharedWith('user@server.com')
- ->setSharedBy('shareOwner')
- ->setShareOwner('shareOwner')
- ->setPermissions(19)
- ->setShareType(IShare::TYPE_REMOTE)
- ->setNode($node);
- $this->provider->create($share);
-
- $share2 = $this->shareManager->newShare();
- $share2->setSharedWith('user2@server.com')
- ->setSharedBy('sharedBy')
- ->setShareOwner('shareOwner')
- ->setPermissions(19)
- ->setShareType(IShare::TYPE_REMOTE)
- ->setNode($node);
- $this->provider->create($share2);
-
- $shares = $this->provider->getSharesBy('shareOwner', IShare::TYPE_REMOTE, null, true, -1, 0);
-
- $this->assertCount(2, $shares);
- }
-
- public function testGetSharedByWithLimit() {
- $node = $this->getMockBuilder(File::class)->getMock();
- $node->method('getId')->willReturn(42);
- $node->method('getName')->willReturn('myFile');
-
- $this->addressHandler->expects($this->any())->method('splitUserRemote')
- ->willReturnCallback(function ($uid) {
- if ($uid === 'user@server.com') {
- return ['user', 'server.com'];
- }
- return ['user2', 'server.com'];
- });
-
- $this->tokenHandler->method('generateToken')->willReturn('token');
- $this->notifications
- ->method('sendRemoteShare')
- ->willReturn(true);
-
- $this->rootFolder->expects($this->never())->method($this->anything());
-
- $this->addressHandler->method('generateRemoteURL')
- ->willReturn('remoteurl.com');
-
- $this->contactsManager->expects($this->any())
- ->method('search')
- ->willReturn([]);
-
- $share = $this->shareManager->newShare();
- $share->setSharedWith('user@server.com')
- ->setSharedBy('sharedBy')
- ->setShareOwner('shareOwner')
- ->setPermissions(19)
- ->setShareType(IShare::TYPE_REMOTE)
- ->setNode($node);
- $this->provider->create($share);
-
- $share2 = $this->shareManager->newShare();
- $share2->setSharedWith('user2@server.com')
- ->setSharedBy('sharedBy')
- ->setShareOwner('shareOwner')
- ->setPermissions(19)
- ->setShareType(IShare::TYPE_REMOTE)
- ->setNode($node);
- $this->provider->create($share2);
-
- $shares = $this->provider->getSharesBy('shareOwner', IShare::TYPE_REMOTE, null, true, 1, 1);
-
- $this->assertCount(1, $shares);
- $this->assertEquals('user2@server.com', $shares[0]->getSharedWith());
- }
-
- public function dataDeleteUser() {
- return [
- ['a', 'b', 'c', 'a', true],
- ['a', 'b', 'c', 'b', false],
- // The recipient is non local.
- ['a', 'b', 'c', 'c', false],
- ['a', 'b', 'c', 'd', false],
- ];
- }
-
- /**
- * @dataProvider dataDeleteUser
- *
- * @param string $owner The owner of the share (uid)
- * @param string $initiator The initiator of the share (uid)
- * @param string $recipient The recipient of the share (uid/gid/pass)
- * @param string $deletedUser The user that is deleted
- * @param bool $rowDeleted Is the row deleted in this setup
- */
- public function testDeleteUser($owner, $initiator, $recipient, $deletedUser, $rowDeleted) {
- $qb = $this->connection->getQueryBuilder();
- $qb->insert('share')
- ->setValue('share_type', $qb->createNamedParameter(IShare::TYPE_REMOTE))
- ->setValue('uid_owner', $qb->createNamedParameter($owner))
- ->setValue('uid_initiator', $qb->createNamedParameter($initiator))
- ->setValue('share_with', $qb->createNamedParameter($recipient))
- ->setValue('item_type', $qb->createNamedParameter('file'))
- ->setValue('item_source', $qb->createNamedParameter(42))
- ->setValue('file_source', $qb->createNamedParameter(42))
- ->execute();
-
- $id = $qb->getLastInsertId();
-
- $this->provider->userDeleted($deletedUser, IShare::TYPE_REMOTE);
-
- $qb = $this->connection->getQueryBuilder();
- $qb->select('*')
- ->from('share')
- ->where(
- $qb->expr()->eq('id', $qb->createNamedParameter($id))
- );
- $cursor = $qb->execute();
- $data = $cursor->fetchAll();
- $cursor->closeCursor();
-
- $this->assertCount($rowDeleted ? 0 : 1, $data);
- }
-
- /**
- * @dataProvider dataTestIsOutgoingServer2serverShareEnabled
- *
- * @param string $isEnabled
- * @param bool $expected
- */
- public function testIsOutgoingServer2serverShareEnabled($internalOnly, $isEnabled, $expected) {
- $this->gsConfig->expects($this->once())->method('onlyInternalFederation')
- ->willReturn($internalOnly);
- $this->config->expects($this->any())->method('getAppValue')
- ->with('files_sharing', 'outgoing_server2server_share_enabled', 'yes')
- ->willReturn($isEnabled);
-
- $this->assertSame($expected,
- $this->provider->isOutgoingServer2serverShareEnabled()
- );
- }
-
- public function dataTestIsOutgoingServer2serverShareEnabled() {
- return [
- [false, 'yes', true],
- [false, 'no', false],
- [true, 'yes', false],
- [true, 'no', false],
- ];
- }
-
- /**
- * @dataProvider dataTestIsIncomingServer2serverShareEnabled
- *
- * @param string $isEnabled
- * @param bool $expected
- */
- public function testIsIncomingServer2serverShareEnabled($onlyInternal, $isEnabled, $expected) {
- $this->gsConfig->expects($this->once())->method('onlyInternalFederation')
- ->willReturn($onlyInternal);
- $this->config->expects($this->any())->method('getAppValue')
- ->with('files_sharing', 'incoming_server2server_share_enabled', 'yes')
- ->willReturn($isEnabled);
-
- $this->assertSame($expected,
- $this->provider->isIncomingServer2serverShareEnabled()
- );
- }
-
- public function dataTestIsIncomingServer2serverShareEnabled() {
- return [
- [false, 'yes', true],
- [false, 'no', false],
- [true, 'yes', false],
- [true, 'no', false],
- ];
- }
-
- /**
- * @dataProvider dataTestIsLookupServerQueriesEnabled
- *
- * @param string $isEnabled
- * @param bool $expected
- */
- public function testIsLookupServerQueriesEnabled($gsEnabled, $isEnabled, $expected) {
- $this->gsConfig->expects($this->once())->method('isGlobalScaleEnabled')
- ->willReturn($gsEnabled);
- $this->config->expects($this->any())->method('getAppValue')
- ->with('files_sharing', 'lookupServerEnabled', 'yes')
- ->willReturn($isEnabled);
-
- $this->assertSame($expected,
- $this->provider->isLookupServerQueriesEnabled()
- );
- }
-
-
- public function dataTestIsLookupServerQueriesEnabled() {
- return [
- [false, 'yes', true],
- [false, 'no', false],
- [true, 'yes', true],
- [true, 'no', true],
- ];
- }
-
- /**
- * @dataProvider dataTestIsLookupServerUploadEnabled
- *
- * @param string $isEnabled
- * @param bool $expected
- */
- public function testIsLookupServerUploadEnabled($gsEnabled, $isEnabled, $expected) {
- $this->gsConfig->expects($this->once())->method('isGlobalScaleEnabled')
- ->willReturn($gsEnabled);
- $this->config->expects($this->any())->method('getAppValue')
- ->with('files_sharing', 'lookupServerUploadEnabled', 'yes')
- ->willReturn($isEnabled);
-
- $this->assertSame($expected,
- $this->provider->isLookupServerUploadEnabled()
- );
- }
-
- public function dataTestIsLookupServerUploadEnabled() {
- return [
- [false, 'yes', true],
- [false, 'no', false],
- [true, 'yes', false],
- [true, 'no', false],
- ];
- }
-
- public function testGetSharesInFolder() {
- $userManager = \OC::$server->getUserManager();
- $rootFolder = \OC::$server->getRootFolder();
-
- $u1 = $userManager->createUser('testFed', md5(time()));
- $u2 = $userManager->createUser('testFed2', md5(time()));
-
- $folder1 = $rootFolder->getUserFolder($u1->getUID())->newFolder('foo');
- $file1 = $folder1->newFile('bar1');
- $file2 = $folder1->newFile('bar2');
-
- $this->tokenHandler->method('generateToken')->willReturn('token');
- $this->notifications
- ->method('sendRemoteShare')
- ->willReturn(true);
-
- $this->addressHandler->method('generateRemoteURL')
- ->willReturn('remoteurl.com');
-
- $this->contactsManager->expects($this->any())
- ->method('search')
- ->willReturn([]);
-
- $share1 = $this->shareManager->newShare();
- $share1->setSharedWith('user@server.com')
- ->setSharedBy($u1->getUID())
- ->setShareOwner($u1->getUID())
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
- ->setShareType(IShare::TYPE_REMOTE)
- ->setNode($file1);
- $this->provider->create($share1);
-
- $share2 = $this->shareManager->newShare();
- $share2->setSharedWith('user@server.com')
- ->setSharedBy($u2->getUID())
- ->setShareOwner($u1->getUID())
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
- ->setShareType(IShare::TYPE_REMOTE)
- ->setNode($file2);
- $this->provider->create($share2);
-
- $result = $this->provider->getSharesInFolder($u1->getUID(), $folder1, false);
- $this->assertCount(1, $result);
- $this->assertCount(1, $result[$file1->getId()]);
-
- $result = $this->provider->getSharesInFolder($u1->getUID(), $folder1, true);
- $this->assertCount(2, $result);
- $this->assertCount(1, $result[$file1->getId()]);
- $this->assertCount(1, $result[$file2->getId()]);
-
- $u1->delete();
- $u2->delete();
- }
-
- public function testGetAccessList() {
- $userManager = \OC::$server->getUserManager();
- $rootFolder = \OC::$server->getRootFolder();
-
- $u1 = $userManager->createUser('testFed', md5(time()));
-
- $folder1 = $rootFolder->getUserFolder($u1->getUID())->newFolder('foo');
- $file1 = $folder1->newFile('bar1');
-
- $this->tokenHandler->expects($this->exactly(2))
- ->method('generateToken')
- ->willReturnOnConsecutiveCalls('token1', 'token2');
- $this->notifications->expects($this->atLeastOnce())
- ->method('sendRemoteShare')
- ->willReturn(true);
-
- $this->contactsManager->expects($this->any())
- ->method('search')
- ->willReturn([]);
-
- $result = $this->provider->getAccessList([$file1], true);
- $this->assertEquals(['remote' => []], $result);
-
- $result = $this->provider->getAccessList([$file1], false);
- $this->assertEquals(['remote' => false], $result);
-
- $this->addressHandler->method('generateRemoteURL')
- ->willReturn('remoteurl.com');
-
- $share1 = $this->shareManager->newShare();
- $share1->setSharedWith('user@server.com')
- ->setSharedBy($u1->getUID())
- ->setShareOwner($u1->getUID())
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
- ->setShareType(IShare::TYPE_REMOTE)
- ->setNode($file1);
- $this->provider->create($share1);
-
- $share2 = $this->shareManager->newShare();
- $share2->setSharedWith('foobar@localhost')
- ->setSharedBy($u1->getUID())
- ->setShareOwner($u1->getUID())
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
- ->setShareType(IShare::TYPE_REMOTE)
- ->setNode($file1);
- $this->provider->create($share2);
-
- $result = $this->provider->getAccessList([$file1], true);
- $this->assertEquals(['remote' => [
- 'user@server.com' => [
- 'token' => 'token1',
- 'node_id' => $file1->getId(),
- ],
- 'foobar@localhost' => [
- 'token' => 'token2',
- 'node_id' => $file1->getId(),
- ],
- ]], $result);
-
- $result = $this->provider->getAccessList([$file1], false);
- $this->assertEquals(['remote' => true], $result);
-
- $u1->delete();
- }
-}
+<?php
+
+/**
+ * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
+ */
+namespace OCA\FederatedFileSharing\Tests;
+
+use OC\Federation\CloudIdManager;
+use OCA\FederatedFileSharing\AddressHandler;
+use OCA\FederatedFileSharing\FederatedShareProvider;
+use OCA\FederatedFileSharing\Notifications;
+use OCA\FederatedFileSharing\TokenHandler;
+use OCP\Contacts\IManager as IContactsManager;
+use OCP\EventDispatcher\IEventDispatcher;
+use OCP\Federation\ICloudFederationProviderManager;
+use OCP\Federation\ICloudIdManager;
+use OCP\Files\File;
+use OCP\Files\IRootFolder;
+use OCP\ICacheFactory;
+use OCP\IConfig;
+use OCP\IDBConnection;
+use OCP\IL10N;
+use OCP\IURLGenerator;
+use OCP\IUserManager;
+use OCP\Share\IManager;
+use OCP\Share\IShare;
+use PHPUnit\Framework\MockObject\MockObject;
+use Psr\Log\LoggerInterface;
+
+/**
+ * Class FederatedShareProviderTest
+ *
+ * @package OCA\FederatedFileSharing\Tests
+ * @group DB
+ */
+class FederatedShareProviderTest extends \Test\TestCase {
+ /** @var IDBConnection */
+ protected $connection;
+ /** @var AddressHandler|MockObject */
+ protected $addressHandler;
+ /** @var Notifications|MockObject */
+ protected $notifications;
+ /** @var TokenHandler|MockObject */
+ protected $tokenHandler;
+ /** @var IL10N */
+ protected $l;
+ /** @var LoggerInterface */
+ protected $logger;
+ /** @var IRootFolder|MockObject */
+ protected $rootFolder;
+ /** @var IConfig|MockObject */
+ protected $config;
+ /** @var IUserManager|MockObject */
+ protected $userManager;
+ /** @var \OCP\GlobalScale\IConfig|MockObject */
+ protected $gsConfig;
+
+ /** @var IManager */
+ protected $shareManager;
+ /** @var FederatedShareProvider */
+ protected $provider;
+ /** @var IContactsManager|MockObject */
+ protected $contactsManager;
+
+ /** @var ICloudIdManager */
+ private $cloudIdManager;
+
+ /** @var MockObject|ICloudFederationProviderManager */
+ private $cloudFederationProviderManager;
+
+ protected function setUp(): void {
+ parent::setUp();
+
+ $this->connection = \OC::$server->getDatabaseConnection();
+ $this->notifications = $this->getMockBuilder(\OCA\FederatedFileSharing\Notifications::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $this->tokenHandler = $this->getMockBuilder(\OCA\FederatedFileSharing\TokenHandler::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $this->l = $this->getMockBuilder(IL10N::class)->getMock();
+ $this->l->method('t')
+ ->willReturnCallback(function ($text, $parameters = []) {
+ return vsprintf($text, $parameters);
+ });
+ $this->logger = $this->getMockBuilder(LoggerInterface::class)->getMock();
+ $this->rootFolder = $this->getMockBuilder(\OCP\Files\IRootFolder::class)->getMock();
+ $this->config = $this->getMockBuilder(IConfig::class)->getMock();
+ $this->userManager = $this->getMockBuilder(IUserManager::class)->getMock();
+ //$this->addressHandler = new AddressHandler(\OC::$server->getURLGenerator(), $this->l);
+ $this->addressHandler = $this->getMockBuilder(\OCA\FederatedFileSharing\AddressHandler::class)->disableOriginalConstructor()->getMock();
+ $this->contactsManager = $this->createMock(IContactsManager::class);
+ $this->cloudIdManager = new CloudIdManager(
+ $this->contactsManager,
+ $this->createMock(IURLGenerator::class),
+ $this->userManager,
+ $this->createMock(ICacheFactory::class),
+ $this->createMock(IEventDispatcher::class)
+ );
+ $this->gsConfig = $this->createMock(\OCP\GlobalScale\IConfig::class);
+
+ $this->userManager->expects($this->any())->method('userExists')->willReturn(true);
+
+ $this->cloudFederationProviderManager = $this->createMock(ICloudFederationProviderManager::class);
+
+ $this->provider = new FederatedShareProvider(
+ $this->connection,
+ $this->addressHandler,
+ $this->notifications,
+ $this->tokenHandler,
+ $this->l,
+ $this->rootFolder,
+ $this->config,
+ $this->userManager,
+ $this->cloudIdManager,
+ $this->gsConfig,
+ $this->cloudFederationProviderManager,
+ $this->logger,
+ );
+
+ $this->shareManager = \OC::$server->getShareManager();
+ }
+
+ protected function tearDown(): void {
+ $this->connection->getQueryBuilder()->delete('share')->execute();
+
+ parent::tearDown();
+ }
+
+ public function dataTestCreate() {
+ return [
+ [null, null],
+ [new \DateTime('2020-03-01T01:02:03'), '2020-03-01 01:02:03'],
+ ];
+ }
+
+ /**
+ * @dataProvider dataTestCreate
+ */
+ public function testCreate($expirationDate, $expectedDataDate): void {
+ $share = $this->shareManager->newShare();
+
+ /** @var File|MockObject $node */
+ $node = $this->getMockBuilder(File::class)->getMock();
+ $node->method('getId')->willReturn(42);
+ $node->method('getName')->willReturn('myFile');
+
+ $share->setSharedWith('user@server.com')
+ ->setSharedBy('sharedBy')
+ ->setShareOwner('shareOwner')
+ ->setPermissions(19)
+ ->setShareType(IShare::TYPE_REMOTE)
+ ->setExpirationDate($expirationDate)
+ ->setNode($node);
+
+ $this->tokenHandler->method('generateToken')->willReturn('token');
+
+ $this->addressHandler->expects($this->any())->method('generateRemoteURL')
+ ->willReturn('http://localhost/');
+ $this->addressHandler->expects($this->any())->method('splitUserRemote')
+ ->willReturn(['user', 'server.com']);
+
+ $this->notifications->expects($this->once())
+ ->method('sendRemoteShare')
+ ->with(
+ $this->equalTo('token'),
+ $this->equalTo('user@server.com'),
+ $this->equalTo('myFile'),
+ $this->anything(),
+ 'shareOwner',
+ 'shareOwner@http://localhost',
+ 'sharedBy',
+ 'sharedBy@http://localhost'
+ )
+ ->willReturn(true);
+
+ $this->rootFolder->expects($this->never())->method($this->anything());
+
+ $this->contactsManager->expects($this->any())
+ ->method('search')
+ ->willReturn([]);
+
+ $share = $this->provider->create($share);
+
+ $qb = $this->connection->getQueryBuilder();
+ $stmt = $qb->select('*')
+ ->from('share')
+ ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
+ ->execute();
+
+ $data = $stmt->fetch();
+ $stmt->closeCursor();
+
+ $expected = [
+ 'share_type' => IShare::TYPE_REMOTE,
+ 'share_with' => 'user@server.com',
+ 'uid_owner' => 'shareOwner',
+ 'uid_initiator' => 'sharedBy',
+ 'item_type' => 'file',
+ 'item_source' => 42,
+ 'file_source' => 42,
+ 'permissions' => 19,
+ 'accepted' => 0,
+ 'token' => 'token',
+ 'expiration' => $expectedDataDate,
+ ];
+ foreach (array_keys($expected) as $key) {
+ $this->assertEquals($expected[$key], $data[$key], "Assert that value for key '$key' is the same");
+ }
+
+ $this->assertEquals($data['id'], $share->getId());
+ $this->assertEquals(IShare::TYPE_REMOTE, $share->getShareType());
+ $this->assertEquals('user@server.com', $share->getSharedWith());
+ $this->assertEquals('sharedBy', $share->getSharedBy());
+ $this->assertEquals('shareOwner', $share->getShareOwner());
+ $this->assertEquals('file', $share->getNodeType());
+ $this->assertEquals(42, $share->getNodeId());
+ $this->assertEquals(19, $share->getPermissions());
+ $this->assertEquals('token', $share->getToken());
+ $this->assertEquals($expirationDate, $share->getExpirationDate());
+ }
+
+ public function testCreateCouldNotFindServer(): void {
+ $share = $this->shareManager->newShare();
+
+ $node = $this->getMockBuilder(File::class)->getMock();
+ $node->method('getId')->willReturn(42);
+ $node->method('getName')->willReturn('myFile');
+
+ $share->setSharedWith('user@server.com')
+ ->setSharedBy('sharedBy')
+ ->setShareOwner('shareOwner')
+ ->setPermissions(19)
+ ->setShareType(IShare::TYPE_REMOTE)
+ ->setNode($node);
+
+ $this->tokenHandler->method('generateToken')->willReturn('token');
+
+ $this->addressHandler->expects($this->any())->method('generateRemoteURL')
+ ->willReturn('http://localhost/');
+ $this->addressHandler->expects($this->any())->method('splitUserRemote')
+ ->willReturn(['user', 'server.com']);
+
+ $this->notifications->expects($this->once())
+ ->method('sendRemoteShare')
+ ->with(
+ $this->equalTo('token'),
+ $this->equalTo('user@server.com'),
+ $this->equalTo('myFile'),
+ $this->anything(),
+ 'shareOwner',
+ 'shareOwner@http://localhost',
+ 'sharedBy',
+ 'sharedBy@http://localhost'
+ )->willReturn(false);
+
+ $this->rootFolder->method('getById')
+ ->with('42')
+ ->willReturn([$node]);
+
+ $this->contactsManager->expects($this->any())
+ ->method('search')
+ ->willReturn([]);
+
+ try {
+ $share = $this->provider->create($share);
+ $this->fail();
+ } catch (\Exception $e) {
+ $this->assertEquals('Sharing myFile failed, could not find user@server.com, maybe the server is currently unreachable or uses a self-signed certificate.', $e->getMessage());
+ }
+
+ $qb = $this->connection->getQueryBuilder();
+ $stmt = $qb->select('*')
+ ->from('share')
+ ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
+ ->execute();
+
+ $data = $stmt->fetch();
+ $stmt->closeCursor();
+
+ $this->assertFalse($data);
+ }
+
+ public function testCreateException(): void {
+ $share = $this->shareManager->newShare();
+
+ $node = $this->getMockBuilder(File::class)->getMock();
+ $node->method('getId')->willReturn(42);
+ $node->method('getName')->willReturn('myFile');
+
+ $share->setSharedWith('user@server.com')
+ ->setSharedBy('sharedBy')
+ ->setShareOwner('shareOwner')
+ ->setPermissions(19)
+ ->setShareType(IShare::TYPE_REMOTE)
+ ->setNode($node);
+
+ $this->tokenHandler->method('generateToken')->willReturn('token');
+
+ $this->addressHandler->expects($this->any())->method('generateRemoteURL')
+ ->willReturn('http://localhost/');
+ $this->addressHandler->expects($this->any())->method('splitUserRemote')
+ ->willReturn(['user', 'server.com']);
+
+ $this->notifications->expects($this->once())
+ ->method('sendRemoteShare')
+ ->with(
+ $this->equalTo('token'),
+ $this->equalTo('user@server.com'),
+ $this->equalTo('myFile'),
+ $this->anything(),
+ 'shareOwner',
+ 'shareOwner@http://localhost',
+ 'sharedBy',
+ 'sharedBy@http://localhost'
+ )->willThrowException(new \Exception('dummy'));
+
+ $this->rootFolder->method('getById')
+ ->with('42')
+ ->willReturn([$node]);
+
+ $this->contactsManager->expects($this->any())
+ ->method('search')
+ ->willReturn([]);
+
+ try {
+ $share = $this->provider->create($share);
+ $this->fail();
+ } catch (\Exception $e) {
+ $this->assertEquals('Sharing myFile failed, could not find user@server.com, maybe the server is currently unreachable or uses a self-signed certificate.', $e->getMessage());
+ }
+
+ $qb = $this->connection->getQueryBuilder();
+ $stmt = $qb->select('*')
+ ->from('share')
+ ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
+ ->execute();
+
+ $data = $stmt->fetch();
+ $stmt->closeCursor();
+
+ $this->assertFalse($data);
+ }
+
+ public function testCreateShareWithSelf(): void {
+ $share = $this->shareManager->newShare();
+
+ $node = $this->getMockBuilder(File::class)->getMock();
+ $node->method('getId')->willReturn(42);
+ $node->method('getName')->willReturn('myFile');
+
+ $this->addressHandler->expects($this->any())->method('compareAddresses')
+ ->willReturn(true);
+
+ $shareWith = 'sharedBy@localhost';
+
+ $share->setSharedWith($shareWith)
+ ->setSharedBy('sharedBy')
+ ->setShareOwner('shareOwner')
+ ->setPermissions(19)
+ ->setNode($node);
+
+ $this->contactsManager->expects($this->any())
+ ->method('search')
+ ->willReturn([]);
+
+ $this->rootFolder->expects($this->never())->method($this->anything());
+
+ try {
+ $share = $this->provider->create($share);
+ $this->fail();
+ } catch (\Exception $e) {
+ $this->assertEquals('Not allowed to create a federated share to the same account', $e->getMessage());
+ }
+
+ $qb = $this->connection->getQueryBuilder();
+ $stmt = $qb->select('*')
+ ->from('share')
+ ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
+ ->execute();
+
+ $data = $stmt->fetch();
+ $stmt->closeCursor();
+
+ $this->assertFalse($data);
+ }
+
+ public function testCreateAlreadyShared(): void {
+ $share = $this->shareManager->newShare();
+
+ $node = $this->getMockBuilder(File::class)->getMock();
+ $node->method('getId')->willReturn(42);
+ $node->method('getName')->willReturn('myFile');
+
+
+ $this->addressHandler->expects($this->any())->method('splitUserRemote')
+ ->willReturn(['user', 'server.com']);
+
+ $share->setSharedWith('user@server.com')
+ ->setSharedBy('sharedBy')
+ ->setShareOwner('shareOwner')
+ ->setPermissions(19)
+ ->setShareType(IShare::TYPE_REMOTE)
+ ->setNode($node);
+
+ $this->tokenHandler->method('generateToken')->willReturn('token');
+
+ $this->addressHandler->expects($this->any())->method('generateRemoteURL')
+ ->willReturn('http://localhost/');
+
+ $this->notifications->expects($this->once())
+ ->method('sendRemoteShare')
+ ->with(
+ $this->equalTo('token'),
+ $this->equalTo('user@server.com'),
+ $this->equalTo('myFile'),
+ $this->anything(),
+ 'shareOwner',
+ 'shareOwner@http://localhost',
+ 'sharedBy',
+ 'sharedBy@http://localhost'
+ )->willReturn(true);
+
+ $this->rootFolder->expects($this->never())->method($this->anything());
+
+ $this->contactsManager->expects($this->any())
+ ->method('search')
+ ->willReturn([]);
+
+ $this->provider->create($share);
+
+ try {
+ $this->provider->create($share);
+ } catch (\Exception $e) {
+ $this->assertEquals('Sharing myFile failed, because this item is already shared with the account user@server.com', $e->getMessage());
+ }
+ }
+
+ /**
+ * @dataProvider dataTestUpdate
+ */
+ public function testUpdate($owner, $sharedBy, $expirationDate): void {
+ $this->provider = $this->getMockBuilder(\OCA\FederatedFileSharing\FederatedShareProvider::class)
+ ->setConstructorArgs(
+ [
+ $this->connection,
+ $this->addressHandler,
+ $this->notifications,
+ $this->tokenHandler,
+ $this->l,
+ $this->rootFolder,
+ $this->config,
+ $this->userManager,
+ $this->cloudIdManager,
+ $this->gsConfig,
+ $this->cloudFederationProviderManager,
+ $this->logger,
+ ]
+ )->setMethods(['sendPermissionUpdate'])->getMock();
+
+ $share = $this->shareManager->newShare();
+
+ $node = $this->getMockBuilder(File::class)->getMock();
+ $node->method('getId')->willReturn(42);
+ $node->method('getName')->willReturn('myFile');
+
+ $this->addressHandler->expects($this->any())->method('splitUserRemote')
+ ->willReturn(['user', 'server.com']);
+
+ $share->setSharedWith('user@server.com')
+ ->setSharedBy($sharedBy)
+ ->setShareOwner($owner)
+ ->setPermissions(19)
+ ->setShareType(IShare::TYPE_REMOTE)
+ ->setExpirationDate(new \DateTime('2019-02-01T01:02:03'))
+ ->setNode($node);
+
+ $this->tokenHandler->method('generateToken')->willReturn('token');
+ $this->addressHandler->expects($this->any())->method('generateRemoteURL')
+ ->willReturn('http://localhost/');
+
+ $this->notifications->expects($this->once())
+ ->method('sendRemoteShare')
+ ->with(
+ $this->equalTo('token'),
+ $this->equalTo('user@server.com'),
+ $this->equalTo('myFile'),
+ $this->anything(),
+ $owner,
+ $owner . '@http://localhost',
+ $sharedBy,
+ $sharedBy . '@http://localhost'
+ )->willReturn(true);
+
+ if ($owner === $sharedBy) {
+ $this->provider->expects($this->never())->method('sendPermissionUpdate');
+ } else {
+ $this->provider->expects($this->once())->method('sendPermissionUpdate');
+ }
+
+ $this->rootFolder->expects($this->never())->method($this->anything());
+
+ $this->contactsManager->expects($this->any())
+ ->method('search')
+ ->willReturn([]);
+
+ $share = $this->provider->create($share);
+
+ $share->setPermissions(1);
+ $share->setExpirationDate($expirationDate);
+ $this->provider->update($share);
+
+ $share = $this->provider->getShareById($share->getId());
+
+ $this->assertEquals(1, $share->getPermissions());
+ $this->assertEquals($expirationDate, $share->getExpirationDate());
+ }
+
+ public function dataTestUpdate() {
+ return [
+ ['sharedBy', 'shareOwner', new \DateTime('2020-03-01T01:02:03')],
+ ['shareOwner', 'shareOwner', null],
+ ];
+ }
+
+ public function testGetSharedBy(): void {
+ $node = $this->getMockBuilder(File::class)->getMock();
+ $node->method('getId')->willReturn(42);
+ $node->method('getName')->willReturn('myFile');
+
+ $this->addressHandler->expects($this->never())->method('splitUserRemote');
+
+ $this->addressHandler->method('generateRemoteURL')
+ ->willReturn('remoteurl.com');
+
+ $this->tokenHandler->method('generateToken')->willReturn('token');
+ $this->notifications
+ ->method('sendRemoteShare')
+ ->willReturn(true);
+
+ $this->rootFolder->expects($this->never())->method($this->anything());
+
+ $this->contactsManager->expects($this->any())
+ ->method('search')
+ ->willReturn([]);
+
+ $share = $this->shareManager->newShare();
+ $share->setSharedWith('user@server.com')
+ ->setSharedBy('sharedBy')
+ ->setShareOwner('shareOwner')
+ ->setPermissions(19)
+ ->setShareType(IShare::TYPE_REMOTE)
+ ->setNode($node);
+ $this->provider->create($share);
+
+ $share2 = $this->shareManager->newShare();
+ $share2->setSharedWith('user2@server.com')
+ ->setSharedBy('sharedBy2')
+ ->setShareOwner('shareOwner')
+ ->setPermissions(19)
+ ->setShareType(IShare::TYPE_REMOTE)
+ ->setNode($node);
+ $this->provider->create($share2);
+
+ $shares = $this->provider->getSharesBy('sharedBy', IShare::TYPE_REMOTE, null, false, -1, 0);
+
+ $this->assertCount(1, $shares);
+ $this->assertEquals('user@server.com', $shares[0]->getSharedWith());
+ $this->assertEquals('sharedBy', $shares[0]->getSharedBy());
+ }
+
+ public function testGetSharedByWithNode(): void {
+ $node = $this->getMockBuilder(File::class)->getMock();
+ $node->method('getId')->willReturn(42);
+ $node->method('getName')->willReturn('myFile');
+
+ $this->tokenHandler->method('generateToken')->willReturn('token');
+ $this->notifications
+ ->method('sendRemoteShare')
+ ->willReturn(true);
+
+ $this->rootFolder->expects($this->never())->method($this->anything());
+
+ $this->addressHandler->method('generateRemoteURL')
+ ->willReturn('remoteurl.com');
+
+ $this->contactsManager->expects($this->any())
+ ->method('search')
+ ->willReturn([]);
+
+ $share = $this->shareManager->newShare();
+ $share->setSharedWith('user@server.com')
+ ->setSharedBy('sharedBy')
+ ->setShareOwner('shareOwner')
+ ->setPermissions(19)
+ ->setShareType(IShare::TYPE_REMOTE)
+ ->setNode($node);
+ $this->provider->create($share);
+
+ $node2 = $this->getMockBuilder(File::class)->getMock();
+ $node2->method('getId')->willReturn(43);
+ $node2->method('getName')->willReturn('myOtherFile');
+
+ $share2 = $this->shareManager->newShare();
+ $share2->setSharedWith('user@server.com')
+ ->setSharedBy('sharedBy')
+ ->setShareOwner('shareOwner')
+ ->setPermissions(19)
+ ->setShareType(IShare::TYPE_REMOTE)
+ ->setNode($node2);
+ $this->provider->create($share2);
+
+ $shares = $this->provider->getSharesBy('sharedBy', IShare::TYPE_REMOTE, $node2, false, -1, 0);
+
+ $this->assertCount(1, $shares);
+ $this->assertEquals(43, $shares[0]->getNodeId());
+ }
+
+ public function testGetSharedByWithReshares(): void {
+ $node = $this->getMockBuilder(File::class)->getMock();
+ $node->method('getId')->willReturn(42);
+ $node->method('getName')->willReturn('myFile');
+
+ $this->tokenHandler->method('generateToken')->willReturn('token');
+ $this->notifications
+ ->method('sendRemoteShare')
+ ->willReturn(true);
+
+ $this->rootFolder->expects($this->never())->method($this->anything());
+
+ $this->addressHandler->method('generateRemoteURL')
+ ->willReturn('remoteurl.com');
+
+ $this->contactsManager->expects($this->any())
+ ->method('search')
+ ->willReturn([]);
+
+ $share = $this->shareManager->newShare();
+ $share->setSharedWith('user@server.com')
+ ->setSharedBy('shareOwner')
+ ->setShareOwner('shareOwner')
+ ->setPermissions(19)
+ ->setShareType(IShare::TYPE_REMOTE)
+ ->setNode($node);
+ $this->provider->create($share);
+
+ $share2 = $this->shareManager->newShare();
+ $share2->setSharedWith('user2@server.com')
+ ->setSharedBy('sharedBy')
+ ->setShareOwner('shareOwner')
+ ->setPermissions(19)
+ ->setShareType(IShare::TYPE_REMOTE)
+ ->setNode($node);
+ $this->provider->create($share2);
+
+ $shares = $this->provider->getSharesBy('shareOwner', IShare::TYPE_REMOTE, null, true, -1, 0);
+
+ $this->assertCount(2, $shares);
+ }
+
+ public function testGetSharedByWithLimit(): void {
+ $node = $this->getMockBuilder(File::class)->getMock();
+ $node->method('getId')->willReturn(42);
+ $node->method('getName')->willReturn('myFile');
+
+ $this->addressHandler->expects($this->any())->method('splitUserRemote')
+ ->willReturnCallback(function ($uid) {
+ if ($uid === 'user@server.com') {
+ return ['user', 'server.com'];
+ }
+ return ['user2', 'server.com'];
+ });
+
+ $this->tokenHandler->method('generateToken')->willReturn('token');
+ $this->notifications
+ ->method('sendRemoteShare')
+ ->willReturn(true);
+
+ $this->rootFolder->expects($this->never())->method($this->anything());
+
+ $this->addressHandler->method('generateRemoteURL')
+ ->willReturn('remoteurl.com');
+
+ $this->contactsManager->expects($this->any())
+ ->method('search')
+ ->willReturn([]);
+
+ $share = $this->shareManager->newShare();
+ $share->setSharedWith('user@server.com')
+ ->setSharedBy('sharedBy')
+ ->setShareOwner('shareOwner')
+ ->setPermissions(19)
+ ->setShareType(IShare::TYPE_REMOTE)
+ ->setNode($node);
+ $this->provider->create($share);
+
+ $share2 = $this->shareManager->newShare();
+ $share2->setSharedWith('user2@server.com')
+ ->setSharedBy('sharedBy')
+ ->setShareOwner('shareOwner')
+ ->setPermissions(19)
+ ->setShareType(IShare::TYPE_REMOTE)
+ ->setNode($node);
+ $this->provider->create($share2);
+
+ $shares = $this->provider->getSharesBy('shareOwner', IShare::TYPE_REMOTE, null, true, 1, 1);
+
+ $this->assertCount(1, $shares);
+ $this->assertEquals('user2@server.com', $shares[0]->getSharedWith());
+ }
+
+ public function dataDeleteUser() {
+ return [
+ ['a', 'b', 'c', 'a', true],
+ ['a', 'b', 'c', 'b', false],
+ // The recipient is non local.
+ ['a', 'b', 'c', 'c', false],
+ ['a', 'b', 'c', 'd', false],
+ ];
+ }
+
+ /**
+ * @dataProvider dataDeleteUser
+ *
+ * @param string $owner The owner of the share (uid)
+ * @param string $initiator The initiator of the share (uid)
+ * @param string $recipient The recipient of the share (uid/gid/pass)
+ * @param string $deletedUser The user that is deleted
+ * @param bool $rowDeleted Is the row deleted in this setup
+ */
+ public function testDeleteUser($owner, $initiator, $recipient, $deletedUser, $rowDeleted): void {
+ $qb = $this->connection->getQueryBuilder();
+ $qb->insert('share')
+ ->setValue('share_type', $qb->createNamedParameter(IShare::TYPE_REMOTE))
+ ->setValue('uid_owner', $qb->createNamedParameter($owner))
+ ->setValue('uid_initiator', $qb->createNamedParameter($initiator))
+ ->setValue('share_with', $qb->createNamedParameter($recipient))
+ ->setValue('item_type', $qb->createNamedParameter('file'))
+ ->setValue('item_source', $qb->createNamedParameter(42))
+ ->setValue('file_source', $qb->createNamedParameter(42))
+ ->execute();
+
+ $id = $qb->getLastInsertId();
+
+ $this->provider->userDeleted($deletedUser, IShare::TYPE_REMOTE);
+
+ $qb = $this->connection->getQueryBuilder();
+ $qb->select('*')
+ ->from('share')
+ ->where(
+ $qb->expr()->eq('id', $qb->createNamedParameter($id))
+ );
+ $cursor = $qb->execute();
+ $data = $cursor->fetchAll();
+ $cursor->closeCursor();
+
+ $this->assertCount($rowDeleted ? 0 : 1, $data);
+ }
+
+ /**
+ * @dataProvider dataTestIsOutgoingServer2serverShareEnabled
+ *
+ * @param string $isEnabled
+ * @param bool $expected
+ */
+ public function testIsOutgoingServer2serverShareEnabled($internalOnly, $isEnabled, $expected): void {
+ $this->gsConfig->expects($this->once())->method('onlyInternalFederation')
+ ->willReturn($internalOnly);
+ $this->config->expects($this->any())->method('getAppValue')
+ ->with('files_sharing', 'outgoing_server2server_share_enabled', 'yes')
+ ->willReturn($isEnabled);
+
+ $this->assertSame($expected,
+ $this->provider->isOutgoingServer2serverShareEnabled()
+ );
+ }
+
+ public function dataTestIsOutgoingServer2serverShareEnabled() {
+ return [
+ [false, 'yes', true],
+ [false, 'no', false],
+ [true, 'yes', false],
+ [true, 'no', false],
+ ];
+ }
+
+ /**
+ * @dataProvider dataTestIsIncomingServer2serverShareEnabled
+ *
+ * @param string $isEnabled
+ * @param bool $expected
+ */
+ public function testIsIncomingServer2serverShareEnabled($onlyInternal, $isEnabled, $expected): void {
+ $this->gsConfig->expects($this->once())->method('onlyInternalFederation')
+ ->willReturn($onlyInternal);
+ $this->config->expects($this->any())->method('getAppValue')
+ ->with('files_sharing', 'incoming_server2server_share_enabled', 'yes')
+ ->willReturn($isEnabled);
+
+ $this->assertSame($expected,
+ $this->provider->isIncomingServer2serverShareEnabled()
+ );
+ }
+
+ public function dataTestIsIncomingServer2serverShareEnabled() {
+ return [
+ [false, 'yes', true],
+ [false, 'no', false],
+ [true, 'yes', false],
+ [true, 'no', false],
+ ];
+ }
+
+ /**
+ * @dataProvider dataTestIsLookupServerQueriesEnabled
+ *
+ * @param string $isEnabled
+ * @param bool $expected
+ */
+ public function testIsLookupServerQueriesEnabled($gsEnabled, $isEnabled, $expected): void {
+ $this->gsConfig->expects($this->once())->method('isGlobalScaleEnabled')
+ ->willReturn($gsEnabled);
+ $this->config->expects($this->any())->method('getAppValue')
+ ->with('files_sharing', 'lookupServerEnabled', 'yes')
+ ->willReturn($isEnabled);
+
+ $this->assertSame($expected,
+ $this->provider->isLookupServerQueriesEnabled()
+ );
+ }
+
+
+ public function dataTestIsLookupServerQueriesEnabled() {
+ return [
+ [false, 'yes', true],
+ [false, 'no', false],
+ [true, 'yes', true],
+ [true, 'no', true],
+ ];
+ }
+
+ /**
+ * @dataProvider dataTestIsLookupServerUploadEnabled
+ *
+ * @param string $isEnabled
+ * @param bool $expected
+ */
+ public function testIsLookupServerUploadEnabled($gsEnabled, $isEnabled, $expected): void {
+ $this->gsConfig->expects($this->once())->method('isGlobalScaleEnabled')
+ ->willReturn($gsEnabled);
+ $this->config->expects($this->any())->method('getAppValue')
+ ->with('files_sharing', 'lookupServerUploadEnabled', 'yes')
+ ->willReturn($isEnabled);
+
+ $this->assertSame($expected,
+ $this->provider->isLookupServerUploadEnabled()
+ );
+ }
+
+ public function dataTestIsLookupServerUploadEnabled() {
+ return [
+ [false, 'yes', true],
+ [false, 'no', false],
+ [true, 'yes', false],
+ [true, 'no', false],
+ ];
+ }
+
+ public function testGetSharesInFolder(): void {
+ $userManager = \OC::$server->getUserManager();
+ $rootFolder = \OC::$server->getRootFolder();
+
+ $u1 = $userManager->createUser('testFed', md5(time()));
+ $u2 = $userManager->createUser('testFed2', md5(time()));
+
+ $folder1 = $rootFolder->getUserFolder($u1->getUID())->newFolder('foo');
+ $file1 = $folder1->newFile('bar1');
+ $file2 = $folder1->newFile('bar2');
+
+ $this->tokenHandler->method('generateToken')->willReturn('token');
+ $this->notifications
+ ->method('sendRemoteShare')
+ ->willReturn(true);
+
+ $this->addressHandler->method('generateRemoteURL')
+ ->willReturn('remoteurl.com');
+
+ $this->contactsManager->expects($this->any())
+ ->method('search')
+ ->willReturn([]);
+
+ $share1 = $this->shareManager->newShare();
+ $share1->setSharedWith('user@server.com')
+ ->setSharedBy($u1->getUID())
+ ->setShareOwner($u1->getUID())
+ ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setShareType(IShare::TYPE_REMOTE)
+ ->setNode($file1);
+ $this->provider->create($share1);
+
+ $share2 = $this->shareManager->newShare();
+ $share2->setSharedWith('user@server.com')
+ ->setSharedBy($u2->getUID())
+ ->setShareOwner($u1->getUID())
+ ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setShareType(IShare::TYPE_REMOTE)
+ ->setNode($file2);
+ $this->provider->create($share2);
+
+ $result = $this->provider->getSharesInFolder($u1->getUID(), $folder1, false);
+ $this->assertCount(1, $result);
+ $this->assertCount(1, $result[$file1->getId()]);
+
+ $result = $this->provider->getSharesInFolder($u1->getUID(), $folder1, true);
+ $this->assertCount(2, $result);
+ $this->assertCount(1, $result[$file1->getId()]);
+ $this->assertCount(1, $result[$file2->getId()]);
+
+ $u1->delete();
+ $u2->delete();
+ }
+
+ public function testGetAccessList(): void {
+ $userManager = \OC::$server->getUserManager();
+ $rootFolder = \OC::$server->getRootFolder();
+
+ $u1 = $userManager->createUser('testFed', md5(time()));
+
+ $folder1 = $rootFolder->getUserFolder($u1->getUID())->newFolder('foo');
+ $file1 = $folder1->newFile('bar1');
+
+ $this->tokenHandler->expects($this->exactly(2))
+ ->method('generateToken')
+ ->willReturnOnConsecutiveCalls('token1', 'token2');
+ $this->notifications->expects($this->atLeastOnce())
+ ->method('sendRemoteShare')
+ ->willReturn(true);
+
+ $this->contactsManager->expects($this->any())
+ ->method('search')
+ ->willReturn([]);
+
+ $result = $this->provider->getAccessList([$file1], true);
+ $this->assertEquals(['remote' => []], $result);
+
+ $result = $this->provider->getAccessList([$file1], false);
+ $this->assertEquals(['remote' => false], $result);
+
+ $this->addressHandler->method('generateRemoteURL')
+ ->willReturn('remoteurl.com');
+
+ $share1 = $this->shareManager->newShare();
+ $share1->setSharedWith('user@server.com')
+ ->setSharedBy($u1->getUID())
+ ->setShareOwner($u1->getUID())
+ ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setShareType(IShare::TYPE_REMOTE)
+ ->setNode($file1);
+ $this->provider->create($share1);
+
+ $share2 = $this->shareManager->newShare();
+ $share2->setSharedWith('foobar@localhost')
+ ->setSharedBy($u1->getUID())
+ ->setShareOwner($u1->getUID())
+ ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setShareType(IShare::TYPE_REMOTE)
+ ->setNode($file1);
+ $this->provider->create($share2);
+
+ $result = $this->provider->getAccessList([$file1], true);
+ $this->assertEquals(['remote' => [
+ 'user@server.com' => [
+ 'token' => 'token1',
+ 'node_id' => $file1->getId(),
+ ],
+ 'foobar@localhost' => [
+ 'token' => 'token2',
+ 'node_id' => $file1->getId(),
+ ],
+ ]], $result);
+
+ $result = $this->provider->getAccessList([$file1], false);
+ $this->assertEquals(['remote' => true], $result);
+
+ $u1->delete();
+ }
+}
diff --git a/apps/federatedfilesharing/tests/NotificationsTest.php b/apps/federatedfilesharing/tests/NotificationsTest.php
index 5f7b07d34ff..24fec06bf72 100644
--- a/apps/federatedfilesharing/tests/NotificationsTest.php
+++ b/apps/federatedfilesharing/tests/NotificationsTest.php
@@ -102,7 +102,7 @@ class NotificationsTest extends \Test\TestCase {
* @param array $httpRequestResult
* @param bool $expected
*/
- public function testSendUpdateToRemote($try, $httpRequestResult, $expected) {
+ public function testSendUpdateToRemote($try, $httpRequestResult, $expected): void {
$remote = 'http://remote';
$id = 42;
$timestamp = 63576;
diff --git a/apps/federatedfilesharing/tests/Settings/AdminTest.php b/apps/federatedfilesharing/tests/Settings/AdminTest.php
index 29f15b0199d..031d19c2cb8 100644
--- a/apps/federatedfilesharing/tests/Settings/AdminTest.php
+++ b/apps/federatedfilesharing/tests/Settings/AdminTest.php
@@ -58,7 +58,7 @@ class AdminTest extends TestCase {
* @dataProvider sharingStateProvider
* @param bool $state
*/
- public function testGetForm($state) {
+ public function testGetForm($state): void {
$this->federatedShareProvider
->expects($this->once())
->method('isOutgoingServer2serverShareEnabled')
@@ -112,11 +112,11 @@ class AdminTest extends TestCase {
$this->assertEquals($expected, $this->admin->getForm());
}
- public function testGetSection() {
+ public function testGetSection(): void {
$this->assertSame('sharing', $this->admin->getSection());
}
- public function testGetPriority() {
+ public function testGetPriority(): void {
$this->assertSame(20, $this->admin->getPriority());
}
}
diff --git a/apps/federatedfilesharing/tests/TokenHandlerTest.php b/apps/federatedfilesharing/tests/TokenHandlerTest.php
index f6b4a2fa9e9..9ed20779857 100644
--- a/apps/federatedfilesharing/tests/TokenHandlerTest.php
+++ b/apps/federatedfilesharing/tests/TokenHandlerTest.php
@@ -29,7 +29,7 @@ class TokenHandlerTest extends \Test\TestCase {
$this->tokenHandler = new TokenHandler($this->secureRandom);
}
- public function testGenerateToken() {
+ public function testGenerateToken(): void {
$this->secureRandom->expects($this->once())->method('generate')
->with(
$this->expectedTokenLength,
diff --git a/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php b/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php
index bc3e971fad2..4fcb579d6f9 100644
--- a/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php
+++ b/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php
@@ -152,7 +152,7 @@ class GetSharedSecretTest extends TestCase {
*
* @param int $statusCode
*/
- public function testRun($statusCode) {
+ public function testRun($statusCode): void {
$target = 'targetURL';
$source = 'sourceURL';
$token = 'token';
@@ -210,7 +210,7 @@ class GetSharedSecretTest extends TestCase {
];
}
- public function testRunExpired() {
+ public function testRunExpired(): void {
$target = 'targetURL';
$source = 'sourceURL';
$token = 'token';
@@ -240,7 +240,7 @@ class GetSharedSecretTest extends TestCase {
$this->invokePrivate($this->getSharedSecret, 'run', [$argument]);
}
- public function testRunConnectionError() {
+ public function testRunConnectionError(): void {
$target = 'targetURL';
$source = 'sourceURL';
$token = 'token';
diff --git a/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php b/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php
index fca00a05b5a..64c7ae3cdd4 100644
--- a/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php
+++ b/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php
@@ -87,7 +87,7 @@ class RequestSharedSecretTest extends TestCase {
* @param bool $isTrustedServer
* @param bool $retainBackgroundJob
*/
- public function testStart($isTrustedServer, $retainBackgroundJob) {
+ public function testStart($isTrustedServer, $retainBackgroundJob): void {
/** @var RequestSharedSecret |MockObject $requestSharedSecret */
$requestSharedSecret = $this->getMockBuilder(\OCA\Federation\BackgroundJob\RequestSharedSecret::class)
->setConstructorArgs(
@@ -196,7 +196,7 @@ class RequestSharedSecretTest extends TestCase {
];
}
- public function testRunExpired() {
+ public function testRunExpired(): void {
$target = 'targetURL';
$source = 'sourceURL';
$token = 'token';
@@ -226,7 +226,7 @@ class RequestSharedSecretTest extends TestCase {
$this->invokePrivate($this->requestSharedSecret, 'run', [$argument]);
}
- public function testRunConnectionError() {
+ public function testRunConnectionError(): void {
$target = 'targetURL';
$source = 'sourceURL';
$token = 'token';
diff --git a/apps/federation/tests/DAV/FedAuthTest.php b/apps/federation/tests/DAV/FedAuthTest.php
index f05863b97cc..aa92b0112d0 100644
--- a/apps/federation/tests/DAV/FedAuthTest.php
+++ b/apps/federation/tests/DAV/FedAuthTest.php
@@ -20,7 +20,7 @@ class FedAuthTest extends TestCase {
* @param string $user
* @param string $password
*/
- public function testFedAuth($expected, $user, $password) {
+ public function testFedAuth($expected, $user, $password): void {
/** @var DbHandler | \PHPUnit\Framework\MockObject\MockObject $db */
$db = $this->getMockBuilder(\OCA\Federation\DbHandler::class)->disableOriginalConstructor()->getMock();
$db->method('auth')->willReturn(true);
diff --git a/apps/federation/tests/DbHandlerTest.php b/apps/federation/tests/DbHandlerTest.php
index df8cd36d8a8..aabbf1472e7 100644
--- a/apps/federation/tests/DbHandlerTest.php
+++ b/apps/federation/tests/DbHandlerTest.php
@@ -62,7 +62,7 @@ class DbHandlerTest extends TestCase {
* @param string $expectedUrl the url we expect to be written to the db
* @param string $expectedHash the hash value we expect to be written to the db
*/
- public function testAddServer($url, $expectedUrl, $expectedHash) {
+ public function testAddServer($url, $expectedUrl, $expectedHash): void {
$id = $this->dbHandler->addServer($url);
$query = $this->connection->getQueryBuilder()->select('*')->from($this->dbTable);
@@ -85,7 +85,7 @@ class DbHandlerTest extends TestCase {
];
}
- public function testRemove() {
+ public function testRemove(): void {
$id1 = $this->dbHandler->addServer('server1');
$id2 = $this->dbHandler->addServer('server2');
@@ -112,7 +112,7 @@ class DbHandlerTest extends TestCase {
}
- public function testGetServerById() {
+ public function testGetServerById(): void {
$this->dbHandler->addServer('server1');
$id = $this->dbHandler->addServer('server2');
@@ -120,7 +120,7 @@ class DbHandlerTest extends TestCase {
$this->assertSame('server2', $result['url']);
}
- public function testGetAll() {
+ public function testGetAll(): void {
$id1 = $this->dbHandler->addServer('server1');
$id2 = $this->dbHandler->addServer('server2');
@@ -139,7 +139,7 @@ class DbHandlerTest extends TestCase {
* @param string $checkForServer
* @param bool $expected
*/
- public function testServerExists($serverInTable, $checkForServer, $expected) {
+ public function testServerExists($serverInTable, $checkForServer, $expected): void {
$this->dbHandler->addServer($serverInTable);
$this->assertSame($expected,
$this->dbHandler->serverExists($checkForServer)
@@ -173,7 +173,7 @@ class DbHandlerTest extends TestCase {
$this->assertSame('token', $result[0]['token']);
}
- public function testGetToken() {
+ public function testGetToken(): void {
$this->dbHandler->addServer('server1');
$this->dbHandler->addToken('http://server1', 'token');
$this->assertSame('token',
@@ -200,7 +200,7 @@ class DbHandlerTest extends TestCase {
$this->assertSame('secret', $result[0]['shared_secret']);
}
- public function testGetSharedSecret() {
+ public function testGetSharedSecret(): void {
$this->dbHandler->addServer('server1');
$this->dbHandler->addSharedSecret('http://server1', 'secret');
$this->assertSame('secret',
@@ -208,7 +208,7 @@ class DbHandlerTest extends TestCase {
);
}
- public function testSetServerStatus() {
+ public function testSetServerStatus(): void {
$this->dbHandler->addServer('server1');
$query = $this->connection->getQueryBuilder()->select('*')->from($this->dbTable);
@@ -227,7 +227,7 @@ class DbHandlerTest extends TestCase {
$this->assertSame(TrustedServers::STATUS_OK, (int)$result[0]['status']);
}
- public function testGetServerStatus() {
+ public function testGetServerStatus(): void {
$this->dbHandler->addServer('server1');
$this->dbHandler->setServerStatus('http://server1', TrustedServers::STATUS_OK);
$this->assertSame(TrustedServers::STATUS_OK,
@@ -248,7 +248,7 @@ class DbHandlerTest extends TestCase {
* @param string $url
* @param string $expected
*/
- public function testHash($url, $expected) {
+ public function testHash($url, $expected): void {
$this->assertSame($expected,
$this->invokePrivate($this->dbHandler, 'hash', [$url])
);
@@ -269,7 +269,7 @@ class DbHandlerTest extends TestCase {
* @param string $url
* @param string $expected
*/
- public function testNormalizeUrl($url, $expected) {
+ public function testNormalizeUrl($url, $expected): void {
$this->assertSame($expected,
$this->invokePrivate($this->dbHandler, 'normalizeUrl', [$url])
);
@@ -288,7 +288,7 @@ class DbHandlerTest extends TestCase {
/**
* @dataProvider providesAuth
*/
- public function testAuth($expectedResult, $user, $password) {
+ public function testAuth($expectedResult, $user, $password): void {
if ($expectedResult) {
$this->dbHandler->addServer('url1');
$this->dbHandler->addSharedSecret('url1', $password);
diff --git a/apps/federation/tests/Middleware/AddServerMiddlewareTest.php b/apps/federation/tests/Middleware/AddServerMiddlewareTest.php
index 85b918a80f1..d5ee241a85a 100644
--- a/apps/federation/tests/Middleware/AddServerMiddlewareTest.php
+++ b/apps/federation/tests/Middleware/AddServerMiddlewareTest.php
@@ -49,7 +49,7 @@ class AddServerMiddlewareTest extends TestCase {
* @param \Exception $exception
* @param string $hint
*/
- public function testAfterException($exception, $hint) {
+ public function testAfterException($exception, $hint): void {
$this->logger->expects($this->once())->method('error');
$this->l10n->expects($this->any())->method('t')
diff --git a/apps/federation/tests/Settings/AdminTest.php b/apps/federation/tests/Settings/AdminTest.php
index 9322db9f731..86baa6d6472 100644
--- a/apps/federation/tests/Settings/AdminTest.php
+++ b/apps/federation/tests/Settings/AdminTest.php
@@ -26,7 +26,7 @@ class AdminTest extends TestCase {
);
}
- public function testGetForm() {
+ public function testGetForm(): void {
$this->trustedServers
->expects($this->once())
->method('getServers')
@@ -39,11 +39,11 @@ class AdminTest extends TestCase {
$this->assertEquals($expected, $this->admin->getForm());
}
- public function testGetSection() {
+ public function testGetSection(): void {
$this->assertSame('sharing', $this->admin->getSection());
}
- public function testGetPriority() {
+ public function testGetPriority(): void {
$this->assertSame(30, $this->admin->getPriority());
}
}
diff --git a/apps/federation/tests/SyncFederationAddressbooksTest.php b/apps/federation/tests/SyncFederationAddressbooksTest.php
index e27d2e7d26e..73a89fea5eb 100644
--- a/apps/federation/tests/SyncFederationAddressbooksTest.php
+++ b/apps/federation/tests/SyncFederationAddressbooksTest.php
@@ -33,7 +33,7 @@ class SyncFederationAddressbooksTest extends \Test\TestCase {
$this->logger = $this->createMock(LoggerInterface::class);
}
- public function testSync() {
+ public function testSync(): void {
/** @var DbHandler | MockObject $dbHandler */
$dbHandler = $this->getMockBuilder(\OCA\Federation\DbHandler::class)
->disableOriginalConstructor()
@@ -63,7 +63,7 @@ class SyncFederationAddressbooksTest extends \Test\TestCase {
$this->assertEquals('1', count($this->callBacks));
}
- public function testException() {
+ public function testException(): void {
/** @var DbHandler | MockObject $dbHandler */
$dbHandler = $this->getMockBuilder(\OCA\Federation\DbHandler::class)->
disableOriginalConstructor()->
@@ -91,7 +91,7 @@ class SyncFederationAddressbooksTest extends \Test\TestCase {
$this->assertEquals(2, count($this->callBacks));
}
- public function testSuccessfulSyncWithoutChangesAfterFailure() {
+ public function testSuccessfulSyncWithoutChangesAfterFailure(): void {
/** @var DbHandler | MockObject $dbHandler */
$dbHandler = $this->getMockBuilder(\OCA\Federation\DbHandler::class)
->disableOriginalConstructor()
diff --git a/apps/federation/tests/TrustedServersTest.php b/apps/federation/tests/TrustedServersTest.php
index c97e815ec06..21f6102317a 100644
--- a/apps/federation/tests/TrustedServersTest.php
+++ b/apps/federation/tests/TrustedServersTest.php
@@ -173,13 +173,13 @@ class TrustedServersTest extends TestCase {
);
}
- public function testSetServerStatus() {
+ public function testSetServerStatus(): void {
$this->dbHandler->expects($this->once())->method('setServerStatus')
->with('url', 1);
$this->trustedServers->setServerStatus('url', 1);
}
- public function testGetServerStatus() {
+ public function testGetServerStatus(): void {
$this->dbHandler->expects($this->once())->method('getServerStatus')
->with('url')->willReturn(1);
$this->assertSame(
diff --git a/apps/files/l10n/es.js b/apps/files/l10n/es.js
index d16176df9ee..91a7b8b0ab4 100644
--- a/apps/files/l10n/es.js
+++ b/apps/files/l10n/es.js
@@ -156,11 +156,20 @@ OC.L10N.register(
"A file has been added to or removed from your <strong>favorites</strong>" : "Un archivo fue agregado o borrado de tus <strong>favoritos</strong>",
"A file or folder has been <strong>changed</strong>" : "Se ha <strong>modificado</strong> un archivo o carpeta",
"A favorite file or folder has been <strong>changed</strong>" : "Un archivo o carpeta favorito ha sido <strong>cambiado</strong>",
+ "Failed to authorize" : "Fallo al autorizar",
+ "Invalid folder path" : "Ruta de carpeta inválida",
+ "Folder not found" : "Carpeta no encontrada",
"Upload (max. %s)" : "Subida (máx. %s)",
+ "Files compatibility" : "Compatibilidad de archivos",
+ "Allow to restrict filenames to ensure files can be synced with all clients. By default all filenames valid on POSIX (e.g. Linux or macOS) are allowed." : "Permitir la restricción en nombres de archivo para asegurar que los archivos se puedan sincronizar con todos los clientes. Por defecto, se permiten todos los nombres de archivos válidos en POSIX (por ejemplo, Linux o macOS).",
+ "Enforce Windows compatibility" : "Forzar la compatibilidad con Windows",
+ "This will block filenames not valid on Windows systems, like using reserved names or special characters. But this will not enforce compatibility of case sensitivity." : "Esto bloqueará los nombres de archivos inválidos en sistemas Windows, tales como usar nombres reservados o caracteres especiales. Pero no forzará la compatibilidad del uso de mayúsculas y minúsculas.",
"Accept" : "Aceptar",
"Reject" : "Rechazar",
"Incoming ownership transfer from {user}" : "Ha llegado una transferencia de propiedad de {user}",
"Do you want to accept {path}?\n\nNote: The transfer process after accepting may take up to 1 hour." : "¿Deseas aceptar {path}?\n\nNota: El proceso de transferencia tras aceptar podría tardar hasta 1 hora.",
+ "Ownership transfer denied" : "Se denegó la transferencia de propiedad",
+ "Your ownership transfer of {path} was denied by {user}." : "Su transferencia de propiedad de {path} fue denegada por {user}.",
"Ownership transfer failed" : "Fallo al transferir la propiedad",
"Your ownership transfer of {path} to {user} failed." : "Ha fallado tu transferencia de propiedad de {path} a {user}.",
"The ownership transfer of {path} from {user} failed." : "Ha fallado la transferencia de propiedad de {path} desde {user}.",
@@ -168,6 +177,7 @@ OC.L10N.register(
"Your ownership transfer of {path} to {user} has completed." : "Se ha completado su transferencia de propiedad de {path} a {user}.",
"The ownership transfer of {path} from {user} has completed." : "Se ha completado la transferencia de propiedad de {path} a {user}.",
"in %s" : "en %s",
+ "Transferred from %1$s on %2$s" : "Se transfirió desde %1$s en %2$s",
"File Management" : "Gestión de archivos",
"Current directory path" : "Dirección de la carpeta actual",
"Reload current directory" : "Recargar carpeta actual",
@@ -179,10 +189,14 @@ OC.L10N.register(
"\"{displayName}\" action failed" : "la acción \"{displayName}\" falló",
"Toggle selection for file \"{displayName}\"" : "Alternar selección para archivo \"{displayName}\"",
"Toggle selection for folder \"{displayName}\"" : "Alternar selección para la carpeta \"{displayName}\"",
+ "File is loading" : "El archivo se está cargando",
+ "Folder is loading" : "La carpeta se está cargando",
"Rename file" : "Renombrar archivo",
"Filename" : "Nombre de archivo",
"Folder name" : "Nombre de la carpeta",
"This node is unavailable" : "Este nodo no está disponible",
+ "Another entry with the same name already exists." : "Ya existe otra entrada con el mismo nombre.",
+ "Invalid filename." : "Nombre de archivo inválido.",
"Renamed \"{oldName}\" to \"{newName}\"" : "Renombrado \"{oldName}\" a \"{newName}\"",
"Could not rename \"{oldName}\", it does not exist any more" : "No se ha podido renombrar \"{oldName}\", ya no existe",
"The name \"{newName}\" is already used in the folder \"{dir}\". Please choose a different name." : "El nombre \"{newName}\" ya está en uso en la carpeta \"{dir}\". Por favor, escoja un nombre diferente.",
@@ -193,6 +207,7 @@ OC.L10N.register(
"Remove filter" : "Quitar filtro",
"Total rows summary" : "Resumen de filas totales",
"Toggle selection for all files and folders" : "Seleccionar/deseleccionar todos los archivos y carpetas",
+ "(selected)" : "(seleccionado)",
"\"{displayName}\" failed on some elements " : "\"{displayName}\" fallo en algunos elementos",
"\"{displayName}\" batch action executed successfully" : "la acción en lotes \"{displayName}\" se ejecutó exitósamente",
"{count} selected" : "{count} seleccionados",
@@ -200,11 +215,16 @@ OC.L10N.register(
"Column headers with buttons are sortable." : "Las columnas con botones en la cabecera son ordenables.",
"This list is not fully rendered for performance reasons. The files will be rendered as you navigate through the list." : "Esta lista no se muestra completamente por motivos de rendimiento. Los archivos se mostrarán a medida que navega por la lista.",
"File not found" : "No se ha encontrado el archivo",
+ "Storage information" : "Información de almacenamiento",
+ "Storage quota" : "Cuota de almacenamiento",
"{usedQuotaByte} used" : "{usedQuotaByte} utilizados",
"{relative}% used" : "{relative}% utilizado",
"Could not refresh storage stats" : "No fue posible refrescar las estadísticas de almacenamiento",
"Your storage is full, files can not be updated or synced anymore!" : "Su almacenamiento está lleno, ¡Ya no se pueden subir ni sincronizarse más archivos!",
"Create" : "Crear",
+ "This name is already in use." : "Este nombre ya está en uso.",
+ "Fill template fields" : "Rellenar los campos de la plantilla",
+ "Submitting fields…" : "Enviando campos…",
"Submit" : "Enviar",
"Transfer ownership of a file or folder" : "Transferir la propiedad de un archivo o carpeta",
"Choose file or folder to transfer" : "Elegir archivo o carpeta para transferir",
@@ -234,6 +254,7 @@ OC.L10N.register(
"Error during upload: {message}" : "Error durante la subida: {message}",
"Error during upload, status code {status}" : "Error durante la subida, código de estado {status}",
"Unknown error during upload" : "Error desconocido durante la subida",
+ "Filter filenames…" : "Filtrar nombres de archivo…",
"Views" : "Vistas",
"Files settings" : "Configuración de archivos",
"File cannot be accessed" : "El archivo no puede ser accesado",
@@ -245,6 +266,7 @@ OC.L10N.register(
"Show hidden files" : "Mostrar archivos ocultos",
"Crop image previews" : "Recortar la previsualización de las imágenes",
"Enable the grid view" : "Habilitar vista de cuadrícula",
+ "Enable folder tree" : "Habilitar el árbol de carpetas",
"Additional settings" : "Ajustes adicionales",
"WebDAV" : "WebDAV",
"WebDAV URL" : "WebDAV URL",
@@ -267,9 +289,14 @@ OC.L10N.register(
"Disconnect storages" : "Desconectar almacenamientos",
"Delete files" : "Eliminar archivos",
"Delete folders" : "Eliminar carpetas",
+ "_You are about to permanently delete {count} item_::_You are about to permanently delete {count} items_" : ["Está a punto de eliminar {count} elemento permanentemente","Está a punto de eliminar {count} elementos permanentemente.","Está a punto de eliminar {count} elementos permanentemente"],
+ "_You are about to delete {count} item_::_You are about to delete {count} items_" : ["Está a punto de eliminar {count} elemento","Está a punto de eliminar {count} elementos","Está a punto de eliminar {count} elementos"],
"Confirm deletion" : "Confirmar eliminación",
"Cancel" : "Cancelar",
+ "Edit file locally" : "Editar archivo localmente",
"The file should now open locally. If you don't see this happening, make sure that the desktop client is installed on your system." : "El archivo debería abrirse ahora de forma local. Si no ve que esto suceda, asegúrese de que el cliente de escritorio esté instalado en su sistema.",
+ "Retry local edit" : "Reintentar la edición local",
+ "Edit online" : "Editar en línea",
"Destination is not a folder" : "El destino no es una carpeta",
"This file/folder is already in that directory" : "Este archivo/carpeta ya está en ese directorio",
"You cannot move a file/folder onto itself or into a subfolder of itself" : "No puede mover un archivo/carpeta a sí mismo o a una sub-carpeta de sí mismo",
@@ -283,6 +310,7 @@ OC.L10N.register(
"Copy to {target}" : "Copiar a {target}",
"Move to {target}" : "Mover a {target}",
"Move or copy operation failed" : "La operación de mover o copiar falló",
+ "Cancelled move or copy of \"{filename}\"." : "Se canceló la operación de mover o copiar de \"{filename}\".",
"Cancelled move or copy operation" : "Se canceló la operación de mover o copiar",
"Open folder {displayName}" : "Abrir carpeta {displayName}",
"Open in Files" : "Abrir en Archivos",
@@ -290,12 +318,20 @@ OC.L10N.register(
"Today" : "Hoy",
"Last 7 days" : "Últimos 7 días",
"Last 30 days" : "Últimos 30 días",
+ "This year ({year})" : "Este año ({year})",
+ "Last year ({year})" : "El año pasado ({year})",
"Documents" : "Documentos",
+ "Spreadsheets" : "Hojas de cálculo",
+ "Presentations" : "Presentaciones",
+ "PDFs" : "PDFs",
"Folders" : "Carpetas",
"Audio" : "Audio",
+ "Photos and images" : "Fotos e imágenes",
"Videos" : "Vídeos",
+ "New folder creation cancelled" : "Se canceló la creación de la carpeta nueva",
"Created new folder \"{name}\"" : "Se creó la carpeta nueva \"{name}\"",
"Unable to initialize the templates directory" : "No se ha podido iniciar la carpeta de plantillas",
+ "Create templates folder" : "Crear carpeta de plantillas",
"Templates" : "Plantillas",
"New template folder" : "Nueva carpeta de plantillas",
"In folder" : "En carpeta",
@@ -318,6 +354,11 @@ OC.L10N.register(
"_1 file and {folderCount} folder_::_1 file and {folderCount} folders_" : ["1 archivo y {folderCount} carpeta","1 archivo y {folderCount} carpetas","1 archivo y {folderCount} carpetas"],
"_{fileCount} file and 1 folder_::_{fileCount} files and 1 folder_" : ["{fileCount} archivo y 1 carpeta","{fileCount} archivos y 1 carpeta","{fileCount} archivos y 1 carpeta"],
"{fileCount} files and {folderCount} folders" : "{fileCount} archivos y {folderCount} carpetas",
+ "Filename must not be empty." : "El nombre de archivo no debe estar vacío.",
+ "\"{char}\" is not allowed inside a filename." : "\"{char}\" no está permitido en el nombre de archivo.",
+ "\"{segment}\" is a reserved name and not allowed for filenames." : "\"{segment}\" es un nombre reservado y no se permite para los nombres de archivo.",
+ "\"{extension}\" is not an allowed filetype." : "\"{extension}\" no es un tipo de archivo permitido.",
+ "Filenames must not end with \"{extension}\"." : "Los nombres de archivo no puede terminar con \"{extension}\".",
"List of favorites files and folders." : "Lista de archivos y carpetas favoritos.",
"No favorites yet" : "Aún no hay favoritos",
"Files and folders you mark as favorite will show up here" : "Aquí aparecerán los archivos y carpetas que has marcado como favoritos",
@@ -341,6 +382,10 @@ OC.L10N.register(
"Copy direct link (only works for users who have access to this file/folder)" : "Copiar enlace directo (solo funciona para usuarios que tienen acceso a este archivo/carpeta)",
"\"remote user\"" : "\"usuario remoto\"",
"{newName} already exists." : "{newName} ya existe.",
+ "\"{segment}\" is not allowed inside a filename." : "\"{segment}\" no se permite dentro de los nombres de archivo.",
+ "\"{segment}\" is a forbidden file or folder name." : "\"{segment}\" no se permite como nombre de archivo o carpeta.",
+ "\"{segment}\" is not an allowed filetype." : "\"{segment}\" no es un tipo de archivo permitido.",
+ "Filenames must not end with \"{segment}\"." : "Los nombres de archivo no pueden terminar con \"{segment}\".",
"Name cannot be empty" : "El nombre no puede estar vacío",
"Another entry with the same name already exists" : "Ya existe otra entrada con el mismo nombre",
"Storage informations" : "Informaciones de almacenamiento",
diff --git a/apps/files/l10n/es.json b/apps/files/l10n/es.json
index 71544a02417..8c7ea4867ce 100644
--- a/apps/files/l10n/es.json
+++ b/apps/files/l10n/es.json
@@ -154,11 +154,20 @@
"A file has been added to or removed from your <strong>favorites</strong>" : "Un archivo fue agregado o borrado de tus <strong>favoritos</strong>",
"A file or folder has been <strong>changed</strong>" : "Se ha <strong>modificado</strong> un archivo o carpeta",
"A favorite file or folder has been <strong>changed</strong>" : "Un archivo o carpeta favorito ha sido <strong>cambiado</strong>",
+ "Failed to authorize" : "Fallo al autorizar",
+ "Invalid folder path" : "Ruta de carpeta inválida",
+ "Folder not found" : "Carpeta no encontrada",
"Upload (max. %s)" : "Subida (máx. %s)",
+ "Files compatibility" : "Compatibilidad de archivos",
+ "Allow to restrict filenames to ensure files can be synced with all clients. By default all filenames valid on POSIX (e.g. Linux or macOS) are allowed." : "Permitir la restricción en nombres de archivo para asegurar que los archivos se puedan sincronizar con todos los clientes. Por defecto, se permiten todos los nombres de archivos válidos en POSIX (por ejemplo, Linux o macOS).",
+ "Enforce Windows compatibility" : "Forzar la compatibilidad con Windows",
+ "This will block filenames not valid on Windows systems, like using reserved names or special characters. But this will not enforce compatibility of case sensitivity." : "Esto bloqueará los nombres de archivos inválidos en sistemas Windows, tales como usar nombres reservados o caracteres especiales. Pero no forzará la compatibilidad del uso de mayúsculas y minúsculas.",
"Accept" : "Aceptar",
"Reject" : "Rechazar",
"Incoming ownership transfer from {user}" : "Ha llegado una transferencia de propiedad de {user}",
"Do you want to accept {path}?\n\nNote: The transfer process after accepting may take up to 1 hour." : "¿Deseas aceptar {path}?\n\nNota: El proceso de transferencia tras aceptar podría tardar hasta 1 hora.",
+ "Ownership transfer denied" : "Se denegó la transferencia de propiedad",
+ "Your ownership transfer of {path} was denied by {user}." : "Su transferencia de propiedad de {path} fue denegada por {user}.",
"Ownership transfer failed" : "Fallo al transferir la propiedad",
"Your ownership transfer of {path} to {user} failed." : "Ha fallado tu transferencia de propiedad de {path} a {user}.",
"The ownership transfer of {path} from {user} failed." : "Ha fallado la transferencia de propiedad de {path} desde {user}.",
@@ -166,6 +175,7 @@
"Your ownership transfer of {path} to {user} has completed." : "Se ha completado su transferencia de propiedad de {path} a {user}.",
"The ownership transfer of {path} from {user} has completed." : "Se ha completado la transferencia de propiedad de {path} a {user}.",
"in %s" : "en %s",
+ "Transferred from %1$s on %2$s" : "Se transfirió desde %1$s en %2$s",
"File Management" : "Gestión de archivos",
"Current directory path" : "Dirección de la carpeta actual",
"Reload current directory" : "Recargar carpeta actual",
@@ -177,10 +187,14 @@
"\"{displayName}\" action failed" : "la acción \"{displayName}\" falló",
"Toggle selection for file \"{displayName}\"" : "Alternar selección para archivo \"{displayName}\"",
"Toggle selection for folder \"{displayName}\"" : "Alternar selección para la carpeta \"{displayName}\"",
+ "File is loading" : "El archivo se está cargando",
+ "Folder is loading" : "La carpeta se está cargando",
"Rename file" : "Renombrar archivo",
"Filename" : "Nombre de archivo",
"Folder name" : "Nombre de la carpeta",
"This node is unavailable" : "Este nodo no está disponible",
+ "Another entry with the same name already exists." : "Ya existe otra entrada con el mismo nombre.",
+ "Invalid filename." : "Nombre de archivo inválido.",
"Renamed \"{oldName}\" to \"{newName}\"" : "Renombrado \"{oldName}\" a \"{newName}\"",
"Could not rename \"{oldName}\", it does not exist any more" : "No se ha podido renombrar \"{oldName}\", ya no existe",
"The name \"{newName}\" is already used in the folder \"{dir}\". Please choose a different name." : "El nombre \"{newName}\" ya está en uso en la carpeta \"{dir}\". Por favor, escoja un nombre diferente.",
@@ -191,6 +205,7 @@
"Remove filter" : "Quitar filtro",
"Total rows summary" : "Resumen de filas totales",
"Toggle selection for all files and folders" : "Seleccionar/deseleccionar todos los archivos y carpetas",
+ "(selected)" : "(seleccionado)",
"\"{displayName}\" failed on some elements " : "\"{displayName}\" fallo en algunos elementos",
"\"{displayName}\" batch action executed successfully" : "la acción en lotes \"{displayName}\" se ejecutó exitósamente",
"{count} selected" : "{count} seleccionados",
@@ -198,11 +213,16 @@
"Column headers with buttons are sortable." : "Las columnas con botones en la cabecera son ordenables.",
"This list is not fully rendered for performance reasons. The files will be rendered as you navigate through the list." : "Esta lista no se muestra completamente por motivos de rendimiento. Los archivos se mostrarán a medida que navega por la lista.",
"File not found" : "No se ha encontrado el archivo",
+ "Storage information" : "Información de almacenamiento",
+ "Storage quota" : "Cuota de almacenamiento",
"{usedQuotaByte} used" : "{usedQuotaByte} utilizados",
"{relative}% used" : "{relative}% utilizado",
"Could not refresh storage stats" : "No fue posible refrescar las estadísticas de almacenamiento",
"Your storage is full, files can not be updated or synced anymore!" : "Su almacenamiento está lleno, ¡Ya no se pueden subir ni sincronizarse más archivos!",
"Create" : "Crear",
+ "This name is already in use." : "Este nombre ya está en uso.",
+ "Fill template fields" : "Rellenar los campos de la plantilla",
+ "Submitting fields…" : "Enviando campos…",
"Submit" : "Enviar",
"Transfer ownership of a file or folder" : "Transferir la propiedad de un archivo o carpeta",
"Choose file or folder to transfer" : "Elegir archivo o carpeta para transferir",
@@ -232,6 +252,7 @@
"Error during upload: {message}" : "Error durante la subida: {message}",
"Error during upload, status code {status}" : "Error durante la subida, código de estado {status}",
"Unknown error during upload" : "Error desconocido durante la subida",
+ "Filter filenames…" : "Filtrar nombres de archivo…",
"Views" : "Vistas",
"Files settings" : "Configuración de archivos",
"File cannot be accessed" : "El archivo no puede ser accesado",
@@ -243,6 +264,7 @@
"Show hidden files" : "Mostrar archivos ocultos",
"Crop image previews" : "Recortar la previsualización de las imágenes",
"Enable the grid view" : "Habilitar vista de cuadrícula",
+ "Enable folder tree" : "Habilitar el árbol de carpetas",
"Additional settings" : "Ajustes adicionales",
"WebDAV" : "WebDAV",
"WebDAV URL" : "WebDAV URL",
@@ -265,9 +287,14 @@
"Disconnect storages" : "Desconectar almacenamientos",
"Delete files" : "Eliminar archivos",
"Delete folders" : "Eliminar carpetas",
+ "_You are about to permanently delete {count} item_::_You are about to permanently delete {count} items_" : ["Está a punto de eliminar {count} elemento permanentemente","Está a punto de eliminar {count} elementos permanentemente.","Está a punto de eliminar {count} elementos permanentemente"],
+ "_You are about to delete {count} item_::_You are about to delete {count} items_" : ["Está a punto de eliminar {count} elemento","Está a punto de eliminar {count} elementos","Está a punto de eliminar {count} elementos"],
"Confirm deletion" : "Confirmar eliminación",
"Cancel" : "Cancelar",
+ "Edit file locally" : "Editar archivo localmente",
"The file should now open locally. If you don't see this happening, make sure that the desktop client is installed on your system." : "El archivo debería abrirse ahora de forma local. Si no ve que esto suceda, asegúrese de que el cliente de escritorio esté instalado en su sistema.",
+ "Retry local edit" : "Reintentar la edición local",
+ "Edit online" : "Editar en línea",
"Destination is not a folder" : "El destino no es una carpeta",
"This file/folder is already in that directory" : "Este archivo/carpeta ya está en ese directorio",
"You cannot move a file/folder onto itself or into a subfolder of itself" : "No puede mover un archivo/carpeta a sí mismo o a una sub-carpeta de sí mismo",
@@ -281,6 +308,7 @@
"Copy to {target}" : "Copiar a {target}",
"Move to {target}" : "Mover a {target}",
"Move or copy operation failed" : "La operación de mover o copiar falló",
+ "Cancelled move or copy of \"{filename}\"." : "Se canceló la operación de mover o copiar de \"{filename}\".",
"Cancelled move or copy operation" : "Se canceló la operación de mover o copiar",
"Open folder {displayName}" : "Abrir carpeta {displayName}",
"Open in Files" : "Abrir en Archivos",
@@ -288,12 +316,20 @@
"Today" : "Hoy",
"Last 7 days" : "Últimos 7 días",
"Last 30 days" : "Últimos 30 días",
+ "This year ({year})" : "Este año ({year})",
+ "Last year ({year})" : "El año pasado ({year})",
"Documents" : "Documentos",
+ "Spreadsheets" : "Hojas de cálculo",
+ "Presentations" : "Presentaciones",
+ "PDFs" : "PDFs",
"Folders" : "Carpetas",
"Audio" : "Audio",
+ "Photos and images" : "Fotos e imágenes",
"Videos" : "Vídeos",
+ "New folder creation cancelled" : "Se canceló la creación de la carpeta nueva",
"Created new folder \"{name}\"" : "Se creó la carpeta nueva \"{name}\"",
"Unable to initialize the templates directory" : "No se ha podido iniciar la carpeta de plantillas",
+ "Create templates folder" : "Crear carpeta de plantillas",
"Templates" : "Plantillas",
"New template folder" : "Nueva carpeta de plantillas",
"In folder" : "En carpeta",
@@ -316,6 +352,11 @@
"_1 file and {folderCount} folder_::_1 file and {folderCount} folders_" : ["1 archivo y {folderCount} carpeta","1 archivo y {folderCount} carpetas","1 archivo y {folderCount} carpetas"],
"_{fileCount} file and 1 folder_::_{fileCount} files and 1 folder_" : ["{fileCount} archivo y 1 carpeta","{fileCount} archivos y 1 carpeta","{fileCount} archivos y 1 carpeta"],
"{fileCount} files and {folderCount} folders" : "{fileCount} archivos y {folderCount} carpetas",
+ "Filename must not be empty." : "El nombre de archivo no debe estar vacío.",
+ "\"{char}\" is not allowed inside a filename." : "\"{char}\" no está permitido en el nombre de archivo.",
+ "\"{segment}\" is a reserved name and not allowed for filenames." : "\"{segment}\" es un nombre reservado y no se permite para los nombres de archivo.",
+ "\"{extension}\" is not an allowed filetype." : "\"{extension}\" no es un tipo de archivo permitido.",
+ "Filenames must not end with \"{extension}\"." : "Los nombres de archivo no puede terminar con \"{extension}\".",
"List of favorites files and folders." : "Lista de archivos y carpetas favoritos.",
"No favorites yet" : "Aún no hay favoritos",
"Files and folders you mark as favorite will show up here" : "Aquí aparecerán los archivos y carpetas que has marcado como favoritos",
@@ -339,6 +380,10 @@
"Copy direct link (only works for users who have access to this file/folder)" : "Copiar enlace directo (solo funciona para usuarios que tienen acceso a este archivo/carpeta)",
"\"remote user\"" : "\"usuario remoto\"",
"{newName} already exists." : "{newName} ya existe.",
+ "\"{segment}\" is not allowed inside a filename." : "\"{segment}\" no se permite dentro de los nombres de archivo.",
+ "\"{segment}\" is a forbidden file or folder name." : "\"{segment}\" no se permite como nombre de archivo o carpeta.",
+ "\"{segment}\" is not an allowed filetype." : "\"{segment}\" no es un tipo de archivo permitido.",
+ "Filenames must not end with \"{segment}\"." : "Los nombres de archivo no pueden terminar con \"{segment}\".",
"Name cannot be empty" : "El nombre no puede estar vacío",
"Another entry with the same name already exists" : "Ya existe otra entrada con el mismo nombre",
"Storage informations" : "Informaciones de almacenamiento",
diff --git a/apps/files/l10n/pt_BR.js b/apps/files/l10n/pt_BR.js
index 694e6d5d8f4..87e4f9702c6 100644
--- a/apps/files/l10n/pt_BR.js
+++ b/apps/files/l10n/pt_BR.js
@@ -207,6 +207,7 @@ OC.L10N.register(
"Remove filter" : "Remover filtro",
"Total rows summary" : "Resumo total de linhas",
"Toggle selection for all files and folders" : "Alternar seleção para todos os arquivos e pastas",
+ "(selected)" : "(selecionado)",
"\"{displayName}\" failed on some elements " : "\"{displayName}\" falhou em alguns elementos",
"\"{displayName}\" batch action executed successfully" : "Ação em lote \"{displayName}\" executada com sucesso",
"{count} selected" : "{count} selecionados",
diff --git a/apps/files/l10n/pt_BR.json b/apps/files/l10n/pt_BR.json
index b3ef2c95aa4..be65430c70b 100644
--- a/apps/files/l10n/pt_BR.json
+++ b/apps/files/l10n/pt_BR.json
@@ -205,6 +205,7 @@
"Remove filter" : "Remover filtro",
"Total rows summary" : "Resumo total de linhas",
"Toggle selection for all files and folders" : "Alternar seleção para todos os arquivos e pastas",
+ "(selected)" : "(selecionado)",
"\"{displayName}\" failed on some elements " : "\"{displayName}\" falhou em alguns elementos",
"\"{displayName}\" batch action executed successfully" : "Ação em lote \"{displayName}\" executada com sucesso",
"{count} selected" : "{count} selecionados",
diff --git a/apps/files/tests/Activity/Filter/GenericTest.php b/apps/files/tests/Activity/Filter/GenericTest.php
index 6f4dd594582..347bea0f643 100644
--- a/apps/files/tests/Activity/Filter/GenericTest.php
+++ b/apps/files/tests/Activity/Filter/GenericTest.php
@@ -28,7 +28,7 @@ class GenericTest extends TestCase {
* @dataProvider dataFilters
* @param string $filterClass
*/
- public function testImplementsInterface($filterClass) {
+ public function testImplementsInterface($filterClass): void {
$filter = \OC::$server->query($filterClass);
$this->assertInstanceOf(IFilter::class, $filter);
}
@@ -37,7 +37,7 @@ class GenericTest extends TestCase {
* @dataProvider dataFilters
* @param string $filterClass
*/
- public function testGetIdentifier($filterClass) {
+ public function testGetIdentifier($filterClass): void {
/** @var IFilter $filter */
$filter = \OC::$server->query($filterClass);
$this->assertIsString($filter->getIdentifier());
@@ -47,7 +47,7 @@ class GenericTest extends TestCase {
* @dataProvider dataFilters
* @param string $filterClass
*/
- public function testGetName($filterClass) {
+ public function testGetName($filterClass): void {
/** @var IFilter $filter */
$filter = \OC::$server->query($filterClass);
$this->assertIsString($filter->getName());
@@ -57,7 +57,7 @@ class GenericTest extends TestCase {
* @dataProvider dataFilters
* @param string $filterClass
*/
- public function testGetPriority($filterClass) {
+ public function testGetPriority($filterClass): void {
/** @var IFilter $filter */
$filter = \OC::$server->query($filterClass);
$priority = $filter->getPriority();
@@ -70,7 +70,7 @@ class GenericTest extends TestCase {
* @dataProvider dataFilters
* @param string $filterClass
*/
- public function testGetIcon($filterClass) {
+ public function testGetIcon($filterClass): void {
/** @var IFilter $filter */
$filter = \OC::$server->query($filterClass);
$this->assertIsString($filter->getIcon());
@@ -81,7 +81,7 @@ class GenericTest extends TestCase {
* @dataProvider dataFilters
* @param string $filterClass
*/
- public function testFilterTypes($filterClass) {
+ public function testFilterTypes($filterClass): void {
/** @var IFilter $filter */
$filter = \OC::$server->query($filterClass);
$this->assertIsArray($filter->filterTypes([]));
@@ -91,7 +91,7 @@ class GenericTest extends TestCase {
* @dataProvider dataFilters
* @param string $filterClass
*/
- public function testAllowedApps($filterClass) {
+ public function testAllowedApps($filterClass): void {
/** @var IFilter $filter */
$filter = \OC::$server->query($filterClass);
$this->assertIsArray($filter->allowedApps());
diff --git a/apps/files/tests/Activity/ProviderTest.php b/apps/files/tests/Activity/ProviderTest.php
index 1716ccfe100..73c726dac3c 100644
--- a/apps/files/tests/Activity/ProviderTest.php
+++ b/apps/files/tests/Activity/ProviderTest.php
@@ -104,7 +104,7 @@ class ProviderTest extends TestCase {
* @param string $name
* @param string $path
*/
- public function testGetFile($parameter, $eventId, $id, $name, $path) {
+ public function testGetFile($parameter, $eventId, $id, $name, $path): void {
$provider = $this->getProvider();
if ($eventId !== null) {
@@ -131,7 +131,7 @@ class ProviderTest extends TestCase {
}
- public function testGetFileThrows() {
+ public function testGetFileThrows(): void {
$this->expectException(\InvalidArgumentException::class);
$provider = $this->getProvider();
diff --git a/apps/files/tests/Activity/Setting/GenericTest.php b/apps/files/tests/Activity/Setting/GenericTest.php
index c124106140a..1cce876cbcf 100644
--- a/apps/files/tests/Activity/Setting/GenericTest.php
+++ b/apps/files/tests/Activity/Setting/GenericTest.php
@@ -23,7 +23,7 @@ class GenericTest extends TestCase {
* @dataProvider dataSettings
* @param string $settingClass
*/
- public function testImplementsInterface($settingClass) {
+ public function testImplementsInterface($settingClass): void {
$setting = \OC::$server->query($settingClass);
$this->assertInstanceOf(ISetting::class, $setting);
}
@@ -32,7 +32,7 @@ class GenericTest extends TestCase {
* @dataProvider dataSettings
* @param string $settingClass
*/
- public function testGetIdentifier($settingClass) {
+ public function testGetIdentifier($settingClass): void {
/** @var ISetting $setting */
$setting = \OC::$server->query($settingClass);
$this->assertIsString($setting->getIdentifier());
@@ -42,7 +42,7 @@ class GenericTest extends TestCase {
* @dataProvider dataSettings
* @param string $settingClass
*/
- public function testGetName($settingClass) {
+ public function testGetName($settingClass): void {
/** @var ISetting $setting */
$setting = \OC::$server->query($settingClass);
$this->assertIsString($setting->getName());
@@ -52,7 +52,7 @@ class GenericTest extends TestCase {
* @dataProvider dataSettings
* @param string $settingClass
*/
- public function testGetPriority($settingClass) {
+ public function testGetPriority($settingClass): void {
/** @var ISetting $setting */
$setting = \OC::$server->query($settingClass);
$priority = $setting->getPriority();
@@ -65,7 +65,7 @@ class GenericTest extends TestCase {
* @dataProvider dataSettings
* @param string $settingClass
*/
- public function testCanChangeStream($settingClass) {
+ public function testCanChangeStream($settingClass): void {
/** @var ISetting $setting */
$setting = \OC::$server->query($settingClass);
$this->assertIsBool($setting->canChangeStream());
@@ -75,7 +75,7 @@ class GenericTest extends TestCase {
* @dataProvider dataSettings
* @param string $settingClass
*/
- public function testIsDefaultEnabledStream($settingClass) {
+ public function testIsDefaultEnabledStream($settingClass): void {
/** @var ISetting $setting */
$setting = \OC::$server->query($settingClass);
$this->assertIsBool($setting->isDefaultEnabledStream());
@@ -85,7 +85,7 @@ class GenericTest extends TestCase {
* @dataProvider dataSettings
* @param string $settingClass
*/
- public function testCanChangeMail($settingClass) {
+ public function testCanChangeMail($settingClass): void {
/** @var ISetting $setting */
$setting = \OC::$server->query($settingClass);
$this->assertIsBool($setting->canChangeMail());
@@ -95,7 +95,7 @@ class GenericTest extends TestCase {
* @dataProvider dataSettings
* @param string $settingClass
*/
- public function testIsDefaultEnabledMail($settingClass) {
+ public function testIsDefaultEnabledMail($settingClass): void {
/** @var ISetting $setting */
$setting = \OC::$server->query($settingClass);
$this->assertIsBool($setting->isDefaultEnabledMail());
diff --git a/apps/files/tests/BackgroundJob/DeleteOrphanedItemsJobTest.php b/apps/files/tests/BackgroundJob/DeleteOrphanedItemsJobTest.php
index fb8ff9884af..1ce2d7bd8f7 100644
--- a/apps/files/tests/BackgroundJob/DeleteOrphanedItemsJobTest.php
+++ b/apps/files/tests/BackgroundJob/DeleteOrphanedItemsJobTest.php
@@ -51,7 +51,7 @@ class DeleteOrphanedItemsJobTest extends \Test\TestCase {
/**
* Test clearing orphaned system tag mappings
*/
- public function testClearSystemTagMappings() {
+ public function testClearSystemTagMappings(): void {
$this->cleanMapping('systemtag_object_mapping');
$query = $this->connection->getQueryBuilder();
@@ -100,7 +100,7 @@ class DeleteOrphanedItemsJobTest extends \Test\TestCase {
/**
* Test clearing orphaned system tag mappings
*/
- public function testClearUserTagMappings() {
+ public function testClearUserTagMappings(): void {
$this->cleanMapping('vcategory_to_object');
$query = $this->connection->getQueryBuilder();
@@ -149,7 +149,7 @@ class DeleteOrphanedItemsJobTest extends \Test\TestCase {
/**
* Test clearing orphaned system tag mappings
*/
- public function testClearComments() {
+ public function testClearComments(): void {
$this->cleanMapping('comments');
$query = $this->connection->getQueryBuilder();
@@ -200,7 +200,7 @@ class DeleteOrphanedItemsJobTest extends \Test\TestCase {
/**
* Test clearing orphaned system tag mappings
*/
- public function testClearCommentReadMarks() {
+ public function testClearCommentReadMarks(): void {
$this->cleanMapping('comments_read_markers');
$query = $this->connection->getQueryBuilder();
diff --git a/apps/files/tests/BackgroundJob/ScanFilesTest.php b/apps/files/tests/BackgroundJob/ScanFilesTest.php
index 9c0dd77dfb0..6e7b6c7cd54 100644
--- a/apps/files/tests/BackgroundJob/ScanFilesTest.php
+++ b/apps/files/tests/BackgroundJob/ScanFilesTest.php
@@ -79,7 +79,7 @@ class ScanFilesTest extends TestCase {
return $storage;
}
- public function testAllScanned() {
+ public function testAllScanned(): void {
$this->setupStorage('foouser', '/foousers/files/foo');
$this->scanFiles->expects($this->never())
@@ -87,7 +87,7 @@ class ScanFilesTest extends TestCase {
$this->runJob();
}
- public function testUnscanned() {
+ public function testUnscanned(): void {
$storage = $this->setupStorage('foouser', '/foousers/files/foo');
$storage->getCache()->put('foo', ['size' => -1]);
diff --git a/apps/files/tests/Command/DeleteOrphanedFilesTest.php b/apps/files/tests/Command/DeleteOrphanedFilesTest.php
index ed9a1866d26..1205e204ec4 100644
--- a/apps/files/tests/Command/DeleteOrphanedFilesTest.php
+++ b/apps/files/tests/Command/DeleteOrphanedFilesTest.php
@@ -82,7 +82,7 @@ class DeleteOrphanedFilesTest extends TestCase {
/**
* Test clearing orphaned files
*/
- public function testClearFiles() {
+ public function testClearFiles(): void {
$input = $this->getMockBuilder(InputInterface::class)
->disableOriginalConstructor()
->getMock();
diff --git a/apps/files/tests/Controller/ApiControllerTest.php b/apps/files/tests/Controller/ApiControllerTest.php
index f79a5c7bb64..ad2a6a15b2b 100644
--- a/apps/files/tests/Controller/ApiControllerTest.php
+++ b/apps/files/tests/Controller/ApiControllerTest.php
@@ -113,12 +113,12 @@ class ApiControllerTest extends TestCase {
);
}
- public function testUpdateFileTagsEmpty() {
+ public function testUpdateFileTagsEmpty(): void {
$expected = new DataResponse([]);
$this->assertEquals($expected, $this->apiController->updateFileTags('/path.txt'));
}
- public function testUpdateFileTagsWorking() {
+ public function testUpdateFileTagsWorking(): void {
$this->tagService->expects($this->once())
->method('updateFileTags')
->with('/path.txt', ['Tag1', 'Tag2']);
@@ -132,7 +132,7 @@ class ApiControllerTest extends TestCase {
$this->assertEquals($expected, $this->apiController->updateFileTags('/path.txt', ['Tag1', 'Tag2']));
}
- public function testUpdateFileTagsNotFoundException() {
+ public function testUpdateFileTagsNotFoundException(): void {
$this->tagService->expects($this->once())
->method('updateFileTags')
->with('/path.txt', ['Tag1', 'Tag2'])
@@ -142,7 +142,7 @@ class ApiControllerTest extends TestCase {
$this->assertEquals($expected, $this->apiController->updateFileTags('/path.txt', ['Tag1', 'Tag2']));
}
- public function testUpdateFileTagsStorageNotAvailableException() {
+ public function testUpdateFileTagsStorageNotAvailableException(): void {
$this->tagService->expects($this->once())
->method('updateFileTags')
->with('/path.txt', ['Tag1', 'Tag2'])
@@ -152,7 +152,7 @@ class ApiControllerTest extends TestCase {
$this->assertEquals($expected, $this->apiController->updateFileTags('/path.txt', ['Tag1', 'Tag2']));
}
- public function testUpdateFileTagsStorageGenericException() {
+ public function testUpdateFileTagsStorageGenericException(): void {
$this->tagService->expects($this->once())
->method('updateFileTags')
->with('/path.txt', ['Tag1', 'Tag2'])
@@ -162,7 +162,7 @@ class ApiControllerTest extends TestCase {
$this->assertEquals($expected, $this->apiController->updateFileTags('/path.txt', ['Tag1', 'Tag2']));
}
- public function testGetThumbnailInvalidSize() {
+ public function testGetThumbnailInvalidSize(): void {
$this->userFolder->method('get')
->with($this->equalTo(''))
->willThrowException(new NotFoundException());
@@ -170,7 +170,7 @@ class ApiControllerTest extends TestCase {
$this->assertEquals($expected, $this->apiController->getThumbnail(0, 0, ''));
}
- public function testGetThumbnailInvalidImage() {
+ public function testGetThumbnailInvalidImage(): void {
$file = $this->createMock(File::class);
$file->method('getId')->willReturn(123);
$this->userFolder->method('get')
@@ -184,7 +184,7 @@ class ApiControllerTest extends TestCase {
$this->assertEquals($expected, $this->apiController->getThumbnail(10, 10, 'unknown.jpg'));
}
- public function testGetThumbnailInvalidPartFile() {
+ public function testGetThumbnailInvalidPartFile(): void {
$file = $this->createMock(File::class);
$file->method('getId')->willReturn(0);
$this->userFolder->method('get')
@@ -194,7 +194,7 @@ class ApiControllerTest extends TestCase {
$this->assertEquals($expected, $this->apiController->getThumbnail(10, 10, 'unknown.jpg'));
}
- public function testGetThumbnail() {
+ public function testGetThumbnail(): void {
$file = $this->createMock(File::class);
$file->method('getId')->willReturn(123);
$this->userFolder->method('get')
@@ -214,7 +214,7 @@ class ApiControllerTest extends TestCase {
$this->assertInstanceOf(Http\FileDisplayResponse::class, $ret);
}
- public function testShowHiddenFiles() {
+ public function testShowHiddenFiles(): void {
$show = false;
$this->config->expects($this->once())
@@ -227,7 +227,7 @@ class ApiControllerTest extends TestCase {
$this->assertEquals($expected, $actual);
}
- public function testCropImagePreviews() {
+ public function testCropImagePreviews(): void {
$crop = true;
$this->config->expects($this->once())
diff --git a/apps/files/tests/Controller/ViewControllerTest.php b/apps/files/tests/Controller/ViewControllerTest.php
index 53984b5fc1c..d9d5910f4c4 100644
--- a/apps/files/tests/Controller/ViewControllerTest.php
+++ b/apps/files/tests/Controller/ViewControllerTest.php
@@ -97,7 +97,7 @@ class ViewControllerTest extends TestCase {
->getMock();
}
- public function testIndexWithRegularBrowser() {
+ public function testIndexWithRegularBrowser(): void {
$this->viewController
->expects($this->any())
->method('getStorageInfo')
@@ -145,7 +145,7 @@ class ViewControllerTest extends TestCase {
$this->assertEquals($expected, $this->viewController->index('MyDir', 'MyView'));
}
- public function testShowFileRouteWithTrashedFile() {
+ public function testShowFileRouteWithTrashedFile(): void {
$this->appManager->expects($this->once())
->method('isEnabledForUser')
->with('files_trashbin')
diff --git a/apps/files/tests/HelperTest.php b/apps/files/tests/HelperTest.php
index 2bafb25dffa..fdcef8f7125 100644
--- a/apps/files/tests/HelperTest.php
+++ b/apps/files/tests/HelperTest.php
@@ -74,7 +74,7 @@ class HelperTest extends \Test\TestCase {
/**
* @dataProvider sortDataProvider
*/
- public function testSortByName(string $sort, bool $sortDescending, array $expectedOrder) {
+ public function testSortByName(string $sort, bool $sortDescending, array $expectedOrder): void {
if (($sort === 'mtime') && (PHP_INT_SIZE < 8)) {
$this->markTestSkipped('Skip mtime sorting on 32bit');
}
@@ -90,7 +90,7 @@ class HelperTest extends \Test\TestCase {
);
}
- public function testPopulateTags() {
+ public function testPopulateTags(): void {
$tagManager = $this->createMock(\OCP\ITagManager::class);
$tagger = $this->createMock(\OCP\ITags::class);
diff --git a/apps/files/tests/Service/TagServiceTest.php b/apps/files/tests/Service/TagServiceTest.php
index 7a2084f21d8..7922c45a639 100644
--- a/apps/files/tests/Service/TagServiceTest.php
+++ b/apps/files/tests/Service/TagServiceTest.php
@@ -101,7 +101,7 @@ class TagServiceTest extends \Test\TestCase {
}
}
- public function testUpdateFileTags() {
+ public function testUpdateFileTags(): void {
$tag1 = 'tag1';
$tag2 = 'tag2';
@@ -142,7 +142,7 @@ class TagServiceTest extends \Test\TestCase {
$subdir->delete();
}
- public function testFavoriteActivity() {
+ public function testFavoriteActivity(): void {
$subdir = $this->root->newFolder('subdir');
$file = $subdir->newFile('test.txt');
diff --git a/apps/files_external/l10n/ar.js b/apps/files_external/l10n/ar.js
index 1f446555fcc..2705bfbeaa6 100644
--- a/apps/files_external/l10n/ar.js
+++ b/apps/files_external/l10n/ar.js
@@ -115,6 +115,10 @@ OC.L10N.register(
"External storage support" : "دعم التخزين الخارجي",
"Adds basic external storage support" : "يُضيف دعماً أساسيّاً للتخزين الخارجي",
"This application enables administrators to configure connections to external storage providers, such as FTP servers, S3 or SWIFT object stores, other Nextcloud servers, WebDAV servers, and more. Administration can choose which types of storage to enable and can mount these storage locations for an account, a group, or the entire system. Users will see a new folder appear in their root Nextcloud directory, which they can access and use like any other Nextcloud folder. External storage also allows people to share files stored in these external locations. In these cases, the credentials for the owner of the file are used when the recipient requests the file from external storage, thereby ensuring that the recipient can access the shared file.\n\nExternal storage can be configured using the GUI or at the command line. This second option provides the administration with more flexibility for configuring bulk external storage mounts and setting mount priorities. More information is available in the external storage GUI documentation and the external storage Configuration File documentation." : "يُمكّن هذا التطبيق المشرفين من تكوين الاتصالات بمُوفّري التخزين الخارجي؛ مثل خوادم FTP، ومخازن عناصر S3 أو SWIFT، و خوادم نكست الأخرى، و خوادم WebDAV و غيرها. يمكن للمشرفين اختيار أنواع التخزين التي يرغبون في تمكينها، ويمكنهم إمطاء mountg مواقع التخزين هذه لمستخدمٍ أو لمجموعة مستخدمين أو للنظام بأكمله. سيرى المستخدمون مُجلّدًا جديدًا يظهر في دليل نكست كلاود الجذري الخاص بهم والذي يمكنهم الوصول إليه واستخدامه مثل أي مجلد آخر من نكست كلاود. \nتتيح وحدة التخزين الخارجية أيضًا للمستخدمين مشاركة الملفات المُخزّنة في هذه المواقع الخارجية. في هذه الحالة، يتم استخدام حيثيات الدخول لمالك الملف عندما يطلب المستلم الملف من وحدة التخزين الخارجية؛ ممّا يضمن إمكانية وصول المستلم إلى الملف المشترك. \nيمكن تكوين التخزين الخارجي عن طريق واجهة المستخدم الرسومية أو عن طريق سطر الأوامر. يوفر الخيار الثاني للمستخدم المتقدم مزيدًا من المرونة لتكوين ممتطيات mounts لوحدات التخزين الخارجية بالجملة و تحديد أولويات الامتطاء. \nللمزيد من المعلومات، أنظر في توثيق واجهة المستخدم الرسومية للتخزين الخارجي، و توثيق تكوين وحدة التخزين الخارجية لتطبيق الملفات Files .",
+ "Storage credentials" : "حيثيّات وحدة التخزين",
+ "To access the storage, you need to provide the authentification informations." : "للوصول إلى وحدة التخزين، يتوجب عليك إعطاء بيانات التصديق.",
+ "Enter the storage login" : "التسجيل للدخول إلى وحدة التخزين",
+ "Enter the storage password" : "أدخِل كلمة المرور لوحدة التخزين",
"Submit" : "إرسال ",
"Unable to update this external storage config. {statusMessage}" : "تعذّر تحديث تهيئة وحدة التخزين الخارجية هذه. {statusMessage}",
"New configuration successfully saved" : "تمّ حفظ التهيئة الجديدة بنجاحٍ",
diff --git a/apps/files_external/l10n/ar.json b/apps/files_external/l10n/ar.json
index af764ec4d44..e13d35f1187 100644
--- a/apps/files_external/l10n/ar.json
+++ b/apps/files_external/l10n/ar.json
@@ -113,6 +113,10 @@
"External storage support" : "دعم التخزين الخارجي",
"Adds basic external storage support" : "يُضيف دعماً أساسيّاً للتخزين الخارجي",
"This application enables administrators to configure connections to external storage providers, such as FTP servers, S3 or SWIFT object stores, other Nextcloud servers, WebDAV servers, and more. Administration can choose which types of storage to enable and can mount these storage locations for an account, a group, or the entire system. Users will see a new folder appear in their root Nextcloud directory, which they can access and use like any other Nextcloud folder. External storage also allows people to share files stored in these external locations. In these cases, the credentials for the owner of the file are used when the recipient requests the file from external storage, thereby ensuring that the recipient can access the shared file.\n\nExternal storage can be configured using the GUI or at the command line. This second option provides the administration with more flexibility for configuring bulk external storage mounts and setting mount priorities. More information is available in the external storage GUI documentation and the external storage Configuration File documentation." : "يُمكّن هذا التطبيق المشرفين من تكوين الاتصالات بمُوفّري التخزين الخارجي؛ مثل خوادم FTP، ومخازن عناصر S3 أو SWIFT، و خوادم نكست الأخرى، و خوادم WebDAV و غيرها. يمكن للمشرفين اختيار أنواع التخزين التي يرغبون في تمكينها، ويمكنهم إمطاء mountg مواقع التخزين هذه لمستخدمٍ أو لمجموعة مستخدمين أو للنظام بأكمله. سيرى المستخدمون مُجلّدًا جديدًا يظهر في دليل نكست كلاود الجذري الخاص بهم والذي يمكنهم الوصول إليه واستخدامه مثل أي مجلد آخر من نكست كلاود. \nتتيح وحدة التخزين الخارجية أيضًا للمستخدمين مشاركة الملفات المُخزّنة في هذه المواقع الخارجية. في هذه الحالة، يتم استخدام حيثيات الدخول لمالك الملف عندما يطلب المستلم الملف من وحدة التخزين الخارجية؛ ممّا يضمن إمكانية وصول المستلم إلى الملف المشترك. \nيمكن تكوين التخزين الخارجي عن طريق واجهة المستخدم الرسومية أو عن طريق سطر الأوامر. يوفر الخيار الثاني للمستخدم المتقدم مزيدًا من المرونة لتكوين ممتطيات mounts لوحدات التخزين الخارجية بالجملة و تحديد أولويات الامتطاء. \nللمزيد من المعلومات، أنظر في توثيق واجهة المستخدم الرسومية للتخزين الخارجي، و توثيق تكوين وحدة التخزين الخارجية لتطبيق الملفات Files .",
+ "Storage credentials" : "حيثيّات وحدة التخزين",
+ "To access the storage, you need to provide the authentification informations." : "للوصول إلى وحدة التخزين، يتوجب عليك إعطاء بيانات التصديق.",
+ "Enter the storage login" : "التسجيل للدخول إلى وحدة التخزين",
+ "Enter the storage password" : "أدخِل كلمة المرور لوحدة التخزين",
"Submit" : "إرسال ",
"Unable to update this external storage config. {statusMessage}" : "تعذّر تحديث تهيئة وحدة التخزين الخارجية هذه. {statusMessage}",
"New configuration successfully saved" : "تمّ حفظ التهيئة الجديدة بنجاحٍ",
diff --git a/apps/files_external/l10n/de_DE.js b/apps/files_external/l10n/de_DE.js
index 679b9d47de1..ddf3cfbba1e 100644
--- a/apps/files_external/l10n/de_DE.js
+++ b/apps/files_external/l10n/de_DE.js
@@ -116,7 +116,7 @@ OC.L10N.register(
"Adds basic external storage support" : "Fügt grundlegende Unterstützung für externen Speicher hinzu",
"This application enables administrators to configure connections to external storage providers, such as FTP servers, S3 or SWIFT object stores, other Nextcloud servers, WebDAV servers, and more. Administration can choose which types of storage to enable and can mount these storage locations for an account, a group, or the entire system. Users will see a new folder appear in their root Nextcloud directory, which they can access and use like any other Nextcloud folder. External storage also allows people to share files stored in these external locations. In these cases, the credentials for the owner of the file are used when the recipient requests the file from external storage, thereby ensuring that the recipient can access the shared file.\n\nExternal storage can be configured using the GUI or at the command line. This second option provides the administration with more flexibility for configuring bulk external storage mounts and setting mount priorities. More information is available in the external storage GUI documentation and the external storage Configuration File documentation." : "Diese Anwendung ermöglicht es Administratoren, Verbindungen zu externen Speicheranbietern wie FTP-Servern, S3- oder SWIFT-Objektspeichern, anderen Nextcloud-Servern, WebDAV-Servern und weiteren zu konfigurieren. Die Administration kann auswählen, welche Arten von Speicherorten aktiviert werden sollen, und kann diese Speicherorte für ein Konto, eine Gruppe oder das gesamte System einbinden. Benutzer sehen einen neuen Ordner in ihrem Nextcloud-Root-Verzeichnis, auf den sie wie auf jeden anderen Nextcloud-Ordner zugreifen und ihn verwenden können. Externer Speicher ermöglicht es Personen auch, Dateien, die in diesen externen Speicherorten gespeichert sind, freizugeben. In diesen Fällen werden die Anmeldeinformationen des Dateibesitzers verwendet, wenn der Empfänger die Datei aus dem externen Speicher anfordert, um sicherzustellen, dass der Empfänger auf die freigegebene Datei zugreifen kann.\n\nExterner Speicher kann über die grafische Benutzeroberfläche oder über die Befehlszeile konfiguriert werden. Diese zweite Option bietet der Administration mehr Flexibilität bei der Konfiguration von Massenspeicher-Einhängepunkten und der Festlegung von Einhängeprioritäten. Weitere Informationen finden Sie in der Dokumentation zur externen Speicher-GUI und der Dokumentation zur externen Speicher-Konfigurationsdatei.",
"Storage credentials" : "Speicheranmeldeinformationen",
- "To access the storage, you need to provide the authentification informations." : "Um auf den Speicher zuzugreifen, müssen Sie die Authentifizierungsinformationen angeben.",
+ "To access the storage, you need to provide the authentification informations." : "Um auf den Speicher zuzugreifen, müssen Sie die Authentifizierungsinformationen eingeben.",
"Enter the storage login" : "Speicher-Login eingeben",
"Enter the storage password" : "Speicher-Passwort eingeben",
"Submit" : "Übermitteln",
diff --git a/apps/files_external/l10n/de_DE.json b/apps/files_external/l10n/de_DE.json
index 4ce748323f4..bc3b8ed657d 100644
--- a/apps/files_external/l10n/de_DE.json
+++ b/apps/files_external/l10n/de_DE.json
@@ -114,7 +114,7 @@
"Adds basic external storage support" : "Fügt grundlegende Unterstützung für externen Speicher hinzu",
"This application enables administrators to configure connections to external storage providers, such as FTP servers, S3 or SWIFT object stores, other Nextcloud servers, WebDAV servers, and more. Administration can choose which types of storage to enable and can mount these storage locations for an account, a group, or the entire system. Users will see a new folder appear in their root Nextcloud directory, which they can access and use like any other Nextcloud folder. External storage also allows people to share files stored in these external locations. In these cases, the credentials for the owner of the file are used when the recipient requests the file from external storage, thereby ensuring that the recipient can access the shared file.\n\nExternal storage can be configured using the GUI or at the command line. This second option provides the administration with more flexibility for configuring bulk external storage mounts and setting mount priorities. More information is available in the external storage GUI documentation and the external storage Configuration File documentation." : "Diese Anwendung ermöglicht es Administratoren, Verbindungen zu externen Speicheranbietern wie FTP-Servern, S3- oder SWIFT-Objektspeichern, anderen Nextcloud-Servern, WebDAV-Servern und weiteren zu konfigurieren. Die Administration kann auswählen, welche Arten von Speicherorten aktiviert werden sollen, und kann diese Speicherorte für ein Konto, eine Gruppe oder das gesamte System einbinden. Benutzer sehen einen neuen Ordner in ihrem Nextcloud-Root-Verzeichnis, auf den sie wie auf jeden anderen Nextcloud-Ordner zugreifen und ihn verwenden können. Externer Speicher ermöglicht es Personen auch, Dateien, die in diesen externen Speicherorten gespeichert sind, freizugeben. In diesen Fällen werden die Anmeldeinformationen des Dateibesitzers verwendet, wenn der Empfänger die Datei aus dem externen Speicher anfordert, um sicherzustellen, dass der Empfänger auf die freigegebene Datei zugreifen kann.\n\nExterner Speicher kann über die grafische Benutzeroberfläche oder über die Befehlszeile konfiguriert werden. Diese zweite Option bietet der Administration mehr Flexibilität bei der Konfiguration von Massenspeicher-Einhängepunkten und der Festlegung von Einhängeprioritäten. Weitere Informationen finden Sie in der Dokumentation zur externen Speicher-GUI und der Dokumentation zur externen Speicher-Konfigurationsdatei.",
"Storage credentials" : "Speicheranmeldeinformationen",
- "To access the storage, you need to provide the authentification informations." : "Um auf den Speicher zuzugreifen, müssen Sie die Authentifizierungsinformationen angeben.",
+ "To access the storage, you need to provide the authentification informations." : "Um auf den Speicher zuzugreifen, müssen Sie die Authentifizierungsinformationen eingeben.",
"Enter the storage login" : "Speicher-Login eingeben",
"Enter the storage password" : "Speicher-Passwort eingeben",
"Submit" : "Übermitteln",
diff --git a/apps/files_external/l10n/pt_BR.js b/apps/files_external/l10n/pt_BR.js
index d3f69d77357..7a2dd264462 100644
--- a/apps/files_external/l10n/pt_BR.js
+++ b/apps/files_external/l10n/pt_BR.js
@@ -18,6 +18,7 @@ OC.L10N.register(
"Once every direct access" : "Uma vez a cada acesso direto",
"Read only" : "Somente leitura",
"Disconnect" : "Desconectar",
+ "Unknown backend: {backendName}" : "Backend desconhecido: {backendName}",
"Admin defined" : "Definido pelo administrador",
"Automatic status checking is disabled due to the large number of configured storages, click to check status" : "A verificação automática de status está desabilitada devido ao grande número de armazenamentos configurados, clique para verificar o status",
"Are you sure you want to disconnect this external storage? It will make the storage unavailable in Nextcloud and will lead to a deletion of these files and folders on any sync client that is currently connected but will not delete any files and folders on the external storage itself." : "Tem certeza de que deseja desconectar este armazenamento externo? Isso tornará o armazenamento indisponível no Nextcloud e levará à exclusão desses arquivos e pastas em qualquer cliente de sincronização que esteja conectado no momento, mas não excluirá nenhum arquivo e pasta no próprio armazenamento externo.",
@@ -114,6 +115,10 @@ OC.L10N.register(
"External storage support" : "Suporte a armazenamento externo",
"Adds basic external storage support" : "Adiciona suporte básico para armazenamento externo",
"This application enables administrators to configure connections to external storage providers, such as FTP servers, S3 or SWIFT object stores, other Nextcloud servers, WebDAV servers, and more. Administration can choose which types of storage to enable and can mount these storage locations for an account, a group, or the entire system. Users will see a new folder appear in their root Nextcloud directory, which they can access and use like any other Nextcloud folder. External storage also allows people to share files stored in these external locations. In these cases, the credentials for the owner of the file are used when the recipient requests the file from external storage, thereby ensuring that the recipient can access the shared file.\n\nExternal storage can be configured using the GUI or at the command line. This second option provides the administration with more flexibility for configuring bulk external storage mounts and setting mount priorities. More information is available in the external storage GUI documentation and the external storage Configuration File documentation." : "Este aplicativo permite que os administradores configurem conexões com provedores de armazenamento externos, como servidores FTP, armazenamentos de objetos S3 ou SWIFT, outros servidores Nextcloud, servidores WebDAV e muito mais. A administração pode escolher quais tipos de armazenamento ativar e pode montar esses locais de armazenamento para uma conta, um grupo ou todo o sistema. Os usuários verão uma nova pasta aparecer em seu diretório raiz Nextcloud, que eles podem acessar e usar como qualquer outra pasta Nextcloud. O armazenamento externo também permite que as pessoas compartilhem arquivos armazenados nesses locais externos. Nesses casos, as credenciais do proprietário do arquivo são usadas quando o destinatário solicita o arquivo do armazenamento externo, garantindo assim que o destinatário possa acessar o arquivo compartilhado. \n\nO armazenamento externo pode ser configurado usando a GUI ou na linha de comando. Esta segunda opção fornece à administração mais flexibilidade para configurar montagens de armazenamento externo em massa e definir prioridades de montagem. Mais informações estão disponíveis na documentação da GUI de armazenamento externo e na documentação do arquivo de configuração de armazenamento externo.",
+ "Storage credentials" : "Credenciais de armazenamento",
+ "To access the storage, you need to provide the authentification informations." : "Para acessar o armazenamento, você precisa fornecer as informações de autenticação.",
+ "Enter the storage login" : "Digite o login de armazenamento",
+ "Enter the storage password" : "Digite a senha de armazenamento",
"Submit" : "Enviar",
"Unable to update this external storage config. {statusMessage}" : "Não é possível atualizar esta configuração de armazenamento externo. {statusMessage}",
"New configuration successfully saved" : "Nova configuração salva com sucesso",
diff --git a/apps/files_external/l10n/pt_BR.json b/apps/files_external/l10n/pt_BR.json
index b5dcaf17c52..b8e266e3ffd 100644
--- a/apps/files_external/l10n/pt_BR.json
+++ b/apps/files_external/l10n/pt_BR.json
@@ -16,6 +16,7 @@
"Once every direct access" : "Uma vez a cada acesso direto",
"Read only" : "Somente leitura",
"Disconnect" : "Desconectar",
+ "Unknown backend: {backendName}" : "Backend desconhecido: {backendName}",
"Admin defined" : "Definido pelo administrador",
"Automatic status checking is disabled due to the large number of configured storages, click to check status" : "A verificação automática de status está desabilitada devido ao grande número de armazenamentos configurados, clique para verificar o status",
"Are you sure you want to disconnect this external storage? It will make the storage unavailable in Nextcloud and will lead to a deletion of these files and folders on any sync client that is currently connected but will not delete any files and folders on the external storage itself." : "Tem certeza de que deseja desconectar este armazenamento externo? Isso tornará o armazenamento indisponível no Nextcloud e levará à exclusão desses arquivos e pastas em qualquer cliente de sincronização que esteja conectado no momento, mas não excluirá nenhum arquivo e pasta no próprio armazenamento externo.",
@@ -112,6 +113,10 @@
"External storage support" : "Suporte a armazenamento externo",
"Adds basic external storage support" : "Adiciona suporte básico para armazenamento externo",
"This application enables administrators to configure connections to external storage providers, such as FTP servers, S3 or SWIFT object stores, other Nextcloud servers, WebDAV servers, and more. Administration can choose which types of storage to enable and can mount these storage locations for an account, a group, or the entire system. Users will see a new folder appear in their root Nextcloud directory, which they can access and use like any other Nextcloud folder. External storage also allows people to share files stored in these external locations. In these cases, the credentials for the owner of the file are used when the recipient requests the file from external storage, thereby ensuring that the recipient can access the shared file.\n\nExternal storage can be configured using the GUI or at the command line. This second option provides the administration with more flexibility for configuring bulk external storage mounts and setting mount priorities. More information is available in the external storage GUI documentation and the external storage Configuration File documentation." : "Este aplicativo permite que os administradores configurem conexões com provedores de armazenamento externos, como servidores FTP, armazenamentos de objetos S3 ou SWIFT, outros servidores Nextcloud, servidores WebDAV e muito mais. A administração pode escolher quais tipos de armazenamento ativar e pode montar esses locais de armazenamento para uma conta, um grupo ou todo o sistema. Os usuários verão uma nova pasta aparecer em seu diretório raiz Nextcloud, que eles podem acessar e usar como qualquer outra pasta Nextcloud. O armazenamento externo também permite que as pessoas compartilhem arquivos armazenados nesses locais externos. Nesses casos, as credenciais do proprietário do arquivo são usadas quando o destinatário solicita o arquivo do armazenamento externo, garantindo assim que o destinatário possa acessar o arquivo compartilhado. \n\nO armazenamento externo pode ser configurado usando a GUI ou na linha de comando. Esta segunda opção fornece à administração mais flexibilidade para configurar montagens de armazenamento externo em massa e definir prioridades de montagem. Mais informações estão disponíveis na documentação da GUI de armazenamento externo e na documentação do arquivo de configuração de armazenamento externo.",
+ "Storage credentials" : "Credenciais de armazenamento",
+ "To access the storage, you need to provide the authentification informations." : "Para acessar o armazenamento, você precisa fornecer as informações de autenticação.",
+ "Enter the storage login" : "Digite o login de armazenamento",
+ "Enter the storage password" : "Digite a senha de armazenamento",
"Submit" : "Enviar",
"Unable to update this external storage config. {statusMessage}" : "Não é possível atualizar esta configuração de armazenamento externo. {statusMessage}",
"New configuration successfully saved" : "Nova configuração salva com sucesso",
diff --git a/apps/files_external/lib/Controller/StoragesController.php b/apps/files_external/lib/Controller/StoragesController.php
index fd004b49b37..ab580987b0e 100644
--- a/apps/files_external/lib/Controller/StoragesController.php
+++ b/apps/files_external/lib/Controller/StoragesController.php
@@ -228,7 +228,7 @@ abstract class StoragesController extends Controller {
)
);
} catch (InsufficientDataForMeaningfulAnswerException $e) {
- $status = $e->getCode() ? $e->getCode() : StorageNotAvailableException::STATUS_INDETERMINATE;
+ $status = $e->getCode() ?: StorageNotAvailableException::STATUS_INDETERMINATE;
$storage->setStatus(
(int)$status,
$this->l10n->t('Insufficient data: %s', [$e->getMessage()])
diff --git a/apps/files_external/tests/Auth/AuthMechanismTest.php b/apps/files_external/tests/Auth/AuthMechanismTest.php
index 3297d93fe94..682d2e1326f 100644
--- a/apps/files_external/tests/Auth/AuthMechanismTest.php
+++ b/apps/files_external/tests/Auth/AuthMechanismTest.php
@@ -11,7 +11,7 @@ use OCA\Files_External\Lib\Backend\Backend;
use OCA\Files_External\Lib\StorageConfig;
class AuthMechanismTest extends \Test\TestCase {
- public function testJsonSerialization() {
+ public function testJsonSerialization(): void {
$mechanism = $this->getMockBuilder(AuthMechanism::class)
->setMethods(['jsonSerializeDefinition'])
->getMock();
@@ -38,7 +38,7 @@ class AuthMechanismTest extends \Test\TestCase {
/**
* @dataProvider validateStorageProvider
*/
- public function testValidateStorage($expectedSuccess, $scheme, $definitionSuccess) {
+ public function testValidateStorage($expectedSuccess, $scheme, $definitionSuccess): void {
$mechanism = $this->getMockBuilder(AuthMechanism::class)
->setMethods(['validateStorageDefinition'])
->getMock();
diff --git a/apps/files_external/tests/Auth/Password/GlobalAuth.php b/apps/files_external/tests/Auth/Password/GlobalAuth.php
index 85a2c1fb27c..9f7aa0ef03a 100644
--- a/apps/files_external/tests/Auth/Password/GlobalAuth.php
+++ b/apps/files_external/tests/Auth/Password/GlobalAuth.php
@@ -60,7 +60,7 @@ class GlobalAuthTest extends TestCase {
return $storageConfig;
}
- public function testNoCredentials() {
+ public function testNoCredentials(): void {
$this->credentialsManager->expects($this->once())
->method('retrieve')
->willReturn(null);
@@ -71,7 +71,7 @@ class GlobalAuthTest extends TestCase {
$this->assertEquals([], $storage->getBackendOptions());
}
- public function testSavedCredentials() {
+ public function testSavedCredentials(): void {
$this->credentialsManager->expects($this->once())
->method('retrieve')
->willReturn([
@@ -89,7 +89,7 @@ class GlobalAuthTest extends TestCase {
}
- public function testNoCredentialsPersonal() {
+ public function testNoCredentialsPersonal(): void {
$this->expectException(\OCA\Files_External\Lib\InsufficientDataForMeaningfulAnswerException::class);
$this->credentialsManager->expects($this->never())
diff --git a/apps/files_external/tests/Backend/BackendTest.php b/apps/files_external/tests/Backend/BackendTest.php
index 771c053982c..26aa5ebe6af 100644
--- a/apps/files_external/tests/Backend/BackendTest.php
+++ b/apps/files_external/tests/Backend/BackendTest.php
@@ -10,7 +10,7 @@ use OCA\Files_External\Lib\Backend\Backend;
use OCA\Files_External\Lib\StorageConfig;
class BackendTest extends \Test\TestCase {
- public function testJsonSerialization() {
+ public function testJsonSerialization(): void {
$backend = $this->getMockBuilder(Backend::class)
->setMethods(['jsonSerializeDefinition'])
->getMock();
@@ -42,7 +42,7 @@ class BackendTest extends \Test\TestCase {
/**
* @dataProvider validateStorageProvider
*/
- public function testValidateStorage($expectedSuccess, $definitionSuccess) {
+ public function testValidateStorage($expectedSuccess, $definitionSuccess): void {
$backend = $this->getMockBuilder(Backend::class)
->setMethods(['validateStorageDefinition'])
->getMock();
@@ -57,7 +57,7 @@ class BackendTest extends \Test\TestCase {
$this->assertEquals($expectedSuccess, $backend->validateStorage($storageConfig));
}
- public function testLegacyAuthMechanismCallback() {
+ public function testLegacyAuthMechanismCallback(): void {
$backend = new Backend();
$backend->setLegacyAuthMechanismCallback(function (array $params) {
if (isset($params['ping'])) {
diff --git a/apps/files_external/tests/Backend/LegacyBackendTest.php b/apps/files_external/tests/Backend/LegacyBackendTest.php
index 44aa4c32d18..cc3a32d65b0 100644
--- a/apps/files_external/tests/Backend/LegacyBackendTest.php
+++ b/apps/files_external/tests/Backend/LegacyBackendTest.php
@@ -1,97 +1,97 @@
-<?php
-/**
- * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
- * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
- * SPDX-License-Identifier: AGPL-3.0-only
- */
-namespace OCA\Files_External\Tests\Backend;
-
-use OCA\Files_External\Lib\Backend\LegacyBackend;
-use OCA\Files_External\Lib\DefinitionParameter;
-use OCA\Files_External\Lib\MissingDependency;
-
-class LegacyBackendTest extends \Test\TestCase {
-
- /**
- * @return MissingDependency[]
- */
- public static function checkDependencies() {
- return [
- (new MissingDependency('abc'))->setMessage('foobar')
- ];
- }
-
- public function testConstructor() {
- $auth = $this->getMockBuilder(\OCA\Files_External\Lib\Auth\Builtin::class)
- ->disableOriginalConstructor()
- ->getMock();
-
- $class = \OCA\Files_External\Tests\Backend\LegacyBackendTest::class;
- $definition = [
- 'configuration' => [
- 'textfield' => 'Text field',
- 'passwordfield' => '*Password field',
- 'checkbox' => '!Checkbox',
- 'hiddenfield' => '#Hidden field',
- 'optionaltext' => '&Optional text field',
- 'optionalpassword' => '&*Optional password field',
- ],
- 'backend' => 'Backend text',
- 'priority' => 123,
- 'custom' => 'foo/bar.js',
- 'has_dependencies' => true,
- ];
-
- $backend = new LegacyBackend($class, $definition, $auth);
-
- $this->assertEquals(\OCA\Files_External\Tests\Backend\LegacyBackendTest::class, $backend->getStorageClass());
- $this->assertEquals('Backend text', $backend->getText());
- $this->assertEquals(123, $backend->getPriority());
- $this->assertContains('foo/bar.js', $backend->getCustomJs());
- $this->assertArrayHasKey('builtin', $backend->getAuthSchemes());
- $this->assertEquals($auth, $backend->getLegacyAuthMechanism());
-
- $dependencies = $backend->checkDependencies();
- $this->assertCount(1, $dependencies);
- $this->assertEquals('abc', $dependencies[0]->getDependency());
- $this->assertEquals('foobar', $dependencies[0]->getMessage());
-
- $parameters = $backend->getParameters();
- $this->assertEquals('Text field', $parameters['textfield']->getText());
- $this->assertEquals(DefinitionParameter::VALUE_TEXT, $parameters['textfield']->getType());
- $this->assertEquals(DefinitionParameter::FLAG_NONE, $parameters['textfield']->getFlags());
- $this->assertEquals('Password field', $parameters['passwordfield']->getText());
- $this->assertEquals(DefinitionParameter::VALUE_PASSWORD, $parameters['passwordfield']->getType());
- $this->assertEquals(DefinitionParameter::FLAG_NONE, $parameters['passwordfield']->getFlags());
- $this->assertEquals('Checkbox', $parameters['checkbox']->getText());
- $this->assertEquals(DefinitionParameter::VALUE_BOOLEAN, $parameters['checkbox']->getType());
- $this->assertEquals(DefinitionParameter::FLAG_NONE, $parameters['checkbox']->getFlags());
- $this->assertEquals('Hidden field', $parameters['hiddenfield']->getText());
- $this->assertEquals(DefinitionParameter::VALUE_HIDDEN, $parameters['hiddenfield']->getType());
- $this->assertEquals(DefinitionParameter::FLAG_NONE, $parameters['hiddenfield']->getFlags());
- $this->assertEquals('Optional text field', $parameters['optionaltext']->getText());
- $this->assertEquals(DefinitionParameter::VALUE_TEXT, $parameters['optionaltext']->getType());
- $this->assertEquals(DefinitionParameter::FLAG_OPTIONAL, $parameters['optionaltext']->getFlags());
- $this->assertEquals('Optional password field', $parameters['optionalpassword']->getText());
- $this->assertEquals(DefinitionParameter::VALUE_PASSWORD, $parameters['optionalpassword']->getType());
- $this->assertEquals(DefinitionParameter::FLAG_OPTIONAL, $parameters['optionalpassword']->getFlags());
- }
-
- public function testNoDependencies() {
- $auth = $this->getMockBuilder(\OCA\Files_External\Lib\Auth\Builtin::class)
- ->disableOriginalConstructor()
- ->getMock();
-
- $class = \OCA\Files_External\Tests\Backend\LegacyBackendTest::class;
- $definition = [
- 'configuration' => [
- ],
- 'backend' => 'Backend text',
- ];
-
- $backend = new LegacyBackend($class, $definition, $auth);
-
- $dependencies = $backend->checkDependencies();
- $this->assertCount(0, $dependencies);
- }
-}
+<?php
+/**
+ * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
+ */
+namespace OCA\Files_External\Tests\Backend;
+
+use OCA\Files_External\Lib\Backend\LegacyBackend;
+use OCA\Files_External\Lib\DefinitionParameter;
+use OCA\Files_External\Lib\MissingDependency;
+
+class LegacyBackendTest extends \Test\TestCase {
+
+ /**
+ * @return MissingDependency[]
+ */
+ public static function checkDependencies() {
+ return [
+ (new MissingDependency('abc'))->setMessage('foobar')
+ ];
+ }
+
+ public function testConstructor(): void {
+ $auth = $this->getMockBuilder(\OCA\Files_External\Lib\Auth\Builtin::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $class = \OCA\Files_External\Tests\Backend\LegacyBackendTest::class;
+ $definition = [
+ 'configuration' => [
+ 'textfield' => 'Text field',
+ 'passwordfield' => '*Password field',
+ 'checkbox' => '!Checkbox',
+ 'hiddenfield' => '#Hidden field',
+ 'optionaltext' => '&Optional text field',
+ 'optionalpassword' => '&*Optional password field',
+ ],
+ 'backend' => 'Backend text',
+ 'priority' => 123,
+ 'custom' => 'foo/bar.js',
+ 'has_dependencies' => true,
+ ];
+
+ $backend = new LegacyBackend($class, $definition, $auth);
+
+ $this->assertEquals(\OCA\Files_External\Tests\Backend\LegacyBackendTest::class, $backend->getStorageClass());
+ $this->assertEquals('Backend text', $backend->getText());
+ $this->assertEquals(123, $backend->getPriority());
+ $this->assertContains('foo/bar.js', $backend->getCustomJs());
+ $this->assertArrayHasKey('builtin', $backend->getAuthSchemes());
+ $this->assertEquals($auth, $backend->getLegacyAuthMechanism());
+
+ $dependencies = $backend->checkDependencies();
+ $this->assertCount(1, $dependencies);
+ $this->assertEquals('abc', $dependencies[0]->getDependency());
+ $this->assertEquals('foobar', $dependencies[0]->getMessage());
+
+ $parameters = $backend->getParameters();
+ $this->assertEquals('Text field', $parameters['textfield']->getText());
+ $this->assertEquals(DefinitionParameter::VALUE_TEXT, $parameters['textfield']->getType());
+ $this->assertEquals(DefinitionParameter::FLAG_NONE, $parameters['textfield']->getFlags());
+ $this->assertEquals('Password field', $parameters['passwordfield']->getText());
+ $this->assertEquals(DefinitionParameter::VALUE_PASSWORD, $parameters['passwordfield']->getType());
+ $this->assertEquals(DefinitionParameter::FLAG_NONE, $parameters['passwordfield']->getFlags());
+ $this->assertEquals('Checkbox', $parameters['checkbox']->getText());
+ $this->assertEquals(DefinitionParameter::VALUE_BOOLEAN, $parameters['checkbox']->getType());
+ $this->assertEquals(DefinitionParameter::FLAG_NONE, $parameters['checkbox']->getFlags());
+ $this->assertEquals('Hidden field', $parameters['hiddenfield']->getText());
+ $this->assertEquals(DefinitionParameter::VALUE_HIDDEN, $parameters['hiddenfield']->getType());
+ $this->assertEquals(DefinitionParameter::FLAG_NONE, $parameters['hiddenfield']->getFlags());
+ $this->assertEquals('Optional text field', $parameters['optionaltext']->getText());
+ $this->assertEquals(DefinitionParameter::VALUE_TEXT, $parameters['optionaltext']->getType());
+ $this->assertEquals(DefinitionParameter::FLAG_OPTIONAL, $parameters['optionaltext']->getFlags());
+ $this->assertEquals('Optional password field', $parameters['optionalpassword']->getText());
+ $this->assertEquals(DefinitionParameter::VALUE_PASSWORD, $parameters['optionalpassword']->getType());
+ $this->assertEquals(DefinitionParameter::FLAG_OPTIONAL, $parameters['optionalpassword']->getFlags());
+ }
+
+ public function testNoDependencies(): void {
+ $auth = $this->getMockBuilder(\OCA\Files_External\Lib\Auth\Builtin::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $class = \OCA\Files_External\Tests\Backend\LegacyBackendTest::class;
+ $definition = [
+ 'configuration' => [
+ ],
+ 'backend' => 'Backend text',
+ ];
+
+ $backend = new LegacyBackend($class, $definition, $auth);
+
+ $dependencies = $backend->checkDependencies();
+ $this->assertCount(0, $dependencies);
+ }
+}
diff --git a/apps/files_external/tests/Command/ApplicableTest.php b/apps/files_external/tests/Command/ApplicableTest.php
index d4caadad343..223b02706e5 100644
--- a/apps/files_external/tests/Command/ApplicableTest.php
+++ b/apps/files_external/tests/Command/ApplicableTest.php
@@ -28,7 +28,7 @@ class ApplicableTest extends CommandTest {
return new Applicable($storageService, $userManager, $groupManager);
}
- public function testListEmpty() {
+ public function testListEmpty(): void {
$mount = $this->getMount(1, '', '');
$storageService = $this->getGlobalStorageService([$mount]);
@@ -45,7 +45,7 @@ class ApplicableTest extends CommandTest {
$this->assertEquals(['users' => [], 'groups' => []], $result);
}
- public function testList() {
+ public function testList(): void {
$mount = $this->getMount(1, '', '', '', [], [], ['test', 'asd']);
$storageService = $this->getGlobalStorageService([$mount]);
@@ -62,7 +62,7 @@ class ApplicableTest extends CommandTest {
$this->assertEquals(['users' => ['test', 'asd'], 'groups' => []], $result);
}
- public function testAddSingle() {
+ public function testAddSingle(): void {
$mount = $this->getMount(1, '', '', '', [], [], []);
$storageService = $this->getGlobalStorageService([$mount]);
@@ -80,7 +80,7 @@ class ApplicableTest extends CommandTest {
$this->assertEquals(['foo'], $mount->getApplicableUsers());
}
- public function testAddDuplicate() {
+ public function testAddDuplicate(): void {
$mount = $this->getMount(1, '', '', '', [], [], ['foo']);
$storageService = $this->getGlobalStorageService([$mount]);
@@ -98,7 +98,7 @@ class ApplicableTest extends CommandTest {
$this->assertEquals(['foo', 'bar'], $mount->getApplicableUsers());
}
- public function testRemoveSingle() {
+ public function testRemoveSingle(): void {
$mount = $this->getMount(1, '', '', '', [], [], ['foo', 'bar']);
$storageService = $this->getGlobalStorageService([$mount]);
@@ -116,7 +116,7 @@ class ApplicableTest extends CommandTest {
$this->assertEquals(['foo'], $mount->getApplicableUsers());
}
- public function testRemoveNonExisting() {
+ public function testRemoveNonExisting(): void {
$mount = $this->getMount(1, '', '', '', [], [], ['foo', 'bar']);
$storageService = $this->getGlobalStorageService([$mount]);
@@ -134,7 +134,7 @@ class ApplicableTest extends CommandTest {
$this->assertEquals(['foo'], $mount->getApplicableUsers());
}
- public function testRemoveAddRemove() {
+ public function testRemoveAddRemove(): void {
$mount = $this->getMount(1, '', '', '', [], [], ['foo', 'bar']);
$storageService = $this->getGlobalStorageService([$mount]);
diff --git a/apps/files_external/tests/Command/ListCommandTest.php b/apps/files_external/tests/Command/ListCommandTest.php
index 8375ba89f2a..bd4430b4116 100644
--- a/apps/files_external/tests/Command/ListCommandTest.php
+++ b/apps/files_external/tests/Command/ListCommandTest.php
@@ -39,7 +39,7 @@ class ListCommandTest extends CommandTest {
return new ListCommand($globalService, $userService, $userSession, $userManager);
}
- public function testListAuthIdentifier() {
+ public function testListAuthIdentifier(): void {
$l10n = $this->createMock(IL10N::class);
$session = $this->createMock(ISession::class);
$crypto = $this->createMock(ICrypto::class);
diff --git a/apps/files_external/tests/Config/UserPlaceholderHandlerTest.php b/apps/files_external/tests/Config/UserPlaceholderHandlerTest.php
index 767ae04fc79..b3c7db9306f 100644
--- a/apps/files_external/tests/Config/UserPlaceholderHandlerTest.php
+++ b/apps/files_external/tests/Config/UserPlaceholderHandlerTest.php
@@ -64,7 +64,7 @@ class UserPlaceholderHandlerTest extends \Test\TestCase {
/**
* @dataProvider optionProvider
*/
- public function testHandle($option, $expected) {
+ public function testHandle($option, $expected): void {
$this->setUser();
$this->assertSame($expected, $this->handler->handle($option));
}
@@ -72,7 +72,7 @@ class UserPlaceholderHandlerTest extends \Test\TestCase {
/**
* @dataProvider optionProvider
*/
- public function testHandleNoUser($option) {
+ public function testHandleNoUser($option): void {
$this->shareManager->expects($this->once())
->method('getShareByToken')
->willThrowException(new ShareNotFound());
diff --git a/apps/files_external/tests/Controller/AjaxControllerTest.php b/apps/files_external/tests/Controller/AjaxControllerTest.php
index 8b233903b75..100c9770058 100644
--- a/apps/files_external/tests/Controller/AjaxControllerTest.php
+++ b/apps/files_external/tests/Controller/AjaxControllerTest.php
@@ -52,7 +52,7 @@ class AjaxControllerTest extends TestCase {
parent::setUp();
}
- public function testGetSshKeys() {
+ public function testGetSshKeys(): void {
$this->rsa
->expects($this->once())
->method('createKey')
@@ -73,7 +73,7 @@ class AjaxControllerTest extends TestCase {
$this->assertEquals($expected, $this->ajaxController->getSshKeys());
}
- public function testSaveGlobalCredentialsAsAdminForAnotherUser() {
+ public function testSaveGlobalCredentialsAsAdminForAnotherUser(): void {
$user = $this->createMock(IUser::class);
$user
->expects($this->once())
@@ -90,7 +90,7 @@ class AjaxControllerTest extends TestCase {
$this->assertSame(false, $this->ajaxController->saveGlobalCredentials('UidOfTestUser', 'test', 'password'));
}
- public function testSaveGlobalCredentialsAsAdminForSelf() {
+ public function testSaveGlobalCredentialsAsAdminForSelf(): void {
$user = $this->createMock(IUser::class);
$user
->expects($this->once())
@@ -108,7 +108,7 @@ class AjaxControllerTest extends TestCase {
$this->assertSame(true, $this->ajaxController->saveGlobalCredentials('MyAdminUid', 'test', 'password'));
}
- public function testSaveGlobalCredentialsAsNormalUserForSelf() {
+ public function testSaveGlobalCredentialsAsNormalUserForSelf(): void {
$user = $this->createMock(IUser::class);
$user
->method('getUID')
@@ -123,7 +123,7 @@ class AjaxControllerTest extends TestCase {
$this->assertSame(true, $this->ajaxController->saveGlobalCredentials('MyUserUid', 'test', 'password'));
}
- public function testSaveGlobalCredentialsAsNormalUserForAnotherUser() {
+ public function testSaveGlobalCredentialsAsNormalUserForAnotherUser(): void {
$user = $this->createMock(IUser::class);
$user
->method('getUID')
diff --git a/apps/files_external/tests/Controller/GlobalStoragesControllerTest.php b/apps/files_external/tests/Controller/GlobalStoragesControllerTest.php
index 6b1beca5374..cf2ef83a9c6 100644
--- a/apps/files_external/tests/Controller/GlobalStoragesControllerTest.php
+++ b/apps/files_external/tests/Controller/GlobalStoragesControllerTest.php
@@ -53,7 +53,7 @@ class GlobalStoragesControllerTest extends StoragesControllerTest {
);
}
- public function testAddLocalStorageWhenDisabled() {
+ public function testAddLocalStorageWhenDisabled(): void {
$this->controller = $this->createController(false);
parent::testAddLocalStorageWhenDisabled();
}
diff --git a/apps/files_external/tests/Controller/StoragesControllerTest.php b/apps/files_external/tests/Controller/StoragesControllerTest.php
index d716a006e0e..d8c00b7bcc2 100644
--- a/apps/files_external/tests/Controller/StoragesControllerTest.php
+++ b/apps/files_external/tests/Controller/StoragesControllerTest.php
@@ -70,7 +70,7 @@ abstract class StoragesControllerTest extends \Test\TestCase {
return $authMech;
}
- public function testAddStorage() {
+ public function testAddStorage(): void {
$authMech = $this->getAuthMechMock();
$authMech->method('validateStorage')
->willReturn(true);
@@ -111,7 +111,7 @@ abstract class StoragesControllerTest extends \Test\TestCase {
$this->assertEquals($storageConfig->jsonSerialize(), $data);
}
- public function testAddLocalStorageWhenDisabled() {
+ public function testAddLocalStorageWhenDisabled(): void {
$authMech = $this->getAuthMechMock();
$backend = $this->getBackendMock();
@@ -141,7 +141,7 @@ abstract class StoragesControllerTest extends \Test\TestCase {
$this->assertEquals(Http::STATUS_FORBIDDEN, $response->getStatus());
}
- public function testUpdateStorage() {
+ public function testUpdateStorage(): void {
$authMech = $this->getAuthMechMock();
$authMech->method('validateStorage')
->willReturn(true);
@@ -194,7 +194,7 @@ abstract class StoragesControllerTest extends \Test\TestCase {
/**
* @dataProvider mountPointNamesProvider
*/
- public function testAddOrUpdateStorageInvalidMountPoint($mountPoint) {
+ public function testAddOrUpdateStorageInvalidMountPoint($mountPoint): void {
$storageConfig = new StorageConfig(1);
$storageConfig->setMountPoint($mountPoint);
$storageConfig->setBackend($this->getBackendMock());
@@ -237,7 +237,7 @@ abstract class StoragesControllerTest extends \Test\TestCase {
$this->assertEquals(Http::STATUS_UNPROCESSABLE_ENTITY, $response->getStatus());
}
- public function testAddOrUpdateStorageInvalidBackend() {
+ public function testAddOrUpdateStorageInvalidBackend(): void {
$this->service->expects($this->exactly(2))
->method('createStorage')
->will($this->throwException(new \InvalidArgumentException()));
@@ -274,7 +274,7 @@ abstract class StoragesControllerTest extends \Test\TestCase {
$this->assertEquals(Http::STATUS_UNPROCESSABLE_ENTITY, $response->getStatus());
}
- public function testUpdateStorageNonExisting() {
+ public function testUpdateStorageNonExisting(): void {
$authMech = $this->getAuthMechMock();
$authMech->method('validateStorage')
->willReturn(true);
@@ -314,7 +314,7 @@ abstract class StoragesControllerTest extends \Test\TestCase {
$this->assertEquals(Http::STATUS_NOT_FOUND, $response->getStatus());
}
- public function testDeleteStorage() {
+ public function testDeleteStorage(): void {
$this->service->expects($this->once())
->method('removeStorage');
@@ -322,7 +322,7 @@ abstract class StoragesControllerTest extends \Test\TestCase {
$this->assertEquals(Http::STATUS_NO_CONTENT, $response->getStatus());
}
- public function testDeleteStorageNonExisting() {
+ public function testDeleteStorageNonExisting(): void {
$this->service->expects($this->once())
->method('removeStorage')
->will($this->throwException(new NotFoundException()));
@@ -331,7 +331,7 @@ abstract class StoragesControllerTest extends \Test\TestCase {
$this->assertEquals(Http::STATUS_NOT_FOUND, $response->getStatus());
}
- public function testGetStorage() {
+ public function testGetStorage(): void {
$backend = $this->getBackendMock();
$authMech = $this->getAuthMechMock();
$storageConfig = new StorageConfig(1);
@@ -365,7 +365,7 @@ abstract class StoragesControllerTest extends \Test\TestCase {
/**
* @dataProvider validateStorageProvider
*/
- public function testValidateStorage($backendValidate, $authMechValidate, $expectSuccess) {
+ public function testValidateStorage($backendValidate, $authMechValidate, $expectSuccess): void {
$backend = $this->getBackendMock();
$backend->method('validateStorage')
->willReturn($backendValidate);
diff --git a/apps/files_external/tests/Controller/UserStoragesControllerTest.php b/apps/files_external/tests/Controller/UserStoragesControllerTest.php
index 4e2fc20d9ee..4a0d3d8850f 100644
--- a/apps/files_external/tests/Controller/UserStoragesControllerTest.php
+++ b/apps/files_external/tests/Controller/UserStoragesControllerTest.php
@@ -60,12 +60,12 @@ class UserStoragesControllerTest extends StoragesControllerTest {
);
}
- public function testAddLocalStorageWhenDisabled() {
+ public function testAddLocalStorageWhenDisabled(): void {
$this->controller = $this->createController(false);
parent::testAddLocalStorageWhenDisabled();
}
- public function testAddOrUpdateStorageDisallowedBackend() {
+ public function testAddOrUpdateStorageDisallowedBackend(): void {
$backend = $this->getBackendMock();
$backend->method('isVisibleFor')
->with(BackendService::VISIBILITY_PERSONAL)
diff --git a/apps/files_external/tests/DefinitionParameterTest.php b/apps/files_external/tests/DefinitionParameterTest.php
index f9d50e7a34c..0b1d11bbf0c 100644
--- a/apps/files_external/tests/DefinitionParameterTest.php
+++ b/apps/files_external/tests/DefinitionParameterTest.php
@@ -9,7 +9,7 @@ namespace OCA\Files_External\Tests;
use OCA\Files_External\Lib\DefinitionParameter as Param;
class DefinitionParameterTest extends \Test\TestCase {
- public function testJsonSerialization() {
+ public function testJsonSerialization(): void {
$param = new Param('foo', 'bar');
$this->assertEquals([
'value' => 'bar',
@@ -70,7 +70,7 @@ class DefinitionParameterTest extends \Test\TestCase {
/**
* @dataProvider validateValueProvider
*/
- public function testValidateValue($type, $flags, $value, $success, $expectedValue = null) {
+ public function testValidateValue($type, $flags, $value, $success, $expectedValue = null): void {
$param = new Param('foo', 'bar');
$param->setType($type);
$param->setFlags($flags);
diff --git a/apps/files_external/tests/FrontendDefinitionTraitTest.php b/apps/files_external/tests/FrontendDefinitionTraitTest.php
index ab2c6113050..e33a175d28b 100644
--- a/apps/files_external/tests/FrontendDefinitionTraitTest.php
+++ b/apps/files_external/tests/FrontendDefinitionTraitTest.php
@@ -10,7 +10,7 @@ use OCA\Files_External\Lib\DefinitionParameter;
use OCA\Files_External\Lib\StorageConfig;
class FrontendDefinitionTraitTest extends \Test\TestCase {
- public function testJsonSerialization() {
+ public function testJsonSerialization(): void {
$param = $this->getMockBuilder(DefinitionParameter::class)
->disableOriginalConstructor()
->getMock();
@@ -42,7 +42,7 @@ class FrontendDefinitionTraitTest extends \Test\TestCase {
/**
* @dataProvider validateStorageProvider
*/
- public function testValidateStorage($expectedSuccess, $params) {
+ public function testValidateStorage($expectedSuccess, $params): void {
$backendParams = [];
foreach ($params as $name => $valid) {
$param = $this->getMockBuilder(DefinitionParameter::class)
@@ -74,7 +74,7 @@ class FrontendDefinitionTraitTest extends \Test\TestCase {
$this->assertEquals($expectedSuccess, $trait->validateStorageDefinition($storageConfig));
}
- public function testValidateStorageSet() {
+ public function testValidateStorageSet(): void {
$param = $this->getMockBuilder(DefinitionParameter::class)
->disableOriginalConstructor()
->getMock();
diff --git a/apps/files_external/tests/LegacyDependencyCheckPolyfillTest.php b/apps/files_external/tests/LegacyDependencyCheckPolyfillTest.php
index 5b8f68ceb79..db12ed3c1b4 100644
--- a/apps/files_external/tests/LegacyDependencyCheckPolyfillTest.php
+++ b/apps/files_external/tests/LegacyDependencyCheckPolyfillTest.php
@@ -1,36 +1,36 @@
-<?php
-/**
- * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
- * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
- * SPDX-License-Identifier: AGPL-3.0-only
- */
-namespace OCA\Files_External\Tests;
-
-use OCA\Files_External\Lib\MissingDependency;
-
-class LegacyDependencyCheckPolyfillTest extends \Test\TestCase {
-
- /**
- * @return MissingDependency[]
- */
- public static function checkDependencies() {
- return [
- (new MissingDependency('dependency'))->setMessage('missing dependency'),
- (new MissingDependency('program'))->setMessage('cannot find program'),
- ];
- }
-
- public function testCheckDependencies() {
- $trait = $this->getMockForTrait(\OCA\Files_External\Lib\LegacyDependencyCheckPolyfill::class);
- $trait->expects($this->once())
- ->method('getStorageClass')
- ->willReturn(\OCA\Files_External\Tests\LegacyDependencyCheckPolyfillTest::class);
-
- $dependencies = $trait->checkDependencies();
- $this->assertCount(2, $dependencies);
- $this->assertEquals('dependency', $dependencies[0]->getDependency());
- $this->assertEquals('missing dependency', $dependencies[0]->getMessage());
- $this->assertEquals('program', $dependencies[1]->getDependency());
- $this->assertEquals('cannot find program', $dependencies[1]->getMessage());
- }
-}
+<?php
+/**
+ * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
+ */
+namespace OCA\Files_External\Tests;
+
+use OCA\Files_External\Lib\MissingDependency;
+
+class LegacyDependencyCheckPolyfillTest extends \Test\TestCase {
+
+ /**
+ * @return MissingDependency[]
+ */
+ public static function checkDependencies() {
+ return [
+ (new MissingDependency('dependency'))->setMessage('missing dependency'),
+ (new MissingDependency('program'))->setMessage('cannot find program'),
+ ];
+ }
+
+ public function testCheckDependencies(): void {
+ $trait = $this->getMockForTrait(\OCA\Files_External\Lib\LegacyDependencyCheckPolyfill::class);
+ $trait->expects($this->once())
+ ->method('getStorageClass')
+ ->willReturn(\OCA\Files_External\Tests\LegacyDependencyCheckPolyfillTest::class);
+
+ $dependencies = $trait->checkDependencies();
+ $this->assertCount(2, $dependencies);
+ $this->assertEquals('dependency', $dependencies[0]->getDependency());
+ $this->assertEquals('missing dependency', $dependencies[0]->getMessage());
+ $this->assertEquals('program', $dependencies[1]->getDependency());
+ $this->assertEquals('cannot find program', $dependencies[1]->getMessage());
+ }
+}
diff --git a/apps/files_external/tests/Listener/StorePasswordListenerTest.php b/apps/files_external/tests/Listener/StorePasswordListenerTest.php
index a028e1ac0ef..ec278f84331 100644
--- a/apps/files_external/tests/Listener/StorePasswordListenerTest.php
+++ b/apps/files_external/tests/Listener/StorePasswordListenerTest.php
@@ -76,7 +76,7 @@ class StorePasswordListenerTest extends TestCase {
$storePasswordListener->handle($event);
}
- public function testClassicLoginSameCredentials() {
+ public function testClassicLoginSameCredentials(): void {
$this->getMockedCredentialManager(
[
'user' => 'test',
@@ -87,7 +87,7 @@ class StorePasswordListenerTest extends TestCase {
);
}
- public function testClassicLoginNewPassword() {
+ public function testClassicLoginNewPassword(): void {
$this->getMockedCredentialManager(
[
'user' => 'test',
@@ -101,7 +101,7 @@ class StorePasswordListenerTest extends TestCase {
);
}
- public function testClassicLoginNewUser() {
+ public function testClassicLoginNewUser(): void {
$this->getMockedCredentialManager(
[
'user' => 'test',
@@ -115,7 +115,7 @@ class StorePasswordListenerTest extends TestCase {
);
}
- public function testSSOLogin() {
+ public function testSSOLogin(): void {
$this->getMockedCredentialManager(
[
'user' => 'test',
@@ -126,7 +126,7 @@ class StorePasswordListenerTest extends TestCase {
);
}
- public function testPasswordUpdated() {
+ public function testPasswordUpdated(): void {
$this->getMockedCredentialManager(
[
'user' => 'test',
@@ -140,7 +140,7 @@ class StorePasswordListenerTest extends TestCase {
);
}
- public function testUserLoginWithToken() {
+ public function testUserLoginWithToken(): void {
$this->getMockedCredentialManager(
null,
new UserLoggedInEvent($this->mockedUser, 'test', 'password', true),
@@ -148,7 +148,7 @@ class StorePasswordListenerTest extends TestCase {
);
}
- public function testNoInitialCredentials() {
+ public function testNoInitialCredentials(): void {
$this->getMockedCredentialManager(
false,
new PasswordUpdatedEvent($this->mockedUser, 'test', 'password'),
diff --git a/apps/files_external/tests/OwnCloudFunctionsTest.php b/apps/files_external/tests/OwnCloudFunctionsTest.php
index 9efefe8e4dd..99cb0cf94de 100644
--- a/apps/files_external/tests/OwnCloudFunctionsTest.php
+++ b/apps/files_external/tests/OwnCloudFunctionsTest.php
@@ -86,7 +86,7 @@ class OwnCloudFunctionsTest extends \Test\TestCase {
/**
* @dataProvider configUrlProvider
*/
- public function testConfig($config, $expectedUri) {
+ public function testConfig($config, $expectedUri): void {
$config['user'] = 'someuser';
$config['password'] = 'somepassword';
$instance = new \OCA\Files_External\Lib\Storage\OwnCloud($config);
diff --git a/apps/files_external/tests/PersonalMountTest.php b/apps/files_external/tests/PersonalMountTest.php
index 17dd632690e..9deb5c41435 100644
--- a/apps/files_external/tests/PersonalMountTest.php
+++ b/apps/files_external/tests/PersonalMountTest.php
@@ -13,7 +13,7 @@ use OCA\Files_External\Lib\StorageConfig;
use Test\TestCase;
class PersonalMountTest extends TestCase {
- public function testFindByStorageId() {
+ public function testFindByStorageId(): void {
$storageConfig = $this->createMock(StorageConfig::class);
/** @var \OCA\Files_External\Service\UserStoragesService $storageService */
$storageService = $this->getMockBuilder(\OCA\Files_External\Service\UserStoragesService::class)
diff --git a/apps/files_external/tests/Service/BackendServiceTest.php b/apps/files_external/tests/Service/BackendServiceTest.php
index 8685325471e..9d4007f852d 100644
--- a/apps/files_external/tests/Service/BackendServiceTest.php
+++ b/apps/files_external/tests/Service/BackendServiceTest.php
@@ -51,7 +51,7 @@ class BackendServiceTest extends \Test\TestCase {
return $backend;
}
- public function testRegisterBackend() {
+ public function testRegisterBackend(): void {
$service = new BackendService($this->config);
$backend = $this->getBackendMock('\Foo\Bar');
@@ -79,7 +79,7 @@ class BackendServiceTest extends \Test\TestCase {
$this->assertArrayNotHasKey('identifier_alias', $backends);
}
- public function testBackendProvider() {
+ public function testBackendProvider(): void {
$service = new BackendService($this->config);
$backend1 = $this->getBackendMock('\Foo\Bar');
@@ -98,7 +98,7 @@ class BackendServiceTest extends \Test\TestCase {
$this->assertCount(2, $service->getBackends());
}
- public function testAuthMechanismProvider() {
+ public function testAuthMechanismProvider(): void {
$service = new BackendService($this->config);
$backend1 = $this->getAuthMechanismMock('\Foo\Bar');
@@ -117,7 +117,7 @@ class BackendServiceTest extends \Test\TestCase {
$this->assertCount(2, $service->getAuthMechanisms());
}
- public function testMultipleBackendProviders() {
+ public function testMultipleBackendProviders(): void {
$service = new BackendService($this->config);
$backend1a = $this->getBackendMock('\Foo\Bar');
@@ -145,7 +145,7 @@ class BackendServiceTest extends \Test\TestCase {
$this->assertCount(3, $service->getBackends());
}
- public function testUserMountingBackends() {
+ public function testUserMountingBackends(): void {
$this->config->expects($this->exactly(2))
->method('getAppValue')
->willReturnMap([
@@ -176,7 +176,7 @@ class BackendServiceTest extends \Test\TestCase {
$service->registerBackend($backendAlias);
}
- public function testGetAvailableBackends() {
+ public function testGetAvailableBackends(): void {
$service = new BackendService($this->config);
$backendAvailable = $this->getBackendMock('\Backend\Available');
@@ -217,7 +217,7 @@ class BackendServiceTest extends \Test\TestCase {
/**
* @dataProvider invalidConfigPlaceholderProvider
*/
- public function testRegisterConfigHandlerInvalid(array $placeholders) {
+ public function testRegisterConfigHandlerInvalid(array $placeholders): void {
$this->expectException(\RuntimeException::class);
$service = new BackendService($this->config);
@@ -230,7 +230,7 @@ class BackendServiceTest extends \Test\TestCase {
}
}
- public function testConfigHandlers() {
+ public function testConfigHandlers(): void {
$service = new BackendService($this->config);
$mock = $this->createMock(IConfigHandler::class);
$mock->expects($this->exactly(3))
diff --git a/apps/files_external/tests/Service/DBConfigServiceTest.php b/apps/files_external/tests/Service/DBConfigServiceTest.php
index 1c2cafc93f0..968c166a505 100644
--- a/apps/files_external/tests/Service/DBConfigServiceTest.php
+++ b/apps/files_external/tests/Service/DBConfigServiceTest.php
@@ -45,7 +45,7 @@ class DBConfigServiceTest extends TestCase {
return $id;
}
- public function testAddSimpleMount() {
+ public function testAddSimpleMount(): void {
$id = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN);
$mount = $this->dbConfig->getMountById($id);
@@ -59,7 +59,7 @@ class DBConfigServiceTest extends TestCase {
$this->assertEquals([], $mount['options']);
}
- public function testAddApplicable() {
+ public function testAddApplicable(): void {
$id = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN);
$this->dbConfig->addApplicable($id, DBConfigService::APPLICABLE_TYPE_USER, 'test');
@@ -79,7 +79,7 @@ class DBConfigServiceTest extends TestCase {
], $mount['applicable']);
}
- public function testAddApplicableDouble() {
+ public function testAddApplicableDouble(): void {
$id = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN);
$this->dbConfig->addApplicable($id, DBConfigService::APPLICABLE_TYPE_USER, 'test');
$this->dbConfig->addApplicable($id, DBConfigService::APPLICABLE_TYPE_USER, 'test');
@@ -90,7 +90,7 @@ class DBConfigServiceTest extends TestCase {
], $mount['applicable']);
}
- public function testDeleteMount() {
+ public function testDeleteMount(): void {
$id = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN);
$this->dbConfig->removeMount($id);
@@ -99,7 +99,7 @@ class DBConfigServiceTest extends TestCase {
$this->assertEquals(null, $mount);
}
- public function testRemoveApplicable() {
+ public function testRemoveApplicable(): void {
$id = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN);
$this->dbConfig->addApplicable($id, DBConfigService::APPLICABLE_TYPE_USER, 'test');
$this->dbConfig->removeApplicable($id, DBConfigService::APPLICABLE_TYPE_USER, 'test');
@@ -108,7 +108,7 @@ class DBConfigServiceTest extends TestCase {
$this->assertEquals([], $mount['applicable']);
}
- public function testRemoveApplicableGlobal() {
+ public function testRemoveApplicableGlobal(): void {
$id = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN);
$this->dbConfig->addApplicable($id, DBConfigService::APPLICABLE_TYPE_GLOBAL, null);
$this->dbConfig->removeApplicable($id, DBConfigService::APPLICABLE_TYPE_GLOBAL, null);
@@ -120,7 +120,7 @@ class DBConfigServiceTest extends TestCase {
], $mount['applicable']);
}
- public function testSetConfig() {
+ public function testSetConfig(): void {
$id = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN);
$this->dbConfig->setConfig($id, 'foo', 'bar');
@@ -133,7 +133,7 @@ class DBConfigServiceTest extends TestCase {
$this->assertEquals(['foo' => 'bar', 'foo2' => 'bar2'], $mount['config']);
}
- public function testSetConfigOverwrite() {
+ public function testSetConfigOverwrite(): void {
$id = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN);
$this->dbConfig->setConfig($id, 'foo', 'bar');
$this->dbConfig->setConfig($id, 'asd', '1');
@@ -143,7 +143,7 @@ class DBConfigServiceTest extends TestCase {
$this->assertEquals(['foo' => 'qwerty', 'asd' => '1'], $mount['config']);
}
- public function testSetOption() {
+ public function testSetOption(): void {
$id = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN);
$this->dbConfig->setOption($id, 'foo', 'bar');
@@ -156,7 +156,7 @@ class DBConfigServiceTest extends TestCase {
$this->assertEquals(['foo' => 'bar', 'foo2' => 'bar2'], $mount['options']);
}
- public function testSetOptionOverwrite() {
+ public function testSetOptionOverwrite(): void {
$id = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN);
$this->dbConfig->setOption($id, 'foo', 'bar');
$this->dbConfig->setOption($id, 'asd', '1');
@@ -166,7 +166,7 @@ class DBConfigServiceTest extends TestCase {
$this->assertEquals(['foo' => 'qwerty', 'asd' => '1'], $mount['options']);
}
- public function testGetMountsFor() {
+ public function testGetMountsFor(): void {
$mounts = $this->dbConfig->getMountsFor(DBConfigService::APPLICABLE_TYPE_USER, 'test');
$this->assertEquals([], $mounts);
@@ -179,7 +179,7 @@ class DBConfigServiceTest extends TestCase {
$this->assertEquals([['type' => DBConfigService::APPLICABLE_TYPE_USER, 'value' => 'test', 'mount_id' => $id]], $mounts[0]['applicable']);
}
- public function testGetAdminMounts() {
+ public function testGetAdminMounts(): void {
$id1 = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN);
$this->addMount('/test2', 'foo2', 'bar2', 100, DBConfigService::MOUNT_TYPE_PERSONAL);
@@ -188,7 +188,7 @@ class DBConfigServiceTest extends TestCase {
$this->assertEquals($id1, $mounts[0]['mount_id']);
}
- public function testGetAdminMountsFor() {
+ public function testGetAdminMountsFor(): void {
$id1 = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN);
$this->addMount('/test2', 'foo2', 'bar2', 100, DBConfigService::MOUNT_TYPE_ADMIN);
$id3 = $this->addMount('/test3', 'foo3', 'bar3', 100, DBConfigService::MOUNT_TYPE_PERSONAL);
@@ -202,7 +202,7 @@ class DBConfigServiceTest extends TestCase {
$this->assertEquals([['type' => DBConfigService::APPLICABLE_TYPE_USER, 'value' => 'test', 'mount_id' => $id1]], $mounts[0]['applicable']);
}
- public function testGetUserMountsFor() {
+ public function testGetUserMountsFor(): void {
$id1 = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN);
$this->addMount('/test2', 'foo2', 'bar2', 100, DBConfigService::MOUNT_TYPE_PERSONAL);
$id3 = $this->addMount('/test3', 'foo3', 'bar3', 100, DBConfigService::MOUNT_TYPE_PERSONAL);
@@ -216,7 +216,7 @@ class DBConfigServiceTest extends TestCase {
$this->assertEquals([['type' => DBConfigService::APPLICABLE_TYPE_USER, 'value' => 'test', 'mount_id' => $id3]], $mounts[0]['applicable']);
}
- public function testGetAdminMountsForGlobal() {
+ public function testGetAdminMountsForGlobal(): void {
$id1 = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN);
$this->dbConfig->addApplicable($id1, DBConfigService::APPLICABLE_TYPE_GLOBAL, null);
@@ -227,7 +227,7 @@ class DBConfigServiceTest extends TestCase {
$this->assertEquals([['type' => DBConfigService::APPLICABLE_TYPE_GLOBAL, 'value' => null, 'mount_id' => $id1]], $mounts[0]['applicable']);
}
- public function testSetMountPoint() {
+ public function testSetMountPoint(): void {
$id1 = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN);
$id2 = $this->addMount('/foo', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN);
@@ -241,7 +241,7 @@ class DBConfigServiceTest extends TestCase {
$this->assertEquals('/foo', $mount['mount_point']);
}
- public function testSetAuthBackend() {
+ public function testSetAuthBackend(): void {
$id1 = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN);
$id2 = $this->addMount('/foo', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN);
@@ -255,7 +255,7 @@ class DBConfigServiceTest extends TestCase {
$this->assertEquals('bar', $mount['auth_backend']);
}
- public function testGetMountsForDuplicateByGroup() {
+ public function testGetMountsForDuplicateByGroup(): void {
$id1 = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN);
$this->dbConfig->addApplicable($id1, DBConfigService::APPLICABLE_TYPE_GROUP, 'group1');
@@ -266,7 +266,7 @@ class DBConfigServiceTest extends TestCase {
$this->assertEquals($id1, $mounts[0]['mount_id']);
}
- public function testGetAllMounts() {
+ public function testGetAllMounts(): void {
$id1 = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN);
$id2 = $this->addMount('/test2', 'foo2', 'bar2', 100, DBConfigService::MOUNT_TYPE_PERSONAL);
diff --git a/apps/files_external/tests/Service/GlobalStoragesServiceTest.php b/apps/files_external/tests/Service/GlobalStoragesServiceTest.php
index 18fd9d174f2..0c9df2e858b 100644
--- a/apps/files_external/tests/Service/GlobalStoragesServiceTest.php
+++ b/apps/files_external/tests/Service/GlobalStoragesServiceTest.php
@@ -115,7 +115,7 @@ class GlobalStoragesServiceTest extends StoragesServiceTest {
/**
* @dataProvider storageDataProvider
*/
- public function testAddStorage($storageParams) {
+ public function testAddStorage($storageParams): void {
$storage = $this->makeStorageConfig($storageParams);
$newStorage = $this->service->addStorage($storage);
@@ -139,7 +139,7 @@ class GlobalStoragesServiceTest extends StoragesServiceTest {
/**
* @dataProvider storageDataProvider
*/
- public function testUpdateStorage($updatedStorageParams) {
+ public function testUpdateStorage($updatedStorageParams): void {
$updatedStorage = $this->makeStorageConfig($updatedStorageParams);
$storage = $this->makeStorageConfig([
'mountPoint' => 'mountpoint',
@@ -281,7 +281,7 @@ class GlobalStoragesServiceTest extends StoragesServiceTest {
/**
* @dataProvider hooksAddStorageDataProvider
*/
- public function testHooksAddStorage($applicableUsers, $applicableGroups, $expectedCalls) {
+ public function testHooksAddStorage($applicableUsers, $applicableGroups, $expectedCalls): void {
$storage = $this->makeTestStorageData();
$storage->setApplicableUsers($applicableUsers);
$storage->setApplicableGroups($applicableGroups);
@@ -424,7 +424,7 @@ class GlobalStoragesServiceTest extends StoragesServiceTest {
$sourceApplicableGroups,
$updatedApplicableUsers,
$updatedApplicableGroups,
- $expectedCalls) {
+ $expectedCalls): void {
$storage = $this->makeTestStorageData();
$storage->setApplicableUsers($sourceApplicableUsers);
$storage->setApplicableGroups($sourceApplicableGroups);
@@ -452,7 +452,7 @@ class GlobalStoragesServiceTest extends StoragesServiceTest {
}
- public function testHooksRenameMountPoint() {
+ public function testHooksRenameMountPoint(): void {
$storage = $this->makeTestStorageData();
$storage->setApplicableUsers(['user1', 'user2']);
$storage->setApplicableGroups(['group1', 'group2']);
@@ -581,7 +581,7 @@ class GlobalStoragesServiceTest extends StoragesServiceTest {
public function testHooksDeleteStorage(
$sourceApplicableUsers,
$sourceApplicableGroups,
- $expectedCalls) {
+ $expectedCalls): void {
$storage = $this->makeTestStorageData();
$storage->setApplicableUsers($sourceApplicableUsers);
$storage->setApplicableGroups($sourceApplicableGroups);
diff --git a/apps/files_external/tests/Service/StoragesServiceTest.php b/apps/files_external/tests/Service/StoragesServiceTest.php
index 234ea12b8e7..c9df7b6c13b 100644
--- a/apps/files_external/tests/Service/StoragesServiceTest.php
+++ b/apps/files_external/tests/Service/StoragesServiceTest.php
@@ -248,7 +248,7 @@ abstract class StoragesServiceTest extends \Test\TestCase {
$this->service->updateStorage($storage);
}
- public function testNonExistingStorage() {
+ public function testNonExistingStorage(): void {
$this->expectException(\OCA\Files_External\NotFoundException::class);
$this->ActualNonExistingStorageTest();
@@ -281,7 +281,7 @@ abstract class StoragesServiceTest extends \Test\TestCase {
/**
* @dataProvider deleteStorageDataProvider
*/
- public function testDeleteStorage($backendOptions, $rustyStorageId) {
+ public function testDeleteStorage($backendOptions, $rustyStorageId): void {
$backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\DAV');
$authMechanism = $this->backendService->getAuthMechanism('identifier:\Auth\Mechanism');
$storage = new StorageConfig(255);
@@ -352,13 +352,13 @@ abstract class StoragesServiceTest extends \Test\TestCase {
$this->service->removeStorage(255);
}
- public function testDeleteUnexistingStorage() {
+ public function testDeleteUnexistingStorage(): void {
$this->expectException(\OCA\Files_External\NotFoundException::class);
$this->actualDeletedUnexistingStorageTest();
}
- public function testCreateStorage() {
+ public function testCreateStorage(): void {
$mountPoint = 'mount';
$backendIdentifier = 'identifier:\OCA\Files_External\Lib\Backend\SMB';
$authMechanismIdentifier = 'identifier:\Auth\Mechanism';
@@ -392,7 +392,7 @@ abstract class StoragesServiceTest extends \Test\TestCase {
$this->assertEquals($priority, $storage->getPriority());
}
- public function testCreateStorageInvalidClass() {
+ public function testCreateStorageInvalidClass(): void {
$storage = $this->service->createStorage(
'mount',
'identifier:\OC\Not\A\Backend',
@@ -402,7 +402,7 @@ abstract class StoragesServiceTest extends \Test\TestCase {
$this->assertInstanceOf(InvalidBackend::class, $storage->getBackend());
}
- public function testCreateStorageInvalidAuthMechanismClass() {
+ public function testCreateStorageInvalidAuthMechanismClass(): void {
$storage = $this->service->createStorage(
'mount',
'identifier:\OCA\Files_External\Lib\Backend\SMB',
@@ -412,7 +412,7 @@ abstract class StoragesServiceTest extends \Test\TestCase {
$this->assertInstanceOf(InvalidAuth::class, $storage->getAuthMechanism());
}
- public function testGetStoragesBackendNotVisible() {
+ public function testGetStoragesBackendNotVisible(): void {
$backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\SMB');
$backend->expects($this->once())
->method('isVisibleFor')
@@ -435,7 +435,7 @@ abstract class StoragesServiceTest extends \Test\TestCase {
$this->assertEmpty($this->service->getStorages());
}
- public function testGetStoragesAuthMechanismNotVisible() {
+ public function testGetStoragesAuthMechanismNotVisible(): void {
$backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\SMB');
$backend->method('isVisibleFor')
->with($this->service->getVisibilityType())
@@ -498,7 +498,7 @@ abstract class StoragesServiceTest extends \Test\TestCase {
);
}
- public function testUpdateStorageMountPoint() {
+ public function testUpdateStorageMountPoint(): void {
$backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\SMB');
$authMechanism = $this->backendService->getAuthMechanism('identifier:\Auth\Mechanism');
diff --git a/apps/files_external/tests/Service/UserGlobalStoragesServiceTest.php b/apps/files_external/tests/Service/UserGlobalStoragesServiceTest.php
index e08f3bd4d7d..992960a6ea1 100644
--- a/apps/files_external/tests/Service/UserGlobalStoragesServiceTest.php
+++ b/apps/files_external/tests/Service/UserGlobalStoragesServiceTest.php
@@ -108,7 +108,7 @@ class UserGlobalStoragesServiceTest extends GlobalStoragesServiceTest {
/**
* @dataProvider applicableStorageProvider
*/
- public function testGetStorageWithApplicable($applicableUsers, $applicableGroups, $isVisible) {
+ public function testGetStorageWithApplicable($applicableUsers, $applicableGroups, $isVisible): void {
$backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\SMB');
$authMechanism = $this->backendService->getAuthMechanism('identifier:\Auth\Mechanism');
@@ -139,7 +139,7 @@ class UserGlobalStoragesServiceTest extends GlobalStoragesServiceTest {
}
- public function testAddStorage($storageParams = null) {
+ public function testAddStorage($storageParams = null): void {
$this->expectException(\DomainException::class);
$backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\SMB');
@@ -155,7 +155,7 @@ class UserGlobalStoragesServiceTest extends GlobalStoragesServiceTest {
}
- public function testUpdateStorage($storageParams = null) {
+ public function testUpdateStorage($storageParams = null): void {
$this->expectException(\DomainException::class);
$backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\SMB');
@@ -175,7 +175,7 @@ class UserGlobalStoragesServiceTest extends GlobalStoragesServiceTest {
}
- public function testNonExistingStorage() {
+ public function testNonExistingStorage(): void {
$this->expectException(\DomainException::class);
$this->ActualNonExistingStorageTest();
@@ -184,7 +184,7 @@ class UserGlobalStoragesServiceTest extends GlobalStoragesServiceTest {
/**
* @dataProvider deleteStorageDataProvider
*/
- public function testDeleteStorage($backendOptions, $rustyStorageId) {
+ public function testDeleteStorage($backendOptions, $rustyStorageId): void {
$this->expectException(\DomainException::class);
$backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\SMB');
@@ -203,7 +203,7 @@ class UserGlobalStoragesServiceTest extends GlobalStoragesServiceTest {
}
- public function testDeleteUnexistingStorage() {
+ public function testDeleteUnexistingStorage(): void {
$this->expectException(\DomainException::class);
$this->actualDeletedUnexistingStorageTest();
@@ -244,7 +244,7 @@ class UserGlobalStoragesServiceTest extends GlobalStoragesServiceTest {
$priority1, $applicableUsers1, $applicableGroups1,
$priority2, $applicableUsers2, $applicableGroups2,
$expectedPrecedence
- ) {
+ ): void {
$backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\SMB');
$backend->method('isVisibleFor')
->willReturn(true);
@@ -284,67 +284,67 @@ class UserGlobalStoragesServiceTest extends GlobalStoragesServiceTest {
}
}
- public function testGetStoragesBackendNotVisible() {
+ public function testGetStoragesBackendNotVisible(): void {
// we don't test this here
$this->addToAssertionCount(1);
}
- public function testGetStoragesAuthMechanismNotVisible() {
+ public function testGetStoragesAuthMechanismNotVisible(): void {
// we don't test this here
$this->addToAssertionCount(1);
}
- public function testHooksAddStorage($a = null, $b = null, $c = null) {
+ public function testHooksAddStorage($a = null, $b = null, $c = null): void {
// we don't test this here
$this->addToAssertionCount(1);
}
- public function testHooksUpdateStorage($a = null, $b = null, $c = null, $d = null, $e = null) {
+ public function testHooksUpdateStorage($a = null, $b = null, $c = null, $d = null, $e = null): void {
// we don't test this here
$this->addToAssertionCount(1);
}
- public function testHooksRenameMountPoint() {
+ public function testHooksRenameMountPoint(): void {
// we don't test this here
$this->addToAssertionCount(1);
}
- public function testHooksDeleteStorage($a = null, $b = null, $c = null) {
+ public function testHooksDeleteStorage($a = null, $b = null, $c = null): void {
// we don't test this here
$this->addToAssertionCount(1);
}
- public function testLegacyConfigConversionApplicableAll() {
+ public function testLegacyConfigConversionApplicableAll(): void {
// we don't test this here
$this->addToAssertionCount(1);
}
- public function testLegacyConfigConversionApplicableUserAndGroup() {
+ public function testLegacyConfigConversionApplicableUserAndGroup(): void {
// we don't test this here
$this->addToAssertionCount(1);
}
- public function testReadLegacyConfigAndGenerateConfigId() {
+ public function testReadLegacyConfigAndGenerateConfigId(): void {
// we don't test this here
$this->addToAssertionCount(1);
}
- public function testReadLegacyConfigNoAuthMechanism() {
+ public function testReadLegacyConfigNoAuthMechanism(): void {
// we don't test this here
$this->addToAssertionCount(1);
}
- public function testReadLegacyConfigClass() {
+ public function testReadLegacyConfigClass(): void {
// we don't test this here
$this->addToAssertionCount(1);
}
- public function testReadEmptyMountPoint() {
+ public function testReadEmptyMountPoint(): void {
// we don't test this here
$this->addToAssertionCount(1);
}
- public function testUpdateStorageMountPoint() {
+ public function testUpdateStorageMountPoint(): void {
// we don't test this here
$this->addToAssertionCount(1);
}
diff --git a/apps/files_external/tests/Service/UserStoragesServiceTest.php b/apps/files_external/tests/Service/UserStoragesServiceTest.php
index e163a6247d2..4ddc7177ebd 100644
--- a/apps/files_external/tests/Service/UserStoragesServiceTest.php
+++ b/apps/files_external/tests/Service/UserStoragesServiceTest.php
@@ -65,7 +65,7 @@ class UserStoragesServiceTest extends StoragesServiceTest {
]);
}
- public function testAddStorage() {
+ public function testAddStorage(): void {
$storage = $this->makeTestStorageData();
$newStorage = $this->service->addStorage($storage);
@@ -93,7 +93,7 @@ class UserStoragesServiceTest extends StoragesServiceTest {
$this->assertEquals($id + 1, $nextStorage->getId());
}
- public function testUpdateStorage() {
+ public function testUpdateStorage(): void {
$storage = $this->makeStorageConfig([
'mountPoint' => 'mountpoint',
'backendIdentifier' => 'identifier:\OCA\Files_External\Lib\Backend\SMB',
@@ -128,7 +128,7 @@ class UserStoragesServiceTest extends StoragesServiceTest {
/**
* @dataProvider deleteStorageDataProvider
*/
- public function testDeleteStorage($backendOptions, $rustyStorageId) {
+ public function testDeleteStorage($backendOptions, $rustyStorageId): void {
parent::testDeleteStorage($backendOptions, $rustyStorageId);
// hook called once for user (first one was during test creation)
@@ -141,7 +141,7 @@ class UserStoragesServiceTest extends StoragesServiceTest {
);
}
- public function testHooksRenameMountPoint() {
+ public function testHooksRenameMountPoint(): void {
$storage = $this->makeTestStorageData();
$storage = $this->service->addStorage($storage);
@@ -170,7 +170,7 @@ class UserStoragesServiceTest extends StoragesServiceTest {
}
- public function testGetAdminStorage() {
+ public function testGetAdminStorage(): void {
$this->expectException(\OCA\Files_External\NotFoundException::class);
$backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\SMB');
diff --git a/apps/files_external/tests/Settings/AdminTest.php b/apps/files_external/tests/Settings/AdminTest.php
index 1d584814da8..602e0124950 100644
--- a/apps/files_external/tests/Settings/AdminTest.php
+++ b/apps/files_external/tests/Settings/AdminTest.php
@@ -40,7 +40,7 @@ class AdminTest extends TestCase {
);
}
- public function testGetForm() {
+ public function testGetForm(): void {
$this->encryptionManager
->expects($this->once())
->method('isEnabled')
@@ -85,11 +85,11 @@ class AdminTest extends TestCase {
$this->assertEquals($expected, $this->admin->getForm());
}
- public function testGetSection() {
+ public function testGetSection(): void {
$this->assertSame('externalstorages', $this->admin->getSection());
}
- public function testGetPriority() {
+ public function testGetPriority(): void {
$this->assertSame(40, $this->admin->getPriority());
}
}
diff --git a/apps/files_external/tests/Settings/SectionTest.php b/apps/files_external/tests/Settings/SectionTest.php
index e9f47cab19d..9154106ff8a 100644
--- a/apps/files_external/tests/Settings/SectionTest.php
+++ b/apps/files_external/tests/Settings/SectionTest.php
@@ -29,11 +29,11 @@ class SectionTest extends TestCase {
);
}
- public function testGetID() {
+ public function testGetID(): void {
$this->assertSame('externalstorages', $this->section->getID());
}
- public function testGetName() {
+ public function testGetName(): void {
$this->l
->expects($this->once())
->method('t')
@@ -43,7 +43,7 @@ class SectionTest extends TestCase {
$this->assertSame('External storage', $this->section->getName());
}
- public function testGetPriority() {
+ public function testGetPriority(): void {
$this->assertSame(10, $this->section->getPriority());
}
}
diff --git a/apps/files_external/tests/Storage/Amazons3MultiPartTest.php b/apps/files_external/tests/Storage/Amazons3MultiPartTest.php
index 3db468b0fa0..1ac18406d24 100644
--- a/apps/files_external/tests/Storage/Amazons3MultiPartTest.php
+++ b/apps/files_external/tests/Storage/Amazons3MultiPartTest.php
@@ -40,11 +40,11 @@ class Amazons3MultiPartTest extends \Test\Files\Storage\Storage {
parent::tearDown();
}
- public function testStat() {
+ public function testStat(): void {
$this->markTestSkipped('S3 doesn\'t update the parents folder mtime');
}
- public function testHashInFileName() {
+ public function testHashInFileName(): void {
$this->markTestSkipped('Localstack has a bug with hashes in filename');
}
}
diff --git a/apps/files_external/tests/Storage/Amazons3Test.php b/apps/files_external/tests/Storage/Amazons3Test.php
index bffe98c3f4d..fd7fd9225c9 100644
--- a/apps/files_external/tests/Storage/Amazons3Test.php
+++ b/apps/files_external/tests/Storage/Amazons3Test.php
@@ -38,11 +38,11 @@ class Amazons3Test extends \Test\Files\Storage\Storage {
parent::tearDown();
}
- public function testStat() {
+ public function testStat(): void {
$this->markTestSkipped('S3 doesn\'t update the parents folder mtime');
}
- public function testHashInFileName() {
+ public function testHashInFileName(): void {
$this->markTestSkipped('Localstack has a bug with hashes in filename');
}
}
diff --git a/apps/files_external/tests/Storage/FtpTest.php b/apps/files_external/tests/Storage/FtpTest.php
index 24f7c511e93..c6a1d8f77ba 100644
--- a/apps/files_external/tests/Storage/FtpTest.php
+++ b/apps/files_external/tests/Storage/FtpTest.php
@@ -55,7 +55,7 @@ class FtpTest extends \Test\Files\Storage\Storage {
/**
* mtime for folders is only with a minute resolution
*/
- public function testStat() {
+ public function testStat(): void {
$textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
$ctimeStart = time();
$this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile));
diff --git a/apps/files_external/tests/Storage/SFTP_KeyTest.php b/apps/files_external/tests/Storage/SFTP_KeyTest.php
index c1aaf0b13a3..9be3cb7d3e8 100644
--- a/apps/files_external/tests/Storage/SFTP_KeyTest.php
+++ b/apps/files_external/tests/Storage/SFTP_KeyTest.php
@@ -41,39 +41,39 @@ class SFTP_KeyTest extends \Test\Files\Storage\Storage {
}
- public function testInvalidAddressShouldThrowException() {
+ public function testInvalidAddressShouldThrowException(): void {
$this->expectException(\InvalidArgumentException::class);
// I'd use example.com for this, but someone decided to break the spec and make it resolve
$this->instance->assertHostAddressValid('notarealaddress...');
}
- public function testValidAddressShouldPass() {
+ public function testValidAddressShouldPass(): void {
$this->assertTrue($this->instance->assertHostAddressValid('localhost'));
}
- public function testNegativePortNumberShouldThrowException() {
+ public function testNegativePortNumberShouldThrowException(): void {
$this->expectException(\InvalidArgumentException::class);
$this->instance->assertPortNumberValid('-1');
}
- public function testNonNumericalPortNumberShouldThrowException() {
+ public function testNonNumericalPortNumberShouldThrowException(): void {
$this->expectException(\InvalidArgumentException::class);
$this->instance->assertPortNumberValid('a');
}
- public function testHighPortNumberShouldThrowException() {
+ public function testHighPortNumberShouldThrowException(): void {
$this->expectException(\InvalidArgumentException::class);
$this->instance->assertPortNumberValid('65536');
}
- public function testValidPortNumberShouldPass() {
+ public function testValidPortNumberShouldPass(): void {
$this->assertTrue($this->instance->assertPortNumberValid('22222'));
}
}
diff --git a/apps/files_external/tests/Storage/SftpTest.php b/apps/files_external/tests/Storage/SftpTest.php
index ce7d7461ba8..cc29486f426 100644
--- a/apps/files_external/tests/Storage/SftpTest.php
+++ b/apps/files_external/tests/Storage/SftpTest.php
@@ -47,7 +47,7 @@ class SftpTest extends \Test\Files\Storage\Storage {
/**
* @dataProvider configProvider
*/
- public function testStorageId($config, $expectedStorageId) {
+ public function testStorageId($config, $expectedStorageId): void {
$instance = new SFTP($config);
$this->assertEquals($expectedStorageId, $instance->getId());
}
diff --git a/apps/files_external/tests/Storage/SmbTest.php b/apps/files_external/tests/Storage/SmbTest.php
index 437ef9a1cdf..d5a83905112 100644
--- a/apps/files_external/tests/Storage/SmbTest.php
+++ b/apps/files_external/tests/Storage/SmbTest.php
@@ -54,14 +54,14 @@ class SmbTest extends \Test\Files\Storage\Storage {
return [['folder']];
}
- public function testRenameWithSpaces() {
+ public function testRenameWithSpaces(): void {
$this->instance->mkdir('with spaces');
$result = $this->instance->rename('with spaces', 'foo bar');
$this->assertTrue($result);
$this->assertTrue($this->instance->is_dir('foo bar'));
}
- public function testStorageId() {
+ public function testStorageId(): void {
$this->instance = new SMB([
'host' => 'testhost',
'user' => 'testuser',
@@ -73,7 +73,7 @@ class SmbTest extends \Test\Files\Storage\Storage {
$this->instance = null;
}
- public function testNotifyGetChanges() {
+ public function testNotifyGetChanges(): void {
$lastError = null;
for ($i = 0; $i < 5; $i++) {
try {
@@ -130,7 +130,7 @@ class SmbTest extends \Test\Files\Storage\Storage {
}
}
- public function testNotifyListen() {
+ public function testNotifyListen(): void {
$notifyHandler = $this->instance->notify('');
usleep(100 * 1000); //give time for the notify to start
$this->instance->file_put_contents('/newfile.txt', 'test content');
@@ -153,7 +153,7 @@ class SmbTest extends \Test\Files\Storage\Storage {
}
}
- public function testRenameRoot() {
+ public function testRenameRoot(): void {
// root can't be renamed
$this->assertFalse($this->instance->rename('', 'foo1'));
@@ -162,12 +162,12 @@ class SmbTest extends \Test\Files\Storage\Storage {
$this->instance->rmdir('foo2');
}
- public function testUnlinkRoot() {
+ public function testUnlinkRoot(): void {
// root can't be deleted
$this->assertFalse($this->instance->unlink(''));
}
- public function testRmdirRoot() {
+ public function testRmdirRoot(): void {
// root can't be deleted
$this->assertFalse($this->instance->rmdir(''));
}
diff --git a/apps/files_external/tests/Storage/SwiftTest.php b/apps/files_external/tests/Storage/SwiftTest.php
index 53ca499e4eb..c21c8c6f506 100644
--- a/apps/files_external/tests/Storage/SwiftTest.php
+++ b/apps/files_external/tests/Storage/SwiftTest.php
@@ -53,7 +53,7 @@ class SwiftTest extends \Test\Files\Storage\Storage {
parent::tearDown();
}
- public function testStat() {
+ public function testStat(): void {
$this->markTestSkipped('Swift doesn\'t update the parents folder mtime');
}
}
diff --git a/apps/files_external/tests/Storage/WebdavTest.php b/apps/files_external/tests/Storage/WebdavTest.php
index a063ddebb0d..872f1b5d0e2 100644
--- a/apps/files_external/tests/Storage/WebdavTest.php
+++ b/apps/files_external/tests/Storage/WebdavTest.php
@@ -41,7 +41,7 @@ class WebdavTest extends \Test\Files\Storage\Storage {
parent::tearDown();
}
- public function testMimetypeFallback() {
+ public function testMimetypeFallback(): void {
$this->instance->file_put_contents('foo.bar', 'asd');
/** @var Detection $mimeDetector */
diff --git a/apps/files_external/tests/StorageConfigTest.php b/apps/files_external/tests/StorageConfigTest.php
index fbbd9de94be..b67d69a3ce7 100644
--- a/apps/files_external/tests/StorageConfigTest.php
+++ b/apps/files_external/tests/StorageConfigTest.php
@@ -12,7 +12,7 @@ use OCA\Files_External\Lib\DefinitionParameter;
use OCA\Files_External\Lib\StorageConfig;
class StorageConfigTest extends \Test\TestCase {
- public function testJsonSerialization() {
+ public function testJsonSerialization(): void {
$backend = $this->getMockBuilder(Backend::class)
->disableOriginalConstructor()
->getMock();
diff --git a/apps/files_sharing/l10n/cs.js b/apps/files_sharing/l10n/cs.js
index a05f9614fab..87f4bfbb735 100644
--- a/apps/files_sharing/l10n/cs.js
+++ b/apps/files_sharing/l10n/cs.js
@@ -120,11 +120,16 @@ OC.L10N.register(
"Note for recipient" : "Poznámka pro příjemce",
"Add a note to help people understand what you are requesting." : "Přidejte poznámku vysvětlující lidem, o co žádáte.",
"Select" : "Vybrat",
+ "Create a file request" : "Vytvořit žádost o soubor",
+ "File request created" : "Žádost o soubor vytvořena",
+ "File request" : "Žádost o soubor",
"Cancel" : "Storno",
+ "Cancel the file request creation" : "Zrušit vytváření žádosti o soubor",
"Close" : "Zavřít",
"Continue" : "Pokračovat",
"Error creating the share: {errorMessage}" : "Chyba při vytváření sdílení: {errorMessage}",
"Error creating the share" : "Chyba při vytváření sdílení",
+ "_File request created and email sent_::_File request created and {count} emails sent_" : ["Byla vytvořena žádost o soubor a odeslán e-mail","Byla vytvořena žádost o soubor a odeslány {count} e-maily","Byla vytvořena žádost o soubor a odesláno {count} e-mailů","Byla vytvořena žádost o soubor a odesláno {count} e-mailů"],
"Error while toggling options" : "Chyba při přepínání voleb",
"Set default folder for accepted shares" : "Nastavit výchozí složku pro přijatá sdílení",
"Reset" : "Vrátit na výchozí hodnoty",
@@ -159,6 +164,7 @@ OC.L10N.register(
"Create a new share link" : "Vytvořit nový odkaz pro sdílení",
"{shareWith} by {initiator}" : "{shareWith} od {initiator}",
"Shared via link by {initiator}" : "{initiator} sdílí odkazem",
+ "File request ({label})" : "Žádost o soubor ({label})",
"Mail share ({label})" : "Sdílení e-mailem ({label})",
"Share link ({label})" : "Odkaz na sdílení ({label})",
"Share link ({index})" : "Odkaz na sdílení ({index})",
@@ -234,6 +240,7 @@ OC.L10N.register(
"Shared multiple times with different people" : "Nasdílet několikrát různým lidem",
"Show sharing options" : "Zobrazit předvolby pro sdílení",
"Shared with others" : "Sdíleno s ostatními",
+ "Create file request" : "Vytvořit žádost o soubor",
"No file" : "Žádný soubor",
"Public share" : "Veřejné sdílení",
"Overview of shared files." : "Přehled nasdílených souborů",
@@ -250,6 +257,10 @@ OC.L10N.register(
"List of files that are shared by link." : "Seznam souborů, které jsou nasdílené odkazem.",
"No shared links" : "Žádné sdílené odkazy",
"Files and folders you shared by link will show up here" : "Zde budou zobrazeny soubory a složky, které jste nasdíleli jako odkazy",
+ "File requests" : "Žádosti o soubory",
+ "List of file requests." : "Seznam žádostí o soubory.",
+ "No file requests" : "Žádné žádosti o soubory",
+ "File requests you have created will show up here" : "Vytvořené žádosti o soubor se zobrazí zde",
"Deleted shares" : "Smazaná sdílení",
"List of shares you left." : "Seznam sdílení, které jste opustili.",
"No deleted shares" : "Žádná smazaná sdílení",
diff --git a/apps/files_sharing/l10n/cs.json b/apps/files_sharing/l10n/cs.json
index 2dfbd50cf47..c0cf504e55a 100644
--- a/apps/files_sharing/l10n/cs.json
+++ b/apps/files_sharing/l10n/cs.json
@@ -118,11 +118,16 @@
"Note for recipient" : "Poznámka pro příjemce",
"Add a note to help people understand what you are requesting." : "Přidejte poznámku vysvětlující lidem, o co žádáte.",
"Select" : "Vybrat",
+ "Create a file request" : "Vytvořit žádost o soubor",
+ "File request created" : "Žádost o soubor vytvořena",
+ "File request" : "Žádost o soubor",
"Cancel" : "Storno",
+ "Cancel the file request creation" : "Zrušit vytváření žádosti o soubor",
"Close" : "Zavřít",
"Continue" : "Pokračovat",
"Error creating the share: {errorMessage}" : "Chyba při vytváření sdílení: {errorMessage}",
"Error creating the share" : "Chyba při vytváření sdílení",
+ "_File request created and email sent_::_File request created and {count} emails sent_" : ["Byla vytvořena žádost o soubor a odeslán e-mail","Byla vytvořena žádost o soubor a odeslány {count} e-maily","Byla vytvořena žádost o soubor a odesláno {count} e-mailů","Byla vytvořena žádost o soubor a odesláno {count} e-mailů"],
"Error while toggling options" : "Chyba při přepínání voleb",
"Set default folder for accepted shares" : "Nastavit výchozí složku pro přijatá sdílení",
"Reset" : "Vrátit na výchozí hodnoty",
@@ -157,6 +162,7 @@
"Create a new share link" : "Vytvořit nový odkaz pro sdílení",
"{shareWith} by {initiator}" : "{shareWith} od {initiator}",
"Shared via link by {initiator}" : "{initiator} sdílí odkazem",
+ "File request ({label})" : "Žádost o soubor ({label})",
"Mail share ({label})" : "Sdílení e-mailem ({label})",
"Share link ({label})" : "Odkaz na sdílení ({label})",
"Share link ({index})" : "Odkaz na sdílení ({index})",
@@ -232,6 +238,7 @@
"Shared multiple times with different people" : "Nasdílet několikrát různým lidem",
"Show sharing options" : "Zobrazit předvolby pro sdílení",
"Shared with others" : "Sdíleno s ostatními",
+ "Create file request" : "Vytvořit žádost o soubor",
"No file" : "Žádný soubor",
"Public share" : "Veřejné sdílení",
"Overview of shared files." : "Přehled nasdílených souborů",
@@ -248,6 +255,10 @@
"List of files that are shared by link." : "Seznam souborů, které jsou nasdílené odkazem.",
"No shared links" : "Žádné sdílené odkazy",
"Files and folders you shared by link will show up here" : "Zde budou zobrazeny soubory a složky, které jste nasdíleli jako odkazy",
+ "File requests" : "Žádosti o soubory",
+ "List of file requests." : "Seznam žádostí o soubory.",
+ "No file requests" : "Žádné žádosti o soubory",
+ "File requests you have created will show up here" : "Vytvořené žádosti o soubor se zobrazí zde",
"Deleted shares" : "Smazaná sdílení",
"List of shares you left." : "Seznam sdílení, které jste opustili.",
"No deleted shares" : "Žádná smazaná sdílení",
diff --git a/apps/files_sharing/l10n/pt_BR.js b/apps/files_sharing/l10n/pt_BR.js
index 760e50216cb..1673d1373a4 100644
--- a/apps/files_sharing/l10n/pt_BR.js
+++ b/apps/files_sharing/l10n/pt_BR.js
@@ -113,6 +113,9 @@ OC.L10N.register(
"You received {share} to group {group} as a share by {user}" : "Você recebeu {share} para o grupo {group} como um compartilhamento de {user}",
"Accept" : "Aceitar",
"Decline" : "Recusar",
+ "Remember to upload the files to %s" : "Lembre-se de enviar os arquivos para %s",
+ "We would like to kindly remind you that you have not yet uploaded any files to the shared folder." : "Gostaríamos de lembrar que você ainda não carregou nenhum arquivo para a pasta compartilhada.",
+ "Open \"%s\"" : "Abrir \"%s\"",
"This application enables people to share files within Nextcloud. If enabled, the admin can choose which groups can share files. The applicable people can then share files and folders with other accounts and groups within Nextcloud. In addition, if the admin enables the share link feature, an external link can be used to share files with other people outside of Nextcloud. Admins can also enforce passwords, expirations dates, and enable server to server sharing via share links, as well as sharing from mobile devices.\nTurning the feature off removes shared files and folders on the server for all share recipients, and also on the sync clients and mobile apps. More information is available in the Nextcloud Documentation." : "Este aplicativo permite que as pessoas compartilhem arquivos dentro do Nextcloud. Se ativado, o administrador pode escolher quais grupos podem compartilhar arquivos. As pessoas aplicáveis ​​podem então compartilhar arquivos e pastas com outras contas e grupos dentro do Nextcloud. Além disso, se o administrador ativar o recurso de compartilhamento de link, um link externo poderá ser usado para compartilhar arquivos com outras pessoas fora do Nextcloud. Os administradores também podem impor senhas, datas de expiração e permitir o compartilhamento de servidor para servidor por meio de links de compartilhamento, bem como compartilhamento de dispositivos móveis. \nDesativar o recurso remove arquivos e pastas compartilhados no servidor para todos os destinatários de compartilhamento e também nos clientes de sincronização e aplicativos móveis. Mais informações estão disponíveis na documentação do Nextcloud.",
"People" : "Pessoas",
"Filter accounts" : "Filtrar contas",
@@ -244,9 +247,14 @@ OC.L10N.register(
"Note from" : "Nota de",
"Note:" : "Anotação:",
"File drop" : "Baixar Arquivo ",
+ "Upload files to {foldername}." : "Subir arquivos para {foldername}.",
+ "By uploading files, you agree to the terms of service." : "Ao enviar arquivos, você concorda com os termos de serviço.",
+ "View terms of service" : "Ver os termos de serviço",
"Terms of service" : "Termos de serviço",
"{ownerDisplayName} shared a folder with you." : "{ownerDisplayName} compartilhou uma pasta com você.",
"To upload files, you need to provide your name first." : "Para fazer upload de arquivos, você precisa primeiro fornecer seu nome.",
+ "Nickname" : "Apelido",
+ "Enter your nickname" : "Digite seu apelido",
"Upload files to {folder}" : "Enviar arquivos para {folder}",
"Submit name" : "Enviar nome",
"Allow upload and editing" : "Permitir envio e edição",
@@ -283,6 +291,7 @@ OC.L10N.register(
"Toggle list of others with access to this directory" : "Alternar a lista de outras pessoas com acesso a este diretório",
"Toggle list of others with access to this file" : "Alternar a lista de outras pessoas com acesso a este arquivo",
"Unable to fetch inherited shares" : "Não foi possível buscar compartilhamentos herdados",
+ "Link shares" : "Compartilhamentos de links",
"Shares" : "Compartilhamentos",
"Unable to load the shares list" : "Não foi possível carregar a lista de compartilhamentos",
"Expires {relativetime}" : "Expira {relativetime}",
@@ -300,8 +309,15 @@ OC.L10N.register(
"Show sharing options" : "Mostrar opções de compartilhamento",
"Shared with others" : "Compartilhado com outros",
"Create file request" : "Criar solicitação de arquivo",
+ "Upload files to {foldername}" : "Subir arquivos para {foldername}",
+ "Public file share" : "Compartilhamento público de arquivo",
+ "Public shared file." : "Arquivo público compartilhado.",
"No file" : "Sem arquivo",
+ "The file shared with you will show up here" : "O arquivo compartilhado com você aparecerá aqui",
"Public share" : "Compartilhamento público",
+ "Public shared files." : "Arquivos de compartilhamentos públicos.",
+ "No files" : "Não há arquivos",
+ "Files and folders shared with you will show up here" : "Arquivos e pastas compartilhados com você aparecerão aqui",
"Overview of shared files." : "Visão geral dos arquivos compartilhados.",
"No shares" : "Sem compartilhamentos",
"Files and folders you shared or have been shared with you will show up here" : "Arquivos e pastas que você compartilhou ou foram compartilhados com você aparecerão aqui",
diff --git a/apps/files_sharing/l10n/pt_BR.json b/apps/files_sharing/l10n/pt_BR.json
index 4bfad8d9ec1..393c7afcfc6 100644
--- a/apps/files_sharing/l10n/pt_BR.json
+++ b/apps/files_sharing/l10n/pt_BR.json
@@ -111,6 +111,9 @@
"You received {share} to group {group} as a share by {user}" : "Você recebeu {share} para o grupo {group} como um compartilhamento de {user}",
"Accept" : "Aceitar",
"Decline" : "Recusar",
+ "Remember to upload the files to %s" : "Lembre-se de enviar os arquivos para %s",
+ "We would like to kindly remind you that you have not yet uploaded any files to the shared folder." : "Gostaríamos de lembrar que você ainda não carregou nenhum arquivo para a pasta compartilhada.",
+ "Open \"%s\"" : "Abrir \"%s\"",
"This application enables people to share files within Nextcloud. If enabled, the admin can choose which groups can share files. The applicable people can then share files and folders with other accounts and groups within Nextcloud. In addition, if the admin enables the share link feature, an external link can be used to share files with other people outside of Nextcloud. Admins can also enforce passwords, expirations dates, and enable server to server sharing via share links, as well as sharing from mobile devices.\nTurning the feature off removes shared files and folders on the server for all share recipients, and also on the sync clients and mobile apps. More information is available in the Nextcloud Documentation." : "Este aplicativo permite que as pessoas compartilhem arquivos dentro do Nextcloud. Se ativado, o administrador pode escolher quais grupos podem compartilhar arquivos. As pessoas aplicáveis ​​podem então compartilhar arquivos e pastas com outras contas e grupos dentro do Nextcloud. Além disso, se o administrador ativar o recurso de compartilhamento de link, um link externo poderá ser usado para compartilhar arquivos com outras pessoas fora do Nextcloud. Os administradores também podem impor senhas, datas de expiração e permitir o compartilhamento de servidor para servidor por meio de links de compartilhamento, bem como compartilhamento de dispositivos móveis. \nDesativar o recurso remove arquivos e pastas compartilhados no servidor para todos os destinatários de compartilhamento e também nos clientes de sincronização e aplicativos móveis. Mais informações estão disponíveis na documentação do Nextcloud.",
"People" : "Pessoas",
"Filter accounts" : "Filtrar contas",
@@ -242,9 +245,14 @@
"Note from" : "Nota de",
"Note:" : "Anotação:",
"File drop" : "Baixar Arquivo ",
+ "Upload files to {foldername}." : "Subir arquivos para {foldername}.",
+ "By uploading files, you agree to the terms of service." : "Ao enviar arquivos, você concorda com os termos de serviço.",
+ "View terms of service" : "Ver os termos de serviço",
"Terms of service" : "Termos de serviço",
"{ownerDisplayName} shared a folder with you." : "{ownerDisplayName} compartilhou uma pasta com você.",
"To upload files, you need to provide your name first." : "Para fazer upload de arquivos, você precisa primeiro fornecer seu nome.",
+ "Nickname" : "Apelido",
+ "Enter your nickname" : "Digite seu apelido",
"Upload files to {folder}" : "Enviar arquivos para {folder}",
"Submit name" : "Enviar nome",
"Allow upload and editing" : "Permitir envio e edição",
@@ -281,6 +289,7 @@
"Toggle list of others with access to this directory" : "Alternar a lista de outras pessoas com acesso a este diretório",
"Toggle list of others with access to this file" : "Alternar a lista de outras pessoas com acesso a este arquivo",
"Unable to fetch inherited shares" : "Não foi possível buscar compartilhamentos herdados",
+ "Link shares" : "Compartilhamentos de links",
"Shares" : "Compartilhamentos",
"Unable to load the shares list" : "Não foi possível carregar a lista de compartilhamentos",
"Expires {relativetime}" : "Expira {relativetime}",
@@ -298,8 +307,15 @@
"Show sharing options" : "Mostrar opções de compartilhamento",
"Shared with others" : "Compartilhado com outros",
"Create file request" : "Criar solicitação de arquivo",
+ "Upload files to {foldername}" : "Subir arquivos para {foldername}",
+ "Public file share" : "Compartilhamento público de arquivo",
+ "Public shared file." : "Arquivo público compartilhado.",
"No file" : "Sem arquivo",
+ "The file shared with you will show up here" : "O arquivo compartilhado com você aparecerá aqui",
"Public share" : "Compartilhamento público",
+ "Public shared files." : "Arquivos de compartilhamentos públicos.",
+ "No files" : "Não há arquivos",
+ "Files and folders shared with you will show up here" : "Arquivos e pastas compartilhados com você aparecerão aqui",
"Overview of shared files." : "Visão geral dos arquivos compartilhados.",
"No shares" : "Sem compartilhamentos",
"Files and folders you shared or have been shared with you will show up here" : "Arquivos e pastas que você compartilhou ou foram compartilhados com você aparecerão aqui",
diff --git a/apps/files_sharing/lib/External/Manager.php b/apps/files_sharing/lib/External/Manager.php
index 9d008170e68..a3226e9f3dd 100644
--- a/apps/files_sharing/lib/External/Manager.php
+++ b/apps/files_sharing/lib/External/Manager.php
@@ -119,7 +119,7 @@ class Manager {
* @throws \Doctrine\DBAL\Exception
*/
public function addShare($remote, $token, $password, $name, $owner, $shareType, $accepted = false, $user = null, $remoteId = '', $parent = -1) {
- $user = $user ? $user : $this->uid;
+ $user = $user ?? $this->uid;
$accepted = $accepted ? IShare::STATUS_ACCEPTED : IShare::STATUS_PENDING;
$name = Filesystem::normalizePath('/' . $name);
diff --git a/apps/files_sharing/tests/ApiTest.php b/apps/files_sharing/tests/ApiTest.php
index 7ce7d2e5226..3806a8c1ea2 100644
--- a/apps/files_sharing/tests/ApiTest.php
+++ b/apps/files_sharing/tests/ApiTest.php
@@ -125,7 +125,7 @@ class ApiTest extends TestCase {
);
}
- public function testCreateShareUserFile() {
+ public function testCreateShareUserFile(): void {
$this->setUp(); // for some reasons phpunit refuses to do this for us only for this test
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
$result = $ocs->createShare($this->filename, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_USER, self::TEST_FILES_SHARING_API_USER2);
@@ -143,7 +143,7 @@ class ApiTest extends TestCase {
$ocs->cleanup();
}
- public function testCreateShareUserFolder() {
+ public function testCreateShareUserFolder(): void {
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
$result = $ocs->createShare($this->folder, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_USER, self::TEST_FILES_SHARING_API_USER2);
$ocs->cleanup();
@@ -160,7 +160,7 @@ class ApiTest extends TestCase {
}
- public function testCreateShareGroupFile() {
+ public function testCreateShareGroupFile(): void {
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
$result = $ocs->createShare($this->filename, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_GROUP, self::TEST_FILES_SHARING_API_GROUP1);
$ocs->cleanup();
@@ -176,7 +176,7 @@ class ApiTest extends TestCase {
$ocs->cleanup();
}
- public function testCreateShareGroupFolder() {
+ public function testCreateShareGroupFolder(): void {
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
$result = $ocs->createShare($this->folder, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_GROUP, self::TEST_FILES_SHARING_API_GROUP1);
$ocs->cleanup();
@@ -195,7 +195,7 @@ class ApiTest extends TestCase {
/**
* @group RoutingWeirdness
*/
- public function testCreateShareLink() {
+ public function testCreateShareLink(): void {
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
$result = $ocs->createShare($this->folder, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_LINK);
$ocs->cleanup();
@@ -220,7 +220,7 @@ class ApiTest extends TestCase {
/**
* @group RoutingWeirdness
*/
- public function testCreateShareLinkPublicUpload() {
+ public function testCreateShareLinkPublicUpload(): void {
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
$result = $ocs->createShare($this->folder, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'true');
$ocs->cleanup();
@@ -248,7 +248,7 @@ class ApiTest extends TestCase {
$ocs->cleanup();
}
- public function testEnforceLinkPassword() {
+ public function testEnforceLinkPassword(): void {
$password = md5(time());
$config = \OC::$server->getConfig();
$config->setAppValue('core', 'shareapi_enforce_links_password', 'yes');
@@ -302,7 +302,7 @@ class ApiTest extends TestCase {
/**
* @medium
*/
- public function testSharePermissions() {
+ public function testSharePermissions(): void {
// sharing file to a user should work if shareapi_exclude_groups is set
// to no
\OC::$server->getConfig()->setAppValue('core', 'shareapi_exclude_groups', 'no');
@@ -353,7 +353,7 @@ class ApiTest extends TestCase {
/**
* @medium
*/
- public function testGetAllShares() {
+ public function testGetAllShares(): void {
$node = $this->userFolder->get($this->filename);
$share = $this->shareManager->newShare();
@@ -374,7 +374,7 @@ class ApiTest extends TestCase {
$this->shareManager->deleteShare($share);
}
- public function testGetAllSharesWithMe() {
+ public function testGetAllSharesWithMe(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER2);
$this->logout();
@@ -414,7 +414,7 @@ class ApiTest extends TestCase {
* @medium
* @group RoutingWeirdness
*/
- public function testPublicLinkUrl() {
+ public function testPublicLinkUrl(): void {
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
$result = $ocs->createShare($this->folder, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_LINK);
$ocs->cleanup();
@@ -463,7 +463,7 @@ class ApiTest extends TestCase {
* @depends testCreateShareUserFile
* @depends testCreateShareLink
*/
- public function testGetShareFromSource() {
+ public function testGetShareFromSource(): void {
$node = $this->userFolder->get($this->filename);
$share = $this->shareManager->newShare();
$share->setNode($node)
@@ -496,7 +496,7 @@ class ApiTest extends TestCase {
* @depends testCreateShareUserFile
* @depends testCreateShareLink
*/
- public function testGetShareFromSourceWithReshares() {
+ public function testGetShareFromSourceWithReshares(): void {
$node = $this->userFolder->get($this->filename);
$share1 = $this->shareManager->newShare();
$share1->setNode($node)
@@ -537,7 +537,7 @@ class ApiTest extends TestCase {
* @medium
* @depends testCreateShareUserFile
*/
- public function testGetShareFromId() {
+ public function testGetShareFromId(): void {
$node = $this->userFolder->get($this->filename);
$share1 = $this->shareManager->newShare();
$share1->setNode($node)
@@ -561,7 +561,7 @@ class ApiTest extends TestCase {
/**
* @medium
*/
- public function testGetShareFromFolder() {
+ public function testGetShareFromFolder(): void {
$node1 = $this->userFolder->get($this->filename);
$share1 = $this->shareManager->newShare();
$share1->setNode($node1)
@@ -591,7 +591,7 @@ class ApiTest extends TestCase {
$this->shareManager->deleteShare($share2);
}
- public function testGetShareFromFolderWithFile() {
+ public function testGetShareFromFolderWithFile(): void {
$node1 = $this->userFolder->get($this->filename);
$share1 = $this->shareManager->newShare();
$share1->setNode($node1)
@@ -617,7 +617,7 @@ class ApiTest extends TestCase {
* share a folder, than reshare a file within the shared folder and check if we construct the correct path
* @medium
*/
- public function testGetShareFromFolderReshares() {
+ public function testGetShareFromFolderReshares(): void {
$node1 = $this->userFolder->get($this->folder);
$share1 = $this->shareManager->newShare();
$share1->setNode($node1)
@@ -677,7 +677,7 @@ class ApiTest extends TestCase {
* reshare a sub folder and check if we get the correct path
* @medium
*/
- public function testGetShareFromSubFolderReShares() {
+ public function testGetShareFromSubFolderReShares(): void {
$node1 = $this->userFolder->get($this->folder . $this->subfolder);
$share1 = $this->shareManager->newShare();
$share1->setNode($node1)
@@ -796,7 +796,7 @@ class ApiTest extends TestCase {
* test multiple shared folder if the path gets constructed correctly
* @medium
*/
- public function testGetShareMultipleSharedFolder() {
+ public function testGetShareMultipleSharedFolder(): void {
$this->setUp();
$node1 = $this->userFolder->get($this->folder . $this->subfolder);
$share1 = $this->shareManager->newShare();
@@ -861,7 +861,7 @@ class ApiTest extends TestCase {
* test re-re-share of folder if the path gets constructed correctly
* @medium
*/
- public function testGetShareFromFileReReShares() {
+ public function testGetShareFromFileReReShares(): void {
$node1 = $this->userFolder->get($this->folder . $this->subfolder);
$share1 = $this->shareManager->newShare();
$share1->setNode($node1)
@@ -916,7 +916,7 @@ class ApiTest extends TestCase {
/**
* @medium
*/
- public function testGetShareFromUnknownId() {
+ public function testGetShareFromUnknownId(): void {
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER3);
try {
$ocs->getShare(0);
@@ -932,7 +932,7 @@ class ApiTest extends TestCase {
* @depends testCreateShareUserFile
* @depends testCreateShareLink
*/
- public function testUpdateShare() {
+ public function testUpdateShare(): void {
$password = md5(time());
$node1 = $this->userFolder->get($this->filename);
@@ -992,7 +992,7 @@ class ApiTest extends TestCase {
/**
* @medium
*/
- public function testUpdateShareUpload() {
+ public function testUpdateShareUpload(): void {
$node1 = $this->userFolder->get($this->folder);
$share1 = $this->shareManager->newShare();
$share1->setNode($node1)
@@ -1023,7 +1023,7 @@ class ApiTest extends TestCase {
/**
* @medium
*/
- public function testUpdateShareExpireDate() {
+ public function testUpdateShareExpireDate(): void {
$node1 = $this->userFolder->get($this->folder);
$share1 = $this->shareManager->newShare();
$share1->setNode($node1)
@@ -1096,7 +1096,7 @@ class ApiTest extends TestCase {
* @medium
* @depends testCreateShareUserFile
*/
- public function testDeleteShare() {
+ public function testDeleteShare(): void {
$node1 = $this->userFolder->get($this->filename);
$share1 = $this->shareManager->newShare();
$share1->setNode($node1)
@@ -1128,7 +1128,7 @@ class ApiTest extends TestCase {
/**
* test unshare of a reshared file
*/
- public function testDeleteReshare() {
+ public function testDeleteReshare(): void {
$node1 = $this->userFolder->get($this->folder);
$share1 = $this->shareManager->newShare();
$share1->setNode($node1)
@@ -1163,7 +1163,7 @@ class ApiTest extends TestCase {
/**
* share a folder which contains a share mount point, should be forbidden
*/
- public function testShareFolderWithAMountPoint() {
+ public function testShareFolderWithAMountPoint(): void {
// user 1 shares a folder with user2
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
@@ -1230,7 +1230,7 @@ class ApiTest extends TestCase {
/**
* Tests mounting a folder that is an external storage mount point.
*/
- public function testShareStorageMountPoint() {
+ public function testShareStorageMountPoint(): void {
$tempStorage = new \OC\Files\Storage\Temporary([]);
$tempStorage->file_put_contents('test.txt', 'abcdef');
$tempStorage->getScanner()->scan('');
@@ -1286,7 +1286,7 @@ class ApiTest extends TestCase {
* @dataProvider datesProvider
* @group RoutingWeirdness
*/
- public function testPublicLinkExpireDate($date, $valid) {
+ public function testPublicLinkExpireDate($date, $valid): void {
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
try {
@@ -1318,7 +1318,7 @@ class ApiTest extends TestCase {
/**
* @group RoutingWeirdness
*/
- public function testCreatePublicLinkExpireDateValid() {
+ public function testCreatePublicLinkExpireDateValid(): void {
$config = \OC::$server->getConfig();
// enforce expire date, by default 7 days after the file was shared
@@ -1350,7 +1350,7 @@ class ApiTest extends TestCase {
$config->setAppValue('core', 'shareapi_enforce_expire_date', 'no');
}
- public function testCreatePublicLinkExpireDateInvalidFuture() {
+ public function testCreatePublicLinkExpireDateInvalidFuture(): void {
$config = \OC::$server->getConfig();
// enforce expire date, by default 7 days after the file was shared
@@ -1400,7 +1400,7 @@ class ApiTest extends TestCase {
* test for no invisible shares
* See: https://github.com/owncloud/core/issues/22295
*/
- public function testInvisibleSharesUser() {
+ public function testInvisibleSharesUser(): void {
// simulate a post request
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
$result = $ocs->createShare($this->folder, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_USER, self::TEST_FILES_SHARING_API_USER2);
@@ -1432,7 +1432,7 @@ class ApiTest extends TestCase {
* test for no invisible shares
* See: https://github.com/owncloud/core/issues/22295
*/
- public function testInvisibleSharesGroup() {
+ public function testInvisibleSharesGroup(): void {
// simulate a post request
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
$result = $ocs->createShare($this->folder, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_GROUP, self::TEST_FILES_SHARING_API_GROUP1);
diff --git a/apps/files_sharing/tests/CacheTest.php b/apps/files_sharing/tests/CacheTest.php
index 9f4a4b9e2ea..4db3adf34a6 100644
--- a/apps/files_sharing/tests/CacheTest.php
+++ b/apps/files_sharing/tests/CacheTest.php
@@ -188,7 +188,7 @@ class CacheTest extends TestCase {
* we cannot use a dataProvider because that would cause the stray hook detection to remove the hooks
* that were added in setUpBeforeClass.
*/
- public function testSearch() {
+ public function testSearch(): void {
foreach ($this->searchDataProvider() as $data) {
[$pattern, $expectedFiles] = $data;
@@ -200,7 +200,7 @@ class CacheTest extends TestCase {
/**
* Test searching by mime type
*/
- public function testSearchByMime() {
+ public function testSearchByMime(): void {
$results = $this->sharedStorage->getCache()->searchByMime('text');
$check = [
[
@@ -219,7 +219,7 @@ class CacheTest extends TestCase {
$this->verifyFiles($check, $results);
}
- public function testGetFolderContentsInRoot() {
+ public function testGetFolderContentsInRoot(): void {
$results = $this->user2View->getDirectoryContent('/');
$results = (array_filter($results, function ($file) {
return $file->getName() !== 'welcome.txt';
@@ -249,7 +249,7 @@ class CacheTest extends TestCase {
);
}
- public function testGetFolderContentsInSubdir() {
+ public function testGetFolderContentsInSubdir(): void {
$results = $this->user2View->getDirectoryContent('/shareddir');
$this->verifyFiles(
@@ -287,7 +287,7 @@ class CacheTest extends TestCase {
*
* https://github.com/nextcloud/server/issues/39879
*/
- public function testShareRenameOriginalFileInRecentResults() {
+ public function testShareRenameOriginalFileInRecentResults(): void {
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
$rootFolder = \OC::$server->getUserFolder(self::TEST_FILES_SHARING_API_USER1);
@@ -316,7 +316,7 @@ class CacheTest extends TestCase {
}, $recents));
}
- public function testGetFolderContentsWhenSubSubdirShared() {
+ public function testGetFolderContentsWhenSubSubdirShared(): void {
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
$rootFolder = \OC::$server->getUserFolder(self::TEST_FILES_SHARING_API_USER1);
@@ -400,7 +400,7 @@ class CacheTest extends TestCase {
}
}
- public function testGetPathByIdDirectShare() {
+ public function testGetPathByIdDirectShare(): void {
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
\OC\Files\Filesystem::file_put_contents('test.txt', 'foo');
$info = \OC\Files\Filesystem::getFileInfo('test.txt');
@@ -430,7 +430,7 @@ class CacheTest extends TestCase {
$this->assertEquals('', $sharedCache->getPathById($info->getId()));
}
- public function testGetPathByIdShareSubFolder() {
+ public function testGetPathByIdShareSubFolder(): void {
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
\OC\Files\Filesystem::mkdir('foo');
\OC\Files\Filesystem::mkdir('foo/bar');
@@ -463,7 +463,7 @@ class CacheTest extends TestCase {
$this->assertEquals('bar/test.txt', $sharedCache->getPathById($fileInfo->getId()));
}
- public function testNumericStorageId() {
+ public function testNumericStorageId(): void {
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
\OC\Files\Filesystem::mkdir('foo');
@@ -490,7 +490,7 @@ class CacheTest extends TestCase {
$this->assertEquals($sourceStorage->getCache()->getNumericStorageId(), $sharedStorage->getCache()->getNumericStorageId());
}
- public function testShareJailedStorage() {
+ public function testShareJailedStorage(): void {
$sourceStorage = new Temporary();
$sourceStorage->mkdir('jail');
$sourceStorage->mkdir('jail/sub');
@@ -529,7 +529,7 @@ class CacheTest extends TestCase {
$this->assertTrue($sourceStorage->getCache()->inCache('jail/sub/bar.txt'));
}
- public function testSearchShareJailedStorage() {
+ public function testSearchShareJailedStorage(): void {
$sourceStorage = new Temporary();
$sourceStorage->mkdir('jail');
$sourceStorage->mkdir('jail/sub');
diff --git a/apps/files_sharing/tests/CapabilitiesTest.php b/apps/files_sharing/tests/CapabilitiesTest.php
index 69911100f56..c188cbfdfcc 100644
--- a/apps/files_sharing/tests/CapabilitiesTest.php
+++ b/apps/files_sharing/tests/CapabilitiesTest.php
@@ -81,7 +81,7 @@ class CapabilitiesTest extends \Test\TestCase {
return $result;
}
- public function testEnabledSharingAPI() {
+ public function testEnabledSharingAPI(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
];
@@ -92,7 +92,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertArrayHasKey('resharing', $result);
}
- public function testDisabledSharingAPI() {
+ public function testDisabledSharingAPI(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'no'],
];
@@ -103,7 +103,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertFalse($result['resharing']);
}
- public function testNoLinkSharing() {
+ public function testNoLinkSharing(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_links', 'yes', 'no'],
@@ -113,7 +113,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertFalse($result['public']['enabled']);
}
- public function testOnlyLinkSharing() {
+ public function testOnlyLinkSharing(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_links', 'yes', 'yes'],
@@ -124,7 +124,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertTrue($result['public']['enabled']);
}
- public function testLinkPassword() {
+ public function testLinkPassword(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_links', 'yes', 'yes'],
@@ -137,7 +137,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertTrue($result['public']['password']['enforced']);
}
- public function testLinkNoPassword() {
+ public function testLinkNoPassword(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_links', 'yes', 'yes'],
@@ -150,7 +150,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertFalse($result['public']['password']['enforced']);
}
- public function testLinkNoExpireDate() {
+ public function testLinkNoExpireDate(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_links', 'yes', 'yes'],
@@ -163,7 +163,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertFalse($result['public']['expire_date']['enabled']);
}
- public function testLinkExpireDate() {
+ public function testLinkExpireDate(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_links', 'yes', 'yes'],
@@ -180,7 +180,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertFalse($result['public']['expire_date']['enforced']);
}
- public function testLinkExpireDateEnforced() {
+ public function testLinkExpireDateEnforced(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_links', 'yes', 'yes'],
@@ -194,7 +194,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertTrue($result['public']['expire_date']['enforced']);
}
- public function testLinkSendMail() {
+ public function testLinkSendMail(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_links', 'yes', 'yes'],
@@ -205,7 +205,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertTrue($result['public']['send_mail']);
}
- public function testLinkNoSendMail() {
+ public function testLinkNoSendMail(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_links', 'yes', 'yes'],
@@ -216,7 +216,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertFalse($result['public']['send_mail']);
}
- public function testResharing() {
+ public function testResharing(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_resharing', 'yes', 'yes'],
@@ -226,7 +226,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertTrue($result['resharing']);
}
- public function testNoResharing() {
+ public function testNoResharing(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_resharing', 'yes', 'no'],
@@ -236,7 +236,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertFalse($result['resharing']);
}
- public function testLinkPublicUpload() {
+ public function testLinkPublicUpload(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_links', 'yes', 'yes'],
@@ -248,7 +248,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertTrue($result['public']['upload_files_drop']);
}
- public function testLinkNoPublicUpload() {
+ public function testLinkNoPublicUpload(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_links', 'yes', 'yes'],
@@ -260,7 +260,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertFalse($result['public']['upload_files_drop']);
}
- public function testNoGroupSharing() {
+ public function testNoGroupSharing(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_group_sharing', 'yes', 'no'],
@@ -269,7 +269,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertFalse($result['group_sharing']);
}
- public function testGroupSharing() {
+ public function testGroupSharing(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_group_sharing', 'yes', 'yes'],
@@ -278,7 +278,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertTrue($result['group_sharing']);
}
- public function testFederatedSharingIncoming() {
+ public function testFederatedSharingIncoming(): void {
$map = [
['files_sharing', 'incoming_server2server_share_enabled', 'yes', 'yes'],
];
@@ -287,7 +287,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertTrue($result['federation']['incoming']);
}
- public function testFederatedSharingNoIncoming() {
+ public function testFederatedSharingNoIncoming(): void {
$map = [
['files_sharing', 'incoming_server2server_share_enabled', 'yes', 'no'],
];
@@ -296,7 +296,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertFalse($result['federation']['incoming']);
}
- public function testFederatedSharingOutgoing() {
+ public function testFederatedSharingOutgoing(): void {
$map = [
['files_sharing', 'outgoing_server2server_share_enabled', 'yes', 'yes'],
];
@@ -305,7 +305,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertTrue($result['federation']['outgoing']);
}
- public function testFederatedSharingNoOutgoing() {
+ public function testFederatedSharingNoOutgoing(): void {
$map = [
['files_sharing', 'outgoing_server2server_share_enabled', 'yes', 'no'],
];
@@ -314,7 +314,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertFalse($result['federation']['outgoing']);
}
- public function testFederatedSharingExpirationDate() {
+ public function testFederatedSharingExpirationDate(): void {
$result = $this->getResults([]);
$this->assertArrayHasKey('federation', $result);
$this->assertEquals(['enabled' => true], $result['federation']['expire_date']);
diff --git a/apps/files_sharing/tests/Collaboration/ShareRecipientSorterTest.php b/apps/files_sharing/tests/Collaboration/ShareRecipientSorterTest.php
index 309bb84d6df..83dde42f37b 100644
--- a/apps/files_sharing/tests/Collaboration/ShareRecipientSorterTest.php
+++ b/apps/files_sharing/tests/Collaboration/ShareRecipientSorterTest.php
@@ -38,7 +38,7 @@ class ShareRecipientSorterTest extends TestCase {
* @dataProvider sortDataProvider
* @param $data
*/
- public function testSort($data) {
+ public function testSort($data): void {
$node = $this->createMock(Node::class);
/** @var Folder|\PHPUnit\Framework\MockObject\MockObject $folder */
@@ -79,7 +79,7 @@ class ShareRecipientSorterTest extends TestCase {
$this->assertEquals($data['expected'], $workArray);
}
- public function testSortNoNodes() {
+ public function testSortNoNodes(): void {
/** @var Folder|\PHPUnit\Framework\MockObject\MockObject $folder */
$folder = $this->createMock(Folder::class);
$this->rootFolder->expects($this->any())
diff --git a/apps/files_sharing/tests/Command/CleanupRemoteStoragesTest.php b/apps/files_sharing/tests/Command/CleanupRemoteStoragesTest.php
index 803ee1d02c9..05b412a60b6 100644
--- a/apps/files_sharing/tests/Command/CleanupRemoteStoragesTest.php
+++ b/apps/files_sharing/tests/Command/CleanupRemoteStoragesTest.php
@@ -163,7 +163,7 @@ class CleanupRemoteStoragesTest extends TestCase {
/**
* Test cleanup of orphaned storages
*/
- public function testCleanup() {
+ public function testCleanup(): void {
$input = $this->getMockBuilder(InputInterface::class)
->disableOriginalConstructor()
->getMock();
diff --git a/apps/files_sharing/tests/Controller/ExternalShareControllerTest.php b/apps/files_sharing/tests/Controller/ExternalShareControllerTest.php
index 3b4173ba7fa..eac37a3f3a5 100644
--- a/apps/files_sharing/tests/Controller/ExternalShareControllerTest.php
+++ b/apps/files_sharing/tests/Controller/ExternalShareControllerTest.php
@@ -53,7 +53,7 @@ class ExternalShareControllerTest extends \Test\TestCase {
);
}
- public function testIndex() {
+ public function testIndex(): void {
$this->externalManager
->expects($this->once())
->method('getOpenShares')
@@ -62,7 +62,7 @@ class ExternalShareControllerTest extends \Test\TestCase {
$this->assertEquals(new JSONResponse(['MyDummyArray']), $this->getExternalShareController()->index());
}
- public function testCreate() {
+ public function testCreate(): void {
$this->externalManager
->expects($this->once())
->method('acceptShare')
@@ -71,7 +71,7 @@ class ExternalShareControllerTest extends \Test\TestCase {
$this->assertEquals(new JSONResponse(), $this->getExternalShareController()->create(4));
}
- public function testDestroy() {
+ public function testDestroy(): void {
$this->externalManager
->expects($this->once())
->method('declineShare')
@@ -80,7 +80,7 @@ class ExternalShareControllerTest extends \Test\TestCase {
$this->assertEquals(new JSONResponse(), $this->getExternalShareController()->destroy(4));
}
- public function testRemoteWithValidHttps() {
+ public function testRemoteWithValidHttps(): void {
$client = $this->createMock(IClient::class);
$response = $this->createMock(IResponse::class);
$response
@@ -103,7 +103,7 @@ class ExternalShareControllerTest extends \Test\TestCase {
$this->assertEquals(new DataResponse('https'), $this->getExternalShareController()->testRemote('nextcloud.com'));
}
- public function testRemoteWithWorkingHttp() {
+ public function testRemoteWithWorkingHttp(): void {
$client = $this->createMock(IClient::class);
$response = $this->createMock(IResponse::class);
$client
@@ -127,7 +127,7 @@ class ExternalShareControllerTest extends \Test\TestCase {
$this->assertEquals(new DataResponse('http'), $this->getExternalShareController()->testRemote('nextcloud.com'));
}
- public function testRemoteWithInvalidRemote() {
+ public function testRemoteWithInvalidRemote(): void {
$client = $this->createMock(IClient::class);
$response = $this->createMock(IResponse::class);
$client
@@ -158,7 +158,7 @@ class ExternalShareControllerTest extends \Test\TestCase {
* @dataProvider dataRemoteWithInvalidRemoteURLs
* @param string $remote
*/
- public function testRemoteWithInvalidRemoteURLs(string $remote) {
+ public function testRemoteWithInvalidRemoteURLs(string $remote): void {
$this->clientService
->expects($this->never())
->method('newClient');
diff --git a/apps/files_sharing/tests/Controller/PublicPreviewControllerTest.php b/apps/files_sharing/tests/Controller/PublicPreviewControllerTest.php
index d1e542cc5d9..700406c97ba 100644
--- a/apps/files_sharing/tests/Controller/PublicPreviewControllerTest.php
+++ b/apps/files_sharing/tests/Controller/PublicPreviewControllerTest.php
@@ -57,28 +57,28 @@ class PublicPreviewControllerTest extends TestCase {
);
}
- public function testInvalidToken() {
+ public function testInvalidToken(): void {
$res = $this->controller->getPreview('', 'file', 10, 10, '');
$expected = new DataResponse([], Http::STATUS_BAD_REQUEST);
$this->assertEquals($expected, $res);
}
- public function testInvalidWidth() {
+ public function testInvalidWidth(): void {
$res = $this->controller->getPreview('token', 'file', 0);
$expected = new DataResponse([], Http::STATUS_BAD_REQUEST);
$this->assertEquals($expected, $res);
}
- public function testInvalidHeight() {
+ public function testInvalidHeight(): void {
$res = $this->controller->getPreview('token', 'file', 10, 0);
$expected = new DataResponse([], Http::STATUS_BAD_REQUEST);
$this->assertEquals($expected, $res);
}
- public function testInvalidShare() {
+ public function testInvalidShare(): void {
$this->shareManager->method('getShareByToken')
->with($this->equalTo('token'))
->willThrowException(new ShareNotFound());
@@ -89,7 +89,7 @@ class PublicPreviewControllerTest extends TestCase {
$this->assertEquals($expected, $res);
}
- public function testShareNotAccessable() {
+ public function testShareNotAccessable(): void {
$share = $this->createMock(IShare::class);
$this->shareManager->method('getShareByToken')
->with($this->equalTo('token'))
@@ -104,7 +104,7 @@ class PublicPreviewControllerTest extends TestCase {
$this->assertEquals($expected, $res);
}
- public function testPreviewFile() {
+ public function testPreviewFile(): void {
$share = $this->createMock(IShare::class);
$this->shareManager->method('getShareByToken')
->with($this->equalTo('token'))
@@ -133,7 +133,7 @@ class PublicPreviewControllerTest extends TestCase {
$this->assertEquals($expected, $res);
}
- public function testPreviewFolderInvalidFile() {
+ public function testPreviewFolderInvalidFile(): void {
$share = $this->createMock(IShare::class);
$this->shareManager->method('getShareByToken')
->with($this->equalTo('token'))
@@ -156,7 +156,7 @@ class PublicPreviewControllerTest extends TestCase {
}
- public function testPreviewFolderValidFile() {
+ public function testPreviewFolderValidFile(): void {
$share = $this->createMock(IShare::class);
$this->shareManager->method('getShareByToken')
->with($this->equalTo('token'))
diff --git a/apps/files_sharing/tests/Controller/ShareAPIControllerTest.php b/apps/files_sharing/tests/Controller/ShareAPIControllerTest.php
index c7163c7141c..8c894f87559 100644
--- a/apps/files_sharing/tests/Controller/ShareAPIControllerTest.php
+++ b/apps/files_sharing/tests/Controller/ShareAPIControllerTest.php
@@ -174,7 +174,7 @@ class ShareAPIControllerTest extends TestCase {
return [$shareAttributes, \json_encode($formattedShareAttributes)];
}
- public function testDeleteShareShareNotFound() {
+ public function testDeleteShareShareNotFound(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
$this->expectExceptionMessage('Wrong share ID, share does not exist');
@@ -194,7 +194,7 @@ class ShareAPIControllerTest extends TestCase {
$this->ocs->deleteShare(42);
}
- public function testDeleteShare() {
+ public function testDeleteShare(): void {
$node = $this->getMockBuilder(File::class)->getMock();
$share = $this->newShare();
@@ -222,7 +222,7 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testDeleteShareLocked() {
+ public function testDeleteShareLocked(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
$this->expectExceptionMessage('Could not delete share');
@@ -256,7 +256,7 @@ class ShareAPIControllerTest extends TestCase {
/**
* You can always remove a share that was shared with you
*/
- public function testDeleteShareWithMe() {
+ public function testDeleteShareWithMe(): void {
$node = $this->getMockBuilder(File::class)->getMock();
$share = $this->newShare();
@@ -288,7 +288,7 @@ class ShareAPIControllerTest extends TestCase {
/**
* You can always delete a share you own
*/
- public function testDeleteShareOwner() {
+ public function testDeleteShareOwner(): void {
$node = $this->getMockBuilder(File::class)->getMock();
$share = $this->newShare();
@@ -320,7 +320,7 @@ class ShareAPIControllerTest extends TestCase {
* You can always delete a share when you own
* the file path it belong to
*/
- public function testDeleteShareFileOwner() {
+ public function testDeleteShareFileOwner(): void {
$node = $this->getMockBuilder(File::class)->getMock();
$node->method('getId')->willReturn(1);
@@ -353,7 +353,7 @@ class ShareAPIControllerTest extends TestCase {
* You can remove (the mountpoint, not the share)
* a share if you're in the group the share is shared with
*/
- public function testDeleteSharedWithMyGroup() {
+ public function testDeleteSharedWithMyGroup(): void {
$node = $this->getMockBuilder(File::class)->getMock();
$node->method('getId')->willReturn(1);
@@ -413,7 +413,7 @@ class ShareAPIControllerTest extends TestCase {
* You cannot remove a share if you're not
* in the group the share is shared with
*/
- public function testDeleteSharedWithGroupIDontBelongTo() {
+ public function testDeleteSharedWithGroupIDontBelongTo(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
$this->expectExceptionMessage('Wrong share ID, share does not exist');
@@ -730,7 +730,7 @@ class ShareAPIControllerTest extends TestCase {
/**
* @dataProvider dataGetShare
*/
- public function testGetShare(\OCP\Share\IShare $share, array $result) {
+ public function testGetShare(\OCP\Share\IShare $share, array $result): void {
/** @var ShareAPIController|\PHPUnit\Framework\MockObject\MockObject $ocs */
$ocs = $this->getMockBuilder(ShareAPIController::class)
->setConstructorArgs([
@@ -819,7 +819,7 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testGetShareInvalidNode() {
+ public function testGetShareInvalidNode(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
$this->expectExceptionMessage('Wrong share ID, share does not exist');
@@ -1364,7 +1364,7 @@ class ShareAPIControllerTest extends TestCase {
/**
* @dataProvider dataGetShares
*/
- public function testGetShares(array $getSharesParameters, array $shares, array $extraShareTypes, array $expected) {
+ public function testGetShares(array $getSharesParameters, array $shares, array $extraShareTypes, array $expected): void {
/** @var \OCA\Files_Sharing\Controller\ShareAPIController $ocs */
$ocs = $this->getMockBuilder(ShareAPIController::class)
->setConstructorArgs([
@@ -1445,7 +1445,7 @@ class ShareAPIControllerTest extends TestCase {
$this->assertEquals($expected, $result->getData());
}
- public function testCanAccessShare() {
+ public function testCanAccessShare(): void {
$share = $this->getMockBuilder(IShare::class)->getMock();
$share->method('getShareOwner')->willReturn($this->currentUser);
$this->assertTrue($this->invokePrivate($this->ocs, 'canAccessShare', [$share]));
@@ -1556,7 +1556,7 @@ class ShareAPIControllerTest extends TestCase {
* @param bool helperAvailable
* @param bool canAccessShareByHelper
*/
- public function testCanAccessRoomShare(bool $expected, \OCP\Share\IShare $share, bool $helperAvailable, bool $canAccessShareByHelper) {
+ public function testCanAccessRoomShare(bool $expected, \OCP\Share\IShare $share, bool $helperAvailable, bool $canAccessShareByHelper): void {
$userFolder = $this->getMockBuilder(Folder::class)->getMock();
$this->rootFolder->method('getUserFolder')
->with($this->currentUser)
@@ -1591,7 +1591,7 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testCreateShareNoPath() {
+ public function testCreateShareNoPath(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
$this->expectExceptionMessage('Please specify a file or folder path');
@@ -1599,7 +1599,7 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testCreateShareInvalidPath() {
+ public function testCreateShareInvalidPath(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
$this->expectExceptionMessage('Wrong path, file/folder does not exist');
@@ -1618,7 +1618,7 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testCreateShareInvalidPermissions() {
+ public function testCreateShareInvalidPermissions(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
$this->expectExceptionMessage('Invalid permissions');
@@ -1647,7 +1647,7 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testCreateShareUserNoShareWith() {
+ public function testCreateShareUserNoShareWith(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
$this->expectExceptionMessage('Please specify a valid account to share with');
@@ -1675,7 +1675,7 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testCreateShareUserNoValidShareWith() {
+ public function testCreateShareUserNoValidShareWith(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
$this->expectExceptionMessage('Please specify a valid account to share with');
@@ -1704,7 +1704,7 @@ class ShareAPIControllerTest extends TestCase {
$this->ocs->createShare('valid-path', \OCP\Constants::PERMISSION_ALL, IShare::TYPE_USER, 'invalidUser');
}
- public function testCreateShareUser() {
+ public function testCreateShareUser(): void {
$share = $this->newShare();
$this->shareManager->method('newShare')->willReturn($share);
@@ -1773,7 +1773,7 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testCreateShareGroupNoValidShareWith() {
+ public function testCreateShareGroupNoValidShareWith(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
$this->expectExceptionMessage('Please specify a valid group');
@@ -1802,7 +1802,7 @@ class ShareAPIControllerTest extends TestCase {
$this->ocs->createShare('valid-path', \OCP\Constants::PERMISSION_ALL, IShare::TYPE_GROUP, 'invalidGroup');
}
- public function testCreateShareGroup() {
+ public function testCreateShareGroup(): void {
$share = $this->newShare();
$this->shareManager->method('newShare')->willReturn($share);
@@ -1880,7 +1880,7 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testCreateShareGroupNotAllowed() {
+ public function testCreateShareGroupNotAllowed(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
$this->expectExceptionMessage('Group sharing is disabled by the administrator');
@@ -1910,7 +1910,7 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testCreateShareLinkNoLinksAllowed() {
+ public function testCreateShareLinkNoLinksAllowed(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
$this->expectExceptionMessage('Public link sharing is disabled by the administrator');
@@ -1941,7 +1941,7 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testCreateShareLinkNoPublicUpload() {
+ public function testCreateShareLinkNoPublicUpload(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSForbiddenException::class);
$this->expectExceptionMessage('Public upload disabled by the administrator');
@@ -1966,7 +1966,7 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testCreateShareLinkPublicUploadFile() {
+ public function testCreateShareLinkPublicUploadFile(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
$this->expectExceptionMessage('Public upload is only possible for publicly shared folders');
@@ -1991,7 +1991,7 @@ class ShareAPIControllerTest extends TestCase {
$this->ocs->createShare('valid-path', \OCP\Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'true');
}
- public function testCreateShareLinkPublicUploadFolder() {
+ public function testCreateShareLinkPublicUploadFolder(): void {
$ocs = $this->mockFormatShare();
$path = $this->getMockBuilder(Folder::class)->getMock();
@@ -2030,7 +2030,7 @@ class ShareAPIControllerTest extends TestCase {
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testCreateShareLinkPassword() {
+ public function testCreateShareLinkPassword(): void {
$ocs = $this->mockFormatShare();
$path = $this->getMockBuilder(Folder::class)->getMock();
@@ -2069,7 +2069,7 @@ class ShareAPIControllerTest extends TestCase {
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testCreateShareLinkSendPasswordByTalk() {
+ public function testCreateShareLinkSendPasswordByTalk(): void {
$ocs = $this->mockFormatShare();
$path = $this->getMockBuilder(Folder::class)->getMock();
@@ -2112,7 +2112,7 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testCreateShareLinkSendPasswordByTalkWithTalkDisabled() {
+ public function testCreateShareLinkSendPasswordByTalkWithTalkDisabled(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSForbiddenException::class);
$this->expectExceptionMessage('Sharing valid-path sending the password by Nextcloud Talk failed because Nextcloud Talk is not enabled');
@@ -2144,7 +2144,7 @@ class ShareAPIControllerTest extends TestCase {
$ocs->createShare('valid-path', \OCP\Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'false', 'password', 'true', '');
}
- public function testCreateShareValidExpireDate() {
+ public function testCreateShareValidExpireDate(): void {
$ocs = $this->mockFormatShare();
$this->request
@@ -2197,7 +2197,7 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testCreateShareInvalidExpireDate() {
+ public function testCreateShareInvalidExpireDate(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
$this->expectExceptionMessage('Invalid date, date format must be YYYY-MM-DD');
@@ -2224,7 +2224,7 @@ class ShareAPIControllerTest extends TestCase {
$ocs->createShare('valid-path', \OCP\Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'false', '', null, 'a1b2d3');
}
- public function testCreateShareRemote() {
+ public function testCreateShareRemote(): void {
$share = $this->newShare();
$this->shareManager->method('newShare')->willReturn($share);
@@ -2294,7 +2294,7 @@ class ShareAPIControllerTest extends TestCase {
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testCreateShareRemoteGroup() {
+ public function testCreateShareRemoteGroup(): void {
$share = $this->newShare();
$this->shareManager->method('newShare')->willReturn($share);
@@ -2364,7 +2364,7 @@ class ShareAPIControllerTest extends TestCase {
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testCreateShareRoom() {
+ public function testCreateShareRoom(): void {
$ocs = $this->mockFormatShare();
$share = $this->newShare();
@@ -2439,7 +2439,7 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testCreateShareRoomHelperNotAvailable() {
+ public function testCreateShareRoomHelperNotAvailable(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSForbiddenException::class);
$this->expectExceptionMessage('Sharing valid-path failed because the back end does not support room shares');
@@ -2476,7 +2476,7 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testCreateShareRoomHelperThrowException() {
+ public function testCreateShareRoomHelperThrowException(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
$this->expectExceptionMessage('Exception thrown by the helper');
@@ -2537,7 +2537,7 @@ class ShareAPIControllerTest extends TestCase {
* Test for https://github.com/owncloud/core/issues/22587
* TODO: Remove once proper solution is in place
*/
- public function testCreateReshareOfFederatedMountNoDeletePermissions() {
+ public function testCreateReshareOfFederatedMountNoDeletePermissions(): void {
$share = \OC::$server->getShareManager()->newShare();
$this->shareManager->method('newShare')->willReturn($share);
@@ -2605,7 +2605,7 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testUpdateShareCantAccess() {
+ public function testUpdateShareCantAccess(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
$this->expectExceptionMessage('Wrong share ID, share does not exist');
@@ -2631,7 +2631,7 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testUpdateNoParametersLink() {
+ public function testUpdateNoParametersLink(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSBadRequestException::class);
$this->expectExceptionMessage('Wrong or no update parameter given');
@@ -2652,7 +2652,7 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testUpdateNoParametersOther() {
+ public function testUpdateNoParametersOther(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSBadRequestException::class);
$this->expectExceptionMessage('Wrong or no update parameter given');
@@ -2672,7 +2672,7 @@ class ShareAPIControllerTest extends TestCase {
$this->ocs->updateShare(42);
}
- public function testUpdateLinkShareClear() {
+ public function testUpdateLinkShareClear(): void {
$ocs = $this->mockFormatShare();
[$userFolder, $node] = $this->getNonSharedUserFolder();
@@ -2733,7 +2733,7 @@ class ShareAPIControllerTest extends TestCase {
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testUpdateLinkShareSet() {
+ public function testUpdateLinkShareSet(): void {
$ocs = $this->mockFormatShare();
[$userFolder, $folder] = $this->getNonSharedUserFolder();
@@ -2790,7 +2790,7 @@ class ShareAPIControllerTest extends TestCase {
/**
* @dataProvider publicUploadParamsProvider
*/
- public function testUpdateLinkShareEnablePublicUpload($permissions, $publicUpload, $expireDate, $password) {
+ public function testUpdateLinkShareEnablePublicUpload($permissions, $publicUpload, $expireDate, $password): void {
$ocs = $this->mockFormatShare();
[$userFolder, $folder] = $this->getNonSharedUserFolder();
@@ -2851,7 +2851,7 @@ class ShareAPIControllerTest extends TestCase {
/**
* @dataProvider publicLinkValidPermissionsProvider
*/
- public function testUpdateLinkShareSetCRUDPermissions($permissions) {
+ public function testUpdateLinkShareSetCRUDPermissions($permissions): void {
$ocs = $this->mockFormatShare();
[$userFolder, $folder] = $this->getNonSharedUserFolder();
@@ -2906,7 +2906,7 @@ class ShareAPIControllerTest extends TestCase {
/**
* @dataProvider publicLinkInvalidPermissionsProvider1
*/
- public function testUpdateLinkShareSetInvalidCRUDPermissions1($permissions) {
+ public function testUpdateLinkShareSetInvalidCRUDPermissions1($permissions): void {
$this->expectException(\OCP\AppFramework\OCS\OCSBadRequestException::class);
$this->expectExceptionMessage('Share must at least have READ or CREATE permissions');
@@ -2923,14 +2923,14 @@ class ShareAPIControllerTest extends TestCase {
/**
* @dataProvider publicLinkInvalidPermissionsProvider2
*/
- public function testUpdateLinkShareSetInvalidCRUDPermissions2($permissions) {
+ public function testUpdateLinkShareSetInvalidCRUDPermissions2($permissions): void {
$this->expectException(\OCP\AppFramework\OCS\OCSBadRequestException::class);
$this->expectExceptionMessage('Share must have READ permission if UPDATE or DELETE permission is set');
$this->testUpdateLinkShareSetCRUDPermissions($permissions);
}
- public function testUpdateLinkShareInvalidDate() {
+ public function testUpdateLinkShareInvalidDate(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSBadRequestException::class);
$this->expectExceptionMessage('Invalid date. Format must be YYYY-MM-DD');
@@ -2977,7 +2977,7 @@ class ShareAPIControllerTest extends TestCase {
/**
* @dataProvider publicUploadParamsProvider
*/
- public function testUpdateLinkSharePublicUploadNotAllowed($permissions, $publicUpload, $expireDate, $password) {
+ public function testUpdateLinkSharePublicUploadNotAllowed($permissions, $publicUpload, $expireDate, $password): void {
$this->expectException(\OCP\AppFramework\OCS\OCSForbiddenException::class);
$this->expectExceptionMessage('Public upload disabled by the administrator');
@@ -3005,7 +3005,7 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testUpdateLinkSharePublicUploadOnFile() {
+ public function testUpdateLinkSharePublicUploadOnFile(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSBadRequestException::class);
$this->expectExceptionMessage('Public upload is only possible for publicly shared folders');
@@ -3086,7 +3086,7 @@ class ShareAPIControllerTest extends TestCase {
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testUpdateLinkShareSendPasswordByTalkDoesNotChangeOther() {
+ public function testUpdateLinkShareSendPasswordByTalkDoesNotChangeOther(): void {
$ocs = $this->mockFormatShare();
$date = new \DateTime('2000-01-01');
@@ -3141,7 +3141,7 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testUpdateLinkShareSendPasswordByTalkWithTalkDisabledDoesNotChangeOther() {
+ public function testUpdateLinkShareSendPasswordByTalkWithTalkDisabledDoesNotChangeOther(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSForbiddenException::class);
$this->expectExceptionMessage('"Sending the password by Nextcloud Talk" for sharing a file or folder failed because Nextcloud Talk is not enabled.');
@@ -3184,7 +3184,7 @@ class ShareAPIControllerTest extends TestCase {
$ocs->updateShare(42, null, null, 'true', null, null, null, null, null);
}
- public function testUpdateLinkShareDoNotSendPasswordByTalkDoesNotChangeOther() {
+ public function testUpdateLinkShareDoNotSendPasswordByTalkDoesNotChangeOther(): void {
$ocs = $this->mockFormatShare();
$date = new \DateTime('2000-01-01');
@@ -3238,7 +3238,7 @@ class ShareAPIControllerTest extends TestCase {
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testUpdateLinkShareDoNotSendPasswordByTalkWithTalkDisabledDoesNotChangeOther() {
+ public function testUpdateLinkShareDoNotSendPasswordByTalkWithTalkDisabledDoesNotChangeOther(): void {
$ocs = $this->mockFormatShare();
$date = new \DateTime('2000-01-01');
@@ -3308,7 +3308,7 @@ class ShareAPIControllerTest extends TestCase {
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testUpdateLinkShareExpireDateDoesNotChangeOther() {
+ public function testUpdateLinkShareExpireDateDoesNotChangeOther(): void {
$ocs = $this->mockFormatShare();
[$userFolder, $node] = $this->getNonSharedUserFolder();
@@ -3370,7 +3370,7 @@ class ShareAPIControllerTest extends TestCase {
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testUpdateLinkSharePublicUploadDoesNotChangeOther() {
+ public function testUpdateLinkSharePublicUploadDoesNotChangeOther(): void {
$ocs = $this->mockFormatShare();
$date = new \DateTime('2000-01-01');
@@ -3431,7 +3431,7 @@ class ShareAPIControllerTest extends TestCase {
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testUpdateLinkSharePermissions() {
+ public function testUpdateLinkSharePermissions(): void {
$ocs = $this->mockFormatShare();
$date = new \DateTime('2000-01-01');
@@ -3491,7 +3491,7 @@ class ShareAPIControllerTest extends TestCase {
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testUpdateLinkSharePermissionsShare() {
+ public function testUpdateLinkSharePermissionsShare(): void {
$ocs = $this->mockFormatShare();
$date = new \DateTime('2000-01-01');
@@ -3551,7 +3551,7 @@ class ShareAPIControllerTest extends TestCase {
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testUpdateOtherPermissions() {
+ public function testUpdateOtherPermissions(): void {
$ocs = $this->mockFormatShare();
[$userFolder, $file] = $this->getNonSharedUserFolder();
@@ -3597,7 +3597,7 @@ class ShareAPIControllerTest extends TestCase {
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testUpdateShareCannotIncreasePermissions() {
+ public function testUpdateShareCannotIncreasePermissions(): void {
$ocs = $this->mockFormatShare();
[$userFolder, $folder] = $this->getNonSharedUserFolder();
@@ -3669,7 +3669,7 @@ class ShareAPIControllerTest extends TestCase {
}
}
- public function testUpdateShareCanIncreasePermissionsIfOwner() {
+ public function testUpdateShareCanIncreasePermissionsIfOwner(): void {
$ocs = $this->mockFormatShare();
[$userFolder, $folder] = $this->getNonSharedUserFolder();
@@ -4665,7 +4665,7 @@ class ShareAPIControllerTest extends TestCase {
* @param array $users
* @param $exception
*/
- public function testFormatShare(array $expects, \OCP\Share\IShare $share, array $users, $exception) {
+ public function testFormatShare(array $expects, \OCP\Share\IShare $share, array $users, $exception): void {
$this->userManager->method('get')->willReturnMap($users);
$recipientGroup = $this->createMock(IGroup::class);
@@ -4882,7 +4882,7 @@ class ShareAPIControllerTest extends TestCase {
* @param bool $helperAvailable
* @param array $formatShareByHelper
*/
- public function testFormatRoomShare(array $expects, \OCP\Share\IShare $share, bool $helperAvailable, array $formatShareByHelper) {
+ public function testFormatRoomShare(array $expects, \OCP\Share\IShare $share, bool $helperAvailable, array $formatShareByHelper): void {
$this->rootFolder->method('getUserFolder')
->with($this->currentUser)
->willReturnSelf();
diff --git a/apps/files_sharing/tests/Controller/ShareControllerTest.php b/apps/files_sharing/tests/Controller/ShareControllerTest.php
index e20646966aa..6d974deb0ff 100644
--- a/apps/files_sharing/tests/Controller/ShareControllerTest.php
+++ b/apps/files_sharing/tests/Controller/ShareControllerTest.php
@@ -165,7 +165,7 @@ class ShareControllerTest extends \Test\TestCase {
parent::tearDown();
}
- public function testShowShareInvalidToken() {
+ public function testShowShareInvalidToken(): void {
$this->shareController->setToken('invalidtoken');
$this->shareManager
@@ -180,7 +180,7 @@ class ShareControllerTest extends \Test\TestCase {
$this->shareController->showShare();
}
- public function testShowShareNotAuthenticated() {
+ public function testShowShareNotAuthenticated(): void {
$this->shareController->setToken('validtoken');
$share = \OC::$server->getShareManager()->newShare();
@@ -199,7 +199,7 @@ class ShareControllerTest extends \Test\TestCase {
}
- public function testShowShare() {
+ public function testShowShare(): void {
$note = 'personal note';
$filename = 'file1.txt';
@@ -347,7 +347,7 @@ class ShareControllerTest extends \Test\TestCase {
$this->assertEquals($expectedResponse, $response);
}
- public function testShowFileDropShare() {
+ public function testShowFileDropShare(): void {
$filename = 'folder1';
$this->shareController->setToken('token');
@@ -484,7 +484,7 @@ class ShareControllerTest extends \Test\TestCase {
$this->assertEquals($expectedResponse, $response);
}
- public function testShowShareWithPrivateName() {
+ public function testShowShareWithPrivateName(): void {
$note = 'personal note';
$filename = 'file1.txt';
@@ -614,7 +614,7 @@ class ShareControllerTest extends \Test\TestCase {
}
- public function testShowShareInvalid() {
+ public function testShowShareInvalid(): void {
$this->expectException(\OCP\Files\NotFoundException::class);
$filename = 'file1.txt';
@@ -664,7 +664,7 @@ class ShareControllerTest extends \Test\TestCase {
$this->shareController->showShare();
}
- public function testDownloadShareWithCreateOnlyShare() {
+ public function testDownloadShareWithCreateOnlyShare(): void {
$share = $this->getMockBuilder(IShare::class)->getMock();
$share->method('getPassword')->willReturn('password');
$share
@@ -684,7 +684,7 @@ class ShareControllerTest extends \Test\TestCase {
$this->assertEquals($expectedResponse, $response);
}
- public function testDisabledOwner() {
+ public function testDisabledOwner(): void {
$this->shareController->setToken('token');
$owner = $this->getMockBuilder(IUser::class)->getMock();
@@ -725,7 +725,7 @@ class ShareControllerTest extends \Test\TestCase {
$this->shareController->showShare();
}
- public function testDisabledInitiator() {
+ public function testDisabledInitiator(): void {
$this->shareController->setToken('token');
$owner = $this->getMockBuilder(IUser::class)->getMock();
diff --git a/apps/files_sharing/tests/Controller/ShareInfoControllerTest.php b/apps/files_sharing/tests/Controller/ShareInfoControllerTest.php
index 59d7afc28d6..f2df74fd01b 100644
--- a/apps/files_sharing/tests/Controller/ShareInfoControllerTest.php
+++ b/apps/files_sharing/tests/Controller/ShareInfoControllerTest.php
@@ -41,7 +41,7 @@ class ShareInfoControllerTest extends TestCase {
->getMock();
}
- public function testNoShare() {
+ public function testNoShare(): void {
$this->shareManager->method('getShareByToken')
->with('token')
->willThrowException(new ShareNotFound());
@@ -51,7 +51,7 @@ class ShareInfoControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->info('token'));
}
- public function testWrongPassword() {
+ public function testWrongPassword(): void {
$share = $this->createMock(IShare::class);
$share->method('getPassword')
->willReturn('sharePass');
@@ -68,7 +68,7 @@ class ShareInfoControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->info('token', 'pass'));
}
- public function testNoReadPermissions() {
+ public function testNoReadPermissions(): void {
$share = $this->createMock(IShare::class);
$share->method('getPassword')
->willReturn('sharePass');
@@ -107,7 +107,7 @@ class ShareInfoControllerTest extends TestCase {
return $file;
}
- public function testInfoFile() {
+ public function testInfoFile(): void {
$file = $this->prepareFile();
$share = $this->createMock(IShare::class);
@@ -139,7 +139,7 @@ class ShareInfoControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->info('token', 'pass'));
}
- public function testInfoFileRO() {
+ public function testInfoFileRO(): void {
$file = $this->prepareFile();
$share = $this->createMock(IShare::class);
@@ -221,7 +221,7 @@ class ShareInfoControllerTest extends TestCase {
return $root;
}
- public function testInfoFolder() {
+ public function testInfoFolder(): void {
$file = $this->prepareFolder();
$share = $this->createMock(IShare::class);
diff --git a/apps/files_sharing/tests/Controller/ShareesAPIControllerTest.php b/apps/files_sharing/tests/Controller/ShareesAPIControllerTest.php
index 250801a2599..525a243e875 100644
--- a/apps/files_sharing/tests/Controller/ShareesAPIControllerTest.php
+++ b/apps/files_sharing/tests/Controller/ShareesAPIControllerTest.php
@@ -223,7 +223,7 @@ class ShareesAPIControllerTest extends TestCase {
bool $shareWithGroupOnly,
bool $shareeEnumeration,
bool $allowGroupSharing,
- ) {
+ ): void {
$search = $getData['search'] ?? '';
$itemType = $getData['itemType'] ?? 'irrelevant';
$page = $getData['page'] ?? 1;
@@ -333,7 +333,7 @@ class ShareesAPIControllerTest extends TestCase {
* @param array $getData
* @param string $message
*/
- public function testSearchInvalid($getData, $message) {
+ public function testSearchInvalid($getData, $message): void {
$page = $getData['page'] ?? 1;
$perPage = $getData['perPage'] ?? 200;
@@ -391,11 +391,11 @@ class ShareesAPIControllerTest extends TestCase {
* @param string $itemType
* @param bool $expected
*/
- public function testIsRemoteSharingAllowed($itemType, $expected) {
+ public function testIsRemoteSharingAllowed($itemType, $expected): void {
$this->assertSame($expected, $this->invokePrivate($this->sharees, 'isRemoteSharingAllowed', [$itemType]));
}
- public function testSearchSharingDisabled() {
+ public function testSearchSharingDisabled(): void {
$this->shareManager->expects($this->once())
->method('sharingDisabledForUser')
->with($this->uid)
@@ -412,7 +412,7 @@ class ShareesAPIControllerTest extends TestCase {
$this->assertInstanceOf(DataResponse::class, $this->sharees->search('', null, 1, 10, [], false));
}
- public function testSearchNoItemType() {
+ public function testSearchNoItemType(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSBadRequestException::class);
$this->expectExceptionMessage('Missing itemType');
@@ -434,7 +434,7 @@ class ShareesAPIControllerTest extends TestCase {
* @param array $params
* @param array $expected
*/
- public function testGetPaginationLink($page, $scriptName, $params, $expected) {
+ public function testGetPaginationLink($page, $scriptName, $params, $expected): void {
$this->request->expects($this->once())
->method('getScriptName')
->willReturn($scriptName);
@@ -455,7 +455,7 @@ class ShareesAPIControllerTest extends TestCase {
* @param string $scriptName
* @param bool $expected
*/
- public function testIsV2($scriptName, $expected) {
+ public function testIsV2($scriptName, $expected): void {
$this->request->expects($this->once())
->method('getScriptName')
->willReturn($scriptName);
diff --git a/apps/files_sharing/tests/DeleteOrphanedSharesJobTest.php b/apps/files_sharing/tests/DeleteOrphanedSharesJobTest.php
index 20365ebb842..e0d2d67d45f 100644
--- a/apps/files_sharing/tests/DeleteOrphanedSharesJobTest.php
+++ b/apps/files_sharing/tests/DeleteOrphanedSharesJobTest.php
@@ -107,7 +107,7 @@ class DeleteOrphanedSharesJobTest extends \Test\TestCase {
/**
* Test clearing orphaned shares
*/
- public function testClearShares() {
+ public function testClearShares(): void {
$this->loginAsUser($this->user1);
$user1Folder = \OC::$server->getUserFolder($this->user1);
diff --git a/apps/files_sharing/tests/EtagPropagationTest.php b/apps/files_sharing/tests/EtagPropagationTest.php
index a1e453dc9be..031f0f02e87 100644
--- a/apps/files_sharing/tests/EtagPropagationTest.php
+++ b/apps/files_sharing/tests/EtagPropagationTest.php
@@ -171,7 +171,7 @@ class EtagPropagationTest extends PropagationTestCase {
}
}
- public function testOwnerWritesToShare() {
+ public function testOwnerWritesToShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER1);
Filesystem::file_put_contents('/sub1/sub2/folder/asd.txt', 'bar');
$this->assertEtagsNotChanged([self::TEST_FILES_SHARING_API_USER4]);
@@ -181,7 +181,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testOwnerWritesToSingleFileShare() {
+ public function testOwnerWritesToSingleFileShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER1);
Filesystem::file_put_contents('/foo.txt', 'longer_bar');
$t = (int)Filesystem::filemtime('/foo.txt') - 1;
@@ -192,7 +192,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testOwnerWritesToShareWithReshare() {
+ public function testOwnerWritesToShareWithReshare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER1);
Filesystem::file_put_contents('/sub1/sub2/folder/inside/bar.txt', 'bar');
$this->assertEtagsForFoldersChanged([self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2,
@@ -201,7 +201,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testOwnerRenameInShare() {
+ public function testOwnerRenameInShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER1);
$this->assertEtagsNotChanged([self::TEST_FILES_SHARING_API_USER4]);
Filesystem::rename('/sub1/sub2/folder/file.txt', '/sub1/sub2/folder/renamed.txt');
@@ -211,7 +211,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testOwnerRenameInReShare() {
+ public function testOwnerRenameInReShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER1);
Filesystem::rename('/sub1/sub2/folder/inside/file.txt', '/sub1/sub2/folder/inside/renamed.txt');
$this->assertEtagsForFoldersChanged([self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2,
@@ -220,7 +220,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testOwnerRenameIntoReShare() {
+ public function testOwnerRenameIntoReShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER1);
Filesystem::rename('/sub1/sub2/folder/file.txt', '/sub1/sub2/folder/inside/renamed.txt');
$this->assertEtagsForFoldersChanged([self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2,
@@ -229,7 +229,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testOwnerRenameOutOfReShare() {
+ public function testOwnerRenameOutOfReShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER1);
Filesystem::rename('/sub1/sub2/folder/inside/file.txt', '/sub1/sub2/folder/renamed.txt');
$this->assertEtagsForFoldersChanged([self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2,
@@ -238,7 +238,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testOwnerDeleteInShare() {
+ public function testOwnerDeleteInShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER1);
Filesystem::unlink('/sub1/sub2/folder/file.txt');
$this->assertEtagsNotChanged([self::TEST_FILES_SHARING_API_USER4]);
@@ -248,7 +248,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testOwnerDeleteInReShare() {
+ public function testOwnerDeleteInReShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER1);
Filesystem::unlink('/sub1/sub2/folder/inside/file.txt');
$this->assertEtagsForFoldersChanged([self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2,
@@ -257,7 +257,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testOwnerUnshares() {
+ public function testOwnerUnshares(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER1);
$folderInfo = $this->rootView->getFileInfo('/' . self::TEST_FILES_SHARING_API_USER1 . '/files/sub1/sub2/folder');
$this->assertInstanceOf(\OC\Files\FileInfo::class, $folderInfo);
@@ -280,7 +280,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testOwnerUnsharesFlatReshares() {
+ public function testOwnerUnsharesFlatReshares(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER1);
$folderInfo = $this->rootView->getFileInfo('/' . self::TEST_FILES_SHARING_API_USER1 . '/files/sub1/sub2/folder/inside');
$this->assertInstanceOf(\OC\Files\FileInfo::class, $folderInfo);
@@ -301,7 +301,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testRecipientUnsharesFromSelf() {
+ public function testRecipientUnsharesFromSelf(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER2);
$ls = $this->rootView->getDirectoryContent('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/sub1/sub2/');
$this->assertTrue(
@@ -315,7 +315,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testRecipientWritesToShare() {
+ public function testRecipientWritesToShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER2);
Filesystem::file_put_contents('/sub1/sub2/folder/asd.txt', 'bar');
$this->assertEtagsNotChanged([self::TEST_FILES_SHARING_API_USER4]);
@@ -328,7 +328,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testRecipientWritesToReshare() {
+ public function testRecipientWritesToReshare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER2);
Filesystem::file_put_contents('/sub1/sub2/folder/inside/asd.txt', 'bar');
$this->assertEtagsForFoldersChanged([self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2,
@@ -337,7 +337,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testRecipientWritesToOtherRecipientsReshare() {
+ public function testRecipientWritesToOtherRecipientsReshare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER3);
Filesystem::file_put_contents('/sub1/sub2/folder/inside/asd.txt', 'bar');
$this->assertEtagsForFoldersChanged([self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2,
@@ -346,7 +346,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testRecipientRenameInShare() {
+ public function testRecipientRenameInShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER2);
Filesystem::rename('/sub1/sub2/folder/file.txt', '/sub1/sub2/folder/renamed.txt');
$this->assertEtagsNotChanged([self::TEST_FILES_SHARING_API_USER4]);
@@ -356,7 +356,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testRecipientRenameInReShare() {
+ public function testRecipientRenameInReShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER2);
Filesystem::rename('/sub1/sub2/folder/inside/file.txt', '/sub1/sub2/folder/inside/renamed.txt');
$this->assertEtagsForFoldersChanged([self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2,
@@ -365,7 +365,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testRecipientRenameResharedFolder() {
+ public function testRecipientRenameResharedFolder(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER2);
Filesystem::rename('/directReshare', '/sub1/directReshare');
$this->assertEtagsNotChanged([self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER3, self::TEST_FILES_SHARING_API_USER4]);
@@ -376,7 +376,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testRecipientDeleteInShare() {
+ public function testRecipientDeleteInShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER2);
Filesystem::unlink('/sub1/sub2/folder/file.txt');
$this->assertEtagsNotChanged([self::TEST_FILES_SHARING_API_USER4]);
@@ -386,7 +386,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testRecipientDeleteInReShare() {
+ public function testRecipientDeleteInReShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER2);
Filesystem::unlink('/sub1/sub2/folder/inside/file.txt');
$this->assertEtagsForFoldersChanged([self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2,
@@ -395,7 +395,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testReshareRecipientWritesToReshare() {
+ public function testReshareRecipientWritesToReshare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER4);
Filesystem::file_put_contents('/sub1/sub2/inside/asd.txt', 'bar');
$this->assertEtagsForFoldersChanged([self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2,
@@ -404,7 +404,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testReshareRecipientRenameInReShare() {
+ public function testReshareRecipientRenameInReShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER4);
Filesystem::rename('/sub1/sub2/inside/file.txt', '/sub1/sub2/inside/renamed.txt');
$this->assertEtagsForFoldersChanged([self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2,
@@ -413,7 +413,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testReshareRecipientDeleteInReShare() {
+ public function testReshareRecipientDeleteInReShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER4);
Filesystem::unlink('/sub1/sub2/inside/file.txt');
$this->assertEtagsForFoldersChanged([self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2,
@@ -422,7 +422,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testRecipientUploadInDirectReshare() {
+ public function testRecipientUploadInDirectReshare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER2);
Filesystem::file_put_contents('/directReshare/test.txt', 'sad');
$this->assertEtagsNotChanged([self::TEST_FILES_SHARING_API_USER3]);
@@ -431,7 +431,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testEtagChangeOnPermissionsChange() {
+ public function testEtagChangeOnPermissionsChange(): void {
$userFolder = $this->rootFolder->getUserFolder(self::TEST_FILES_SHARING_API_USER1);
$node = $userFolder->get('/sub1/sub2/folder');
diff --git a/apps/files_sharing/tests/ExpireSharesJobTest.php b/apps/files_sharing/tests/ExpireSharesJobTest.php
index e6383d12ded..cf7be7b20a0 100644
--- a/apps/files_sharing/tests/ExpireSharesJobTest.php
+++ b/apps/files_sharing/tests/ExpireSharesJobTest.php
@@ -107,7 +107,7 @@ class ExpireSharesJobTest extends \Test\TestCase {
* @param bool $addInterval If true add to the current time if false subtract
* @param bool $shouldExpire Should this share be expired
*/
- public function testExpireLinkShare($addExpiration, $interval, $addInterval, $shouldExpire) {
+ public function testExpireLinkShare($addExpiration, $interval, $addInterval, $shouldExpire): void {
$this->loginAsUser($this->user1);
$user1Folder = \OC::$server->getUserFolder($this->user1);
@@ -164,7 +164,7 @@ class ExpireSharesJobTest extends \Test\TestCase {
}
}
- public function testDoNotExpireOtherShares() {
+ public function testDoNotExpireOtherShares(): void {
$this->loginAsUser($this->user1);
$user1Folder = \OC::$server->getUserFolder($this->user1);
diff --git a/apps/files_sharing/tests/External/CacheTest.php b/apps/files_sharing/tests/External/CacheTest.php
index 09ce05aec1d..8ba2427868e 100644
--- a/apps/files_sharing/tests/External/CacheTest.php
+++ b/apps/files_sharing/tests/External/CacheTest.php
@@ -91,7 +91,7 @@ class CacheTest extends TestCase {
parent::tearDown();
}
- public function testGetInjectsOwnerDisplayName() {
+ public function testGetInjectsOwnerDisplayName(): void {
$info = $this->cache->get('test.txt');
$this->assertEquals(
$this->remoteUser . '@example.com/owncloud',
@@ -99,12 +99,12 @@ class CacheTest extends TestCase {
);
}
- public function testGetReturnsFalseIfNotFound() {
+ public function testGetReturnsFalseIfNotFound(): void {
$info = $this->cache->get('unexisting-entry.txt');
$this->assertFalse($info);
}
- public function testGetFolderPopulatesOwner() {
+ public function testGetFolderPopulatesOwner(): void {
$dirId = $this->cache->put(
'subdir',
[
diff --git a/apps/files_sharing/tests/External/ManagerTest.php b/apps/files_sharing/tests/External/ManagerTest.php
index 7add0be88e0..9993f4c6d8f 100644
--- a/apps/files_sharing/tests/External/ManagerTest.php
+++ b/apps/files_sharing/tests/External/ManagerTest.php
@@ -181,7 +181,7 @@ class ManagerTest extends TestCase {
$this->mountManager->addMount(new MountPoint(Temporary::class, '', []));
}
- public function testAddUserShare() {
+ public function testAddUserShare(): void {
$this->doTestAddShare([
'remote' => 'http://localhost',
'token' => 'token1',
@@ -195,7 +195,7 @@ class ManagerTest extends TestCase {
], false);
}
- public function testAddGroupShare() {
+ public function testAddGroupShare(): void {
$this->doTestAddShare([
'remote' => 'http://localhost',
'token' => 'token1',
@@ -474,7 +474,7 @@ class ManagerTest extends TestCase {
return [$shareData, $groupShare];
}
- public function testAcceptOriginalGroupShare() {
+ public function testAcceptOriginalGroupShare(): void {
[$shareData, $groupShare] = $this->createTestGroupShare();
$this->assertTrue($this->manager->acceptShare($groupShare['id']));
$this->verifyAcceptedGroupShare($shareData);
@@ -484,7 +484,7 @@ class ManagerTest extends TestCase {
$this->verifyAcceptedGroupShare($shareData);
}
- public function testAcceptGroupShareAgainThroughGroupShare() {
+ public function testAcceptGroupShareAgainThroughGroupShare(): void {
[$shareData, $groupShare] = $this->createTestGroupShare();
$this->assertTrue($this->manager->acceptShare($groupShare['id']));
$this->verifyAcceptedGroupShare($shareData);
@@ -506,7 +506,7 @@ class ManagerTest extends TestCase {
$this->verifyAcceptedGroupShare($shareData, '/SharedFolder');
}
- public function testAcceptGroupShareAgainThroughSubShare() {
+ public function testAcceptGroupShareAgainThroughSubShare(): void {
[$shareData, $groupShare] = $this->createTestGroupShare();
$this->assertTrue($this->manager->acceptShare($groupShare['id']));
$this->verifyAcceptedGroupShare($shareData);
@@ -528,7 +528,7 @@ class ManagerTest extends TestCase {
$this->verifyAcceptedGroupShare($shareData);
}
- public function testDeclineOriginalGroupShare() {
+ public function testDeclineOriginalGroupShare(): void {
[$shareData, $groupShare] = $this->createTestGroupShare();
$this->assertTrue($this->manager->declineShare($groupShare['id']));
$this->verifyDeclinedGroupShare($shareData);
@@ -538,7 +538,7 @@ class ManagerTest extends TestCase {
$this->verifyDeclinedGroupShare($shareData);
}
- public function testDeclineGroupShareAgainThroughGroupShare() {
+ public function testDeclineGroupShareAgainThroughGroupShare(): void {
[$shareData, $groupShare] = $this->createTestGroupShare();
$this->assertTrue($this->manager->acceptShare($groupShare['id']));
$this->verifyAcceptedGroupShare($shareData);
@@ -552,7 +552,7 @@ class ManagerTest extends TestCase {
$this->verifyDeclinedGroupShare($shareData, '/SharedFolder');
}
- public function testDeclineGroupShareAgainThroughSubshare() {
+ public function testDeclineGroupShareAgainThroughSubshare(): void {
[$shareData, $groupShare] = $this->createTestGroupShare();
$this->assertTrue($this->manager->acceptShare($groupShare['id']));
$this->verifyAcceptedGroupShare($shareData);
@@ -570,7 +570,7 @@ class ManagerTest extends TestCase {
$this->verifyDeclinedGroupShare($shareData, '/SharedFolder');
}
- public function testDeclineGroupShareAgainThroughMountPoint() {
+ public function testDeclineGroupShareAgainThroughMountPoint(): void {
[$shareData, $groupShare] = $this->createTestGroupShare();
$this->assertTrue($this->manager->acceptShare($groupShare['id']));
$this->verifyAcceptedGroupShare($shareData);
@@ -583,7 +583,7 @@ class ManagerTest extends TestCase {
$this->assertFalse($this->manager->removeShare($this->uid . '/files/' . $shareData['name']));
}
- public function testDeclineThenAcceptGroupShareAgainThroughGroupShare() {
+ public function testDeclineThenAcceptGroupShareAgainThroughGroupShare(): void {
[$shareData, $groupShare] = $this->createTestGroupShare();
// decline, this creates a declined sub-share
$this->assertTrue($this->manager->declineShare($groupShare['id']));
@@ -601,7 +601,7 @@ class ManagerTest extends TestCase {
$this->verifyAcceptedGroupShare($shareData, '/SharedFolder');
}
- public function testDeclineThenAcceptGroupShareAgainThroughSubShare() {
+ public function testDeclineThenAcceptGroupShareAgainThroughSubShare(): void {
[$shareData, $groupShare] = $this->createTestGroupShare();
// decline, this creates a declined sub-share
$this->assertTrue($this->manager->declineShare($groupShare['id']));
@@ -619,7 +619,7 @@ class ManagerTest extends TestCase {
$this->verifyAcceptedGroupShare($shareData);
}
- public function testDeleteUserShares() {
+ public function testDeleteUserShares(): void {
// user 1 shares
$shareData = $this->createTestUserShare($this->uid);
@@ -666,7 +666,7 @@ class ManagerTest extends TestCase {
$this->assertEquals($user2Shares[1]['user'], 'user2');
}
- public function testDeleteGroupShares() {
+ public function testDeleteGroupShares(): void {
$shareData = $this->createTestUserShare($this->uid);
[$shareData, $groupShare] = $this->createTestGroupShare();
diff --git a/apps/files_sharing/tests/External/ScannerTest.php b/apps/files_sharing/tests/External/ScannerTest.php
index 0e3c8de8e2e..1a0077cf04b 100644
--- a/apps/files_sharing/tests/External/ScannerTest.php
+++ b/apps/files_sharing/tests/External/ScannerTest.php
@@ -35,7 +35,7 @@ class ScannerTest extends TestCase {
$this->scanner = new Scanner($this->storage);
}
- public function testScan() {
+ public function testScan(): void {
$this->storage->expects($this->any())
->method('getShareInfo')
->willReturn(['status' => 'success', 'data' => []]);
@@ -47,7 +47,7 @@ class ScannerTest extends TestCase {
$this->addToAssertionCount(1);
}
- public function testScanFile() {
+ public function testScanFile(): void {
// FIXME add real tests, we are currently only checking for
// Declaration of OCA\Files_Sharing\External\Scanner::*() should be
// compatible with OC\Files\Cache\Scanner::*()
diff --git a/apps/files_sharing/tests/ExternalStorageTest.php b/apps/files_sharing/tests/ExternalStorageTest.php
index 4d807526f0d..56a1f320030 100644
--- a/apps/files_sharing/tests/ExternalStorageTest.php
+++ b/apps/files_sharing/tests/ExternalStorageTest.php
@@ -89,12 +89,12 @@ class ExternalStorageTest extends \Test\TestCase {
/**
* @dataProvider optionsProvider
*/
- public function testStorageMountOptions($inputUri, $baseUri) {
+ public function testStorageMountOptions($inputUri, $baseUri): void {
$storage = $this->getTestStorage($inputUri);
$this->assertEquals($baseUri, $storage->getBaseUri());
}
- public function testIfTestReturnsTheValue() {
+ public function testIfTestReturnsTheValue(): void {
$result = $this->getTestStorage('https://remoteserver')->test();
$this->assertSame(true, $result);
}
diff --git a/apps/files_sharing/tests/GroupEtagPropagationTest.php b/apps/files_sharing/tests/GroupEtagPropagationTest.php
index 280b091b5f7..9b2b63b0181 100644
--- a/apps/files_sharing/tests/GroupEtagPropagationTest.php
+++ b/apps/files_sharing/tests/GroupEtagPropagationTest.php
@@ -89,7 +89,7 @@ class GroupEtagPropagationTest extends PropagationTestCase {
}
}
- public function testGroupReShareRecipientWrites() {
+ public function testGroupReShareRecipientWrites(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER3);
Filesystem::file_put_contents('/test/sub/file.txt', 'asd');
@@ -99,7 +99,7 @@ class GroupEtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testGroupReShareSubFolderRecipientWrites() {
+ public function testGroupReShareSubFolderRecipientWrites(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER4);
Filesystem::file_put_contents('/sub/file.txt', 'asd');
@@ -109,7 +109,7 @@ class GroupEtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testRecipientUnsharesFromSelf() {
+ public function testRecipientUnsharesFromSelf(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER2);
$this->assertTrue(
$this->rootView->unlink('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/test')
@@ -119,7 +119,7 @@ class GroupEtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testRecipientUnsharesFromSelfUniqueGroupShare() {
+ public function testRecipientUnsharesFromSelfUniqueGroupShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER2);
// rename to create an extra entry in the share table
$this->rootView->rename('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/test', '/' . self::TEST_FILES_SHARING_API_USER2 . '/files/test_renamed');
diff --git a/apps/files_sharing/tests/HelperTest.php b/apps/files_sharing/tests/HelperTest.php
index cc5c0d27e60..d72afc4d4aa 100644
--- a/apps/files_sharing/tests/HelperTest.php
+++ b/apps/files_sharing/tests/HelperTest.php
@@ -16,7 +16,7 @@ class HelperTest extends TestCase {
/**
* test set and get share folder
*/
- public function testSetGetShareFolder() {
+ public function testSetGetShareFolder(): void {
$this->assertSame('/', \OCA\Files_Sharing\Helper::getShareFolder());
\OCA\Files_Sharing\Helper::setShareFolder('/Shared/Folder');
diff --git a/apps/files_sharing/tests/LockingTest.php b/apps/files_sharing/tests/LockingTest.php
index 0ca204ef215..c69cf99f185 100644
--- a/apps/files_sharing/tests/LockingTest.php
+++ b/apps/files_sharing/tests/LockingTest.php
@@ -61,7 +61,7 @@ class LockingTest extends TestCase {
}
- public function testLockAsRecipient() {
+ public function testLockAsRecipient(): void {
$this->expectException(\OCP\Lock\LockedException::class);
$this->loginAsUser($this->ownerUid);
@@ -73,7 +73,7 @@ class LockingTest extends TestCase {
Filesystem::rename('/foo', '/asd');
}
- public function testUnLockAsRecipient() {
+ public function testUnLockAsRecipient(): void {
$this->loginAsUser($this->ownerUid);
Filesystem::initMountPoints($this->recipientUid);
@@ -84,7 +84,7 @@ class LockingTest extends TestCase {
$this->assertTrue(Filesystem::rename('/foo', '/asd'));
}
- public function testChangeLock() {
+ public function testChangeLock(): void {
Filesystem::initMountPoints($this->recipientUid);
$recipientView = new View('/' . $this->recipientUid . '/files');
$recipientView->lockFile('bar.txt', ILockingProvider::LOCK_SHARED);
diff --git a/apps/files_sharing/tests/Middleware/OCSShareAPIMiddlewareTest.php b/apps/files_sharing/tests/Middleware/OCSShareAPIMiddlewareTest.php
index f6be80f1167..127d982fb2f 100644
--- a/apps/files_sharing/tests/Middleware/OCSShareAPIMiddlewareTest.php
+++ b/apps/files_sharing/tests/Middleware/OCSShareAPIMiddlewareTest.php
@@ -78,7 +78,7 @@ class OCSShareAPIMiddlewareTest extends \Test\TestCase {
* @param bool $enabled
* @param bool $exception
*/
- public function testBeforeController(Controller $controller, $enabled, $exception) {
+ public function testBeforeController(Controller $controller, $enabled, $exception): void {
$this->shareManager->method('shareApiEnabled')->willReturn($enabled);
try {
@@ -109,7 +109,7 @@ class OCSShareAPIMiddlewareTest extends \Test\TestCase {
* @param Controller $controller
* @param bool $called
*/
- public function testAfterController(Controller $controller) {
+ public function testAfterController(Controller $controller): void {
if ($controller instanceof ShareAPIController) {
$controller->expects($this->once())->method('cleanup');
}
diff --git a/apps/files_sharing/tests/Middleware/ShareInfoMiddlewareTest.php b/apps/files_sharing/tests/Middleware/ShareInfoMiddlewareTest.php
index 5ba21255a8d..88fa56a9bcb 100644
--- a/apps/files_sharing/tests/Middleware/ShareInfoMiddlewareTest.php
+++ b/apps/files_sharing/tests/Middleware/ShareInfoMiddlewareTest.php
@@ -29,14 +29,14 @@ class ShareInfoMiddlewareTest extends TestCase {
$this->middleware = new ShareInfoMiddleware($this->shareManager);
}
- public function testBeforeControllerNoShareInfo() {
+ public function testBeforeControllerNoShareInfo(): void {
$this->shareManager->expects($this->never())
->method($this->anything());
$this->middleware->beforeController($this->createMock(ShareInfoMiddlewareTestController::class), 'foo');
}
- public function testBeforeControllerShareInfoNoS2s() {
+ public function testBeforeControllerShareInfoNoS2s(): void {
$this->shareManager->expects($this->once())
->method('outgoingServer2ServerSharesAllowed')
->willReturn(false);
@@ -45,7 +45,7 @@ class ShareInfoMiddlewareTest extends TestCase {
$this->middleware->beforeController($this->createMock(ShareInfoController::class), 'foo');
}
- public function testBeforeControllerShareInfo() {
+ public function testBeforeControllerShareInfo(): void {
$this->shareManager->expects($this->once())
->method('outgoingServer2ServerSharesAllowed')
->willReturn(true);
@@ -53,7 +53,7 @@ class ShareInfoMiddlewareTest extends TestCase {
$this->middleware->beforeController($this->createMock(ShareInfoController::class), 'foo');
}
- public function testAfterExceptionNoShareInfo() {
+ public function testAfterExceptionNoShareInfo(): void {
$exeption = new \Exception();
try {
@@ -65,7 +65,7 @@ class ShareInfoMiddlewareTest extends TestCase {
}
- public function testAfterExceptionNoS2S() {
+ public function testAfterExceptionNoS2S(): void {
$exeption = new \Exception();
try {
@@ -76,7 +76,7 @@ class ShareInfoMiddlewareTest extends TestCase {
}
}
- public function testAfterExceptionS2S() {
+ public function testAfterExceptionS2S(): void {
$expected = new JSONResponse([], Http::STATUS_NOT_FOUND);
$this->assertEquals(
@@ -85,7 +85,7 @@ class ShareInfoMiddlewareTest extends TestCase {
);
}
- public function testAfterControllerNoShareInfo() {
+ public function testAfterControllerNoShareInfo(): void {
$response = $this->createMock(Http\Response::class);
$this->assertEquals(
@@ -94,7 +94,7 @@ class ShareInfoMiddlewareTest extends TestCase {
);
}
- public function testAfterControllerNoJSON() {
+ public function testAfterControllerNoJSON(): void {
$response = $this->createMock(Http\Response::class);
$this->assertEquals(
@@ -103,7 +103,7 @@ class ShareInfoMiddlewareTest extends TestCase {
);
}
- public function testAfterControllerJSONok() {
+ public function testAfterControllerJSONok(): void {
$data = ['foo' => 'bar'];
$response = new JSONResponse($data);
@@ -118,7 +118,7 @@ class ShareInfoMiddlewareTest extends TestCase {
);
}
- public function testAfterControllerJSONerror() {
+ public function testAfterControllerJSONerror(): void {
$data = ['foo' => 'bar'];
$response = new JSONResponse($data, Http::STATUS_FORBIDDEN);
diff --git a/apps/files_sharing/tests/Middleware/SharingCheckMiddlewareTest.php b/apps/files_sharing/tests/Middleware/SharingCheckMiddlewareTest.php
index 580295a26ec..99fcb4eaea0 100644
--- a/apps/files_sharing/tests/Middleware/SharingCheckMiddlewareTest.php
+++ b/apps/files_sharing/tests/Middleware/SharingCheckMiddlewareTest.php
@@ -59,7 +59,7 @@ class SharingCheckMiddlewareTest extends \Test\TestCase {
$this->request);
}
- public function testIsSharingEnabledWithAppEnabled() {
+ public function testIsSharingEnabledWithAppEnabled(): void {
$this->appManager
->expects($this->once())
->method('isEnabledForUser')
@@ -69,7 +69,7 @@ class SharingCheckMiddlewareTest extends \Test\TestCase {
$this->assertTrue(self::invokePrivate($this->sharingCheckMiddleware, 'isSharingEnabled'));
}
- public function testIsSharingEnabledWithAppDisabled() {
+ public function testIsSharingEnabledWithAppDisabled(): void {
$this->appManager
->expects($this->once())
->method('isEnabledForUser')
@@ -117,7 +117,7 @@ class SharingCheckMiddlewareTest extends \Test\TestCase {
/**
* @dataProvider externalSharesChecksDataProvider
*/
- public function testExternalSharesChecks($annotations, $config, $expectedResult) {
+ public function testExternalSharesChecks($annotations, $config, $expectedResult): void {
$this->reflector
->expects($this->atLeastOnce())
->method('hasAnnotation')
@@ -133,7 +133,7 @@ class SharingCheckMiddlewareTest extends \Test\TestCase {
/**
* @dataProvider externalSharesChecksDataProvider
*/
- public function testBeforeControllerWithExternalShareControllerWithSharingEnabled($annotations, $config, $noException) {
+ public function testBeforeControllerWithExternalShareControllerWithSharingEnabled($annotations, $config, $noException): void {
$this->appManager
->expects($this->once())
->method('isEnabledForUser')
@@ -162,7 +162,7 @@ class SharingCheckMiddlewareTest extends \Test\TestCase {
$this->assertNotEquals($noException, $exceptionThrown);
}
- public function testBeforeControllerWithShareControllerWithSharingEnabled() {
+ public function testBeforeControllerWithShareControllerWithSharingEnabled(): void {
$share = $this->createMock(IShare::class);
$this->appManager
@@ -177,7 +177,7 @@ class SharingCheckMiddlewareTest extends \Test\TestCase {
}
- public function testBeforeControllerWithSharingDisabled() {
+ public function testBeforeControllerWithSharingDisabled(): void {
$this->expectException(\OCP\Files\NotFoundException::class);
$this->expectExceptionMessage('Sharing is disabled.');
@@ -191,18 +191,18 @@ class SharingCheckMiddlewareTest extends \Test\TestCase {
}
- public function testAfterExceptionWithRegularException() {
+ public function testAfterExceptionWithRegularException(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('My Exception message');
$this->sharingCheckMiddleware->afterException($this->controllerMock, 'myMethod', new \Exception('My Exception message'));
}
- public function testAfterExceptionWithNotFoundException() {
+ public function testAfterExceptionWithNotFoundException(): void {
$this->assertEquals(new NotFoundResponse(), $this->sharingCheckMiddleware->afterException($this->controllerMock, 'myMethod', new NotFoundException('My Exception message')));
}
- public function testAfterExceptionWithS2SException() {
+ public function testAfterExceptionWithS2SException(): void {
$this->assertEquals(new JSONResponse('My Exception message', 405), $this->sharingCheckMiddleware->afterException($this->controllerMock, 'myMethod', new S2SException('My Exception message')));
}
}
diff --git a/apps/files_sharing/tests/Migration/SetPasswordColumnTest.php b/apps/files_sharing/tests/Migration/SetPasswordColumnTest.php
index eb377412a2e..e15914f6ba1 100644
--- a/apps/files_sharing/tests/Migration/SetPasswordColumnTest.php
+++ b/apps/files_sharing/tests/Migration/SetPasswordColumnTest.php
@@ -50,7 +50,7 @@ class SetPasswordColumnTest extends TestCase {
$query->delete($this->table)->execute();
}
- public function testAddPasswordColumn() {
+ public function testAddPasswordColumn(): void {
$this->config->expects($this->once())
->method('getAppValue')
->with('files_sharing', 'installed_version', '0.0.0')
diff --git a/apps/files_sharing/tests/MountProviderTest.php b/apps/files_sharing/tests/MountProviderTest.php
index 1167c3f9fd3..014153f5660 100644
--- a/apps/files_sharing/tests/MountProviderTest.php
+++ b/apps/files_sharing/tests/MountProviderTest.php
@@ -113,7 +113,7 @@ class MountProviderTest extends \Test\TestCase {
* - shares that were opted out of (permissions === 0)
* - shares with a group in which the owner is already in
*/
- public function testExcludeShares() {
+ public function testExcludeShares(): void {
$rootFolder = $this->createMock(IRootFolder::class);
$userManager = $this->createMock(IUserManager::class);
$attr1 = [];
@@ -346,7 +346,7 @@ class MountProviderTest extends \Test\TestCase {
* @param array $groupShares array of group share specs
* @param array $expectedShares array of expected supershare specs
*/
- public function testMergeShares($userShares, $groupShares, $expectedShares, $moveFails = false) {
+ public function testMergeShares($userShares, $groupShares, $expectedShares, $moveFails = false): void {
$rootFolder = $this->createMock(IRootFolder::class);
$userManager = $this->createMock(IUserManager::class);
diff --git a/apps/files_sharing/tests/ShareTest.php b/apps/files_sharing/tests/ShareTest.php
index a1580c97fcf..651341a5607 100644
--- a/apps/files_sharing/tests/ShareTest.php
+++ b/apps/files_sharing/tests/ShareTest.php
@@ -48,7 +48,7 @@ class ShareTest extends TestCase {
parent::tearDown();
}
- public function testUnshareFromSelf() {
+ public function testUnshareFromSelf(): void {
$groupManager = \OC::$server->getGroupManager();
$userManager = \OC::$server->getUserManager();
@@ -108,7 +108,7 @@ class ShareTest extends TestCase {
}
}
- public function testShareWithDifferentShareFolder() {
+ public function testShareWithDifferentShareFolder(): void {
$fileinfo = $this->view->getFileInfo($this->filename);
$folderinfo = $this->view->getFileInfo($this->folder);
@@ -139,7 +139,7 @@ class ShareTest extends TestCase {
\OC::$server->getConfig()->deleteSystemValue('share_folder');
}
- public function testShareWithGroupUniqueName() {
+ public function testShareWithGroupUniqueName(): void {
$this->markTestSkipped('TODO: Disable because fails on drone');
$this->loginHelper(self::TEST_FILES_SHARING_API_USER1);
@@ -182,7 +182,7 @@ class ShareTest extends TestCase {
* shared files should never have delete permissions
* @dataProvider dataProviderTestFileSharePermissions
*/
- public function testFileSharePermissions($permission, $expectedvalid) {
+ public function testFileSharePermissions($permission, $expectedvalid): void {
$pass = true;
try {
$this->share(
@@ -215,7 +215,7 @@ class ShareTest extends TestCase {
];
}
- public function testFileOwner() {
+ public function testFileOwner(): void {
$this->share(
IShare::TYPE_USER,
$this->filename,
diff --git a/apps/files_sharing/tests/SharedMountTest.php b/apps/files_sharing/tests/SharedMountTest.php
index c8d42460b8b..82c0770440d 100644
--- a/apps/files_sharing/tests/SharedMountTest.php
+++ b/apps/files_sharing/tests/SharedMountTest.php
@@ -65,7 +65,7 @@ class SharedMountTest extends TestCase {
/**
* test if the mount point moves up if the parent folder no longer exists
*/
- public function testShareMountLoseParentFolder() {
+ public function testShareMountLoseParentFolder(): void {
// share to user
$share = $this->share(
@@ -97,7 +97,7 @@ class SharedMountTest extends TestCase {
/**
* @medium
*/
- public function testDeleteParentOfMountPoint() {
+ public function testDeleteParentOfMountPoint(): void {
// share to user
$share = $this->share(
IShare::TYPE_USER,
@@ -137,7 +137,7 @@ class SharedMountTest extends TestCase {
$this->view->unlink($this->folder);
}
- public function testMoveSharedFile() {
+ public function testMoveSharedFile(): void {
$share = $this->share(
IShare::TYPE_USER,
$this->filename,
@@ -171,7 +171,7 @@ class SharedMountTest extends TestCase {
* share file with a group if a user renames the file the filename should not change
* for the other users
*/
- public function testMoveGroupShare() {
+ public function testMoveGroupShare(): void {
$testGroup = $this->groupManager->createGroup('testGroup');
$user1 = $this->userManager->get(self::TEST_FILES_SHARING_API_USER1);
$user2 = $this->userManager->get(self::TEST_FILES_SHARING_API_USER2);
@@ -223,7 +223,7 @@ class SharedMountTest extends TestCase {
* @param string $expectedResult
* @param bool $exception if a exception is expected
*/
- public function testStripUserFilesPath($path, $expectedResult, $exception) {
+ public function testStripUserFilesPath($path, $expectedResult, $exception): void {
$testClass = new DummyTestClassSharedMount(null, null);
try {
$result = $testClass->stripUserFilesPathDummy($path);
@@ -252,7 +252,7 @@ class SharedMountTest extends TestCase {
* If the permissions on a group share are upgraded be sure to still respect
* removed shares by a member of that group
*/
- public function testPermissionUpgradeOnUserDeletedGroupShare() {
+ public function testPermissionUpgradeOnUserDeletedGroupShare(): void {
$testGroup = $this->groupManager->createGroup('testGroup');
$user1 = $this->userManager->get(self::TEST_FILES_SHARING_API_USER1);
$user2 = $this->userManager->get(self::TEST_FILES_SHARING_API_USER2);
@@ -314,7 +314,7 @@ class SharedMountTest extends TestCase {
/**
* test if the mount point gets renamed if a folder exists at the target
*/
- public function testShareMountOverFolder() {
+ public function testShareMountOverFolder(): void {
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
$this->view2->mkdir('bar');
@@ -349,7 +349,7 @@ class SharedMountTest extends TestCase {
/**
* test if the mount point gets renamed if another share exists at the target
*/
- public function testShareMountOverShare() {
+ public function testShareMountOverShare(): void {
// create a shared cache
$caches = [];
$cacheFactory = $this->createMock(ICacheFactory::class);
diff --git a/apps/files_sharing/tests/SharedStorageTest.php b/apps/files_sharing/tests/SharedStorageTest.php
index 12b286939ae..521872755b5 100644
--- a/apps/files_sharing/tests/SharedStorageTest.php
+++ b/apps/files_sharing/tests/SharedStorageTest.php
@@ -56,7 +56,7 @@ class SharedStorageTest extends TestCase {
*
* @medium
*/
- public function testParentOfMountPointIsGone() {
+ public function testParentOfMountPointIsGone(): void {
// share to user
$share = $this->share(
@@ -101,7 +101,7 @@ class SharedStorageTest extends TestCase {
/**
* @medium
*/
- public function testRenamePartFile() {
+ public function testRenamePartFile(): void {
// share to user
$share = $this->share(
@@ -139,7 +139,7 @@ class SharedStorageTest extends TestCase {
$this->shareManager->deleteShare($share);
}
- public function testFilesize() {
+ public function testFilesize(): void {
$folderSize = $this->view->filesize($this->folder);
$file1Size = $this->view->filesize($this->folder . $this->filename);
$file2Size = $this->view->filesize($this->filename);
@@ -173,7 +173,7 @@ class SharedStorageTest extends TestCase {
$this->shareManager->deleteShare($share2);
}
- public function testGetPermissions() {
+ public function testGetPermissions(): void {
$share = $this->share(
IShare::TYPE_USER,
$this->folder,
@@ -203,7 +203,7 @@ class SharedStorageTest extends TestCase {
$this->shareManager->deleteShare($share);
}
- public function testFopenWithReadOnlyPermission() {
+ public function testFopenWithReadOnlyPermission(): void {
$this->view->file_put_contents($this->folder . '/existing.txt', 'foo');
$share = $this->share(
@@ -235,7 +235,7 @@ class SharedStorageTest extends TestCase {
$this->shareManager->deleteShare($share);
}
- public function testFopenWithCreateOnlyPermission() {
+ public function testFopenWithCreateOnlyPermission(): void {
$this->view->file_put_contents($this->folder . '/existing.txt', 'foo');
$fileinfoFolder = $this->view->getFileInfo($this->folder);
@@ -282,7 +282,7 @@ class SharedStorageTest extends TestCase {
$this->shareManager->deleteShare($share);
}
- public function testFopenWithUpdateOnlyPermission() {
+ public function testFopenWithUpdateOnlyPermission(): void {
$this->view->file_put_contents($this->folder . '/existing.txt', 'foo');
$share = $this->share(
@@ -328,7 +328,7 @@ class SharedStorageTest extends TestCase {
$this->shareManager->deleteShare($share);
}
- public function testFopenWithDeleteOnlyPermission() {
+ public function testFopenWithDeleteOnlyPermission(): void {
$this->view->file_put_contents($this->folder . '/existing.txt', 'foo');
$share = $this->share(
@@ -360,7 +360,7 @@ class SharedStorageTest extends TestCase {
$this->shareManager->deleteShare($share);
}
- public function testMountSharesOtherUser() {
+ public function testMountSharesOtherUser(): void {
$rootView = new \OC\Files\View('');
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
@@ -401,7 +401,7 @@ class SharedStorageTest extends TestCase {
$this->shareManager->deleteShare($share2);
}
- public function testCopyFromStorage() {
+ public function testCopyFromStorage(): void {
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
$share = $this->share(
@@ -434,7 +434,7 @@ class SharedStorageTest extends TestCase {
$this->shareManager->deleteShare($share);
}
- public function testMoveFromStorage() {
+ public function testMoveFromStorage(): void {
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
$share = $this->share(
@@ -467,7 +467,7 @@ class SharedStorageTest extends TestCase {
$this->shareManager->deleteShare($share);
}
- public function testNameConflict() {
+ public function testNameConflict(): void {
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
$view1 = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER1 . '/files');
$view1->mkdir('foo');
@@ -518,7 +518,7 @@ class SharedStorageTest extends TestCase {
$this->shareManager->deleteShare($share2);
}
- public function testOwnerPermissions() {
+ public function testOwnerPermissions(): void {
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
$share = $this->share(
@@ -545,7 +545,7 @@ class SharedStorageTest extends TestCase {
$this->shareManager->deleteShare($share);
}
- public function testInitWithNonExistingUser() {
+ public function testInitWithNonExistingUser(): void {
$share = $this->createMock(IShare::class);
$share->method('getShareOwner')->willReturn('unexist');
$ownerView = $this->createMock(View::class);
@@ -561,7 +561,7 @@ class SharedStorageTest extends TestCase {
$this->assertInstanceOf(\OC\Files\Cache\FailedCache::class, $storage->getCache());
}
- public function testInitWithNotFoundSource() {
+ public function testInitWithNotFoundSource(): void {
$share = $this->createMock(IShare::class);
$share->method('getShareOwner')->willReturn(self::TEST_FILES_SHARING_API_USER1);
$share->method('getNodeId')->willReturn(1);
diff --git a/apps/files_sharing/tests/SizePropagationTest.php b/apps/files_sharing/tests/SizePropagationTest.php
index 14223d86e40..56057a3722c 100644
--- a/apps/files_sharing/tests/SizePropagationTest.php
+++ b/apps/files_sharing/tests/SizePropagationTest.php
@@ -28,7 +28,7 @@ class SizePropagationTest extends TestCase {
return new View('/' . $name . '/files');
}
- public function testSizePropagationWhenOwnerChangesFile() {
+ public function testSizePropagationWhenOwnerChangesFile(): void {
$recipientView = $this->setupUser(self::TEST_FILES_SHARING_API_USER1);
$ownerView = $this->setupUser(self::TEST_FILES_SHARING_API_USER2);
@@ -63,7 +63,7 @@ class SizePropagationTest extends TestCase {
$this->assertEquals($ownerRootInfo->getSize() + 3, $newOwnerRootInfo->getSize());
}
- public function testSizePropagationWhenRecipientChangesFile() {
+ public function testSizePropagationWhenRecipientChangesFile(): void {
$recipientView = $this->setupUser(self::TEST_FILES_SHARING_API_USER1);
$ownerView = $this->setupUser(self::TEST_FILES_SHARING_API_USER2);
diff --git a/apps/files_sharing/tests/UnshareChildrenTest.php b/apps/files_sharing/tests/UnshareChildrenTest.php
index 892788db3db..dd84061b9d3 100644
--- a/apps/files_sharing/tests/UnshareChildrenTest.php
+++ b/apps/files_sharing/tests/UnshareChildrenTest.php
@@ -54,7 +54,7 @@ class UnshareChildrenTest extends TestCase {
/**
* @medium
*/
- public function testUnshareChildren() {
+ public function testUnshareChildren(): void {
$fileInfo2 = \OC\Files\Filesystem::getFileInfo($this->folder);
$this->share(
diff --git a/apps/files_sharing/tests/UpdaterTest.php b/apps/files_sharing/tests/UpdaterTest.php
index aeefbac5934..9d26ff873a5 100644
--- a/apps/files_sharing/tests/UpdaterTest.php
+++ b/apps/files_sharing/tests/UpdaterTest.php
@@ -50,7 +50,7 @@ class UpdaterTest extends TestCase {
* points should be unshared before the folder gets deleted so
* that the mount point doesn't end up at the trash bin
*/
- public function testDeleteParentFolder() {
+ public function testDeleteParentFolder(): void {
$status = \OC::$server->getAppManager()->isEnabledForUser('files_trashbin');
(new \OC_App())->enable('files_trashbin');
@@ -128,7 +128,7 @@ class UpdaterTest extends TestCase {
*
* @param string $shareFolder share folder to use
*/
- public function testShareFile($shareFolder) {
+ public function testShareFile($shareFolder): void {
$config = \OC::$server->getConfig();
$oldShareFolder = $config->getSystemValue('share_folder');
$config->setSystemValue('share_folder', $shareFolder);
@@ -178,7 +178,7 @@ class UpdaterTest extends TestCase {
/**
* if a folder gets renamed all children mount points should be renamed too
*/
- public function testRename() {
+ public function testRename(): void {
$fileinfo = \OC\Files\Filesystem::getFileInfo($this->folder);
$share = $this->share(
@@ -225,7 +225,7 @@ class UpdaterTest extends TestCase {
* |-subfolder2
* |-file2.txt --> shared with user3
*/
- public function testMovedIntoShareChangeOwner() {
+ public function testMovedIntoShareChangeOwner(): void {
$this->markTestSkipped('Skipped because this is failing with S3 as primary as file id are change when moved.');
// user1 creates folder1
diff --git a/apps/files_sharing/tests/WatcherTest.php b/apps/files_sharing/tests/WatcherTest.php
index c116f542fba..012acdcd691 100644
--- a/apps/files_sharing/tests/WatcherTest.php
+++ b/apps/files_sharing/tests/WatcherTest.php
@@ -87,7 +87,7 @@ class WatcherTest extends TestCase {
* Tests that writing a file using the shared storage will propagate the file
* size to the owner's parent folders.
*/
- public function testFolderSizePropagationToOwnerStorage() {
+ public function testFolderSizePropagationToOwnerStorage(): void {
$initialSizes = self::getOwnerDirSizes('files/container/shareddir');
$textData = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
@@ -117,7 +117,7 @@ class WatcherTest extends TestCase {
* Tests that writing a file using the shared storage will propagate the file
* size to the owner's parent folders.
*/
- public function testSubFolderSizePropagationToOwnerStorage() {
+ public function testSubFolderSizePropagationToOwnerStorage(): void {
$initialSizes = self::getOwnerDirSizes('files/container/shareddir/subdir');
$textData = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
diff --git a/apps/files_trashbin/tests/CapabilitiesTest.php b/apps/files_trashbin/tests/CapabilitiesTest.php
index f5d3bdd9a9b..a2a17ca349e 100644
--- a/apps/files_trashbin/tests/CapabilitiesTest.php
+++ b/apps/files_trashbin/tests/CapabilitiesTest.php
@@ -18,7 +18,7 @@ class CapabilitiesTest extends TestCase {
$this->capabilities = new Capabilities();
}
- public function testGetCapabilities() {
+ public function testGetCapabilities(): void {
$capabilities = [
'files' => [
'undelete' => true
diff --git a/apps/files_trashbin/tests/Command/CleanUpTest.php b/apps/files_trashbin/tests/Command/CleanUpTest.php
index dd8d5b5d3c2..625ca595a11 100644
--- a/apps/files_trashbin/tests/Command/CleanUpTest.php
+++ b/apps/files_trashbin/tests/Command/CleanUpTest.php
@@ -82,7 +82,7 @@ class CleanUpTest extends TestCase {
* @dataProvider dataTestRemoveDeletedFiles
* @param boolean $nodeExists
*/
- public function testRemoveDeletedFiles(bool $nodeExists) {
+ public function testRemoveDeletedFiles(bool $nodeExists): void {
$this->initTable();
$this->rootFolder
->method('nodeExists')
@@ -137,7 +137,7 @@ class CleanUpTest extends TestCase {
/**
* test remove deleted files from users given as parameter
*/
- public function testExecuteDeleteListOfUsers() {
+ public function testExecuteDeleteListOfUsers(): void {
$userIds = ['user1', 'user2', 'user3'];
$instance = $this->getMockBuilder(\OCA\Files_Trashbin\Command\CleanUp::class)
->setMethods(['removeDeletedFiles'])
@@ -168,7 +168,7 @@ class CleanUpTest extends TestCase {
/**
* test remove deleted files of all users
*/
- public function testExecuteAllUsers() {
+ public function testExecuteAllUsers(): void {
$userIds = [];
$backendUsers = ['user1', 'user2'];
$instance = $this->getMockBuilder(\OCA\Files_Trashbin\Command\CleanUp::class)
@@ -200,7 +200,7 @@ class CleanUpTest extends TestCase {
$this->invokePrivate($instance, 'execute', [$inputInterface, $outputInterface]);
}
- public function testExecuteNoUsersAndNoAllUsers() {
+ public function testExecuteNoUsersAndNoAllUsers(): void {
$inputInterface = $this->createMock(InputInterface::class);
$inputInterface->method('getArgument')
->with('user_id')
@@ -218,7 +218,7 @@ class CleanUpTest extends TestCase {
$this->invokePrivate($this->cleanup, 'execute', [$inputInterface, $outputInterface]);
}
- public function testExecuteUsersAndAllUsers() {
+ public function testExecuteUsersAndAllUsers(): void {
$inputInterface = $this->createMock(InputInterface::class);
$inputInterface->method('getArgument')
->with('user_id')
diff --git a/apps/files_trashbin/tests/Command/ExpireTest.php b/apps/files_trashbin/tests/Command/ExpireTest.php
index 5a7f857adbe..4402e07bbb0 100644
--- a/apps/files_trashbin/tests/Command/ExpireTest.php
+++ b/apps/files_trashbin/tests/Command/ExpireTest.php
@@ -17,7 +17,7 @@ use Test\TestCase;
* @package OCA\Files_Trashbin\Tests\Command
*/
class ExpireTest extends TestCase {
- public function testExpireNonExistingUser() {
+ public function testExpireNonExistingUser(): void {
$command = new Expire('test');
$command->handle();
diff --git a/apps/files_trashbin/tests/Controller/PreviewControllerTest.php b/apps/files_trashbin/tests/Controller/PreviewControllerTest.php
index f834b324f2b..1076870bb9f 100644
--- a/apps/files_trashbin/tests/Controller/PreviewControllerTest.php
+++ b/apps/files_trashbin/tests/Controller/PreviewControllerTest.php
@@ -78,21 +78,21 @@ class PreviewControllerTest extends TestCase {
);
}
- public function testInvalidWidth() {
+ public function testInvalidWidth(): void {
$res = $this->controller->getPreview(42, 0);
$expected = new DataResponse([], Http::STATUS_BAD_REQUEST);
$this->assertEquals($expected, $res);
}
- public function testInvalidHeight() {
+ public function testInvalidHeight(): void {
$res = $this->controller->getPreview(42, 10, 0);
$expected = new DataResponse([], Http::STATUS_BAD_REQUEST);
$this->assertEquals($expected, $res);
}
- public function testValidPreview() {
+ public function testValidPreview(): void {
$userFolder = $this->createMock(Folder::class);
$userRoot = $this->createMock(Folder::class);
$trash = $this->createMock(Folder::class);
@@ -145,7 +145,7 @@ class PreviewControllerTest extends TestCase {
$this->assertEquals($expected, $res);
}
- public function testTrashFileNotFound() {
+ public function testTrashFileNotFound(): void {
$userFolder = $this->createMock(Folder::class);
$userRoot = $this->createMock(Folder::class);
$trash = $this->createMock(Folder::class);
@@ -169,7 +169,7 @@ class PreviewControllerTest extends TestCase {
$this->assertEquals($expected, $res);
}
- public function testTrashFolder() {
+ public function testTrashFolder(): void {
$userFolder = $this->createMock(Folder::class);
$userRoot = $this->createMock(Folder::class);
$trash = $this->createMock(Folder::class);
diff --git a/apps/files_trashbin/tests/ExpirationTest.php b/apps/files_trashbin/tests/ExpirationTest.php
index bf4e1ef2ad9..7f026c16806 100644
--- a/apps/files_trashbin/tests/ExpirationTest.php
+++ b/apps/files_trashbin/tests/ExpirationTest.php
@@ -89,7 +89,7 @@ class ExpirationTest extends \Test\TestCase {
* @param bool $quotaExceeded
* @param string $expectedResult
*/
- public function testExpiration($retentionObligation, $timeNow, $timestamp, $quotaExceeded, $expectedResult) {
+ public function testExpiration($retentionObligation, $timeNow, $timestamp, $quotaExceeded, $expectedResult): void {
$mockedConfig = $this->getMockedConfig($retentionObligation);
$mockedTimeFactory = $this->getMockedTimeFactory($timeNow);
@@ -120,7 +120,7 @@ class ExpirationTest extends \Test\TestCase {
* @param string $configValue
* @param int $expectedMaxAgeTimestamp
*/
- public function testGetMaxAgeAsTimestamp($configValue, $expectedMaxAgeTimestamp) {
+ public function testGetMaxAgeAsTimestamp($configValue, $expectedMaxAgeTimestamp): void {
$mockedConfig = $this->getMockedConfig($configValue);
$mockedTimeFactory = $this->getMockedTimeFactory(
self::FAKE_TIME_NOW
diff --git a/apps/files_trashbin/tests/StorageTest.php b/apps/files_trashbin/tests/StorageTest.php
index 5e8542fd051..eaf815f9c89 100644
--- a/apps/files_trashbin/tests/StorageTest.php
+++ b/apps/files_trashbin/tests/StorageTest.php
@@ -110,7 +110,7 @@ class StorageTest extends \Test\TestCase {
/**
* Test that deleting a file puts it into the trashbin.
*/
- public function testSingleStorageDeleteFile() {
+ public function testSingleStorageDeleteFile(): void {
$this->assertTrue($this->userView->file_exists('test.txt'));
$this->userView->unlink('test.txt');
[$storage,] = $this->userView->resolvePath('test.txt');
@@ -127,7 +127,7 @@ class StorageTest extends \Test\TestCase {
/**
* Test that deleting a folder puts it into the trashbin.
*/
- public function testSingleStorageDeleteFolder() {
+ public function testSingleStorageDeleteFolder(): void {
$this->assertTrue($this->userView->file_exists('folder/inside.txt'));
$this->userView->rmdir('folder');
[$storage,] = $this->userView->resolvePath('folder/inside.txt');
@@ -149,7 +149,7 @@ class StorageTest extends \Test\TestCase {
/**
* Test that deleting a file with a long filename puts it into the trashbin.
*/
- public function testSingleStorageDeleteLongFilename() {
+ public function testSingleStorageDeleteLongFilename(): void {
$truncatedFilename = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.txt';
$this->assertTrue($this->userView->file_exists(static::LONG_FILENAME));
@@ -168,7 +168,7 @@ class StorageTest extends \Test\TestCase {
/**
* Test that deleting a file with the max filename length puts it into the trashbin.
*/
- public function testSingleStorageDeleteMaxLengthFilename() {
+ public function testSingleStorageDeleteMaxLengthFilename(): void {
$truncatedFilename = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.txt';
$this->assertTrue($this->userView->file_exists(static::MAX_FILENAME));
@@ -190,7 +190,7 @@ class StorageTest extends \Test\TestCase {
* the trashbin folder is in the root storage while the mounted one
* isn't.
*/
- public function testCrossStorageDeleteFile() {
+ public function testCrossStorageDeleteFile(): void {
$storage2 = new Temporary([]);
\OC\Files\Filesystem::mount($storage2, [], $this->user . '/files/substorage');
@@ -216,7 +216,7 @@ class StorageTest extends \Test\TestCase {
* the trashbin folder is in the root storage while the mounted one
* isn't.
*/
- public function testCrossStorageDeleteFolder() {
+ public function testCrossStorageDeleteFolder(): void {
$storage2 = new Temporary([]);
\OC\Files\Filesystem::mount($storage2, [], $this->user . '/files/substorage');
@@ -245,7 +245,7 @@ class StorageTest extends \Test\TestCase {
/**
* Test that deleted versions properly land in the trashbin.
*/
- public function testDeleteVersionsOfFile() {
+ public function testDeleteVersionsOfFile(): void {
// trigger a version (multiple would not work because of the expire logic)
$this->userView->file_put_contents('test.txt', 'v1');
@@ -272,7 +272,7 @@ class StorageTest extends \Test\TestCase {
/**
* Test that deleted versions properly land in the trashbin.
*/
- public function testDeleteVersionsOfFolder() {
+ public function testDeleteVersionsOfFolder(): void {
// trigger a version (multiple would not work because of the expire logic)
$this->userView->file_put_contents('folder/inside.txt', 'v1');
@@ -305,7 +305,7 @@ class StorageTest extends \Test\TestCase {
/**
* Test that deleted versions properly land in the trashbin when deleting as share recipient.
*/
- public function testDeleteVersionsOfFileAsRecipient() {
+ public function testDeleteVersionsOfFileAsRecipient(): void {
$this->userView->mkdir('share');
// trigger a version (multiple would not work because of the expire logic)
$this->userView->file_put_contents('share/test.txt', 'v1');
@@ -356,7 +356,7 @@ class StorageTest extends \Test\TestCase {
/**
* Test that deleted versions properly land in the trashbin when deleting as share recipient.
*/
- public function testDeleteVersionsOfFolderAsRecipient() {
+ public function testDeleteVersionsOfFolderAsRecipient(): void {
$this->userView->mkdir('share');
$this->userView->mkdir('share/folder');
// trigger a version (multiple would not work because of the expire logic)
@@ -423,7 +423,7 @@ class StorageTest extends \Test\TestCase {
* storages. This is because rename() between storages would call
* unlink() which should NOT trigger the version deletion logic.
*/
- public function testKeepFileAndVersionsWhenMovingFileBetweenStorages() {
+ public function testKeepFileAndVersionsWhenMovingFileBetweenStorages(): void {
$storage2 = new Temporary([]);
\OC\Files\Filesystem::mount($storage2, [], $this->user . '/files/substorage');
@@ -462,7 +462,7 @@ class StorageTest extends \Test\TestCase {
* storages. This is because rename() between storages would call
* unlink() which should NOT trigger the version deletion logic.
*/
- public function testKeepFileAndVersionsWhenMovingFolderBetweenStorages() {
+ public function testKeepFileAndVersionsWhenMovingFolderBetweenStorages(): void {
$storage2 = new Temporary([]);
\OC\Files\Filesystem::mount($storage2, [], $this->user . '/files/substorage');
@@ -499,7 +499,7 @@ class StorageTest extends \Test\TestCase {
/**
* Delete should fail if the source file can't be deleted.
*/
- public function testSingleStorageDeleteFileFail() {
+ public function testSingleStorageDeleteFileFail(): void {
/**
* @var \OC\Files\Storage\Temporary | \PHPUnit\Framework\MockObject\MockObject $storage
*/
@@ -536,7 +536,7 @@ class StorageTest extends \Test\TestCase {
/**
* Delete should fail if the source folder can't be deleted.
*/
- public function testSingleStorageDeleteFolderFail() {
+ public function testSingleStorageDeleteFolderFail(): void {
/**
* @var \OC\Files\Storage\Temporary | \PHPUnit\Framework\MockObject\MockObject $storage
*/
@@ -570,7 +570,7 @@ class StorageTest extends \Test\TestCase {
/**
* @dataProvider dataTestShouldMoveToTrash
*/
- public function testShouldMoveToTrash($mountPoint, $path, $userExists, $appDisablesTrash, $expected) {
+ public function testShouldMoveToTrash($mountPoint, $path, $userExists, $appDisablesTrash, $expected): void {
$fileID = 1;
$cache = $this->createMock(ICache::class);
$cache->expects($this->any())->method('getId')->willReturn($fileID);
@@ -628,7 +628,7 @@ class StorageTest extends \Test\TestCase {
/**
* Test that deleting a file doesn't error when nobody is logged in
*/
- public function testSingleStorageDeleteFileLoggedOut() {
+ public function testSingleStorageDeleteFileLoggedOut(): void {
$this->logout();
if (!$this->userView->file_exists('test.txt')) {
@@ -639,7 +639,7 @@ class StorageTest extends \Test\TestCase {
}
}
- public function testTrashbinCollision() {
+ public function testTrashbinCollision(): void {
$this->userView->file_put_contents('test.txt', 'foo');
$this->userView->file_put_contents('folder/test.txt', 'bar');
@@ -671,7 +671,7 @@ class StorageTest extends \Test\TestCase {
$this->assertEquals('bar', $this->rootView->file_get_contents($this->user . '/files_trashbin/files/test.txt.d1001'));
}
- public function testMoveFromStoragePreserveFileId() {
+ public function testMoveFromStoragePreserveFileId(): void {
if (!$this->userView->getMount('')->getStorage()->instanceOfStorage(Local::class)) {
$this->markTestSkipped('Skipping on non-local users storage');
}
diff --git a/apps/files_trashbin/tests/TrashbinTest.php b/apps/files_trashbin/tests/TrashbinTest.php
index 87f4bf55679..df361ee6b76 100644
--- a/apps/files_trashbin/tests/TrashbinTest.php
+++ b/apps/files_trashbin/tests/TrashbinTest.php
@@ -146,7 +146,7 @@ class TrashbinTest extends \Test\TestCase {
/**
* test expiration of files older then the max storage time defined for the trash
*/
- public function testExpireOldFiles() {
+ public function testExpireOldFiles(): void {
/** @var \OCP\AppFramework\Utility\ITimeFactory $time */
$time = \OC::$server->query(\OCP\AppFramework\Utility\ITimeFactory::class);
@@ -198,7 +198,7 @@ class TrashbinTest extends \Test\TestCase {
* the owner of the file and the one from the user who deleted the file get expired
* correctly
*/
- public function testExpireOldFilesShared() {
+ public function testExpireOldFilesShared(): void {
$currentTime = time();
$folder = 'trashTest-' . $currentTime . '/';
$expiredDate = $currentTime - 3 * 24 * 60 * 60;
@@ -316,7 +316,7 @@ class TrashbinTest extends \Test\TestCase {
* test expiration of old files in the trash bin until the max size
* of the trash bin is met again
*/
- public function testExpireOldFilesUtilLimitsAreMet() {
+ public function testExpireOldFilesUtilLimitsAreMet(): void {
// create some files
\OC\Files\Filesystem::file_put_contents('file1.txt', 'file1');
@@ -349,7 +349,7 @@ class TrashbinTest extends \Test\TestCase {
/**
* Test restoring a file
*/
- public function testRestoreFileInRoot() {
+ public function testRestoreFileInRoot(): void {
$userFolder = \OC::$server->getUserFolder();
$file = $userFolder->newFile('file1.txt');
$file->putContent('foo');
@@ -381,7 +381,7 @@ class TrashbinTest extends \Test\TestCase {
/**
* Test restoring a file in subfolder
*/
- public function testRestoreFileInSubfolder() {
+ public function testRestoreFileInSubfolder(): void {
$userFolder = \OC::$server->getUserFolder();
$folder = $userFolder->newFolder('folder');
$file = $folder->newFile('file1.txt');
@@ -414,7 +414,7 @@ class TrashbinTest extends \Test\TestCase {
/**
* Test restoring a folder
*/
- public function testRestoreFolder() {
+ public function testRestoreFolder(): void {
$userFolder = \OC::$server->getUserFolder();
$folder = $userFolder->newFolder('folder');
$file = $folder->newFile('file1.txt');
@@ -447,7 +447,7 @@ class TrashbinTest extends \Test\TestCase {
/**
* Test restoring a file from inside a trashed folder
*/
- public function testRestoreFileFromTrashedSubfolder() {
+ public function testRestoreFileFromTrashedSubfolder(): void {
$userFolder = \OC::$server->getUserFolder();
$folder = $userFolder->newFolder('folder');
$file = $folder->newFile('file1.txt');
@@ -481,7 +481,7 @@ class TrashbinTest extends \Test\TestCase {
* Test restoring a file whenever the source folder was removed.
* The file should then land in the root.
*/
- public function testRestoreFileWithMissingSourceFolder() {
+ public function testRestoreFileWithMissingSourceFolder(): void {
$userFolder = \OC::$server->getUserFolder();
$folder = $userFolder->newFolder('folder');
$file = $folder->newFile('file1.txt');
@@ -518,7 +518,7 @@ class TrashbinTest extends \Test\TestCase {
* Test restoring a file in the root folder whenever there is another file
* with the same name in the root folder
*/
- public function testRestoreFileDoesNotOverwriteExistingInRoot() {
+ public function testRestoreFileDoesNotOverwriteExistingInRoot(): void {
$userFolder = \OC::$server->getUserFolder();
$file = $userFolder->newFile('file1.txt');
$file->putContent('foo');
@@ -558,7 +558,7 @@ class TrashbinTest extends \Test\TestCase {
* Test restoring a file whenever there is another file
* with the same name in the source folder
*/
- public function testRestoreFileDoesNotOverwriteExistingInSubfolder() {
+ public function testRestoreFileDoesNotOverwriteExistingInSubfolder(): void {
$userFolder = \OC::$server->getUserFolder();
$folder = $userFolder->newFolder('folder');
$file = $folder->newFile('file1.txt');
@@ -598,7 +598,7 @@ class TrashbinTest extends \Test\TestCase {
/**
* Test restoring a non-existing file from trashbin, returns false
*/
- public function testRestoreUnexistingFile() {
+ public function testRestoreUnexistingFile(): void {
$this->assertFalse(
OCA\Files_Trashbin\Trashbin::restore(
'unexist.txt.d123456',
@@ -612,7 +612,7 @@ class TrashbinTest extends \Test\TestCase {
* Test restoring a file into a read-only folder, will restore
* the file to root instead
*/
- public function testRestoreFileIntoReadOnlySourceFolder() {
+ public function testRestoreFileIntoReadOnlySourceFolder(): void {
$userFolder = \OC::$server->getUserFolder();
$folder = $userFolder->newFolder('folder');
$file = $folder->newFile('file1.txt');
diff --git a/apps/files_versions/tests/Command/CleanupTest.php b/apps/files_versions/tests/Command/CleanupTest.php
index de222d61257..efa873edf86 100644
--- a/apps/files_versions/tests/Command/CleanupTest.php
+++ b/apps/files_versions/tests/Command/CleanupTest.php
@@ -52,7 +52,7 @@ class CleanupTest extends TestCase {
* @dataProvider dataTestDeleteVersions
* @param boolean $nodeExists
*/
- public function testDeleteVersions($nodeExists) {
+ public function testDeleteVersions($nodeExists): void {
$this->rootFolder->expects($this->once())
->method('nodeExists')
->with('/testUser/files_versions')
@@ -102,7 +102,7 @@ class CleanupTest extends TestCase {
/**
* test delete versions from users given as parameter
*/
- public function testExecuteDeleteListOfUsers() {
+ public function testExecuteDeleteListOfUsers(): void {
$userIds = ['user1', 'user2', 'user3'];
$instance = $this->getMockBuilder(\OCA\Files_Versions\Command\CleanUp::class)
@@ -133,7 +133,7 @@ class CleanupTest extends TestCase {
/**
* test delete versions of all users
*/
- public function testExecuteAllUsers() {
+ public function testExecuteAllUsers(): void {
$userIds = [];
$backendUsers = ['user1', 'user2'];
diff --git a/apps/files_versions/tests/Command/ExpireTest.php b/apps/files_versions/tests/Command/ExpireTest.php
index ac1fc4ada7f..11f4eb2e2be 100644
--- a/apps/files_versions/tests/Command/ExpireTest.php
+++ b/apps/files_versions/tests/Command/ExpireTest.php
@@ -17,7 +17,7 @@ use Test\TestCase;
* @package OCA\Files_Versions\Tests\Command
*/
class ExpireTest extends TestCase {
- public function testExpireNonExistingUser() {
+ public function testExpireNonExistingUser(): void {
$command = new Expire($this->getUniqueID('test'), '');
$command->handle();
diff --git a/apps/files_versions/tests/Controller/PreviewControllerTest.php b/apps/files_versions/tests/Controller/PreviewControllerTest.php
index 1673a212f89..9899836bb88 100644
--- a/apps/files_versions/tests/Controller/PreviewControllerTest.php
+++ b/apps/files_versions/tests/Controller/PreviewControllerTest.php
@@ -71,35 +71,35 @@ class PreviewControllerTest extends TestCase {
);
}
- public function testInvalidFile() {
+ public function testInvalidFile(): void {
$res = $this->controller->getPreview('');
$expected = new DataResponse([], Http::STATUS_BAD_REQUEST);
$this->assertEquals($expected, $res);
}
- public function testInvalidWidth() {
+ public function testInvalidWidth(): void {
$res = $this->controller->getPreview('file', 0);
$expected = new DataResponse([], Http::STATUS_BAD_REQUEST);
$this->assertEquals($expected, $res);
}
- public function testInvalidHeight() {
+ public function testInvalidHeight(): void {
$res = $this->controller->getPreview('file', 10, 0);
$expected = new DataResponse([], Http::STATUS_BAD_REQUEST);
$this->assertEquals($expected, $res);
}
- public function testInvalidVersion() {
+ public function testInvalidVersion(): void {
$res = $this->controller->getPreview('file', 10, 0);
$expected = new DataResponse([], Http::STATUS_BAD_REQUEST);
$this->assertEquals($expected, $res);
}
- public function testValidPreview() {
+ public function testValidPreview(): void {
$userFolder = $this->createMock(Folder::class);
$userRoot = $this->createMock(Folder::class);
@@ -136,7 +136,7 @@ class PreviewControllerTest extends TestCase {
$this->assertEquals($expected, $res);
}
- public function testVersionNotFound() {
+ public function testVersionNotFound(): void {
$userFolder = $this->createMock(Folder::class);
$userRoot = $this->createMock(Folder::class);
diff --git a/apps/files_versions/tests/ExpirationTest.php b/apps/files_versions/tests/ExpirationTest.php
index a998d3a3e9a..ac8af7c093a 100644
--- a/apps/files_versions/tests/ExpirationTest.php
+++ b/apps/files_versions/tests/ExpirationTest.php
@@ -88,7 +88,7 @@ class ExpirationTest extends \Test\TestCase {
* @param bool $quotaExceeded
* @param string $expectedResult
*/
- public function testExpiration($retentionObligation, $timeNow, $timestamp, $quotaExceeded, $expectedResult) {
+ public function testExpiration($retentionObligation, $timeNow, $timestamp, $quotaExceeded, $expectedResult): void {
$mockedConfig = $this->getMockedConfig($retentionObligation);
$mockedTimeFactory = $this->getMockedTimeFactory($timeNow);
$mockedLogger = $this->createMock(LoggerInterface::class);
diff --git a/apps/files_versions/tests/StorageTest.php b/apps/files_versions/tests/StorageTest.php
index ead125e905c..e085729eddd 100644
--- a/apps/files_versions/tests/StorageTest.php
+++ b/apps/files_versions/tests/StorageTest.php
@@ -55,7 +55,7 @@ class StorageTest extends TestCase {
$file->touch($mtime);
}
- public function testExpireMaxAge() {
+ public function testExpireMaxAge(): void {
$this->userFolder->newFolder('folder1');
$this->userFolder->newFolder('folder1/sub1');
$this->userFolder->newFolder('folder2');
diff --git a/apps/files_versions/tests/VersioningTest.php b/apps/files_versions/tests/VersioningTest.php
index 4b6820750a2..3200b5f784b 100644
--- a/apps/files_versions/tests/VersioningTest.php
+++ b/apps/files_versions/tests/VersioningTest.php
@@ -123,7 +123,7 @@ class VersioningTest extends \Test\TestCase {
* test expire logic
* @dataProvider versionsProvider
*/
- public function testGetExpireList($versions, $sizeOfAllDeletedFiles) {
+ public function testGetExpireList($versions, $sizeOfAllDeletedFiles): void {
// last interval end at 2592000
$startTime = 5000000;
@@ -269,7 +269,7 @@ class VersioningTest extends \Test\TestCase {
];
}
- public function testRename() {
+ public function testRename(): void {
\OC\Files\Filesystem::file_put_contents('test.txt', 'test file');
$t1 = time();
@@ -298,7 +298,7 @@ class VersioningTest extends \Test\TestCase {
$this->assertTrue($this->rootView->file_exists($v2Renamed), 'version 2 of renamed file exists');
}
- public function testRenameInSharedFolder() {
+ public function testRenameInSharedFolder(): void {
\OC\Files\Filesystem::mkdir('folder1');
\OC\Files\Filesystem::mkdir('folder1/folder2');
\OC\Files\Filesystem::file_put_contents('folder1/test.txt', 'test file');
@@ -348,7 +348,7 @@ class VersioningTest extends \Test\TestCase {
\OC::$server->getShareManager()->deleteShare($share);
}
- public function testMoveFolder() {
+ public function testMoveFolder(): void {
\OC\Files\Filesystem::mkdir('folder1');
\OC\Files\Filesystem::mkdir('folder2');
\OC\Files\Filesystem::file_put_contents('folder1/test.txt', 'test file');
@@ -381,7 +381,7 @@ class VersioningTest extends \Test\TestCase {
}
- public function testMoveFileIntoSharedFolderAsRecipient() {
+ public function testMoveFileIntoSharedFolderAsRecipient(): void {
\OC\Files\Filesystem::mkdir('folder1');
$fileInfo = \OC\Files\Filesystem::getFileInfo('folder1');
@@ -431,7 +431,7 @@ class VersioningTest extends \Test\TestCase {
\OC::$server->getShareManager()->deleteShare($share);
}
- public function testMoveFolderIntoSharedFolderAsRecipient() {
+ public function testMoveFolderIntoSharedFolderAsRecipient(): void {
\OC\Files\Filesystem::mkdir('folder1');
$node = \OC::$server->getUserFolder(self::TEST_VERSIONS_USER)->get('folder1');
@@ -482,7 +482,7 @@ class VersioningTest extends \Test\TestCase {
\OC::$server->getShareManager()->deleteShare($share);
}
- public function testRenameSharedFile() {
+ public function testRenameSharedFile(): void {
\OC\Files\Filesystem::file_put_contents('test.txt', 'test file');
$t1 = time();
@@ -531,7 +531,7 @@ class VersioningTest extends \Test\TestCase {
\OC::$server->getShareManager()->deleteShare($share);
}
- public function testCopy() {
+ public function testCopy(): void {
\OC\Files\Filesystem::file_put_contents('test.txt', 'test file');
$t1 = time();
@@ -564,7 +564,7 @@ class VersioningTest extends \Test\TestCase {
* test if we find all versions and if the versions array contain
* the correct 'path' and 'name'
*/
- public function testGetVersions() {
+ public function testGetVersions(): void {
$t1 = time();
// second version is two weeks older, this way we make sure that no
// version will be expired
@@ -597,7 +597,7 @@ class VersioningTest extends \Test\TestCase {
* test if we find all versions and if the versions array contain
* the correct 'path' and 'name'
*/
- public function testGetVersionsEmptyFile() {
+ public function testGetVersionsEmptyFile(): void {
// execute copy hook of versions app
$versions = \OCA\Files_Versions\Storage::getVersions(self::TEST_VERSIONS_USER, '');
$this->assertCount(0, $versions);
@@ -606,7 +606,7 @@ class VersioningTest extends \Test\TestCase {
$this->assertCount(0, $versions);
}
- public function testExpireNonexistingFile() {
+ public function testExpireNonexistingFile(): void {
$this->logout();
// needed to have a FS setup (the background job does this)
\OC_Util::setupFS(self::TEST_VERSIONS_USER);
@@ -615,7 +615,7 @@ class VersioningTest extends \Test\TestCase {
}
- public function testExpireNonexistingUser() {
+ public function testExpireNonexistingUser(): void {
$this->expectException(\OC\User\NoUserException::class);
$this->logout();
@@ -626,19 +626,19 @@ class VersioningTest extends \Test\TestCase {
$this->assertFalse(\OCA\Files_Versions\Storage::expire('test.txt', 'unexist'));
}
- public function testRestoreSameStorage() {
+ public function testRestoreSameStorage(): void {
\OC\Files\Filesystem::mkdir('sub');
$this->doTestRestore();
}
- public function testRestoreCrossStorage() {
+ public function testRestoreCrossStorage(): void {
$storage2 = new Temporary([]);
\OC\Files\Filesystem::mount($storage2, [], self::TEST_VERSIONS_USER . '/files/sub');
$this->doTestRestore();
}
- public function testRestoreNoPermission() {
+ public function testRestoreNoPermission(): void {
$this->loginAsUser(self::TEST_VERSIONS_USER);
$userHome = \OC::$server->getUserFolder(self::TEST_VERSIONS_USER);
@@ -673,7 +673,7 @@ class VersioningTest extends \Test\TestCase {
$this->assertEquals('test file', $file->getContent(), 'File content has not changed');
}
- public function testRestoreMovedShare() {
+ public function testRestoreMovedShare(): void {
$this->markTestSkipped('Unreliable test');
$this->loginAsUser(self::TEST_VERSIONS_USER);
@@ -864,7 +864,7 @@ class VersioningTest extends \Test\TestCase {
/**
* Test whether versions are created when overwriting as owner
*/
- public function testStoreVersionAsOwner() {
+ public function testStoreVersionAsOwner(): void {
$this->loginAsUser(self::TEST_VERSIONS_USER);
$this->createAndCheckVersions(
@@ -876,7 +876,7 @@ class VersioningTest extends \Test\TestCase {
/**
* Test whether versions are created when overwriting as share recipient
*/
- public function testStoreVersionAsRecipient() {
+ public function testStoreVersionAsRecipient(): void {
$this->loginAsUser(self::TEST_VERSIONS_USER);
\OC\Files\Filesystem::mkdir('folder');
@@ -909,7 +909,7 @@ class VersioningTest extends \Test\TestCase {
* is logged in. File modification must still be able to find
* the owner and create versions.
*/
- public function testStoreVersionAsAnonymous() {
+ public function testStoreVersionAsAnonymous(): void {
$this->logout();
// note: public link upload does this,
diff --git a/apps/files_versions/tests/Versions/VersionManagerTest.php b/apps/files_versions/tests/Versions/VersionManagerTest.php
index d621d67a6de..a50781b899d 100644
--- a/apps/files_versions/tests/Versions/VersionManagerTest.php
+++ b/apps/files_versions/tests/Versions/VersionManagerTest.php
@@ -29,7 +29,7 @@ class VersionManagerTest extends TestCase {
->getMock();
}
- public function testGetBackendSingle() {
+ public function testGetBackendSingle(): void {
$manager = new VersionManager();
$backend = $this->getBackend();
$manager->registerBackend(IStorage::class, $backend);
@@ -37,7 +37,7 @@ class VersionManagerTest extends TestCase {
$this->assertEquals($backend, $manager->getBackendForStorage($this->getStorage(Local::class)));
}
- public function testGetBackendMoreSpecific() {
+ public function testGetBackendMoreSpecific(): void {
$manager = new VersionManager();
$backend1 = $this->getBackend();
$backend2 = $this->getBackend();
@@ -47,7 +47,7 @@ class VersionManagerTest extends TestCase {
$this->assertEquals($backend2, $manager->getBackendForStorage($this->getStorage(Local::class)));
}
- public function testGetBackendNoUse() {
+ public function testGetBackendNoUse(): void {
$manager = new VersionManager();
$backend1 = $this->getBackend();
$backend2 = $this->getBackend(false);
@@ -57,7 +57,7 @@ class VersionManagerTest extends TestCase {
$this->assertEquals($backend1, $manager->getBackendForStorage($this->getStorage(Local::class)));
}
- public function testGetBackendMultiple() {
+ public function testGetBackendMultiple(): void {
$manager = new VersionManager();
$backend1 = $this->getBackend();
$backend2 = $this->getBackend(false);
diff --git a/apps/oauth2/tests/Controller/LoginRedirectorControllerTest.php b/apps/oauth2/tests/Controller/LoginRedirectorControllerTest.php
index eb8e47a102f..30806854574 100644
--- a/apps/oauth2/tests/Controller/LoginRedirectorControllerTest.php
+++ b/apps/oauth2/tests/Controller/LoginRedirectorControllerTest.php
@@ -53,7 +53,7 @@ class LoginRedirectorControllerTest extends TestCase {
);
}
- public function testAuthorize() {
+ public function testAuthorize(): void {
$client = new Client();
$client->setClientIdentifier('MyClientIdentifier');
$this->clientMapper
@@ -80,7 +80,7 @@ class LoginRedirectorControllerTest extends TestCase {
$this->assertEquals($expected, $this->loginRedirectorController->authorize('MyClientId', 'MyState', 'code'));
}
- public function testAuthorizeWrongResponseType() {
+ public function testAuthorizeWrongResponseType(): void {
$client = new Client();
$client->setClientIdentifier('MyClientIdentifier');
$client->setRedirectUri('http://foo.bar');
@@ -98,7 +98,7 @@ class LoginRedirectorControllerTest extends TestCase {
$this->assertEquals($expected, $this->loginRedirectorController->authorize('MyClientId', 'MyState', 'wrongcode'));
}
- public function testClientNotFound() {
+ public function testClientNotFound(): void {
$clientNotFound = new ClientNotFoundException('could not find client test123', 0);
$this->clientMapper
->expects($this->once())
diff --git a/apps/oauth2/tests/Controller/OauthApiControllerTest.php b/apps/oauth2/tests/Controller/OauthApiControllerTest.php
index 803bdce16b1..fa8c90843e6 100644
--- a/apps/oauth2/tests/Controller/OauthApiControllerTest.php
+++ b/apps/oauth2/tests/Controller/OauthApiControllerTest.php
@@ -84,7 +84,7 @@ class OauthApiControllerTest extends TestCase {
);
}
- public function testGetTokenInvalidGrantType() {
+ public function testGetTokenInvalidGrantType(): void {
$expected = new JSONResponse([
'error' => 'invalid_grant',
], Http::STATUS_BAD_REQUEST);
@@ -93,7 +93,7 @@ class OauthApiControllerTest extends TestCase {
$this->assertEquals($expected, $this->oauthApiController->getToken('foo', null, null, null, null));
}
- public function testGetTokenInvalidCode() {
+ public function testGetTokenInvalidCode(): void {
$expected = new JSONResponse([
'error' => 'invalid_request',
], Http::STATUS_BAD_REQUEST);
@@ -106,7 +106,7 @@ class OauthApiControllerTest extends TestCase {
$this->assertEquals($expected, $this->oauthApiController->getToken('authorization_code', 'invalidcode', null, null, null));
}
- public function testGetTokenExpiredCode() {
+ public function testGetTokenExpiredCode(): void {
$codeCreatedAt = 100;
$expiredSince = 123;
@@ -131,7 +131,7 @@ class OauthApiControllerTest extends TestCase {
$this->assertEquals($expected, $this->oauthApiController->getToken('authorization_code', 'validcode', null, null, null));
}
- public function testGetTokenWithCodeForActiveToken() {
+ public function testGetTokenWithCodeForActiveToken(): void {
// if a token has already delivered oauth tokens,
// it should not be possible to get a new oauth token from a valid authorization code
$codeCreatedAt = 100;
@@ -158,7 +158,7 @@ class OauthApiControllerTest extends TestCase {
$this->assertEquals($expected, $this->oauthApiController->getToken('authorization_code', 'validcode', null, null, null));
}
- public function testGetTokenClientDoesNotExist() {
+ public function testGetTokenClientDoesNotExist(): void {
// In this test, the token's authorization code is valid and has not expired
// and we check what happens when the associated Oauth client does not exist
$codeCreatedAt = 100;
@@ -189,7 +189,7 @@ class OauthApiControllerTest extends TestCase {
$this->assertEquals($expected, $this->oauthApiController->getToken('authorization_code', 'validcode', null, null, null));
}
- public function testRefreshTokenInvalidRefreshToken() {
+ public function testRefreshTokenInvalidRefreshToken(): void {
$expected = new JSONResponse([
'error' => 'invalid_request',
], Http::STATUS_BAD_REQUEST);
@@ -202,7 +202,7 @@ class OauthApiControllerTest extends TestCase {
$this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'invalidrefresh', null, null));
}
- public function testRefreshTokenClientDoesNotExist() {
+ public function testRefreshTokenClientDoesNotExist(): void {
$expected = new JSONResponse([
'error' => 'invalid_request',
], Http::STATUS_BAD_REQUEST);
@@ -236,7 +236,7 @@ class OauthApiControllerTest extends TestCase {
* @param string $clientId
* @param string $clientSecret
*/
- public function testRefreshTokenInvalidClient($clientId, $clientSecret) {
+ public function testRefreshTokenInvalidClient($clientId, $clientSecret): void {
$expected = new JSONResponse([
'error' => 'invalid_client',
], Http::STATUS_BAD_REQUEST);
@@ -270,7 +270,7 @@ class OauthApiControllerTest extends TestCase {
$this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', $clientId, $clientSecret));
}
- public function testRefreshTokenInvalidAppToken() {
+ public function testRefreshTokenInvalidAppToken(): void {
$expected = new JSONResponse([
'error' => 'invalid_request',
], Http::STATUS_BAD_REQUEST);
@@ -313,7 +313,7 @@ class OauthApiControllerTest extends TestCase {
$this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', 'clientId', 'clientSecret'));
}
- public function testRefreshTokenValidAppToken() {
+ public function testRefreshTokenValidAppToken(): void {
$accessToken = new AccessToken();
$accessToken->setClientId(42);
$accessToken->setTokenId(1337);
@@ -409,7 +409,7 @@ class OauthApiControllerTest extends TestCase {
$this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', 'clientId', 'clientSecret'));
}
- public function testRefreshTokenValidAppTokenBasicAuth() {
+ public function testRefreshTokenValidAppTokenBasicAuth(): void {
$accessToken = new AccessToken();
$accessToken->setClientId(42);
$accessToken->setTokenId(1337);
@@ -508,7 +508,7 @@ class OauthApiControllerTest extends TestCase {
$this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', null, null));
}
- public function testRefreshTokenExpiredAppToken() {
+ public function testRefreshTokenExpiredAppToken(): void {
$accessToken = new AccessToken();
$accessToken->setClientId(42);
$accessToken->setTokenId(1337);
diff --git a/apps/oauth2/tests/Controller/SettingsControllerTest.php b/apps/oauth2/tests/Controller/SettingsControllerTest.php
index 1f93a272ee7..0ea23439b89 100644
--- a/apps/oauth2/tests/Controller/SettingsControllerTest.php
+++ b/apps/oauth2/tests/Controller/SettingsControllerTest.php
@@ -70,7 +70,7 @@ class SettingsControllerTest extends TestCase {
}
- public function testAddClient() {
+ public function testAddClient(): void {
$this->secureRandom
->expects($this->exactly(2))
->method('generate')
@@ -117,7 +117,7 @@ class SettingsControllerTest extends TestCase {
], $data);
}
- public function testDeleteClient() {
+ public function testDeleteClient(): void {
$userManager = \OC::$server->getUserManager();
// count other users in the db before adding our own
@@ -177,7 +177,7 @@ class SettingsControllerTest extends TestCase {
$user1->delete();
}
- public function testInvalidRedirectUri() {
+ public function testInvalidRedirectUri(): void {
$result = $this->settingsController->addClient('test', 'invalidurl');
$this->assertEquals(Http::STATUS_BAD_REQUEST, $result->getStatus());
diff --git a/apps/oauth2/tests/Db/AccessTokenMapperTest.php b/apps/oauth2/tests/Db/AccessTokenMapperTest.php
index a248c1e0d38..5bb069248f3 100644
--- a/apps/oauth2/tests/Db/AccessTokenMapperTest.php
+++ b/apps/oauth2/tests/Db/AccessTokenMapperTest.php
@@ -22,7 +22,7 @@ class AccessTokenMapperTest extends TestCase {
$this->accessTokenMapper = new AccessTokenMapper(\OC::$server->getDatabaseConnection(), \OC::$server->get(ITimeFactory::class));
}
- public function testGetByCode() {
+ public function testGetByCode(): void {
$this->accessTokenMapper->deleteByClientId(1234);
$token = new AccessToken();
$token->setClientId(1234);
@@ -38,7 +38,7 @@ class AccessTokenMapperTest extends TestCase {
}
- public function testDeleteByClientId() {
+ public function testDeleteByClientId(): void {
$this->expectException(\OCA\OAuth2\Exceptions\AccessTokenNotFoundException::class);
$this->accessTokenMapper->deleteByClientId(1234);
diff --git a/apps/oauth2/tests/Db/ClientMapperTest.php b/apps/oauth2/tests/Db/ClientMapperTest.php
index 3d8b25acbef..8c00c2e0a21 100644
--- a/apps/oauth2/tests/Db/ClientMapperTest.php
+++ b/apps/oauth2/tests/Db/ClientMapperTest.php
@@ -28,7 +28,7 @@ class ClientMapperTest extends TestCase {
parent::tearDown();
}
- public function testGetByIdentifier() {
+ public function testGetByIdentifier(): void {
$client = new Client();
$client->setClientIdentifier('MyAwesomeClientIdentifier');
$client->setName('Client Name');
@@ -39,13 +39,13 @@ class ClientMapperTest extends TestCase {
$this->assertEquals($client, $this->clientMapper->getByIdentifier('MyAwesomeClientIdentifier'));
}
- public function testGetByIdentifierNotExisting() {
+ public function testGetByIdentifierNotExisting(): void {
$this->expectException(\OCA\OAuth2\Exceptions\ClientNotFoundException::class);
$this->clientMapper->getByIdentifier('MyTotallyNotExistingClient');
}
- public function testGetByUid() {
+ public function testGetByUid(): void {
$client = new Client();
$client->setClientIdentifier('MyNewClient');
$client->setName('Client Name');
@@ -56,13 +56,13 @@ class ClientMapperTest extends TestCase {
$this->assertEquals($client, $this->clientMapper->getByUid($client->getId()));
}
- public function testGetByUidNotExisting() {
+ public function testGetByUidNotExisting(): void {
$this->expectException(\OCA\OAuth2\Exceptions\ClientNotFoundException::class);
$this->clientMapper->getByUid(1234);
}
- public function testGetClients() {
+ public function testGetClients(): void {
$this->assertSame('array', gettype($this->clientMapper->getClients()));
}
diff --git a/apps/oauth2/tests/Settings/AdminTest.php b/apps/oauth2/tests/Settings/AdminTest.php
index 9cbefb74671..ca9100669df 100644
--- a/apps/oauth2/tests/Settings/AdminTest.php
+++ b/apps/oauth2/tests/Settings/AdminTest.php
@@ -39,7 +39,7 @@ class AdminTest extends TestCase {
);
}
- public function testGetForm() {
+ public function testGetForm(): void {
$expected = new TemplateResponse(
'oauth2',
'admin',
@@ -49,11 +49,11 @@ class AdminTest extends TestCase {
$this->assertEquals($expected, $this->admin->getForm());
}
- public function testGetSection() {
+ public function testGetSection(): void {
$this->assertSame('security', $this->admin->getSection());
}
- public function testGetPriority() {
+ public function testGetPriority(): void {
$this->assertSame(100, $this->admin->getPriority());
}
}
diff --git a/apps/provisioning_api/tests/CapabilitiesTest.php b/apps/provisioning_api/tests/CapabilitiesTest.php
index 8b4215063b7..e3c14f37ed7 100644
--- a/apps/provisioning_api/tests/CapabilitiesTest.php
+++ b/apps/provisioning_api/tests/CapabilitiesTest.php
@@ -52,7 +52,7 @@ class CapabilitiesTest extends TestCase {
/**
* @dataProvider getCapabilitiesProvider
*/
- public function testGetCapabilities($federationAppEnabled, $federatedFileSharingAppEnabled, $lookupServerEnabled, $expectedFederatedScopeEnabled, $expectedPublishedScopeEnabled) {
+ public function testGetCapabilities($federationAppEnabled, $federatedFileSharingAppEnabled, $lookupServerEnabled, $expectedFederatedScopeEnabled, $expectedPublishedScopeEnabled): void {
$this->appManager->expects($this->any())
->method('isEnabledForUser')
->will($this->returnValueMap([
diff --git a/apps/provisioning_api/tests/Controller/AppConfigControllerTest.php b/apps/provisioning_api/tests/Controller/AppConfigControllerTest.php
index 23a1f2ee195..f878b6b73d0 100644
--- a/apps/provisioning_api/tests/Controller/AppConfigControllerTest.php
+++ b/apps/provisioning_api/tests/Controller/AppConfigControllerTest.php
@@ -83,7 +83,7 @@ class AppConfigControllerTest extends TestCase {
}
}
- public function testGetApps() {
+ public function testGetApps(): void {
$this->appConfig->expects($this->once())
->method('getApps')
->willReturn(['apps']);
@@ -108,7 +108,7 @@ class AppConfigControllerTest extends TestCase {
* @param \Exception|null $throws
* @param int $status
*/
- public function testGetKeys($app, $keys, $throws, $status) {
+ public function testGetKeys($app, $keys, $throws, $status): void {
$api = $this->getInstance(['verifyAppId']);
if ($throws instanceof \Exception) {
$api->expects($this->once())
@@ -155,7 +155,7 @@ class AppConfigControllerTest extends TestCase {
* @param \Exception|null $throws
* @param int $status
*/
- public function testGetValue($app, $key, $default, $return, $throws, $status) {
+ public function testGetValue($app, $key, $default, $return, $throws, $status): void {
$api = $this->getInstance(['verifyAppId']);
if ($throws instanceof \Exception) {
$api->expects($this->once())
@@ -207,7 +207,7 @@ class AppConfigControllerTest extends TestCase {
* @param \Exception|null $keyThrows
* @param int|\Throwable $status
*/
- public function testSetValue($app, $key, $value, $appThrows, $keyThrows, $status, int|\Throwable $type = IAppConfig::VALUE_MIXED) {
+ public function testSetValue($app, $key, $value, $appThrows, $keyThrows, $status, int|\Throwable $type = IAppConfig::VALUE_MIXED): void {
$adminUser = $this->createMock(IUser::class);
$adminUser->expects($this->once())
->method('getUid')
@@ -312,7 +312,7 @@ class AppConfigControllerTest extends TestCase {
* @param \Exception|null $keyThrows
* @param int $status
*/
- public function testDeleteValue($app, $key, $appThrows, $keyThrows, $status) {
+ public function testDeleteValue($app, $key, $appThrows, $keyThrows, $status): void {
$api = $this->getInstance(['verifyAppId', 'verifyConfigKey']);
if ($appThrows instanceof \Exception) {
$api->expects($this->once())
@@ -360,7 +360,7 @@ class AppConfigControllerTest extends TestCase {
}
}
- public function testVerifyAppId() {
+ public function testVerifyAppId(): void {
$api = $this->getInstance();
$this->invokePrivate($api, 'verifyAppId', ['activity']);
$this->addToAssertionCount(1);
@@ -379,7 +379,7 @@ class AppConfigControllerTest extends TestCase {
* @dataProvider dataVerifyAppIdThrows
* @param string $app
*/
- public function testVerifyAppIdThrows($app) {
+ public function testVerifyAppIdThrows($app): void {
$this->expectException(\InvalidArgumentException::class);
$api = $this->getInstance();
@@ -401,7 +401,7 @@ class AppConfigControllerTest extends TestCase {
* @param string $key
* @param string $value
*/
- public function testVerifyConfigKey($app, $key, $value) {
+ public function testVerifyConfigKey($app, $key, $value): void {
$api = $this->getInstance();
$this->invokePrivate($api, 'verifyConfigKey', [$app, $key, $value]);
$this->addToAssertionCount(1);
@@ -427,7 +427,7 @@ class AppConfigControllerTest extends TestCase {
* @param string $key
* @param string $value
*/
- public function testVerifyConfigKeyThrows($app, $key, $value) {
+ public function testVerifyConfigKeyThrows($app, $key, $value): void {
$this->expectException(\InvalidArgumentException::class);
$api = $this->getInstance();
diff --git a/apps/provisioning_api/tests/Controller/AppsControllerTest.php b/apps/provisioning_api/tests/Controller/AppsControllerTest.php
index b59433b365f..9c815a52178 100644
--- a/apps/provisioning_api/tests/Controller/AppsControllerTest.php
+++ b/apps/provisioning_api/tests/Controller/AppsControllerTest.php
@@ -49,21 +49,21 @@ class AppsControllerTest extends \OCA\Provisioning_API\Tests\TestCase {
$this->userSession->setUser(null);
}
- public function testGetAppInfo() {
+ public function testGetAppInfo(): void {
$result = $this->api->getAppInfo('provisioning_api');
$expected = $this->appManager->getAppInfo('provisioning_api');
$this->assertEquals($expected, $result->getData());
}
- public function testGetAppInfoOnBadAppID() {
+ public function testGetAppInfoOnBadAppID(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(998);
$this->api->getAppInfo('not_provisioning_api');
}
- public function testGetApps() {
+ public function testGetApps(): void {
$user = $this->generateUsers();
$this->groupManager->get('admin')->addUser($user);
$this->userSession->setUser($user);
@@ -74,13 +74,13 @@ class AppsControllerTest extends \OCA\Provisioning_API\Tests\TestCase {
$this->assertEquals(count((new \OC_App())->listAllApps()), count($data['apps']));
}
- public function testGetAppsEnabled() {
+ public function testGetAppsEnabled(): void {
$result = $this->api->getApps('enabled');
$data = $result->getData();
$this->assertEquals(count(\OC_App::getEnabledApps()), count($data['apps']));
}
- public function testGetAppsDisabled() {
+ public function testGetAppsDisabled(): void {
$result = $this->api->getApps('disabled');
$data = $result->getData();
$apps = (new \OC_App)->listAllApps();
@@ -93,7 +93,7 @@ class AppsControllerTest extends \OCA\Provisioning_API\Tests\TestCase {
}
- public function testGetAppsInvalidFilter() {
+ public function testGetAppsInvalidFilter(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(101);
diff --git a/apps/provisioning_api/tests/Controller/GroupsControllerTest.php b/apps/provisioning_api/tests/Controller/GroupsControllerTest.php
index 1b6a956ea52..751e92cc285 100644
--- a/apps/provisioning_api/tests/Controller/GroupsControllerTest.php
+++ b/apps/provisioning_api/tests/Controller/GroupsControllerTest.php
@@ -175,7 +175,7 @@ class GroupsControllerTest extends \Test\TestCase {
* @param int|null $limit
* @param int|null $offset
*/
- public function testGetGroups($search, $limit, $offset) {
+ public function testGetGroups($search, $limit, $offset): void {
$groups = [$this->createGroup('group1'), $this->createGroup('group2')];
$search = $search === null ? '' : $search;
@@ -197,7 +197,7 @@ class GroupsControllerTest extends \Test\TestCase {
* @param int|null $limit
* @param int|null $offset
*/
- public function testGetGroupsDetails($search, $limit, $offset) {
+ public function testGetGroupsDetails($search, $limit, $offset): void {
$groups = [$this->createGroup('group1'), $this->createGroup('group2')];
$search = $search === null ? '' : $search;
@@ -229,7 +229,7 @@ class GroupsControllerTest extends \Test\TestCase {
]], $result->getData());
}
- public function testGetGroupAsSubadmin() {
+ public function testGetGroupAsSubadmin(): void {
$group = $this->createGroup('group');
$this->asSubAdminOfGroup($group);
@@ -254,7 +254,7 @@ class GroupsControllerTest extends \Test\TestCase {
}
- public function testGetGroupAsIrrelevantSubadmin() {
+ public function testGetGroupAsIrrelevantSubadmin(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(403);
@@ -274,7 +274,7 @@ class GroupsControllerTest extends \Test\TestCase {
$this->api->getGroup('group');
}
- public function testGetGroupAsAdmin() {
+ public function testGetGroupAsAdmin(): void {
$group = $this->createGroup('group');
$this->asAdmin();
@@ -299,7 +299,7 @@ class GroupsControllerTest extends \Test\TestCase {
}
- public function testGetGroupNonExisting() {
+ public function testGetGroupNonExisting(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionMessage('The requested group could not be found');
$this->expectExceptionCode(404);
@@ -310,7 +310,7 @@ class GroupsControllerTest extends \Test\TestCase {
}
- public function testGetSubAdminsOfGroupsNotExists() {
+ public function testGetSubAdminsOfGroupsNotExists(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionMessage('Group does not exist');
$this->expectExceptionCode(101);
@@ -318,7 +318,7 @@ class GroupsControllerTest extends \Test\TestCase {
$this->api->getSubAdminsOfGroup('NonExistingGroup');
}
- public function testGetSubAdminsOfGroup() {
+ public function testGetSubAdminsOfGroup(): void {
$group = $this->createGroup('GroupWithSubAdmins');
$this->groupManager
->method('get')
@@ -338,7 +338,7 @@ class GroupsControllerTest extends \Test\TestCase {
$this->assertEquals(['SubAdmin1', 'SubAdmin2'], $result->getData());
}
- public function testGetSubAdminsOfGroupEmptyList() {
+ public function testGetSubAdminsOfGroupEmptyList(): void {
$group = $this->createGroup('GroupWithOutSubAdmins');
$this->groupManager
->method('get')
@@ -357,7 +357,7 @@ class GroupsControllerTest extends \Test\TestCase {
}
- public function testAddGroupEmptyGroup() {
+ public function testAddGroupEmptyGroup(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionMessage('Invalid group name');
$this->expectExceptionCode(101);
@@ -366,7 +366,7 @@ class GroupsControllerTest extends \Test\TestCase {
}
- public function testAddGroupExistingGroup() {
+ public function testAddGroupExistingGroup(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(102);
@@ -378,7 +378,7 @@ class GroupsControllerTest extends \Test\TestCase {
$this->api->addGroup('ExistingGroup');
}
- public function testAddGroup() {
+ public function testAddGroup(): void {
$this->groupManager
->method('groupExists')
->with('NewGroup')
@@ -394,7 +394,7 @@ class GroupsControllerTest extends \Test\TestCase {
$this->api->addGroup('NewGroup');
}
- public function testAddGroupWithSpecialChar() {
+ public function testAddGroupWithSpecialChar(): void {
$this->groupManager
->method('groupExists')
->with('Iñtërnâtiônàlizætiøn')
@@ -411,7 +411,7 @@ class GroupsControllerTest extends \Test\TestCase {
}
- public function testDeleteGroupNonExisting() {
+ public function testDeleteGroupNonExisting(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(101);
@@ -419,7 +419,7 @@ class GroupsControllerTest extends \Test\TestCase {
}
- public function testDeleteAdminGroup() {
+ public function testDeleteAdminGroup(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(102);
@@ -431,7 +431,7 @@ class GroupsControllerTest extends \Test\TestCase {
$this->api->deleteGroup('admin');
}
- public function testDeleteGroup() {
+ public function testDeleteGroup(): void {
$this->groupManager
->method('groupExists')
->with('ExistingGroup')
@@ -450,7 +450,7 @@ class GroupsControllerTest extends \Test\TestCase {
$this->api->deleteGroup('ExistingGroup');
}
- public function testDeleteGroupEncoding() {
+ public function testDeleteGroupEncoding(): void {
$this->groupManager
->method('groupExists')
->with('ExistingGroup A/B')
@@ -469,7 +469,7 @@ class GroupsControllerTest extends \Test\TestCase {
$this->api->deleteGroup(urlencode('ExistingGroup A/B'));
}
- public function testGetGroupUsersDetails() {
+ public function testGetGroupUsersDetails(): void {
$gid = 'ncg1';
$this->asAdmin();
@@ -514,7 +514,7 @@ class GroupsControllerTest extends \Test\TestCase {
$this->api->getGroupUsersDetails($gid);
}
- public function testGetGroupUsersDetailsEncoded() {
+ public function testGetGroupUsersDetailsEncoded(): void {
$gid = 'Department A/B C/D';
$this->asAdmin();
diff --git a/apps/provisioning_api/tests/Controller/UsersControllerTest.php b/apps/provisioning_api/tests/Controller/UsersControllerTest.php
index fb132bcb546..c64bd4405e9 100644
--- a/apps/provisioning_api/tests/Controller/UsersControllerTest.php
+++ b/apps/provisioning_api/tests/Controller/UsersControllerTest.php
@@ -122,7 +122,7 @@ class UsersControllerTest extends TestCase {
->getMock();
}
- public function testGetUsersAsAdmin() {
+ public function testGetUsersAsAdmin(): void {
$loggedInUser = $this->getMockBuilder(IUser::class)
->disableOriginalConstructor()
->getMock();
@@ -154,7 +154,7 @@ class UsersControllerTest extends TestCase {
$this->assertEquals($expected, $this->api->getUsers('MyCustomSearch')->getData());
}
- public function testGetUsersAsSubAdmin() {
+ public function testGetUsersAsSubAdmin(): void {
$loggedInUser = $this->getMockBuilder(IUser::class)
->disableOriginalConstructor()
->getMock();
@@ -215,7 +215,7 @@ class UsersControllerTest extends TestCase {
}
- public function testAddUserAlreadyExisting() {
+ public function testAddUserAlreadyExisting(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(102);
@@ -249,7 +249,7 @@ class UsersControllerTest extends TestCase {
}
- public function testAddUserNonExistingGroup() {
+ public function testAddUserNonExistingGroup(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionMessage('Group NonExistingGroup does not exist');
$this->expectExceptionCode(104);
@@ -285,7 +285,7 @@ class UsersControllerTest extends TestCase {
}
- public function testAddUserExistingGroupNonExistingGroup() {
+ public function testAddUserExistingGroupNonExistingGroup(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionMessage('Group NonExistingGroup does not exist');
$this->expectExceptionCode(104);
@@ -326,7 +326,7 @@ class UsersControllerTest extends TestCase {
$this->api->addUser('NewUser', 'pass', '', '', ['ExistingGroup', 'NonExistingGroup']);
}
- public function testAddUserSuccessful() {
+ public function testAddUserSuccessful(): void {
$this->userManager
->expects($this->once())
->method('userExists')
@@ -363,7 +363,7 @@ class UsersControllerTest extends TestCase {
));
}
- public function testAddUserSuccessfulWithDisplayName() {
+ public function testAddUserSuccessfulWithDisplayName(): void {
/**
* @var UserController
*/
@@ -429,7 +429,7 @@ class UsersControllerTest extends TestCase {
));
}
- public function testAddUserSuccessfulGenerateUserID() {
+ public function testAddUserSuccessfulGenerateUserID(): void {
$this->config
->expects($this->any())
->method('getAppValue')
@@ -481,7 +481,7 @@ class UsersControllerTest extends TestCase {
));
}
- public function testAddUserSuccessfulGeneratePassword() {
+ public function testAddUserSuccessfulGeneratePassword(): void {
$this->userManager
->expects($this->once())
->method('userExists')
@@ -526,7 +526,7 @@ class UsersControllerTest extends TestCase {
}
- public function testAddUserFailedToGenerateUserID() {
+ public function testAddUserFailedToGenerateUserID(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionMessage('Could not create non-existing user ID');
$this->expectExceptionCode(111);
@@ -569,7 +569,7 @@ class UsersControllerTest extends TestCase {
}
- public function testAddUserEmailRequired() {
+ public function testAddUserEmailRequired(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionMessage('Required email address was not provided');
$this->expectExceptionCode(110);
@@ -614,7 +614,7 @@ class UsersControllerTest extends TestCase {
));
}
- public function testAddUserExistingGroup() {
+ public function testAddUserExistingGroup(): void {
$this->userManager
->expects($this->once())
->method('userExists')
@@ -676,7 +676,7 @@ class UsersControllerTest extends TestCase {
}
- public function testAddUserUnsuccessful() {
+ public function testAddUserUnsuccessful(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionMessage('Bad request');
$this->expectExceptionCode(101);
@@ -723,7 +723,7 @@ class UsersControllerTest extends TestCase {
}
- public function testAddUserAsSubAdminNoGroup() {
+ public function testAddUserAsSubAdminNoGroup(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionMessage('No group specified (required for sub-admins)');
$this->expectExceptionCode(106);
@@ -756,7 +756,7 @@ class UsersControllerTest extends TestCase {
}
- public function testAddUserAsSubAdminValidGroupNotSubAdmin() {
+ public function testAddUserAsSubAdminValidGroupNotSubAdmin(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionMessage('Insufficient privileges for group ExistingGroup');
$this->expectExceptionCode(105);
@@ -804,7 +804,7 @@ class UsersControllerTest extends TestCase {
$this->api->addUser('NewUser', 'PasswordOfTheNewUser', '', '', ['ExistingGroup'])->getData();
}
- public function testAddUserAsSubAdminExistingGroups() {
+ public function testAddUserAsSubAdminExistingGroups(): void {
$this->userManager
->expects($this->once())
->method('userExists')
@@ -899,7 +899,7 @@ class UsersControllerTest extends TestCase {
}
- public function testGetUserTargetDoesNotExist() {
+ public function testGetUserTargetDoesNotExist(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionMessage('User does not exist');
$this->expectExceptionCode(404);
@@ -919,7 +919,7 @@ class UsersControllerTest extends TestCase {
$this->api->getUser('UserToGet');
}
- public function testGetUserDataAsAdmin() {
+ public function testGetUserDataAsAdmin(): void {
$group0 = $this->createMock(IGroup::class);
$group1 = $this->createMock(IGroup::class);
$group2 = $this->createMock(IGroup::class);
@@ -1072,7 +1072,7 @@ class UsersControllerTest extends TestCase {
$this->assertEquals($expected, $this->invokePrivate($this->api, 'getUserData', ['UID']));
}
- public function testGetUserDataAsSubAdminAndUserIsAccessible() {
+ public function testGetUserDataAsSubAdminAndUserIsAccessible(): void {
$loggedInUser = $this->getMockBuilder(IUser::class)
->disableOriginalConstructor()
->getMock();
@@ -1215,7 +1215,7 @@ class UsersControllerTest extends TestCase {
- public function testGetUserDataAsSubAdminAndUserIsNotAccessible() {
+ public function testGetUserDataAsSubAdminAndUserIsNotAccessible(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(998);
@@ -1258,7 +1258,7 @@ class UsersControllerTest extends TestCase {
$this->invokePrivate($this->api, 'getUser', ['UserToGet']);
}
- public function testGetUserDataAsSubAdminSelfLookup() {
+ public function testGetUserDataAsSubAdminSelfLookup(): void {
$loggedInUser = $this->getMockBuilder(IUser::class)
->disableOriginalConstructor()
->getMock();
@@ -1412,7 +1412,7 @@ class UsersControllerTest extends TestCase {
* @param int $status
* @param array $expected
*/
- public function testSearchByPhoneNumbers(string $location, array $search, int $status, ?array $searchUsers, ?array $userMatches, array $expected) {
+ public function testSearchByPhoneNumbers(string $location, array $search, int $status, ?array $searchUsers, ?array $userMatches, array $expected): void {
$knownTo = 'knownTo';
$user = $this->createMock(IUser::class);
$user->method('getUID')
@@ -1448,7 +1448,7 @@ class UsersControllerTest extends TestCase {
self::assertEquals($expected, $response->getData());
}
- public function testEditUserRegularUserSelfEditChangeDisplayName() {
+ public function testEditUserRegularUserSelfEditChangeDisplayName(): void {
$loggedInUser = $this->getMockBuilder(IUser::class)
->disableOriginalConstructor()
->getMock();
@@ -1485,7 +1485,7 @@ class UsersControllerTest extends TestCase {
$this->assertEquals([], $this->api->editUser('UserToEdit', 'display', 'NewDisplayName')->getData());
}
- public function testEditUserRegularUserSelfEditChangeEmailValid() {
+ public function testEditUserRegularUserSelfEditChangeEmailValid(): void {
$loggedInUser = $this->getMockBuilder(IUser::class)
->disableOriginalConstructor()
->getMock();
@@ -1680,7 +1680,7 @@ class UsersControllerTest extends TestCase {
$this->api->editUser('UserToEdit', 'additional_mail', 'demo1@nextcloud.com')->getData();
}
- public function testEditUserRegularUserSelfEditChangeEmailInvalid() {
+ public function testEditUserRegularUserSelfEditChangeEmailInvalid(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(102);
@@ -1735,7 +1735,7 @@ class UsersControllerTest extends TestCase {
/**
* @dataProvider selfEditChangePropertyProvider
*/
- public function testEditUserRegularUserSelfEditChangeProperty($propertyName, $oldValue, $newValue) {
+ public function testEditUserRegularUserSelfEditChangeProperty($propertyName, $oldValue, $newValue): void {
$loggedInUser = $this->getMockBuilder(IUser::class)
->disableOriginalConstructor()
->getMock();
@@ -1812,7 +1812,7 @@ class UsersControllerTest extends TestCase {
/**
* @dataProvider selfEditChangePropertyProvider
*/
- public function testEditUserRegularUserSelfEditChangePropertyScope($propertyName, $oldScope, $newScope) {
+ public function testEditUserRegularUserSelfEditChangePropertyScope($propertyName, $oldScope, $newScope): void {
$loggedInUser = $this->getMockBuilder(IUser::class)
->disableOriginalConstructor()
->getMock();
@@ -1868,7 +1868,7 @@ class UsersControllerTest extends TestCase {
$this->assertEquals([], $this->api->editUser('UserToEdit', $propertyName . 'Scope', $newScope)->getData());
}
- public function testEditUserRegularUserSelfEditChangePassword() {
+ public function testEditUserRegularUserSelfEditChangePassword(): void {
$loggedInUser = $this->getMockBuilder(IUser::class)
->disableOriginalConstructor()
->getMock();
@@ -1912,7 +1912,7 @@ class UsersControllerTest extends TestCase {
- public function testEditUserRegularUserSelfEditChangeQuota() {
+ public function testEditUserRegularUserSelfEditChangeQuota(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(103);
@@ -1949,7 +1949,7 @@ class UsersControllerTest extends TestCase {
$this->api->editUser('UserToEdit', 'quota', 'NewQuota');
}
- public function testEditUserAdminUserSelfEditChangeValidQuota() {
+ public function testEditUserAdminUserSelfEditChangeValidQuota(): void {
$this->config
->expects($this->once())
->method('getAppValue')
@@ -1998,7 +1998,7 @@ class UsersControllerTest extends TestCase {
- public function testEditUserAdminUserSelfEditChangeInvalidQuota() {
+ public function testEditUserAdminUserSelfEditChangeInvalidQuota(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionMessage('Invalid quota value: ABC');
$this->expectExceptionCode(102);
@@ -2037,7 +2037,7 @@ class UsersControllerTest extends TestCase {
$this->api->editUser('UserToEdit', 'quota', 'ABC');
}
- public function testEditUserAdminUserEditChangeValidQuota() {
+ public function testEditUserAdminUserEditChangeValidQuota(): void {
$this->config
->expects($this->once())
->method('getAppValue')
@@ -2091,7 +2091,7 @@ class UsersControllerTest extends TestCase {
$this->assertEquals([], $this->api->editUser('UserToEdit', 'quota', '3042824')->getData());
}
- public function testEditUserSelfEditChangeLanguage() {
+ public function testEditUserSelfEditChangeLanguage(): void {
$this->l10nFactory->expects($this->once())
->method('findAvailableLanguages')
->willReturn(['en', 'de', 'sv']);
@@ -2149,7 +2149,7 @@ class UsersControllerTest extends TestCase {
/**
* @dataProvider dataEditUserSelfEditChangeLanguageButForced
*/
- public function testEditUserSelfEditChangeLanguageButForced($forced) {
+ public function testEditUserSelfEditChangeLanguageButForced($forced): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->config->expects($this->any())
@@ -2195,7 +2195,7 @@ class UsersControllerTest extends TestCase {
$this->assertEquals([], $this->api->editUser('UserToEdit', 'language', 'de')->getData());
}
- public function testEditUserAdminEditChangeLanguage() {
+ public function testEditUserAdminEditChangeLanguage(): void {
$this->l10nFactory->expects($this->once())
->method('findAvailableLanguages')
->willReturn(['en', 'de', 'sv']);
@@ -2245,7 +2245,7 @@ class UsersControllerTest extends TestCase {
/**
* @dataProvider dataEditUserSelfEditChangeLanguageButForced
*/
- public function testEditUserAdminEditChangeLanguageInvalidLanguage() {
+ public function testEditUserAdminEditChangeLanguageInvalidLanguage(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
@@ -2294,7 +2294,7 @@ class UsersControllerTest extends TestCase {
$this->assertEquals([], $this->api->editUser('UserToEdit', 'language', 'ru')->getData());
}
- public function testEditUserSubadminUserAccessible() {
+ public function testEditUserSubadminUserAccessible(): void {
$this->config
->expects($this->once())
->method('getAppValue')
@@ -2349,7 +2349,7 @@ class UsersControllerTest extends TestCase {
}
- public function testEditUserSubadminUserInaccessible() {
+ public function testEditUserSubadminUserInaccessible(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(998);
@@ -2389,7 +2389,7 @@ class UsersControllerTest extends TestCase {
}
- public function testDeleteUserNotExistingUser() {
+ public function testDeleteUserNotExistingUser(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(998);
@@ -2412,7 +2412,7 @@ class UsersControllerTest extends TestCase {
}
- public function testDeleteUserSelf() {
+ public function testDeleteUserSelf(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(101);
@@ -2439,7 +2439,7 @@ class UsersControllerTest extends TestCase {
$this->api->deleteUser('UserToDelete');
}
- public function testDeleteSuccessfulUserAsAdmin() {
+ public function testDeleteSuccessfulUserAsAdmin(): void {
$loggedInUser = $this->getMockBuilder(IUser::class)->disableOriginalConstructor()->getMock();
$loggedInUser
->expects($this->any())
@@ -2473,7 +2473,7 @@ class UsersControllerTest extends TestCase {
}
- public function testDeleteUnsuccessfulUserAsAdmin() {
+ public function testDeleteUnsuccessfulUserAsAdmin(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(101);
@@ -2509,7 +2509,7 @@ class UsersControllerTest extends TestCase {
$this->api->deleteUser('UserToDelete');
}
- public function testDeleteSuccessfulUserAsSubadmin() {
+ public function testDeleteSuccessfulUserAsSubadmin(): void {
$loggedInUser = $this->getMockBuilder(IUser::class)->disableOriginalConstructor()->getMock();
$loggedInUser
->expects($this->any())
@@ -2554,7 +2554,7 @@ class UsersControllerTest extends TestCase {
}
- public function testDeleteUnsuccessfulUserAsSubadmin() {
+ public function testDeleteUnsuccessfulUserAsSubadmin(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(101);
@@ -2602,7 +2602,7 @@ class UsersControllerTest extends TestCase {
}
- public function testDeleteUserAsSubAdminAndUserIsNotAccessible() {
+ public function testDeleteUserAsSubAdminAndUserIsNotAccessible(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(998);
@@ -2646,7 +2646,7 @@ class UsersControllerTest extends TestCase {
}
- public function testGetUsersGroupsTargetUserNotExisting() {
+ public function testGetUsersGroupsTargetUserNotExisting(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(998);
@@ -2659,7 +2659,7 @@ class UsersControllerTest extends TestCase {
$this->api->getUsersGroups('UserToLookup');
}
- public function testGetUsersGroupsSelfTargetted() {
+ public function testGetUsersGroupsSelfTargetted(): void {
$loggedInUser = $this->getMockBuilder(IUser::class)->disableOriginalConstructor()->getMock();
$loggedInUser
->expects($this->exactly(3))
@@ -2688,7 +2688,7 @@ class UsersControllerTest extends TestCase {
$this->assertEquals(['groups' => ['DummyValue']], $this->api->getUsersGroups('UserToLookup')->getData());
}
- public function testGetUsersGroupsForAdminUser() {
+ public function testGetUsersGroupsForAdminUser(): void {
$loggedInUser = $this->getMockBuilder(IUser::class)->disableOriginalConstructor()->getMock();
$loggedInUser
->expects($this->exactly(3))
@@ -2722,7 +2722,7 @@ class UsersControllerTest extends TestCase {
$this->assertEquals(['groups' => ['DummyValue']], $this->api->getUsersGroups('UserToLookup')->getData());
}
- public function testGetUsersGroupsForSubAdminUserAndUserIsAccessible() {
+ public function testGetUsersGroupsForSubAdminUserAndUserIsAccessible(): void {
$loggedInUser = $this->getMockBuilder(IUser::class)->disableOriginalConstructor()->getMock();
$loggedInUser
->expects($this->exactly(3))
@@ -2783,7 +2783,7 @@ class UsersControllerTest extends TestCase {
}
- public function testGetUsersGroupsForSubAdminUserAndUserIsInaccessible() {
+ public function testGetUsersGroupsForSubAdminUserAndUserIsInaccessible(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(998);
@@ -2832,7 +2832,7 @@ class UsersControllerTest extends TestCase {
}
- public function testAddToGroupWithTargetGroupNotExisting() {
+ public function testAddToGroupWithTargetGroupNotExisting(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(102);
@@ -2845,7 +2845,7 @@ class UsersControllerTest extends TestCase {
}
- public function testAddToGroupWithNoGroupSpecified() {
+ public function testAddToGroupWithNoGroupSpecified(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(101);
@@ -2853,7 +2853,7 @@ class UsersControllerTest extends TestCase {
}
- public function testAddToGroupWithTargetUserNotExisting() {
+ public function testAddToGroupWithTargetUserNotExisting(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(103);
@@ -2867,7 +2867,7 @@ class UsersControllerTest extends TestCase {
}
- public function testAddToGroupNoSubadmin() {
+ public function testAddToGroupNoSubadmin(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(104);
@@ -2914,7 +2914,7 @@ class UsersControllerTest extends TestCase {
$this->api->addToGroup('TargetUser', 'GroupToAddTo');
}
- public function testAddToGroupSuccessAsSubadmin() {
+ public function testAddToGroupSuccessAsSubadmin(): void {
$targetUser = $this->createMock(IUser::class);
$loggedInUser = $this->createMock(IUser::class);
$loggedInUser->expects($this->exactly(2))
@@ -2958,7 +2958,7 @@ class UsersControllerTest extends TestCase {
$this->assertEquals(new DataResponse(), $this->api->addToGroup('TargetUser', 'GroupToAddTo'));
}
- public function testAddToGroupSuccessAsAdmin() {
+ public function testAddToGroupSuccessAsAdmin(): void {
$targetUser = $this->createMock(IUser::class);
$loggedInUser = $this->createMock(IUser::class);
$loggedInUser->expects($this->exactly(2))
@@ -3001,7 +3001,7 @@ class UsersControllerTest extends TestCase {
}
- public function testRemoveFromGroupWithNoTargetGroup() {
+ public function testRemoveFromGroupWithNoTargetGroup(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(101);
@@ -3015,7 +3015,7 @@ class UsersControllerTest extends TestCase {
}
- public function testRemoveFromGroupWithEmptyTargetGroup() {
+ public function testRemoveFromGroupWithEmptyTargetGroup(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(101);
@@ -3029,7 +3029,7 @@ class UsersControllerTest extends TestCase {
}
- public function testRemoveFromGroupWithNotExistingTargetGroup() {
+ public function testRemoveFromGroupWithNotExistingTargetGroup(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(102);
@@ -3048,7 +3048,7 @@ class UsersControllerTest extends TestCase {
}
- public function testRemoveFromGroupWithNotExistingTargetUser() {
+ public function testRemoveFromGroupWithNotExistingTargetUser(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(103);
@@ -3073,7 +3073,7 @@ class UsersControllerTest extends TestCase {
}
- public function testRemoveFromGroupWithoutPermission() {
+ public function testRemoveFromGroupWithoutPermission(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(104);
@@ -3114,7 +3114,7 @@ class UsersControllerTest extends TestCase {
}
- public function testRemoveFromGroupAsAdminFromAdmin() {
+ public function testRemoveFromGroupAsAdminFromAdmin(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionMessage('Cannot remove yourself from the admin group');
$this->expectExceptionCode(105);
@@ -3164,7 +3164,7 @@ class UsersControllerTest extends TestCase {
}
- public function testRemoveFromGroupAsSubAdminFromSubAdmin() {
+ public function testRemoveFromGroupAsSubAdminFromSubAdmin(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionMessage('Cannot remove yourself from this group as you are a sub-admin');
$this->expectExceptionCode(105);
@@ -3219,7 +3219,7 @@ class UsersControllerTest extends TestCase {
}
- public function testRemoveFromGroupAsSubAdminFromLastSubAdminGroup() {
+ public function testRemoveFromGroupAsSubAdminFromLastSubAdminGroup(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionMessage('Not viable to remove user from the last group you are sub-admin of');
$this->expectExceptionCode(105);
@@ -3280,7 +3280,7 @@ class UsersControllerTest extends TestCase {
$this->api->removeFromGroup('AnotherUser', 'subadmin');
}
- public function testRemoveFromGroupSuccessful() {
+ public function testRemoveFromGroupSuccessful(): void {
$loggedInUser = $this->getMockBuilder(IUser::class)->disableOriginalConstructor()->getMock();
$loggedInUser
->expects($this->any())
@@ -3322,7 +3322,7 @@ class UsersControllerTest extends TestCase {
}
- public function testAddSubAdminWithNotExistingTargetUser() {
+ public function testAddSubAdminWithNotExistingTargetUser(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionMessage('User does not exist');
$this->expectExceptionCode(101);
@@ -3337,7 +3337,7 @@ class UsersControllerTest extends TestCase {
}
- public function testAddSubAdminWithNotExistingTargetGroup() {
+ public function testAddSubAdminWithNotExistingTargetGroup(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionMessage('Group does not exist');
$this->expectExceptionCode(102);
@@ -3359,7 +3359,7 @@ class UsersControllerTest extends TestCase {
}
- public function testAddSubAdminToAdminGroup() {
+ public function testAddSubAdminToAdminGroup(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionMessage('Cannot create sub-admins for admin group');
$this->expectExceptionCode(103);
@@ -3384,7 +3384,7 @@ class UsersControllerTest extends TestCase {
$this->api->addSubAdmin('ExistingUser', 'ADmiN');
}
- public function testAddSubAdminTwice() {
+ public function testAddSubAdminTwice(): void {
$targetUser = $this->getMockBuilder(IUser::class)->disableOriginalConstructor()->getMock();
$targetGroup = $this->getMockBuilder(\OCP\IGroup::class)->disableOriginalConstructor()->getMock();
$this->userManager
@@ -3412,7 +3412,7 @@ class UsersControllerTest extends TestCase {
$this->assertEquals([], $this->api->addSubAdmin('ExistingUser', 'TargetGroup')->getData());
}
- public function testAddSubAdminSuccessful() {
+ public function testAddSubAdminSuccessful(): void {
$targetUser = $this->getMockBuilder(IUser::class)->disableOriginalConstructor()->getMock();
$targetGroup = $this->getMockBuilder(\OCP\IGroup::class)->disableOriginalConstructor()->getMock();
$this->userManager
@@ -3445,7 +3445,7 @@ class UsersControllerTest extends TestCase {
}
- public function testRemoveSubAdminNotExistingTargetUser() {
+ public function testRemoveSubAdminNotExistingTargetUser(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionMessage('User does not exist');
$this->expectExceptionCode(101);
@@ -3460,7 +3460,7 @@ class UsersControllerTest extends TestCase {
}
- public function testRemoveSubAdminNotExistingTargetGroup() {
+ public function testRemoveSubAdminNotExistingTargetGroup(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionMessage('Group does not exist');
$this->expectExceptionCode(101);
@@ -3482,7 +3482,7 @@ class UsersControllerTest extends TestCase {
- public function testRemoveSubAdminFromNotASubadmin() {
+ public function testRemoveSubAdminFromNotASubadmin(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionMessage('User is not a sub-admin of this group');
$this->expectExceptionCode(102);
@@ -3514,7 +3514,7 @@ class UsersControllerTest extends TestCase {
$this->api->removeSubAdmin('ExistingUser', 'GroupToDeleteFrom');
}
- public function testRemoveSubAdminSuccessful() {
+ public function testRemoveSubAdminSuccessful(): void {
$targetUser = $this->getMockBuilder(IUser::class)->disableOriginalConstructor()->getMock();
$targetGroup = $this->getMockBuilder(\OCP\IGroup::class)->disableOriginalConstructor()->getMock();
$this->userManager
@@ -3547,7 +3547,7 @@ class UsersControllerTest extends TestCase {
}
- public function testGetUserSubAdminGroupsNotExistingTargetUser() {
+ public function testGetUserSubAdminGroupsNotExistingTargetUser(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionMessage('User does not exist');
$this->expectExceptionCode(404);
@@ -3561,7 +3561,7 @@ class UsersControllerTest extends TestCase {
$this->api->getUserSubAdminGroups('RequestedUser');
}
- public function testGetUserSubAdminGroupsWithGroups() {
+ public function testGetUserSubAdminGroupsWithGroups(): void {
$targetUser = $this->getMockBuilder(IUser::class)->disableOriginalConstructor()->getMock();
$targetGroup = $this->getMockBuilder(\OCP\IGroup::class)->disableOriginalConstructor()->getMock();
$targetGroup
@@ -3588,7 +3588,7 @@ class UsersControllerTest extends TestCase {
$this->assertEquals(['TargetGroup'], $this->api->getUserSubAdminGroups('RequestedUser')->getData());
}
- public function testEnableUser() {
+ public function testEnableUser(): void {
$targetUser = $this->getMockBuilder(IUser::class)->disableOriginalConstructor()->getMock();
$targetUser->expects($this->once())
->method('setEnabled')
@@ -3615,7 +3615,7 @@ class UsersControllerTest extends TestCase {
$this->assertEquals([], $this->api->enableUser('RequestedUser')->getData());
}
- public function testDisableUser() {
+ public function testDisableUser(): void {
$targetUser = $this->getMockBuilder(IUser::class)->disableOriginalConstructor()->getMock();
$targetUser->expects($this->once())
->method('setEnabled')
@@ -3642,7 +3642,7 @@ class UsersControllerTest extends TestCase {
$this->assertEquals([], $this->api->disableUser('RequestedUser')->getData());
}
- public function testGetCurrentUserLoggedIn() {
+ public function testGetCurrentUserLoggedIn(): void {
$user = $this->createMock(IUser::class);
$user->expects($this->once())->method('getUID')->willReturn('UID');
@@ -3717,7 +3717,7 @@ class UsersControllerTest extends TestCase {
}
- public function testGetCurrentUserNotLoggedIn() {
+ public function testGetCurrentUserNotLoggedIn(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
@@ -3727,7 +3727,7 @@ class UsersControllerTest extends TestCase {
$this->api->getCurrentUser();
}
- public function testGetUser() {
+ public function testGetUser(): void {
$loggedInUser = $this->createMock(IUser::class);
$loggedInUser
->method('getUID')
@@ -3792,7 +3792,7 @@ class UsersControllerTest extends TestCase {
}
- public function testResendWelcomeMessageWithNotExistingTargetUser() {
+ public function testResendWelcomeMessageWithNotExistingTargetUser(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(998);
@@ -3806,7 +3806,7 @@ class UsersControllerTest extends TestCase {
}
- public function testResendWelcomeMessageAsSubAdminAndUserIsNotAccessible() {
+ public function testResendWelcomeMessageAsSubAdminAndUserIsNotAccessible(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionCode(998);
@@ -3851,7 +3851,7 @@ class UsersControllerTest extends TestCase {
}
- public function testResendWelcomeMessageNoEmail() {
+ public function testResendWelcomeMessageNoEmail(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionMessage('Email address not available');
$this->expectExceptionCode(101);
@@ -3896,7 +3896,7 @@ class UsersControllerTest extends TestCase {
}
- public function testResendWelcomeMessageNullEmail() {
+ public function testResendWelcomeMessageNullEmail(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionMessage('Email address not available');
$this->expectExceptionCode(101);
@@ -3940,7 +3940,7 @@ class UsersControllerTest extends TestCase {
$this->api->resendWelcomeMessage('UserToGet');
}
- public function testResendWelcomeMessageSuccess() {
+ public function testResendWelcomeMessageSuccess(): void {
$loggedInUser = $this->getMockBuilder(IUser::class)
->disableOriginalConstructor()
->getMock();
@@ -3991,7 +3991,7 @@ class UsersControllerTest extends TestCase {
$this->api->resendWelcomeMessage('UserToGet');
}
- public function testResendWelcomeMessageSuccessWithFallbackLanguage() {
+ public function testResendWelcomeMessageSuccessWithFallbackLanguage(): void {
$loggedInUser = $this->getMockBuilder(IUser::class)
->disableOriginalConstructor()
->getMock();
@@ -4043,7 +4043,7 @@ class UsersControllerTest extends TestCase {
}
- public function testResendWelcomeMessageFailed() {
+ public function testResendWelcomeMessageFailed(): void {
$this->expectException(\OCP\AppFramework\OCS\OCSException::class);
$this->expectExceptionMessage('Sending email failed');
$this->expectExceptionCode(102);
@@ -4155,7 +4155,7 @@ class UsersControllerTest extends TestCase {
* @param string $userBackend
* @param array $expected
*/
- public function testGetEditableFields(bool $allowedToChangeDisplayName, string $userBackend, array $expected) {
+ public function testGetEditableFields(bool $allowedToChangeDisplayName, string $userBackend, array $expected): void {
$this->config
->method('getSystemValue')
->with(
diff --git a/apps/provisioning_api/tests/Middleware/ProvisioningApiMiddlewareTest.php b/apps/provisioning_api/tests/Middleware/ProvisioningApiMiddlewareTest.php
index df3ae0bd358..d097febb04f 100644
--- a/apps/provisioning_api/tests/Middleware/ProvisioningApiMiddlewareTest.php
+++ b/apps/provisioning_api/tests/Middleware/ProvisioningApiMiddlewareTest.php
@@ -51,7 +51,7 @@ class ProvisioningApiMiddlewareTest extends TestCase {
* @param bool $isSubAdmin
* @param bool $shouldThrowException
*/
- public function testBeforeController($subadminRequired, $isAdmin, $isSubAdmin, $hasSettingAuthorizationAnnotation, $shouldThrowException) {
+ public function testBeforeController($subadminRequired, $isAdmin, $isSubAdmin, $hasSettingAuthorizationAnnotation, $shouldThrowException): void {
$middleware = new ProvisioningApiMiddleware(
$this->reflector,
$isAdmin,
@@ -93,7 +93,7 @@ class ProvisioningApiMiddlewareTest extends TestCase {
* @param \Exception $e
* @param bool $forwared
*/
- public function testAfterException(\Exception $exception, $forwared) {
+ public function testAfterException(\Exception $exception, $forwared): void {
$middleware = new ProvisioningApiMiddleware(
$this->reflector,
false,
diff --git a/apps/settings/l10n/ar.js b/apps/settings/l10n/ar.js
index 824fda79935..af16dd8d311 100644
--- a/apps/settings/l10n/ar.js
+++ b/apps/settings/l10n/ar.js
@@ -881,7 +881,6 @@ OC.L10N.register(
"SMTP Username" : "اسم مستخدم الـ SMTP",
"To allow this check to run you have to make sure that your webserver can connect to itself. Therefor it must be able to resolve and connect to at least one its `trusted_domains` or the `overwrite.cli.url`." : "للسماح بتشغيل هذا الفحص، عليك التأكد من أن خادوم الويب عندك يمكنه الاتصال بنفسه. ولذلك، يجب أن يكون قادراً على حل المشكلة والاتصال بنطاق واحد على الأقل من \"النطاقات_الموثوقة\" أو 'overwrite.cli.url'.",
"Could not check for JavaScript support via any of your `trusted_domains` nor `overwrite.cli.url`. This may be the result of a server-side DNS mismatch or outbound firewall rule. Please check manually if your webserver serves `.mjs` files using the JavaScript MIME type." : "تعذر التحقُّق من دعم JavaScript عبر أيٍّ من \"النطاقات_الموثوقة\" أو \"overwrite.cli.url\". قد يكون هذا نتيجة عدم تطابق DNS من جانب الخادوم أو بسبب إحدى سياسات إدارة الحركة الصادرة في جدار الحماية. يرجى التحقق يدويًا مما إذا كان خادوم الويب عندك يقدم ملفات `.mjs` باستخدام نوع JavaScript MIME.",
- "Active accounts" : "حسابات نشطة",
- "None of your currently installed apps provide custom Text processing functionality." : "لا أحد من تطبيقاتك المثبتة حاليّاً يوفر وظيفة مخصصة لمعالجة النصوص."
+ "Active accounts" : "حسابات نشطة"
},
"nplurals=6; plural=n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 && n%100<=99 ? 4 : 5;");
diff --git a/apps/settings/l10n/ar.json b/apps/settings/l10n/ar.json
index a7036aadf27..1028c3aec17 100644
--- a/apps/settings/l10n/ar.json
+++ b/apps/settings/l10n/ar.json
@@ -879,7 +879,6 @@
"SMTP Username" : "اسم مستخدم الـ SMTP",
"To allow this check to run you have to make sure that your webserver can connect to itself. Therefor it must be able to resolve and connect to at least one its `trusted_domains` or the `overwrite.cli.url`." : "للسماح بتشغيل هذا الفحص، عليك التأكد من أن خادوم الويب عندك يمكنه الاتصال بنفسه. ولذلك، يجب أن يكون قادراً على حل المشكلة والاتصال بنطاق واحد على الأقل من \"النطاقات_الموثوقة\" أو 'overwrite.cli.url'.",
"Could not check for JavaScript support via any of your `trusted_domains` nor `overwrite.cli.url`. This may be the result of a server-side DNS mismatch or outbound firewall rule. Please check manually if your webserver serves `.mjs` files using the JavaScript MIME type." : "تعذر التحقُّق من دعم JavaScript عبر أيٍّ من \"النطاقات_الموثوقة\" أو \"overwrite.cli.url\". قد يكون هذا نتيجة عدم تطابق DNS من جانب الخادوم أو بسبب إحدى سياسات إدارة الحركة الصادرة في جدار الحماية. يرجى التحقق يدويًا مما إذا كان خادوم الويب عندك يقدم ملفات `.mjs` باستخدام نوع JavaScript MIME.",
- "Active accounts" : "حسابات نشطة",
- "None of your currently installed apps provide custom Text processing functionality." : "لا أحد من تطبيقاتك المثبتة حاليّاً يوفر وظيفة مخصصة لمعالجة النصوص."
+ "Active accounts" : "حسابات نشطة"
},"pluralForm" :"nplurals=6; plural=n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 && n%100<=99 ? 4 : 5;"
} \ No newline at end of file
diff --git a/apps/settings/l10n/cs.js b/apps/settings/l10n/cs.js
index 9ce82396bec..f3433d18ab4 100644
--- a/apps/settings/l10n/cs.js
+++ b/apps/settings/l10n/cs.js
@@ -133,7 +133,7 @@ OC.L10N.register(
"Brute-force Throttle" : "Přiškrcování útoků hrubou silou",
"Your remote address could not be determined." : "Nepodařilo se zjistit vaši vzdálenou adresu.",
"Your remote address was identified as \"%s\" and is brute-force throttled at the moment slowing down the performance of various requests. If the remote address is not your address this can be an indication that a proxy is not configured correctly." : "Vaše vzdálená adresa byla identifikována jako „%s“ a rychlost vyřizování požadavků z ní je v tuto chvíli omezována kvůli zamezení přetěžování útokem hádání hesel (bruteforce). Pokud vzdálená adresa není vaše, může se jednat o indikaci, že není správně nastavena proxy.",
- "Your remote address \"%s\" is not brute-force throttled." : "Vaše vzdálená adresa „%s“ není omezována co se útoků hrubou silou týče.",
+ "Your remote address \"%s\" is not brute-force throttled." : "Vaše vzdálená adresa „%s“ není omezena z důvodu ochrany proti útokům hrubou silou.",
"Old administration imported certificates" : "Staré správou naimportované certifikáty",
"A background job is pending that checks for administration imported SSL certificates. Please check back later." : "Úloha na pozadí čeká na kontrolu správou naimportovaných SSL certifikátů. Zkuste to prosím později.",
"There are some administration imported SSL certificates present, that are not used anymore with Nextcloud 21. They can be imported on the command line via \"occ security:certificates:import\" command. Their paths inside the data directory are shown below." : "Nacházejí se zde některé SSL certifikáty, naimportované správou, které se už s Nextcloud 21 nepoužívají. Lze je naimportovat v příkazovém řádku pomocí příkazu „occ security:certificates:import“. Popisy jejich umístění v adresáři s daty jsou uvedeny níže.",
@@ -419,7 +419,7 @@ OC.L10N.register(
"Could not copy login name. Please copy it manually." : "Přihlašovací jméno se nepodařilo zkopírovat. Zkopírujte ho ručně.",
"For the server to work properly, it's important to configure background jobs correctly. Cron is the recommended setting. Please see the documentation for more information." : "Pro správnou funkci serveru je důležité správně nastavit úlohy spouštěné na pozadí. Doporučenou metodou je použití systémového plánovače (cron). Další informace naleznete v dokumentaci.",
"Last job execution ran {time}. Something seems wrong." : "Minulé vykonání úlohy bylo {time}. Zdá se, že něco není v pořádku.",
- "Last job ran {relativeTime}." : "Úloha minule běžela {relativeTime}.",
+ "Last job ran {relativeTime}." : "Poslední úloha proběhla {relativeTime}.",
"Background job did not run yet!" : "Úloha na pozadí ještě nebyla spuštěná!",
"AJAX" : "AJAX",
"Webcron" : "Webcron",
diff --git a/apps/settings/l10n/cs.json b/apps/settings/l10n/cs.json
index d9fb51f4a38..a12b8028438 100644
--- a/apps/settings/l10n/cs.json
+++ b/apps/settings/l10n/cs.json
@@ -131,7 +131,7 @@
"Brute-force Throttle" : "Přiškrcování útoků hrubou silou",
"Your remote address could not be determined." : "Nepodařilo se zjistit vaši vzdálenou adresu.",
"Your remote address was identified as \"%s\" and is brute-force throttled at the moment slowing down the performance of various requests. If the remote address is not your address this can be an indication that a proxy is not configured correctly." : "Vaše vzdálená adresa byla identifikována jako „%s“ a rychlost vyřizování požadavků z ní je v tuto chvíli omezována kvůli zamezení přetěžování útokem hádání hesel (bruteforce). Pokud vzdálená adresa není vaše, může se jednat o indikaci, že není správně nastavena proxy.",
- "Your remote address \"%s\" is not brute-force throttled." : "Vaše vzdálená adresa „%s“ není omezována co se útoků hrubou silou týče.",
+ "Your remote address \"%s\" is not brute-force throttled." : "Vaše vzdálená adresa „%s“ není omezena z důvodu ochrany proti útokům hrubou silou.",
"Old administration imported certificates" : "Staré správou naimportované certifikáty",
"A background job is pending that checks for administration imported SSL certificates. Please check back later." : "Úloha na pozadí čeká na kontrolu správou naimportovaných SSL certifikátů. Zkuste to prosím později.",
"There are some administration imported SSL certificates present, that are not used anymore with Nextcloud 21. They can be imported on the command line via \"occ security:certificates:import\" command. Their paths inside the data directory are shown below." : "Nacházejí se zde některé SSL certifikáty, naimportované správou, které se už s Nextcloud 21 nepoužívají. Lze je naimportovat v příkazovém řádku pomocí příkazu „occ security:certificates:import“. Popisy jejich umístění v adresáři s daty jsou uvedeny níže.",
@@ -417,7 +417,7 @@
"Could not copy login name. Please copy it manually." : "Přihlašovací jméno se nepodařilo zkopírovat. Zkopírujte ho ručně.",
"For the server to work properly, it's important to configure background jobs correctly. Cron is the recommended setting. Please see the documentation for more information." : "Pro správnou funkci serveru je důležité správně nastavit úlohy spouštěné na pozadí. Doporučenou metodou je použití systémového plánovače (cron). Další informace naleznete v dokumentaci.",
"Last job execution ran {time}. Something seems wrong." : "Minulé vykonání úlohy bylo {time}. Zdá se, že něco není v pořádku.",
- "Last job ran {relativeTime}." : "Úloha minule běžela {relativeTime}.",
+ "Last job ran {relativeTime}." : "Poslední úloha proběhla {relativeTime}.",
"Background job did not run yet!" : "Úloha na pozadí ještě nebyla spuštěná!",
"AJAX" : "AJAX",
"Webcron" : "Webcron",
diff --git a/apps/settings/l10n/de.js b/apps/settings/l10n/de.js
index 87364a2e1e3..87eef7d9297 100644
--- a/apps/settings/l10n/de.js
+++ b/apps/settings/l10n/de.js
@@ -881,7 +881,6 @@ OC.L10N.register(
"SMTP Username" : "SMTP-Benutzername",
"To allow this check to run you have to make sure that your webserver can connect to itself. Therefor it must be able to resolve and connect to at least one its `trusted_domains` or the `overwrite.cli.url`." : "Um diese Prüfung auszuführen, musst du sicherstellen, dass dein Webserver eine Verbindung zu sich selbst herstellen kann. Dafür muss dieser in der Lage sein, sich mit mindestens einer seiner \"trusted_domains\" oder der \"overwrite.cli.url\" zu verbinden und diese aufzulösen.",
"Could not check for JavaScript support via any of your `trusted_domains` nor `overwrite.cli.url`. This may be the result of a server-side DNS mismatch or outbound firewall rule. Please check manually if your webserver serves `.mjs` files using the JavaScript MIME type." : "Es konnte weder über Ihre `trusted_domains` noch über `overwrite.cli.url` nach JavaScript-Unterstützung gesucht werden. Dies kann auf eine serverseitige DNS-Nichtübereinstimmung oder eine ausgehende Firewall-Regel zurückzuführen sein. Bitte überprüfe manuell, ob dein Webserver `.mjs`-Dateien mit dem JavaScript-MIME-Typ bereitstellt.",
- "Active accounts" : "Aktive Konten",
- "None of your currently installed apps provide custom Text processing functionality." : "Keine deiner aktuell installierten Apps bietet benutzerdefinierte Textverarbeitungsfunktionen."
+ "Active accounts" : "Aktive Konten"
},
"nplurals=2; plural=(n != 1);");
diff --git a/apps/settings/l10n/de.json b/apps/settings/l10n/de.json
index 978f82d6282..df0a11efcf3 100644
--- a/apps/settings/l10n/de.json
+++ b/apps/settings/l10n/de.json
@@ -879,7 +879,6 @@
"SMTP Username" : "SMTP-Benutzername",
"To allow this check to run you have to make sure that your webserver can connect to itself. Therefor it must be able to resolve and connect to at least one its `trusted_domains` or the `overwrite.cli.url`." : "Um diese Prüfung auszuführen, musst du sicherstellen, dass dein Webserver eine Verbindung zu sich selbst herstellen kann. Dafür muss dieser in der Lage sein, sich mit mindestens einer seiner \"trusted_domains\" oder der \"overwrite.cli.url\" zu verbinden und diese aufzulösen.",
"Could not check for JavaScript support via any of your `trusted_domains` nor `overwrite.cli.url`. This may be the result of a server-side DNS mismatch or outbound firewall rule. Please check manually if your webserver serves `.mjs` files using the JavaScript MIME type." : "Es konnte weder über Ihre `trusted_domains` noch über `overwrite.cli.url` nach JavaScript-Unterstützung gesucht werden. Dies kann auf eine serverseitige DNS-Nichtübereinstimmung oder eine ausgehende Firewall-Regel zurückzuführen sein. Bitte überprüfe manuell, ob dein Webserver `.mjs`-Dateien mit dem JavaScript-MIME-Typ bereitstellt.",
- "Active accounts" : "Aktive Konten",
- "None of your currently installed apps provide custom Text processing functionality." : "Keine deiner aktuell installierten Apps bietet benutzerdefinierte Textverarbeitungsfunktionen."
+ "Active accounts" : "Aktive Konten"
},"pluralForm" :"nplurals=2; plural=(n != 1);"
} \ No newline at end of file
diff --git a/apps/settings/l10n/de_DE.js b/apps/settings/l10n/de_DE.js
index daff4b98710..c83a24bbaab 100644
--- a/apps/settings/l10n/de_DE.js
+++ b/apps/settings/l10n/de_DE.js
@@ -881,7 +881,6 @@ OC.L10N.register(
"SMTP Username" : "SMTP-Kontenname",
"To allow this check to run you have to make sure that your webserver can connect to itself. Therefor it must be able to resolve and connect to at least one its `trusted_domains` or the `overwrite.cli.url`." : "Um diese Prüfung auszuführen, müssen Sie sicherstellen, dass Ihr Webserver eine Verbindung zu sich selbst herstellen kann. Dafür muss er in der Lage sein, sich mit mindestens einer seiner \"trusted_domains\" oder der \"overwrite.cli.url\" zu verbinden und diese aufzulösen.",
"Could not check for JavaScript support via any of your `trusted_domains` nor `overwrite.cli.url`. This may be the result of a server-side DNS mismatch or outbound firewall rule. Please check manually if your webserver serves `.mjs` files using the JavaScript MIME type." : "Es konnte weder über Ihre `trusted_domains` noch über `overwrite.cli.url` nach JavaScript-Unterstützung gesucht werden. Dies kann auf eine serverseitige DNS-Nichtübereinstimmung oder eine ausgehende Firewall-Regel zurückzuführen sein. Bitte überprüfen Sie manuell, ob Ihr Webserver `.mjs`-Dateien mit dem JavaScript-MIME-Typ bereitstellt.",
- "Active accounts" : "Aktive Konten",
- "None of your currently installed apps provide custom Text processing functionality." : "Keine Ihrer aktuell installierten Apps bietet benutzerdefinierte Textverarbeitungsfunktionen."
+ "Active accounts" : "Aktive Konten"
},
"nplurals=2; plural=(n != 1);");
diff --git a/apps/settings/l10n/de_DE.json b/apps/settings/l10n/de_DE.json
index dd88f31e626..0f370cb1e04 100644
--- a/apps/settings/l10n/de_DE.json
+++ b/apps/settings/l10n/de_DE.json
@@ -879,7 +879,6 @@
"SMTP Username" : "SMTP-Kontenname",
"To allow this check to run you have to make sure that your webserver can connect to itself. Therefor it must be able to resolve and connect to at least one its `trusted_domains` or the `overwrite.cli.url`." : "Um diese Prüfung auszuführen, müssen Sie sicherstellen, dass Ihr Webserver eine Verbindung zu sich selbst herstellen kann. Dafür muss er in der Lage sein, sich mit mindestens einer seiner \"trusted_domains\" oder der \"overwrite.cli.url\" zu verbinden und diese aufzulösen.",
"Could not check for JavaScript support via any of your `trusted_domains` nor `overwrite.cli.url`. This may be the result of a server-side DNS mismatch or outbound firewall rule. Please check manually if your webserver serves `.mjs` files using the JavaScript MIME type." : "Es konnte weder über Ihre `trusted_domains` noch über `overwrite.cli.url` nach JavaScript-Unterstützung gesucht werden. Dies kann auf eine serverseitige DNS-Nichtübereinstimmung oder eine ausgehende Firewall-Regel zurückzuführen sein. Bitte überprüfen Sie manuell, ob Ihr Webserver `.mjs`-Dateien mit dem JavaScript-MIME-Typ bereitstellt.",
- "Active accounts" : "Aktive Konten",
- "None of your currently installed apps provide custom Text processing functionality." : "Keine Ihrer aktuell installierten Apps bietet benutzerdefinierte Textverarbeitungsfunktionen."
+ "Active accounts" : "Aktive Konten"
},"pluralForm" :"nplurals=2; plural=(n != 1);"
} \ No newline at end of file
diff --git a/apps/settings/l10n/en_GB.js b/apps/settings/l10n/en_GB.js
index 670f9c2a39e..83611953a30 100644
--- a/apps/settings/l10n/en_GB.js
+++ b/apps/settings/l10n/en_GB.js
@@ -881,7 +881,6 @@ OC.L10N.register(
"SMTP Username" : "SMTP Username",
"To allow this check to run you have to make sure that your webserver can connect to itself. Therefor it must be able to resolve and connect to at least one its `trusted_domains` or the `overwrite.cli.url`." : "To allow this check to run you have to make sure that your webserver can connect to itself. Therefor it must be able to resolve and connect to at least one its `trusted_domains` or the `overwrite.cli.url`.",
"Could not check for JavaScript support via any of your `trusted_domains` nor `overwrite.cli.url`. This may be the result of a server-side DNS mismatch or outbound firewall rule. Please check manually if your webserver serves `.mjs` files using the JavaScript MIME type." : "Could not check for JavaScript support via any of your `trusted_domains` nor `overwrite.cli.url`. This may be the result of a server-side DNS mismatch or outbound firewall rule. Please check manually if your webserver serves `.mjs` files using the JavaScript MIME type.",
- "Active accounts" : "Active accounts",
- "None of your currently installed apps provide custom Text processing functionality." : "None of your currently installed apps provide custom Text processing functionality."
+ "Active accounts" : "Active accounts"
},
"nplurals=2; plural=(n != 1);");
diff --git a/apps/settings/l10n/en_GB.json b/apps/settings/l10n/en_GB.json
index 4194e435ea5..2915d208a02 100644
--- a/apps/settings/l10n/en_GB.json
+++ b/apps/settings/l10n/en_GB.json
@@ -879,7 +879,6 @@
"SMTP Username" : "SMTP Username",
"To allow this check to run you have to make sure that your webserver can connect to itself. Therefor it must be able to resolve and connect to at least one its `trusted_domains` or the `overwrite.cli.url`." : "To allow this check to run you have to make sure that your webserver can connect to itself. Therefor it must be able to resolve and connect to at least one its `trusted_domains` or the `overwrite.cli.url`.",
"Could not check for JavaScript support via any of your `trusted_domains` nor `overwrite.cli.url`. This may be the result of a server-side DNS mismatch or outbound firewall rule. Please check manually if your webserver serves `.mjs` files using the JavaScript MIME type." : "Could not check for JavaScript support via any of your `trusted_domains` nor `overwrite.cli.url`. This may be the result of a server-side DNS mismatch or outbound firewall rule. Please check manually if your webserver serves `.mjs` files using the JavaScript MIME type.",
- "Active accounts" : "Active accounts",
- "None of your currently installed apps provide custom Text processing functionality." : "None of your currently installed apps provide custom Text processing functionality."
+ "Active accounts" : "Active accounts"
},"pluralForm" :"nplurals=2; plural=(n != 1);"
} \ No newline at end of file
diff --git a/apps/settings/l10n/es.js b/apps/settings/l10n/es.js
index ead74bdb2b9..080fa1f2042 100644
--- a/apps/settings/l10n/es.js
+++ b/apps/settings/l10n/es.js
@@ -72,6 +72,7 @@ OC.L10N.register(
"Email could not be sent. Check your mail server log" : "No se ha podido enviar el correo. Compruebe el registro del servidor de correo",
"A problem occurred while sending the email. Please revise your settings. (Error: %s)" : "Ha ocurrido un problema al enviar el mensaje de correo electrónico. Revisa tu configuración. (Error: %s)",
"You need to set your account email before being able to send test emails. Go to %s for that." : "Necesita establecer el correo electrónico de su cuenta antes de poder enviar correos de prueba. Vaya a %s para hacerlo.",
+ "Recently active" : "Activos recientemente",
"Disabled accounts" : "Cuentas deshabilitadas",
"Invalid account" : "Cuenta inválida",
"Invalid mail address" : "Dirección de correo no válido",
@@ -124,6 +125,11 @@ OC.L10N.register(
"Background jobs" : "Trabajos en segundo plano",
"Unlimited" : "Ilimitado",
"Verifying" : "Verificar",
+ "Allowed admin IP ranges" : "Rangos de IP permitidos para administración",
+ "Admin IP filtering isn’t applied." : "No se ha aplicado ningún filtrado de IPs para administración.",
+ "Configuration key \"%1$s\" expects an array (%2$s found). Admin IP range validation will not be applied." : "El parámetro de configuración \"%1$s\" espera un arreglo (se encontró %2$s). No se aplicará la validación de rangos de IP para administración.",
+ "Configuration key \"%1$s\" contains invalid IP range(s): \"%2$s\"" : "El parámetro de configuración \"%1$s\" contiene rangos de IP inválido(as): \"%2$s\"",
+ "Admin IP filtering is correctly configured." : "El filtrado de rangos de IP para administración está correctamente configurado.",
"App directories owner" : "Propietario de los directorios de aplicaciones",
"Some app directories are owned by a different user than the web server one. This may be the case if apps have been installed manually. Check the permissions of the following app directories:\n%s" : "Algunos directorios de aplicaciones son propiedad de un usuario diferente al del servidor web. Esto puede ocurrir si las aplicaciones se han instalado manualmente. Compruebe los permisos de los siguientes directorios de aplicaciones:\n%s",
"App directories have the correct owner \"%s\"" : "Los directorios de aplicaciones tienen al propietario correcto \"%s\"",
@@ -131,6 +137,7 @@ OC.L10N.register(
"Your remote address could not be determined." : "No se pudo determinar su dirección remota.",
"Your remote address was identified as \"%s\" and is brute-force throttled at the moment slowing down the performance of various requests. If the remote address is not your address this can be an indication that a proxy is not configured correctly." : "Su dirección remota se ha identificado como \"%s\" y está siendo ralentizada mediante fuerza bruta, disminuyendo el rendimiento de varias solicitudes. Si la dirección remota no es su dirección, esto puede ser una señal de que un proxy no se ha configurado correctamente.",
"Your remote address \"%s\" is not brute-force throttled." : "Su dirección remota \"%s\" no está limitada por fuerza bruta.",
+ "To allow this check to run you have to make sure that your Web server can connect to itself. Therefore it must be able to resolve and connect to at least one of its `trusted_domains` or the `overwrite.cli.url`. This failure may be the result of a server-side DNS mismatch or outbound firewall rule." : "Para permitir que este chequeo se lleve a cabo, debe asegurarse que su servidor pueda conectarse a sí mismo. Por tanto, este debe poder resolver y conectarse a alguno de sus `trusted_domains` o al url definido en `overwrite.cli.url`. Este fallo puede ser resultado de una inconsistencia DNS del lado del servidor o una regla de salida del cortafuegos.",
"Old administration imported certificates" : "Certificados de administración antiguos importados",
"A background job is pending that checks for administration imported SSL certificates. Please check back later." : "Está pendiente una tarea en segundo plano que comprueba los certificados SSL de administración importados. Por favor, vuelva a verificar más tarde.",
"There are some administration imported SSL certificates present, that are not used anymore with Nextcloud 21. They can be imported on the command line via \"occ security:certificates:import\" command. Their paths inside the data directory are shown below." : "Están presentes algunos certificados SSL de administración importados, que, ya no se utilizan con Nextcloud 21. Pueden ser importados usando la línea de comandos con \"occ security:certificates:import\". Sus rutas dentro del directorio de datos se muestran a continuación.",
@@ -151,6 +158,9 @@ OC.L10N.register(
"Missing optional column \"%s\" in table \"%s\"." : "Falta la columna opcional \"%s\" en la tabla \"%s\".",
"The database is missing some optional columns. Due to the fact that adding columns on big tables could take some time they were not added automatically when they can be optional. By running \"occ db:add-missing-columns\" those missing columns could be added manually while the instance keeps running. Once the columns are added some features might improve responsiveness or usability." : "A la base de datos le faltan algunas columnas opcionales. Debido al hecho de que agregar columnas en tablas grandes podría llevar mucho tiempo, estas no se agregaron automáticamente cuando pueden ser opcionales. Al ejecutar \"occ db:add-missing-columns\", estas columnas faltantes se pueden agregar manualmente mientras la instancia sigue en ejecución. Una vez que se agreguen las columnas, algunas características podrían mejorar su capacidad de respuesta o la usabilidad.",
"Database missing indices" : "Faltan índices en la base de datos",
+ "Missing indices:" : "Índices faltantes:",
+ "\"%s\" in table \"%s\"" : "\"%s\" en tabla \"%s\"",
+ "Detected some missing optional indices. Occasionally new indices are added (by Nextcloud or installed applications) to improve database performance. Adding indices can sometimes take awhile and temporarily hurt performance so this is not done automatically during upgrades. Once the indices are added, queries to those tables should be faster. Use the command `occ db:add-missing-indices` to add them. " : "Se detectaron algunos índices opcionales faltantes. Ocasionalmente, se añaden nuevos índices (bien sea por Nextcloud o por las aplicaciones instaladas) para mejorar el rendimiento de la base de datos. Añadir índices algunas veces puede tomar un tiempo, y, afectar el rendimiento temporalmente, así que esto no se hace de manera automática durante las actualizaciones. Una vez que los índices son añadidos, las consultas a esas tablas deben ser más rápidas. Use el comando `occ db:add-missing-indices` para añadirlos.",
"Database missing primary keys" : "Faltan claves primarias en la base de datos",
"Missing primary key on table \"%s\"." : "Falta la clave primaria en la tabla \"%s\".",
"The database is missing some primary keys. Due to the fact that adding primary keys on big tables could take some time they were not added automatically. By running \"occ db:add-missing-primary-keys\" those missing primary keys could be added manually while the instance keeps running." : "A la base de datos le faltan algunas claves primarias. Debido a que añadir claves primarias en tablas grandes podría llevar mucho tiempo, no se añadieron automáticamente. Al ejecutar \"occ db:add-missing-primary-keys\" esas claves primarias faltantes podrían ser añadidas manualmente mientras la instancia sigue funcionando.",
@@ -176,11 +186,14 @@ OC.L10N.register(
"HTTPS access and URLs" : "Acceso HTTPS y URLs",
"Accessing site insecurely via HTTP. You are strongly advised to set up your server to require HTTPS instead. Without it some important web functionality like \"copy to clipboard\" or \"service workers\" will not work!" : "Se está accediendo al sitio de manera insegura mediante HTTP. Se recomienda encarecidamente que configure su servidor para que requiera HTTP. ¡Sin ello, algunas funciones importantes de la web como \"copiar al portapapeles\" o \"service workers\" no funcionarán!",
"Accessing site insecurely via HTTP." : "Accediendo al sitio de manera insegura mediante HTTP.",
+ "You are accessing your instance over a secure connection, however your instance is generating insecure URLs. This likely means that your instance is behind a reverse proxy and the Nextcloud `overwrite*` config values are not set correctly." : "Está accediendo a su instancia a través de una conexión segura, sin embargo, su instancia está generando URLs inseguras. Esto suele significar que está tras un proxy inverso y que los valores de configuración `overwrite*` no están bien configurados.",
+ "Your instance is generating insecure URLs. If you access your instance over HTTPS, this likely means that your instance is behind a reverse proxy and the Nextcloud `overwrite*` config values are not set correctly." : "Su instancia está generando URLs inseguras, Si accede a su instancia a través de HTTPS, esto podría significar que su instancia está tras un proxy inverso y que los valores de configuración Nexcloud `overwrite*` no están bien configurados.",
"You are accessing your instance over a secure connection, and your instance is generating secure URLs." : "Está accediendo a su instancia mediante una conexión segura, y su instancia está generando URLs seguros.",
"Internet connectivity" : "Conexión a Internet",
"Internet connectivity is disabled in configuration file." : "La conexión a Internet está deshabilitada en el archivo de configuración.",
"This server has no working internet connection: Multiple endpoints could not be reached. This means that some of the features like mounting external storage, notifications about updates or installation of third-party apps will not work. Accessing files remotely and sending of notification emails might not work, either. Establish a connection from this server to the internet to enjoy all features." : "Este servidor no tiene una conexión a Internet que funcione: No se pudieron alcanzar varios endpoints. Esto significa que algunas de las funciones, como montar almacenamiento externo, notificaciones sobre actualizaciones o instalación de aplicaciones de terceros no funcionarán. Es posible que el acceso a archivos de forma remota y el envío de emails de notificación tampoco funcionen. Establezca una conexión desde este servidor a Internet para disfrutar de todas las funciones.",
"JavaScript modules support" : "Soporte a módulos JavaScript",
+ "Unable to run check for JavaScript support. Please remedy or confirm manually if your webserver serves `.mjs` files using the JavaScript MIME type." : "No se pudo hacer el chequeo del soporte JavaScript. Por favor remedie el problema, o, confirme manualmente si su servidor web sirve archivos `.mjs` utilizando el tipo MIME JavaScript.",
"Your webserver does not serve `.mjs` files using the JavaScript MIME type. This will break some apps by preventing browsers from executing the JavaScript files. You should configure your webserver to serve `.mjs` files with either the `text/javascript` or `application/javascript` MIME type." : "Su servidor web no sirve archivos `.mjs` utilizando el tipo MIME JavaScript. Esto causará problemas con algunas apps, impidiendo que los navegadores ejecuten los archivos JavaScript. Debe configurar su servidor web para servir archivos `.mjs` bien sea con el tipo MIME `text/javascript`, o, `application/javascript`.",
"JavaScript source map support" : "Soporte de mapa fuente de JavaScript",
"Your webserver is not set up to serve `.js.map` files. Without these files, JavaScript Source Maps won't function properly, making it more challenging to troubleshoot and debug any issues that may arise." : "Su servidor web no está configurado para servir archivos `.js.map`. Sin estos archivos, los mapas de fuente JavaScript no funcionarán apropiadamente, haciendo más difícil la resolución y depuración de problemas que puedan surgir.",
@@ -191,8 +204,12 @@ OC.L10N.register(
"Server has no maintenance window start time configured. This means resource intensive daily background jobs will also be executed during your main usage time. We recommend to set it to a time of low usage, so users are less impacted by the load caused from these heavy tasks." : "El servidor no tiene un tiempo de inicio de la ventana de mantenimiento configurado. Esto significa que los trabajos en segundo plano diarios que consumen recursos de manera intensiva serán ejecutados durante el tiempo regular de uso. Recomendamos establecerlo a una franja horaria de poco uso, de manera que el impacto a los usuarios disminuya por la carga causada a raíz estas tareas intensivas.",
"Maintenance window to execute heavy background jobs is between {start}:00 UTC and {end}:00 UTC" : "La ventana de mantenimiento para ejecutar trabajos en segundo plano intensivos está entre {start}:00 UTC y {end}:00 UTC",
"Memcache" : "Memcache",
+ "Memcached is configured as distributed cache, but the wrong PHP module (\"memcache\") is installed. Please install the PHP module \"memcached\"." : "Memcached está configurado como un caché distribuido, pero el módulo PHP incorrecto (memcache) está instalado. Por favor, instale el módulo PHP \"memcached\".",
+ "Memcached is configured as distributed cache, but the PHP module \"memcached\" is not installed. Please install the PHP module \"memcached\"." : "Memcached está configurado como un caché distribuido, pero el módulo PHP \"memcached\" no está instalado. Por favor, instale el módulo PHP \"memcached\".",
"No memory cache has been configured. To enhance performance, please configure a memcache, if available." : "No hay un caché en memoria configurado. Para mejorar el rendimiento, configura memcache, si está disponible.",
"Configured" : "Configurado",
+ "Mimetype migrations available" : "Están disponibles las migraciones del tipo MIME",
+ "One or more mimetype migrations are available. Occasionally new mimetypes are added to better handle certain file types. Migrating the mimetypes take a long time on larger instances so this is not done automatically during upgrades. Use the command `occ maintenance:repair --include-expensive` to perform the migrations." : "Una o más migraciones del tipo MIME están disponibles. Ocasionalmente, nuevos tipos MIME se añaden para manejar de una manera más adecuada ciertos tipos de archivo. Migrar los tipos MIME puede tomar un tiempo considerable en instancias grandes así que esto no se hace de manera automática durante las actualizaciones. Use el comando `occ maintenance:repair --include-expensive` para realizar las migraciones.",
"MySQL Unicode support" : "Soporte Unicode de MySQL",
"You are not using MySQL" : "No está usando MySQL",
"MySQL is used as database and does support 4-byte characters" : "MySQL se está utilizando como base de datos y soportar caracteres de 4 bytes",
@@ -204,6 +221,9 @@ OC.L10N.register(
"The \"overwrite.cli.url\" option in your config.php is correctly set to \"%s\"." : "La opción \"overwrite.cli.url\" en su config.php está correctamente establecida como \"%s\".",
"The \"overwrite.cli.url\" option in your config.php is set to \"%s\" which is a correct URL. Suggested URL is \"%s\"." : "La opción \"overwrite.cli.url\" en su config.php está establecida como \"%s\". que es una URL correcta. La URL sugerida es \"%s\",",
"Please make sure to set the \"overwrite.cli.url\" option in your config.php file to the URL that your users mainly use to access this Nextcloud. Suggestion: \"%s\". Otherwise there might be problems with the URL generation via cron. (It is possible though that the suggested URL is not the URL that your users mainly use to access this Nextcloud. Best is to double check this in any case.)" : "Asegúrese de establecer la opción \"overwrite.cli.url\" en su archivo config.php con la URL que sus usuarios suelen utilizar para acceder a Nextcloud. Sugerencia: \"%s\". De lo contrario, podría haber problemas con la generación de URLs a través de cron. (Sin embargo, es posible que la URL sugerida no sea la que sus usuarios suelen utilizar para acceder a Nextcloud. Lo mejor es verificar esto en cualquier caso.)",
+ "PHP APCu configuration" : "Configuración de PHP APCu",
+ "Your APCu cache has been running full, consider increasing the apc.shm_size php setting." : "Su caché APCu ha estado cache ha estado funcionando a máxima capacidad, considere incrementar el ajuste apc.shm_size de php.",
+ "Your APCu cache is almost full at %s%%, consider increasing the apc.shm_size php setting." : "Su caché APCu está casi al máximo a %s%%, considere incrementar el ajuste apc.shm_size de php.",
"PHP default charset" : "Conjunto de caracteres predeterminado de PHP",
"PHP configuration option \"default_charset\" should be UTF-8" : "La opción de configuración PHP \"default_charset\" debería ser UTF-8",
"PHP set_time_limit" : "set_time_limit en PHP",
@@ -234,6 +254,7 @@ OC.L10N.register(
"The OPcache interned strings buffer is nearly full. To assure that repeating strings can be effectively cached, it is recommended to apply \"opcache.interned_strings_buffer\" to your PHP configuration with a value higher than \"%s\"." : "El búfer de cadenas internadas de OPcache está casi lleno. Para asegurarse de que las cadenas repetidas puedan ser almacenadas en caché de manera efectiva, se recomienda añadir \"opcache.interned_strings_buffer\" a la configuración de PHP con un valor superior a \"%s\".",
"OPcache is configured to remove code comments. With OPcache enabled, \"opcache.save_comments=1\" must be set for Nextcloud to function." : "OPcache está configurado para eliminar comentarios en el código. Con OPcache activado, se debe establecer \"opcache.save_comments=1\" para que Nextcloud funcione.",
"Nextcloud is not allowed to use the OPcache API. With OPcache enabled, it is highly recommended to include all Nextcloud directories with \"opcache.restrict_api\" or unset this setting to disable OPcache API restrictions, to prevent errors during Nextcloud core or app upgrades." : "Nextcloud no tiene permiso para utilizar la API de OPcache. Con OPcache habilitado, es altamente recomendado incluir todos los directorios de Nextcloud con \"opcache.restrict_api\" o deshabilitar este ajuste para desactivar las restricciones de la API de OPcache, para prevenir errores durante las actualizaciones base de Nextcloud o de las aplicaciones.",
+ "Checking from CLI, OPcache checks have been skipped." : "Haciendo el chequeo desde línea de comandos, los chequeos de OPcache han sido omitidos.",
"The PHP OPcache module is not properly configured. %s." : "El módulo PHP OPcache no está configurado correctamente %s.",
"Correctly configured" : "Correctamente configurado",
"PHP version" : "Versión PHP",
@@ -251,6 +272,9 @@ OC.L10N.register(
"Configuration file access rights" : "Configuración de permisos de archivos",
"The read-only config has been enabled. This prevents setting some configurations via the web-interface. Furthermore, the file needs to be made writable manually for every update." : "Se ha activado la configuración de solo lectura. Esto evita cambiar ciertas configuraciones vía la interfaz web. Además, el archivo debe hacerse escribible de manera manual para cada actualización.",
"Nextcloud configuration file is writable" : "Se puede escribir al archivo de configuración de Nextcloud",
+ "Scheduling objects table size" : "Tamaño de tabla para objetos de calendario",
+ "You have more than %s rows in the scheduling objects table. Please run the expensive repair jobs via occ maintenance:repair --include-expensive." : "Tiene más de %s filas en la tabla de objetos de calendario. Por favor, ejecute los trabajos de reparación complejos a través del comando occ maintenance:repair --include-expensive.",
+ "Scheduling objects table size is within acceptable range." : "El tamaño de la tabla para objetos de calendario está dentro de un rango aceptable.",
"HTTP headers" : "Encabezados HTTP",
"- The `%1$s` HTTP header is not set to `%2$s`. Some features might not work correctly, as it is recommended to adjust this setting accordingly." : "- El encabezado HTTP `%1$s` no está configurado a `%2$s`. Algunas características podrían no funcionar correctamente, por lo que se recomienda ajustar esta configuración adecuadamente.",
"- The `%1$s` HTTP header is not set to `%2$s`. This is a potential security or privacy risk, as it is recommended to adjust this setting accordingly." : "- El encabezado HTTP `%1$s` no está configurado a `%2$s`. Este es un riesgo potencial de seguridad o privacidad, por lo que se recomienda ajustar esta configuración adecuadamente.",
@@ -264,6 +288,8 @@ OC.L10N.register(
"Could not check that your web server serves security headers correctly, unable to query `%s`" : "No se pudo verificar que su servidor web sirve los encabezados de seguridad correctamente, no fue posible consultar `%s`",
"Your server is correctly configured to send security headers." : "Su servidor está correctamente configurado para enviar los encabezados de seguridad.",
"Database version" : "Versión de base de datos",
+ "MariaDB version 10.3 detected, this version is end-of-life and only supported as part of Ubuntu 20.04. MariaDB >=%1$s and <=%2$s is suggested for best performance, stability and functionality with this version of Nextcloud." : "Se detectó la version 10.3 de MariaDB, esta versión ya está en end-of-life y sólo está soportada por Ubuntu 20.04. Se sugiere utilizar MariaDB >=%1$s and <=%2$s para un mejor rendimiento, estabilidad y funcionalidad con esta versión de Nextcloud.",
+ "MariaDB version \"%1$s\" detected. MariaDB >=%2$s and <=%3$s is suggested for best performance, stability and functionality with this version of Nextcloud." : "Se detectó la versión \"%1$s\" de MariaDB. Se sugiere utilizar una versión de MariaDB entre >=%2$s y <=%3$s para un mejor rendimiento, estabilidad y funcionalidad con esta versión de Nextcloud.",
"SQLite is currently being used as the backend database. For larger installations we recommend that you switch to a different database backend. This is particularly recommended when using the desktop client for file synchronisation. To migrate to another database use the command line tool: \"occ db:convert-type\"." : "SQLite se está utilizando actualmente como la base de datos principal. Para instalaciones más grandes, recomendamos que cambie a una base de datos principal diferente. Esto es particularmente recomendado cuando se utiliza el cliente de escritorio para la sincronización de archivos. Para migrar a otra base de datos, utilice la herramienta de línea de comandos: \"occ db:convert-type\".",
"Unknown database platform" : "Plataforma de base de datos desconocida",
"Architecture" : "Arquitectura",
diff --git a/apps/settings/l10n/es.json b/apps/settings/l10n/es.json
index 12032ed6981..2d931e5b67a 100644
--- a/apps/settings/l10n/es.json
+++ b/apps/settings/l10n/es.json
@@ -70,6 +70,7 @@
"Email could not be sent. Check your mail server log" : "No se ha podido enviar el correo. Compruebe el registro del servidor de correo",
"A problem occurred while sending the email. Please revise your settings. (Error: %s)" : "Ha ocurrido un problema al enviar el mensaje de correo electrónico. Revisa tu configuración. (Error: %s)",
"You need to set your account email before being able to send test emails. Go to %s for that." : "Necesita establecer el correo electrónico de su cuenta antes de poder enviar correos de prueba. Vaya a %s para hacerlo.",
+ "Recently active" : "Activos recientemente",
"Disabled accounts" : "Cuentas deshabilitadas",
"Invalid account" : "Cuenta inválida",
"Invalid mail address" : "Dirección de correo no válido",
@@ -122,6 +123,11 @@
"Background jobs" : "Trabajos en segundo plano",
"Unlimited" : "Ilimitado",
"Verifying" : "Verificar",
+ "Allowed admin IP ranges" : "Rangos de IP permitidos para administración",
+ "Admin IP filtering isn’t applied." : "No se ha aplicado ningún filtrado de IPs para administración.",
+ "Configuration key \"%1$s\" expects an array (%2$s found). Admin IP range validation will not be applied." : "El parámetro de configuración \"%1$s\" espera un arreglo (se encontró %2$s). No se aplicará la validación de rangos de IP para administración.",
+ "Configuration key \"%1$s\" contains invalid IP range(s): \"%2$s\"" : "El parámetro de configuración \"%1$s\" contiene rangos de IP inválido(as): \"%2$s\"",
+ "Admin IP filtering is correctly configured." : "El filtrado de rangos de IP para administración está correctamente configurado.",
"App directories owner" : "Propietario de los directorios de aplicaciones",
"Some app directories are owned by a different user than the web server one. This may be the case if apps have been installed manually. Check the permissions of the following app directories:\n%s" : "Algunos directorios de aplicaciones son propiedad de un usuario diferente al del servidor web. Esto puede ocurrir si las aplicaciones se han instalado manualmente. Compruebe los permisos de los siguientes directorios de aplicaciones:\n%s",
"App directories have the correct owner \"%s\"" : "Los directorios de aplicaciones tienen al propietario correcto \"%s\"",
@@ -129,6 +135,7 @@
"Your remote address could not be determined." : "No se pudo determinar su dirección remota.",
"Your remote address was identified as \"%s\" and is brute-force throttled at the moment slowing down the performance of various requests. If the remote address is not your address this can be an indication that a proxy is not configured correctly." : "Su dirección remota se ha identificado como \"%s\" y está siendo ralentizada mediante fuerza bruta, disminuyendo el rendimiento de varias solicitudes. Si la dirección remota no es su dirección, esto puede ser una señal de que un proxy no se ha configurado correctamente.",
"Your remote address \"%s\" is not brute-force throttled." : "Su dirección remota \"%s\" no está limitada por fuerza bruta.",
+ "To allow this check to run you have to make sure that your Web server can connect to itself. Therefore it must be able to resolve and connect to at least one of its `trusted_domains` or the `overwrite.cli.url`. This failure may be the result of a server-side DNS mismatch or outbound firewall rule." : "Para permitir que este chequeo se lleve a cabo, debe asegurarse que su servidor pueda conectarse a sí mismo. Por tanto, este debe poder resolver y conectarse a alguno de sus `trusted_domains` o al url definido en `overwrite.cli.url`. Este fallo puede ser resultado de una inconsistencia DNS del lado del servidor o una regla de salida del cortafuegos.",
"Old administration imported certificates" : "Certificados de administración antiguos importados",
"A background job is pending that checks for administration imported SSL certificates. Please check back later." : "Está pendiente una tarea en segundo plano que comprueba los certificados SSL de administración importados. Por favor, vuelva a verificar más tarde.",
"There are some administration imported SSL certificates present, that are not used anymore with Nextcloud 21. They can be imported on the command line via \"occ security:certificates:import\" command. Their paths inside the data directory are shown below." : "Están presentes algunos certificados SSL de administración importados, que, ya no se utilizan con Nextcloud 21. Pueden ser importados usando la línea de comandos con \"occ security:certificates:import\". Sus rutas dentro del directorio de datos se muestran a continuación.",
@@ -149,6 +156,9 @@
"Missing optional column \"%s\" in table \"%s\"." : "Falta la columna opcional \"%s\" en la tabla \"%s\".",
"The database is missing some optional columns. Due to the fact that adding columns on big tables could take some time they were not added automatically when they can be optional. By running \"occ db:add-missing-columns\" those missing columns could be added manually while the instance keeps running. Once the columns are added some features might improve responsiveness or usability." : "A la base de datos le faltan algunas columnas opcionales. Debido al hecho de que agregar columnas en tablas grandes podría llevar mucho tiempo, estas no se agregaron automáticamente cuando pueden ser opcionales. Al ejecutar \"occ db:add-missing-columns\", estas columnas faltantes se pueden agregar manualmente mientras la instancia sigue en ejecución. Una vez que se agreguen las columnas, algunas características podrían mejorar su capacidad de respuesta o la usabilidad.",
"Database missing indices" : "Faltan índices en la base de datos",
+ "Missing indices:" : "Índices faltantes:",
+ "\"%s\" in table \"%s\"" : "\"%s\" en tabla \"%s\"",
+ "Detected some missing optional indices. Occasionally new indices are added (by Nextcloud or installed applications) to improve database performance. Adding indices can sometimes take awhile and temporarily hurt performance so this is not done automatically during upgrades. Once the indices are added, queries to those tables should be faster. Use the command `occ db:add-missing-indices` to add them. " : "Se detectaron algunos índices opcionales faltantes. Ocasionalmente, se añaden nuevos índices (bien sea por Nextcloud o por las aplicaciones instaladas) para mejorar el rendimiento de la base de datos. Añadir índices algunas veces puede tomar un tiempo, y, afectar el rendimiento temporalmente, así que esto no se hace de manera automática durante las actualizaciones. Una vez que los índices son añadidos, las consultas a esas tablas deben ser más rápidas. Use el comando `occ db:add-missing-indices` para añadirlos.",
"Database missing primary keys" : "Faltan claves primarias en la base de datos",
"Missing primary key on table \"%s\"." : "Falta la clave primaria en la tabla \"%s\".",
"The database is missing some primary keys. Due to the fact that adding primary keys on big tables could take some time they were not added automatically. By running \"occ db:add-missing-primary-keys\" those missing primary keys could be added manually while the instance keeps running." : "A la base de datos le faltan algunas claves primarias. Debido a que añadir claves primarias en tablas grandes podría llevar mucho tiempo, no se añadieron automáticamente. Al ejecutar \"occ db:add-missing-primary-keys\" esas claves primarias faltantes podrían ser añadidas manualmente mientras la instancia sigue funcionando.",
@@ -174,11 +184,14 @@
"HTTPS access and URLs" : "Acceso HTTPS y URLs",
"Accessing site insecurely via HTTP. You are strongly advised to set up your server to require HTTPS instead. Without it some important web functionality like \"copy to clipboard\" or \"service workers\" will not work!" : "Se está accediendo al sitio de manera insegura mediante HTTP. Se recomienda encarecidamente que configure su servidor para que requiera HTTP. ¡Sin ello, algunas funciones importantes de la web como \"copiar al portapapeles\" o \"service workers\" no funcionarán!",
"Accessing site insecurely via HTTP." : "Accediendo al sitio de manera insegura mediante HTTP.",
+ "You are accessing your instance over a secure connection, however your instance is generating insecure URLs. This likely means that your instance is behind a reverse proxy and the Nextcloud `overwrite*` config values are not set correctly." : "Está accediendo a su instancia a través de una conexión segura, sin embargo, su instancia está generando URLs inseguras. Esto suele significar que está tras un proxy inverso y que los valores de configuración `overwrite*` no están bien configurados.",
+ "Your instance is generating insecure URLs. If you access your instance over HTTPS, this likely means that your instance is behind a reverse proxy and the Nextcloud `overwrite*` config values are not set correctly." : "Su instancia está generando URLs inseguras, Si accede a su instancia a través de HTTPS, esto podría significar que su instancia está tras un proxy inverso y que los valores de configuración Nexcloud `overwrite*` no están bien configurados.",
"You are accessing your instance over a secure connection, and your instance is generating secure URLs." : "Está accediendo a su instancia mediante una conexión segura, y su instancia está generando URLs seguros.",
"Internet connectivity" : "Conexión a Internet",
"Internet connectivity is disabled in configuration file." : "La conexión a Internet está deshabilitada en el archivo de configuración.",
"This server has no working internet connection: Multiple endpoints could not be reached. This means that some of the features like mounting external storage, notifications about updates or installation of third-party apps will not work. Accessing files remotely and sending of notification emails might not work, either. Establish a connection from this server to the internet to enjoy all features." : "Este servidor no tiene una conexión a Internet que funcione: No se pudieron alcanzar varios endpoints. Esto significa que algunas de las funciones, como montar almacenamiento externo, notificaciones sobre actualizaciones o instalación de aplicaciones de terceros no funcionarán. Es posible que el acceso a archivos de forma remota y el envío de emails de notificación tampoco funcionen. Establezca una conexión desde este servidor a Internet para disfrutar de todas las funciones.",
"JavaScript modules support" : "Soporte a módulos JavaScript",
+ "Unable to run check for JavaScript support. Please remedy or confirm manually if your webserver serves `.mjs` files using the JavaScript MIME type." : "No se pudo hacer el chequeo del soporte JavaScript. Por favor remedie el problema, o, confirme manualmente si su servidor web sirve archivos `.mjs` utilizando el tipo MIME JavaScript.",
"Your webserver does not serve `.mjs` files using the JavaScript MIME type. This will break some apps by preventing browsers from executing the JavaScript files. You should configure your webserver to serve `.mjs` files with either the `text/javascript` or `application/javascript` MIME type." : "Su servidor web no sirve archivos `.mjs` utilizando el tipo MIME JavaScript. Esto causará problemas con algunas apps, impidiendo que los navegadores ejecuten los archivos JavaScript. Debe configurar su servidor web para servir archivos `.mjs` bien sea con el tipo MIME `text/javascript`, o, `application/javascript`.",
"JavaScript source map support" : "Soporte de mapa fuente de JavaScript",
"Your webserver is not set up to serve `.js.map` files. Without these files, JavaScript Source Maps won't function properly, making it more challenging to troubleshoot and debug any issues that may arise." : "Su servidor web no está configurado para servir archivos `.js.map`. Sin estos archivos, los mapas de fuente JavaScript no funcionarán apropiadamente, haciendo más difícil la resolución y depuración de problemas que puedan surgir.",
@@ -189,8 +202,12 @@
"Server has no maintenance window start time configured. This means resource intensive daily background jobs will also be executed during your main usage time. We recommend to set it to a time of low usage, so users are less impacted by the load caused from these heavy tasks." : "El servidor no tiene un tiempo de inicio de la ventana de mantenimiento configurado. Esto significa que los trabajos en segundo plano diarios que consumen recursos de manera intensiva serán ejecutados durante el tiempo regular de uso. Recomendamos establecerlo a una franja horaria de poco uso, de manera que el impacto a los usuarios disminuya por la carga causada a raíz estas tareas intensivas.",
"Maintenance window to execute heavy background jobs is between {start}:00 UTC and {end}:00 UTC" : "La ventana de mantenimiento para ejecutar trabajos en segundo plano intensivos está entre {start}:00 UTC y {end}:00 UTC",
"Memcache" : "Memcache",
+ "Memcached is configured as distributed cache, but the wrong PHP module (\"memcache\") is installed. Please install the PHP module \"memcached\"." : "Memcached está configurado como un caché distribuido, pero el módulo PHP incorrecto (memcache) está instalado. Por favor, instale el módulo PHP \"memcached\".",
+ "Memcached is configured as distributed cache, but the PHP module \"memcached\" is not installed. Please install the PHP module \"memcached\"." : "Memcached está configurado como un caché distribuido, pero el módulo PHP \"memcached\" no está instalado. Por favor, instale el módulo PHP \"memcached\".",
"No memory cache has been configured. To enhance performance, please configure a memcache, if available." : "No hay un caché en memoria configurado. Para mejorar el rendimiento, configura memcache, si está disponible.",
"Configured" : "Configurado",
+ "Mimetype migrations available" : "Están disponibles las migraciones del tipo MIME",
+ "One or more mimetype migrations are available. Occasionally new mimetypes are added to better handle certain file types. Migrating the mimetypes take a long time on larger instances so this is not done automatically during upgrades. Use the command `occ maintenance:repair --include-expensive` to perform the migrations." : "Una o más migraciones del tipo MIME están disponibles. Ocasionalmente, nuevos tipos MIME se añaden para manejar de una manera más adecuada ciertos tipos de archivo. Migrar los tipos MIME puede tomar un tiempo considerable en instancias grandes así que esto no se hace de manera automática durante las actualizaciones. Use el comando `occ maintenance:repair --include-expensive` para realizar las migraciones.",
"MySQL Unicode support" : "Soporte Unicode de MySQL",
"You are not using MySQL" : "No está usando MySQL",
"MySQL is used as database and does support 4-byte characters" : "MySQL se está utilizando como base de datos y soportar caracteres de 4 bytes",
@@ -202,6 +219,9 @@
"The \"overwrite.cli.url\" option in your config.php is correctly set to \"%s\"." : "La opción \"overwrite.cli.url\" en su config.php está correctamente establecida como \"%s\".",
"The \"overwrite.cli.url\" option in your config.php is set to \"%s\" which is a correct URL. Suggested URL is \"%s\"." : "La opción \"overwrite.cli.url\" en su config.php está establecida como \"%s\". que es una URL correcta. La URL sugerida es \"%s\",",
"Please make sure to set the \"overwrite.cli.url\" option in your config.php file to the URL that your users mainly use to access this Nextcloud. Suggestion: \"%s\". Otherwise there might be problems with the URL generation via cron. (It is possible though that the suggested URL is not the URL that your users mainly use to access this Nextcloud. Best is to double check this in any case.)" : "Asegúrese de establecer la opción \"overwrite.cli.url\" en su archivo config.php con la URL que sus usuarios suelen utilizar para acceder a Nextcloud. Sugerencia: \"%s\". De lo contrario, podría haber problemas con la generación de URLs a través de cron. (Sin embargo, es posible que la URL sugerida no sea la que sus usuarios suelen utilizar para acceder a Nextcloud. Lo mejor es verificar esto en cualquier caso.)",
+ "PHP APCu configuration" : "Configuración de PHP APCu",
+ "Your APCu cache has been running full, consider increasing the apc.shm_size php setting." : "Su caché APCu ha estado cache ha estado funcionando a máxima capacidad, considere incrementar el ajuste apc.shm_size de php.",
+ "Your APCu cache is almost full at %s%%, consider increasing the apc.shm_size php setting." : "Su caché APCu está casi al máximo a %s%%, considere incrementar el ajuste apc.shm_size de php.",
"PHP default charset" : "Conjunto de caracteres predeterminado de PHP",
"PHP configuration option \"default_charset\" should be UTF-8" : "La opción de configuración PHP \"default_charset\" debería ser UTF-8",
"PHP set_time_limit" : "set_time_limit en PHP",
@@ -232,6 +252,7 @@
"The OPcache interned strings buffer is nearly full. To assure that repeating strings can be effectively cached, it is recommended to apply \"opcache.interned_strings_buffer\" to your PHP configuration with a value higher than \"%s\"." : "El búfer de cadenas internadas de OPcache está casi lleno. Para asegurarse de que las cadenas repetidas puedan ser almacenadas en caché de manera efectiva, se recomienda añadir \"opcache.interned_strings_buffer\" a la configuración de PHP con un valor superior a \"%s\".",
"OPcache is configured to remove code comments. With OPcache enabled, \"opcache.save_comments=1\" must be set for Nextcloud to function." : "OPcache está configurado para eliminar comentarios en el código. Con OPcache activado, se debe establecer \"opcache.save_comments=1\" para que Nextcloud funcione.",
"Nextcloud is not allowed to use the OPcache API. With OPcache enabled, it is highly recommended to include all Nextcloud directories with \"opcache.restrict_api\" or unset this setting to disable OPcache API restrictions, to prevent errors during Nextcloud core or app upgrades." : "Nextcloud no tiene permiso para utilizar la API de OPcache. Con OPcache habilitado, es altamente recomendado incluir todos los directorios de Nextcloud con \"opcache.restrict_api\" o deshabilitar este ajuste para desactivar las restricciones de la API de OPcache, para prevenir errores durante las actualizaciones base de Nextcloud o de las aplicaciones.",
+ "Checking from CLI, OPcache checks have been skipped." : "Haciendo el chequeo desde línea de comandos, los chequeos de OPcache han sido omitidos.",
"The PHP OPcache module is not properly configured. %s." : "El módulo PHP OPcache no está configurado correctamente %s.",
"Correctly configured" : "Correctamente configurado",
"PHP version" : "Versión PHP",
@@ -249,6 +270,9 @@
"Configuration file access rights" : "Configuración de permisos de archivos",
"The read-only config has been enabled. This prevents setting some configurations via the web-interface. Furthermore, the file needs to be made writable manually for every update." : "Se ha activado la configuración de solo lectura. Esto evita cambiar ciertas configuraciones vía la interfaz web. Además, el archivo debe hacerse escribible de manera manual para cada actualización.",
"Nextcloud configuration file is writable" : "Se puede escribir al archivo de configuración de Nextcloud",
+ "Scheduling objects table size" : "Tamaño de tabla para objetos de calendario",
+ "You have more than %s rows in the scheduling objects table. Please run the expensive repair jobs via occ maintenance:repair --include-expensive." : "Tiene más de %s filas en la tabla de objetos de calendario. Por favor, ejecute los trabajos de reparación complejos a través del comando occ maintenance:repair --include-expensive.",
+ "Scheduling objects table size is within acceptable range." : "El tamaño de la tabla para objetos de calendario está dentro de un rango aceptable.",
"HTTP headers" : "Encabezados HTTP",
"- The `%1$s` HTTP header is not set to `%2$s`. Some features might not work correctly, as it is recommended to adjust this setting accordingly." : "- El encabezado HTTP `%1$s` no está configurado a `%2$s`. Algunas características podrían no funcionar correctamente, por lo que se recomienda ajustar esta configuración adecuadamente.",
"- The `%1$s` HTTP header is not set to `%2$s`. This is a potential security or privacy risk, as it is recommended to adjust this setting accordingly." : "- El encabezado HTTP `%1$s` no está configurado a `%2$s`. Este es un riesgo potencial de seguridad o privacidad, por lo que se recomienda ajustar esta configuración adecuadamente.",
@@ -262,6 +286,8 @@
"Could not check that your web server serves security headers correctly, unable to query `%s`" : "No se pudo verificar que su servidor web sirve los encabezados de seguridad correctamente, no fue posible consultar `%s`",
"Your server is correctly configured to send security headers." : "Su servidor está correctamente configurado para enviar los encabezados de seguridad.",
"Database version" : "Versión de base de datos",
+ "MariaDB version 10.3 detected, this version is end-of-life and only supported as part of Ubuntu 20.04. MariaDB >=%1$s and <=%2$s is suggested for best performance, stability and functionality with this version of Nextcloud." : "Se detectó la version 10.3 de MariaDB, esta versión ya está en end-of-life y sólo está soportada por Ubuntu 20.04. Se sugiere utilizar MariaDB >=%1$s and <=%2$s para un mejor rendimiento, estabilidad y funcionalidad con esta versión de Nextcloud.",
+ "MariaDB version \"%1$s\" detected. MariaDB >=%2$s and <=%3$s is suggested for best performance, stability and functionality with this version of Nextcloud." : "Se detectó la versión \"%1$s\" de MariaDB. Se sugiere utilizar una versión de MariaDB entre >=%2$s y <=%3$s para un mejor rendimiento, estabilidad y funcionalidad con esta versión de Nextcloud.",
"SQLite is currently being used as the backend database. For larger installations we recommend that you switch to a different database backend. This is particularly recommended when using the desktop client for file synchronisation. To migrate to another database use the command line tool: \"occ db:convert-type\"." : "SQLite se está utilizando actualmente como la base de datos principal. Para instalaciones más grandes, recomendamos que cambie a una base de datos principal diferente. Esto es particularmente recomendado cuando se utiliza el cliente de escritorio para la sincronización de archivos. Para migrar a otra base de datos, utilice la herramienta de línea de comandos: \"occ db:convert-type\".",
"Unknown database platform" : "Plataforma de base de datos desconocida",
"Architecture" : "Arquitectura",
diff --git a/apps/settings/l10n/ga.js b/apps/settings/l10n/ga.js
index 3fd96972e51..ca059d828a7 100644
--- a/apps/settings/l10n/ga.js
+++ b/apps/settings/l10n/ga.js
@@ -881,7 +881,6 @@ OC.L10N.register(
"SMTP Username" : "Ainm Úsáideora SMTP",
"To allow this check to run you have to make sure that your webserver can connect to itself. Therefor it must be able to resolve and connect to at least one its `trusted_domains` or the `overwrite.cli.url`." : "Le gur féidir an tseiceáil seo a rith caithfidh tú a chinntiú gur féidir le do fhreastalaí gréasáin nascadh leis féin. Mar sin caithfidh sé a bheith in ann réiteach agus ceangal a dhéanamh le ceann amháin ar a laghad dá `fearainn_iontaofa` nó don `overwrite.cli.url`.",
"Could not check for JavaScript support via any of your `trusted_domains` nor `overwrite.cli.url`. This may be the result of a server-side DNS mismatch or outbound firewall rule. Please check manually if your webserver serves `.mjs` files using the JavaScript MIME type." : "Níorbh fhéidir tacaíocht JavaScript a fháil trí aon cheann de na `fearainn_ iontaofa` ná `overwrite.cli.url`. D'fhéadfadh sé seo a bheith mar thoradh ar mhímheaitseáil DNS ar thaobh an fhreastalaí nó riail balla dóiteáin amach. Seiceáil le do thoil de láimh an bhfreastalaíonn do fhreastalaí gréasáin ar chomhaid `.mjs` ag baint úsáide as an gcineál JavaScript MIME.",
- "Active accounts" : "Cuntais ghníomhacha",
- "None of your currently installed apps provide custom Text processing functionality." : "Ní sholáthraíonn aon cheann de na haipeanna atá suiteáilte agat faoi láthair feidhmiúlacht próiseála Téacs saincheaptha."
+ "Active accounts" : "Cuntais ghníomhacha"
},
"nplurals=5; plural=(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4);");
diff --git a/apps/settings/l10n/ga.json b/apps/settings/l10n/ga.json
index 19f3c9a6b23..e7bda19cacc 100644
--- a/apps/settings/l10n/ga.json
+++ b/apps/settings/l10n/ga.json
@@ -879,7 +879,6 @@
"SMTP Username" : "Ainm Úsáideora SMTP",
"To allow this check to run you have to make sure that your webserver can connect to itself. Therefor it must be able to resolve and connect to at least one its `trusted_domains` or the `overwrite.cli.url`." : "Le gur féidir an tseiceáil seo a rith caithfidh tú a chinntiú gur féidir le do fhreastalaí gréasáin nascadh leis féin. Mar sin caithfidh sé a bheith in ann réiteach agus ceangal a dhéanamh le ceann amháin ar a laghad dá `fearainn_iontaofa` nó don `overwrite.cli.url`.",
"Could not check for JavaScript support via any of your `trusted_domains` nor `overwrite.cli.url`. This may be the result of a server-side DNS mismatch or outbound firewall rule. Please check manually if your webserver serves `.mjs` files using the JavaScript MIME type." : "Níorbh fhéidir tacaíocht JavaScript a fháil trí aon cheann de na `fearainn_ iontaofa` ná `overwrite.cli.url`. D'fhéadfadh sé seo a bheith mar thoradh ar mhímheaitseáil DNS ar thaobh an fhreastalaí nó riail balla dóiteáin amach. Seiceáil le do thoil de láimh an bhfreastalaíonn do fhreastalaí gréasáin ar chomhaid `.mjs` ag baint úsáide as an gcineál JavaScript MIME.",
- "Active accounts" : "Cuntais ghníomhacha",
- "None of your currently installed apps provide custom Text processing functionality." : "Ní sholáthraíonn aon cheann de na haipeanna atá suiteáilte agat faoi láthair feidhmiúlacht próiseála Téacs saincheaptha."
+ "Active accounts" : "Cuntais ghníomhacha"
},"pluralForm" :"nplurals=5; plural=(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4);"
} \ No newline at end of file
diff --git a/apps/settings/l10n/gl.js b/apps/settings/l10n/gl.js
index d9802d5e8e8..9132d9f0247 100644
--- a/apps/settings/l10n/gl.js
+++ b/apps/settings/l10n/gl.js
@@ -881,7 +881,6 @@ OC.L10N.register(
"SMTP Username" : "Nome de usuario SMTP",
"To allow this check to run you have to make sure that your webserver can connect to itself. Therefor it must be able to resolve and connect to at least one its `trusted_domains` or the `overwrite.cli.url`." : "Para permitir que esta comprobación se execute, debe asegurarse de que o seu servidor web poida conectarse a si mesmo. Por tanto, debe ser quen de resolver e conectarse a polo menos un dos seus «trusted_domains» ou ao «overwrite.cli.url».",
"Could not check for JavaScript support via any of your `trusted_domains` nor `overwrite.cli.url`. This may be the result of a server-side DNS mismatch or outbound firewall rule. Please check manually if your webserver serves `.mjs` files using the JavaScript MIME type." : "Non foi posíbel comprobar a compatibilidade de JavaScript a través de ningún dos seus «trusted_domains» nin «overwrite.cli.url». Isto pode ser o resultado dunha falta de coincidencia de DNS do servidor ou dunha regra da devasa de saída. Comprobe manualmente se o seu servidor web serve ficheiros «.mjs» usando o tipo MIME JavaScript.",
- "Active accounts" : "Contas activas",
- "None of your currently installed apps provide custom Text processing functionality." : "Ningunha das aplicacións instaladas neste momento ofrece funcións de procesamento de texto personalizadas."
+ "Active accounts" : "Contas activas"
},
"nplurals=2; plural=(n != 1);");
diff --git a/apps/settings/l10n/gl.json b/apps/settings/l10n/gl.json
index 4b36dec1422..028a9f58de8 100644
--- a/apps/settings/l10n/gl.json
+++ b/apps/settings/l10n/gl.json
@@ -879,7 +879,6 @@
"SMTP Username" : "Nome de usuario SMTP",
"To allow this check to run you have to make sure that your webserver can connect to itself. Therefor it must be able to resolve and connect to at least one its `trusted_domains` or the `overwrite.cli.url`." : "Para permitir que esta comprobación se execute, debe asegurarse de que o seu servidor web poida conectarse a si mesmo. Por tanto, debe ser quen de resolver e conectarse a polo menos un dos seus «trusted_domains» ou ao «overwrite.cli.url».",
"Could not check for JavaScript support via any of your `trusted_domains` nor `overwrite.cli.url`. This may be the result of a server-side DNS mismatch or outbound firewall rule. Please check manually if your webserver serves `.mjs` files using the JavaScript MIME type." : "Non foi posíbel comprobar a compatibilidade de JavaScript a través de ningún dos seus «trusted_domains» nin «overwrite.cli.url». Isto pode ser o resultado dunha falta de coincidencia de DNS do servidor ou dunha regra da devasa de saída. Comprobe manualmente se o seu servidor web serve ficheiros «.mjs» usando o tipo MIME JavaScript.",
- "Active accounts" : "Contas activas",
- "None of your currently installed apps provide custom Text processing functionality." : "Ningunha das aplicacións instaladas neste momento ofrece funcións de procesamento de texto personalizadas."
+ "Active accounts" : "Contas activas"
},"pluralForm" :"nplurals=2; plural=(n != 1);"
} \ No newline at end of file
diff --git a/apps/settings/l10n/ja.js b/apps/settings/l10n/ja.js
index b1cf5975d8a..41f8a25976c 100644
--- a/apps/settings/l10n/ja.js
+++ b/apps/settings/l10n/ja.js
@@ -881,7 +881,6 @@ OC.L10N.register(
"SMTP Username" : "SMTPユーザー名",
"To allow this check to run you have to make sure that your webserver can connect to itself. Therefor it must be able to resolve and connect to at least one its `trusted_domains` or the `overwrite.cli.url`." : "このチェックを実行させるには、ウェブサーバが自分自身に接続できることを確認する必要があります。したがって、少なくとも `trusted_domains` または `overwrite.cli.url` を解決して接続できなければなりません。",
"Could not check for JavaScript support via any of your `trusted_domains` nor `overwrite.cli.url`. This may be the result of a server-side DNS mismatch or outbound firewall rule. Please check manually if your webserver serves `.mjs` files using the JavaScript MIME type." : "`trusted_domains` または `overwrite.cli.url` で JavaScript のサポートを確認できませんでした。これはサーバ側の DNS の不一致か、アウトバウンドファイアウォールルールの結果である可能性があります。お使いのウェブサーバーが JavaScript MIMEタイプを使用して `.mjs` ファイルを提供しているかどうかを手動で確認してください。",
- "Active accounts" : "アクティブなアカウント",
- "None of your currently installed apps provide custom Text processing functionality." : "現在インストールされているアプリは、カスタムテキスト処理機能を提供していません。"
+ "Active accounts" : "アクティブなアカウント"
},
"nplurals=1; plural=0;");
diff --git a/apps/settings/l10n/ja.json b/apps/settings/l10n/ja.json
index d462c65198e..8bd71fa4015 100644
--- a/apps/settings/l10n/ja.json
+++ b/apps/settings/l10n/ja.json
@@ -879,7 +879,6 @@
"SMTP Username" : "SMTPユーザー名",
"To allow this check to run you have to make sure that your webserver can connect to itself. Therefor it must be able to resolve and connect to at least one its `trusted_domains` or the `overwrite.cli.url`." : "このチェックを実行させるには、ウェブサーバが自分自身に接続できることを確認する必要があります。したがって、少なくとも `trusted_domains` または `overwrite.cli.url` を解決して接続できなければなりません。",
"Could not check for JavaScript support via any of your `trusted_domains` nor `overwrite.cli.url`. This may be the result of a server-side DNS mismatch or outbound firewall rule. Please check manually if your webserver serves `.mjs` files using the JavaScript MIME type." : "`trusted_domains` または `overwrite.cli.url` で JavaScript のサポートを確認できませんでした。これはサーバ側の DNS の不一致か、アウトバウンドファイアウォールルールの結果である可能性があります。お使いのウェブサーバーが JavaScript MIMEタイプを使用して `.mjs` ファイルを提供しているかどうかを手動で確認してください。",
- "Active accounts" : "アクティブなアカウント",
- "None of your currently installed apps provide custom Text processing functionality." : "現在インストールされているアプリは、カスタムテキスト処理機能を提供していません。"
+ "Active accounts" : "アクティブなアカウント"
},"pluralForm" :"nplurals=1; plural=0;"
} \ No newline at end of file
diff --git a/apps/settings/l10n/pt_BR.js b/apps/settings/l10n/pt_BR.js
index e5c3dd71364..ff011f733a0 100644
--- a/apps/settings/l10n/pt_BR.js
+++ b/apps/settings/l10n/pt_BR.js
@@ -331,6 +331,7 @@ OC.L10N.register(
"None of your currently installed apps provide image generation functionality" : "Nenhum dos seus aplicativos instalados atualmente oferece funcionalidade de geração de imagens",
"Text processing" : "Processamento de texto",
"Text processing tasks can be implemented by different apps. Here you can set which app should be used for which task." : "Tarefas de processamento de texto podem ser implementadas por diferentes aplicativos. Aqui você pode definir qual aplicativo deve ser usado para qual tarefa.",
+ "None of your currently installed apps provide text processing functionality using the Text Processing API." : "Nenhum dos seus aplicativos instalados oferece funcionalidade de processamento de texto usando a API Processamento de Texto.",
"Here you can decide which group can access certain sections of the administration settings." : "Aqui você pode decidir qual grupo pode acessar certas seções das configurações de administração.",
"None" : "Nenhuma",
"Unable to modify setting" : "Incapaz de modificar a configuração",
@@ -604,7 +605,7 @@ OC.L10N.register(
"Password change is disabled because the master key is disabled" : "A alteração de senha está desativada porque a chave mestra está desativada",
"New account" : "Nova conta",
"Display name" : "Nome de exibição",
- "Either password or email is required" : "Either password or email is required",
+ "Either password or email is required" : "É necessário email ou senha",
"Password (required)" : "Password (required)",
"Email (required)" : "Email (required)",
"Email" : "E-mail",
diff --git a/apps/settings/l10n/pt_BR.json b/apps/settings/l10n/pt_BR.json
index 8ca662b5ebb..c6dbca7bd3d 100644
--- a/apps/settings/l10n/pt_BR.json
+++ b/apps/settings/l10n/pt_BR.json
@@ -329,6 +329,7 @@
"None of your currently installed apps provide image generation functionality" : "Nenhum dos seus aplicativos instalados atualmente oferece funcionalidade de geração de imagens",
"Text processing" : "Processamento de texto",
"Text processing tasks can be implemented by different apps. Here you can set which app should be used for which task." : "Tarefas de processamento de texto podem ser implementadas por diferentes aplicativos. Aqui você pode definir qual aplicativo deve ser usado para qual tarefa.",
+ "None of your currently installed apps provide text processing functionality using the Text Processing API." : "Nenhum dos seus aplicativos instalados oferece funcionalidade de processamento de texto usando a API Processamento de Texto.",
"Here you can decide which group can access certain sections of the administration settings." : "Aqui você pode decidir qual grupo pode acessar certas seções das configurações de administração.",
"None" : "Nenhuma",
"Unable to modify setting" : "Incapaz de modificar a configuração",
@@ -602,7 +603,7 @@
"Password change is disabled because the master key is disabled" : "A alteração de senha está desativada porque a chave mestra está desativada",
"New account" : "Nova conta",
"Display name" : "Nome de exibição",
- "Either password or email is required" : "Either password or email is required",
+ "Either password or email is required" : "É necessário email ou senha",
"Password (required)" : "Password (required)",
"Email (required)" : "Email (required)",
"Email" : "E-mail",
diff --git a/apps/settings/l10n/ru.js b/apps/settings/l10n/ru.js
index 06c97dc780a..5164443758f 100644
--- a/apps/settings/l10n/ru.js
+++ b/apps/settings/l10n/ru.js
@@ -880,7 +880,6 @@ OC.L10N.register(
"SMTP Username" : "Пользователь SMTP",
"To allow this check to run you have to make sure that your webserver can connect to itself. Therefor it must be able to resolve and connect to at least one its `trusted_domains` or the `overwrite.cli.url`." : "Чтобы разрешить выполнение этой проверки, вы должны убедиться, что ваш веб-сервер может подключаться к самому себе. Для этого он должен иметь возможность разрешать и подключаться по крайней мере к одному из своих `trusted_domains\" или \"overwrite.cli.url\".",
"Could not check for JavaScript support via any of your `trusted_domains` nor `overwrite.cli.url`. This may be the result of a server-side DNS mismatch or outbound firewall rule. Please check manually if your webserver serves `.mjs` files using the JavaScript MIME type." : "Не удалось проверить поддержку JavaScript ни в одном из ваших `trusted_domains`, ни в `overwrite.cli.url`. Это может быть результатом несоответствия DNS на стороне сервера или правила исходящего брандмауэра. Пожалуйста, проверьте вручную, обслуживает ли ваш веб-сервер файлы `.mjs`, используя MIME-тип JavaScript.",
- "Active accounts" : "Активные учётные записи",
- "None of your currently installed apps provide custom Text processing functionality." : "Ни одно из установленных на данный момент приложений не предоставляет пользовательских функций обработки текста."
+ "Active accounts" : "Активные учётные записи"
},
"nplurals=4; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : n%10==0 || (n%10>=5 && n%10<=9) || (n%100>=11 && n%100<=14)? 2 : 3);");
diff --git a/apps/settings/l10n/ru.json b/apps/settings/l10n/ru.json
index 5dee87666d8..c8a19aff24f 100644
--- a/apps/settings/l10n/ru.json
+++ b/apps/settings/l10n/ru.json
@@ -878,7 +878,6 @@
"SMTP Username" : "Пользователь SMTP",
"To allow this check to run you have to make sure that your webserver can connect to itself. Therefor it must be able to resolve and connect to at least one its `trusted_domains` or the `overwrite.cli.url`." : "Чтобы разрешить выполнение этой проверки, вы должны убедиться, что ваш веб-сервер может подключаться к самому себе. Для этого он должен иметь возможность разрешать и подключаться по крайней мере к одному из своих `trusted_domains\" или \"overwrite.cli.url\".",
"Could not check for JavaScript support via any of your `trusted_domains` nor `overwrite.cli.url`. This may be the result of a server-side DNS mismatch or outbound firewall rule. Please check manually if your webserver serves `.mjs` files using the JavaScript MIME type." : "Не удалось проверить поддержку JavaScript ни в одном из ваших `trusted_domains`, ни в `overwrite.cli.url`. Это может быть результатом несоответствия DNS на стороне сервера или правила исходящего брандмауэра. Пожалуйста, проверьте вручную, обслуживает ли ваш веб-сервер файлы `.mjs`, используя MIME-тип JavaScript.",
- "Active accounts" : "Активные учётные записи",
- "None of your currently installed apps provide custom Text processing functionality." : "Ни одно из установленных на данный момент приложений не предоставляет пользовательских функций обработки текста."
+ "Active accounts" : "Активные учётные записи"
},"pluralForm" :"nplurals=4; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : n%10==0 || (n%10>=5 && n%10<=9) || (n%100>=11 && n%100<=14)? 2 : 3);"
} \ No newline at end of file
diff --git a/apps/settings/l10n/tr.js b/apps/settings/l10n/tr.js
index 73bbefecc63..8b3b8f12d7c 100644
--- a/apps/settings/l10n/tr.js
+++ b/apps/settings/l10n/tr.js
@@ -881,7 +881,6 @@ OC.L10N.register(
"SMTP Username" : "SMTP kullanıcı adı",
"To allow this check to run you have to make sure that your webserver can connect to itself. Therefor it must be able to resolve and connect to at least one its `trusted_domains` or the `overwrite.cli.url`." : "Bu denetimi çalıştırabilmek için site sunucunuzun kendisine bağlanabildiğinden emin olmanız gerekir. Bu nedenle, `trusted_domains` ya da `overwrite.cli.url` değerlerinden en az birini çözümleyebilmeli ve bunlara bağlanabilmelidir.",
"Could not check for JavaScript support via any of your `trusted_domains` nor `overwrite.cli.url`. This may be the result of a server-side DNS mismatch or outbound firewall rule. Please check manually if your webserver serves `.mjs` files using the JavaScript MIME type." : "`trusted_domains` ya da `overwrite.cli.url` değerlerinden biri ile JavaScript desteği olup olmadığ denetlenemedi. Bu durum, sunucu tarafı DNS uyuşmazlığından ya da giden güvenlik duvarı kuralından kaynaklanıyor olabilir. Lütfen site sunucunuzun JavaScript MIME türünü kullanarak `.mjs` dosyalarını sunup sunmadığını el ile denetleyin.",
- "Active accounts" : "Etkin hesaplar",
- "None of your currently installed apps provide custom Text processing functionality." : "Şu anda kurulu uygulamaların hiç birinde özel metin işleme özelliği yok"
+ "Active accounts" : "Etkin hesaplar"
},
"nplurals=2; plural=(n > 1);");
diff --git a/apps/settings/l10n/tr.json b/apps/settings/l10n/tr.json
index 397587e4b9a..eac186592f1 100644
--- a/apps/settings/l10n/tr.json
+++ b/apps/settings/l10n/tr.json
@@ -879,7 +879,6 @@
"SMTP Username" : "SMTP kullanıcı adı",
"To allow this check to run you have to make sure that your webserver can connect to itself. Therefor it must be able to resolve and connect to at least one its `trusted_domains` or the `overwrite.cli.url`." : "Bu denetimi çalıştırabilmek için site sunucunuzun kendisine bağlanabildiğinden emin olmanız gerekir. Bu nedenle, `trusted_domains` ya da `overwrite.cli.url` değerlerinden en az birini çözümleyebilmeli ve bunlara bağlanabilmelidir.",
"Could not check for JavaScript support via any of your `trusted_domains` nor `overwrite.cli.url`. This may be the result of a server-side DNS mismatch or outbound firewall rule. Please check manually if your webserver serves `.mjs` files using the JavaScript MIME type." : "`trusted_domains` ya da `overwrite.cli.url` değerlerinden biri ile JavaScript desteği olup olmadığ denetlenemedi. Bu durum, sunucu tarafı DNS uyuşmazlığından ya da giden güvenlik duvarı kuralından kaynaklanıyor olabilir. Lütfen site sunucunuzun JavaScript MIME türünü kullanarak `.mjs` dosyalarını sunup sunmadığını el ile denetleyin.",
- "Active accounts" : "Etkin hesaplar",
- "None of your currently installed apps provide custom Text processing functionality." : "Şu anda kurulu uygulamaların hiç birinde özel metin işleme özelliği yok"
+ "Active accounts" : "Etkin hesaplar"
},"pluralForm" :"nplurals=2; plural=(n > 1);"
} \ No newline at end of file
diff --git a/apps/settings/l10n/zh_HK.js b/apps/settings/l10n/zh_HK.js
index bf7ce9b32d0..65c9e3b61f2 100644
--- a/apps/settings/l10n/zh_HK.js
+++ b/apps/settings/l10n/zh_HK.js
@@ -881,7 +881,6 @@ OC.L10N.register(
"SMTP Username" : "SMTP 用戶名稱",
"To allow this check to run you have to make sure that your webserver can connect to itself. Therefor it must be able to resolve and connect to at least one its `trusted_domains` or the `overwrite.cli.url`." : "要執行此檢查,您必須確保您的網路伺服器可以連線到其自身。因此,其必須至少能解析並連線至 `trusted_domains` 或 `overwrite.cli.url` 其中一個。",
"Could not check for JavaScript support via any of your `trusted_domains` nor `overwrite.cli.url`. This may be the result of a server-side DNS mismatch or outbound firewall rule. Please check manually if your webserver serves `.mjs` files using the JavaScript MIME type." : "無法透過您的任何「trusted_domains」或「overwrite.cli.url」檢查 JavaScript 支援。這可能是伺服器端 DNS 不符或連出防火牆規則造成的。請手動檢查您的網頁伺服器是否使用 JavaScript MIME 類型提供「.mjs」檔案。",
- "Active accounts" : "活躍帳戶",
- "None of your currently installed apps provide custom Text processing functionality." : "您目前安裝的應用程式均不提供自訂文字處理功能。"
+ "Active accounts" : "活躍帳戶"
},
"nplurals=1; plural=0;");
diff --git a/apps/settings/l10n/zh_HK.json b/apps/settings/l10n/zh_HK.json
index 48a2dca4d09..10000e9c032 100644
--- a/apps/settings/l10n/zh_HK.json
+++ b/apps/settings/l10n/zh_HK.json
@@ -879,7 +879,6 @@
"SMTP Username" : "SMTP 用戶名稱",
"To allow this check to run you have to make sure that your webserver can connect to itself. Therefor it must be able to resolve and connect to at least one its `trusted_domains` or the `overwrite.cli.url`." : "要執行此檢查,您必須確保您的網路伺服器可以連線到其自身。因此,其必須至少能解析並連線至 `trusted_domains` 或 `overwrite.cli.url` 其中一個。",
"Could not check for JavaScript support via any of your `trusted_domains` nor `overwrite.cli.url`. This may be the result of a server-side DNS mismatch or outbound firewall rule. Please check manually if your webserver serves `.mjs` files using the JavaScript MIME type." : "無法透過您的任何「trusted_domains」或「overwrite.cli.url」檢查 JavaScript 支援。這可能是伺服器端 DNS 不符或連出防火牆規則造成的。請手動檢查您的網頁伺服器是否使用 JavaScript MIME 類型提供「.mjs」檔案。",
- "Active accounts" : "活躍帳戶",
- "None of your currently installed apps provide custom Text processing functionality." : "您目前安裝的應用程式均不提供自訂文字處理功能。"
+ "Active accounts" : "活躍帳戶"
},"pluralForm" :"nplurals=1; plural=0;"
} \ No newline at end of file
diff --git a/apps/settings/l10n/zh_TW.js b/apps/settings/l10n/zh_TW.js
index de353c03ba2..e751427112e 100644
--- a/apps/settings/l10n/zh_TW.js
+++ b/apps/settings/l10n/zh_TW.js
@@ -881,7 +881,6 @@ OC.L10N.register(
"SMTP Username" : "SMTP 使用者名稱",
"To allow this check to run you have to make sure that your webserver can connect to itself. Therefor it must be able to resolve and connect to at least one its `trusted_domains` or the `overwrite.cli.url`." : "要執行此檢查,您必須確保您的網路伺服器可以連線到其自身。因此,其必須至少能解析並連線至 `trusted_domains` 或 `overwrite.cli.url` 其中一個。",
"Could not check for JavaScript support via any of your `trusted_domains` nor `overwrite.cli.url`. This may be the result of a server-side DNS mismatch or outbound firewall rule. Please check manually if your webserver serves `.mjs` files using the JavaScript MIME type." : "無法透過您的任何「trusted_domains」或「overwrite.cli.url」檢查 JavaScript 支援。這可能是伺服器端 DNS 不符或連出防火牆規則造成的。請手動檢查您的網頁伺服器是否使用 JavaScript MIME 類型提供「.mjs」檔案。",
- "Active accounts" : "活躍帳號",
- "None of your currently installed apps provide custom Text processing functionality." : "您目前安裝的應用程式均不提供自訂文字處理功能。"
+ "Active accounts" : "活躍帳號"
},
"nplurals=1; plural=0;");
diff --git a/apps/settings/l10n/zh_TW.json b/apps/settings/l10n/zh_TW.json
index 77204dc1e76..91b5ff49f06 100644
--- a/apps/settings/l10n/zh_TW.json
+++ b/apps/settings/l10n/zh_TW.json
@@ -879,7 +879,6 @@
"SMTP Username" : "SMTP 使用者名稱",
"To allow this check to run you have to make sure that your webserver can connect to itself. Therefor it must be able to resolve and connect to at least one its `trusted_domains` or the `overwrite.cli.url`." : "要執行此檢查,您必須確保您的網路伺服器可以連線到其自身。因此,其必須至少能解析並連線至 `trusted_domains` 或 `overwrite.cli.url` 其中一個。",
"Could not check for JavaScript support via any of your `trusted_domains` nor `overwrite.cli.url`. This may be the result of a server-side DNS mismatch or outbound firewall rule. Please check manually if your webserver serves `.mjs` files using the JavaScript MIME type." : "無法透過您的任何「trusted_domains」或「overwrite.cli.url」檢查 JavaScript 支援。這可能是伺服器端 DNS 不符或連出防火牆規則造成的。請手動檢查您的網頁伺服器是否使用 JavaScript MIME 類型提供「.mjs」檔案。",
- "Active accounts" : "活躍帳號",
- "None of your currently installed apps provide custom Text processing functionality." : "您目前安裝的應用程式均不提供自訂文字處理功能。"
+ "Active accounts" : "活躍帳號"
},"pluralForm" :"nplurals=1; plural=0;"
} \ No newline at end of file
diff --git a/apps/settings/tests/Activity/SecurityFilterTest.php b/apps/settings/tests/Activity/SecurityFilterTest.php
index 637c717da02..f3f94df3d21 100644
--- a/apps/settings/tests/Activity/SecurityFilterTest.php
+++ b/apps/settings/tests/Activity/SecurityFilterTest.php
@@ -31,15 +31,15 @@ class SecurityFilterTest extends TestCase {
$this->filter = new SecurityFilter($this->urlGenerator, $this->l10n);
}
- public function testAllowedApps() {
+ public function testAllowedApps(): void {
$this->assertEquals([], $this->filter->allowedApps());
}
- public function testFilterTypes() {
+ public function testFilterTypes(): void {
$this->assertEquals(['security'], $this->filter->filterTypes(['comments', 'security']));
}
- public function testGetIcon() {
+ public function testGetIcon(): void {
$this->urlGenerator->expects($this->once())
->method('imagePath')
->with('core', 'actions/password.svg')
@@ -51,11 +51,11 @@ class SecurityFilterTest extends TestCase {
$this->assertEquals('abs/path/to/icon.svg', $this->filter->getIcon());
}
- public function testGetIdentifier() {
+ public function testGetIdentifier(): void {
$this->assertEquals('security', $this->filter->getIdentifier());
}
- public function testGetName() {
+ public function testGetName(): void {
$this->l10n->expects($this->once())
->method('t')
->with('Security')
@@ -63,7 +63,7 @@ class SecurityFilterTest extends TestCase {
$this->assertEquals('translated', $this->filter->getName());
}
- public function testGetPriority() {
+ public function testGetPriority(): void {
$this->assertEquals(30, $this->filter->getPriority());
}
}
diff --git a/apps/settings/tests/Activity/SecurityProviderTest.php b/apps/settings/tests/Activity/SecurityProviderTest.php
index 9d10b1e596e..b00c62281cc 100644
--- a/apps/settings/tests/Activity/SecurityProviderTest.php
+++ b/apps/settings/tests/Activity/SecurityProviderTest.php
@@ -39,7 +39,7 @@ class SecurityProviderTest extends TestCase {
$this->provider = new SecurityProvider($this->l10n, $this->urlGenerator, $this->activityManager);
}
- public function testParseUnrelated() {
+ public function testParseUnrelated(): void {
$lang = 'ru';
$event = $this->createMock(IEvent::class);
$event->expects($this->once())
@@ -60,7 +60,7 @@ class SecurityProviderTest extends TestCase {
/**
* @dataProvider subjectData
*/
- public function testParse($subject) {
+ public function testParse($subject): void {
$lang = 'ru';
$event = $this->createMock(IEvent::class);
$l = $this->createMock(IL10N::class);
@@ -96,7 +96,7 @@ class SecurityProviderTest extends TestCase {
$this->provider->parse($lang, $event);
}
- public function testParseInvalidSubject() {
+ public function testParseInvalidSubject(): void {
$lang = 'ru';
$l = $this->createMock(IL10N::class);
$event = $this->createMock(IEvent::class);
diff --git a/apps/settings/tests/Activity/SecuritySettingTest.php b/apps/settings/tests/Activity/SecuritySettingTest.php
index dd28d757e72..1b2b0e3361c 100644
--- a/apps/settings/tests/Activity/SecuritySettingTest.php
+++ b/apps/settings/tests/Activity/SecuritySettingTest.php
@@ -23,19 +23,19 @@ class SecuritySettingTest extends TestCase {
$this->setting = new SecuritySetting($this->l10n);
}
- public function testCanChangeMail() {
+ public function testCanChangeMail(): void {
$this->assertFalse($this->setting->canChangeMail());
}
- public function testCanChangeStream() {
+ public function testCanChangeStream(): void {
$this->assertFalse($this->setting->canChangeStream());
}
- public function testGetIdentifier() {
+ public function testGetIdentifier(): void {
$this->assertEquals('security', $this->setting->getIdentifier());
}
- public function testGetName() {
+ public function testGetName(): void {
$this->l10n->expects($this->once())
->method('t')
->with('Security')
@@ -43,11 +43,11 @@ class SecuritySettingTest extends TestCase {
$this->assertEquals('Sicherheit', $this->setting->getName());
}
- public function testGetPriority() {
+ public function testGetPriority(): void {
$this->assertEquals(30, $this->setting->getPriority());
}
- public function testIsDefaultEnabled() {
+ public function testIsDefaultEnabled(): void {
$this->assertTrue($this->setting->isDefaultEnabledMail());
$this->assertTrue($this->setting->isDefaultEnabledStream());
}
diff --git a/apps/settings/tests/AppInfo/ApplicationTest.php b/apps/settings/tests/AppInfo/ApplicationTest.php
index 60c37e42015..677efdc64bf 100644
--- a/apps/settings/tests/AppInfo/ApplicationTest.php
+++ b/apps/settings/tests/AppInfo/ApplicationTest.php
@@ -38,7 +38,7 @@ class ApplicationTest extends TestCase {
$this->container = $this->app->getContainer();
}
- public function testContainerAppName() {
+ public function testContainerAppName(): void {
$this->app = new Application();
$this->assertEquals('settings', $this->container->getAppName());
}
@@ -62,7 +62,7 @@ class ApplicationTest extends TestCase {
* @param string $service
* @param string $expected
*/
- public function testContainerQuery($service, $expected) {
+ public function testContainerQuery($service, $expected): void {
$this->assertTrue($this->container->query($service) instanceof $expected);
}
}
diff --git a/apps/settings/tests/Controller/AdminSettingsControllerTest.php b/apps/settings/tests/Controller/AdminSettingsControllerTest.php
index 578348a3031..60ba5e0750e 100644
--- a/apps/settings/tests/Controller/AdminSettingsControllerTest.php
+++ b/apps/settings/tests/Controller/AdminSettingsControllerTest.php
@@ -87,7 +87,7 @@ class AdminSettingsControllerTest extends TestCase {
parent::tearDown();
}
- public function testIndex() {
+ public function testIndex(): void {
$user = $this->createMock(IUser::class);
$this->userSession
->method('getUser')
diff --git a/apps/settings/tests/Controller/AppSettingsControllerTest.php b/apps/settings/tests/Controller/AppSettingsControllerTest.php
index 71d263ac935..c219ee2fc9f 100644
--- a/apps/settings/tests/Controller/AppSettingsControllerTest.php
+++ b/apps/settings/tests/Controller/AppSettingsControllerTest.php
@@ -116,7 +116,7 @@ class AppSettingsControllerTest extends TestCase {
);
}
- public function testListCategories() {
+ public function testListCategories(): void {
$this->installer->expects($this->any())
->method('isUpdateAvailable')
->willReturn(false);
@@ -171,7 +171,7 @@ class AppSettingsControllerTest extends TestCase {
$this->assertEquals($expected, $this->appSettingsController->listCategories());
}
- public function testViewApps() {
+ public function testViewApps(): void {
$this->bundleFetcher->expects($this->once())->method('getBundles')->willReturn([]);
$this->installer->expects($this->any())
->method('isUpdateAvailable')
@@ -204,7 +204,7 @@ class AppSettingsControllerTest extends TestCase {
$this->assertEquals($expected, $this->appSettingsController->viewApps());
}
- public function testViewAppsAppstoreNotEnabled() {
+ public function testViewAppsAppstoreNotEnabled(): void {
$this->installer->expects($this->any())
->method('isUpdateAvailable')
->willReturn(false);
diff --git a/apps/settings/tests/Controller/AuthSettingsControllerTest.php b/apps/settings/tests/Controller/AuthSettingsControllerTest.php
index a054d5e306c..13213992d94 100644
--- a/apps/settings/tests/Controller/AuthSettingsControllerTest.php
+++ b/apps/settings/tests/Controller/AuthSettingsControllerTest.php
@@ -74,7 +74,7 @@ class AuthSettingsControllerTest extends TestCase {
);
}
- public function testCreate() {
+ public function testCreate(): void {
$name = 'Nexus 4';
$sessionToken = $this->createMock(IToken::class);
$deviceToken = $this->createMock(IToken::class);
@@ -123,7 +123,7 @@ class AuthSettingsControllerTest extends TestCase {
$this->assertEquals($expected, $response->getData());
}
- public function testCreateSessionNotAvailable() {
+ public function testCreateSessionNotAvailable(): void {
$name = 'personal phone';
$this->session->expects($this->once())
@@ -136,7 +136,7 @@ class AuthSettingsControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->create($name));
}
- public function testCreateInvalidToken() {
+ public function testCreateInvalidToken(): void {
$name = 'Company IPhone';
$this->session->expects($this->once())
@@ -153,7 +153,7 @@ class AuthSettingsControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->create($name));
}
- public function testDestroy() {
+ public function testDestroy(): void {
$tokenId = 124;
$token = $this->createMock(PublicKeyToken::class);
@@ -175,7 +175,7 @@ class AuthSettingsControllerTest extends TestCase {
$this->assertEquals([], $this->controller->destroy($tokenId));
}
- public function testDestroyExpired() {
+ public function testDestroyExpired(): void {
$tokenId = 124;
$token = $this->createMock(PublicKeyToken::class);
@@ -199,7 +199,7 @@ class AuthSettingsControllerTest extends TestCase {
$this->assertSame([], $this->controller->destroy($tokenId));
}
- public function testDestroyWrongUser() {
+ public function testDestroyWrongUser(): void {
$tokenId = 124;
$token = $this->createMock(PublicKeyToken::class);
@@ -331,7 +331,7 @@ class AuthSettingsControllerTest extends TestCase {
$this->assertSame([], $this->controller->update($tokenId, [IToken::SCOPE_FILESYSTEM => true], 'App password'));
}
- public function testUpdateExpired() {
+ public function testUpdateExpired(): void {
$tokenId = 42;
$token = $this->createMock(PublicKeyToken::class);
@@ -351,7 +351,7 @@ class AuthSettingsControllerTest extends TestCase {
$this->assertSame([], $this->controller->update($tokenId, [IToken::SCOPE_FILESYSTEM => true], 'App password'));
}
- public function testUpdateTokenWrongUser() {
+ public function testUpdateTokenWrongUser(): void {
$tokenId = 42;
$token = $this->createMock(PublicKeyToken::class);
@@ -371,7 +371,7 @@ class AuthSettingsControllerTest extends TestCase {
$this->assertSame(\OCP\AppFramework\Http::STATUS_NOT_FOUND, $response->getStatus());
}
- public function testUpdateTokenNonExisting() {
+ public function testUpdateTokenNonExisting(): void {
$this->tokenProvider->expects($this->once())
->method('getTokenById')
->with($this->equalTo(42))
diff --git a/apps/settings/tests/Controller/CheckSetupControllerTest.php b/apps/settings/tests/Controller/CheckSetupControllerTest.php
index 77ca9f257f7..6111cbf249b 100644
--- a/apps/settings/tests/Controller/CheckSetupControllerTest.php
+++ b/apps/settings/tests/Controller/CheckSetupControllerTest.php
@@ -84,7 +84,7 @@ class CheckSetupControllerTest extends TestCase {
])->getMock();
}
- public function testCheck() {
+ public function testCheck(): void {
$this->config->expects($this->any())
->method('getAppValue')
->willReturnMap([
@@ -142,7 +142,7 @@ class CheckSetupControllerTest extends TestCase {
$this->assertEquals($expected, $this->checkSetupController->check());
}
- public function testRescanFailedIntegrityCheck() {
+ public function testRescanFailedIntegrityCheck(): void {
$this->checker
->expects($this->once())
->method('runInstanceVerification');
@@ -156,7 +156,7 @@ class CheckSetupControllerTest extends TestCase {
$this->assertEquals($expected, $this->checkSetupController->rescanFailedIntegrityCheck());
}
- public function testGetFailedIntegrityCheckDisabled() {
+ public function testGetFailedIntegrityCheckDisabled(): void {
$this->checker
->expects($this->once())
->method('isCodeCheckEnforced')
@@ -167,7 +167,7 @@ class CheckSetupControllerTest extends TestCase {
}
- public function testGetFailedIntegrityCheckFilesWithNoErrorsFound() {
+ public function testGetFailedIntegrityCheckFilesWithNoErrorsFound(): void {
$this->checker
->expects($this->once())
->method('isCodeCheckEnforced')
@@ -187,7 +187,7 @@ class CheckSetupControllerTest extends TestCase {
$this->assertEquals($expected, $this->checkSetupController->getFailedIntegrityCheckFiles());
}
- public function testGetFailedIntegrityCheckFilesWithSomeErrorsFound() {
+ public function testGetFailedIntegrityCheckFilesWithSomeErrorsFound(): void {
$this->checker
->expects($this->once())
->method('isCodeCheckEnforced')
diff --git a/apps/settings/tests/Controller/DelegationControllerTest.php b/apps/settings/tests/Controller/DelegationControllerTest.php
index 2d03e316ce9..5994ddf298d 100644
--- a/apps/settings/tests/Controller/DelegationControllerTest.php
+++ b/apps/settings/tests/Controller/DelegationControllerTest.php
@@ -32,7 +32,7 @@ class DelegationControllerTest extends TestCase {
);
}
- public function testSaveSettings() {
+ public function testSaveSettings(): void {
$setting = 'MySecretSetting';
$oldGroups = [];
$oldGroups[] = AuthorizedGroup::fromParams(['groupId' => 'hello', 'class' => $setting]);
diff --git a/apps/settings/tests/Controller/MailSettingsControllerTest.php b/apps/settings/tests/Controller/MailSettingsControllerTest.php
index 52642884d23..d4d1e319a8e 100644
--- a/apps/settings/tests/Controller/MailSettingsControllerTest.php
+++ b/apps/settings/tests/Controller/MailSettingsControllerTest.php
@@ -58,7 +58,7 @@ class MailSettingsControllerTest extends \Test\TestCase {
);
}
- public function testSetMailSettings() {
+ public function testSetMailSettings(): void {
$this->config->expects($this->exactly(2))
->method('setSystemValues')
->withConsecutive(
@@ -113,7 +113,7 @@ class MailSettingsControllerTest extends \Test\TestCase {
$this->assertSame(Http::STATUS_OK, $response->getStatus());
}
- public function testStoreCredentials() {
+ public function testStoreCredentials(): void {
$this->config
->expects($this->once())
->method('setSystemValues')
@@ -126,7 +126,7 @@ class MailSettingsControllerTest extends \Test\TestCase {
$this->assertSame(Http::STATUS_OK, $response->getStatus());
}
- public function testSendTestMail() {
+ public function testSendTestMail(): void {
$user = $this->createMock(User::class);
$user->expects($this->any())
->method('getUID')
diff --git a/apps/settings/tests/Controller/TwoFactorSettingsControllerTest.php b/apps/settings/tests/Controller/TwoFactorSettingsControllerTest.php
index 91b532b05f8..c34b2907dfd 100644
--- a/apps/settings/tests/Controller/TwoFactorSettingsControllerTest.php
+++ b/apps/settings/tests/Controller/TwoFactorSettingsControllerTest.php
@@ -37,7 +37,7 @@ class TwoFactorSettingsControllerTest extends TestCase {
);
}
- public function testIndex() {
+ public function testIndex(): void {
$state = new EnforcementState(true);
$this->mandatoryTwoFactor->expects($this->once())
->method('getState')
@@ -49,7 +49,7 @@ class TwoFactorSettingsControllerTest extends TestCase {
$this->assertEquals($expected, $resp);
}
- public function testUpdate() {
+ public function testUpdate(): void {
$state = new EnforcementState(true);
$this->mandatoryTwoFactor->expects($this->once())
->method('setState')
diff --git a/apps/settings/tests/Controller/UsersControllerTest.php b/apps/settings/tests/Controller/UsersControllerTest.php
index 93dfd4c4cd6..3a6b54dbeb9 100644
--- a/apps/settings/tests/Controller/UsersControllerTest.php
+++ b/apps/settings/tests/Controller/UsersControllerTest.php
@@ -249,7 +249,7 @@ class UsersControllerTest extends \Test\TestCase {
* @param bool $validEmail
* @param $expectedStatus
*/
- public function testSetUserSettings($email, $validEmail, $expectedStatus) {
+ public function testSetUserSettings($email, $validEmail, $expectedStatus): void {
$controller = $this->getController(false, ['saveUserSettings']);
$user = $this->createMock(IUser::class);
$user->method('getUID')->willReturn('johndoe');
@@ -303,7 +303,7 @@ class UsersControllerTest extends \Test\TestCase {
];
}
- public function testSetUserSettingsWhenUserDisplayNameChangeNotAllowed() {
+ public function testSetUserSettingsWhenUserDisplayNameChangeNotAllowed(): void {
$controller = $this->getController(false, ['saveUserSettings']);
$avatarScope = IAccountManager::SCOPE_PUBLISHED;
@@ -401,7 +401,7 @@ class UsersControllerTest extends \Test\TestCase {
);
}
- public function testSetUserSettingsWhenFederatedFilesharingNotEnabled() {
+ public function testSetUserSettingsWhenFederatedFilesharingNotEnabled(): void {
$controller = $this->getController(false, ['saveUserSettings']);
$user = $this->createMock(IUser::class);
$user->method('getUID')->willReturn('johndoe');
@@ -488,7 +488,7 @@ class UsersControllerTest extends \Test\TestCase {
* @param string $property
* @param string $propertyValue
*/
- public function testSetUserSettingsSubset($property, $propertyValue) {
+ public function testSetUserSettingsSubset($property, $propertyValue): void {
$controller = $this->getController(false, ['saveUserSettings']);
$user = $this->createMock(IUser::class);
$user->method('getUID')->willReturn('johndoe');
@@ -619,7 +619,7 @@ class UsersControllerTest extends \Test\TestCase {
public function testSaveUserSettings($data,
$oldEmailAddress,
$oldDisplayName
- ) {
+ ): void {
$controller = $this->getController();
$user = $this->createMock(IUser::class);
@@ -742,7 +742,7 @@ class UsersControllerTest extends \Test\TestCase {
string $oldDisplayName,
bool $setDisplayNameResult,
bool $canChangeEmail
- ) {
+ ): void {
$this->expectException(ForbiddenException::class);
$controller = $this->getController();
@@ -826,7 +826,7 @@ class UsersControllerTest extends \Test\TestCase {
*
* @dataProvider dataTestGetVerificationCode
*/
- public function testGetVerificationCode($account, $type, $dataBefore, $expectedData, $onlyVerificationCode) {
+ public function testGetVerificationCode($account, $type, $dataBefore, $expectedData, $onlyVerificationCode): void {
$message = 'Use my Federated Cloud ID to share with me: user@nextcloud.com';
$signature = 'theSignature';
@@ -912,7 +912,7 @@ class UsersControllerTest extends \Test\TestCase {
/**
* test get verification code in case no valid user was given
*/
- public function testGetVerificationCodeInvalidUser() {
+ public function testGetVerificationCodeInvalidUser(): void {
$controller = $this->getController();
$this->userSession->expects($this->once())->method('getUser')->willReturn(null);
$result = $controller->getVerificationCode('account', false);
@@ -931,7 +931,7 @@ class UsersControllerTest extends \Test\TestCase {
public function testCanAdminChangeUserPasswords($encryptionEnabled,
$encryptionModuleLoaded,
$masterKeyEnabled,
- $expected) {
+ $expected): void {
$controller = $this->getController();
$this->encryptionManager->expects($this->any())
diff --git a/apps/settings/tests/Mailer/NewUserMailHelperTest.php b/apps/settings/tests/Mailer/NewUserMailHelperTest.php
index f3e21c1d401..badd56cf600 100644
--- a/apps/settings/tests/Mailer/NewUserMailHelperTest.php
+++ b/apps/settings/tests/Mailer/NewUserMailHelperTest.php
@@ -102,7 +102,7 @@ class NewUserMailHelperTest extends TestCase {
);
}
- public function testGenerateTemplateWithPasswordResetToken() {
+ public function testGenerateTemplateWithPasswordResetToken(): void {
$this->secureRandom
->expects($this->once())
->method('generate')
@@ -357,7 +357,7 @@ EOF;
$this->assertSame(\OC\Mail\EMailTemplate::class, get_class($result));
}
- public function testGenerateTemplateWithoutPasswordResetToken() {
+ public function testGenerateTemplateWithoutPasswordResetToken(): void {
$this->urlGenerator
->expects($this->any())
->method('getAbsoluteURL')
@@ -593,7 +593,7 @@ EOF;
$this->assertSame(\OC\Mail\EMailTemplate::class, get_class($result));
}
- public function testGenerateTemplateWithoutUserId() {
+ public function testGenerateTemplateWithoutUserId(): void {
$this->urlGenerator
->expects($this->any())
->method('getAbsoluteURL')
@@ -816,7 +816,7 @@ EOF;
$this->assertSame(\OC\Mail\EMailTemplate::class, get_class($result));
}
- public function testSendMail() {
+ public function testSendMail(): void {
/** @var IUser|\PHPUnit\Framework\MockObject\MockObject $user */
$user = $this->createMock(IUser::class);
$user
diff --git a/apps/settings/tests/Middleware/SubadminMiddlewareTest.php b/apps/settings/tests/Middleware/SubadminMiddlewareTest.php
index 1a832c528bf..c4672a06d49 100644
--- a/apps/settings/tests/Middleware/SubadminMiddlewareTest.php
+++ b/apps/settings/tests/Middleware/SubadminMiddlewareTest.php
@@ -44,7 +44,7 @@ class SubadminMiddlewareTest extends \Test\TestCase {
}
- public function testBeforeControllerAsUserWithExemption() {
+ public function testBeforeControllerAsUserWithExemption(): void {
$this->expectException(\OC\AppFramework\Middleware\Security\Exceptions\NotAdminException::class);
$this->reflector
@@ -58,7 +58,7 @@ class SubadminMiddlewareTest extends \Test\TestCase {
}
- public function testBeforeControllerAsUserWithoutExemption() {
+ public function testBeforeControllerAsUserWithoutExemption(): void {
$this->reflector
->expects($this->once())
->method('hasAnnotation')
@@ -67,7 +67,7 @@ class SubadminMiddlewareTest extends \Test\TestCase {
$this->subadminMiddleware->beforeController($this->controller, 'foo');
}
- public function testBeforeControllerAsSubAdminWithoutExemption() {
+ public function testBeforeControllerAsSubAdminWithoutExemption(): void {
$this->reflector
->expects($this->exactly(2))
->method('hasAnnotation')
@@ -78,7 +78,7 @@ class SubadminMiddlewareTest extends \Test\TestCase {
$this->subadminMiddlewareAsSubAdmin->beforeController($this->controller, 'foo');
}
- public function testBeforeControllerAsSubAdminWithExemption() {
+ public function testBeforeControllerAsSubAdminWithExemption(): void {
$this->reflector
->expects($this->once())
->method('hasAnnotation')
@@ -87,14 +87,14 @@ class SubadminMiddlewareTest extends \Test\TestCase {
$this->subadminMiddlewareAsSubAdmin->beforeController($this->controller, 'foo');
}
- public function testAfterNotAdminException() {
+ public function testAfterNotAdminException(): void {
$expectedResponse = new TemplateResponse('core', '403', [], 'guest');
$expectedResponse->setStatus(403);
$this->assertEquals($expectedResponse, $this->subadminMiddleware->afterException($this->controller, 'foo', new NotAdminException('')));
}
- public function testAfterRegularException() {
+ public function testAfterRegularException(): void {
$this->expectException(\Exception::class);
$expectedResponse = new TemplateResponse('core', '403', [], 'guest');
diff --git a/apps/settings/tests/Settings/Admin/MailTest.php b/apps/settings/tests/Settings/Admin/MailTest.php
index cab0596ad44..021dbac241b 100644
--- a/apps/settings/tests/Settings/Admin/MailTest.php
+++ b/apps/settings/tests/Settings/Admin/MailTest.php
@@ -30,7 +30,7 @@ class MailTest extends TestCase {
);
}
- public function testGetForm() {
+ public function testGetForm(): void {
$this->config
->expects($this->any())
->method('getSystemValue')
@@ -69,11 +69,11 @@ class MailTest extends TestCase {
$this->assertEquals($expected, $this->admin->getForm());
}
- public function testGetSection() {
+ public function testGetSection(): void {
$this->assertSame('server', $this->admin->getSection());
}
- public function testGetPriority() {
+ public function testGetPriority(): void {
$this->assertSame(10, $this->admin->getPriority());
}
}
diff --git a/apps/settings/tests/Settings/Admin/SecurityTest.php b/apps/settings/tests/Settings/Admin/SecurityTest.php
index 4af8ad496ce..95b5e988397 100644
--- a/apps/settings/tests/Settings/Admin/SecurityTest.php
+++ b/apps/settings/tests/Settings/Admin/SecurityTest.php
@@ -57,7 +57,7 @@ class SecurityTest extends TestCase {
* @dataProvider encryptionSettingsProvider
* @param bool $enabled
*/
- public function testGetFormWithOnlyOneBackend($enabled) {
+ public function testGetFormWithOnlyOneBackend($enabled): void {
$this->manager
->expects($this->once())
->method('isEnabled')
@@ -87,7 +87,7 @@ class SecurityTest extends TestCase {
* @dataProvider encryptionSettingsProvider
* @param bool $enabled
*/
- public function testGetFormWithMultipleBackends($enabled) {
+ public function testGetFormWithMultipleBackends($enabled): void {
$this->manager
->expects($this->once())
->method('isEnabled')
@@ -113,11 +113,11 @@ class SecurityTest extends TestCase {
$this->assertEquals($expected, $this->admin->getForm());
}
- public function testGetSection() {
+ public function testGetSection(): void {
$this->assertSame('security', $this->admin->getSection());
}
- public function testGetPriority() {
+ public function testGetPriority(): void {
$this->assertSame(10, $this->admin->getPriority());
}
}
diff --git a/apps/settings/tests/Settings/Personal/Security/AuthtokensTest.php b/apps/settings/tests/Settings/Personal/Security/AuthtokensTest.php
index d2cd10e34d3..44641ee98b3 100644
--- a/apps/settings/tests/Settings/Personal/Security/AuthtokensTest.php
+++ b/apps/settings/tests/Settings/Personal/Security/AuthtokensTest.php
@@ -57,7 +57,7 @@ class AuthtokensTest extends TestCase {
);
}
- public function testGetForm() {
+ public function testGetForm(): void {
$token1 = new PublicKeyToken();
$token1->setId(100);
$token2 = new PublicKeyToken();
diff --git a/apps/settings/tests/Settings/Personal/Security/PasswordTest.php b/apps/settings/tests/Settings/Personal/Security/PasswordTest.php
index 4ed7583339e..62f2c998943 100644
--- a/apps/settings/tests/Settings/Personal/Security/PasswordTest.php
+++ b/apps/settings/tests/Settings/Personal/Security/PasswordTest.php
@@ -38,7 +38,7 @@ class PasswordTest extends TestCase {
);
}
- public function testGetForm() {
+ public function testGetForm(): void {
$user = $this->createMock(IUser::class);
$this->userManager->expects($this->once())
->method('get')
diff --git a/apps/settings/tests/SetupChecks/AppDirsWithDifferentOwnerTest.php b/apps/settings/tests/SetupChecks/AppDirsWithDifferentOwnerTest.php
index 24fd28c5e9f..db3141e3a26 100644
--- a/apps/settings/tests/SetupChecks/AppDirsWithDifferentOwnerTest.php
+++ b/apps/settings/tests/SetupChecks/AppDirsWithDifferentOwnerTest.php
@@ -46,7 +46,7 @@ class AppDirsWithDifferentOwnerTest extends TestCase {
*
* @return void
*/
- public function testAppDirectoryOwnersOk() {
+ public function testAppDirectoryOwnersOk(): void {
$tempDir = tempnam(sys_get_temp_dir(), 'apps') . 'dir';
mkdir($tempDir);
mkdir($tempDir . DIRECTORY_SEPARATOR . 'app1');
@@ -73,7 +73,7 @@ class AppDirsWithDifferentOwnerTest extends TestCase {
*
* @return void
*/
- public function testAppDirectoryOwnersNotWritable() {
+ public function testAppDirectoryOwnersNotWritable(): void {
$tempDir = tempnam(sys_get_temp_dir(), 'apps') . 'dir';
\OC::$APPSROOTS = [
[
diff --git a/apps/sharebymail/tests/CapabilitiesTest.php b/apps/sharebymail/tests/CapabilitiesTest.php
index 3d8aca1a537..d38618650b3 100644
--- a/apps/sharebymail/tests/CapabilitiesTest.php
+++ b/apps/sharebymail/tests/CapabilitiesTest.php
@@ -34,7 +34,7 @@ class CapabilitiesTest extends TestCase {
$this->capabilities = new Capabilities($this->manager, $this->settingsManager, $this->appManager);
}
- public function testGetCapabilities() {
+ public function testGetCapabilities(): void {
$this->manager->method('shareApiAllowLinks')
->willReturn(true);
$this->manager->method('shareApiLinkEnforcePassword')
diff --git a/apps/sharebymail/tests/ShareByMailProviderTest.php b/apps/sharebymail/tests/ShareByMailProviderTest.php
index e7fb3fa0abf..908c2969244 100644
--- a/apps/sharebymail/tests/ShareByMailProviderTest.php
+++ b/apps/sharebymail/tests/ShareByMailProviderTest.php
@@ -148,7 +148,7 @@ class ShareByMailProviderTest extends TestCase {
parent::tearDown();
}
- public function testCreate() {
+ public function testCreate(): void {
$expectedShare = $this->createMock(IShare::class);
$share = $this->getMockBuilder(IShare::class)->getMock();
@@ -177,7 +177,7 @@ class ShareByMailProviderTest extends TestCase {
$this->assertSame($expectedShare, $instance->create($share));
}
- public function testCreateSendPasswordByMailWithoutEnforcedPasswordProtection() {
+ public function testCreateSendPasswordByMailWithoutEnforcedPasswordProtection(): void {
$expectedShare = $this->createMock(IShare::class);
$node = $this->getMockBuilder(File::class)->getMock();
@@ -219,7 +219,7 @@ class ShareByMailProviderTest extends TestCase {
$instance->sendMailNotification($share);
}
- public function testCreateSendPasswordByMailWithPasswordAndWithoutEnforcedPasswordProtectionWithPermanentPassword() {
+ public function testCreateSendPasswordByMailWithPasswordAndWithoutEnforcedPasswordProtectionWithPermanentPassword(): void {
$expectedShare = $this->createMock(IShare::class);
$node = $this->getMockBuilder(File::class)->getMock();
@@ -265,7 +265,7 @@ class ShareByMailProviderTest extends TestCase {
$instance->sendMailNotification($share);
}
- public function testCreateSendPasswordByMailWithPasswordAndWithoutEnforcedPasswordProtectionWithoutPermanentPassword() {
+ public function testCreateSendPasswordByMailWithPasswordAndWithoutEnforcedPasswordProtectionWithoutPermanentPassword(): void {
$expectedShare = $this->createMock(IShare::class);
$node = $this->getMockBuilder(File::class)->getMock();
@@ -318,7 +318,7 @@ class ShareByMailProviderTest extends TestCase {
$instance->sendMailNotification($share);
}
- public function testCreateSendPasswordByMailWithEnforcedPasswordProtectionWithPermanentPassword() {
+ public function testCreateSendPasswordByMailWithEnforcedPasswordProtectionWithPermanentPassword(): void {
$expectedShare = $this->createMock(IShare::class);
$node = $this->getMockBuilder(File::class)->getMock();
@@ -399,7 +399,7 @@ class ShareByMailProviderTest extends TestCase {
$instance->sendMailNotification($share);
}
- public function testCreateSendPasswordByMailWithPasswordAndWithEnforcedPasswordProtectionWithPermanentPassword() {
+ public function testCreateSendPasswordByMailWithPasswordAndWithEnforcedPasswordProtectionWithPermanentPassword(): void {
$expectedShare = $this->createMock(IShare::class);
$node = $this->getMockBuilder(File::class)->getMock();
@@ -473,7 +473,7 @@ class ShareByMailProviderTest extends TestCase {
$instance->sendMailNotification($share);
}
- public function testCreateSendPasswordByTalkWithEnforcedPasswordProtectionWithPermanentPassword() {
+ public function testCreateSendPasswordByTalkWithEnforcedPasswordProtectionWithPermanentPassword(): void {
$expectedShare = $this->createMock(IShare::class);
// The owner of the share.
@@ -617,7 +617,7 @@ class ShareByMailProviderTest extends TestCase {
$instance->sendMailNotification($share);
}
- public function testCreateFailed() {
+ public function testCreateFailed(): void {
$this->expectException(\Exception::class);
$this->share->expects($this->once())->method('getSharedWith')->willReturn('user1');
@@ -637,7 +637,7 @@ class ShareByMailProviderTest extends TestCase {
);
}
- public function testCreateMailShare() {
+ public function testCreateMailShare(): void {
$this->share->expects($this->any())->method('getToken')->willReturn('token');
$this->share->expects($this->once())->method('setToken')->with('token');
$this->share->expects($this->any())->method('getSharedBy')->willReturn('validby@valid.com');
@@ -662,7 +662,7 @@ class ShareByMailProviderTest extends TestCase {
);
}
- public function testGenerateToken() {
+ public function testGenerateToken(): void {
$instance = $this->getInstance();
$this->secureRandom->expects($this->once())->method('generate')->willReturn('token');
@@ -672,7 +672,7 @@ class ShareByMailProviderTest extends TestCase {
);
}
- public function testAddShareToDB() {
+ public function testAddShareToDB(): void {
$itemSource = 11;
$itemType = 'file';
$shareWith = 'user@server.com';
@@ -735,7 +735,7 @@ class ShareByMailProviderTest extends TestCase {
$this->assertSame($expiration->getTimestamp(), \DateTime::createFromFormat('Y-m-d H:i:s', $result[0]['expiration'])->getTimestamp());
}
- public function testUpdate() {
+ public function testUpdate(): void {
$itemSource = 11;
$itemType = 'file';
$shareWith = 'user@server.com';
@@ -803,7 +803,7 @@ class ShareByMailProviderTest extends TestCase {
* @param string newSendPasswordByTalk
* @param bool sendMail
*/
- public function testUpdateSendPassword($plainTextPassword, string $originalPassword, string $newPassword, $originalSendPasswordByTalk, $newSendPasswordByTalk, bool $sendMail) {
+ public function testUpdateSendPassword($plainTextPassword, string $originalPassword, string $newPassword, $originalSendPasswordByTalk, $newSendPasswordByTalk, bool $sendMail): void {
$node = $this->createMock(File::class);
$node->expects($this->any())->method('getName')->willReturn('filename');
@@ -844,7 +844,7 @@ class ShareByMailProviderTest extends TestCase {
);
}
- public function testDelete() {
+ public function testDelete(): void {
$instance = $this->getInstance(['removeShareFromTable', 'createShareActivity']);
$this->share->expects($this->once())->method('getId')->willReturn(42);
$instance->expects($this->once())->method('removeShareFromTable')->with(42);
@@ -852,7 +852,7 @@ class ShareByMailProviderTest extends TestCase {
$instance->delete($this->share);
}
- public function testGetShareById() {
+ public function testGetShareById(): void {
$instance = $this->getInstance(['createShareObject']);
$itemSource = 11;
@@ -882,7 +882,7 @@ class ShareByMailProviderTest extends TestCase {
}
- public function testGetShareByIdFailed() {
+ public function testGetShareByIdFailed(): void {
$this->expectException(\OCP\Share\Exceptions\ShareNotFound::class);
$instance = $this->getInstance(['createShareObject']);
@@ -900,7 +900,7 @@ class ShareByMailProviderTest extends TestCase {
$instance->getShareById($id + 1);
}
- public function testGetShareByPath() {
+ public function testGetShareByPath(): void {
$itemSource = 11;
$itemType = 'file';
$shareWith = 'user@server.com';
@@ -935,7 +935,7 @@ class ShareByMailProviderTest extends TestCase {
$this->assertInstanceOf(\OCP\Share\IShare::class, $result[0]);
}
- public function testGetShareByToken() {
+ public function testGetShareByToken(): void {
$itemSource = 11;
$itemType = 'file';
$shareWith = 'user@server.com';
@@ -965,7 +965,7 @@ class ShareByMailProviderTest extends TestCase {
}
- public function testGetShareByTokenFailed() {
+ public function testGetShareByTokenFailed(): void {
$this->expectException(\OCP\Share\Exceptions\ShareNotFound::class);
@@ -989,7 +989,7 @@ class ShareByMailProviderTest extends TestCase {
);
}
- public function testRemoveShareFromTable() {
+ public function testRemoveShareFromTable(): void {
$itemSource = 11;
$itemType = 'file';
$shareWith = 'user@server.com';
@@ -1027,7 +1027,7 @@ class ShareByMailProviderTest extends TestCase {
$this->assertEmpty($after);
}
- public function testUserDeleted() {
+ public function testUserDeleted(): void {
$itemSource = 11;
$itemType = 'file';
$shareWith = 'user@server.com';
@@ -1066,7 +1066,7 @@ class ShareByMailProviderTest extends TestCase {
$this->assertSame($id, (int)$after[0]['id']);
}
- public function testGetRawShare() {
+ public function testGetRawShare(): void {
$itemSource = 11;
$itemType = 'file';
$shareWith = 'user@server.com';
@@ -1092,7 +1092,7 @@ class ShareByMailProviderTest extends TestCase {
}
- public function testGetRawShareFailed() {
+ public function testGetRawShareFailed(): void {
$this->expectException(\OCP\Share\Exceptions\ShareNotFound::class);
$itemSource = 11;
@@ -1137,7 +1137,7 @@ class ShareByMailProviderTest extends TestCase {
return (int)$id;
}
- public function testGetSharesInFolder() {
+ public function testGetSharesInFolder(): void {
$userManager = \OC::$server->getUserManager();
$rootFolder = \OC::$server->getRootFolder();
@@ -1184,7 +1184,7 @@ class ShareByMailProviderTest extends TestCase {
$u2->delete();
}
- public function testGetAccessList() {
+ public function testGetAccessList(): void {
$userManager = \OC::$server->getUserManager();
$rootFolder = \OC::$server->getRootFolder();
@@ -1252,7 +1252,7 @@ class ShareByMailProviderTest extends TestCase {
$u2->delete();
}
- public function testSendMailNotificationWithSameUserAndUserEmail() {
+ public function testSendMailNotificationWithSameUserAndUserEmail(): void {
$provider = $this->getInstance();
$user = $this->createMock(IUser::class);
$this->settingsManager->expects($this->any())->method('replyToInitiator')->willReturn(true);
@@ -1365,7 +1365,7 @@ class ShareByMailProviderTest extends TestCase {
);
}
- public function testSendMailNotificationWithSameUserAndUserEmailAndNote() {
+ public function testSendMailNotificationWithSameUserAndUserEmailAndNote(): void {
$provider = $this->getInstance();
$user = $this->createMock(IUser::class);
$this->settingsManager->expects($this->any())->method('replyToInitiator')->willReturn(true);
@@ -1491,7 +1491,7 @@ class ShareByMailProviderTest extends TestCase {
);
}
- public function testSendMailNotificationWithSameUserAndUserEmailAndExpiration() {
+ public function testSendMailNotificationWithSameUserAndUserEmailAndExpiration(): void {
$provider = $this->getInstance();
$user = $this->createMock(IUser::class);
$this->settingsManager->expects($this->any())->method('replyToInitiator')->willReturn(true);
@@ -1623,7 +1623,7 @@ class ShareByMailProviderTest extends TestCase {
);
}
- public function testSendMailNotificationWithDifferentUserAndNoUserEmail() {
+ public function testSendMailNotificationWithDifferentUserAndNoUserEmail(): void {
$provider = $this->getInstance();
$initiatorUser = $this->createMock(IUser::class);
$this->settingsManager->expects($this->any())->method('replyToInitiator')->willReturn(true);
@@ -1727,7 +1727,7 @@ class ShareByMailProviderTest extends TestCase {
);
}
- public function testSendMailNotificationWithSameUserAndUserEmailAndReplyToDesactivate() {
+ public function testSendMailNotificationWithSameUserAndUserEmailAndReplyToDesactivate(): void {
$provider = $this->getInstance();
$user = $this->createMock(IUser::class);
$this->settingsManager->expects($this->any())->method('replyToInitiator')->willReturn(false);
@@ -1835,7 +1835,7 @@ class ShareByMailProviderTest extends TestCase {
);
}
- public function testSendMailNotificationWithDifferentUserAndNoUserEmailAndReplyToDesactivate() {
+ public function testSendMailNotificationWithDifferentUserAndNoUserEmailAndReplyToDesactivate(): void {
$provider = $this->getInstance();
$initiatorUser = $this->createMock(IUser::class);
$this->settingsManager->expects($this->any())->method('replyToInitiator')->willReturn(false);
diff --git a/apps/systemtags/tests/Activity/SettingTest.php b/apps/systemtags/tests/Activity/SettingTest.php
index 91aef57aeef..7ef46705e02 100644
--- a/apps/systemtags/tests/Activity/SettingTest.php
+++ b/apps/systemtags/tests/Activity/SettingTest.php
@@ -22,11 +22,11 @@ class SettingTest extends TestCase {
$this->setting = new Setting($this->l);
}
- public function testGetIdentifier() {
+ public function testGetIdentifier(): void {
$this->assertSame('systemtags', $this->setting->getIdentifier());
}
- public function testGetName() {
+ public function testGetName(): void {
$this->l
->expects($this->once())
->method('t')
@@ -36,23 +36,23 @@ class SettingTest extends TestCase {
$this->assertSame('<strong>System tags</strong> for a file have been modified', $this->setting->getName());
}
- public function testGetPriority() {
+ public function testGetPriority(): void {
$this->assertSame(50, $this->setting->getPriority());
}
- public function testCanChangeStream() {
+ public function testCanChangeStream(): void {
$this->assertSame(true, $this->setting->canChangeStream());
}
- public function testIsDefaultEnabledStream() {
+ public function testIsDefaultEnabledStream(): void {
$this->assertSame(true, $this->setting->isDefaultEnabledStream());
}
- public function testCanChangeMail() {
+ public function testCanChangeMail(): void {
$this->assertSame(true, $this->setting->canChangeMail());
}
- public function testIsDefaultEnabledMail() {
+ public function testIsDefaultEnabledMail(): void {
$this->assertSame(false, $this->setting->isDefaultEnabledMail());
}
}
diff --git a/apps/systemtags/tests/Settings/AdminTest.php b/apps/systemtags/tests/Settings/AdminTest.php
index b18019484ef..78f19475fae 100644
--- a/apps/systemtags/tests/Settings/AdminTest.php
+++ b/apps/systemtags/tests/Settings/AdminTest.php
@@ -19,16 +19,16 @@ class AdminTest extends TestCase {
$this->admin = new Admin();
}
- public function testGetForm() {
+ public function testGetForm(): void {
$expected = new TemplateResponse('systemtags', 'admin', [], '');
$this->assertEquals($expected, $this->admin->getForm());
}
- public function testGetSection() {
+ public function testGetSection(): void {
$this->assertSame('server', $this->admin->getSection());
}
- public function testGetPriority() {
+ public function testGetPriority(): void {
$this->assertSame(70, $this->admin->getPriority());
}
}
diff --git a/apps/theming/tests/CapabilitiesTest.php b/apps/theming/tests/CapabilitiesTest.php
index 5accb30b6a1..277dd5b6a7a 100644
--- a/apps/theming/tests/CapabilitiesTest.php
+++ b/apps/theming/tests/CapabilitiesTest.php
@@ -143,7 +143,7 @@ class CapabilitiesTest extends TestCase {
* @param bool $backgroundThemed
* @param string[] $expected
*/
- public function testGetCapabilities($name, $url, $slogan, $color, $textColor, $logo, $background, $backgroundColor, $backgroundTextColor, $baseUrl, $backgroundThemed, array $expected) {
+ public function testGetCapabilities($name, $url, $slogan, $color, $textColor, $logo, $background, $backgroundColor, $backgroundTextColor, $baseUrl, $backgroundThemed, array $expected): void {
$this->config->expects($this->once())
->method('getAppValue')
->willReturn($background);
diff --git a/apps/theming/tests/Controller/IconControllerTest.php b/apps/theming/tests/Controller/IconControllerTest.php
index 4fef05c7f23..303a48a6f73 100644
--- a/apps/theming/tests/Controller/IconControllerTest.php
+++ b/apps/theming/tests/Controller/IconControllerTest.php
@@ -80,7 +80,7 @@ class IconControllerTest extends TestCase {
return new SimpleFile($icon);
}
- public function testGetThemedIcon() {
+ public function testGetThemedIcon(): void {
$file = $this->iconFileMock('icon-core-filetypes_folder.svg', 'filecontent');
$this->imageManager->expects($this->once())
->method('getCachedImage')
@@ -91,7 +91,7 @@ class IconControllerTest extends TestCase {
$this->assertEquals($expected, $this->iconController->getThemedIcon('core', 'filetypes/folder.svg'));
}
- public function testGetFaviconDefault() {
+ public function testGetFaviconDefault(): void {
if (!extension_loaded('imagick')) {
$this->markTestSkipped('Imagemagick is required for dynamic icon generation.');
}
@@ -123,7 +123,7 @@ class IconControllerTest extends TestCase {
$this->assertEquals($expected, $this->iconController->getFavicon());
}
- public function testGetFaviconFail() {
+ public function testGetFaviconFail(): void {
$this->imageManager->expects($this->once())
->method('getImage')
->with('favicon', false)
@@ -141,7 +141,7 @@ class IconControllerTest extends TestCase {
$this->assertEquals($expected, $this->iconController->getFavicon());
}
- public function testGetTouchIconDefault() {
+ public function testGetTouchIconDefault(): void {
if (!extension_loaded('imagick')) {
$this->markTestSkipped('Imagemagick is required for dynamic icon generation.');
}
@@ -173,7 +173,7 @@ class IconControllerTest extends TestCase {
$this->assertEquals($expected, $this->iconController->getTouchIcon());
}
- public function testGetTouchIconFail() {
+ public function testGetTouchIconFail(): void {
$this->imageManager->expects($this->once())
->method('getImage')
->with('favicon')
diff --git a/apps/theming/tests/Controller/ThemingControllerTest.php b/apps/theming/tests/Controller/ThemingControllerTest.php
index f32f3c790d0..d69ceefa0e5 100644
--- a/apps/theming/tests/Controller/ThemingControllerTest.php
+++ b/apps/theming/tests/Controller/ThemingControllerTest.php
@@ -96,7 +96,7 @@ class ThemingControllerTest extends TestCase {
* @param string $value
* @param string $message
*/
- public function testUpdateStylesheetSuccess($setting, $value, $message) {
+ public function testUpdateStylesheetSuccess($setting, $value, $message): void {
$this->themingDefaults
->expects($this->once())
->method('set')
@@ -147,7 +147,7 @@ class ThemingControllerTest extends TestCase {
* @param string $value
* @param string $message
*/
- public function testUpdateStylesheetError($setting, $value, $message) {
+ public function testUpdateStylesheetError($setting, $value, $message): void {
$this->themingDefaults
->expects($this->never())
->method('set')
@@ -172,7 +172,7 @@ class ThemingControllerTest extends TestCase {
$this->assertEquals($expected, $this->themingController->updateStylesheet($setting, $value));
}
- public function testUpdateLogoNoData() {
+ public function testUpdateLogoNoData(): void {
$this->request
->expects($this->once())
->method('getParam')
@@ -204,7 +204,7 @@ class ThemingControllerTest extends TestCase {
$this->assertEquals($expected, $this->themingController->uploadImage());
}
- public function testUploadInvalidUploadKey() {
+ public function testUploadInvalidUploadKey(): void {
$this->request
->expects($this->once())
->method('getParam')
@@ -241,7 +241,7 @@ class ThemingControllerTest extends TestCase {
* @test
* @return void
*/
- public function testUploadSVGFaviconWithoutImagemagick() {
+ public function testUploadSVGFaviconWithoutImagemagick(): void {
$this->imageManager
->method('shouldReplaceIcons')
->willReturn(false);
@@ -286,7 +286,7 @@ class ThemingControllerTest extends TestCase {
$this->assertEquals($expected, $this->themingController->uploadImage());
}
- public function testUpdateLogoInvalidMimeType() {
+ public function testUpdateLogoInvalidMimeType(): void {
$this->request
->expects($this->once())
->method('getParam')
@@ -339,7 +339,7 @@ class ThemingControllerTest extends TestCase {
}
/** @dataProvider dataUpdateImages */
- public function testUpdateLogoNormalLogoUpload($mimeType, $folderExists = true) {
+ public function testUpdateLogoNormalLogoUpload($mimeType, $folderExists = true): void {
$tmpLogo = \OC::$server->getTempManager()->getTemporaryFolder() . '/logo.svg';
$destination = \OC::$server->getTempManager()->getTemporaryFolder();
@@ -391,7 +391,7 @@ class ThemingControllerTest extends TestCase {
}
/** @dataProvider dataUpdateImages */
- public function testUpdateLogoLoginScreenUpload($folderExists) {
+ public function testUpdateLogoLoginScreenUpload($folderExists): void {
$tmpLogo = \OC::$server->getTempManager()->getTemporaryFolder() . 'logo.png';
touch($tmpLogo);
@@ -439,7 +439,7 @@ class ThemingControllerTest extends TestCase {
$this->assertEquals($expected, $this->themingController->uploadImage());
}
- public function testUpdateLogoLoginScreenUploadWithInvalidImage() {
+ public function testUpdateLogoLoginScreenUploadWithInvalidImage(): void {
$tmpLogo = \OC::$server->getTempManager()->getTemporaryFolder() . '/logo.svg';
touch($tmpLogo);
@@ -498,7 +498,7 @@ class ThemingControllerTest extends TestCase {
/**
* @dataProvider dataPhpUploadErrors
*/
- public function testUpdateLogoLoginScreenUploadWithInvalidImageUpload($error, $expectedErrorMessage) {
+ public function testUpdateLogoLoginScreenUploadWithInvalidImageUpload($error, $expectedErrorMessage): void {
$this->request
->expects($this->once())
->method('getParam')
@@ -537,7 +537,7 @@ class ThemingControllerTest extends TestCase {
/**
* @dataProvider dataPhpUploadErrors
*/
- public function testUpdateLogoUploadWithInvalidImageUpload($error, $expectedErrorMessage) {
+ public function testUpdateLogoUploadWithInvalidImageUpload($error, $expectedErrorMessage): void {
$this->request
->expects($this->once())
->method('getParam')
@@ -573,7 +573,7 @@ class ThemingControllerTest extends TestCase {
$this->assertEquals($expected, $this->themingController->uploadImage());
}
- public function testUndo() {
+ public function testUndo(): void {
$this->l10n
->expects($this->once())
->method('t')
@@ -606,7 +606,7 @@ class ThemingControllerTest extends TestCase {
}
/** @dataProvider dataUndoDelete */
- public function testUndoDelete($value, $filename) {
+ public function testUndoDelete($value, $filename): void {
$this->l10n
->expects($this->once())
->method('t')
@@ -633,7 +633,7 @@ class ThemingControllerTest extends TestCase {
- public function testGetLogoNotExistent() {
+ public function testGetLogoNotExistent(): void {
$this->imageManager->method('getImage')
->with($this->equalTo('logo'))
->willThrowException(new NotFoundException());
@@ -642,7 +642,7 @@ class ThemingControllerTest extends TestCase {
$this->assertEquals($expected, $this->themingController->getImage('logo'));
}
- public function testGetLogo() {
+ public function testGetLogo(): void {
$file = $this->createMock(ISimpleFile::class);
$file->method('getName')->willReturn('logo.svg');
$file->method('getMTime')->willReturn(42);
@@ -666,7 +666,7 @@ class ThemingControllerTest extends TestCase {
}
- public function testGetLoginBackgroundNotExistent() {
+ public function testGetLoginBackgroundNotExistent(): void {
$this->imageManager->method('getImage')
->with($this->equalTo('background'))
->willThrowException(new NotFoundException());
@@ -674,7 +674,7 @@ class ThemingControllerTest extends TestCase {
$this->assertEquals($expected, $this->themingController->getImage('background'));
}
- public function testGetLoginBackground() {
+ public function testGetLoginBackground(): void {
$file = $this->createMock(ISimpleFile::class);
$file->method('getName')->willReturn('background.png');
$file->method('getMTime')->willReturn(42);
@@ -698,7 +698,7 @@ class ThemingControllerTest extends TestCase {
@$this->assertEquals($expected, $this->themingController->getImage('background'));
}
- public function testGetManifest() {
+ public function testGetManifest(): void {
$this->config
->expects($this->once())
->method('getAppValue')
diff --git a/apps/theming/tests/Controller/UserThemeControllerTest.php b/apps/theming/tests/Controller/UserThemeControllerTest.php
index 8c3ae7364cd..7d369463c0d 100644
--- a/apps/theming/tests/Controller/UserThemeControllerTest.php
+++ b/apps/theming/tests/Controller/UserThemeControllerTest.php
@@ -104,7 +104,7 @@ class UserThemeControllerTest extends TestCase {
* @param string $themeId
* @param string $exception
*/
- public function testEnableTheme($themeId, ?string $exception = null) {
+ public function testEnableTheme($themeId, ?string $exception = null): void {
$this->themesService
->expects($this->any())
->method('getThemes')
@@ -124,7 +124,7 @@ class UserThemeControllerTest extends TestCase {
* @param string $themeId
* @param string $exception
*/
- public function testDisableTheme($themeId, ?string $exception = null) {
+ public function testDisableTheme($themeId, ?string $exception = null): void {
$this->themesService
->expects($this->any())
->method('getThemes')
diff --git a/apps/theming/tests/IconBuilderTest.php b/apps/theming/tests/IconBuilderTest.php
index 0d8b8c83923..942bcf399fa 100644
--- a/apps/theming/tests/IconBuilderTest.php
+++ b/apps/theming/tests/IconBuilderTest.php
@@ -74,7 +74,7 @@ class IconBuilderTest extends TestCase {
* @param $color
* @param $file
*/
- public function testRenderAppIcon($app, $color, $file) {
+ public function testRenderAppIcon($app, $color, $file): void {
$this->checkImagick();
$this->themingDefaults->expects($this->once())
->method('getColorPrimary')
@@ -103,7 +103,7 @@ class IconBuilderTest extends TestCase {
* @param $color
* @param $file
*/
- public function testGetTouchIcon($app, $color, $file) {
+ public function testGetTouchIcon($app, $color, $file): void {
$this->checkImagick();
$this->themingDefaults->expects($this->once())
->method('getColorPrimary')
@@ -133,7 +133,7 @@ class IconBuilderTest extends TestCase {
* @param $color
* @param $file
*/
- public function testGetFavicon($app, $color, $file) {
+ public function testGetFavicon($app, $color, $file): void {
$this->checkImagick();
$this->imageManager->expects($this->once())
->method('shouldReplaceIcons')
@@ -162,7 +162,7 @@ class IconBuilderTest extends TestCase {
// cloud be something like $expectedIcon->compareImages($icon, Imagick::METRIC_MEANABSOLUTEERROR)[1])
}
- public function testGetFaviconNotFound() {
+ public function testGetFaviconNotFound(): void {
$this->checkImagick();
$this->expectWarning(Warning::class);
$util = $this->getMockBuilder(Util::class)->disableOriginalConstructor()->getMock();
@@ -176,7 +176,7 @@ class IconBuilderTest extends TestCase {
$this->assertFalse($iconBuilder->getFavicon('noapp'));
}
- public function testGetTouchIconNotFound() {
+ public function testGetTouchIconNotFound(): void {
$this->checkImagick();
$this->expectWarning(Warning::class);
$util = $this->getMockBuilder(Util::class)->disableOriginalConstructor()->getMock();
@@ -187,7 +187,7 @@ class IconBuilderTest extends TestCase {
$this->assertFalse($iconBuilder->getTouchIcon('noapp'));
}
- public function testColorSvgNotFound() {
+ public function testColorSvgNotFound(): void {
$this->checkImagick();
$this->expectWarning(Warning::class);
$util = $this->getMockBuilder(Util::class)->disableOriginalConstructor()->getMock();
diff --git a/apps/theming/tests/ImageManagerTest.php b/apps/theming/tests/ImageManagerTest.php
index f3c2156be7e..54e4e2a70ee 100644
--- a/apps/theming/tests/ImageManagerTest.php
+++ b/apps/theming/tests/ImageManagerTest.php
@@ -117,7 +117,7 @@ class ImageManagerTest extends TestCase {
}
}
- public function testGetImageUrl() {
+ public function testGetImageUrl(): void {
$this->checkImagick();
$file = $this->createMock(ISimpleFile::class);
$this->config->expects($this->exactly(2))
@@ -133,7 +133,7 @@ class ImageManagerTest extends TestCase {
$this->assertEquals('url-to-image?v=0', $this->imageManager->getImageUrl('logo', false));
}
- public function testGetImageUrlDefault() {
+ public function testGetImageUrlDefault(): void {
$this->config->expects($this->exactly(2))
->method('getAppValue')
->withConsecutive(
@@ -148,7 +148,7 @@ class ImageManagerTest extends TestCase {
$this->assertEquals('logo/logo.png?v=0', $this->imageManager->getImageUrl('logo'));
}
- public function testGetImageUrlAbsolute() {
+ public function testGetImageUrlAbsolute(): void {
$this->checkImagick();
$file = $this->createMock(ISimpleFile::class);
$this->config->expects($this->exactly(2))
@@ -164,7 +164,7 @@ class ImageManagerTest extends TestCase {
$this->assertEquals('url-to-image-absolute?v=0', $this->imageManager->getImageUrlAbsolute('logo', false));
}
- public function testGetImage() {
+ public function testGetImage(): void {
$this->checkImagick();
$this->config->expects($this->once())
->method('getAppValue')->with('theming', 'logoMime', false)
@@ -175,7 +175,7 @@ class ImageManagerTest extends TestCase {
}
- public function testGetImageUnset() {
+ public function testGetImageUnset(): void {
$this->expectException(\OCP\Files\NotFoundException::class);
$this->config->expects($this->once())
@@ -184,7 +184,7 @@ class ImageManagerTest extends TestCase {
$this->imageManager->getImage('logo');
}
- public function testGetCacheFolder() {
+ public function testGetCacheFolder(): void {
$folder = $this->createMock(ISimpleFolder::class);
$this->config->expects($this->once())
->method('getAppValue')
@@ -196,7 +196,7 @@ class ImageManagerTest extends TestCase {
->willReturn($folder);
$this->assertEquals($folder, $this->imageManager->getCacheFolder());
}
- public function testGetCacheFolderCreate() {
+ public function testGetCacheFolderCreate(): void {
$folder = $this->createMock(ISimpleFolder::class);
$this->config->expects($this->exactly(2))
->method('getAppValue')
@@ -219,7 +219,7 @@ class ImageManagerTest extends TestCase {
$this->assertEquals($folder, $this->imageManager->getCacheFolder());
}
- public function testGetCachedImage() {
+ public function testGetCachedImage(): void {
$expected = $this->createMock(ISimpleFile::class);
$folder = $this->setupCacheFolder();
$folder->expects($this->once())
@@ -230,7 +230,7 @@ class ImageManagerTest extends TestCase {
}
- public function testGetCachedImageNotFound() {
+ public function testGetCachedImageNotFound(): void {
$this->expectException(\OCP\Files\NotFoundException::class);
$folder = $this->setupCacheFolder();
@@ -241,7 +241,7 @@ class ImageManagerTest extends TestCase {
$image = $this->imageManager->getCachedImage('filename');
}
- public function testSetCachedImage() {
+ public function testSetCachedImage(): void {
$folder = $this->setupCacheFolder();
$file = $this->createMock(ISimpleFile::class);
$folder->expects($this->once())
@@ -258,7 +258,7 @@ class ImageManagerTest extends TestCase {
$this->assertEquals($file, $this->imageManager->setCachedImage('filename', 'filecontent'));
}
- public function testSetCachedImageCreate() {
+ public function testSetCachedImageCreate(): void {
$folder = $this->setupCacheFolder();
$file = $this->createMock(ISimpleFile::class);
$folder->expects($this->once())
@@ -288,7 +288,7 @@ class ImageManagerTest extends TestCase {
return $folder;
}
- public function testCleanup() {
+ public function testCleanup(): void {
$folders = [
$this->createMock(ISimpleFolder::class),
$this->createMock(ISimpleFolder::class),
@@ -332,7 +332,7 @@ class ImageManagerTest extends TestCase {
/**
* @dataProvider dataUpdateImage
*/
- public function testUpdateImage($key, $tmpFile, $folderExists, $shouldConvert) {
+ public function testUpdateImage($key, $tmpFile, $folderExists, $shouldConvert): void {
$file = $this->createMock(ISimpleFile::class);
$folder = $this->createMock(ISimpleFolder::class);
$oldFile = $this->createMock(ISimpleFile::class);
diff --git a/apps/theming/tests/Service/ThemesServiceTest.php b/apps/theming/tests/Service/ThemesServiceTest.php
index 1644deea4c7..77371cfe34c 100644
--- a/apps/theming/tests/Service/ThemesServiceTest.php
+++ b/apps/theming/tests/Service/ThemesServiceTest.php
@@ -70,7 +70,7 @@ class ThemesServiceTest extends TestCase {
parent::setUp();
}
- public function testGetThemes() {
+ public function testGetThemes(): void {
$expected = [
'default',
'light',
@@ -82,7 +82,7 @@ class ThemesServiceTest extends TestCase {
$this->assertEquals($expected, array_keys($this->themesService->getThemes()));
}
- public function testGetThemesEnforced() {
+ public function testGetThemesEnforced(): void {
$this->config->expects($this->once())
->method('getSystemValueString')
->with('enforce_theme', '')
@@ -98,7 +98,7 @@ class ThemesServiceTest extends TestCase {
$this->assertEquals($expected, array_keys($this->themesService->getThemes()));
}
- public function testGetThemesEnforcedInvalid() {
+ public function testGetThemesEnforcedInvalid(): void {
$this->config->expects($this->once())
->method('getSystemValueString')
->with('enforce_theme', '')
@@ -136,7 +136,7 @@ class ThemesServiceTest extends TestCase {
* @param string[] $enabledThemes
* @param string[] $expectedEnabled
*/
- public function testEnableTheme(string $toEnable, array $enabledThemes, array $expectedEnabled) {
+ public function testEnableTheme(string $toEnable, array $enabledThemes, array $expectedEnabled): void {
$user = $this->createMock(IUser::class);
$this->userSession->expects($this->any())
->method('getUser')
@@ -170,7 +170,7 @@ class ThemesServiceTest extends TestCase {
* @param string[] $enabledThemes
* @param string[] $expectedEnabled
*/
- public function testDisableTheme(string $toDisable, array $enabledThemes, array $expectedEnabled) {
+ public function testDisableTheme(string $toDisable, array $enabledThemes, array $expectedEnabled): void {
$user = $this->createMock(IUser::class);
$this->userSession->expects($this->any())
->method('getUser')
@@ -204,7 +204,7 @@ class ThemesServiceTest extends TestCase {
* @param string $toEnable
* @param string[] $enabledThemes
*/
- public function testIsEnabled(string $themeId, array $enabledThemes, $expected) {
+ public function testIsEnabled(string $themeId, array $enabledThemes, $expected): void {
$user = $this->createMock(IUser::class);
$this->userSession->expects($this->any())
->method('getUser')
@@ -222,7 +222,7 @@ class ThemesServiceTest extends TestCase {
$this->assertEquals($expected, $this->themesService->isEnabled($this->themes[$themeId]));
}
- public function testGetEnabledThemes() {
+ public function testGetEnabledThemes(): void {
$user = $this->createMock(IUser::class);
$this->userSession->expects($this->any())
->method('getUser')
@@ -244,7 +244,7 @@ class ThemesServiceTest extends TestCase {
$this->assertEquals([], $this->themesService->getEnabledThemes());
}
- public function testGetEnabledThemesEnforced() {
+ public function testGetEnabledThemesEnforced(): void {
$user = $this->createMock(IUser::class);
$this->userSession->expects($this->any())
->method('getUser')
@@ -282,7 +282,7 @@ class ThemesServiceTest extends TestCase {
* @param string[] $enabledThemes
* @param string[] $expected
*/
- public function testSetEnabledThemes(array $enabledThemes, array $expected) {
+ public function testSetEnabledThemes(array $enabledThemes, array $expected): void {
$user = $this->createMock(IUser::class);
$this->userSession->expects($this->any())
->method('getUser')
diff --git a/apps/theming/tests/ServicesTest.php b/apps/theming/tests/ServicesTest.php
index 2e404d6fd43..3223de0a489 100644
--- a/apps/theming/tests/ServicesTest.php
+++ b/apps/theming/tests/ServicesTest.php
@@ -64,7 +64,7 @@ class ServicesTest extends TestCase {
* @param string $service
* @param string $expected
*/
- public function testContainerQuery($service, $expected = null) {
+ public function testContainerQuery($service, $expected = null): void {
if ($expected === null) {
$expected = $service;
}
diff --git a/apps/theming/tests/Settings/AdminSectionTest.php b/apps/theming/tests/Settings/AdminSectionTest.php
index 8916313e9a2..a73eca1cc5a 100644
--- a/apps/theming/tests/Settings/AdminSectionTest.php
+++ b/apps/theming/tests/Settings/AdminSectionTest.php
@@ -31,11 +31,11 @@ class AdminSectionTest extends TestCase {
);
}
- public function testGetID() {
+ public function testGetID(): void {
$this->assertSame('theming', $this->section->getID());
}
- public function testGetName() {
+ public function testGetName(): void {
$this->l
->expects($this->once())
->method('t')
@@ -45,11 +45,11 @@ class AdminSectionTest extends TestCase {
$this->assertSame('Theming', $this->section->getName());
}
- public function testGetPriority() {
+ public function testGetPriority(): void {
$this->assertSame(30, $this->section->getPriority());
}
- public function testGetIcon() {
+ public function testGetIcon(): void {
$this->url->expects($this->once())
->method('imagePath')
->with('theming', 'app-dark.svg')
diff --git a/apps/theming/tests/Settings/AdminTest.php b/apps/theming/tests/Settings/AdminTest.php
index d74668f5e6f..189a91bae3a 100644
--- a/apps/theming/tests/Settings/AdminTest.php
+++ b/apps/theming/tests/Settings/AdminTest.php
@@ -49,7 +49,7 @@ class AdminTest extends TestCase {
);
}
- public function testGetFormNoErrors() {
+ public function testGetFormNoErrors(): void {
$this->config
->expects($this->once())
->method('getSystemValue')
@@ -84,7 +84,7 @@ class AdminTest extends TestCase {
$this->assertEquals($expected, $this->admin->getForm());
}
- public function testGetFormWithErrors() {
+ public function testGetFormWithErrors(): void {
$this->config
->expects($this->once())
->method('getSystemValue')
@@ -124,11 +124,11 @@ class AdminTest extends TestCase {
$this->assertEquals($expected, $this->admin->getForm());
}
- public function testGetSection() {
+ public function testGetSection(): void {
$this->assertSame('theming', $this->admin->getSection());
}
- public function testGetPriority() {
+ public function testGetPriority(): void {
$this->assertSame(5, $this->admin->getPriority());
}
}
diff --git a/apps/theming/tests/Settings/PersonalTest.php b/apps/theming/tests/Settings/PersonalTest.php
index 88c5e93d1c7..4630ef48c8a 100644
--- a/apps/theming/tests/Settings/PersonalTest.php
+++ b/apps/theming/tests/Settings/PersonalTest.php
@@ -91,7 +91,7 @@ class PersonalTest extends TestCase {
* @param string $toEnable
* @param string[] $enabledThemes
*/
- public function testGetForm(string $enforcedTheme, $themesState) {
+ public function testGetForm(string $enforcedTheme, $themesState): void {
$this->config->expects($this->once())
->method('getSystemValueString')
->with('enforce_theme', '')
@@ -125,11 +125,11 @@ class PersonalTest extends TestCase {
$this->assertEquals($expected, $this->admin->getForm());
}
- public function testGetSection() {
+ public function testGetSection(): void {
$this->assertSame('theming', $this->admin->getSection());
}
- public function testGetPriority() {
+ public function testGetPriority(): void {
$this->assertSame(40, $this->admin->getPriority());
}
diff --git a/apps/theming/tests/Themes/AccessibleThemeTestCase.php b/apps/theming/tests/Themes/AccessibleThemeTestCase.php
index 5f13e2259aa..a1327a04f0b 100644
--- a/apps/theming/tests/Themes/AccessibleThemeTestCase.php
+++ b/apps/theming/tests/Themes/AccessibleThemeTestCase.php
@@ -148,7 +148,7 @@ class AccessibleThemeTestCase extends TestCase {
/**
* @dataProvider dataAccessibilityPairs
*/
- public function testAccessibilityOfVariables($mainColors, $backgroundColors, $minContrast) {
+ public function testAccessibilityOfVariables($mainColors, $backgroundColors, $minContrast): void {
if (!isset($this->theme)) {
$this->markTestSkipped('You need to setup $this->theme in your setUp function');
} elseif (!isset($this->util)) {
diff --git a/apps/theming/tests/Themes/DarkHighContrastThemeTest.php b/apps/theming/tests/Themes/DarkHighContrastThemeTest.php
index 30bbc5f110d..63fb2bf414d 100644
--- a/apps/theming/tests/Themes/DarkHighContrastThemeTest.php
+++ b/apps/theming/tests/Themes/DarkHighContrastThemeTest.php
@@ -108,27 +108,27 @@ class DarkHighContrastThemeTest extends AccessibleThemeTestCase {
}
- public function testGetId() {
+ public function testGetId(): void {
$this->assertEquals('dark-highcontrast', $this->theme->getId());
}
- public function testGetType() {
+ public function testGetType(): void {
$this->assertEquals(ITheme::TYPE_THEME, $this->theme->getType());
}
- public function testGetTitle() {
+ public function testGetTitle(): void {
$this->assertEquals('Dark theme with high contrast mode', $this->theme->getTitle());
}
- public function testGetEnableLabel() {
+ public function testGetEnableLabel(): void {
$this->assertEquals('Enable dark high contrast mode', $this->theme->getEnableLabel());
}
- public function testGetDescription() {
+ public function testGetDescription(): void {
$this->assertEquals('Similar to the high contrast mode, but with dark colours.', $this->theme->getDescription());
}
- public function testGetMediaQuery() {
+ public function testGetMediaQuery(): void {
$this->assertEquals('(prefers-color-scheme: dark) and (prefers-contrast: more)', $this->theme->getMediaQuery());
}
}
diff --git a/apps/theming/tests/Themes/DarkThemeTest.php b/apps/theming/tests/Themes/DarkThemeTest.php
index 16a289053ae..f53028d3a63 100644
--- a/apps/theming/tests/Themes/DarkThemeTest.php
+++ b/apps/theming/tests/Themes/DarkThemeTest.php
@@ -105,31 +105,31 @@ class DarkThemeTest extends AccessibleThemeTestCase {
}
- public function testGetId() {
+ public function testGetId(): void {
$this->assertEquals('dark', $this->theme->getId());
}
- public function testGetType() {
+ public function testGetType(): void {
$this->assertEquals(ITheme::TYPE_THEME, $this->theme->getType());
}
- public function testGetTitle() {
+ public function testGetTitle(): void {
$this->assertEquals('Dark theme', $this->theme->getTitle());
}
- public function testGetEnableLabel() {
+ public function testGetEnableLabel(): void {
$this->assertEquals('Enable dark theme', $this->theme->getEnableLabel());
}
- public function testGetDescription() {
+ public function testGetDescription(): void {
$this->assertEquals('A dark theme to ease your eyes by reducing the overall luminosity and brightness.', $this->theme->getDescription());
}
- public function testGetMediaQuery() {
+ public function testGetMediaQuery(): void {
$this->assertEquals('(prefers-color-scheme: dark)', $this->theme->getMediaQuery());
}
- public function testGetCustomCss() {
+ public function testGetCustomCss(): void {
$this->assertEquals('', $this->theme->getCustomCss());
}
}
diff --git a/apps/theming/tests/Themes/DefaultThemeTest.php b/apps/theming/tests/Themes/DefaultThemeTest.php
index d11237e774c..db6a5bf1cfc 100644
--- a/apps/theming/tests/Themes/DefaultThemeTest.php
+++ b/apps/theming/tests/Themes/DefaultThemeTest.php
@@ -109,31 +109,31 @@ class DefaultThemeTest extends AccessibleThemeTestCase {
}
- public function testGetId() {
+ public function testGetId(): void {
$this->assertEquals('default', $this->theme->getId());
}
- public function testGetType() {
+ public function testGetType(): void {
$this->assertEquals(ITheme::TYPE_THEME, $this->theme->getType());
}
- public function testGetTitle() {
+ public function testGetTitle(): void {
$this->assertEquals('System default theme', $this->theme->getTitle());
}
- public function testGetEnableLabel() {
+ public function testGetEnableLabel(): void {
$this->assertEquals('Enable the system default', $this->theme->getEnableLabel());
}
- public function testGetDescription() {
+ public function testGetDescription(): void {
$this->assertEquals('Using the default system appearance.', $this->theme->getDescription());
}
- public function testGetMediaQuery() {
+ public function testGetMediaQuery(): void {
$this->assertEquals('', $this->theme->getMediaQuery());
}
- public function testGetCustomCss() {
+ public function testGetCustomCss(): void {
$this->assertEquals('', $this->theme->getCustomCss());
}
@@ -141,7 +141,7 @@ class DefaultThemeTest extends AccessibleThemeTestCase {
* Ensure parity between the default theme and the static generated file
* @see ThemingController.php:313
*/
- public function testThemindDisabledFallbackCss() {
+ public function testThemindDisabledFallbackCss(): void {
// Generate variables
$variables = '';
foreach ($this->theme->getCSSVariables() as $variable => $value) {
diff --git a/apps/theming/tests/Themes/DyslexiaFontTest.php b/apps/theming/tests/Themes/DyslexiaFontTest.php
index 99b6f8cfc8e..53505f4bd03 100644
--- a/apps/theming/tests/Themes/DyslexiaFontTest.php
+++ b/apps/theming/tests/Themes/DyslexiaFontTest.php
@@ -110,31 +110,31 @@ class DyslexiaFontTest extends TestCase {
}
- public function testGetId() {
+ public function testGetId(): void {
$this->assertEquals('opendyslexic', $this->dyslexiaFont->getId());
}
- public function testGetType() {
+ public function testGetType(): void {
$this->assertEquals(ITheme::TYPE_FONT, $this->dyslexiaFont->getType());
}
- public function testGetTitle() {
+ public function testGetTitle(): void {
$this->assertNotEmpty($this->dyslexiaFont->getTitle());
}
- public function testGetEnableLabel() {
+ public function testGetEnableLabel(): void {
$this->assertNotEmpty($this->dyslexiaFont->getEnableLabel());
}
- public function testGetDescription() {
+ public function testGetDescription(): void {
$this->assertNotEmpty($this->dyslexiaFont->getDescription());
}
- public function testGetMediaQuery() {
+ public function testGetMediaQuery(): void {
$this->assertEquals('', $this->dyslexiaFont->getMediaQuery());
}
- public function testGetCSSVariables() {
+ public function testGetCSSVariables(): void {
$this->assertStringStartsWith('OpenDyslexic', $this->dyslexiaFont->getCSSVariables()['--font-face']);
}
@@ -156,7 +156,7 @@ class DyslexiaFontTest extends TestCase {
* @param string $webRoot
* @param bool $prettyUrlsEnabled
*/
- public function testGetCustomCss($webRoot, $prettyUrlsEnabled) {
+ public function testGetCustomCss($webRoot, $prettyUrlsEnabled): void {
\OC::$WEBROOT = $webRoot;
$this->config->expects($this->any())
->method('getSystemValue')
diff --git a/apps/theming/tests/Themes/HighContrastThemeTest.php b/apps/theming/tests/Themes/HighContrastThemeTest.php
index 47c4b3bb374..603bf08a0ee 100644
--- a/apps/theming/tests/Themes/HighContrastThemeTest.php
+++ b/apps/theming/tests/Themes/HighContrastThemeTest.php
@@ -108,27 +108,27 @@ class HighContrastThemeTest extends AccessibleThemeTestCase {
}
- public function testGetId() {
+ public function testGetId(): void {
$this->assertEquals('light-highcontrast', $this->theme->getId());
}
- public function testGetType() {
+ public function testGetType(): void {
$this->assertEquals(ITheme::TYPE_THEME, $this->theme->getType());
}
- public function testGetTitle() {
+ public function testGetTitle(): void {
$this->assertEquals('High contrast mode', $this->theme->getTitle());
}
- public function testGetEnableLabel() {
+ public function testGetEnableLabel(): void {
$this->assertEquals('Enable high contrast mode', $this->theme->getEnableLabel());
}
- public function testGetDescription() {
+ public function testGetDescription(): void {
$this->assertEquals('A high contrast mode to ease your navigation. Visual quality will be reduced but clarity will be increased.', $this->theme->getDescription());
}
- public function testGetMediaQuery() {
+ public function testGetMediaQuery(): void {
$this->assertEquals('(prefers-contrast: more)', $this->theme->getMediaQuery());
}
}
diff --git a/apps/theming/tests/ThemingDefaultsTest.php b/apps/theming/tests/ThemingDefaultsTest.php
index 8edbcbc53c1..d8f169e7f3d 100644
--- a/apps/theming/tests/ThemingDefaultsTest.php
+++ b/apps/theming/tests/ThemingDefaultsTest.php
@@ -85,7 +85,7 @@ class ThemingDefaultsTest extends TestCase {
);
}
- public function testGetNameWithDefault() {
+ public function testGetNameWithDefault(): void {
$this->config
->expects($this->once())
->method('getAppValue')
@@ -95,7 +95,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals('Nextcloud', $this->template->getName());
}
- public function testGetNameWithCustom() {
+ public function testGetNameWithCustom(): void {
$this->config
->expects($this->once())
->method('getAppValue')
@@ -105,7 +105,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals('MyCustomCloud', $this->template->getName());
}
- public function testGetHTMLNameWithDefault() {
+ public function testGetHTMLNameWithDefault(): void {
$this->config
->expects($this->once())
->method('getAppValue')
@@ -115,7 +115,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals('Nextcloud', $this->template->getHTMLName());
}
- public function testGetHTMLNameWithCustom() {
+ public function testGetHTMLNameWithCustom(): void {
$this->config
->expects($this->once())
->method('getAppValue')
@@ -125,7 +125,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals('MyCustomCloud', $this->template->getHTMLName());
}
- public function testGetTitleWithDefault() {
+ public function testGetTitleWithDefault(): void {
$this->config
->expects($this->once())
->method('getAppValue')
@@ -135,7 +135,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals('Nextcloud', $this->template->getTitle());
}
- public function testGetTitleWithCustom() {
+ public function testGetTitleWithCustom(): void {
$this->config
->expects($this->once())
->method('getAppValue')
@@ -146,7 +146,7 @@ class ThemingDefaultsTest extends TestCase {
}
- public function testGetEntityWithDefault() {
+ public function testGetEntityWithDefault(): void {
$this->config
->expects($this->once())
->method('getAppValue')
@@ -156,7 +156,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals('Nextcloud', $this->template->getEntity());
}
- public function testGetEntityWithCustom() {
+ public function testGetEntityWithCustom(): void {
$this->config
->expects($this->once())
->method('getAppValue')
@@ -166,7 +166,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals('MyCustomCloud', $this->template->getEntity());
}
- public function testGetBaseUrlWithDefault() {
+ public function testGetBaseUrlWithDefault(): void {
$this->config
->expects($this->once())
->method('getAppValue')
@@ -176,7 +176,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals($this->defaults->getBaseUrl(), $this->template->getBaseUrl());
}
- public function testGetBaseUrlWithCustom() {
+ public function testGetBaseUrlWithCustom(): void {
$this->config
->expects($this->once())
->method('getAppValue')
@@ -197,7 +197,7 @@ class ThemingDefaultsTest extends TestCase {
* @param $imprintUrl
* @dataProvider legalUrlProvider
*/
- public function testGetImprintURL($imprintUrl) {
+ public function testGetImprintURL($imprintUrl): void {
$this->config
->expects($this->once())
->method('getAppValue')
@@ -211,7 +211,7 @@ class ThemingDefaultsTest extends TestCase {
* @param $privacyUrl
* @dataProvider legalUrlProvider
*/
- public function testGetPrivacyURL($privacyUrl) {
+ public function testGetPrivacyURL($privacyUrl): void {
$this->config
->expects($this->once())
->method('getAppValue')
@@ -221,7 +221,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals($privacyUrl, $this->template->getPrivacyUrl());
}
- public function testGetSloganWithDefault() {
+ public function testGetSloganWithDefault(): void {
$this->config
->expects($this->once())
->method('getAppValue')
@@ -231,7 +231,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals($this->defaults->getSlogan(), $this->template->getSlogan());
}
- public function testGetSloganWithCustom() {
+ public function testGetSloganWithCustom(): void {
$this->config
->expects($this->once())
->method('getAppValue')
@@ -241,7 +241,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals('My custom Slogan', $this->template->getSlogan());
}
- public function testGetShortFooter() {
+ public function testGetShortFooter(): void {
$this->config
->expects($this->exactly(5))
->method('getAppValue')
@@ -256,7 +256,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals('<a href="url" target="_blank" rel="noreferrer noopener" class="entity-name">Name</a> – Slogan', $this->template->getShortFooter());
}
- public function testGetShortFooterEmptyUrl() {
+ public function testGetShortFooterEmptyUrl(): void {
$this->navigationManager->expects($this->once())->method('getAll')->with(INavigationManager::TYPE_GUEST)->willReturn([]);
$this->config
->expects($this->exactly(5))
@@ -272,7 +272,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals('<span class="entity-name">Name</span> – Slogan', $this->template->getShortFooter());
}
- public function testGetShortFooterEmptySlogan() {
+ public function testGetShortFooterEmptySlogan(): void {
$this->navigationManager->expects($this->once())->method('getAll')->with(INavigationManager::TYPE_GUEST)->willReturn([]);
$this->config
->expects($this->exactly(5))
@@ -288,7 +288,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals('<a href="url" target="_blank" rel="noreferrer noopener" class="entity-name">Name</a>', $this->template->getShortFooter());
}
- public function testGetShortFooterImprint() {
+ public function testGetShortFooterImprint(): void {
$this->navigationManager->expects($this->once())->method('getAll')->with(INavigationManager::TYPE_GUEST)->willReturn([]);
$this->config
->expects($this->exactly(5))
@@ -309,7 +309,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals('<a href="url" target="_blank" rel="noreferrer noopener" class="entity-name">Name</a> – Slogan<br/><span class="footer__legal-links"><a href="https://example.com/imprint" class="legal" target="_blank" rel="noreferrer noopener">Legal notice</a></span>', $this->template->getShortFooter());
}
- public function testGetShortFooterPrivacy() {
+ public function testGetShortFooterPrivacy(): void {
$this->navigationManager->expects($this->once())->method('getAll')->with(INavigationManager::TYPE_GUEST)->willReturn([]);
$this->config
->expects($this->exactly(5))
@@ -330,7 +330,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals('<a href="url" target="_blank" rel="noreferrer noopener" class="entity-name">Name</a> – Slogan<br/><span class="footer__legal-links"><a href="https://example.com/privacy" class="legal" target="_blank" rel="noreferrer noopener">Privacy policy</a></span>', $this->template->getShortFooter());
}
- public function testGetShortFooterAllLegalLinks() {
+ public function testGetShortFooterAllLegalLinks(): void {
$this->navigationManager->expects($this->once())->method('getAll')->with(INavigationManager::TYPE_GUEST)->willReturn([]);
$this->config
->expects($this->exactly(5))
@@ -362,7 +362,7 @@ class ThemingDefaultsTest extends TestCase {
* @param $invalidImprintUrl
* @dataProvider invalidLegalUrlProvider
*/
- public function testGetShortFooterInvalidImprint($invalidImprintUrl) {
+ public function testGetShortFooterInvalidImprint($invalidImprintUrl): void {
$this->navigationManager->expects($this->once())->method('getAll')->with(INavigationManager::TYPE_GUEST)->willReturn([]);
$this->config
->expects($this->exactly(5))
@@ -382,7 +382,7 @@ class ThemingDefaultsTest extends TestCase {
* @param $invalidPrivacyUrl
* @dataProvider invalidLegalUrlProvider
*/
- public function testGetShortFooterInvalidPrivacy($invalidPrivacyUrl) {
+ public function testGetShortFooterInvalidPrivacy($invalidPrivacyUrl): void {
$this->navigationManager->expects($this->once())->method('getAll')->with(INavigationManager::TYPE_GUEST)->willReturn([]);
$this->config
->expects($this->exactly(5))
@@ -398,7 +398,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals('<a href="url" target="_blank" rel="noreferrer noopener" class="entity-name">Name</a> – Slogan', $this->template->getShortFooter());
}
- public function testGetColorPrimaryWithDefault() {
+ public function testGetColorPrimaryWithDefault(): void {
$this->appConfig
->expects(self::once())
->method('getValueBool')
@@ -413,7 +413,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals($this->defaults->getColorPrimary(), $this->template->getColorPrimary());
}
- public function testGetColorPrimaryWithCustom() {
+ public function testGetColorPrimaryWithCustom(): void {
$this->appConfig
->expects(self::once())
->method('getValueBool')
@@ -472,7 +472,7 @@ class ThemingDefaultsTest extends TestCase {
/**
* @dataProvider dataGetColorPrimary
*/
- public function testGetColorPrimary(bool $disableTheming, string $primaryColor, string $userPrimaryColor, string $expected) {
+ public function testGetColorPrimary(bool $disableTheming, string $primaryColor, string $userPrimaryColor, string $expected): void {
$user = $this->createMock(IUser::class);
$this->userSession->expects($this->any())
->method('getUser')
@@ -499,7 +499,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals($expected, $this->template->getColorPrimary());
}
- public function testSet() {
+ public function testSet(): void {
$this->config
->expects($this->exactly(2))
->method('setAppValue')
@@ -527,7 +527,7 @@ class ThemingDefaultsTest extends TestCase {
$this->template->set('MySetting', 'MyValue');
}
- public function testUndoName() {
+ public function testUndoName(): void {
$this->config
->expects($this->once())
->method('deleteAppValue')
@@ -550,7 +550,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertSame('Nextcloud', $this->template->undo('name'));
}
- public function testUndoBaseUrl() {
+ public function testUndoBaseUrl(): void {
$this->config
->expects($this->once())
->method('deleteAppValue')
@@ -573,7 +573,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertSame($this->defaults->getBaseUrl(), $this->template->undo('url'));
}
- public function testUndoSlogan() {
+ public function testUndoSlogan(): void {
$this->config
->expects($this->once())
->method('deleteAppValue')
@@ -596,7 +596,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertSame($this->defaults->getSlogan(), $this->template->undo('slogan'));
}
- public function testUndoPrimaryColor() {
+ public function testUndoPrimaryColor(): void {
$this->config
->expects($this->once())
->method('deleteAppValue')
@@ -614,7 +614,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertSame($this->defaults->getColorPrimary(), $this->template->undo('primary_color'));
}
- public function testUndoDefaultAction() {
+ public function testUndoDefaultAction(): void {
$this->config
->expects($this->once())
->method('deleteAppValue')
@@ -632,7 +632,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertSame('', $this->template->undo('defaultitem'));
}
- public function testGetBackground() {
+ public function testGetBackground(): void {
$this->imageManager
->expects($this->once())
->method('getImageUrl')
@@ -663,15 +663,15 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals('core-logo?v=0', $this->template->getLogo($useSvg));
}
- public function testGetLogoDefaultWithSvg() {
+ public function testGetLogoDefaultWithSvg(): void {
$this->getLogoHelper('logo/logo.svg', true);
}
- public function testGetLogoDefaultWithoutSvg() {
+ public function testGetLogoDefaultWithoutSvg(): void {
$this->getLogoHelper('logo/logo.png', false);
}
- public function testGetLogoCustom() {
+ public function testGetLogoCustom(): void {
$this->config
->expects($this->exactly(2))
->method('getAppValue')
@@ -689,7 +689,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals('custom-logo' . '?v=0', $this->template->getLogo());
}
- public function testGetScssVariablesCached() {
+ public function testGetScssVariablesCached(): void {
$this->config->expects($this->any())->method('getAppValue')->with('theming', 'cachebuster', '0')->willReturn('1');
$this->cacheFactory->expects($this->once())
->method('createDistributed')
@@ -699,7 +699,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals(['foo' => 'bar'], $this->template->getScssVariables());
}
- public function testGetScssVariables() {
+ public function testGetScssVariables(): void {
$this->config
->expects($this->any())
->method('getAppValue')
@@ -754,7 +754,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals($expected, $this->template->getScssVariables());
}
- public function testGetDefaultAndroidURL() {
+ public function testGetDefaultAndroidURL(): void {
$this->config
->expects($this->once())
->method('getAppValue')
@@ -764,7 +764,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals('https://play.google.com/store/apps/details?id=com.nextcloud.client', $this->template->getAndroidClientUrl());
}
- public function testGetCustomAndroidURL() {
+ public function testGetCustomAndroidURL(): void {
$this->config
->expects($this->once())
->method('getAppValue')
@@ -774,7 +774,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals('https://play.google.com/store/apps/details?id=com.mycloud.client', $this->template->getAndroidClientUrl());
}
- public function testGetDefaultiOSURL() {
+ public function testGetDefaultiOSURL(): void {
$this->config
->expects($this->once())
->method('getAppValue')
@@ -784,7 +784,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals('https://geo.itunes.apple.com/us/app/nextcloud/id1125420102?mt=8', $this->template->getiOSClientUrl());
}
- public function testGetCustomiOSURL() {
+ public function testGetCustomiOSURL(): void {
$this->config
->expects($this->once())
->method('getAppValue')
@@ -794,7 +794,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals('https://geo.itunes.apple.com/us/app/nextcloud/id1234567890?mt=8', $this->template->getiOSClientUrl());
}
- public function testGetDefaultiTunesAppId() {
+ public function testGetDefaultiTunesAppId(): void {
$this->config
->expects($this->once())
->method('getAppValue')
@@ -804,7 +804,7 @@ class ThemingDefaultsTest extends TestCase {
$this->assertEquals('1125420102', $this->template->getiTunesAppId());
}
- public function testGetCustomiTunesAppId() {
+ public function testGetCustomiTunesAppId(): void {
$this->config
->expects($this->once())
->method('getAppValue')
@@ -824,7 +824,7 @@ class ThemingDefaultsTest extends TestCase {
}
/** @dataProvider dataReplaceImagePath */
- public function testReplaceImagePath($app, $image, $result = 'themingRoute?v=1234abcd') {
+ public function testReplaceImagePath($app, $image, $result = 'themingRoute?v=1234abcd'): void {
$this->cache->expects($this->any())
->method('get')
->with('shouldReplaceIcons')
diff --git a/apps/theming/tests/UtilTest.php b/apps/theming/tests/UtilTest.php
index 474daab6030..ba160684b7a 100644
--- a/apps/theming/tests/UtilTest.php
+++ b/apps/theming/tests/UtilTest.php
@@ -47,7 +47,7 @@ class UtilTest extends TestCase {
/**
* @dataProvider dataColorContrast
*/
- public function testColorContrast(string $color1, string $color2, $contrast) {
+ public function testColorContrast(string $color1, string $color2, $contrast): void {
$this->assertEqualsWithDelta($contrast, $this->util->colorContrast($color1, $color2), .001);
}
@@ -62,78 +62,78 @@ class UtilTest extends TestCase {
/**
* @dataProvider dataInvertTextColor
*/
- public function testInvertTextColor($color, $expected) {
+ public function testInvertTextColor($color, $expected): void {
$invert = $this->util->invertTextColor($color);
$this->assertEquals($expected, $invert);
}
- public function testCalculateLuminanceLight() {
+ public function testCalculateLuminanceLight(): void {
$luminance = $this->util->calculateLuminance('#ffffff');
$this->assertEquals(1, $luminance);
}
- public function testCalculateLuminanceDark() {
+ public function testCalculateLuminanceDark(): void {
$luminance = $this->util->calculateLuminance('#000000');
$this->assertEquals(0, $luminance);
}
- public function testCalculateLuminanceLightShorthand() {
+ public function testCalculateLuminanceLightShorthand(): void {
$luminance = $this->util->calculateLuminance('#fff');
$this->assertEquals(1, $luminance);
}
- public function testCalculateLuminanceDarkShorthand() {
+ public function testCalculateLuminanceDarkShorthand(): void {
$luminance = $this->util->calculateLuminance('#000');
$this->assertEquals(0, $luminance);
}
- public function testInvertTextColorInvalid() {
+ public function testInvertTextColorInvalid(): void {
$this->expectException(\Exception::class);
$this->util->invertTextColor('aaabbbcccddd123');
}
- public function testInvertTextColorEmpty() {
+ public function testInvertTextColorEmpty(): void {
$this->expectException(\Exception::class);
$this->util->invertTextColor('');
}
- public function testElementColorDefaultBlack() {
+ public function testElementColorDefaultBlack(): void {
$elementColor = $this->util->elementColor('#000000');
$this->assertEquals('#4d4d4d', $elementColor);
}
- public function testElementColorDefaultWhite() {
+ public function testElementColorDefaultWhite(): void {
$elementColor = $this->util->elementColor('#ffffff');
$this->assertEquals('#b3b3b3', $elementColor);
}
- public function testElementColorBlackOnDarkBackground() {
+ public function testElementColorBlackOnDarkBackground(): void {
$elementColor = $this->util->elementColor('#000000', false);
$this->assertEquals('#4d4d4d', $elementColor);
}
- public function testElementColorBlackOnBrightBackground() {
+ public function testElementColorBlackOnBrightBackground(): void {
$elementColor = $this->util->elementColor('#000000', true);
$this->assertEquals('#000000', $elementColor);
}
- public function testElementColorWhiteOnBrightBackground() {
+ public function testElementColorWhiteOnBrightBackground(): void {
$elementColor = $this->util->elementColor('#ffffff', true);
$this->assertEquals('#b3b3b3', $elementColor);
}
- public function testElementColorWhiteOnDarkBackground() {
+ public function testElementColorWhiteOnDarkBackground(): void {
$elementColor = $this->util->elementColor('#ffffff', false);
$this->assertEquals('#ffffff', $elementColor);
}
- public function testGenerateRadioButtonWhite() {
+ public function testGenerateRadioButtonWhite(): void {
$button = $this->util->generateRadioButton('#ffffff');
$expected = 'PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMTYiIHdpZHRoPSIxNiI+PHBhdGggZD0iTTggMWE3IDcgMCAwIDAtNyA3IDcgNyAwIDAgMCA3IDcgNyA3IDAgMCAwIDctNyA3IDcgMCAwIDAtNy03em0wIDFhNiA2IDAgMCAxIDYgNiA2IDYgMCAwIDEtNiA2IDYgNiAwIDAgMS02LTYgNiA2IDAgMCAxIDYtNnptMCAyYTQgNCAwIDEgMCAwIDggNCA0IDAgMCAwIDAtOHoiIGZpbGw9IiNmZmZmZmYiLz48L3N2Zz4=';
$this->assertEquals($expected, $button);
}
- public function testGenerateRadioButtonBlack() {
+ public function testGenerateRadioButtonBlack(): void {
$button = $this->util->generateRadioButton('#000000');
$expected = 'PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMTYiIHdpZHRoPSIxNiI+PHBhdGggZD0iTTggMWE3IDcgMCAwIDAtNyA3IDcgNyAwIDAgMCA3IDcgNyA3IDAgMCAwIDctNyA3IDcgMCAwIDAtNy03em0wIDFhNiA2IDAgMCAxIDYgNiA2IDYgMCAwIDEtNiA2IDYgNiAwIDAgMS02LTYgNiA2IDAgMCAxIDYtNnptMCAyYTQgNCAwIDEgMCAwIDggNCA0IDAgMCAwIDAtOHoiIGZpbGw9IiMwMDAwMDAiLz48L3N2Zz4=';
$this->assertEquals($expected, $button);
@@ -142,7 +142,7 @@ class UtilTest extends TestCase {
/**
* @dataProvider dataGetAppIcon
*/
- public function testGetAppIcon($app, $expected) {
+ public function testGetAppIcon($app, $expected): void {
$this->appData->expects($this->any())
->method('getFolder')
->with('global/images')
@@ -159,7 +159,7 @@ class UtilTest extends TestCase {
];
}
- public function testGetAppIconThemed() {
+ public function testGetAppIconThemed(): void {
$file = $this->createMock(ISimpleFile::class);
$folder = $this->createMock(ISimpleFolder::class);
$folder->expects($this->once())
@@ -177,7 +177,7 @@ class UtilTest extends TestCase {
/**
* @dataProvider dataGetAppImage
*/
- public function testGetAppImage($app, $image, $expected) {
+ public function testGetAppImage($app, $image, $expected): void {
$this->assertEquals($expected, $this->util->getAppImage($app, $image));
}
@@ -190,14 +190,14 @@ class UtilTest extends TestCase {
];
}
- public function testColorizeSvg() {
+ public function testColorizeSvg(): void {
$input = '#0082c9 #0082C9 #000000 #FFFFFF';
$expected = '#AAAAAA #AAAAAA #000000 #FFFFFF';
$result = $this->util->colorizeSvg($input, '#AAAAAA');
$this->assertEquals($expected, $result);
}
- public function testIsAlreadyThemedFalse() {
+ public function testIsAlreadyThemedFalse(): void {
$this->config->expects($this->once())
->method('getSystemValue')
->with('theme', '')
@@ -206,7 +206,7 @@ class UtilTest extends TestCase {
$this->assertFalse($actual);
}
- public function testIsAlreadyThemedTrue() {
+ public function testIsAlreadyThemedTrue(): void {
$this->config->expects($this->once())
->method('getSystemValue')
->with('theme', '')
@@ -225,7 +225,7 @@ class UtilTest extends TestCase {
/**
* @dataProvider dataIsBackgroundThemed
*/
- public function testIsBackgroundThemed($backgroundMime, $expected) {
+ public function testIsBackgroundThemed($backgroundMime, $expected): void {
$this->config->expects($this->once())
->method('getAppValue')
->with('theming', 'backgroundMime', '')
diff --git a/apps/twofactor_backupcodes/tests/Db/BackupCodeMapperTest.php b/apps/twofactor_backupcodes/tests/Db/BackupCodeMapperTest.php
index ce373aea1d9..5cde4c5a718 100644
--- a/apps/twofactor_backupcodes/tests/Db/BackupCodeMapperTest.php
+++ b/apps/twofactor_backupcodes/tests/Db/BackupCodeMapperTest.php
@@ -50,7 +50,7 @@ class BackupCodeMapperTest extends TestCase {
$this->resetDB();
}
- public function testGetBackupCodes() {
+ public function testGetBackupCodes(): void {
$code1 = new BackupCode();
$code1->setUserId($this->testUID);
$code1->setCode('1|$2y$10$Fyo.DkMtkaHapVvRVbQBeeIdi5x/6nmPnxiBzD0GDKa08NMus5xze');
@@ -76,7 +76,7 @@ class BackupCodeMapperTest extends TestCase {
$this->assertInstanceOf(BackupCode::class, $dbCodes[1]);
}
- public function testDeleteCodes() {
+ public function testDeleteCodes(): void {
$code = new BackupCode();
$code->setUserId($this->testUID);
$code->setCode('1|$2y$10$CagG8pEhZL.xDirtCCP/KuuWtnsAasgq60zY9rU46dBK4w8yW0Z/y');
@@ -95,7 +95,7 @@ class BackupCodeMapperTest extends TestCase {
$this->assertCount(0, $this->mapper->getBackupCodes($user));
}
- public function testInsertArgonEncryptedCodes() {
+ public function testInsertArgonEncryptedCodes(): void {
$code = new BackupCode();
$code->setUserId($this->testUID);
$code->setCode('2|$argon2i$v=19$m=1024,t=2,p=2$MjJWUjRFWndtMm5BWGxOag$BusVxLeFyiLLWtaVvX/JRFBiPdZcjRrzpQ/rAhn6vqY');
diff --git a/apps/twofactor_backupcodes/tests/Service/BackupCodeStorageTest.php b/apps/twofactor_backupcodes/tests/Service/BackupCodeStorageTest.php
index bd300b21b94..f184cb1c75c 100644
--- a/apps/twofactor_backupcodes/tests/Service/BackupCodeStorageTest.php
+++ b/apps/twofactor_backupcodes/tests/Service/BackupCodeStorageTest.php
@@ -38,7 +38,7 @@ class BackupCodeStorageTest extends TestCase {
$this->overwriteService(IManager::class, $this->notificationManager);
}
- public function testSimpleWorkFlow() {
+ public function testSimpleWorkFlow(): void {
$user = $this->getMockBuilder(\OCP\IUser::class)->getMock();
$user->expects($this->any())
->method('getUID')
diff --git a/apps/twofactor_backupcodes/tests/Unit/Activity/ProviderTest.php b/apps/twofactor_backupcodes/tests/Unit/Activity/ProviderTest.php
index d73acad7979..fb2c419f521 100644
--- a/apps/twofactor_backupcodes/tests/Unit/Activity/ProviderTest.php
+++ b/apps/twofactor_backupcodes/tests/Unit/Activity/ProviderTest.php
@@ -41,7 +41,7 @@ class ProviderTest extends TestCase {
$this->provider = new Provider($this->l10n, $this->urlGenerator, $this->activityManager);
}
- public function testParseUnrelated() {
+ public function testParseUnrelated(): void {
$lang = 'ru';
$event = $this->createMock(IEvent::class);
$event->expects($this->once())
@@ -61,7 +61,7 @@ class ProviderTest extends TestCase {
/**
* @dataProvider subjectData
*/
- public function testParse($subject) {
+ public function testParse($subject): void {
$lang = 'ru';
$event = $this->createMock(IEvent::class);
$l = $this->createMock(IL10N::class);
@@ -93,7 +93,7 @@ class ProviderTest extends TestCase {
$this->provider->parse($lang, $event);
}
- public function testParseInvalidSubject() {
+ public function testParseInvalidSubject(): void {
$lang = 'ru';
$l = $this->createMock(IL10N::class);
$event = $this->createMock(IEvent::class);
diff --git a/apps/twofactor_backupcodes/tests/Unit/BackgroundJob/CheckBackupCodeTest.php b/apps/twofactor_backupcodes/tests/Unit/BackgroundJob/CheckBackupCodeTest.php
index 5f95994e6fa..7b6fe6cb2d8 100644
--- a/apps/twofactor_backupcodes/tests/Unit/BackgroundJob/CheckBackupCodeTest.php
+++ b/apps/twofactor_backupcodes/tests/Unit/BackgroundJob/CheckBackupCodeTest.php
@@ -63,7 +63,7 @@ class CheckBackupCodeTest extends TestCase {
);
}
- public function testRunAlreadyGenerated() {
+ public function testRunAlreadyGenerated(): void {
$this->user->method('isEnabled')
->willReturn(true);
@@ -79,7 +79,7 @@ class CheckBackupCodeTest extends TestCase {
$this->invokePrivate($this->checkBackupCodes, 'run', [[]]);
}
- public function testRun() {
+ public function testRun(): void {
$this->user->method('getUID')
->willReturn('myUID');
$this->user->method('isEnabled')
@@ -104,7 +104,7 @@ class CheckBackupCodeTest extends TestCase {
$this->invokePrivate($this->checkBackupCodes, 'run', [[]]);
}
- public function testRunDisabledUser() {
+ public function testRunDisabledUser(): void {
$this->user->method('getUID')
->willReturn('myUID');
$this->user->method('isEnabled')
@@ -120,7 +120,7 @@ class CheckBackupCodeTest extends TestCase {
$this->invokePrivate($this->checkBackupCodes, 'run', [[]]);
}
- public function testRunNoProviders() {
+ public function testRunNoProviders(): void {
$this->user->method('isEnabled')
->willReturn(true);
diff --git a/apps/twofactor_backupcodes/tests/Unit/BackgroundJob/RememberBackupCodesJobTest.php b/apps/twofactor_backupcodes/tests/Unit/BackgroundJob/RememberBackupCodesJobTest.php
index 8b2714227cd..31b7d514246 100644
--- a/apps/twofactor_backupcodes/tests/Unit/BackgroundJob/RememberBackupCodesJobTest.php
+++ b/apps/twofactor_backupcodes/tests/Unit/BackgroundJob/RememberBackupCodesJobTest.php
@@ -59,7 +59,7 @@ class RememberBackupCodesJobTest extends TestCase {
);
}
- public function testInvalidUID() {
+ public function testInvalidUID(): void {
$this->userManager->method('get')
->with('invalidUID')
->willReturn(null);
@@ -78,7 +78,7 @@ class RememberBackupCodesJobTest extends TestCase {
self::invokePrivate($this->job, 'run', [['uid' => 'invalidUID']]);
}
- public function testBackupCodesGenerated() {
+ public function testBackupCodesGenerated(): void {
$user = $this->createMock(IUser::class);
$user->method('getUID')
->willReturn('validUID');
@@ -108,7 +108,7 @@ class RememberBackupCodesJobTest extends TestCase {
self::invokePrivate($this->job, 'run', [['uid' => 'validUID']]);
}
- public function testNoActiveProvider() {
+ public function testNoActiveProvider(): void {
$user = $this->createMock(IUser::class);
$user->method('getUID')
->willReturn('validUID');
@@ -136,7 +136,7 @@ class RememberBackupCodesJobTest extends TestCase {
self::invokePrivate($this->job, 'run', [['uid' => 'validUID']]);
}
- public function testNotificationSend() {
+ public function testNotificationSend(): void {
$user = $this->createMock(IUser::class);
$user->method('getUID')
->willReturn('validUID');
@@ -176,7 +176,7 @@ class RememberBackupCodesJobTest extends TestCase {
self::invokePrivate($this->job, 'run', [['uid' => 'validUID']]);
}
- public function testNotificationNotSendForDisabledUser() {
+ public function testNotificationNotSendForDisabledUser(): void {
$user = $this->createMock(IUser::class);
$user->method('getUID')
->willReturn('validUID');
diff --git a/apps/twofactor_backupcodes/tests/Unit/Controller/SettingsControllerTest.php b/apps/twofactor_backupcodes/tests/Unit/Controller/SettingsControllerTest.php
index da4d58cf0bc..85b23e88fee 100644
--- a/apps/twofactor_backupcodes/tests/Unit/Controller/SettingsControllerTest.php
+++ b/apps/twofactor_backupcodes/tests/Unit/Controller/SettingsControllerTest.php
@@ -42,7 +42,7 @@ class SettingsControllerTest extends TestCase {
$this->controller = new SettingsController('twofactor_backupcodes', $this->request, $this->storage, $this->userSession);
}
- public function testCreateCodes() {
+ public function testCreateCodes(): void {
$user = $this->getMockBuilder(IUser::class)->getMock();
$codes = ['a', 'b'];
diff --git a/apps/twofactor_backupcodes/tests/Unit/Event/CodesGeneratedTest.php b/apps/twofactor_backupcodes/tests/Unit/Event/CodesGeneratedTest.php
index fd7841b0e98..3f619e387e9 100644
--- a/apps/twofactor_backupcodes/tests/Unit/Event/CodesGeneratedTest.php
+++ b/apps/twofactor_backupcodes/tests/Unit/Event/CodesGeneratedTest.php
@@ -13,7 +13,7 @@ use OCP\IUser;
use Test\TestCase;
class CodesGeneratedTest extends TestCase {
- public function testCodeGeneratedEvent() {
+ public function testCodeGeneratedEvent(): void {
$user = $this->createMock(IUser::class);
$event = new CodesGenerated($user);
diff --git a/apps/twofactor_backupcodes/tests/Unit/Listener/ActivityPublisherTest.php b/apps/twofactor_backupcodes/tests/Unit/Listener/ActivityPublisherTest.php
index bfb5065fdfa..72ca91ed8eb 100644
--- a/apps/twofactor_backupcodes/tests/Unit/Listener/ActivityPublisherTest.php
+++ b/apps/twofactor_backupcodes/tests/Unit/Listener/ActivityPublisherTest.php
@@ -37,7 +37,7 @@ class ActivityPublisherTest extends TestCase {
$this->listener = new ActivityPublisher($this->activityManager, $this->logger);
}
- public function testHandleGenericEvent() {
+ public function testHandleGenericEvent(): void {
$event = $this->createMock(Event::class);
$this->activityManager->expects($this->never())
->method('publish');
@@ -45,7 +45,7 @@ class ActivityPublisherTest extends TestCase {
$this->listener->handle($event);
}
- public function testHandleCodesGeneratedEvent() {
+ public function testHandleCodesGeneratedEvent(): void {
$user = $this->createMock(IUser::class);
$user->method('getUID')->willReturn('fritz');
$event = new CodesGenerated($user);
diff --git a/apps/twofactor_backupcodes/tests/Unit/Listener/ClearNotificationsTest.php b/apps/twofactor_backupcodes/tests/Unit/Listener/ClearNotificationsTest.php
index 14807ffdd5e..b4afa9c2a72 100644
--- a/apps/twofactor_backupcodes/tests/Unit/Listener/ClearNotificationsTest.php
+++ b/apps/twofactor_backupcodes/tests/Unit/Listener/ClearNotificationsTest.php
@@ -34,7 +34,7 @@ class ClearNotificationsTest extends TestCase {
$this->listener = new ClearNotifications($this->notificationManager);
}
- public function testHandleGenericEvent() {
+ public function testHandleGenericEvent(): void {
$event = $this->createMock(Event::class);
$this->notificationManager->expects($this->never())
->method($this->anything());
@@ -42,7 +42,7 @@ class ClearNotificationsTest extends TestCase {
$this->listener->handle($event);
}
- public function testHandleCodesGeneratedEvent() {
+ public function testHandleCodesGeneratedEvent(): void {
$user = $this->createMock(IUser::class);
$user->method('getUID')->willReturn('fritz');
$event = new CodesGenerated($user);
diff --git a/apps/twofactor_backupcodes/tests/Unit/Listener/ProviderDisabledTest.php b/apps/twofactor_backupcodes/tests/Unit/Listener/ProviderDisabledTest.php
index f9e9f46b1d6..7f7b5dc3011 100644
--- a/apps/twofactor_backupcodes/tests/Unit/Listener/ProviderDisabledTest.php
+++ b/apps/twofactor_backupcodes/tests/Unit/Listener/ProviderDisabledTest.php
@@ -31,7 +31,7 @@ class ProviderDisabledTest extends TestCase {
$this->listener = new ProviderDisabled($this->registy, $this->jobList);
}
- public function testHandleGenericEvent() {
+ public function testHandleGenericEvent(): void {
$event = $this->createMock(Event::class);
$this->jobList->expects($this->never())
->method($this->anything());
@@ -39,7 +39,7 @@ class ProviderDisabledTest extends TestCase {
$this->listener->handle($event);
}
- public function testHandleStillActiveProvider() {
+ public function testHandleStillActiveProvider(): void {
$user = $this->createMock(IUser::class);
$user->method('getUID')
->willReturn('myUID');
@@ -60,7 +60,7 @@ class ProviderDisabledTest extends TestCase {
$this->listener->handle($event);
}
- public function testHandleNoActiveProvider() {
+ public function testHandleNoActiveProvider(): void {
$user = $this->createMock(IUser::class);
$user->method('getUID')
->willReturn('myUID');
diff --git a/apps/twofactor_backupcodes/tests/Unit/Listener/ProviderEnabledTest.php b/apps/twofactor_backupcodes/tests/Unit/Listener/ProviderEnabledTest.php
index 60e8b13656c..145944fccca 100644
--- a/apps/twofactor_backupcodes/tests/Unit/Listener/ProviderEnabledTest.php
+++ b/apps/twofactor_backupcodes/tests/Unit/Listener/ProviderEnabledTest.php
@@ -31,7 +31,7 @@ class ProviderEnabledTest extends TestCase {
$this->listener = new ProviderEnabled($this->registy, $this->jobList);
}
- public function testHandleGenericEvent() {
+ public function testHandleGenericEvent(): void {
$event = $this->createMock(Event::class);
$this->jobList->expects($this->never())
->method($this->anything());
@@ -39,7 +39,7 @@ class ProviderEnabledTest extends TestCase {
$this->listener->handle($event);
}
- public function testHandleCodesGeneratedEventAlraedyBackupcodes() {
+ public function testHandleCodesGeneratedEventAlraedyBackupcodes(): void {
$user = $this->createMock(IUser::class);
$user->method('getUID')
->willReturn('myUID');
@@ -59,7 +59,7 @@ class ProviderEnabledTest extends TestCase {
$this->listener->handle($event);
}
- public function testHandleCodesGeneratedEventNoBackupcodes() {
+ public function testHandleCodesGeneratedEventNoBackupcodes(): void {
$user = $this->createMock(IUser::class);
$user->method('getUID')
->willReturn('myUID');
diff --git a/apps/twofactor_backupcodes/tests/Unit/Listener/RegistryUpdaterTest.php b/apps/twofactor_backupcodes/tests/Unit/Listener/RegistryUpdaterTest.php
index d23c477cb7b..4f724f888d7 100644
--- a/apps/twofactor_backupcodes/tests/Unit/Listener/RegistryUpdaterTest.php
+++ b/apps/twofactor_backupcodes/tests/Unit/Listener/RegistryUpdaterTest.php
@@ -36,7 +36,7 @@ class RegistryUpdaterTest extends TestCase {
$this->listener = new RegistryUpdater($this->registry, $this->provider);
}
- public function testHandleGenericEvent() {
+ public function testHandleGenericEvent(): void {
$event = $this->createMock(Event::class);
$this->registry->expects($this->never())
->method('enableProviderFor');
@@ -44,7 +44,7 @@ class RegistryUpdaterTest extends TestCase {
$this->listener->handle($event);
}
- public function testHandleCodesGeneratedEvent() {
+ public function testHandleCodesGeneratedEvent(): void {
$user = $this->createMock(IUser::class);
$event = new CodesGenerated($user);
$this->registry->expects($this->once())
diff --git a/apps/twofactor_backupcodes/tests/Unit/Migration/CheckBackupCodeTest.php b/apps/twofactor_backupcodes/tests/Unit/Migration/CheckBackupCodeTest.php
index 25972f8aaca..bb959ff08b3 100644
--- a/apps/twofactor_backupcodes/tests/Unit/Migration/CheckBackupCodeTest.php
+++ b/apps/twofactor_backupcodes/tests/Unit/Migration/CheckBackupCodeTest.php
@@ -28,11 +28,11 @@ class CheckBackupCodeTest extends TestCase {
$this->checkBackupsCodes = new CheckBackupCodes($this->jobList);
}
- public function testGetName() {
+ public function testGetName(): void {
$this->assertSame('Add background job to check for backup codes', $this->checkBackupsCodes->getName());
}
- public function testRun() {
+ public function testRun(): void {
$this->jobList->expects($this->once())
->method('add')
->with(
diff --git a/apps/twofactor_backupcodes/tests/Unit/Notification/NotifierTest.php b/apps/twofactor_backupcodes/tests/Unit/Notification/NotifierTest.php
index 87aca38ba73..dc42c8c0bdc 100644
--- a/apps/twofactor_backupcodes/tests/Unit/Notification/NotifierTest.php
+++ b/apps/twofactor_backupcodes/tests/Unit/Notification/NotifierTest.php
@@ -49,7 +49,7 @@ class NotifierTest extends TestCase {
}
- public function testPrepareWrongApp() {
+ public function testPrepareWrongApp(): void {
$this->expectException(\InvalidArgumentException::class);
/** @var INotification|\PHPUnit\Framework\MockObject\MockObject $notification */
@@ -64,7 +64,7 @@ class NotifierTest extends TestCase {
}
- public function testPrepareWrongSubject() {
+ public function testPrepareWrongSubject(): void {
$this->expectException(\InvalidArgumentException::class);
/** @var INotification|\PHPUnit\Framework\MockObject\MockObject $notification */
@@ -79,7 +79,7 @@ class NotifierTest extends TestCase {
$this->notifier->prepare($notification, 'en');
}
- public function testPrepare() {
+ public function testPrepare(): void {
/** @var \OCP\Notification\INotification|\PHPUnit\Framework\MockObject\MockObject $notification */
$notification = $this->createMock(INotification::class);
diff --git a/apps/twofactor_backupcodes/tests/Unit/Provider/BackupCodesProviderTest.php b/apps/twofactor_backupcodes/tests/Unit/Provider/BackupCodesProviderTest.php
index ffeb5fd1e15..24e986710c4 100644
--- a/apps/twofactor_backupcodes/tests/Unit/Provider/BackupCodesProviderTest.php
+++ b/apps/twofactor_backupcodes/tests/Unit/Provider/BackupCodesProviderTest.php
@@ -49,11 +49,11 @@ class BackupCodesProviderTest extends TestCase {
$this->provider = new BackupCodesProvider($this->appName, $this->storage, $this->l10n, $this->appManager, $this->initialState);
}
- public function testGetId() {
+ public function testGetId(): void {
$this->assertEquals('backup_codes', $this->provider->getId());
}
- public function testGetDisplayName() {
+ public function testGetDisplayName(): void {
$this->l10n->expects($this->once())
->method('t')
->with('Backup code')
@@ -61,7 +61,7 @@ class BackupCodesProviderTest extends TestCase {
$this->assertSame('l10n backup code', $this->provider->getDisplayName());
}
- public function testGetDescription() {
+ public function testGetDescription(): void {
$this->l10n->expects($this->once())
->method('t')
->with('Use backup code')
@@ -69,14 +69,14 @@ class BackupCodesProviderTest extends TestCase {
$this->assertSame('l10n use backup code', $this->provider->getDescription());
}
- public function testGetTempalte() {
+ public function testGetTempalte(): void {
$user = $this->getMockBuilder(IUser::class)->getMock();
$expected = new Template('twofactor_backupcodes', 'challenge');
$this->assertEquals($expected, $this->provider->getTemplate($user));
}
- public function testVerfiyChallenge() {
+ public function testVerfiyChallenge(): void {
$user = $this->getMockBuilder(IUser::class)->getMock();
$challenge = 'xyz';
@@ -88,7 +88,7 @@ class BackupCodesProviderTest extends TestCase {
$this->assertFalse($this->provider->verifyChallenge($user, $challenge));
}
- public function testIsTwoFactorEnabledForUser() {
+ public function testIsTwoFactorEnabledForUser(): void {
$user = $this->getMockBuilder(IUser::class)->getMock();
$this->storage->expects($this->once())
@@ -99,7 +99,7 @@ class BackupCodesProviderTest extends TestCase {
$this->assertTrue($this->provider->isTwoFactorAuthEnabledForUser($user));
}
- public function testIsActiveNoProviders() {
+ public function testIsActiveNoProviders(): void {
$user = $this->getMockBuilder(IUser::class)->getMock();
$this->appManager->expects($this->once())
@@ -119,7 +119,7 @@ class BackupCodesProviderTest extends TestCase {
$this->assertFalse($this->provider->isActive($user));
}
- public function testIsActiveWithProviders() {
+ public function testIsActiveWithProviders(): void {
$user = $this->getMockBuilder(IUser::class)->getMock();
$this->appManager->expects($this->once())
diff --git a/apps/twofactor_backupcodes/tests/Unit/Service/BackupCodeStorageTest.php b/apps/twofactor_backupcodes/tests/Unit/Service/BackupCodeStorageTest.php
index 7725102db88..67124a7a928 100644
--- a/apps/twofactor_backupcodes/tests/Unit/Service/BackupCodeStorageTest.php
+++ b/apps/twofactor_backupcodes/tests/Unit/Service/BackupCodeStorageTest.php
@@ -46,7 +46,7 @@ class BackupCodeStorageTest extends TestCase {
$this->storage = new BackupCodeStorage($this->mapper, $this->random, $this->hasher, $this->eventDispatcher);
}
- public function testCreateCodes() {
+ public function testCreateCodes(): void {
$user = $this->createMock(IUser::class);
$number = 5;
$user->method('getUID')->willReturn('fritz');
@@ -78,7 +78,7 @@ class BackupCodeStorageTest extends TestCase {
}
}
- public function testHasBackupCodes() {
+ public function testHasBackupCodes(): void {
$user = $this->createMock(IUser::class);
$codes = [
new BackupCode(),
@@ -93,7 +93,7 @@ class BackupCodeStorageTest extends TestCase {
$this->assertTrue($this->storage->hasBackupCodes($user));
}
- public function testHasBackupCodesNoCodes() {
+ public function testHasBackupCodesNoCodes(): void {
$user = $this->createMock(IUser::class);
$codes = [];
@@ -105,7 +105,7 @@ class BackupCodeStorageTest extends TestCase {
$this->assertFalse($this->storage->hasBackupCodes($user));
}
- public function testGetBackupCodeState() {
+ public function testGetBackupCodeState(): void {
$user = $this->createMock(IUser::class);
$code1 = new BackupCode();
@@ -130,7 +130,7 @@ class BackupCodeStorageTest extends TestCase {
$this->assertEquals($expected, $this->storage->getBackupCodesState($user));
}
- public function testGetBackupCodeDisabled() {
+ public function testGetBackupCodeDisabled(): void {
$user = $this->createMock(IUser::class);
$codes = [];
@@ -148,7 +148,7 @@ class BackupCodeStorageTest extends TestCase {
$this->assertEquals($expected, $this->storage->getBackupCodesState($user));
}
- public function testValidateCode() {
+ public function testValidateCode(): void {
$user = $this->createMock(IUser::class);
$code = new BackupCode();
$code->setUsed(0);
@@ -174,7 +174,7 @@ class BackupCodeStorageTest extends TestCase {
$this->assertEquals(1, $code->getUsed());
}
- public function testValidateUsedCode() {
+ public function testValidateUsedCode(): void {
$user = $this->createMock(IUser::class);
$code = new BackupCode();
$code->setUsed('1');
@@ -195,7 +195,7 @@ class BackupCodeStorageTest extends TestCase {
$this->assertFalse($this->storage->validateCode($user, 'CHALLENGE'));
}
- public function testValidateCodeWithWrongHash() {
+ public function testValidateCodeWithWrongHash(): void {
$user = $this->createMock(IUser::class);
$code = new BackupCode();
$code->setUsed(0);
diff --git a/apps/updatenotification/tests/BackgroundJob/ResetTokenTest.php b/apps/updatenotification/tests/BackgroundJob/ResetTokenTest.php
index b93efd3a275..1b0fe0cbc59 100644
--- a/apps/updatenotification/tests/BackgroundJob/ResetTokenTest.php
+++ b/apps/updatenotification/tests/BackgroundJob/ResetTokenTest.php
@@ -33,7 +33,7 @@ class ResetTokenTest extends TestCase {
);
}
- public function testRunWithNotExpiredToken() {
+ public function testRunWithNotExpiredToken(): void {
$this->timeFactory
->expects($this->atLeastOnce())
->method('getTime')
@@ -54,7 +54,7 @@ class ResetTokenTest extends TestCase {
static::invokePrivate($this->resetTokenBackgroundJob, 'run', [null]);
}
- public function testRunWithExpiredToken() {
+ public function testRunWithExpiredToken(): void {
$this->timeFactory
->expects($this->once())
->method('getTime')
@@ -72,7 +72,7 @@ class ResetTokenTest extends TestCase {
static::invokePrivate($this->resetTokenBackgroundJob, 'run', [null]);
}
- public function testRunWithExpiredTokenAndReadOnlyConfigFile() {
+ public function testRunWithExpiredTokenAndReadOnlyConfigFile(): void {
$this->timeFactory
->expects($this->never())
->method('getTime');
diff --git a/apps/updatenotification/tests/BackgroundJob/UpdateAvailableNotificationsTest.php b/apps/updatenotification/tests/BackgroundJob/UpdateAvailableNotificationsTest.php
index ca058cedff7..dccccf1a940 100644
--- a/apps/updatenotification/tests/BackgroundJob/UpdateAvailableNotificationsTest.php
+++ b/apps/updatenotification/tests/BackgroundJob/UpdateAvailableNotificationsTest.php
@@ -80,7 +80,7 @@ class UpdateAvailableNotificationsTest extends TestCase {
}
}
- public function testRun() {
+ public function testRun(): void {
$job = $this->getJob([
'checkCoreUpdate',
'checkAppUpdates',
@@ -105,7 +105,7 @@ class UpdateAvailableNotificationsTest extends TestCase {
self::invokePrivate($job, 'run', [null]);
}
- public function testRunNoInternet() {
+ public function testRunNoInternet(): void {
$job = $this->getJob([
'checkCoreUpdate',
'checkAppUpdates',
@@ -160,7 +160,7 @@ class UpdateAvailableNotificationsTest extends TestCase {
* @param null|string $readableVersion
* @param null|int $errorDays
*/
- public function testCheckCoreUpdate(string $channel, $versionCheck, $version, $readableVersion, $errorDays) {
+ public function testCheckCoreUpdate(string $channel, $versionCheck, $version, $readableVersion, $errorDays): void {
$job = $this->getJob([
'getChannel',
'createNotifications',
@@ -237,7 +237,7 @@ class UpdateAvailableNotificationsTest extends TestCase {
* @param array $isUpdateAvailable
* @param array $notifications
*/
- public function testCheckAppUpdates(array $apps, array $isUpdateAvailable, array $notifications) {
+ public function testCheckAppUpdates(array $apps, array $isUpdateAvailable, array $notifications): void {
$job = $this->getJob([
'isUpdateAvailable',
'createNotifications',
@@ -277,7 +277,7 @@ class UpdateAvailableNotificationsTest extends TestCase {
* @param string[]|null $users
* @param array|null $userNotifications
*/
- public function testCreateNotifications(string $app, string $version, $lastNotification, $callDelete, $createNotification, $users, $userNotifications) {
+ public function testCreateNotifications(string $app, string $version, $lastNotification, $callDelete, $createNotification, $users, $userNotifications): void {
$job = $this->getJob([
'deleteOutdatedNotifications',
'getUsersToNotify',
@@ -286,7 +286,7 @@ class UpdateAvailableNotificationsTest extends TestCase {
$this->appConfig->expects($this->once())
->method('getAppValueString')
->with($app, '')
- ->willReturn($lastNotification ? $lastNotification : '');
+ ->willReturn($lastNotification ?: '');
if ($lastNotification !== $version) {
$this->appConfig->expects($this->once())
@@ -364,7 +364,7 @@ class UpdateAvailableNotificationsTest extends TestCase {
* @param array $groupUsers
* @param string[] $expected
*/
- public function testGetUsersToNotify(array $groups, array $groupUsers, array $expected) {
+ public function testGetUsersToNotify(array $groups, array $groupUsers, array $expected): void {
$job = $this->getJob();
$this->appConfig->expects($this->once())
@@ -408,7 +408,7 @@ class UpdateAvailableNotificationsTest extends TestCase {
* @param string $app
* @param string $version
*/
- public function testDeleteOutdatedNotifications(string $app, string $version) {
+ public function testDeleteOutdatedNotifications(string $app, string $version): void {
$notification = $this->createMock(INotification::class);
$notification->expects($this->once())
->method('setApp')
diff --git a/apps/updatenotification/tests/Controller/AdminControllerTest.php b/apps/updatenotification/tests/Controller/AdminControllerTest.php
index 74fcb4f8773..877a0276373 100644
--- a/apps/updatenotification/tests/Controller/AdminControllerTest.php
+++ b/apps/updatenotification/tests/Controller/AdminControllerTest.php
@@ -55,7 +55,7 @@ class AdminControllerTest extends TestCase {
);
}
- public function testCreateCredentials() {
+ public function testCreateCredentials(): void {
$this->jobList
->expects($this->once())
->method('add')
diff --git a/apps/updatenotification/tests/Notification/NotifierTest.php b/apps/updatenotification/tests/Notification/NotifierTest.php
index 7455966975a..1e53b8d4aea 100644
--- a/apps/updatenotification/tests/Notification/NotifierTest.php
+++ b/apps/updatenotification/tests/Notification/NotifierTest.php
@@ -90,7 +90,7 @@ class NotifierTest extends TestCase {
* @param string $versionInstalled
* @param bool $exception
*/
- public function testUpdateAlreadyInstalledCheck(string $versionNotification, string $versionInstalled, bool $exception) {
+ public function testUpdateAlreadyInstalledCheck(string $versionNotification, string $versionInstalled, bool $exception): void {
$notifier = $this->getNotifier();
$notification = $this->createMock(INotification::class);
diff --git a/apps/updatenotification/tests/Settings/AdminTest.php b/apps/updatenotification/tests/Settings/AdminTest.php
index 80ad2ec7587..b39cb8fe127 100644
--- a/apps/updatenotification/tests/Settings/AdminTest.php
+++ b/apps/updatenotification/tests/Settings/AdminTest.php
@@ -80,7 +80,7 @@ class AdminTest extends TestCase {
);
}
- public function testGetFormWithUpdate() {
+ public function testGetFormWithUpdate(): void {
$backend1 = $this->createMock(CountUsersBackend::class);
$backend2 = $this->createMock(CountUsersBackend::class);
$backend3 = $this->createMock(CountUsersBackend::class);
@@ -206,7 +206,7 @@ class AdminTest extends TestCase {
$this->assertEquals($expected, $this->admin->getForm());
}
- public function testGetFormWithUpdateAndChangedUpdateServer() {
+ public function testGetFormWithUpdateAndChangedUpdateServer(): void {
$backend1 = $this->createMock(CountUsersBackend::class);
$backend2 = $this->createMock(CountUsersBackend::class);
$backend3 = $this->createMock(CountUsersBackend::class);
@@ -333,7 +333,7 @@ class AdminTest extends TestCase {
$this->assertEquals($expected, $this->admin->getForm());
}
- public function testGetFormWithUpdateAndCustomersUpdateServer() {
+ public function testGetFormWithUpdateAndCustomersUpdateServer(): void {
$backend1 = $this->createMock(CountUsersBackend::class);
$backend2 = $this->createMock(CountUsersBackend::class);
$backend3 = $this->createMock(CountUsersBackend::class);
@@ -461,11 +461,11 @@ class AdminTest extends TestCase {
}
- public function testGetSection() {
+ public function testGetSection(): void {
$this->assertSame('overview', $this->admin->getSection());
}
- public function testGetPriority() {
+ public function testGetPriority(): void {
$this->assertSame(11, $this->admin->getPriority());
}
@@ -527,7 +527,7 @@ class AdminTest extends TestCase {
/**
* @dataProvider changesProvider
*/
- public function testFilterChanges($changes, $userLang, $expectation) {
+ public function testFilterChanges($changes, $userLang, $expectation): void {
$iterator = $this->createMock(ILanguageIterator::class);
$iterator->expects($this->any())
->method('current')
diff --git a/apps/updatenotification/tests/UpdateCheckerTest.php b/apps/updatenotification/tests/UpdateCheckerTest.php
index 54d756ddcb7..0497a992669 100644
--- a/apps/updatenotification/tests/UpdateCheckerTest.php
+++ b/apps/updatenotification/tests/UpdateCheckerTest.php
@@ -29,7 +29,7 @@ class UpdateCheckerTest extends TestCase {
$this->updateChecker = new UpdateChecker($this->updater, $this->changesChecker);
}
- public function testGetUpdateStateWithUpdateAndInvalidLink() {
+ public function testGetUpdateStateWithUpdateAndInvalidLink(): void {
$this->updater
->expects($this->once())
->method('check')
@@ -53,7 +53,7 @@ class UpdateCheckerTest extends TestCase {
$this->assertSame($expected, $this->updateChecker->getUpdateState());
}
- public function testGetUpdateStateWithUpdateAndValidLink() {
+ public function testGetUpdateStateWithUpdateAndValidLink(): void {
$changes = [
'changelog' => 'https://nextcloud.com/changelog/#123-0-0',
'whatsNew' => [
@@ -101,7 +101,7 @@ class UpdateCheckerTest extends TestCase {
$this->assertSame($expected, $this->updateChecker->getUpdateState());
}
- public function testGetUpdateStateWithoutUpdate() {
+ public function testGetUpdateStateWithoutUpdate(): void {
$this->updater
->expects($this->once())
->method('check')
diff --git a/apps/user_ldap/l10n/es.js b/apps/user_ldap/l10n/es.js
index f4204fb5aca..46b7c8c794c 100644
--- a/apps/user_ldap/l10n/es.js
+++ b/apps/user_ldap/l10n/es.js
@@ -31,7 +31,7 @@ OC.L10N.register(
"Base DN could not be auto-detected, please revise credentials, host and port." : "Base DN no puede ser detectada automáticamente, por favor revise credenciales, host y puerto.",
"Could not detect Base DN, please enter it manually." : "No se ha podido detectar Base DN, por favor introdúzcala manualmente.",
"{nthServer}. Server" : "{nthServer}. servidor",
- "No object found in the given Base DN. Please revise." : "No se encuentra ningún objeto en la Base DN dada. Por favor revisar.",
+ "No object found in the given Base DN. Please revise." : "No se encuentra ningún objeto en el Base DN proporcionado. Por favor revisar.",
"More than 1,000 directory entries available." : "Más de 1.000 entradas de directorios disponibles.",
"_{objectsFound} entry available within the provided Base DN_::_{objectsFound} entries available within the provided Base DN_" : ["{objectsFound} entrada disponible en la base DN proporcionada","{objectsFound} entradas disponibles en la base DN proporcionada","{objectsFound} entradas disponibles en la base DN proporcionada"],
"An error occurred. Please check the Base DN, as well as connection settings and credentials." : "Un error ocurrió. Por favor revise la Base DN, también como la configuración de la conexión y credenciales.",
diff --git a/apps/user_ldap/l10n/es.json b/apps/user_ldap/l10n/es.json
index 0c96c953db0..17351635c6b 100644
--- a/apps/user_ldap/l10n/es.json
+++ b/apps/user_ldap/l10n/es.json
@@ -29,7 +29,7 @@
"Base DN could not be auto-detected, please revise credentials, host and port." : "Base DN no puede ser detectada automáticamente, por favor revise credenciales, host y puerto.",
"Could not detect Base DN, please enter it manually." : "No se ha podido detectar Base DN, por favor introdúzcala manualmente.",
"{nthServer}. Server" : "{nthServer}. servidor",
- "No object found in the given Base DN. Please revise." : "No se encuentra ningún objeto en la Base DN dada. Por favor revisar.",
+ "No object found in the given Base DN. Please revise." : "No se encuentra ningún objeto en el Base DN proporcionado. Por favor revisar.",
"More than 1,000 directory entries available." : "Más de 1.000 entradas de directorios disponibles.",
"_{objectsFound} entry available within the provided Base DN_::_{objectsFound} entries available within the provided Base DN_" : ["{objectsFound} entrada disponible en la base DN proporcionada","{objectsFound} entradas disponibles en la base DN proporcionada","{objectsFound} entradas disponibles en la base DN proporcionada"],
"An error occurred. Please check the Base DN, as well as connection settings and credentials." : "Un error ocurrió. Por favor revise la Base DN, también como la configuración de la conexión y credenciales.",
diff --git a/apps/user_ldap/lib/LoginListener.php b/apps/user_ldap/lib/LoginListener.php
index c417300b45e..f397f4694d2 100644
--- a/apps/user_ldap/lib/LoginListener.php
+++ b/apps/user_ldap/lib/LoginListener.php
@@ -42,7 +42,7 @@ class LoginListener implements IEventListener {
public function onPostLogin(IUser $user): void {
$this->logger->info(
- __CLASS__ . ' - {user} postLogin',
+ self::class . ' - {user} postLogin',
[
'app' => 'user_ldap',
'user' => $user->getUID(),
@@ -67,7 +67,7 @@ class LoginListener implements IEventListener {
$groupObject = $this->groupManager->get($groupId);
if ($groupObject === null) {
$this->logger->error(
- __CLASS__ . ' - group {group} could not be found (user {user})',
+ self::class . ' - group {group} could not be found (user {user})',
[
'app' => 'user_ldap',
'user' => $userId,
@@ -81,7 +81,7 @@ class LoginListener implements IEventListener {
} catch (Exception $e) {
if ($e->getReason() !== Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
$this->logger->error(
- __CLASS__ . ' - group {group} membership failed to be added (user {user})',
+ self::class . ' - group {group} membership failed to be added (user {user})',
[
'app' => 'user_ldap',
'user' => $userId,
@@ -96,7 +96,7 @@ class LoginListener implements IEventListener {
$this->groupBackend->addRelationshipToCaches($userId, null, $groupId);
$this->dispatcher->dispatchTyped(new UserAddedEvent($groupObject, $userObject));
$this->logger->info(
- __CLASS__ . ' - {user} added to {group}',
+ self::class . ' - {user} added to {group}',
[
'app' => 'user_ldap',
'user' => $userId,
@@ -110,7 +110,7 @@ class LoginListener implements IEventListener {
} catch (Exception $e) {
if ($e->getReason() !== Exception::REASON_DATABASE_OBJECT_NOT_FOUND) {
$this->logger->error(
- __CLASS__ . ' - group {group} membership failed to be removed (user {user})',
+ self::class . ' - group {group} membership failed to be removed (user {user})',
[
'app' => 'user_ldap',
'user' => $userId,
@@ -125,7 +125,7 @@ class LoginListener implements IEventListener {
$groupObject = $this->groupManager->get($groupId);
if ($groupObject === null) {
$this->logger->error(
- __CLASS__ . ' - group {group} could not be found (user {user})',
+ self::class . ' - group {group} could not be found (user {user})',
[
'app' => 'user_ldap',
'user' => $userId,
diff --git a/apps/user_ldap/lib/Service/UpdateGroupsService.php b/apps/user_ldap/lib/Service/UpdateGroupsService.php
index 4c007f7201f..94f2a7fd4a1 100644
--- a/apps/user_ldap/lib/Service/UpdateGroupsService.php
+++ b/apps/user_ldap/lib/Service/UpdateGroupsService.php
@@ -90,7 +90,7 @@ class UpdateGroupsService {
if ($e->getReason() !== Exception::REASON_DATABASE_OBJECT_NOT_FOUND) {
/* If reason is not found something else removed the membership, that’s fine */
$this->logger->error(
- __CLASS__ . ' - group {group} membership failed to be removed (user {user})',
+ self::class . ' - group {group} membership failed to be removed (user {user})',
[
'app' => 'user_ldap',
'user' => $removedUser,
@@ -121,7 +121,7 @@ class UpdateGroupsService {
if ($e->getReason() !== Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
/* If reason is unique constraint something else added the membership, that’s fine */
$this->logger->error(
- __CLASS__ . ' - group {group} membership failed to be added (user {user})',
+ self::class . ' - group {group} membership failed to be added (user {user})',
[
'app' => 'user_ldap',
'user' => $addedUser,
@@ -167,7 +167,7 @@ class UpdateGroupsService {
} catch (Exception $e) {
if ($e->getReason() !== Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
$this->logger->error(
- __CLASS__ . ' - group {group} membership failed to be added (user {user})',
+ self::class . ' - group {group} membership failed to be added (user {user})',
[
'app' => 'user_ldap',
'user' => $user,
diff --git a/apps/user_ldap/lib/SetupChecks/LdapConnection.php b/apps/user_ldap/lib/SetupChecks/LdapConnection.php
index e0e9e6b63d0..a33dd10f063 100644
--- a/apps/user_ldap/lib/SetupChecks/LdapConnection.php
+++ b/apps/user_ldap/lib/SetupChecks/LdapConnection.php
@@ -58,7 +58,7 @@ class LdapConnection implements ISetupCheck {
if (!empty($bindFailedConfigurations)) {
$output .= $this->l10n->n(
'Binding failed for this LDAP configuration: %s',
- 'Binding failed for these LDAP configurations: %s',
+ 'Binding failed for %n LDAP configurations: %s',
count($bindFailedConfigurations),
[implode(',', $bindFailedConfigurations)]
)."\n";
@@ -66,7 +66,7 @@ class LdapConnection implements ISetupCheck {
if (!empty($searchFailedConfigurations)) {
$output .= $this->l10n->n(
'Searching failed for this LDAP configuration: %s',
- 'Searching failed for these LDAP configurations: %s',
+ 'Searching failed for %n LDAP configurations: %s',
count($searchFailedConfigurations),
[implode(',', $searchFailedConfigurations)]
)."\n";
@@ -74,7 +74,7 @@ class LdapConnection implements ISetupCheck {
if (!empty($inactiveConfigurations)) {
$output .= $this->l10n->n(
'There is an inactive LDAP configuration: %s',
- 'There are inactive LDAP configurations: %s',
+ 'There are %n inactive LDAP configurations: %s',
count($inactiveConfigurations),
[implode(',', $inactiveConfigurations)]
)."\n";
@@ -86,7 +86,7 @@ class LdapConnection implements ISetupCheck {
}
return SetupResult::success($this->l10n->n(
'Binding and searching works on the configured LDAP connection (%s)',
- 'Binding and searching works on all of the configured LDAP connections (%s)',
+ 'Binding and searching works on all of the %n configured LDAP connections (%s)',
count($availableConfigs),
[implode(',', $availableConfigs)]
));
diff --git a/apps/user_ldap/lib/User/User.php b/apps/user_ldap/lib/User/User.php
index b500c72ca98..3423455e819 100644
--- a/apps/user_ldap/lib/User/User.php
+++ b/apps/user_ldap/lib/User/User.php
@@ -646,8 +646,7 @@ class User {
try {
$accountProperty = $account->getProperty($property);
$currentValue = $accountProperty->getValue();
- $scope = ($accountProperty->getScope() ? $accountProperty->getScope()
- : $defaultScopes[$property]);
+ $scope = ($accountProperty->getScope() ?: $defaultScopes[$property]);
} catch (PropertyDoesNotExistException $e) { // thrown at getProperty
$this->logger->error('property does not exist: '.$property
.' for uid='.$this->uid.'', ['app' => 'user_ldap', 'exception' => $e]);
diff --git a/apps/user_ldap/tests/AccessTest.php b/apps/user_ldap/tests/AccessTest.php
index b04a9f69e0b..79c0f3216a2 100644
--- a/apps/user_ldap/tests/AccessTest.php
+++ b/apps/user_ldap/tests/AccessTest.php
@@ -122,18 +122,18 @@ class AccessTest extends TestCase {
return [$lw, $connector, $um, $helper];
}
- public function testEscapeFilterPartValidChars() {
+ public function testEscapeFilterPartValidChars(): void {
$input = 'okay';
$this->assertTrue($input === $this->access->escapeFilterPart($input));
}
- public function testEscapeFilterPartEscapeWildcard() {
+ public function testEscapeFilterPartEscapeWildcard(): void {
$input = '*';
$expected = '\\2a';
$this->assertTrue($expected === $this->access->escapeFilterPart($input));
}
- public function testEscapeFilterPartEscapeWildcard2() {
+ public function testEscapeFilterPartEscapeWildcard2(): void {
$input = 'foo*bar';
$expected = 'foo\\2abar';
$this->assertTrue($expected === $this->access->escapeFilterPart($input));
@@ -144,7 +144,7 @@ class AccessTest extends TestCase {
* @param array $sidArray
* @param $sidExpected
*/
- public function testConvertSID2StrSuccess(array $sidArray, $sidExpected) {
+ public function testConvertSID2StrSuccess(array $sidArray, $sidExpected): void {
$sidBinary = implode('', $sidArray);
$this->assertSame($sidExpected, $this->access->convertSID2Str($sidBinary));
}
@@ -176,14 +176,14 @@ class AccessTest extends TestCase {
];
}
- public function testConvertSID2StrInputError() {
+ public function testConvertSID2StrInputError(): void {
$sidIllegal = 'foobar';
$sidExpected = '';
$this->assertSame($sidExpected, $this->access->convertSID2Str($sidIllegal));
}
- public function testGetDomainDNFromDNSuccess() {
+ public function testGetDomainDNFromDNSuccess(): void {
$inputDN = 'uid=zaphod,cn=foobar,dc=my,dc=server,dc=com';
$domainDN = 'dc=my,dc=server,dc=com';
@@ -195,7 +195,7 @@ class AccessTest extends TestCase {
$this->assertSame($domainDN, $this->access->getDomainDNFromDN($inputDN));
}
- public function testGetDomainDNFromDNError() {
+ public function testGetDomainDNFromDNError(): void {
$inputDN = 'foobar';
$expected = '';
@@ -231,7 +231,7 @@ class AccessTest extends TestCase {
* @dataProvider dnInputDataProvider
* @param array $case
*/
- public function testStringResemblesDN($case) {
+ public function testStringResemblesDN($case): void {
[$lw, $con, $um, $helper] = $this->getConnectorAndLdapMock();
/** @var IConfig|MockObject $config */
$config = $this->createMock(IConfig::class);
@@ -253,7 +253,7 @@ class AccessTest extends TestCase {
* @dataProvider dnInputDataProvider
* @param $case
*/
- public function testStringResemblesDNLDAPmod($case) {
+ public function testStringResemblesDNLDAPmod($case): void {
[, $con, $um, $helper] = $this->getConnectorAndLdapMock();
/** @var IConfig|MockObject $config */
$config = $this->createMock(IConfig::class);
@@ -267,14 +267,14 @@ class AccessTest extends TestCase {
$this->assertSame($case['expectedResult'], $access->stringResemblesDN($case['input']));
}
- public function testCacheUserHome() {
+ public function testCacheUserHome(): void {
$this->connection->expects($this->once())
->method('writeToCache');
$this->access->cacheUserHome('foobar', '/foobars/path');
}
- public function testBatchApplyUserAttributes() {
+ public function testBatchApplyUserAttributes(): void {
$this->ldap->expects($this->any())
->method('isResource')
->willReturn(true);
@@ -332,7 +332,7 @@ class AccessTest extends TestCase {
$this->access->batchApplyUserAttributes($data);
}
- public function testBatchApplyUserAttributesSkipped() {
+ public function testBatchApplyUserAttributesSkipped(): void {
/** @var UserMapping|MockObject $mapperMock */
$mapperMock = $this->createMock(UserMapping::class);
$mapperMock->expects($this->any())
@@ -373,7 +373,7 @@ class AccessTest extends TestCase {
$this->access->batchApplyUserAttributes($data);
}
- public function testBatchApplyUserAttributesDontSkip() {
+ public function testBatchApplyUserAttributesDontSkip(): void {
/** @var UserMapping|MockObject $mapperMock */
$mapperMock = $this->createMock(UserMapping::class);
$mapperMock->expects($this->any())
@@ -428,7 +428,7 @@ class AccessTest extends TestCase {
* @dataProvider dNAttributeProvider
* @param $attribute
*/
- public function testSanitizeDN($attribute) {
+ public function testSanitizeDN($attribute): void {
[$lw, $con, $um, $helper] = $this->getConnectorAndLdapMock();
/** @var IConfig|MockObject $config */
$config = $this->createMock(IConfig::class);
@@ -450,7 +450,7 @@ class AccessTest extends TestCase {
}
- public function testSetPasswordWithDisabledChanges() {
+ public function testSetPasswordWithDisabledChanges(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('LDAP password changes are disabled');
@@ -462,7 +462,7 @@ class AccessTest extends TestCase {
$this->access->setPassword('CN=foo', 'MyPassword');
}
- public function testSetPasswordWithLdapNotAvailable() {
+ public function testSetPasswordWithLdapNotAvailable(): void {
$this->connection
->method('__get')
->willReturn(true);
@@ -481,7 +481,7 @@ class AccessTest extends TestCase {
}
- public function testSetPasswordWithRejectedChange() {
+ public function testSetPasswordWithRejectedChange(): void {
$this->expectException(\OCP\HintException::class);
$this->expectExceptionMessage('Password change rejected.');
@@ -503,7 +503,7 @@ class AccessTest extends TestCase {
$this->access->setPassword('CN=foo', 'MyPassword');
}
- public function testSetPassword() {
+ public function testSetPassword(): void {
$this->connection
->method('__get')
->willReturn(true);
@@ -565,7 +565,7 @@ class AccessTest extends TestCase {
->willReturnArgument(0);
}
- public function testSearchNoPagedSearch() {
+ public function testSearchNoPagedSearch(): void {
// scenario: no pages search, 1 search base
$filter = 'objectClass=nextcloudUser';
$base = 'ou=zombies,dc=foobar,dc=nextcloud,dc=com';
@@ -592,7 +592,7 @@ class AccessTest extends TestCase {
$this->assertSame($expected, $result);
}
- public function testFetchListOfUsers() {
+ public function testFetchListOfUsers(): void {
$filter = 'objectClass=nextcloudUser';
$base = 'ou=zombies,dc=foobar,dc=nextcloud,dc=com';
$attrs = ['dn', 'uid'];
@@ -635,7 +635,7 @@ class AccessTest extends TestCase {
$this->assertSame($expected, $list);
}
- public function testFetchListOfGroupsKnown() {
+ public function testFetchListOfGroupsKnown(): void {
$filter = 'objectClass=nextcloudGroup';
$attributes = ['cn', 'gidNumber', 'dn'];
$base = 'ou=SomeGroups,dc=my,dc=directory';
@@ -715,7 +715,7 @@ class AccessTest extends TestCase {
* @param $name
* @param $expected
*/
- public function testSanitizeUsername($name, $expected) {
+ public function testSanitizeUsername($name, $expected): void {
if ($expected === null) {
$this->expectException(\InvalidArgumentException::class);
}
@@ -726,12 +726,12 @@ class AccessTest extends TestCase {
/**
* @dataProvider groupIDCandidateProvider
*/
- public function testSanitizeGroupIDCandidate(string $name, string $expected) {
+ public function testSanitizeGroupIDCandidate(string $name, string $expected): void {
$sanitizedName = $this->access->sanitizeGroupIDCandidate($name);
$this->assertSame($expected, $sanitizedName);
}
- public function testUserStateUpdate() {
+ public function testUserStateUpdate(): void {
$this->connection->expects($this->any())
->method('__get')
->willReturnMap([
diff --git a/apps/user_ldap/tests/ConfigurationTest.php b/apps/user_ldap/tests/ConfigurationTest.php
index 96b08c4cf8a..cced8334bf5 100644
--- a/apps/user_ldap/tests/ConfigurationTest.php
+++ b/apps/user_ldap/tests/ConfigurationTest.php
@@ -89,7 +89,7 @@ class ConfigurationTest extends \Test\TestCase {
/**
* @dataProvider configurationDataProvider
*/
- public function testSetValue($key, $input, $expected) {
+ public function testSetValue($key, $input, $expected): void {
$this->configuration->setConfiguration([$key => $input]);
$this->assertSame($this->configuration->$key, $expected);
}
@@ -108,7 +108,7 @@ class ConfigurationTest extends \Test\TestCase {
/**
* @dataProvider avatarRuleValueProvider
*/
- public function testGetAvatarAttributes($setting, $expected) {
+ public function testGetAvatarAttributes($setting, $expected): void {
$this->configuration->setConfiguration(['ldapUserAvatarRule' => $setting]);
$this->assertSame($expected, $this->configuration->getAvatarAttributes());
}
@@ -116,7 +116,7 @@ class ConfigurationTest extends \Test\TestCase {
/**
* @dataProvider avatarRuleValueProvider
*/
- public function testResolveRule($setting, $expected) {
+ public function testResolveRule($setting, $expected): void {
$this->configuration->setConfiguration(['ldapUserAvatarRule' => $setting]);
// so far the only thing that can get resolved :)
$this->assertSame($expected, $this->configuration->resolveRule('avatar'));
diff --git a/apps/user_ldap/tests/ConnectionTest.php b/apps/user_ldap/tests/ConnectionTest.php
index 9d8202ad155..348a8878ea6 100644
--- a/apps/user_ldap/tests/ConnectionTest.php
+++ b/apps/user_ldap/tests/ConnectionTest.php
@@ -39,7 +39,7 @@ class ConnectionTest extends \Test\TestCase {
->willReturn(true);
}
- public function testOriginalAgentUnchangedOnClone() {
+ public function testOriginalAgentUnchangedOnClone(): void {
//background: upon login a bind is done with the user credentials
//which is valid for the whole LDAP resource. It needs to be reset
//to the agent's credentials
@@ -66,7 +66,7 @@ class ConnectionTest extends \Test\TestCase {
$this->assertSame($agentPawd, $agent['ldapAgentPassword']);
}
- public function testUseBackupServer() {
+ public function testUseBackupServer(): void {
$mainHost = 'ldap://nixda.ldap';
$backupHost = 'ldap://fallback.ldap';
$config = [
@@ -125,7 +125,7 @@ class ConnectionTest extends \Test\TestCase {
$this->connection->init();
}
- public function testDontUseBackupServerOnFailedAuth() {
+ public function testDontUseBackupServerOnFailedAuth(): void {
$mainHost = 'ldap://nixda.ldap';
$backupHost = 'ldap://fallback.ldap';
$config = [
@@ -172,7 +172,7 @@ class ConnectionTest extends \Test\TestCase {
$this->connection->init();
}
- public function testBindWithInvalidCredentials() {
+ public function testBindWithInvalidCredentials(): void {
// background: Bind with invalid credentials should return false
// and not throw a ServerNotAvailableException.
@@ -217,7 +217,7 @@ class ConnectionTest extends \Test\TestCase {
}
}
- public function testStartTlsNegotiationFailure() {
+ public function testStartTlsNegotiationFailure(): void {
// background: If Start TLS negotiation fails,
// a ServerNotAvailableException should be thrown.
diff --git a/apps/user_ldap/tests/GroupLDAPPluginTest.php b/apps/user_ldap/tests/GroupLDAPPluginTest.php
index 62c77298449..496a86ba245 100644
--- a/apps/user_ldap/tests/GroupLDAPPluginTest.php
+++ b/apps/user_ldap/tests/GroupLDAPPluginTest.php
@@ -17,7 +17,7 @@ class GroupLDAPPluginTest extends \Test\TestCase {
return new GroupPluginManager();
}
- public function testImplementsActions() {
+ public function testImplementsActions(): void {
$pluginManager = $this->getGroupPluginManager();
$plugin = $this->getMockBuilder(\OCA\User_LDAP\Tests\LDAPGroupPluginDummy::class)
@@ -44,7 +44,7 @@ class GroupLDAPPluginTest extends \Test\TestCase {
$this->assertTrue($pluginManager->implementsActions(GroupInterface::ADD_TO_GROUP));
}
- public function testCreateGroup() {
+ public function testCreateGroup(): void {
$pluginManager = $this->getGroupPluginManager();
$plugin = $this->getMockBuilder(\OCA\User_LDAP\Tests\LDAPGroupPluginDummy::class)
@@ -66,7 +66,7 @@ class GroupLDAPPluginTest extends \Test\TestCase {
}
- public function testCreateGroupNotRegistered() {
+ public function testCreateGroupNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements createGroup in this LDAP Backend.');
@@ -74,7 +74,7 @@ class GroupLDAPPluginTest extends \Test\TestCase {
$pluginManager->createGroup('foo');
}
- public function testDeleteGroup() {
+ public function testDeleteGroup(): void {
$pluginManager = $this->getGroupPluginManager();
$plugin = $this->getMockBuilder(\OCA\User_LDAP\Tests\LDAPGroupPluginDummy::class)
@@ -96,7 +96,7 @@ class GroupLDAPPluginTest extends \Test\TestCase {
}
- public function testDeleteGroupNotRegistered() {
+ public function testDeleteGroupNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements deleteGroup in this LDAP Backend.');
@@ -104,7 +104,7 @@ class GroupLDAPPluginTest extends \Test\TestCase {
$pluginManager->deleteGroup('foo');
}
- public function testAddToGroup() {
+ public function testAddToGroup(): void {
$pluginManager = $this->getGroupPluginManager();
$plugin = $this->getMockBuilder(\OCA\User_LDAP\Tests\LDAPGroupPluginDummy::class)
@@ -127,7 +127,7 @@ class GroupLDAPPluginTest extends \Test\TestCase {
}
- public function testAddToGroupNotRegistered() {
+ public function testAddToGroupNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements addToGroup in this LDAP Backend.');
@@ -135,7 +135,7 @@ class GroupLDAPPluginTest extends \Test\TestCase {
$pluginManager->addToGroup('foo', 'bar');
}
- public function testRemoveFromGroup() {
+ public function testRemoveFromGroup(): void {
$pluginManager = $this->getGroupPluginManager();
$plugin = $this->getMockBuilder(\OCA\User_LDAP\Tests\LDAPGroupPluginDummy::class)
@@ -158,7 +158,7 @@ class GroupLDAPPluginTest extends \Test\TestCase {
}
- public function testRemoveFromGroupNotRegistered() {
+ public function testRemoveFromGroupNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements removeFromGroup in this LDAP Backend.');
@@ -166,7 +166,7 @@ class GroupLDAPPluginTest extends \Test\TestCase {
$pluginManager->removeFromGroup('foo', 'bar');
}
- public function testCountUsersInGroup() {
+ public function testCountUsersInGroup(): void {
$pluginManager = $this->getGroupPluginManager();
$plugin = $this->getMockBuilder(\OCA\User_LDAP\Tests\LDAPGroupPluginDummy::class)
@@ -189,7 +189,7 @@ class GroupLDAPPluginTest extends \Test\TestCase {
}
- public function testCountUsersInGroupNotRegistered() {
+ public function testCountUsersInGroupNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements countUsersInGroup in this LDAP Backend.');
@@ -197,7 +197,7 @@ class GroupLDAPPluginTest extends \Test\TestCase {
$pluginManager->countUsersInGroup('foo', 'bar');
}
- public function testgetGroupDetails() {
+ public function testgetGroupDetails(): void {
$pluginManager = $this->getGroupPluginManager();
$plugin = $this->getMockBuilder(\OCA\User_LDAP\Tests\LDAPGroupPluginDummy::class)
@@ -219,7 +219,7 @@ class GroupLDAPPluginTest extends \Test\TestCase {
}
- public function testgetGroupDetailsNotRegistered() {
+ public function testgetGroupDetailsNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements getGroupDetails in this LDAP Backend.');
diff --git a/apps/user_ldap/tests/Group_LDAPTest.php b/apps/user_ldap/tests/Group_LDAPTest.php
index 06d64b99a4f..58006627410 100644
--- a/apps/user_ldap/tests/Group_LDAPTest.php
+++ b/apps/user_ldap/tests/Group_LDAPTest.php
@@ -51,7 +51,7 @@ class Group_LDAPTest extends TestCase {
$this->groupBackend = new GroupLDAP($this->access, $this->pluginManager, $this->config, $this->ncUserManager);
}
- public function testCountEmptySearchString() {
+ public function testCountEmptySearchString(): void {
$groupDN = 'cn=group,dc=foo,dc=bar';
$this->enableGroups();
@@ -130,7 +130,7 @@ class Group_LDAPTest extends TestCase {
});
}
- public function testCountWithSearchString() {
+ public function testCountWithSearchString(): void {
$this->enableGroups();
$this->access->expects($this->any())
@@ -174,7 +174,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame(2, $users);
}
- public function testCountUsersWithPlugin() {
+ public function testCountUsersWithPlugin(): void {
/** @var GroupPluginManager|MockObject $pluginManager */
$this->pluginManager = $this->getMockBuilder(GroupPluginManager::class)
->setMethods(['implementsActions', 'countUsersInGroup'])
@@ -194,7 +194,7 @@ class Group_LDAPTest extends TestCase {
$this->assertEquals($this->groupBackend->countUsersInGroup('gid', 'search'), 42);
}
- public function testGidNumber2NameSuccess() {
+ public function testGidNumber2NameSuccess(): void {
$this->enableGroups();
$userDN = 'cn=alice,cn=foo,dc=barfoo,dc=bar';
@@ -214,7 +214,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame('MyGroup', $group);
}
- public function testGidNumberID2NameNoGroup() {
+ public function testGidNumberID2NameNoGroup(): void {
$this->enableGroups();
$userDN = 'cn=alice,cn=foo,dc=barfoo,dc=bar';
@@ -232,7 +232,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame(false, $group);
}
- public function testGidNumberID2NameNoName() {
+ public function testGidNumberID2NameNoName(): void {
$this->enableGroups();
$userDN = 'cn=alice,cn=foo,dc=barfoo,dc=bar';
@@ -251,7 +251,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame(false, $group);
}
- public function testGetEntryGidNumberValue() {
+ public function testGetEntryGidNumberValue(): void {
$this->enableGroups();
$dn = 'cn=foobar,cn=foo,dc=barfoo,dc=bar';
@@ -268,7 +268,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame('3117', $gid);
}
- public function testGetEntryGidNumberNoValue() {
+ public function testGetEntryGidNumberNoValue(): void {
$this->enableGroups();
$dn = 'cn=foobar,cn=foo,dc=barfoo,dc=bar';
@@ -285,7 +285,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame(false, $gid);
}
- public function testPrimaryGroupID2NameSuccessCache() {
+ public function testPrimaryGroupID2NameSuccessCache(): void {
$this->enableGroups();
$userDN = 'cn=alice,cn=foo,dc=barfoo,dc=bar';
@@ -313,7 +313,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame('MyGroup', $group);
}
- public function testPrimaryGroupID2NameSuccess() {
+ public function testPrimaryGroupID2NameSuccess(): void {
$this->enableGroups();
$userDN = 'cn=alice,cn=foo,dc=barfoo,dc=bar';
@@ -338,7 +338,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame('MyGroup', $group);
}
- public function testPrimaryGroupID2NameNoSID() {
+ public function testPrimaryGroupID2NameNoSID(): void {
$this->enableGroups();
$userDN = 'cn=alice,cn=foo,dc=barfoo,dc=bar';
@@ -360,7 +360,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame(false, $group);
}
- public function testPrimaryGroupID2NameNoGroup() {
+ public function testPrimaryGroupID2NameNoGroup(): void {
$this->enableGroups();
$userDN = 'cn=alice,cn=foo,dc=barfoo,dc=bar';
@@ -383,7 +383,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame(false, $group);
}
- public function testPrimaryGroupID2NameNoName() {
+ public function testPrimaryGroupID2NameNoName(): void {
$this->enableGroups();
$userDN = 'cn=alice,cn=foo,dc=barfoo,dc=bar';
@@ -407,7 +407,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame(false, $group);
}
- public function testGetEntryGroupIDValue() {
+ public function testGetEntryGroupIDValue(): void {
//tests getEntryGroupID via getGroupPrimaryGroupID
//which is basically identical to getUserPrimaryGroupIDs
$this->enableGroups();
@@ -426,7 +426,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame('3117', $gid);
}
- public function testGetEntryGroupIDNoValue() {
+ public function testGetEntryGroupIDNoValue(): void {
//tests getEntryGroupID via getGroupPrimaryGroupID
//which is basically identical to getUserPrimaryGroupIDs
$this->enableGroups();
@@ -449,7 +449,7 @@ class Group_LDAPTest extends TestCase {
* tests whether Group Backend behaves correctly when cache with uid and gid
* is hit
*/
- public function testInGroupHitsUidGidCache() {
+ public function testInGroupHitsUidGidCache(): void {
$this->enableGroups();
$uid = 'someUser';
@@ -486,7 +486,7 @@ class Group_LDAPTest extends TestCase {
/**
* @dataProvider groupWithMembersProvider
*/
- public function testInGroupMember(string $gid, string $groupDn, array $memberDNs) {
+ public function testInGroupMember(string $gid, string $groupDn, array $memberDNs): void {
$uid = 'someUser';
$userDn = $memberDNs[0];
@@ -527,7 +527,7 @@ class Group_LDAPTest extends TestCase {
/**
* @dataProvider groupWithMembersProvider
*/
- public function testInGroupMemberNot(string $gid, string $groupDn, array $memberDNs) {
+ public function testInGroupMemberNot(string $gid, string $groupDn, array $memberDNs): void {
$uid = 'unelatedUser';
$userDn = 'uid=unrelatedUser,ou=unrelatedTeam,ou=unrelatedDepartment,dc=someDomain,dc=someTld';
@@ -568,7 +568,7 @@ class Group_LDAPTest extends TestCase {
/**
* @dataProvider groupWithMembersProvider
*/
- public function testInGroupMemberUid(string $gid, string $groupDn, array $memberDNs) {
+ public function testInGroupMemberUid(string $gid, string $groupDn, array $memberDNs): void {
$memberUids = [];
$userRecords = [];
foreach ($memberDNs as $dn) {
@@ -625,7 +625,7 @@ class Group_LDAPTest extends TestCase {
$this->assertTrue($this->groupBackend->inGroup($uid, $gid));
}
- public function testGetGroupsWithOffset() {
+ public function testGetGroupsWithOffset(): void {
$this->enableGroups();
$this->access->expects($this->once())
@@ -642,7 +642,7 @@ class Group_LDAPTest extends TestCase {
* tests that a user listing is complete, if all its members have the group
* as their primary.
*/
- public function testUsersInGroupPrimaryMembersOnly() {
+ public function testUsersInGroupPrimaryMembersOnly(): void {
$this->enableGroups();
$this->access->connection->expects($this->any())
@@ -685,7 +685,7 @@ class Group_LDAPTest extends TestCase {
* tests that a user listing is complete, if all its members have the group
* as their primary.
*/
- public function testUsersInGroupPrimaryAndUnixMembers() {
+ public function testUsersInGroupPrimaryAndUnixMembers(): void {
$this->enableGroups();
$this->access->connection->expects($this->any())
@@ -726,7 +726,7 @@ class Group_LDAPTest extends TestCase {
* tests that a user counting is complete, if all its members have the group
* as their primary.
*/
- public function testCountUsersInGroupPrimaryMembersOnly() {
+ public function testCountUsersInGroupPrimaryMembersOnly(): void {
$this->enableGroups();
$this->access->connection->expects($this->any())
@@ -761,7 +761,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame(4, $users);
}
- public function testGetUserGroupsMemberOf() {
+ public function testGetUserGroupsMemberOf(): void {
$this->enableGroups();
$dn = 'cn=userX,dc=foobar';
@@ -797,7 +797,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame(2, count($groups));
}
- public function testGetUserGroupsMemberOfDisabled() {
+ public function testGetUserGroupsMemberOfDisabled(): void {
$this->access->connection->expects($this->any())
->method('__get')
->willReturnCallback(function ($name) {
@@ -856,7 +856,7 @@ class Group_LDAPTest extends TestCase {
$this->groupBackend->getUserGroups('userX');
}
- public function testGetUserGroupsOfflineUser() {
+ public function testGetUserGroupsOfflineUser(): void {
$this->enableGroups();
$offlineUser = $this->createMock(OfflineUser::class);
@@ -882,7 +882,7 @@ class Group_LDAPTest extends TestCase {
* regression tests against a case where a json object was stored instead of expected list
* @see https://github.com/nextcloud/server/issues/42374
*/
- public function testGetUserGroupsOfflineUserUnexpectedJson() {
+ public function testGetUserGroupsOfflineUserUnexpectedJson(): void {
$this->enableGroups();
$offlineUser = $this->createMock(OfflineUser::class);
@@ -905,7 +905,7 @@ class Group_LDAPTest extends TestCase {
$this->assertTrue(in_array('groupF', $returnedGroups));
}
- public function testGetUserGroupsUnrecognizedOfflineUser() {
+ public function testGetUserGroupsUnrecognizedOfflineUser(): void {
$this->enableGroups();
$dn = 'cn=userX,dc=foobar';
@@ -958,7 +958,7 @@ class Group_LDAPTest extends TestCase {
/**
* @dataProvider nestedGroupsProvider
*/
- public function testGetGroupsByMember(bool $nestedGroups) {
+ public function testGetGroupsByMember(bool $nestedGroups): void {
$groupFilter = '(&(objectclass=nextcloudGroup)(nextcloudEnabled=TRUE))';
$this->access->connection->expects($this->any())
->method('__get')
@@ -1072,7 +1072,7 @@ class Group_LDAPTest extends TestCase {
$this->assertEquals($expectedGroupsNames, $groupsAgain);
}
- public function testCreateGroupWithPlugin() {
+ public function testCreateGroupWithPlugin(): void {
$this->pluginManager = $this->getMockBuilder(GroupPluginManager::class)
->setMethods(['implementsActions', 'createGroup'])
->getMock();
@@ -1092,7 +1092,7 @@ class Group_LDAPTest extends TestCase {
}
- public function testCreateGroupFailing() {
+ public function testCreateGroupFailing(): void {
$this->expectException(\Exception::class);
$this->pluginManager = $this->getMockBuilder(GroupPluginManager::class)
@@ -1108,7 +1108,7 @@ class Group_LDAPTest extends TestCase {
$this->groupBackend->createGroup('gid');
}
- public function testDeleteGroupWithPlugin() {
+ public function testDeleteGroupWithPlugin(): void {
$this->pluginManager = $this->getMockBuilder(GroupPluginManager::class)
->setMethods(['implementsActions', 'deleteGroup'])
->getMock();
@@ -1137,7 +1137,7 @@ class Group_LDAPTest extends TestCase {
}
- public function testDeleteGroupFailing() {
+ public function testDeleteGroupFailing(): void {
$this->expectException(\Exception::class);
$this->pluginManager = $this->getMockBuilder(GroupPluginManager::class)
@@ -1153,7 +1153,7 @@ class Group_LDAPTest extends TestCase {
$this->groupBackend->deleteGroup('gid');
}
- public function testAddToGroupWithPlugin() {
+ public function testAddToGroupWithPlugin(): void {
$this->pluginManager = $this->getMockBuilder(GroupPluginManager::class)
->setMethods(['implementsActions', 'addToGroup'])
->getMock();
@@ -1173,7 +1173,7 @@ class Group_LDAPTest extends TestCase {
}
- public function testAddToGroupFailing() {
+ public function testAddToGroupFailing(): void {
$this->expectException(\Exception::class);
$this->pluginManager = $this->getMockBuilder(GroupPluginManager::class)
@@ -1189,7 +1189,7 @@ class Group_LDAPTest extends TestCase {
$this->groupBackend->addToGroup('uid', 'gid');
}
- public function testRemoveFromGroupWithPlugin() {
+ public function testRemoveFromGroupWithPlugin(): void {
$this->pluginManager = $this->getMockBuilder(GroupPluginManager::class)
->setMethods(['implementsActions', 'removeFromGroup'])
->getMock();
@@ -1209,7 +1209,7 @@ class Group_LDAPTest extends TestCase {
}
- public function testRemoveFromGroupFailing() {
+ public function testRemoveFromGroupFailing(): void {
$this->expectException(\Exception::class);
$this->pluginManager = $this->getMockBuilder(GroupPluginManager::class)
@@ -1225,7 +1225,7 @@ class Group_LDAPTest extends TestCase {
$this->groupBackend->removeFromGroup('uid', 'gid');
}
- public function testGetGroupDetailsWithPlugin() {
+ public function testGetGroupDetailsWithPlugin(): void {
/** @var GroupPluginManager|MockObject $pluginManager */
$this->pluginManager = $this->getMockBuilder(GroupPluginManager::class)
->setMethods(['implementsActions', 'getGroupDetails'])
@@ -1245,7 +1245,7 @@ class Group_LDAPTest extends TestCase {
$this->assertEquals($this->groupBackend->getGroupDetails('gid'), 'result');
}
- public function testGetGroupDetailsFailing() {
+ public function testGetGroupDetailsFailing(): void {
$this->expectException(\Exception::class);
$this->pluginManager = $this->getMockBuilder(GroupPluginManager::class)
@@ -1333,7 +1333,7 @@ class Group_LDAPTest extends TestCase {
* @param string[] $expectedMembers
* @dataProvider groupMemberProvider
*/
- public function testGroupMembers(array $expectedResult, ?array $groupsInfo = null) {
+ public function testGroupMembers(array $expectedResult, ?array $groupsInfo = null): void {
$this->access->expects($this->any())
->method('readAttribute')
->willReturnCallback(function ($group) use ($groupsInfo) {
@@ -1372,7 +1372,7 @@ class Group_LDAPTest extends TestCase {
/**
* @dataProvider displayNameProvider
*/
- public function testGetDisplayName(string $expected, $ldapResult) {
+ public function testGetDisplayName(string $expected, $ldapResult): void {
$gid = 'graphic_novelists';
$this->access->expects($this->atLeastOnce())
diff --git a/apps/user_ldap/tests/HelperTest.php b/apps/user_ldap/tests/HelperTest.php
index bbb3956f918..38c6a639340 100644
--- a/apps/user_ldap/tests/HelperTest.php
+++ b/apps/user_ldap/tests/HelperTest.php
@@ -26,7 +26,7 @@ class HelperTest extends \Test\TestCase {
$this->helper = new Helper($this->config, \OC::$server->getDatabaseConnection());
}
- public function testGetServerConfigurationPrefixes() {
+ public function testGetServerConfigurationPrefixes(): void {
$this->config->method('getAppKeys')
->with($this->equalTo('user_ldap'))
->willReturn([
@@ -40,7 +40,7 @@ class HelperTest extends \Test\TestCase {
$this->assertEquals(['', 's1'], $result);
}
- public function testGetServerConfigurationPrefixesActive() {
+ public function testGetServerConfigurationPrefixesActive(): void {
$this->config->method('getAppKeys')
->with($this->equalTo('user_ldap'))
->willReturn([
@@ -65,7 +65,7 @@ class HelperTest extends \Test\TestCase {
$this->assertEquals(['s1'], $result);
}
- public function testGetServerConfigurationHost() {
+ public function testGetServerConfigurationHost(): void {
$this->config->method('getAppKeys')
->with($this->equalTo('user_ldap'))
->willReturn([
diff --git a/apps/user_ldap/tests/Jobs/CleanUpTest.php b/apps/user_ldap/tests/Jobs/CleanUpTest.php
index 05d202f82df..582b6fba5d7 100644
--- a/apps/user_ldap/tests/Jobs/CleanUpTest.php
+++ b/apps/user_ldap/tests/Jobs/CleanUpTest.php
@@ -43,7 +43,7 @@ class CleanUpTest extends TestCase {
/**
* clean up job must not run when there are disabled configurations
*/
- public function test_runNotAllowedByDisabledConfigurations() {
+ public function test_runNotAllowedByDisabledConfigurations(): void {
$this->mocks['helper']->expects($this->once())
->method('haveDisabledConfigurations')
->willReturn(true);
@@ -59,7 +59,7 @@ class CleanUpTest extends TestCase {
* clean up job must not run when LDAP Helper is broken i.e.
* returning unexpected results
*/
- public function test_runNotAllowedByBrokenHelper() {
+ public function test_runNotAllowedByBrokenHelper(): void {
$this->mocks['helper']->expects($this->once())
->method('haveDisabledConfigurations')
->will($this->throwException(new Exception()));
@@ -74,7 +74,7 @@ class CleanUpTest extends TestCase {
/**
* clean up job must not run when it is not enabled
*/
- public function test_runNotAllowedBySysConfig() {
+ public function test_runNotAllowedBySysConfig(): void {
$this->mocks['helper']->expects($this->once())
->method('haveDisabledConfigurations')
->willReturn(false);
@@ -90,7 +90,7 @@ class CleanUpTest extends TestCase {
/**
* clean up job is allowed to run
*/
- public function test_runIsAllowed() {
+ public function test_runIsAllowed(): void {
$this->mocks['helper']->expects($this->once())
->method('haveDisabledConfigurations')
->willReturn(false);
@@ -106,7 +106,7 @@ class CleanUpTest extends TestCase {
/**
* check whether offset will be reset when it needs to
*/
- public function test_OffsetResetIsNecessary() {
+ public function test_OffsetResetIsNecessary(): void {
$result = $this->bgJob->isOffsetResetNecessary($this->bgJob->getChunkSize() - 1);
$this->assertSame(true, $result);
}
@@ -114,7 +114,7 @@ class CleanUpTest extends TestCase {
/**
* make sure offset is not reset when it is not due
*/
- public function test_OffsetResetIsNotNecessary() {
+ public function test_OffsetResetIsNotNecessary(): void {
$result = $this->bgJob->isOffsetResetNecessary($this->bgJob->getChunkSize());
$this->assertSame(false, $result);
}
diff --git a/apps/user_ldap/tests/Jobs/SyncTest.php b/apps/user_ldap/tests/Jobs/SyncTest.php
index 379402166e3..8277e7d48a9 100644
--- a/apps/user_ldap/tests/Jobs/SyncTest.php
+++ b/apps/user_ldap/tests/Jobs/SyncTest.php
@@ -152,7 +152,7 @@ class SyncTest extends TestCase {
/**
* @dataProvider moreResultsProvider
*/
- public function testMoreResults($pagingSize, $results, $expected) {
+ public function testMoreResults($pagingSize, $results, $expected): void {
$connection = $this->createMock(Connection::class);
$this->connectionFactory->expects($this->any())
->method('get')
@@ -207,7 +207,7 @@ class SyncTest extends TestCase {
/**
* @dataProvider cycleDataProvider
*/
- public function testDetermineNextCycle($cycleData, $prefixes, $expectedCycle) {
+ public function testDetermineNextCycle($cycleData, $prefixes, $expectedCycle): void {
$this->helper->expects($this->any())
->method('getServerConfigurationPrefixes')
->with(true)
@@ -283,7 +283,7 @@ class SyncTest extends TestCase {
/**
* @dataProvider runDataProvider
*/
- public function testRun($runData) {
+ public function testRun($runData): void {
$this->config->expects($this->any())
->method('getAppValue')
->willReturnCallback(function ($app, $key, $default) use ($runData) {
diff --git a/apps/user_ldap/tests/LDAPProviderTest.php b/apps/user_ldap/tests/LDAPProviderTest.php
index 1688c2a960f..11097c6acbd 100644
--- a/apps/user_ldap/tests/LDAPProviderTest.php
+++ b/apps/user_ldap/tests/LDAPProviderTest.php
@@ -1,865 +1,865 @@
-<?php
-/**
- * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
- * SPDX-License-Identifier: AGPL-3.0-or-later
- */
-namespace OCA\User_LDAP\Tests;
-
-use OC\User\Manager;
-use OCA\User_LDAP\Access;
-use OCA\User_LDAP\Connection;
-use OCA\User_LDAP\Group_LDAP;
-use OCA\User_LDAP\IGroupLDAP;
-use OCA\User_LDAP\IUserLDAP;
-use OCA\User_LDAP\User_LDAP;
-use OCP\EventDispatcher\IEventDispatcher;
-use OCP\ICacheFactory;
-use OCP\IConfig;
-use OCP\IServerContainer;
-
-/**
- * Class LDAPProviderTest
- *
- * @group DB
- *
- * @package OCA\User_LDAP\Tests
- */
-class LDAPProviderTest extends \Test\TestCase {
- protected function setUp(): void {
- parent::setUp();
- }
-
- private function getServerMock(IUserLDAP $userBackend, IGroupLDAP $groupBackend) {
- $server = $this->getMockBuilder(\OC\Server::class)
- ->setMethods(['getUserManager', 'getBackends', 'getGroupManager'])
- ->setConstructorArgs(['', new \OC\Config(\OC::$configDir)])
- ->getMock();
- $server->expects($this->any())
- ->method('getUserManager')
- ->willReturn($this->getUserManagerMock($userBackend));
- $server->expects($this->any())
- ->method('getGroupManager')
- ->willReturn($this->getGroupManagerMock($groupBackend));
- $server->expects($this->any())
- ->method($this->anything())
- ->willReturnSelf();
-
- return $server;
- }
-
- private function getUserManagerMock(IUserLDAP $userBackend) {
- $userManager = $this->getMockBuilder(Manager::class)
- ->setMethods(['getBackends'])
- ->setConstructorArgs([
- $this->createMock(IConfig::class),
- $this->createMock(ICacheFactory::class),
- $this->createMock(IEventDispatcher::class),
- ])
- ->getMock();
- $userManager->expects($this->any())
- ->method('getBackends')
- ->willReturn([$userBackend]);
- return $userManager;
- }
-
- private function getGroupManagerMock(IGroupLDAP $groupBackend) {
- $groupManager = $this->getMockBuilder(\OC\Group\Manager::class)
- ->setMethods(['getBackends'])
- ->disableOriginalConstructor()
- ->getMock();
- $groupManager->expects($this->any())
- ->method('getBackends')
- ->willReturn([$groupBackend]);
- return $groupManager;
- }
-
- private function getDefaultGroupBackendMock() {
- $groupBackend = $this->getMockBuilder(\OCA\User_LDAP\Group_LDAP::class)
- ->disableOriginalConstructor()
- ->getMock();
-
- return $groupBackend;
- }
-
- private function getLDAPProvider(IServerContainer $serverContainer) {
- $factory = new \OCA\User_LDAP\LDAPProviderFactory($serverContainer);
- return $factory->getLDAPProvider();
- }
-
-
- public function testGetUserDNUserIDNotFound() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('User id not found in LDAP');
-
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->setMethods(['userExists'])
- ->disableOriginalConstructor()
- ->getMock();
- $userBackend->expects($this->any())->method('userExists')->willReturn(false);
-
- $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
-
- $ldapProvider = $this->getLDAPProvider($server);
- $ldapProvider->getUserDN('nonexisting_user');
- }
-
- public function testGetUserDN() {
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->setMethods(['userExists', 'getLDAPAccess', 'username2dn'])
- ->disableOriginalConstructor()
- ->getMock();
- $userBackend->expects($this->once())
- ->method('userExists')
- ->willReturn(true);
- $userBackend->expects($this->once())
- ->method('username2dn')
- ->willReturn('cn=existing_user,ou=Are Sufficient To,ou=Test,dc=example,dc=org');
- $userBackend->expects($this->any())
- ->method($this->anything())
- ->willReturnSelf();
-
- $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
-
- $ldapProvider = $this->getLDAPProvider($server);
- $this->assertEquals('cn=existing_user,ou=Are Sufficient To,ou=Test,dc=example,dc=org',
- $ldapProvider->getUserDN('existing_user'));
- }
-
-
- public function testGetGroupDNGroupIDNotFound() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('Group id not found in LDAP');
-
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->disableOriginalConstructor()
- ->getMock();
-
- $groupBackend = $this->getMockBuilder(\OCA\User_LDAP\Group_LDAP::class)
- ->setMethods(['groupExists'])
- ->disableOriginalConstructor()
- ->getMock();
-
- $groupBackend->expects($this->any())->method('groupExists')->willReturn(false);
-
- $server = $this->getServerMock($userBackend, $groupBackend);
-
- $ldapProvider = $this->getLDAPProvider($server);
- $ldapProvider->getGroupDN('nonexisting_group');
- }
-
- public function testGetGroupDN() {
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->setMethods(['userExists', 'getLDAPAccess', 'username2dn'])
- ->disableOriginalConstructor()
- ->getMock();
-
- $groupBackend = $this->getMockBuilder(\OCA\User_LDAP\Group_LDAP::class)
- ->setMethods(['groupExists', 'getLDAPAccess', 'groupname2dn'])
- ->disableOriginalConstructor()
- ->getMock();
-
- $groupBackend->expects($this->once())
- ->method('groupExists')
- ->willReturn(true);
- $groupBackend->expects($this->once())
- ->method('groupname2dn')
- ->willReturn('cn=existing_group,ou=Are Sufficient To,ou=Test,dc=example,dc=org');
- $groupBackend->expects($this->any())
- ->method($this->anything())
- ->willReturnSelf();
-
- $server = $this->getServerMock($userBackend, $groupBackend);
-
- $ldapProvider = $this->getLDAPProvider($server);
- $this->assertEquals('cn=existing_group,ou=Are Sufficient To,ou=Test,dc=example,dc=org',
- $ldapProvider->getGroupDN('existing_group'));
- }
-
- public function testGetUserName() {
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->setMethods(['dn2UserName'])
- ->disableOriginalConstructor()
- ->getMock();
- $userBackend->expects($this->any())
- ->method('dn2UserName')
- ->willReturn('existing_user');
-
- $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
-
- $ldapProvider = $this->getLDAPProvider($server);
- $this->assertEquals('existing_user',
- $ldapProvider->getUserName('cn=existing_user,ou=Are Sufficient To,ou=Test,dc=example,dc=org'));
- }
-
- public function testDNasBaseParameter() {
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->setMethods([])
- ->disableOriginalConstructor()
- ->getMock();
-
- $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
-
- $helper = new \OCA\User_LDAP\Helper(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection());
-
- $ldapProvider = $this->getLDAPProvider($server);
- $this->assertEquals(
- $helper->DNasBaseParameter('cn=existing_user,ou=Are Sufficient To,ou=Test,dc=example,dc=org'),
- $ldapProvider->DNasBaseParameter('cn=existing_user,ou=Are Sufficient To,ou=Test,dc=example,dc=org'));
- }
-
- public function testSanitizeDN() {
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->setMethods([])
- ->disableOriginalConstructor()
- ->getMock();
-
- $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
-
- $helper = new \OCA\User_LDAP\Helper(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection());
-
- $ldapProvider = $this->getLDAPProvider($server);
- $this->assertEquals(
- $helper->sanitizeDN('cn=existing_user,ou=Are Sufficient To,ou=Test,dc=example,dc=org'),
- $ldapProvider->sanitizeDN('cn=existing_user,ou=Are Sufficient To,ou=Test,dc=example,dc=org'));
- }
-
-
- public function testGetLDAPConnectionUserIDNotFound() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('User id not found in LDAP');
-
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->setMethods(['userExists'])
- ->disableOriginalConstructor()
- ->getMock();
- $userBackend->expects($this->any())->method('userExists')->willReturn(false);
-
- $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
-
- $ldapProvider = $this->getLDAPProvider($server);
- $ldapProvider->getLDAPConnection('nonexisting_user');
- }
-
- public function testGetLDAPConnection() {
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->setMethods(['userExists', 'getNewLDAPConnection'])
- ->disableOriginalConstructor()
- ->getMock();
- $userBackend->expects($this->any())
- ->method('userExists')
- ->willReturn(true);
- $ldapConnection = ldap_connect('ldap://example.com');
- $userBackend->expects($this->any())
- ->method('getNewLDAPConnection')
- ->willReturn($ldapConnection);
-
- $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
-
- $ldapProvider = $this->getLDAPProvider($server);
- $this->assertEquals($ldapConnection, $ldapProvider->getLDAPConnection('existing_user'));
- }
-
-
- public function testGetGroupLDAPConnectionGroupIDNotFound() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('Group id not found in LDAP');
-
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->disableOriginalConstructor()
- ->getMock();
-
- $groupBackend = $this->getMockBuilder(\OCA\User_LDAP\Group_LDAP::class)
- ->setMethods(['groupExists'])
- ->disableOriginalConstructor()
- ->getMock();
-
- $groupBackend->expects($this->any())->method('groupExists')->willReturn(false);
-
- $server = $this->getServerMock($userBackend, $groupBackend);
-
- $ldapProvider = $this->getLDAPProvider($server);
- $ldapProvider->getGroupLDAPConnection('nonexisting_group');
- }
-
- public function testGetGroupLDAPConnection() {
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->disableOriginalConstructor()
- ->getMock();
-
- $groupBackend = $this->getMockBuilder(\OCA\User_LDAP\Group_LDAP::class)
- ->setMethods(['groupExists','getNewLDAPConnection'])
- ->disableOriginalConstructor()
- ->getMock();
-
- $groupBackend->expects($this->any())
- ->method('groupExists')
- ->willReturn(true);
-
- $ldapConnection = ldap_connect('ldap://example.com');
- $groupBackend->expects($this->any())
- ->method('getNewLDAPConnection')
- ->willReturn($ldapConnection);
-
- $server = $this->getServerMock($userBackend, $groupBackend);
-
- $ldapProvider = $this->getLDAPProvider($server);
- $this->assertEquals($ldapConnection, $ldapProvider->getGroupLDAPConnection('existing_group'));
- }
-
-
- public function testGetLDAPBaseUsersUserIDNotFound() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('User id not found in LDAP');
-
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->setMethods(['userExists'])
- ->disableOriginalConstructor()
- ->getMock();
- $userBackend->expects($this->any())->method('userExists')->willReturn(false);
-
- $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
-
- $ldapProvider = $this->getLDAPProvider($server);
- $ldapProvider->getLDAPBaseUsers('nonexisting_user');
- }
-
- public function testGetLDAPBaseUsers() {
- $bases = [
- 'ou=users,ou=foobar,dc=example,dc=org',
- 'ou=users,ou=barfoo,dc=example,dc=org',
- ];
- $dn = 'uid=malik,' . $bases[1];
-
- $connection = $this->createMock(Connection::class);
- $connection->expects($this->any())
- ->method('__get')
- ->willReturnCallback(function ($key) use ($bases) {
- switch ($key) {
- case 'ldapBaseUsers':
- return $bases;
- }
- return null;
- });
-
- $access = $this->createMock(Access::class);
- $access->expects($this->any())
- ->method('getConnection')
- ->willReturn($connection);
- $access->expects($this->exactly(2))
- ->method('isDNPartOfBase')
- ->willReturnOnConsecutiveCalls(false, true);
- $access->expects($this->atLeastOnce())
- ->method('username2dn')
- ->willReturn($dn);
-
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->setMethods(['userExists', 'getLDAPAccess', 'getConnection', 'getConfiguration'])
- ->disableOriginalConstructor()
- ->getMock();
- $userBackend->expects($this->atLeastOnce())
- ->method('userExists')
- ->willReturn(true);
- $userBackend->expects($this->any())
- ->method('getLDAPAccess')
- ->willReturn($access);
-
- $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
-
- $ldapProvider = $this->getLDAPProvider($server);
- $this->assertEquals($bases[1], $ldapProvider->getLDAPBaseUsers('existing_user'));
- }
-
-
- public function testGetLDAPBaseGroupsUserIDNotFound() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('User id not found in LDAP');
-
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->setMethods(['userExists'])
- ->disableOriginalConstructor()
- ->getMock();
- $userBackend->expects($this->any())->method('userExists')->willReturn(false);
-
- $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
-
- $ldapProvider = $this->getLDAPProvider($server);
- $ldapProvider->getLDAPBaseGroups('nonexisting_user');
- }
-
- public function testGetLDAPBaseGroups() {
- $bases = [
- 'ou=groupd,ou=foobar,dc=example,dc=org',
- 'ou=groups,ou=barfoo,dc=example,dc=org',
- ];
-
- $connection = $this->createMock(Connection::class);
- $connection->expects($this->any())
- ->method('__get')
- ->willReturnCallback(function ($key) use ($bases) {
- switch ($key) {
- case 'ldapBaseGroups':
- return $bases;
- }
- return null;
- });
-
- $access = $this->createMock(Access::class);
- $access->expects($this->any())
- ->method('getConnection')
- ->willReturn($connection);
-
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->setMethods(['userExists', 'getLDAPAccess', 'getConnection', 'getConfiguration'])
- ->disableOriginalConstructor()
- ->getMock();
- $userBackend->expects($this->any())
- ->method('userExists')
- ->willReturn(true);
- $userBackend->expects($this->any())
- ->method('getLDAPAccess')
- ->willReturn($access);
-
- $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
-
- $ldapProvider = $this->getLDAPProvider($server);
- $this->assertEquals($bases[0], $ldapProvider->getLDAPBaseGroups('existing_user'));
- }
-
-
- public function testClearCacheUserIDNotFound() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('User id not found in LDAP');
-
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->setMethods(['userExists'])
- ->disableOriginalConstructor()
- ->getMock();
- $userBackend->expects($this->any())->method('userExists')->willReturn(false);
-
- $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
-
- $ldapProvider = $this->getLDAPProvider($server);
- $ldapProvider->clearCache('nonexisting_user');
- }
-
- public function testClearCache() {
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->setMethods(['userExists', 'getLDAPAccess', 'getConnection', 'clearCache'])
- ->disableOriginalConstructor()
- ->getMock();
- $userBackend->expects($this->once())
- ->method('userExists')
- ->willReturn(true);
- $userBackend->expects($this->once())
- ->method('clearCache')
- ->willReturn(true);
- $userBackend->expects($this->any())
- ->method($this->anything())
- ->willReturnSelf();
-
- $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
-
- $ldapProvider = $this->getLDAPProvider($server);
- $ldapProvider->clearCache('existing_user');
- $this->addToAssertionCount(1);
- }
-
-
- public function testClearGroupCacheGroupIDNotFound() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('Group id not found in LDAP');
-
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->disableOriginalConstructor()
- ->getMock();
- $groupBackend = $this->getMockBuilder(\OCA\User_LDAP\Group_LDAP::class)
- ->setMethods(['groupExists'])
- ->disableOriginalConstructor()
- ->getMock();
- $groupBackend->expects($this->any())->method('groupExists')->willReturn(false);
-
- $server = $this->getServerMock($userBackend, $groupBackend);
-
- $ldapProvider = $this->getLDAPProvider($server);
- $ldapProvider->clearGroupCache('nonexisting_group');
- }
-
- public function testClearGroupCache() {
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->disableOriginalConstructor()
- ->getMock();
- $groupBackend = $this->getMockBuilder(\OCA\User_LDAP\Group_LDAP::class)
- ->setMethods(['groupExists', 'getLDAPAccess', 'getConnection', 'clearCache'])
- ->disableOriginalConstructor()
- ->getMock();
- $groupBackend->expects($this->once())
- ->method('groupExists')
- ->willReturn(true);
- $groupBackend->expects($this->once())
- ->method('clearCache')
- ->willReturn(true);
- $groupBackend->expects($this->any())
- ->method($this->anything())
- ->willReturnSelf();
-
- $server = $this->getServerMock($userBackend, $groupBackend);
-
- $ldapProvider = $this->getLDAPProvider($server);
- $ldapProvider->clearGroupCache('existing_group');
- $this->addToAssertionCount(1);
- }
-
- public function testDnExists() {
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->setMethods(['dn2UserName'])
- ->disableOriginalConstructor()
- ->getMock();
- $userBackend->expects($this->any())
- ->method('dn2UserName')
- ->willReturn('existing_user');
-
- $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
-
- $ldapProvider = $this->getLDAPProvider($server);
- $this->assertTrue($ldapProvider->dnExists('cn=existing_user,ou=Are Sufficient To,ou=Test,dc=example,dc=org'));
- }
-
- public function testFlagRecord() {
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->setMethods([])
- ->disableOriginalConstructor()
- ->getMock();
-
- $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
-
- $ldapProvider = $this->getLDAPProvider($server);
- $ldapProvider->flagRecord('existing_user');
- $this->addToAssertionCount(1);
- }
-
- public function testUnflagRecord() {
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->setMethods([])
- ->disableOriginalConstructor()
- ->getMock();
-
- $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
-
- $ldapProvider = $this->getLDAPProvider($server);
- $ldapProvider->unflagRecord('existing_user');
- $this->addToAssertionCount(1);
- }
-
-
- public function testGetLDAPDisplayNameFieldUserIDNotFound() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('User id not found in LDAP');
-
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->setMethods(['userExists'])
- ->disableOriginalConstructor()
- ->getMock();
- $userBackend->expects($this->any())->method('userExists')->willReturn(false);
-
- $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
-
- $ldapProvider = $this->getLDAPProvider($server);
- $ldapProvider->getLDAPDisplayNameField('nonexisting_user');
- }
-
- public function testGetLDAPDisplayNameField() {
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->setMethods(['userExists', 'getLDAPAccess', 'getConnection', 'getConfiguration'])
- ->disableOriginalConstructor()
- ->getMock();
- $userBackend->expects($this->once())
- ->method('userExists')
- ->willReturn(true);
- $userBackend->expects($this->once())
- ->method('getConfiguration')
- ->willReturn(['ldap_display_name' => 'displayName']);
- $userBackend->expects($this->any())
- ->method($this->anything())
- ->willReturnSelf();
-
- $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
-
- $ldapProvider = $this->getLDAPProvider($server);
- $this->assertEquals('displayName', $ldapProvider->getLDAPDisplayNameField('existing_user'));
- }
-
-
- public function testGetLDAPEmailFieldUserIDNotFound() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('User id not found in LDAP');
-
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->setMethods(['userExists'])
- ->disableOriginalConstructor()
- ->getMock();
- $userBackend->expects($this->any())->method('userExists')->willReturn(false);
-
- $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
-
- $ldapProvider = $this->getLDAPProvider($server);
- $ldapProvider->getLDAPEmailField('nonexisting_user');
- }
-
- public function testGetLDAPEmailField() {
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->setMethods(['userExists', 'getLDAPAccess', 'getConnection', 'getConfiguration'])
- ->disableOriginalConstructor()
- ->getMock();
- $userBackend->expects($this->once())
- ->method('userExists')
- ->willReturn(true);
- $userBackend->expects($this->once())
- ->method('getConfiguration')
- ->willReturn(['ldap_email_attr' => 'mail']);
- $userBackend->expects($this->any())
- ->method($this->anything())
- ->willReturnSelf();
-
- $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
-
- $ldapProvider = $this->getLDAPProvider($server);
- $this->assertEquals('mail', $ldapProvider->getLDAPEmailField('existing_user'));
- }
-
-
- public function testGetLDAPGroupMemberAssocUserIDNotFound() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('Group id not found in LDAP');
-
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->disableOriginalConstructor()
- ->getMock();
-
- $groupBackend = $this->getMockBuilder(\OCA\User_LDAP\Group_LDAP::class)
- ->setMethods(['groupExists'])
- ->disableOriginalConstructor()
- ->getMock();
-
- $groupBackend->expects($this->any())->method('groupExists')->willReturn(false);
-
- $server = $this->getServerMock($userBackend, $groupBackend);
-
- $ldapProvider = $this->getLDAPProvider($server);
- $ldapProvider->getLDAPGroupMemberAssoc('nonexisting_group');
- }
-
- public function testgetLDAPGroupMemberAssoc() {
- $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
- ->disableOriginalConstructor()
- ->getMock();
-
- $groupBackend = $this->getMockBuilder(\OCA\User_LDAP\Group_LDAP::class)
- ->setMethods(['groupExists', 'getLDAPAccess', 'getConnection', 'getConfiguration'])
- ->disableOriginalConstructor()
- ->getMock();
-
- $groupBackend->expects($this->once())
- ->method('groupExists')
- ->willReturn(true);
- $groupBackend->expects($this->any())
- ->method('getConfiguration')
- ->willReturn(['ldap_group_member_assoc_attribute' => 'assoc_type']);
- $groupBackend->expects($this->any())
- ->method($this->anything())
- ->willReturnSelf();
-
- $server = $this->getServerMock($userBackend, $groupBackend);
-
- $ldapProvider = $this->getLDAPProvider($server);
- $this->assertEquals('assoc_type', $ldapProvider->getLDAPGroupMemberAssoc('existing_group'));
- }
-
- public function testGetMultiValueUserAttributeUserNotFound() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('User id not found in LDAP');
-
- $userBackend = $this->createMock(User_LDAP::class);
- $userBackend->expects(self::once())
- ->method('userExists')
- ->with('admin')
- ->willReturn(false);
- $groupBackend = $this->createMock(Group_LDAP::class);
- $server = $this->getServerMock($userBackend, $groupBackend);
-
- $ldapProvider = $this->getLDAPProvider($server);
- $ldapProvider->getMultiValueUserAttribute('admin', 'mailAlias');
- }
-
- public function testGetMultiValueUserAttributeCacheHit() {
- $connection = $this->createMock(Connection::class);
- $connection->expects(self::once())
- ->method('getFromCache')
- ->with('admin-mailAlias')
- ->willReturn(['aliasA@test.local', 'aliasB@test.local']);
- $access = $this->createMock(Access::class);
- $access->expects(self::once())
- ->method('getConnection')
- ->willReturn($connection);
- $userBackend = $this->createMock(User_LDAP::class);
- $userBackend->expects(self::once())
- ->method('userExists')
- ->with('admin')
- ->willReturn(true);
- $userBackend->expects(self::once())
- ->method('getLDAPAccess')
- ->willReturn($access);
- $groupBackend = $this->createMock(Group_LDAP::class);
- $server = $this->getServerMock($userBackend, $groupBackend);
-
- $ldapProvider = $this->getLDAPProvider($server);
- $ldapProvider->getMultiValueUserAttribute('admin', 'mailAlias');
- }
-
- public function testGetMultiValueUserAttributeLdapError() {
- $connection = $this->createMock(Connection::class);
- $connection->expects(self::once())
- ->method('getFromCache')
- ->with('admin-mailAlias')
- ->willReturn(null);
- $access = $this->createMock(Access::class);
- $access->expects(self::once())
- ->method('getConnection')
- ->willReturn($connection);
- $access->expects(self::once())
- ->method('username2dn')
- ->with('admin')
- ->willReturn('admin');
- $access->expects(self::once())
- ->method('readAttribute')
- ->with('admin', 'mailAlias')
- ->willReturn(false);
- $userBackend = $this->getMockBuilder(User_LDAP::class)
- ->disableOriginalConstructor()
- ->getMock();
- $userBackend->method('userExists')
- ->with('admin')
- ->willReturn(true);
- $userBackend->method('getLDAPAccess')
- ->willReturn($access);
- $groupBackend = $this->getMockBuilder(Group_LDAP::class)
- ->disableOriginalConstructor()
- ->getMock();
- $server = $this->getServerMock($userBackend, $groupBackend);
-
- $ldapProvider = $this->getLDAPProvider($server);
- $values = $ldapProvider->getMultiValueUserAttribute('admin', 'mailAlias');
-
- self::assertCount(0, $values);
- }
-
- public function testGetMultiValueUserAttribute() {
- $connection = $this->createMock(Connection::class);
- $connection->expects(self::once())
- ->method('getFromCache')
- ->with('admin-mailAlias')
- ->willReturn(null);
- $access = $this->createMock(Access::class);
- $access->expects(self::once())
- ->method('getConnection')
- ->willReturn($connection);
- $access->expects(self::once())
- ->method('username2dn')
- ->with('admin')
- ->willReturn('admin');
- $access->expects(self::once())
- ->method('readAttribute')
- ->with('admin', 'mailAlias')
- ->willReturn(['aliasA@test.local', 'aliasB@test.local']);
- $userBackend = $this->getMockBuilder(User_LDAP::class)
- ->disableOriginalConstructor()
- ->getMock();
- $userBackend->method('userExists')
- ->with('admin')
- ->willReturn(true);
- $userBackend->method('getLDAPAccess')
- ->willReturn($access);
- $groupBackend = $this->getMockBuilder(Group_LDAP::class)
- ->disableOriginalConstructor()
- ->getMock();
- $server = $this->getServerMock($userBackend, $groupBackend);
-
- $ldapProvider = $this->getLDAPProvider($server);
- $values = $ldapProvider->getMultiValueUserAttribute('admin', 'mailAlias');
-
- self::assertCount(2, $values);
- }
-
- public function testGetUserAttributeLdapError() {
- $connection = $this->createMock(Connection::class);
- $connection->expects(self::once())
- ->method('getFromCache')
- ->with('admin-mailAlias')
- ->willReturn(null);
- $access = $this->createMock(Access::class);
- $access->expects(self::once())
- ->method('getConnection')
- ->willReturn($connection);
- $access->expects(self::once())
- ->method('username2dn')
- ->with('admin')
- ->willReturn('admin');
- $access->expects(self::once())
- ->method('readAttribute')
- ->with('admin', 'mailAlias')
- ->willReturn(false);
- $userBackend = $this->getMockBuilder(User_LDAP::class)
- ->disableOriginalConstructor()
- ->getMock();
- $userBackend->method('userExists')
- ->with('admin')
- ->willReturn(true);
- $userBackend->method('getLDAPAccess')
- ->willReturn($access);
- $groupBackend = $this->getMockBuilder(Group_LDAP::class)
- ->disableOriginalConstructor()
- ->getMock();
- $server = $this->getServerMock($userBackend, $groupBackend);
-
- $ldapProvider = $this->getLDAPProvider($server);
- $value = $ldapProvider->getUserAttribute('admin', 'mailAlias');
-
- self::assertNull($value);
- }
-
- public function testGetUserAttribute() {
- $connection = $this->createMock(Connection::class);
- $connection->expects(self::once())
- ->method('getFromCache')
- ->with('admin-mailAlias')
- ->willReturn(null);
- $access = $this->createMock(Access::class);
- $access->expects(self::once())
- ->method('getConnection')
- ->willReturn($connection);
- $access->expects(self::once())
- ->method('username2dn')
- ->with('admin')
- ->willReturn('admin');
- $access->expects(self::once())
- ->method('readAttribute')
- ->with('admin', 'mailAlias')
- ->willReturn(['aliasA@test.local', 'aliasB@test.local']);
- $userBackend = $this->getMockBuilder(User_LDAP::class)
- ->disableOriginalConstructor()
- ->getMock();
- $userBackend->method('userExists')
- ->with('admin')
- ->willReturn(true);
- $userBackend->method('getLDAPAccess')
- ->willReturn($access);
- $groupBackend = $this->getMockBuilder(Group_LDAP::class)
- ->disableOriginalConstructor()
- ->getMock();
- $server = $this->getServerMock($userBackend, $groupBackend);
-
- $ldapProvider = $this->getLDAPProvider($server);
- $value = $ldapProvider->getUserAttribute('admin', 'mailAlias');
-
- self::assertEquals('aliasA@test.local', $value);
- }
-}
+<?php
+/**
+ * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+namespace OCA\User_LDAP\Tests;
+
+use OC\User\Manager;
+use OCA\User_LDAP\Access;
+use OCA\User_LDAP\Connection;
+use OCA\User_LDAP\Group_LDAP;
+use OCA\User_LDAP\IGroupLDAP;
+use OCA\User_LDAP\IUserLDAP;
+use OCA\User_LDAP\User_LDAP;
+use OCP\EventDispatcher\IEventDispatcher;
+use OCP\ICacheFactory;
+use OCP\IConfig;
+use OCP\IServerContainer;
+
+/**
+ * Class LDAPProviderTest
+ *
+ * @group DB
+ *
+ * @package OCA\User_LDAP\Tests
+ */
+class LDAPProviderTest extends \Test\TestCase {
+ protected function setUp(): void {
+ parent::setUp();
+ }
+
+ private function getServerMock(IUserLDAP $userBackend, IGroupLDAP $groupBackend) {
+ $server = $this->getMockBuilder(\OC\Server::class)
+ ->setMethods(['getUserManager', 'getBackends', 'getGroupManager'])
+ ->setConstructorArgs(['', new \OC\Config(\OC::$configDir)])
+ ->getMock();
+ $server->expects($this->any())
+ ->method('getUserManager')
+ ->willReturn($this->getUserManagerMock($userBackend));
+ $server->expects($this->any())
+ ->method('getGroupManager')
+ ->willReturn($this->getGroupManagerMock($groupBackend));
+ $server->expects($this->any())
+ ->method($this->anything())
+ ->willReturnSelf();
+
+ return $server;
+ }
+
+ private function getUserManagerMock(IUserLDAP $userBackend) {
+ $userManager = $this->getMockBuilder(Manager::class)
+ ->setMethods(['getBackends'])
+ ->setConstructorArgs([
+ $this->createMock(IConfig::class),
+ $this->createMock(ICacheFactory::class),
+ $this->createMock(IEventDispatcher::class),
+ ])
+ ->getMock();
+ $userManager->expects($this->any())
+ ->method('getBackends')
+ ->willReturn([$userBackend]);
+ return $userManager;
+ }
+
+ private function getGroupManagerMock(IGroupLDAP $groupBackend) {
+ $groupManager = $this->getMockBuilder(\OC\Group\Manager::class)
+ ->setMethods(['getBackends'])
+ ->disableOriginalConstructor()
+ ->getMock();
+ $groupManager->expects($this->any())
+ ->method('getBackends')
+ ->willReturn([$groupBackend]);
+ return $groupManager;
+ }
+
+ private function getDefaultGroupBackendMock() {
+ $groupBackend = $this->getMockBuilder(\OCA\User_LDAP\Group_LDAP::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ return $groupBackend;
+ }
+
+ private function getLDAPProvider(IServerContainer $serverContainer) {
+ $factory = new \OCA\User_LDAP\LDAPProviderFactory($serverContainer);
+ return $factory->getLDAPProvider();
+ }
+
+
+ public function testGetUserDNUserIDNotFound(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('User id not found in LDAP');
+
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->setMethods(['userExists'])
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userBackend->expects($this->any())->method('userExists')->willReturn(false);
+
+ $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $ldapProvider->getUserDN('nonexisting_user');
+ }
+
+ public function testGetUserDN(): void {
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->setMethods(['userExists', 'getLDAPAccess', 'username2dn'])
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userBackend->expects($this->once())
+ ->method('userExists')
+ ->willReturn(true);
+ $userBackend->expects($this->once())
+ ->method('username2dn')
+ ->willReturn('cn=existing_user,ou=Are Sufficient To,ou=Test,dc=example,dc=org');
+ $userBackend->expects($this->any())
+ ->method($this->anything())
+ ->willReturnSelf();
+
+ $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $this->assertEquals('cn=existing_user,ou=Are Sufficient To,ou=Test,dc=example,dc=org',
+ $ldapProvider->getUserDN('existing_user'));
+ }
+
+
+ public function testGetGroupDNGroupIDNotFound(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('Group id not found in LDAP');
+
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $groupBackend = $this->getMockBuilder(\OCA\User_LDAP\Group_LDAP::class)
+ ->setMethods(['groupExists'])
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $groupBackend->expects($this->any())->method('groupExists')->willReturn(false);
+
+ $server = $this->getServerMock($userBackend, $groupBackend);
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $ldapProvider->getGroupDN('nonexisting_group');
+ }
+
+ public function testGetGroupDN(): void {
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->setMethods(['userExists', 'getLDAPAccess', 'username2dn'])
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $groupBackend = $this->getMockBuilder(\OCA\User_LDAP\Group_LDAP::class)
+ ->setMethods(['groupExists', 'getLDAPAccess', 'groupname2dn'])
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $groupBackend->expects($this->once())
+ ->method('groupExists')
+ ->willReturn(true);
+ $groupBackend->expects($this->once())
+ ->method('groupname2dn')
+ ->willReturn('cn=existing_group,ou=Are Sufficient To,ou=Test,dc=example,dc=org');
+ $groupBackend->expects($this->any())
+ ->method($this->anything())
+ ->willReturnSelf();
+
+ $server = $this->getServerMock($userBackend, $groupBackend);
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $this->assertEquals('cn=existing_group,ou=Are Sufficient To,ou=Test,dc=example,dc=org',
+ $ldapProvider->getGroupDN('existing_group'));
+ }
+
+ public function testGetUserName(): void {
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->setMethods(['dn2UserName'])
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userBackend->expects($this->any())
+ ->method('dn2UserName')
+ ->willReturn('existing_user');
+
+ $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $this->assertEquals('existing_user',
+ $ldapProvider->getUserName('cn=existing_user,ou=Are Sufficient To,ou=Test,dc=example,dc=org'));
+ }
+
+ public function testDNasBaseParameter(): void {
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->setMethods([])
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
+
+ $helper = new \OCA\User_LDAP\Helper(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection());
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $this->assertEquals(
+ $helper->DNasBaseParameter('cn=existing_user,ou=Are Sufficient To,ou=Test,dc=example,dc=org'),
+ $ldapProvider->DNasBaseParameter('cn=existing_user,ou=Are Sufficient To,ou=Test,dc=example,dc=org'));
+ }
+
+ public function testSanitizeDN(): void {
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->setMethods([])
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
+
+ $helper = new \OCA\User_LDAP\Helper(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection());
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $this->assertEquals(
+ $helper->sanitizeDN('cn=existing_user,ou=Are Sufficient To,ou=Test,dc=example,dc=org'),
+ $ldapProvider->sanitizeDN('cn=existing_user,ou=Are Sufficient To,ou=Test,dc=example,dc=org'));
+ }
+
+
+ public function testGetLDAPConnectionUserIDNotFound(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('User id not found in LDAP');
+
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->setMethods(['userExists'])
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userBackend->expects($this->any())->method('userExists')->willReturn(false);
+
+ $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $ldapProvider->getLDAPConnection('nonexisting_user');
+ }
+
+ public function testGetLDAPConnection(): void {
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->setMethods(['userExists', 'getNewLDAPConnection'])
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userBackend->expects($this->any())
+ ->method('userExists')
+ ->willReturn(true);
+ $ldapConnection = ldap_connect('ldap://example.com');
+ $userBackend->expects($this->any())
+ ->method('getNewLDAPConnection')
+ ->willReturn($ldapConnection);
+
+ $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $this->assertEquals($ldapConnection, $ldapProvider->getLDAPConnection('existing_user'));
+ }
+
+
+ public function testGetGroupLDAPConnectionGroupIDNotFound(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('Group id not found in LDAP');
+
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $groupBackend = $this->getMockBuilder(\OCA\User_LDAP\Group_LDAP::class)
+ ->setMethods(['groupExists'])
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $groupBackend->expects($this->any())->method('groupExists')->willReturn(false);
+
+ $server = $this->getServerMock($userBackend, $groupBackend);
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $ldapProvider->getGroupLDAPConnection('nonexisting_group');
+ }
+
+ public function testGetGroupLDAPConnection(): void {
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $groupBackend = $this->getMockBuilder(\OCA\User_LDAP\Group_LDAP::class)
+ ->setMethods(['groupExists','getNewLDAPConnection'])
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $groupBackend->expects($this->any())
+ ->method('groupExists')
+ ->willReturn(true);
+
+ $ldapConnection = ldap_connect('ldap://example.com');
+ $groupBackend->expects($this->any())
+ ->method('getNewLDAPConnection')
+ ->willReturn($ldapConnection);
+
+ $server = $this->getServerMock($userBackend, $groupBackend);
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $this->assertEquals($ldapConnection, $ldapProvider->getGroupLDAPConnection('existing_group'));
+ }
+
+
+ public function testGetLDAPBaseUsersUserIDNotFound(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('User id not found in LDAP');
+
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->setMethods(['userExists'])
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userBackend->expects($this->any())->method('userExists')->willReturn(false);
+
+ $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $ldapProvider->getLDAPBaseUsers('nonexisting_user');
+ }
+
+ public function testGetLDAPBaseUsers(): void {
+ $bases = [
+ 'ou=users,ou=foobar,dc=example,dc=org',
+ 'ou=users,ou=barfoo,dc=example,dc=org',
+ ];
+ $dn = 'uid=malik,' . $bases[1];
+
+ $connection = $this->createMock(Connection::class);
+ $connection->expects($this->any())
+ ->method('__get')
+ ->willReturnCallback(function ($key) use ($bases) {
+ switch ($key) {
+ case 'ldapBaseUsers':
+ return $bases;
+ }
+ return null;
+ });
+
+ $access = $this->createMock(Access::class);
+ $access->expects($this->any())
+ ->method('getConnection')
+ ->willReturn($connection);
+ $access->expects($this->exactly(2))
+ ->method('isDNPartOfBase')
+ ->willReturnOnConsecutiveCalls(false, true);
+ $access->expects($this->atLeastOnce())
+ ->method('username2dn')
+ ->willReturn($dn);
+
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->setMethods(['userExists', 'getLDAPAccess', 'getConnection', 'getConfiguration'])
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userBackend->expects($this->atLeastOnce())
+ ->method('userExists')
+ ->willReturn(true);
+ $userBackend->expects($this->any())
+ ->method('getLDAPAccess')
+ ->willReturn($access);
+
+ $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $this->assertEquals($bases[1], $ldapProvider->getLDAPBaseUsers('existing_user'));
+ }
+
+
+ public function testGetLDAPBaseGroupsUserIDNotFound(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('User id not found in LDAP');
+
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->setMethods(['userExists'])
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userBackend->expects($this->any())->method('userExists')->willReturn(false);
+
+ $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $ldapProvider->getLDAPBaseGroups('nonexisting_user');
+ }
+
+ public function testGetLDAPBaseGroups(): void {
+ $bases = [
+ 'ou=groupd,ou=foobar,dc=example,dc=org',
+ 'ou=groups,ou=barfoo,dc=example,dc=org',
+ ];
+
+ $connection = $this->createMock(Connection::class);
+ $connection->expects($this->any())
+ ->method('__get')
+ ->willReturnCallback(function ($key) use ($bases) {
+ switch ($key) {
+ case 'ldapBaseGroups':
+ return $bases;
+ }
+ return null;
+ });
+
+ $access = $this->createMock(Access::class);
+ $access->expects($this->any())
+ ->method('getConnection')
+ ->willReturn($connection);
+
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->setMethods(['userExists', 'getLDAPAccess', 'getConnection', 'getConfiguration'])
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userBackend->expects($this->any())
+ ->method('userExists')
+ ->willReturn(true);
+ $userBackend->expects($this->any())
+ ->method('getLDAPAccess')
+ ->willReturn($access);
+
+ $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $this->assertEquals($bases[0], $ldapProvider->getLDAPBaseGroups('existing_user'));
+ }
+
+
+ public function testClearCacheUserIDNotFound(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('User id not found in LDAP');
+
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->setMethods(['userExists'])
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userBackend->expects($this->any())->method('userExists')->willReturn(false);
+
+ $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $ldapProvider->clearCache('nonexisting_user');
+ }
+
+ public function testClearCache(): void {
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->setMethods(['userExists', 'getLDAPAccess', 'getConnection', 'clearCache'])
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userBackend->expects($this->once())
+ ->method('userExists')
+ ->willReturn(true);
+ $userBackend->expects($this->once())
+ ->method('clearCache')
+ ->willReturn(true);
+ $userBackend->expects($this->any())
+ ->method($this->anything())
+ ->willReturnSelf();
+
+ $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $ldapProvider->clearCache('existing_user');
+ $this->addToAssertionCount(1);
+ }
+
+
+ public function testClearGroupCacheGroupIDNotFound(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('Group id not found in LDAP');
+
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $groupBackend = $this->getMockBuilder(\OCA\User_LDAP\Group_LDAP::class)
+ ->setMethods(['groupExists'])
+ ->disableOriginalConstructor()
+ ->getMock();
+ $groupBackend->expects($this->any())->method('groupExists')->willReturn(false);
+
+ $server = $this->getServerMock($userBackend, $groupBackend);
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $ldapProvider->clearGroupCache('nonexisting_group');
+ }
+
+ public function testClearGroupCache(): void {
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $groupBackend = $this->getMockBuilder(\OCA\User_LDAP\Group_LDAP::class)
+ ->setMethods(['groupExists', 'getLDAPAccess', 'getConnection', 'clearCache'])
+ ->disableOriginalConstructor()
+ ->getMock();
+ $groupBackend->expects($this->once())
+ ->method('groupExists')
+ ->willReturn(true);
+ $groupBackend->expects($this->once())
+ ->method('clearCache')
+ ->willReturn(true);
+ $groupBackend->expects($this->any())
+ ->method($this->anything())
+ ->willReturnSelf();
+
+ $server = $this->getServerMock($userBackend, $groupBackend);
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $ldapProvider->clearGroupCache('existing_group');
+ $this->addToAssertionCount(1);
+ }
+
+ public function testDnExists(): void {
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->setMethods(['dn2UserName'])
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userBackend->expects($this->any())
+ ->method('dn2UserName')
+ ->willReturn('existing_user');
+
+ $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $this->assertTrue($ldapProvider->dnExists('cn=existing_user,ou=Are Sufficient To,ou=Test,dc=example,dc=org'));
+ }
+
+ public function testFlagRecord(): void {
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->setMethods([])
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $ldapProvider->flagRecord('existing_user');
+ $this->addToAssertionCount(1);
+ }
+
+ public function testUnflagRecord(): void {
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->setMethods([])
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $ldapProvider->unflagRecord('existing_user');
+ $this->addToAssertionCount(1);
+ }
+
+
+ public function testGetLDAPDisplayNameFieldUserIDNotFound(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('User id not found in LDAP');
+
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->setMethods(['userExists'])
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userBackend->expects($this->any())->method('userExists')->willReturn(false);
+
+ $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $ldapProvider->getLDAPDisplayNameField('nonexisting_user');
+ }
+
+ public function testGetLDAPDisplayNameField(): void {
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->setMethods(['userExists', 'getLDAPAccess', 'getConnection', 'getConfiguration'])
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userBackend->expects($this->once())
+ ->method('userExists')
+ ->willReturn(true);
+ $userBackend->expects($this->once())
+ ->method('getConfiguration')
+ ->willReturn(['ldap_display_name' => 'displayName']);
+ $userBackend->expects($this->any())
+ ->method($this->anything())
+ ->willReturnSelf();
+
+ $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $this->assertEquals('displayName', $ldapProvider->getLDAPDisplayNameField('existing_user'));
+ }
+
+
+ public function testGetLDAPEmailFieldUserIDNotFound(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('User id not found in LDAP');
+
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->setMethods(['userExists'])
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userBackend->expects($this->any())->method('userExists')->willReturn(false);
+
+ $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $ldapProvider->getLDAPEmailField('nonexisting_user');
+ }
+
+ public function testGetLDAPEmailField(): void {
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->setMethods(['userExists', 'getLDAPAccess', 'getConnection', 'getConfiguration'])
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userBackend->expects($this->once())
+ ->method('userExists')
+ ->willReturn(true);
+ $userBackend->expects($this->once())
+ ->method('getConfiguration')
+ ->willReturn(['ldap_email_attr' => 'mail']);
+ $userBackend->expects($this->any())
+ ->method($this->anything())
+ ->willReturnSelf();
+
+ $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $this->assertEquals('mail', $ldapProvider->getLDAPEmailField('existing_user'));
+ }
+
+
+ public function testGetLDAPGroupMemberAssocUserIDNotFound(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('Group id not found in LDAP');
+
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $groupBackend = $this->getMockBuilder(\OCA\User_LDAP\Group_LDAP::class)
+ ->setMethods(['groupExists'])
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $groupBackend->expects($this->any())->method('groupExists')->willReturn(false);
+
+ $server = $this->getServerMock($userBackend, $groupBackend);
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $ldapProvider->getLDAPGroupMemberAssoc('nonexisting_group');
+ }
+
+ public function testgetLDAPGroupMemberAssoc(): void {
+ $userBackend = $this->getMockBuilder(\OCA\User_LDAP\User_LDAP::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $groupBackend = $this->getMockBuilder(\OCA\User_LDAP\Group_LDAP::class)
+ ->setMethods(['groupExists', 'getLDAPAccess', 'getConnection', 'getConfiguration'])
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $groupBackend->expects($this->once())
+ ->method('groupExists')
+ ->willReturn(true);
+ $groupBackend->expects($this->any())
+ ->method('getConfiguration')
+ ->willReturn(['ldap_group_member_assoc_attribute' => 'assoc_type']);
+ $groupBackend->expects($this->any())
+ ->method($this->anything())
+ ->willReturnSelf();
+
+ $server = $this->getServerMock($userBackend, $groupBackend);
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $this->assertEquals('assoc_type', $ldapProvider->getLDAPGroupMemberAssoc('existing_group'));
+ }
+
+ public function testGetMultiValueUserAttributeUserNotFound(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('User id not found in LDAP');
+
+ $userBackend = $this->createMock(User_LDAP::class);
+ $userBackend->expects(self::once())
+ ->method('userExists')
+ ->with('admin')
+ ->willReturn(false);
+ $groupBackend = $this->createMock(Group_LDAP::class);
+ $server = $this->getServerMock($userBackend, $groupBackend);
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $ldapProvider->getMultiValueUserAttribute('admin', 'mailAlias');
+ }
+
+ public function testGetMultiValueUserAttributeCacheHit(): void {
+ $connection = $this->createMock(Connection::class);
+ $connection->expects(self::once())
+ ->method('getFromCache')
+ ->with('admin-mailAlias')
+ ->willReturn(['aliasA@test.local', 'aliasB@test.local']);
+ $access = $this->createMock(Access::class);
+ $access->expects(self::once())
+ ->method('getConnection')
+ ->willReturn($connection);
+ $userBackend = $this->createMock(User_LDAP::class);
+ $userBackend->expects(self::once())
+ ->method('userExists')
+ ->with('admin')
+ ->willReturn(true);
+ $userBackend->expects(self::once())
+ ->method('getLDAPAccess')
+ ->willReturn($access);
+ $groupBackend = $this->createMock(Group_LDAP::class);
+ $server = $this->getServerMock($userBackend, $groupBackend);
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $ldapProvider->getMultiValueUserAttribute('admin', 'mailAlias');
+ }
+
+ public function testGetMultiValueUserAttributeLdapError(): void {
+ $connection = $this->createMock(Connection::class);
+ $connection->expects(self::once())
+ ->method('getFromCache')
+ ->with('admin-mailAlias')
+ ->willReturn(null);
+ $access = $this->createMock(Access::class);
+ $access->expects(self::once())
+ ->method('getConnection')
+ ->willReturn($connection);
+ $access->expects(self::once())
+ ->method('username2dn')
+ ->with('admin')
+ ->willReturn('admin');
+ $access->expects(self::once())
+ ->method('readAttribute')
+ ->with('admin', 'mailAlias')
+ ->willReturn(false);
+ $userBackend = $this->getMockBuilder(User_LDAP::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userBackend->method('userExists')
+ ->with('admin')
+ ->willReturn(true);
+ $userBackend->method('getLDAPAccess')
+ ->willReturn($access);
+ $groupBackend = $this->getMockBuilder(Group_LDAP::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $server = $this->getServerMock($userBackend, $groupBackend);
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $values = $ldapProvider->getMultiValueUserAttribute('admin', 'mailAlias');
+
+ self::assertCount(0, $values);
+ }
+
+ public function testGetMultiValueUserAttribute(): void {
+ $connection = $this->createMock(Connection::class);
+ $connection->expects(self::once())
+ ->method('getFromCache')
+ ->with('admin-mailAlias')
+ ->willReturn(null);
+ $access = $this->createMock(Access::class);
+ $access->expects(self::once())
+ ->method('getConnection')
+ ->willReturn($connection);
+ $access->expects(self::once())
+ ->method('username2dn')
+ ->with('admin')
+ ->willReturn('admin');
+ $access->expects(self::once())
+ ->method('readAttribute')
+ ->with('admin', 'mailAlias')
+ ->willReturn(['aliasA@test.local', 'aliasB@test.local']);
+ $userBackend = $this->getMockBuilder(User_LDAP::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userBackend->method('userExists')
+ ->with('admin')
+ ->willReturn(true);
+ $userBackend->method('getLDAPAccess')
+ ->willReturn($access);
+ $groupBackend = $this->getMockBuilder(Group_LDAP::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $server = $this->getServerMock($userBackend, $groupBackend);
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $values = $ldapProvider->getMultiValueUserAttribute('admin', 'mailAlias');
+
+ self::assertCount(2, $values);
+ }
+
+ public function testGetUserAttributeLdapError(): void {
+ $connection = $this->createMock(Connection::class);
+ $connection->expects(self::once())
+ ->method('getFromCache')
+ ->with('admin-mailAlias')
+ ->willReturn(null);
+ $access = $this->createMock(Access::class);
+ $access->expects(self::once())
+ ->method('getConnection')
+ ->willReturn($connection);
+ $access->expects(self::once())
+ ->method('username2dn')
+ ->with('admin')
+ ->willReturn('admin');
+ $access->expects(self::once())
+ ->method('readAttribute')
+ ->with('admin', 'mailAlias')
+ ->willReturn(false);
+ $userBackend = $this->getMockBuilder(User_LDAP::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userBackend->method('userExists')
+ ->with('admin')
+ ->willReturn(true);
+ $userBackend->method('getLDAPAccess')
+ ->willReturn($access);
+ $groupBackend = $this->getMockBuilder(Group_LDAP::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $server = $this->getServerMock($userBackend, $groupBackend);
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $value = $ldapProvider->getUserAttribute('admin', 'mailAlias');
+
+ self::assertNull($value);
+ }
+
+ public function testGetUserAttribute(): void {
+ $connection = $this->createMock(Connection::class);
+ $connection->expects(self::once())
+ ->method('getFromCache')
+ ->with('admin-mailAlias')
+ ->willReturn(null);
+ $access = $this->createMock(Access::class);
+ $access->expects(self::once())
+ ->method('getConnection')
+ ->willReturn($connection);
+ $access->expects(self::once())
+ ->method('username2dn')
+ ->with('admin')
+ ->willReturn('admin');
+ $access->expects(self::once())
+ ->method('readAttribute')
+ ->with('admin', 'mailAlias')
+ ->willReturn(['aliasA@test.local', 'aliasB@test.local']);
+ $userBackend = $this->getMockBuilder(User_LDAP::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userBackend->method('userExists')
+ ->with('admin')
+ ->willReturn(true);
+ $userBackend->method('getLDAPAccess')
+ ->willReturn($access);
+ $groupBackend = $this->getMockBuilder(Group_LDAP::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $server = $this->getServerMock($userBackend, $groupBackend);
+
+ $ldapProvider = $this->getLDAPProvider($server);
+ $value = $ldapProvider->getUserAttribute('admin', 'mailAlias');
+
+ self::assertEquals('aliasA@test.local', $value);
+ }
+}
diff --git a/apps/user_ldap/tests/LDAPTest.php b/apps/user_ldap/tests/LDAPTest.php
index 51ed0c2b462..b7349d11b36 100644
--- a/apps/user_ldap/tests/LDAPTest.php
+++ b/apps/user_ldap/tests/LDAPTest.php
@@ -36,7 +36,7 @@ class LDAPTest extends TestCase {
* @param bool $passThrough
* @dataProvider errorProvider
*/
- public function testSearchWithErrorHandler(string $errorMessage, bool $passThrough) {
+ public function testSearchWithErrorHandler(string $errorMessage, bool $passThrough): void {
$wasErrorHandlerCalled = false;
$errorHandler = function ($number, $message, $file, $line) use (&$wasErrorHandlerCalled) {
$wasErrorHandlerCalled = true;
@@ -59,7 +59,7 @@ class LDAPTest extends TestCase {
restore_error_handler();
}
- public function testModReplace() {
+ public function testModReplace(): void {
$link = $this->createMock(LDAP::class);
$userDN = 'CN=user';
$password = 'MyPassword';
diff --git a/apps/user_ldap/tests/Mapping/AbstractMappingTest.php b/apps/user_ldap/tests/Mapping/AbstractMappingTest.php
index 478e5ea0395..e0a31c119ba 100644
--- a/apps/user_ldap/tests/Mapping/AbstractMappingTest.php
+++ b/apps/user_ldap/tests/Mapping/AbstractMappingTest.php
@@ -16,7 +16,7 @@ abstract class AbstractMappingTest extends \Test\TestCase {
/**
* kiss test on isColNameValid
*/
- public function testIsColNameValid() {
+ public function testIsColNameValid(): void {
$dbMock = $this->createMock(IDBConnection::class);
$mapper = $this->getMapper($dbMock);
@@ -84,7 +84,7 @@ abstract class AbstractMappingTest extends \Test\TestCase {
* tests map() method with input that should result in not-mapping.
* Hint: successful mapping is tested inherently with mapEntries().
*/
- public function testMap() {
+ public function testMap(): void {
[$mapper, $data] = $this->initTest();
// test that mapping will not happen when it shall not
@@ -104,7 +104,7 @@ abstract class AbstractMappingTest extends \Test\TestCase {
* tests unmap() for both successful and unsuccessful removing of
* mapping entries
*/
- public function testUnmap() {
+ public function testUnmap(): void {
[$mapper, $data] = $this->initTest();
foreach ($data as $entry) {
@@ -124,7 +124,7 @@ abstract class AbstractMappingTest extends \Test\TestCase {
* tests getDNByName(), getNameByDN() and getNameByUUID() for successful
* and unsuccessful requests.
*/
- public function testGetMethods() {
+ public function testGetMethods(): void {
[$mapper, $data] = $this->initTest();
foreach ($data as $entry) {
@@ -152,7 +152,7 @@ abstract class AbstractMappingTest extends \Test\TestCase {
/**
* tests getNamesBySearch() for successful and unsuccessful requests.
*/
- public function testSearch() {
+ public function testSearch(): void {
[$mapper,] = $this->initTest();
$names = $mapper->getNamesBySearch('oo', '%', '%');
@@ -168,7 +168,7 @@ abstract class AbstractMappingTest extends \Test\TestCase {
/**
* tests setDNbyUUID() for successful and unsuccessful update.
*/
- public function testSetDNMethod() {
+ public function testSetDNMethod(): void {
[$mapper, $data] = $this->initTest();
$newDN = 'uid=modified,dc=example,dc=org';
@@ -187,7 +187,7 @@ abstract class AbstractMappingTest extends \Test\TestCase {
/**
* tests setUUIDbyDN() for successful and unsuccessful update.
*/
- public function testSetUUIDMethod() {
+ public function testSetUUIDMethod(): void {
/** @var AbstractMapping $mapper */
[$mapper, $data] = $this->initTest();
@@ -207,7 +207,7 @@ abstract class AbstractMappingTest extends \Test\TestCase {
/**
* tests clear() for successful update.
*/
- public function testClear() {
+ public function testClear(): void {
[$mapper, $data] = $this->initTest();
$done = $mapper->clear();
@@ -221,7 +221,7 @@ abstract class AbstractMappingTest extends \Test\TestCase {
/**
* tests clear() for successful update.
*/
- public function testClearCb() {
+ public function testClearCb(): void {
[$mapper, $data] = $this->initTest();
$callbackCalls = 0;
@@ -244,7 +244,7 @@ abstract class AbstractMappingTest extends \Test\TestCase {
/**
* tests getList() method
*/
- public function testList() {
+ public function testList(): void {
[$mapper, $data] = $this->initTest();
// get all entries without specifying offset or limit
@@ -265,7 +265,7 @@ abstract class AbstractMappingTest extends \Test\TestCase {
$this->assertSame(1, count($results));
}
- public function testGetListOfIdsByDn() {
+ public function testGetListOfIdsByDn(): void {
/** @var AbstractMapping $mapper */
[$mapper,] = $this->initTest();
diff --git a/apps/user_ldap/tests/Migration/AbstractUUIDFixTest.php b/apps/user_ldap/tests/Migration/AbstractUUIDFixTest.php
index 9d433cf4937..f8abcaeb482 100644
--- a/apps/user_ldap/tests/Migration/AbstractUUIDFixTest.php
+++ b/apps/user_ldap/tests/Migration/AbstractUUIDFixTest.php
@@ -48,7 +48,7 @@ abstract class AbstractUUIDFixTest extends TestCase {
->willReturn($this->access);
}
- public function testRunSingleRecord() {
+ public function testRunSingleRecord(): void {
$args = [
'records' => [
0 => [
@@ -72,7 +72,7 @@ abstract class AbstractUUIDFixTest extends TestCase {
$this->job->run($args);
}
- public function testRunValidRecord() {
+ public function testRunValidRecord(): void {
$correctUUID = '4355-AED3-9D73-03AD';
$args = [
'records' => [
@@ -95,7 +95,7 @@ abstract class AbstractUUIDFixTest extends TestCase {
$this->job->run($args);
}
- public function testRunRemovedRecord() {
+ public function testRunRemovedRecord(): void {
$args = [
'records' => [
0 => [
@@ -117,7 +117,7 @@ abstract class AbstractUUIDFixTest extends TestCase {
$this->job->run($args);
}
- public function testRunManyRecords() {
+ public function testRunManyRecords(): void {
$args = [
'records' => [
0 => [
diff --git a/apps/user_ldap/tests/Migration/UUIDFixInsertTest.php b/apps/user_ldap/tests/Migration/UUIDFixInsertTest.php
index 78d119bf566..f31da43c584 100644
--- a/apps/user_ldap/tests/Migration/UUIDFixInsertTest.php
+++ b/apps/user_ldap/tests/Migration/UUIDFixInsertTest.php
@@ -44,7 +44,7 @@ class UUIDFixInsertTest extends TestCase {
);
}
- public function testGetName() {
+ public function testGetName(): void {
$this->assertSame('Insert UUIDFix background job for user and group in batches', $this->job->getName());
}
@@ -97,7 +97,7 @@ class UUIDFixInsertTest extends TestCase {
/**
* @dataProvider recordProvider
*/
- public function testRun($userBatches, $groupBatches) {
+ public function testRun($userBatches, $groupBatches): void {
$this->config->expects($this->once())
->method('getAppValue')
->with('user_ldap', 'installed_version', '1.2.1')
@@ -124,7 +124,7 @@ class UUIDFixInsertTest extends TestCase {
/**
* @dataProvider recordProviderTooLongAndNone
*/
- public function testRunWithManyAndNone($userBatches, $groupBatches) {
+ public function testRunWithManyAndNone($userBatches, $groupBatches): void {
$this->config->expects($this->once())
->method('getAppValue')
->with('user_ldap', 'installed_version', '1.2.1')
@@ -155,7 +155,7 @@ class UUIDFixInsertTest extends TestCase {
$this->job->run($out);
}
- public function testDonNotRun() {
+ public function testDonNotRun(): void {
$this->config->expects($this->once())
->method('getAppValue')
->with('user_ldap', 'installed_version', '1.2.1')
diff --git a/apps/user_ldap/tests/Settings/AdminTest.php b/apps/user_ldap/tests/Settings/AdminTest.php
index 7906a07c3e9..e06563d1856 100644
--- a/apps/user_ldap/tests/Settings/AdminTest.php
+++ b/apps/user_ldap/tests/Settings/AdminTest.php
@@ -34,7 +34,7 @@ class AdminTest extends TestCase {
/**
* @UseDB
*/
- public function testGetForm() {
+ public function testGetForm(): void {
$prefixes = ['s01'];
$hosts = ['s01' => ''];
@@ -59,11 +59,11 @@ class AdminTest extends TestCase {
$this->assertEquals($expected, $this->admin->getForm());
}
- public function testGetSection() {
+ public function testGetSection(): void {
$this->assertSame('ldap', $this->admin->getSection());
}
- public function testGetPriority() {
+ public function testGetPriority(): void {
$this->assertSame(5, $this->admin->getPriority());
}
}
diff --git a/apps/user_ldap/tests/Settings/SectionTest.php b/apps/user_ldap/tests/Settings/SectionTest.php
index 5fe5476f1c3..722581713d1 100644
--- a/apps/user_ldap/tests/Settings/SectionTest.php
+++ b/apps/user_ldap/tests/Settings/SectionTest.php
@@ -29,11 +29,11 @@ class SectionTest extends TestCase {
);
}
- public function testGetID() {
+ public function testGetID(): void {
$this->assertSame('ldap', $this->section->getID());
}
- public function testGetName() {
+ public function testGetName(): void {
$this->l
->expects($this->once())
->method('t')
@@ -43,11 +43,11 @@ class SectionTest extends TestCase {
$this->assertSame('LDAP/AD integration', $this->section->getName());
}
- public function testGetPriority() {
+ public function testGetPriority(): void {
$this->assertSame(25, $this->section->getPriority());
}
- public function testGetIcon() {
+ public function testGetIcon(): void {
$this->url->expects($this->once())
->method('imagePath')
->with('user_ldap', 'app-dark.svg')
diff --git a/apps/user_ldap/tests/User/DeletedUsersIndexTest.php b/apps/user_ldap/tests/User/DeletedUsersIndexTest.php
index 32fa5bc38bf..0e77f5023d5 100644
--- a/apps/user_ldap/tests/User/DeletedUsersIndexTest.php
+++ b/apps/user_ldap/tests/User/DeletedUsersIndexTest.php
@@ -54,7 +54,7 @@ class DeletedUsersIndexTest extends \Test\TestCase {
parent::tearDown();
}
- public function testMarkAndFetchUser() {
+ public function testMarkAndFetchUser(): void {
$uids = [
'cef3775c-71d2-48eb-8984-39a4051b0b95',
'8c4bbb40-33ed-42d0-9b14-85b0ab76c1cc',
@@ -82,7 +82,7 @@ class DeletedUsersIndexTest extends \Test\TestCase {
$this->assertEmpty($uids);
}
- public function testUnmarkUser() {
+ public function testUnmarkUser(): void {
$uids = [
'22a162c7-a9ee-487c-9f33-0563795583fb',
'1fb4e0da-4a75-47f3-8fa7-becc7e35c9c5',
diff --git a/apps/user_ldap/tests/User/ManagerTest.php b/apps/user_ldap/tests/User/ManagerTest.php
index 597a2e69a0a..449f159ec4d 100644
--- a/apps/user_ldap/tests/User/ManagerTest.php
+++ b/apps/user_ldap/tests/User/ManagerTest.php
@@ -114,7 +114,7 @@ class ManagerTest extends \Test\TestCase {
/**
* @dataProvider dnProvider
*/
- public function testGetByDNExisting(string $inputDN) {
+ public function testGetByDNExisting(string $inputDN): void {
$uid = '563418fc-423b-1033-8d1c-ad5f418ee02e';
$this->access->expects($this->once())
@@ -139,7 +139,7 @@ class ManagerTest extends \Test\TestCase {
$this->assertInstanceOf(User::class, $user);
}
- public function testGetByDNNotExisting() {
+ public function testGetByDNNotExisting(): void {
$inputDN = 'cn=gone,dc=foobar,dc=bar';
$this->access->expects($this->once())
@@ -161,7 +161,7 @@ class ManagerTest extends \Test\TestCase {
$this->assertNull($user);
}
- public function testGetByUidExisting() {
+ public function testGetByUidExisting(): void {
$dn = 'cn=foo,dc=foobar,dc=bar';
$uid = '563418fc-423b-1033-8d1c-ad5f418ee02e';
@@ -187,7 +187,7 @@ class ManagerTest extends \Test\TestCase {
$this->assertInstanceOf(User::class, $user);
}
- public function testGetByUidNotExisting() {
+ public function testGetByUidNotExisting(): void {
$uid = 'gone';
$this->access->expects($this->never())
@@ -213,7 +213,7 @@ class ManagerTest extends \Test\TestCase {
/**
* @dataProvider attributeRequestProvider
*/
- public function testGetAttributes($minimal) {
+ public function testGetAttributes($minimal): void {
$this->connection->setConfiguration([
'ldapEmailAttribute' => 'MAIL',
'ldapUserAvatarRule' => 'default',
diff --git a/apps/user_ldap/tests/User/OfflineUserTest.php b/apps/user_ldap/tests/User/OfflineUserTest.php
index 8ac0e617d80..e53bfca7f47 100644
--- a/apps/user_ldap/tests/User/OfflineUserTest.php
+++ b/apps/user_ldap/tests/User/OfflineUserTest.php
@@ -55,7 +55,7 @@ class OfflineUserTest extends TestCase {
/**
* @dataProvider shareOwnerProvider
*/
- public function testHasActiveShares(array $existingShareTypes, bool $expected) {
+ public function testHasActiveShares(array $existingShareTypes, bool $expected): void {
$shareMock = $this->createMock(IShare::class);
$this->shareManager->expects($this->atLeastOnce())
diff --git a/apps/user_ldap/tests/User/UserTest.php b/apps/user_ldap/tests/User/UserTest.php
index 1d4aeb619b6..aca4e2434e2 100644
--- a/apps/user_ldap/tests/User/UserTest.php
+++ b/apps/user_ldap/tests/User/UserTest.php
@@ -87,12 +87,12 @@ class UserTest extends \Test\TestCase {
);
}
- public function testGetDNandUsername() {
+ public function testGetDNandUsername(): void {
$this->assertSame($this->dn, $this->user->getDN());
$this->assertSame($this->uid, $this->user->getUsername());
}
- public function testUpdateEmailProvided() {
+ public function testUpdateEmailProvided(): void {
$this->connection->expects($this->once())
->method('__get')
->with($this->equalTo('ldapEmailAttribute'))
@@ -118,7 +118,7 @@ class UserTest extends \Test\TestCase {
$this->user->updateEmail();
}
- public function testUpdateEmailNotProvided() {
+ public function testUpdateEmailNotProvided(): void {
$this->connection->expects($this->once())
->method('__get')
->with($this->equalTo('ldapEmailAttribute'))
@@ -136,7 +136,7 @@ class UserTest extends \Test\TestCase {
$this->user->updateEmail();
}
- public function testUpdateEmailNotConfigured() {
+ public function testUpdateEmailNotConfigured(): void {
$this->connection->expects($this->once())
->method('__get')
->with($this->equalTo('ldapEmailAttribute'))
@@ -151,7 +151,7 @@ class UserTest extends \Test\TestCase {
$this->user->updateEmail();
}
- public function testUpdateQuotaAllProvided() {
+ public function testUpdateQuotaAllProvided(): void {
$this->connection->expects($this->exactly(2))
->method('__get')
->willReturnMap([
@@ -178,7 +178,7 @@ class UserTest extends \Test\TestCase {
$this->user->updateQuota();
}
- public function testUpdateQuotaToDefaultAllProvided() {
+ public function testUpdateQuotaToDefaultAllProvided(): void {
$this->connection->expects($this->exactly(2))
->method('__get')
->willReturnMap([
@@ -205,7 +205,7 @@ class UserTest extends \Test\TestCase {
$this->user->updateQuota();
}
- public function testUpdateQuotaToNoneAllProvided() {
+ public function testUpdateQuotaToNoneAllProvided(): void {
$this->connection->expects($this->exactly(2))
->method('__get')
->willReturnMap([
@@ -232,7 +232,7 @@ class UserTest extends \Test\TestCase {
$this->user->updateQuota();
}
- public function testUpdateQuotaDefaultProvided() {
+ public function testUpdateQuotaDefaultProvided(): void {
$this->connection->expects($this->exactly(2))
->method('__get')
->willReturnMap([
@@ -259,7 +259,7 @@ class UserTest extends \Test\TestCase {
$this->user->updateQuota();
}
- public function testUpdateQuotaIndividualProvided() {
+ public function testUpdateQuotaIndividualProvided(): void {
$this->connection->expects($this->exactly(2))
->method('__get')
->willReturnMap([
@@ -286,7 +286,7 @@ class UserTest extends \Test\TestCase {
$this->user->updateQuota();
}
- public function testUpdateQuotaNoneProvided() {
+ public function testUpdateQuotaNoneProvided(): void {
$this->connection->expects($this->exactly(2))
->method('__get')
->willReturnMap([
@@ -314,7 +314,7 @@ class UserTest extends \Test\TestCase {
$this->user->updateQuota();
}
- public function testUpdateQuotaNoneConfigured() {
+ public function testUpdateQuotaNoneConfigured(): void {
$this->connection->expects($this->exactly(2))
->method('__get')
->willReturnMap([
@@ -338,7 +338,7 @@ class UserTest extends \Test\TestCase {
$this->user->updateQuota();
}
- public function testUpdateQuotaFromValue() {
+ public function testUpdateQuotaFromValue(): void {
$readQuota = '19 GB';
$this->connection->expects($this->exactly(2))
@@ -367,7 +367,7 @@ class UserTest extends \Test\TestCase {
/**
* Unparseable quota will fallback to use the LDAP default
*/
- public function testUpdateWrongQuotaAllProvided() {
+ public function testUpdateWrongQuotaAllProvided(): void {
$this->connection->expects($this->exactly(2))
->method('__get')
->willReturnMap([
@@ -397,7 +397,7 @@ class UserTest extends \Test\TestCase {
/**
* No user quota and wrong default will set 'default' as quota
*/
- public function testUpdateWrongDefaultQuotaProvided() {
+ public function testUpdateWrongDefaultQuotaProvided(): void {
$this->connection->expects($this->exactly(2))
->method('__get')
->willReturnMap([
@@ -424,7 +424,7 @@ class UserTest extends \Test\TestCase {
/**
* Wrong user quota and wrong default will set 'default' as quota
*/
- public function testUpdateWrongQuotaAndDefaultAllProvided() {
+ public function testUpdateWrongQuotaAndDefaultAllProvided(): void {
$this->connection->expects($this->exactly(2))
->method('__get')
->willReturnMap([
@@ -451,7 +451,7 @@ class UserTest extends \Test\TestCase {
/**
* No quota attribute set and wrong default will set 'default' as quota
*/
- public function testUpdateWrongDefaultQuotaNotProvided() {
+ public function testUpdateWrongDefaultQuotaNotProvided(): void {
$this->connection->expects($this->exactly(2))
->method('__get')
->willReturnMap([
@@ -529,7 +529,7 @@ class UserTest extends \Test\TestCase {
$this->user->updateAvatar();
}
- public function testUpdateAvatarKnownJpegPhotoProvided() {
+ public function testUpdateAvatarKnownJpegPhotoProvided(): void {
$this->access->expects($this->once())
->method('readAttribute')
->with($this->equalTo($this->dn),
@@ -647,7 +647,7 @@ class UserTest extends \Test\TestCase {
$this->user->updateAvatar();
}
- public function testUpdateAvatarCorruptPhotoProvided() {
+ public function testUpdateAvatarCorruptPhotoProvided(): void {
$this->access->expects($this->any())
->method('readAttribute')
->willReturnCallback(function ($dn, $attr) {
@@ -761,7 +761,7 @@ class UserTest extends \Test\TestCase {
$this->assertFalse($this->user->updateAvatar());
}
- public function testUpdateAvatarNotProvided() {
+ public function testUpdateAvatarNotProvided(): void {
$this->access->expects($this->any())
->method('readAttribute')
->willReturnCallback(function ($dn, $attr) {
@@ -816,7 +816,7 @@ class UserTest extends \Test\TestCase {
/**
* @dataProvider extStorageHomeDataProvider
*/
- public function testUpdateExtStorageHome(string $expected, ?string $valueFromLDAP = null, bool $isSet = true) {
+ public function testUpdateExtStorageHome(string $expected, ?string $valueFromLDAP = null, bool $isSet = true): void {
if ($valueFromLDAP === null) {
$this->connection->expects($this->once())
->method('__get')
@@ -848,7 +848,7 @@ class UserTest extends \Test\TestCase {
$this->assertSame($expected, $actual);
}
- public function testMarkLogin() {
+ public function testMarkLogin(): void {
$this->config->expects($this->once())
->method('setUserValue')
->with($this->equalTo($this->uid),
@@ -860,7 +860,7 @@ class UserTest extends \Test\TestCase {
$this->user->markLogin();
}
- public function testGetAvatarImageProvided() {
+ public function testGetAvatarImageProvided(): void {
$this->access->expects($this->once())
->method('readAttribute')
->with($this->equalTo($this->dn),
@@ -878,7 +878,7 @@ class UserTest extends \Test\TestCase {
$this->user->getAvatarImage();
}
- public function testGetAvatarImageDisabled() {
+ public function testGetAvatarImageDisabled(): void {
$this->access->expects($this->never())
->method('readAttribute')
->with($this->equalTo($this->dn), $this->anything());
@@ -898,7 +898,7 @@ class UserTest extends \Test\TestCase {
];
}
- public function testProcessAttributes() {
+ public function testProcessAttributes(): void {
$requiredMethods = [
'updateQuota',
'updateEmail',
@@ -973,7 +973,7 @@ class UserTest extends \Test\TestCase {
/**
* @dataProvider emptyHomeFolderAttributeValueProvider
*/
- public function testGetHomePathNotConfigured($attributeValue) {
+ public function testGetHomePathNotConfigured($attributeValue): void {
$this->connection->expects($this->any())
->method('__get')
->with($this->equalTo('homeFolderNamingRule'))
@@ -989,7 +989,7 @@ class UserTest extends \Test\TestCase {
$this->assertFalse($this->user->getHomePath());
}
- public function testGetHomePathConfiguredNotAvailableAllowed() {
+ public function testGetHomePathConfiguredNotAvailableAllowed(): void {
$this->connection->expects($this->any())
->method('__get')
->with($this->equalTo('homeFolderNamingRule'))
@@ -1013,7 +1013,7 @@ class UserTest extends \Test\TestCase {
}
- public function testGetHomePathConfiguredNotAvailableNotAllowed() {
+ public function testGetHomePathConfiguredNotAvailableNotAllowed(): void {
$this->expectException(\Exception::class);
$this->connection->expects($this->any())
@@ -1050,7 +1050,7 @@ class UserTest extends \Test\TestCase {
/**
* @dataProvider displayNameProvider
*/
- public function testComposeAndStoreDisplayName($part1, $part2, $expected, $expectTriggerChange) {
+ public function testComposeAndStoreDisplayName($part1, $part2, $expected, $expectTriggerChange): void {
$this->config->expects($this->once())
->method('setUserValue');
$oldName = $expectTriggerChange ? 'xxGunslingerxx' : null;
@@ -1076,7 +1076,7 @@ class UserTest extends \Test\TestCase {
$this->assertSame($expected, $displayName);
}
- public function testComposeAndStoreDisplayNameNoOverwrite() {
+ public function testComposeAndStoreDisplayNameNoOverwrite(): void {
$displayName = 'Randall Flagg';
$this->config->expects($this->never())
->method('setUserValue');
@@ -1091,7 +1091,7 @@ class UserTest extends \Test\TestCase {
$this->assertSame($composedDisplayName, $displayName);
}
- public function testHandlePasswordExpiryWarningDefaultPolicy() {
+ public function testHandlePasswordExpiryWarningDefaultPolicy(): void {
$this->connection->expects($this->any())
->method('__get')
->willReturnCallback(function ($name) {
@@ -1154,7 +1154,7 @@ class UserTest extends \Test\TestCase {
\OC_Hook::emit('OC_User', 'post_login', ['uid' => $this->uid]);
}
- public function testHandlePasswordExpiryWarningCustomPolicy() {
+ public function testHandlePasswordExpiryWarningCustomPolicy(): void {
$this->connection->expects($this->any())
->method('__get')
->willReturnCallback(function ($name) {
diff --git a/apps/user_ldap/tests/UserLDAPPluginTest.php b/apps/user_ldap/tests/UserLDAPPluginTest.php
index 48d52028f37..cefc98b3a5e 100644
--- a/apps/user_ldap/tests/UserLDAPPluginTest.php
+++ b/apps/user_ldap/tests/UserLDAPPluginTest.php
@@ -17,7 +17,7 @@ class UserLDAPPluginTest extends \Test\TestCase {
return new UserPluginManager();
}
- public function testImplementsActions() {
+ public function testImplementsActions(): void {
$pluginManager = $this->getUserPluginManager();
$plugin = $this->getMockBuilder(\OCA\User_LDAP\Tests\LDAPUserPluginDummy::class)
@@ -44,7 +44,7 @@ class UserLDAPPluginTest extends \Test\TestCase {
$this->assertTrue($pluginManager->implementsActions(Backend::PROVIDE_AVATAR));
}
- public function testCreateUser() {
+ public function testCreateUser(): void {
$pluginManager = $this->getUserPluginManager();
$plugin = $this->getMockBuilder(\OCA\User_LDAP\Tests\LDAPUserPluginDummy::class)
@@ -67,7 +67,7 @@ class UserLDAPPluginTest extends \Test\TestCase {
}
- public function testCreateUserNotRegistered() {
+ public function testCreateUserNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements createUser in this LDAP Backend.');
@@ -75,7 +75,7 @@ class UserLDAPPluginTest extends \Test\TestCase {
$pluginManager->createUser('foo', 'bar');
}
- public function testSetPassword() {
+ public function testSetPassword(): void {
$pluginManager = $this->getUserPluginManager();
$plugin = $this->getMockBuilder(\OCA\User_LDAP\Tests\LDAPUserPluginDummy::class)
@@ -98,7 +98,7 @@ class UserLDAPPluginTest extends \Test\TestCase {
}
- public function testSetPasswordNotRegistered() {
+ public function testSetPasswordNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements setPassword in this LDAP Backend.');
@@ -106,7 +106,7 @@ class UserLDAPPluginTest extends \Test\TestCase {
$pluginManager->setPassword('foo', 'bar');
}
- public function testGetHome() {
+ public function testGetHome(): void {
$pluginManager = $this->getUserPluginManager();
$plugin = $this->getMockBuilder(\OCA\User_LDAP\Tests\LDAPUserPluginDummy::class)
@@ -128,7 +128,7 @@ class UserLDAPPluginTest extends \Test\TestCase {
}
- public function testGetHomeNotRegistered() {
+ public function testGetHomeNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements getHome in this LDAP Backend.');
@@ -136,7 +136,7 @@ class UserLDAPPluginTest extends \Test\TestCase {
$pluginManager->getHome('foo');
}
- public function testGetDisplayName() {
+ public function testGetDisplayName(): void {
$pluginManager = $this->getUserPluginManager();
$plugin = $this->getMockBuilder(\OCA\User_LDAP\Tests\LDAPUserPluginDummy::class)
@@ -158,7 +158,7 @@ class UserLDAPPluginTest extends \Test\TestCase {
}
- public function testGetDisplayNameNotRegistered() {
+ public function testGetDisplayNameNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements getDisplayName in this LDAP Backend.');
@@ -166,7 +166,7 @@ class UserLDAPPluginTest extends \Test\TestCase {
$pluginManager->getDisplayName('foo');
}
- public function testSetDisplayName() {
+ public function testSetDisplayName(): void {
$pluginManager = $this->getUserPluginManager();
$plugin = $this->getMockBuilder(\OCA\User_LDAP\Tests\LDAPUserPluginDummy::class)
@@ -189,7 +189,7 @@ class UserLDAPPluginTest extends \Test\TestCase {
}
- public function testSetDisplayNameNotRegistered() {
+ public function testSetDisplayNameNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements setDisplayName in this LDAP Backend.');
@@ -197,7 +197,7 @@ class UserLDAPPluginTest extends \Test\TestCase {
$pluginManager->setDisplayName('foo', 'bar');
}
- public function testCanChangeAvatar() {
+ public function testCanChangeAvatar(): void {
$pluginManager = $this->getUserPluginManager();
$plugin = $this->getMockBuilder(\OCA\User_LDAP\Tests\LDAPUserPluginDummy::class)
@@ -219,7 +219,7 @@ class UserLDAPPluginTest extends \Test\TestCase {
}
- public function testCanChangeAvatarNotRegistered() {
+ public function testCanChangeAvatarNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements canChangeAvatar in this LDAP Backend.');
@@ -227,7 +227,7 @@ class UserLDAPPluginTest extends \Test\TestCase {
$pluginManager->canChangeAvatar('foo');
}
- public function testCountUsers() {
+ public function testCountUsers(): void {
$pluginManager = $this->getUserPluginManager();
$plugin = $this->getMockBuilder(\OCA\User_LDAP\Tests\LDAPUserPluginDummy::class)
@@ -246,7 +246,7 @@ class UserLDAPPluginTest extends \Test\TestCase {
}
- public function testCountUsersNotRegistered() {
+ public function testCountUsersNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements countUsers in this LDAP Backend.');
@@ -254,7 +254,7 @@ class UserLDAPPluginTest extends \Test\TestCase {
$pluginManager->countUsers();
}
- public function testDeleteUser() {
+ public function testDeleteUser(): void {
$pluginManager = $this->getUserPluginManager();
$plugin = $this->getMockBuilder(\OCA\User_LDAP\Tests\LDAPUserPluginDummy::class)
@@ -282,7 +282,7 @@ class UserLDAPPluginTest extends \Test\TestCase {
}
- public function testDeleteUserNotRegistered() {
+ public function testDeleteUserNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements deleteUser in this LDAP Backend.');
diff --git a/apps/user_ldap/tests/User_LDAPTest.php b/apps/user_ldap/tests/User_LDAPTest.php
index 8d6a56112ce..90166beccff 100644
--- a/apps/user_ldap/tests/User_LDAPTest.php
+++ b/apps/user_ldap/tests/User_LDAPTest.php
@@ -170,7 +170,7 @@ class User_LDAPTest extends TestCase {
->willReturn(['dn', 'uid', 'mail', 'displayname']);
}
- public function testCheckPasswordUidReturn() {
+ public function testCheckPasswordUidReturn(): void {
$user = $this->createMock(User::class);
$user->expects($this->any())
->method('getUsername')
@@ -189,7 +189,7 @@ class User_LDAPTest extends TestCase {
$this->assertEquals('gunslinger', $result);
}
- public function testCheckPasswordWrongPassword() {
+ public function testCheckPasswordWrongPassword(): void {
$this->prepareAccessForCheckPassword();
$backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
\OC_User::useBackend($backend);
@@ -198,7 +198,7 @@ class User_LDAPTest extends TestCase {
$this->assertFalse($result);
}
- public function testCheckPasswordWrongUser() {
+ public function testCheckPasswordWrongUser(): void {
$this->prepareAccessForCheckPassword();
$backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
\OC_User::useBackend($backend);
@@ -207,7 +207,7 @@ class User_LDAPTest extends TestCase {
$this->assertFalse($result);
}
- public function testCheckPasswordNoDisplayName() {
+ public function testCheckPasswordNoDisplayName(): void {
$this->prepareAccessForCheckPassword(true);
$this->prepareAccessForCheckPassword();
@@ -222,7 +222,7 @@ class User_LDAPTest extends TestCase {
$this->assertFalse($result);
}
- public function testCheckPasswordPublicAPI() {
+ public function testCheckPasswordPublicAPI(): void {
$user = $this->createMock(User::class);
$user->expects($this->any())
->method('getUsername')
@@ -244,7 +244,7 @@ class User_LDAPTest extends TestCase {
$this->assertEquals('gunslinger', $result);
}
- public function testCheckPasswordPublicAPIWrongPassword() {
+ public function testCheckPasswordPublicAPIWrongPassword(): void {
$this->prepareAccessForCheckPassword();
$backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
\OC_User::useBackend($backend);
@@ -257,7 +257,7 @@ class User_LDAPTest extends TestCase {
$this->assertFalse($result);
}
- public function testCheckPasswordPublicAPIWrongUser() {
+ public function testCheckPasswordPublicAPIWrongUser(): void {
$this->prepareAccessForCheckPassword();
$backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
\OC_User::useBackend($backend);
@@ -270,13 +270,13 @@ class User_LDAPTest extends TestCase {
$this->assertFalse($result);
}
- public function testDeleteUserCancel() {
+ public function testDeleteUserCancel(): void {
$backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$result = $backend->deleteUser('notme');
$this->assertFalse($result);
}
- public function testDeleteUserSuccess() {
+ public function testDeleteUserSuccess(): void {
$uid = 'jeremy';
$home = '/var/vhome/jdings/';
@@ -316,7 +316,7 @@ class User_LDAPTest extends TestCase {
$this->assertSame($backend->getHome($uid), $home);
}
- public function testDeleteUserWithPlugin() {
+ public function testDeleteUserWithPlugin(): void {
$this->pluginManager->expects($this->once())
->method('canDeleteUser')
->willReturn(true);
@@ -395,7 +395,7 @@ class User_LDAPTest extends TestCase {
->willReturn(['dn', 'uid', 'mail', 'displayname']);
}
- public function testGetUsersNoParam() {
+ public function testGetUsersNoParam(): void {
$this->prepareAccessForGetUsers();
$backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
@@ -403,7 +403,7 @@ class User_LDAPTest extends TestCase {
$this->assertEquals(3, count($result));
}
- public function testGetUsersLimitOffset() {
+ public function testGetUsersLimitOffset(): void {
$this->prepareAccessForGetUsers();
$backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
@@ -411,7 +411,7 @@ class User_LDAPTest extends TestCase {
$this->assertEquals(1, count($result));
}
- public function testGetUsersLimitOffset2() {
+ public function testGetUsersLimitOffset2(): void {
$this->prepareAccessForGetUsers();
$backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
@@ -419,7 +419,7 @@ class User_LDAPTest extends TestCase {
$this->assertEquals(2, count($result));
}
- public function testGetUsersSearchWithResult() {
+ public function testGetUsersSearchWithResult(): void {
$this->prepareAccessForGetUsers();
$backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
@@ -427,7 +427,7 @@ class User_LDAPTest extends TestCase {
$this->assertEquals(2, count($result));
}
- public function testGetUsersSearchEmptyResult() {
+ public function testGetUsersSearchEmptyResult(): void {
$this->prepareAccessForGetUsers();
$backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
@@ -443,7 +443,7 @@ class User_LDAPTest extends TestCase {
return $uids;
}
- public function testGetUsersViaAPINoParam() {
+ public function testGetUsersViaAPINoParam(): void {
$this->prepareAccessForGetUsers();
$backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
\OC_User::useBackend($backend);
@@ -452,7 +452,7 @@ class User_LDAPTest extends TestCase {
$this->assertEquals(3, count($result));
}
- public function testGetUsersViaAPILimitOffset() {
+ public function testGetUsersViaAPILimitOffset(): void {
$this->prepareAccessForGetUsers();
$backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
\OC_User::useBackend($backend);
@@ -461,7 +461,7 @@ class User_LDAPTest extends TestCase {
$this->assertEquals(1, count($result));
}
- public function testGetUsersViaAPILimitOffset2() {
+ public function testGetUsersViaAPILimitOffset2(): void {
$this->prepareAccessForGetUsers();
$backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
\OC_User::useBackend($backend);
@@ -470,7 +470,7 @@ class User_LDAPTest extends TestCase {
$this->assertEquals(2, count($result));
}
- public function testGetUsersViaAPISearchWithResult() {
+ public function testGetUsersViaAPISearchWithResult(): void {
$this->prepareAccessForGetUsers();
$backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
\OC_User::useBackend($backend);
@@ -479,7 +479,7 @@ class User_LDAPTest extends TestCase {
$this->assertEquals(2, count($result));
}
- public function testGetUsersViaAPISearchEmptyResult() {
+ public function testGetUsersViaAPISearchEmptyResult(): void {
$this->prepareAccessForGetUsers();
$backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
\OC_User::useBackend($backend);
@@ -488,7 +488,7 @@ class User_LDAPTest extends TestCase {
$this->assertEquals(0, count($result));
}
- public function testUserExists() {
+ public function testUserExists(): void {
$backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$this->prepareMockForUserExists();
@@ -510,7 +510,7 @@ class User_LDAPTest extends TestCase {
$this->assertTrue($result);
}
- public function testUserExistsForDeleted() {
+ public function testUserExistsForDeleted(): void {
$backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$this->prepareMockForUserExists();
@@ -535,7 +535,7 @@ class User_LDAPTest extends TestCase {
$this->assertTrue($backend->userExists('formerUser'));
}
- public function testUserExistsForNeverExisting() {
+ public function testUserExistsForNeverExisting(): void {
$backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$this->prepareMockForUserExists();
@@ -554,7 +554,7 @@ class User_LDAPTest extends TestCase {
$this->assertFalse($result);
}
- public function testUserExistsPublicAPI() {
+ public function testUserExistsPublicAPI(): void {
$backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$this->prepareMockForUserExists();
\OC_User::useBackend($backend);
@@ -587,7 +587,7 @@ class User_LDAPTest extends TestCase {
$this->assertTrue($result);
}
- public function testDeleteUserExisting() {
+ public function testDeleteUserExisting(): void {
$backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
//we do not support deleting existing users at all
@@ -595,7 +595,7 @@ class User_LDAPTest extends TestCase {
$this->assertFalse($result);
}
- public function testGetHomeAbsolutePath() {
+ public function testGetHomeAbsolutePath(): void {
$backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$this->prepareMockForUserExists();
@@ -649,7 +649,7 @@ class User_LDAPTest extends TestCase {
$this->assertEquals('/tmp/rolandshome/', $result);
}
- public function testGetHomeRelative() {
+ public function testGetHomeRelative(): void {
$backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$this->prepareMockForUserExists();
@@ -705,7 +705,7 @@ class User_LDAPTest extends TestCase {
}
- public function testGetHomeNoPath() {
+ public function testGetHomeNoPath(): void {
$this->expectException(\Exception::class);
$backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
@@ -750,7 +750,7 @@ class User_LDAPTest extends TestCase {
$this->assertFalse($result);
}
- public function testGetHomeDeletedUser() {
+ public function testGetHomeDeletedUser(): void {
$uid = 'newyorker';
$backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
@@ -793,7 +793,7 @@ class User_LDAPTest extends TestCase {
$this->assertFalse($result);
}
- public function testGetHomeWithPlugin() {
+ public function testGetHomeWithPlugin(): void {
$this->pluginManager->expects($this->once())
->method('implementsActions')
->with(Backend::GET_HOME)
@@ -844,7 +844,7 @@ class User_LDAPTest extends TestCase {
->willReturn([]);
}
- public function testGetDisplayName() {
+ public function testGetDisplayName(): void {
$this->prepareAccessForGetDisplayName();
$backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$this->prepareMockForUserExists();
@@ -915,7 +915,7 @@ class User_LDAPTest extends TestCase {
$this->assertEquals(null, $result);
}
- public function testGetDisplayNamePublicAPI() {
+ public function testGetDisplayNamePublicAPI(): void {
$this->access->expects($this->any())
->method('username2dn')
->willReturnCallback(function ($uid) {
@@ -1008,7 +1008,7 @@ class User_LDAPTest extends TestCase {
$this->assertEquals('newyorker', $result);
}
- public function testGetDisplayNameWithPlugin() {
+ public function testGetDisplayNameWithPlugin(): void {
$this->pluginManager->expects($this->once())
->method('implementsActions')
->with(Backend::GET_DISPLAYNAME)
@@ -1024,7 +1024,7 @@ class User_LDAPTest extends TestCase {
//no test for getDisplayNames, because it just invokes getUsers and
//getDisplayName
- public function testCountUsers() {
+ public function testCountUsers(): void {
$this->access->expects($this->once())
->method('countUsers')
->willReturn(5);
@@ -1035,7 +1035,7 @@ class User_LDAPTest extends TestCase {
$this->assertEquals(5, $result);
}
- public function testCountUsersFailing() {
+ public function testCountUsersFailing(): void {
$this->access->expects($this->once())
->method('countUsers')
->willReturn(false);
@@ -1046,7 +1046,7 @@ class User_LDAPTest extends TestCase {
$this->assertFalse($result);
}
- public function testCountUsersWithPlugin() {
+ public function testCountUsersWithPlugin(): void {
$this->pluginManager->expects($this->once())
->method('implementsActions')
->with(Backend::COUNT_USERS)
@@ -1058,7 +1058,7 @@ class User_LDAPTest extends TestCase {
$this->assertEquals($this->backend->countUsers(), 42);
}
- public function testLoginName2UserNameSuccess() {
+ public function testLoginName2UserNameSuccess(): void {
$loginName = 'Alice';
$username = 'alice';
$dn = 'uid=alice,dc=what,dc=ever';
@@ -1107,7 +1107,7 @@ class User_LDAPTest extends TestCase {
$backend->loginName2UserName($loginName);
}
- public function testLoginName2UserNameNoUsersOnLDAP() {
+ public function testLoginName2UserNameNoUsersOnLDAP(): void {
$loginName = 'Loki';
$this->access->expects($this->once())
@@ -1139,7 +1139,7 @@ class User_LDAPTest extends TestCase {
$backend->loginName2UserName($loginName);
}
- public function testLoginName2UserNameOfflineUser() {
+ public function testLoginName2UserNameOfflineUser(): void {
$loginName = 'Alice';
$dn = 'uid=alice,dc=what,dc=ever';
@@ -1237,7 +1237,7 @@ class User_LDAPTest extends TestCase {
}
- public function testSetPasswordInvalid() {
+ public function testSetPasswordInvalid(): void {
$this->expectException(\OCP\HintException::class);
$this->expectExceptionMessage('Password fails quality checking policy');
@@ -1251,7 +1251,7 @@ class User_LDAPTest extends TestCase {
$this->assertTrue(\OC_User::setPassword('roland', 'dt'));
}
- public function testSetPasswordValid() {
+ public function testSetPasswordValid(): void {
$this->prepareAccessForSetPassword($this->access);
$this->userManager->expects($this->any())
@@ -1268,7 +1268,7 @@ class User_LDAPTest extends TestCase {
$this->assertTrue(\OC_User::setPassword('roland', 'dt12234$'));
}
- public function testSetPasswordValidDisabled() {
+ public function testSetPasswordValidDisabled(): void {
$this->userManager->expects($this->any())
->method('get')
->willReturn($this->createMock(User::class));
@@ -1281,7 +1281,7 @@ class User_LDAPTest extends TestCase {
}
- public function testSetPasswordWithInvalidUser() {
+ public function testSetPasswordWithInvalidUser(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('LDAP setPassword: Could not get user object for uid NotExistingUser. Maybe the LDAP entry has no set display name attribute?');
@@ -1294,7 +1294,7 @@ class User_LDAPTest extends TestCase {
$this->backend->setPassword('NotExistingUser', 'Password');
}
- public function testSetPasswordWithUsernameFalse() {
+ public function testSetPasswordWithUsernameFalse(): void {
$user = $this->createMock(User::class);
$user
->expects($this->once())
@@ -1310,7 +1310,7 @@ class User_LDAPTest extends TestCase {
$this->assertFalse($this->backend->setPassword('NotExistingUser', 'Password'));
}
- public function testSetPasswordWithPlugin() {
+ public function testSetPasswordWithPlugin(): void {
$this->pluginManager->expects($this->once())
->method('implementsActions')
->with(Backend::SET_PASSWORD)
@@ -1333,7 +1333,7 @@ class User_LDAPTest extends TestCase {
}
/** @dataProvider avatarDataProvider */
- public function testCanChangeAvatar($imageData, $expected) {
+ public function testCanChangeAvatar($imageData, $expected): void {
$isValidImage = str_starts_with((string)$imageData, 'valid');
$user = $this->createMock(User::class);
@@ -1352,7 +1352,7 @@ class User_LDAPTest extends TestCase {
$this->assertSame($expected, $this->backend->canChangeAvatar('uid'));
}
- public function testCanChangeAvatarWithPlugin() {
+ public function testCanChangeAvatarWithPlugin(): void {
$this->pluginManager->expects($this->once())
->method('implementsActions')
->with(Backend::PROVIDE_AVATAR)
@@ -1365,7 +1365,7 @@ class User_LDAPTest extends TestCase {
$this->assertEquals($this->backend->canChangeAvatar('uid'), 'result');
}
- public function testSetDisplayNameWithPlugin() {
+ public function testSetDisplayNameWithPlugin(): void {
$newDisplayName = 'J. Baker';
$this->pluginManager->expects($this->once())
->method('implementsActions')
@@ -1382,7 +1382,7 @@ class User_LDAPTest extends TestCase {
}
- public function testSetDisplayNameErrorWithPlugin() {
+ public function testSetDisplayNameErrorWithPlugin(): void {
$this->expectException(\OCP\HintException::class);
$newDisplayName = 'J. Baker';
@@ -1400,7 +1400,7 @@ class User_LDAPTest extends TestCase {
$this->backend->setDisplayName('uid', $newDisplayName);
}
- public function testSetDisplayNameFailing() {
+ public function testSetDisplayNameFailing(): void {
$this->pluginManager->expects($this->once())
->method('implementsActions')
->with(Backend::SET_DISPLAYNAME)
@@ -1411,7 +1411,7 @@ class User_LDAPTest extends TestCase {
$this->assertFalse($this->backend->setDisplayName('uid', 'displayName'));
}
- public function testCreateUserWithPlugin() {
+ public function testCreateUserWithPlugin(): void {
$uid = 'alien6372';
$uuid = '123-2345-36756-123-2345234-4431';
$pwd = 'passwørd';
@@ -1438,7 +1438,7 @@ class User_LDAPTest extends TestCase {
$this->assertEquals($this->backend->createUser($uid, $pwd), true);
}
- public function testCreateUserFailing() {
+ public function testCreateUserFailing(): void {
$this->pluginManager->expects($this->once())
->method('implementsActions')
->with(Backend::CREATE_USER)
@@ -1460,7 +1460,7 @@ class User_LDAPTest extends TestCase {
/**
* @dataProvider actionProvider
*/
- public function testImplementsAction($configurable, $value, $actionCode, $expected) {
+ public function testImplementsAction($configurable, $value, $actionCode, $expected): void {
$this->pluginManager->expects($this->once())
->method('getImplementedActions')
->willReturn(0);
diff --git a/apps/user_ldap/tests/User_ProxyTest.php b/apps/user_ldap/tests/User_ProxyTest.php
index 5af7fef3f00..4544276a714 100644
--- a/apps/user_ldap/tests/User_ProxyTest.php
+++ b/apps/user_ldap/tests/User_ProxyTest.php
@@ -58,7 +58,7 @@ class User_ProxyTest extends TestCase {
->getMock();
}
- public function testSetPassword() {
+ public function testSetPassword(): void {
$this->proxy
->expects($this->once())
->method('handleRequest')
@@ -68,7 +68,7 @@ class User_ProxyTest extends TestCase {
$this->assertTrue($this->proxy->setPassword('MyUid', 'MyPassword'));
}
- public function testSetDisplayName() {
+ public function testSetDisplayName(): void {
$this->proxy
->expects($this->once())
->method('handleRequest')
@@ -78,7 +78,7 @@ class User_ProxyTest extends TestCase {
$this->assertTrue($this->proxy->setDisplayName('MyUid', 'MyPassword'));
}
- public function testCreateUser() {
+ public function testCreateUser(): void {
$this->proxy
->expects($this->once())
->method('handleRequest')
diff --git a/apps/user_ldap/tests/WizardTest.php b/apps/user_ldap/tests/WizardTest.php
index cc5867a5ca0..9595af15a99 100644
--- a/apps/user_ldap/tests/WizardTest.php
+++ b/apps/user_ldap/tests/WizardTest.php
@@ -75,7 +75,7 @@ class WizardTest extends TestCase {
->willReturn(true);
}
- public function testCumulativeSearchOnAttributeLimited() {
+ public function testCumulativeSearchOnAttributeLimited(): void {
[$wizard, $configuration, $ldap] = $this->getWizardAndMocks();
$configuration->expects($this->any())
@@ -135,7 +135,7 @@ class WizardTest extends TestCase {
unset($uidnumber);
}
- public function testCumulativeSearchOnAttributeUnlimited() {
+ public function testCumulativeSearchOnAttributeUnlimited(): void {
[$wizard, $configuration, $ldap] = $this->getWizardAndMocks();
$configuration->expects($this->any())
@@ -211,7 +211,7 @@ class WizardTest extends TestCase {
unset($uidnumber);
}
- public function testDetectEmailAttributeAlreadySet() {
+ public function testDetectEmailAttributeAlreadySet(): void {
[$wizard, $configuration, $ldap, $access]
= $this->getWizardAndMocks();
@@ -233,7 +233,7 @@ class WizardTest extends TestCase {
$wizard->detectEmailAttribute();
}
- public function testDetectEmailAttributeOverrideSet() {
+ public function testDetectEmailAttributeOverrideSet(): void {
[$wizard, $configuration, $ldap, $access]
= $this->getWizardAndMocks();
@@ -272,7 +272,7 @@ class WizardTest extends TestCase {
$result['changes']['ldap_email_attr']);
}
- public function testDetectEmailAttributeFind() {
+ public function testDetectEmailAttributeFind(): void {
[$wizard, $configuration, $ldap, $access]
= $this->getWizardAndMocks();
@@ -311,7 +311,7 @@ class WizardTest extends TestCase {
$result['changes']['ldap_email_attr']);
}
- public function testDetectEmailAttributeFindNothing() {
+ public function testDetectEmailAttributeFindNothing(): void {
[$wizard, $configuration, $ldap, $access]
= $this->getWizardAndMocks();
@@ -349,7 +349,7 @@ class WizardTest extends TestCase {
$this->assertSame(false, $result->hasChanges());
}
- public function testCumulativeSearchOnAttributeSkipReadDN() {
+ public function testCumulativeSearchOnAttributeSkipReadDN(): void {
// tests that there is no infinite loop, when skipping already processed
// DNs (they can be returned multiple times for multiple filters )
[$wizard, $configuration, $ldap] = $this->getWizardAndMocks();
diff --git a/apps/user_status/tests/Unit/BackgroundJob/ClearOldStatusesBackgroundJobTest.php b/apps/user_status/tests/Unit/BackgroundJob/ClearOldStatusesBackgroundJobTest.php
index d5c744b614e..90c85bcdaac 100644
--- a/apps/user_status/tests/Unit/BackgroundJob/ClearOldStatusesBackgroundJobTest.php
+++ b/apps/user_status/tests/Unit/BackgroundJob/ClearOldStatusesBackgroundJobTest.php
@@ -33,7 +33,7 @@ class ClearOldStatusesBackgroundJobTest extends TestCase {
$this->job = new ClearOldStatusesBackgroundJob($this->time, $this->mapper);
}
- public function testRun() {
+ public function testRun(): void {
$this->mapper->expects($this->once())
->method('clearOlderThanClearAt')
->with(1337);
diff --git a/apps/user_status/tests/Unit/Connector/UserStatusTest.php b/apps/user_status/tests/Unit/Connector/UserStatusTest.php
index 8cc730b9836..fee9b4e4b89 100644
--- a/apps/user_status/tests/Unit/Connector/UserStatusTest.php
+++ b/apps/user_status/tests/Unit/Connector/UserStatusTest.php
@@ -13,7 +13,7 @@ use OCA\UserStatus\Db;
use Test\TestCase;
class UserStatusTest extends TestCase {
- public function testUserStatus() {
+ public function testUserStatus(): void {
$status = new Db\UserStatus();
$status->setUserId('user2');
$status->setStatus('away');
@@ -34,7 +34,7 @@ class UserStatusTest extends TestCase {
$this->assertEquals('60000', $dateTime->format('U'));
}
- public function testUserStatusInvisible() {
+ public function testUserStatusInvisible(): void {
$status = new Db\UserStatus();
$status->setUserId('user2');
$status->setStatus('invisible');
diff --git a/apps/user_status/tests/Unit/Controller/PredefinedStatusControllerTest.php b/apps/user_status/tests/Unit/Controller/PredefinedStatusControllerTest.php
index 67670f56e5c..5709cdc89cf 100644
--- a/apps/user_status/tests/Unit/Controller/PredefinedStatusControllerTest.php
+++ b/apps/user_status/tests/Unit/Controller/PredefinedStatusControllerTest.php
@@ -31,7 +31,7 @@ class PredefinedStatusControllerTest extends TestCase {
$this->service);
}
- public function testFindAll() {
+ public function testFindAll(): void {
$this->service->expects($this->once())
->method('getDefaultStatuses')
->with()
diff --git a/apps/weather_status/lib/Service/WeatherStatusService.php b/apps/weather_status/lib/Service/WeatherStatusService.php
index da0ee855e85..6aee18c0618 100644
--- a/apps/weather_status/lib/Service/WeatherStatusService.php
+++ b/apps/weather_status/lib/Service/WeatherStatusService.php
@@ -121,7 +121,7 @@ class WeatherStatusService {
$this->config->setUserValue($this->userId, Application::APP_ID, 'lon', strval($lon));
// resolve and store formatted address
$address = $this->resolveLocation($lat, $lon);
- $address = $address ? $address : $this->l10n->t('Unknown address');
+ $address = $address ?: $this->l10n->t('Unknown address');
$this->config->setUserValue($this->userId, Application::APP_ID, 'address', $address);
// get and store altitude
$altitude = $this->getAltitude($lat, $lon);
diff --git a/apps/webhook_listeners/tests/Db/WebhookListenerMapperTest.php b/apps/webhook_listeners/tests/Db/WebhookListenerMapperTest.php
index bf39d4779ea..aefed2961ea 100644
--- a/apps/webhook_listeners/tests/Db/WebhookListenerMapperTest.php
+++ b/apps/webhook_listeners/tests/Db/WebhookListenerMapperTest.php
@@ -48,7 +48,7 @@ class WebhookListenerMapperTest extends TestCase {
$query->delete(WebhookListenerMapper::TABLE_NAME)->executeStatement();
}
- public function testInsertListenerWithNotSupportedEvent() {
+ public function testInsertListenerWithNotSupportedEvent(): void {
$this->expectException(\UnexpectedValueException::class);
$listener1 = $this->mapper->addWebhookListener(
null,
@@ -64,7 +64,7 @@ class WebhookListenerMapperTest extends TestCase {
);
}
- public function testInsertListenerAndGetIt() {
+ public function testInsertListenerAndGetIt(): void {
$listener1 = $this->mapper->addWebhookListener(
null,
'bob',
@@ -84,7 +84,7 @@ class WebhookListenerMapperTest extends TestCase {
$this->assertEquals($listener1, $listener2);
}
- public function testInsertListenerAndGetItByUri() {
+ public function testInsertListenerAndGetItByUri(): void {
$uri = 'https://webhook.example.com/endpoint';
$listener1 = $this->mapper->addWebhookListener(
null,
@@ -105,7 +105,7 @@ class WebhookListenerMapperTest extends TestCase {
$this->assertContains($listener1->getId(), array_map(fn ($listener) => $listener->getId(), $listeners));
}
- public function testInsertListenerAndGetItWithAuthData() {
+ public function testInsertListenerAndGetItWithAuthData(): void {
$listener1 = $this->mapper->addWebhookListener(
null,
'bob',
@@ -125,7 +125,7 @@ class WebhookListenerMapperTest extends TestCase {
$this->assertEquals($listener1, $listener2);
}
- public function testInsertListenerAndGetItByEventAndUser() {
+ public function testInsertListenerAndGetItByEventAndUser(): void {
$listener1 = $this->mapper->addWebhookListener(
null,
'bob',
diff --git a/apps/webhook_listeners/tests/Service/PHPMongoQueryTest.php b/apps/webhook_listeners/tests/Service/PHPMongoQueryTest.php
index 071330a79e3..b1094731733 100644
--- a/apps/webhook_listeners/tests/Service/PHPMongoQueryTest.php
+++ b/apps/webhook_listeners/tests/Service/PHPMongoQueryTest.php
@@ -41,7 +41,7 @@ class PHPMongoQueryTest extends TestCase {
/**
* @dataProvider dataExecuteQuery
*/
- public function testExecuteQuery(array $query, array $document, bool $matches) {
+ public function testExecuteQuery(array $query, array $document, bool $matches): void {
$this->assertEquals($matches, PHPMongoQuery::executeQuery($query, $document));
}
}
diff --git a/apps/workflowengine/tests/Check/AbstractStringCheckTest.php b/apps/workflowengine/tests/Check/AbstractStringCheckTest.php
index e924e0d3d1b..e96a3b4cc71 100644
--- a/apps/workflowengine/tests/Check/AbstractStringCheckTest.php
+++ b/apps/workflowengine/tests/Check/AbstractStringCheckTest.php
@@ -53,7 +53,7 @@ class AbstractStringCheckTest extends \Test\TestCase {
* @param string $actualValue
* @param bool $expected
*/
- public function testExecuteStringCheck($operation, $checkValue, $actualValue, $expected) {
+ public function testExecuteStringCheck($operation, $checkValue, $actualValue, $expected): void {
$check = $this->getCheckMock();
/** @var \OCA\WorkflowEngine\Check\AbstractStringCheck $check */
@@ -74,7 +74,7 @@ class AbstractStringCheckTest extends \Test\TestCase {
* @param string $operator
* @param string $value
*/
- public function testValidateCheck($operator, $value) {
+ public function testValidateCheck($operator, $value): void {
$check = $this->getCheckMock();
/** @var \OCA\WorkflowEngine\Check\AbstractStringCheck $check */
@@ -99,7 +99,7 @@ class AbstractStringCheckTest extends \Test\TestCase {
* @param $exceptionCode
* @param $exceptionMessage
*/
- public function testValidateCheckInvalid($operator, $value, $exceptionCode, $exceptionMessage) {
+ public function testValidateCheckInvalid($operator, $value, $exceptionCode, $exceptionMessage): void {
$check = $this->getCheckMock();
try {
@@ -125,7 +125,7 @@ class AbstractStringCheckTest extends \Test\TestCase {
* @param array[] $matches
* @param bool $expected
*/
- public function testMatch($pattern, $subject, $matches, $expected) {
+ public function testMatch($pattern, $subject, $matches, $expected): void {
$check = $this->getCheckMock();
$this->invokePrivate($check, 'matches', [$matches]);
diff --git a/apps/workflowengine/tests/Check/FileMimeTypeTest.php b/apps/workflowengine/tests/Check/FileMimeTypeTest.php
index 0420ea0120c..35cd4728ca5 100644
--- a/apps/workflowengine/tests/Check/FileMimeTypeTest.php
+++ b/apps/workflowengine/tests/Check/FileMimeTypeTest.php
@@ -71,7 +71,7 @@ class FileMimeTypeTest extends TestCase {
});
}
- public function testUseCachedMimetype() {
+ public function testUseCachedMimetype(): void {
$storage = new Temporary([]);
$storage->mkdir('foo');
$storage->file_put_contents('foo/bar.txt', 'asd');
@@ -84,7 +84,7 @@ class FileMimeTypeTest extends TestCase {
$this->assertTrue($check->executeCheck('is', 'text/plain'));
}
- public function testNonCachedNotExists() {
+ public function testNonCachedNotExists(): void {
$storage = new Temporary([]);
$check = new FileMimeType($this->l10n, $this->request, $this->mimeDetector);
@@ -93,7 +93,7 @@ class FileMimeTypeTest extends TestCase {
$this->assertTrue($check->executeCheck('is', 'text/plain-path-detected'));
}
- public function testNonCachedLocal() {
+ public function testNonCachedLocal(): void {
$storage = new Temporary([]);
$storage->mkdir('foo');
$storage->file_put_contents('foo/bar.txt', 'text-content');
@@ -104,7 +104,7 @@ class FileMimeTypeTest extends TestCase {
$this->assertTrue($check->executeCheck('is', 'text/plain-content-detected'));
}
- public function testNonCachedNotLocal() {
+ public function testNonCachedNotLocal(): void {
$storage = new TemporaryNoLocal([]);
$storage->mkdir('foo');
$storage->file_put_contents('foo/bar.txt', 'text-content');
@@ -115,7 +115,7 @@ class FileMimeTypeTest extends TestCase {
$this->assertTrue($check->executeCheck('is', 'text/plain-content-detected'));
}
- public function testFallback() {
+ public function testFallback(): void {
$storage = new Temporary([]);
$check = new FileMimeType($this->l10n, $this->request, $this->mimeDetector);
@@ -124,7 +124,7 @@ class FileMimeTypeTest extends TestCase {
$this->assertTrue($check->executeCheck('is', 'application/octet-stream'));
}
- public function testFromCacheCached() {
+ public function testFromCacheCached(): void {
$storage = new Temporary([]);
$storage->mkdir('foo');
$storage->file_put_contents('foo/bar.txt', 'text-content');
@@ -144,7 +144,7 @@ class FileMimeTypeTest extends TestCase {
$this->assertTrue($newCheck->executeCheck('is', 'text/plain-content-detected'));
}
- public function testExistsCached() {
+ public function testExistsCached(): void {
$storage = new TemporaryNoLocal([]);
$storage->mkdir('foo');
$storage->file_put_contents('foo/bar.txt', 'text-content');
@@ -161,7 +161,7 @@ class FileMimeTypeTest extends TestCase {
$this->assertTrue($newCheck->executeCheck('is', 'text/plain-path-detected'));
}
- public function testNonExistsNotCached() {
+ public function testNonExistsNotCached(): void {
$storage = new TemporaryNoLocal([]);
$check = new FileMimeType($this->l10n, $this->request, $this->mimeDetector);
diff --git a/apps/workflowengine/tests/Check/RequestRemoteAddressTest.php b/apps/workflowengine/tests/Check/RequestRemoteAddressTest.php
index 7c46a33a477..438a59a8a48 100644
--- a/apps/workflowengine/tests/Check/RequestRemoteAddressTest.php
+++ b/apps/workflowengine/tests/Check/RequestRemoteAddressTest.php
@@ -52,7 +52,7 @@ class RequestRemoteAddressTest extends \Test\TestCase {
* @param string $ip
* @param bool $expected
*/
- public function testExecuteCheckMatchesIPv4($value, $ip, $expected) {
+ public function testExecuteCheckMatchesIPv4($value, $ip, $expected): void {
$check = new \OCA\WorkflowEngine\Check\RequestRemoteAddress($this->getL10NMock(), $this->request);
$this->request->expects($this->once())
@@ -68,7 +68,7 @@ class RequestRemoteAddressTest extends \Test\TestCase {
* @param string $ip
* @param bool $expected
*/
- public function testExecuteCheckNotMatchesIPv4($value, $ip, $expected) {
+ public function testExecuteCheckNotMatchesIPv4($value, $ip, $expected): void {
$check = new \OCA\WorkflowEngine\Check\RequestRemoteAddress($this->getL10NMock(), $this->request);
$this->request->expects($this->once())
@@ -96,7 +96,7 @@ class RequestRemoteAddressTest extends \Test\TestCase {
* @param string $ip
* @param bool $expected
*/
- public function testExecuteCheckMatchesIPv6($value, $ip, $expected) {
+ public function testExecuteCheckMatchesIPv6($value, $ip, $expected): void {
$check = new \OCA\WorkflowEngine\Check\RequestRemoteAddress($this->getL10NMock(), $this->request);
$this->request->expects($this->once())
@@ -112,7 +112,7 @@ class RequestRemoteAddressTest extends \Test\TestCase {
* @param string $ip
* @param bool $expected
*/
- public function testExecuteCheckNotMatchesIPv6($value, $ip, $expected) {
+ public function testExecuteCheckNotMatchesIPv6($value, $ip, $expected): void {
$check = new \OCA\WorkflowEngine\Check\RequestRemoteAddress($this->getL10NMock(), $this->request);
$this->request->expects($this->once())
diff --git a/apps/workflowengine/tests/Check/RequestTimeTest.php b/apps/workflowengine/tests/Check/RequestTimeTest.php
index 90cdc279bbf..410378d5839 100644
--- a/apps/workflowengine/tests/Check/RequestTimeTest.php
+++ b/apps/workflowengine/tests/Check/RequestTimeTest.php
@@ -71,7 +71,7 @@ class RequestTimeTest extends \Test\TestCase {
* @param int $timestamp
* @param bool $expected
*/
- public function testExecuteCheckIn($value, $timestamp, $expected) {
+ public function testExecuteCheckIn($value, $timestamp, $expected): void {
$check = new \OCA\WorkflowEngine\Check\RequestTime($this->getL10NMock(), $this->timeFactory);
$this->timeFactory->expects($this->once())
@@ -87,7 +87,7 @@ class RequestTimeTest extends \Test\TestCase {
* @param int $timestamp
* @param bool $expected
*/
- public function testExecuteCheckNotIn($value, $timestamp, $expected) {
+ public function testExecuteCheckNotIn($value, $timestamp, $expected): void {
$check = new \OCA\WorkflowEngine\Check\RequestTime($this->getL10NMock(), $this->timeFactory);
$this->timeFactory->expects($this->once())
@@ -110,7 +110,7 @@ class RequestTimeTest extends \Test\TestCase {
* @param string $operator
* @param string $value
*/
- public function testValidateCheck($operator, $value) {
+ public function testValidateCheck($operator, $value): void {
$check = new \OCA\WorkflowEngine\Check\RequestTime($this->getL10NMock(), $this->timeFactory);
$check->validateCheck($operator, $value);
$this->addToAssertionCount(1);
@@ -135,7 +135,7 @@ class RequestTimeTest extends \Test\TestCase {
* @param int $exceptionCode
* @param string $exceptionMessage
*/
- public function testValidateCheckInvalid($operator, $value, $exceptionCode, $exceptionMessage) {
+ public function testValidateCheckInvalid($operator, $value, $exceptionCode, $exceptionMessage): void {
$check = new \OCA\WorkflowEngine\Check\RequestTime($this->getL10NMock(), $this->timeFactory);
try {
diff --git a/apps/workflowengine/tests/Check/RequestUserAgentTest.php b/apps/workflowengine/tests/Check/RequestUserAgentTest.php
index f41f95c15ff..f74cf669cc7 100644
--- a/apps/workflowengine/tests/Check/RequestUserAgentTest.php
+++ b/apps/workflowengine/tests/Check/RequestUserAgentTest.php
@@ -90,7 +90,7 @@ class RequestUserAgentTest extends TestCase {
* @param string $actualValue
* @param bool $expected
*/
- public function testExecuteCheck($operation, $checkValue, $actualValue, $expected) {
+ public function testExecuteCheck($operation, $checkValue, $actualValue, $expected): void {
$this->request->expects($this->once())
->method('getHeader')
->willReturn($actualValue);
diff --git a/apps/workflowengine/tests/ManagerTest.php b/apps/workflowengine/tests/ManagerTest.php
index 4a547f5c8bf..334666af039 100644
--- a/apps/workflowengine/tests/ManagerTest.php
+++ b/apps/workflowengine/tests/ManagerTest.php
@@ -123,7 +123,7 @@ class ManagerTest extends TestCase {
}
}
- public function testChecks() {
+ public function testChecks(): void {
$check1 = $this->invokePrivate($this->manager, 'addCheck', ['Test', 'equal', 1]);
$check2 = $this->invokePrivate($this->manager, 'addCheck', ['Test', '!equal', 2]);
@@ -144,7 +144,7 @@ class ManagerTest extends TestCase {
$this->assertArrayHasKey($check2, $data);
}
- public function testScope() {
+ public function testScope(): void {
$adminScope = $this->buildScope();
$userScope = $this->buildScope('jackie');
$entity = File::class;
@@ -178,7 +178,7 @@ class ManagerTest extends TestCase {
$this->assertTrue($this->invokePrivate($this->manager, 'canModify', [$opId3, $userScope]));
}
- public function testGetAllOperations() {
+ public function testGetAllOperations(): void {
$adminScope = $this->buildScope();
$userScope = $this->buildScope('jackie');
$entity = File::class;
@@ -249,7 +249,7 @@ class ManagerTest extends TestCase {
$this->assertSame(2, count($userOps['OCA\WFE\TestUserOp']));
}
- public function testGetOperations() {
+ public function testGetOperations(): void {
$adminScope = $this->buildScope();
$userScope = $this->buildScope('jackie');
$entity = File::class;
@@ -319,7 +319,7 @@ class ManagerTest extends TestCase {
});
}
- public function testGetAllConfiguredEvents() {
+ public function testGetAllConfiguredEvents(): void {
$adminScope = $this->buildScope();
$userScope = $this->buildScope('jackie');
$entity = File::class;
@@ -353,7 +353,7 @@ class ManagerTest extends TestCase {
$this->assertEquals($allOperationsCached, $allOperations);
}
- public function testUpdateOperation() {
+ public function testUpdateOperation(): void {
$adminScope = $this->buildScope();
$userScope = $this->buildScope('jackie');
$entity = File::class;
@@ -434,7 +434,7 @@ class ManagerTest extends TestCase {
}
}
- public function testDeleteOperation() {
+ public function testDeleteOperation(): void {
$adminScope = $this->buildScope();
$userScope = $this->buildScope('jackie');
$entity = File::class;
@@ -484,7 +484,7 @@ class ManagerTest extends TestCase {
}
}
- public function testGetEntitiesListBuildInOnly() {
+ public function testGetEntitiesListBuildInOnly(): void {
$fileEntityMock = $this->createMock(File::class);
$this->container->expects($this->once())
@@ -498,7 +498,7 @@ class ManagerTest extends TestCase {
$this->assertInstanceOf(IEntity::class, $entities[0]);
}
- public function testGetEntitiesList() {
+ public function testGetEntitiesList(): void {
$fileEntityMock = $this->createMock(File::class);
$this->container->expects($this->once())
@@ -532,7 +532,7 @@ class ManagerTest extends TestCase {
$this->assertSame(1, $entityTypeCounts[1]);
}
- public function testValidateOperationOK() {
+ public function testValidateOperationOK(): void {
$check = [
'class' => ICheck::class,
'operator' => 'is',
@@ -592,7 +592,7 @@ class ManagerTest extends TestCase {
$this->manager->validateOperation(IOperation::class, 'test', [$check], 'operationData', $scopeMock, IEntity::class, ['MyEvent']);
}
- public function testValidateOperationCheckInputLengthError() {
+ public function testValidateOperationCheckInputLengthError(): void {
$check = [
'class' => ICheck::class,
'operator' => 'is',
@@ -656,7 +656,7 @@ class ManagerTest extends TestCase {
}
}
- public function testValidateOperationDataLengthError() {
+ public function testValidateOperationDataLengthError(): void {
$check = [
'class' => ICheck::class,
'operator' => 'is',
@@ -720,7 +720,7 @@ class ManagerTest extends TestCase {
}
}
- public function testValidateOperationScopeNotAvailable() {
+ public function testValidateOperationScopeNotAvailable(): void {
$check = [
'class' => ICheck::class,
'operator' => 'is',
diff --git a/build/psalm-baseline-ocp.xml b/build/psalm-baseline-ocp.xml
index e98e45b2bed..9f69654ff3d 100644
--- a/build/psalm-baseline-ocp.xml
+++ b/build/psalm-baseline-ocp.xml
@@ -18,14 +18,6 @@
<code><![CDATA[\OC]]></code>
</UndefinedClass>
</file>
- <file src="lib/public/AppFramework/Db/Entity.php">
- <InvalidNullableReturnType>
- <code><![CDATA[string]]></code>
- </InvalidNullableReturnType>
- <NullableReturnStatement>
- <code><![CDATA[$column]]></code>
- </NullableReturnStatement>
- </file>
<file src="lib/public/AppFramework/Http/RedirectToDefaultAppResponse.php">
<UndefinedClass>
<code><![CDATA[\OC]]></code>
diff --git a/build/psalm-baseline.xml b/build/psalm-baseline.xml
index d06ea259287..740240471ba 100644
--- a/build/psalm-baseline.xml
+++ b/build/psalm-baseline.xml
@@ -2157,9 +2157,6 @@
</InvalidReturnType>
</file>
<file src="lib/private/Files/Storage/Local.php">
- <ImplicitToStringCast>
- <code><![CDATA[$file]]></code>
- </ImplicitToStringCast>
<TypeDoesNotContainNull>
<code><![CDATA[$space === false || is_null($space)]]></code>
<code><![CDATA[is_null($space)]]></code>
@@ -2902,14 +2899,6 @@
<code><![CDATA[new RouteConfig($this->container, $router, $routes)]]></code>
</InternalMethod>
</file>
- <file src="lib/public/AppFramework/Db/Entity.php">
- <InvalidNullableReturnType>
- <code><![CDATA[string]]></code>
- </InvalidNullableReturnType>
- <NullableReturnStatement>
- <code><![CDATA[$column]]></code>
- </NullableReturnStatement>
- </file>
<file src="lib/public/AppFramework/Http/Response.php">
<LessSpecificReturnStatement>
<code><![CDATA[array_merge($mergeWith, $this->headers)]]></code>
diff --git a/core/l10n/es.js b/core/l10n/es.js
index 35dbb25f9d1..3926235431c 100644
--- a/core/l10n/es.js
+++ b/core/l10n/es.js
@@ -39,9 +39,11 @@ OC.L10N.register(
"Click the following button to reset your password. If you have not requested the password reset, then ignore this email." : "Haz clic en el siguiente botón para restaurar tu contraseña. Si no has solicitado que se te restaure la contraseña, ignora este correo.",
"Click the following link to reset your password. If you have not requested the password reset, then ignore this email." : "Haz clic en el siguiente enlace para restaurar tu contraseña. Si no has solicitado que se te restaure la contraseña, ignora este correo.",
"Reset your password" : "Resetear su contraseña",
+ "The given provider is not available" : "El proveedor indicado no está disponible",
"Task not found" : "Tarea no encontrada",
"Internal error" : "Error interno",
"Not found" : "No encontrado",
+ "Bad request" : "Solicitud errónea",
"Requested task type does not exist" : "El tipo de tarea solicitada no existe",
"Necessary language model provider is not available" : "El proveedor de modelo de lenguaje necesario no está disponible",
"No text to image provider is available" : "No hay proveedores de texto a imagen disponible",
@@ -102,12 +104,20 @@ OC.L10N.register(
"No" : "No",
"Yes" : "Sí",
"Federated user" : "Usuario federado",
+ "user@your-nextcloud.org" : "usuario@su-nextcloud.org",
"Create share" : "Crear un recurso compartido",
+ "The remote URL must include the user." : "La URL remota debe incluir el usuario.",
+ "Invalid remote URL." : "URL remota inválida.",
"Failed to add the public link to your Nextcloud" : "No se ha podido añadir el enlace público a tu Nextcloud",
+ "Direct link copied to clipboard" : "Enlace directo copiado al portapapeles",
+ "Please copy the link manually:" : "Por favor, copie el enlace manualmente:",
"Custom date range" : "Rango de fechas personalizado",
"Pick start date" : "Escoja una fecha de inicio",
"Pick end date" : "Escoja una fecha fin",
"Search in date range" : "Buscar en un rango de fechas",
+ "Search in current app" : "Buscar en la app actual",
+ "Clear search" : "Limpiar búsqueda",
+ "Search everywhere" : "Buscar en todas partes",
"Unified search" : "Búsqueda unificada",
"Search apps, files, tags, messages" : "Buscar en apps, archivos, etiquetas, mensajes",
"Places" : "Ubicaciones",
@@ -276,6 +286,7 @@ OC.L10N.register(
"The server was unable to complete your request." : "El servidor no ha podido completar tu petición.",
"If this happens again, please send the technical details below to the server administrator." : "Si sucede de nuevo, por favor, envía los detalles técnicos a continuación al administrador del servidor.",
"More details can be found in the server log." : "Pueden verse más detalles en el registro del servidor.",
+ "For more details see the documentation ↗." : "Para más detalles, vea la documentación ↗.",
"Technical details" : "Detalles técnicos",
"Remote Address: %s" : "Dirección remota: %s",
"Request ID: %s" : "ID de la solicitud: %s",
diff --git a/core/l10n/es.json b/core/l10n/es.json
index 8ec3af3c7dd..a3dd55d790f 100644
--- a/core/l10n/es.json
+++ b/core/l10n/es.json
@@ -37,9 +37,11 @@
"Click the following button to reset your password. If you have not requested the password reset, then ignore this email." : "Haz clic en el siguiente botón para restaurar tu contraseña. Si no has solicitado que se te restaure la contraseña, ignora este correo.",
"Click the following link to reset your password. If you have not requested the password reset, then ignore this email." : "Haz clic en el siguiente enlace para restaurar tu contraseña. Si no has solicitado que se te restaure la contraseña, ignora este correo.",
"Reset your password" : "Resetear su contraseña",
+ "The given provider is not available" : "El proveedor indicado no está disponible",
"Task not found" : "Tarea no encontrada",
"Internal error" : "Error interno",
"Not found" : "No encontrado",
+ "Bad request" : "Solicitud errónea",
"Requested task type does not exist" : "El tipo de tarea solicitada no existe",
"Necessary language model provider is not available" : "El proveedor de modelo de lenguaje necesario no está disponible",
"No text to image provider is available" : "No hay proveedores de texto a imagen disponible",
@@ -100,12 +102,20 @@
"No" : "No",
"Yes" : "Sí",
"Federated user" : "Usuario federado",
+ "user@your-nextcloud.org" : "usuario@su-nextcloud.org",
"Create share" : "Crear un recurso compartido",
+ "The remote URL must include the user." : "La URL remota debe incluir el usuario.",
+ "Invalid remote URL." : "URL remota inválida.",
"Failed to add the public link to your Nextcloud" : "No se ha podido añadir el enlace público a tu Nextcloud",
+ "Direct link copied to clipboard" : "Enlace directo copiado al portapapeles",
+ "Please copy the link manually:" : "Por favor, copie el enlace manualmente:",
"Custom date range" : "Rango de fechas personalizado",
"Pick start date" : "Escoja una fecha de inicio",
"Pick end date" : "Escoja una fecha fin",
"Search in date range" : "Buscar en un rango de fechas",
+ "Search in current app" : "Buscar en la app actual",
+ "Clear search" : "Limpiar búsqueda",
+ "Search everywhere" : "Buscar en todas partes",
"Unified search" : "Búsqueda unificada",
"Search apps, files, tags, messages" : "Buscar en apps, archivos, etiquetas, mensajes",
"Places" : "Ubicaciones",
@@ -274,6 +284,7 @@
"The server was unable to complete your request." : "El servidor no ha podido completar tu petición.",
"If this happens again, please send the technical details below to the server administrator." : "Si sucede de nuevo, por favor, envía los detalles técnicos a continuación al administrador del servidor.",
"More details can be found in the server log." : "Pueden verse más detalles en el registro del servidor.",
+ "For more details see the documentation ↗." : "Para más detalles, vea la documentación ↗.",
"Technical details" : "Detalles técnicos",
"Remote Address: %s" : "Dirección remota: %s",
"Request ID: %s" : "ID de la solicitud: %s",
diff --git a/core/l10n/pt_BR.js b/core/l10n/pt_BR.js
index 3d0a4229756..433a19476a1 100644
--- a/core/l10n/pt_BR.js
+++ b/core/l10n/pt_BR.js
@@ -104,8 +104,13 @@ OC.L10N.register(
"No" : "Não",
"Yes" : "Sim",
"Federated user" : "Usuário federado",
+ "user@your-nextcloud.org" : "user@your-nextcloud.org",
"Create share" : "Criar compartilhamento",
+ "The remote URL must include the user." : "A URL remota deve incluir o usuário.",
+ "Invalid remote URL." : "URL remota inválida.",
"Failed to add the public link to your Nextcloud" : "Ocorreu uma falha ao adicionar o link público ao seu Nextcloud",
+ "Direct link copied to clipboard" : "Link direto copiado para a área de transferência",
+ "Please copy the link manually:" : "Copie o link manualmente:",
"Custom date range" : "Data personalizada",
"Pick start date" : "Escolha uma data de início",
"Pick end date" : "Escolha uma data de fim",
diff --git a/core/l10n/pt_BR.json b/core/l10n/pt_BR.json
index 0089585b21a..3ad61b1cf38 100644
--- a/core/l10n/pt_BR.json
+++ b/core/l10n/pt_BR.json
@@ -102,8 +102,13 @@
"No" : "Não",
"Yes" : "Sim",
"Federated user" : "Usuário federado",
+ "user@your-nextcloud.org" : "user@your-nextcloud.org",
"Create share" : "Criar compartilhamento",
+ "The remote URL must include the user." : "A URL remota deve incluir o usuário.",
+ "Invalid remote URL." : "URL remota inválida.",
"Failed to add the public link to your Nextcloud" : "Ocorreu uma falha ao adicionar o link público ao seu Nextcloud",
+ "Direct link copied to clipboard" : "Link direto copiado para a área de transferência",
+ "Please copy the link manually:" : "Copie o link manualmente:",
"Custom date range" : "Data personalizada",
"Pick start date" : "Escolha uma data de início",
"Pick end date" : "Escolha uma data de fim",
diff --git a/core/l10n/uk.js b/core/l10n/uk.js
index 8d7c38dbb0d..129e3e6b97c 100644
--- a/core/l10n/uk.js
+++ b/core/l10n/uk.js
@@ -103,8 +103,14 @@ OC.L10N.register(
"_{count} notification_::_{count} notifications_" : ["{count} сповіщень","{count} сповіщень","{count} сповіщень","{count} сповіщень"],
"No" : "Ні",
"Yes" : "Так",
+ "Federated user" : "Обʼєднаний користувач",
+ "user@your-nextcloud.org" : "користувач@ваш-nextcloud.org",
"Create share" : "Створити спільний ресурс",
+ "The remote URL must include the user." : "Віддалена адреса повинна містити в собі імʼя користувача.",
+ "Invalid remote URL." : "Недійсна віддалена адреса.",
"Failed to add the public link to your Nextcloud" : "Не вдалося додати загальнодоступне посилання до вашого Nextcloud",
+ "Direct link copied to clipboard" : "Посилання прямого доступу скопійовано в буфер обміну",
+ "Please copy the link manually:" : "Будь ласка, скопіюйте посилання вручну:",
"Custom date range" : "Власний вибір проміжку",
"Pick start date" : "Виберіть початкову дату",
"Pick end date" : "Виберіть кінцеву дату",
diff --git a/core/l10n/uk.json b/core/l10n/uk.json
index ee26aca11d9..755a278c11d 100644
--- a/core/l10n/uk.json
+++ b/core/l10n/uk.json
@@ -101,8 +101,14 @@
"_{count} notification_::_{count} notifications_" : ["{count} сповіщень","{count} сповіщень","{count} сповіщень","{count} сповіщень"],
"No" : "Ні",
"Yes" : "Так",
+ "Federated user" : "Обʼєднаний користувач",
+ "user@your-nextcloud.org" : "користувач@ваш-nextcloud.org",
"Create share" : "Створити спільний ресурс",
+ "The remote URL must include the user." : "Віддалена адреса повинна містити в собі імʼя користувача.",
+ "Invalid remote URL." : "Недійсна віддалена адреса.",
"Failed to add the public link to your Nextcloud" : "Не вдалося додати загальнодоступне посилання до вашого Nextcloud",
+ "Direct link copied to clipboard" : "Посилання прямого доступу скопійовано в буфер обміну",
+ "Please copy the link manually:" : "Будь ласка, скопіюйте посилання вручну:",
"Custom date range" : "Власний вибір проміжку",
"Pick start date" : "Виберіть початкову дату",
"Pick end date" : "Виберіть кінцеву дату",
diff --git a/lib/l10n/es.js b/lib/l10n/es.js
index 0d5bae0bc1c..1e361819686 100644
--- a/lib/l10n/es.js
+++ b/lib/l10n/es.js
@@ -249,7 +249,7 @@ OC.L10N.register(
"Check the value of \"datadirectory\" in your configuration." : "Comprueba el valor de «datadirectory» en tu configuración.",
"Your data directory is invalid." : "Tu carpeta de datos es inválida.",
"Action \"%s\" not supported or implemented." : "La acción \"%s\" no está soportada o implementada.",
- "Authentication failed, wrong token or provider ID given" : "La autentificación ha fallado. Se ha dado un token o una ID de proveedor erróneos.",
+ "Authentication failed, wrong token or provider ID given" : "La autentificación ha fallado. Se ha proporcionado un token o una ID de proveedor erróneos.",
"Parameters missing in order to complete the request. Missing Parameters: \"%s\"" : "Faltan parámetros para completar la petición. Parámetros que faltan: \"%s\"",
"ID \"%1$s\" already used by cloud federation provider \"%2$s\"" : "La ID «%1$s» ya está siendo usada por el proveedor de federación en la nube «%2$s»",
"Cloud Federation Provider with ID: \"%s\" does not exist." : "El proveedor de nube federada con ID \"%s\" no existe.",
@@ -264,6 +264,7 @@ OC.L10N.register(
"Writes text in a given style based on the provided source material." : "Escribe el texto en un estilo dado basándose en el material fuente proporcionado.",
"Writing style" : "Estilo de escritura",
"Source material" : "Material fuente",
+ "The generated text with content from the source material in the given style" : "El texto generado con el contenido del material fuente en el estilo dado",
"Generate image" : "Generar imagen",
"Prompt" : "Prompt",
"Generates a possible headline for a text." : "Genera un posible titular para un texto.",
diff --git a/lib/l10n/es.json b/lib/l10n/es.json
index 93710380530..7922cd73598 100644
--- a/lib/l10n/es.json
+++ b/lib/l10n/es.json
@@ -247,7 +247,7 @@
"Check the value of \"datadirectory\" in your configuration." : "Comprueba el valor de «datadirectory» en tu configuración.",
"Your data directory is invalid." : "Tu carpeta de datos es inválida.",
"Action \"%s\" not supported or implemented." : "La acción \"%s\" no está soportada o implementada.",
- "Authentication failed, wrong token or provider ID given" : "La autentificación ha fallado. Se ha dado un token o una ID de proveedor erróneos.",
+ "Authentication failed, wrong token or provider ID given" : "La autentificación ha fallado. Se ha proporcionado un token o una ID de proveedor erróneos.",
"Parameters missing in order to complete the request. Missing Parameters: \"%s\"" : "Faltan parámetros para completar la petición. Parámetros que faltan: \"%s\"",
"ID \"%1$s\" already used by cloud federation provider \"%2$s\"" : "La ID «%1$s» ya está siendo usada por el proveedor de federación en la nube «%2$s»",
"Cloud Federation Provider with ID: \"%s\" does not exist." : "El proveedor de nube federada con ID \"%s\" no existe.",
@@ -262,6 +262,7 @@
"Writes text in a given style based on the provided source material." : "Escribe el texto en un estilo dado basándose en el material fuente proporcionado.",
"Writing style" : "Estilo de escritura",
"Source material" : "Material fuente",
+ "The generated text with content from the source material in the given style" : "El texto generado con el contenido del material fuente en el estilo dado",
"Generate image" : "Generar imagen",
"Prompt" : "Prompt",
"Generates a possible headline for a text." : "Genera un posible titular para un texto.",
diff --git a/lib/l10n/pt_BR.js b/lib/l10n/pt_BR.js
index 948dcf8000c..c750601e4c4 100644
--- a/lib/l10n/pt_BR.js
+++ b/lib/l10n/pt_BR.js
@@ -155,15 +155,48 @@ OC.L10N.register(
"%1$s shared »%2$s« with you and wants to add:" : "%1$s compartilhou »%2$s« com você e quer adicionar:",
"%1$s shared »%2$s« with you and wants to add" : "%1$s compartilhou »%2$s« com você e quer adicionar",
"»%s« added a note to a file shared with you" : "»%s« adicionou uma anotação num arquivo compartilhado com você",
+ "Passwords are enforced for link and mail shares" : "As senhas são aplicadas para compartilhamentos de links e e-mails",
+ "SharedWith is not a valid user" : "SharedWith não é um usuário válido",
+ "SharedWith is not a valid group" : "SharedWith não é um grupo válido",
+ "SharedWith should be empty" : "SharedWith pode estar vazio",
+ "SharedWith should not be empty" : "SharedWith não pode estar vazio",
+ "SharedWith is not a valid circle" : "SharedWith não é um círculo válido",
"Unknown share type" : "Tipo de compartilhamento desconhecido",
+ "SharedBy should be set" : "SharedBy deve estar definido",
+ "Cannot share with yourself" : "Não é possível compartilhar consigo mesmo",
+ "Path should be set" : "O caminho deve estar definido",
+ "Path should be either a file or a folder" : "O caminho deve ser um arquivo ou pasta",
+ "You cannot share your root folder" : "Você não pode compartilhar sua pasta raiz",
"You are not allowed to share %s" : "Você não tem permissão para compartilhar %s",
+ "A share requires permissions" : "Um compartilhamento requer permissões",
"Cannot increase permissions of %s" : "Não foi possível aumentar as permissões de %s",
+ "Shares need at least read permissions" : "Compartilhamentos precisam pelo menos permissões de leitura",
"Files cannot be shared with delete permissions" : "Arquivos não podem ser compartilhados com permissões de exclusão",
"Files cannot be shared with create permissions" : "Arquivos não podem ser compartilhados com permissões de criação",
"Expiration date is in the past" : "Data de expiração está no passado",
+ "Expiration date is enforced" : "A data de expiração é aplicada",
"_Cannot set expiration date more than %n day in the future_::_Cannot set expiration date more than %n days in the future_" : ["Não foi possível definir a data de expiração superior que %n dias no futuro","Não foi possível definir a data de expiração superior que %n dias no futuro","Não foi possível definir a data de expiração superior que %n dias no futuro"],
"Sharing is only allowed with group members" : "O compartilhamento só é permitido com membros do grupo ",
"Sharing %s failed, because this item is already shared with the account %s" : "Falha no compartilhamento %s porque este item já está compartilhado com a conta %s",
+ "Group sharing is now allowed" : "O compartilhamento em grupo é permitido agora",
+ "Sharing is only allowed within your own groups" : "O compartilhamento só é permitido dentro de seus próprios grupos",
+ "Path is already shared with this group" : "O caminho já está compartilhado com este grupo",
+ "Link sharing is not allowed" : "O compartilhamento de link não é permitido",
+ "Public upload is not allowed" : "O upload público não é permitido",
+ "Path contains files shared with you" : "O caminho contém arquivos compartilhados com você",
+ "Sharing is disabled" : "O compartilhamento está desativado",
+ "Sharing is disabled for you" : "O compartilhamento está desativado para você",
+ "Cannot share with the share owner" : "Não é possível compartilhar com o proprietário do compartilhamento",
+ "Share does not have a full ID" : "O compartilhamento não tem um ID completo",
+ "Cannot change share type" : "Não é possível alterar o tipo de compartilhamento",
+ "Can only update recipient on user shares" : "Só é possível atualizar o destinatário em compartilhamentos de usuários",
+ "Cannot enable sending the password by Talk with an empty password" : "Não é possível ativar o envio da senha pelo Talk com uma senha vazia",
+ "Cannot enable sending the password by Talk without setting a new password" : "Não é possível ativar o envio da senha pelo Talk sem definir uma nova senha",
+ "Cannot disable sending the password by Talk without setting a new password" : "Não é possível desativar o envio da senha pelo Talk sem definir uma nova senha",
+ "Share provider does not support accepting" : "O provedor de compartilhamento não oferece suporte à aceitação",
+ "Cannot change target of link share" : "Não é possível alterar o destino do compartilhamento do link",
+ "Invalid recipient" : "Destinatário inválido",
+ "Group \"%s\" does not exist" : "Grupo \"%s\" não existe",
"The requested share does not exist anymore" : "O compartilhamento solicitado não existe mais",
"The requested share comes from a disabled user" : "O compartilhamento solicitado vem de um usuário desabilitado",
"The user was not created because the user limit has been reached. Check your notifications to learn more." : "O usuário não foi criado porque o limite de usuários foi atingido. Confira suas notificações para saber mais.",
diff --git a/lib/l10n/pt_BR.json b/lib/l10n/pt_BR.json
index 019aab2e2c6..6ddfc036043 100644
--- a/lib/l10n/pt_BR.json
+++ b/lib/l10n/pt_BR.json
@@ -153,15 +153,48 @@
"%1$s shared »%2$s« with you and wants to add:" : "%1$s compartilhou »%2$s« com você e quer adicionar:",
"%1$s shared »%2$s« with you and wants to add" : "%1$s compartilhou »%2$s« com você e quer adicionar",
"»%s« added a note to a file shared with you" : "»%s« adicionou uma anotação num arquivo compartilhado com você",
+ "Passwords are enforced for link and mail shares" : "As senhas são aplicadas para compartilhamentos de links e e-mails",
+ "SharedWith is not a valid user" : "SharedWith não é um usuário válido",
+ "SharedWith is not a valid group" : "SharedWith não é um grupo válido",
+ "SharedWith should be empty" : "SharedWith pode estar vazio",
+ "SharedWith should not be empty" : "SharedWith não pode estar vazio",
+ "SharedWith is not a valid circle" : "SharedWith não é um círculo válido",
"Unknown share type" : "Tipo de compartilhamento desconhecido",
+ "SharedBy should be set" : "SharedBy deve estar definido",
+ "Cannot share with yourself" : "Não é possível compartilhar consigo mesmo",
+ "Path should be set" : "O caminho deve estar definido",
+ "Path should be either a file or a folder" : "O caminho deve ser um arquivo ou pasta",
+ "You cannot share your root folder" : "Você não pode compartilhar sua pasta raiz",
"You are not allowed to share %s" : "Você não tem permissão para compartilhar %s",
+ "A share requires permissions" : "Um compartilhamento requer permissões",
"Cannot increase permissions of %s" : "Não foi possível aumentar as permissões de %s",
+ "Shares need at least read permissions" : "Compartilhamentos precisam pelo menos permissões de leitura",
"Files cannot be shared with delete permissions" : "Arquivos não podem ser compartilhados com permissões de exclusão",
"Files cannot be shared with create permissions" : "Arquivos não podem ser compartilhados com permissões de criação",
"Expiration date is in the past" : "Data de expiração está no passado",
+ "Expiration date is enforced" : "A data de expiração é aplicada",
"_Cannot set expiration date more than %n day in the future_::_Cannot set expiration date more than %n days in the future_" : ["Não foi possível definir a data de expiração superior que %n dias no futuro","Não foi possível definir a data de expiração superior que %n dias no futuro","Não foi possível definir a data de expiração superior que %n dias no futuro"],
"Sharing is only allowed with group members" : "O compartilhamento só é permitido com membros do grupo ",
"Sharing %s failed, because this item is already shared with the account %s" : "Falha no compartilhamento %s porque este item já está compartilhado com a conta %s",
+ "Group sharing is now allowed" : "O compartilhamento em grupo é permitido agora",
+ "Sharing is only allowed within your own groups" : "O compartilhamento só é permitido dentro de seus próprios grupos",
+ "Path is already shared with this group" : "O caminho já está compartilhado com este grupo",
+ "Link sharing is not allowed" : "O compartilhamento de link não é permitido",
+ "Public upload is not allowed" : "O upload público não é permitido",
+ "Path contains files shared with you" : "O caminho contém arquivos compartilhados com você",
+ "Sharing is disabled" : "O compartilhamento está desativado",
+ "Sharing is disabled for you" : "O compartilhamento está desativado para você",
+ "Cannot share with the share owner" : "Não é possível compartilhar com o proprietário do compartilhamento",
+ "Share does not have a full ID" : "O compartilhamento não tem um ID completo",
+ "Cannot change share type" : "Não é possível alterar o tipo de compartilhamento",
+ "Can only update recipient on user shares" : "Só é possível atualizar o destinatário em compartilhamentos de usuários",
+ "Cannot enable sending the password by Talk with an empty password" : "Não é possível ativar o envio da senha pelo Talk com uma senha vazia",
+ "Cannot enable sending the password by Talk without setting a new password" : "Não é possível ativar o envio da senha pelo Talk sem definir uma nova senha",
+ "Cannot disable sending the password by Talk without setting a new password" : "Não é possível desativar o envio da senha pelo Talk sem definir uma nova senha",
+ "Share provider does not support accepting" : "O provedor de compartilhamento não oferece suporte à aceitação",
+ "Cannot change target of link share" : "Não é possível alterar o destino do compartilhamento do link",
+ "Invalid recipient" : "Destinatário inválido",
+ "Group \"%s\" does not exist" : "Grupo \"%s\" não existe",
"The requested share does not exist anymore" : "O compartilhamento solicitado não existe mais",
"The requested share comes from a disabled user" : "O compartilhamento solicitado vem de um usuário desabilitado",
"The user was not created because the user limit has been reached. Check your notifications to learn more." : "O usuário não foi criado porque o limite de usuários foi atingido. Confira suas notificações para saber mais.",
diff --git a/lib/private/Log/LogDetails.php b/lib/private/Log/LogDetails.php
index 95b09c0a181..bd18eb983db 100644
--- a/lib/private/Log/LogDetails.php
+++ b/lib/private/Log/LogDetails.php
@@ -37,7 +37,7 @@ abstract class LogDetails {
$url = ($request->getRequestUri() !== '') ? $request->getRequestUri() : '--';
$method = is_string($request->getMethod()) ? $request->getMethod() : '--';
if ($this->config->getValue('installed', false)) {
- $user = \OC_User::getUser() ? \OC_User::getUser() : '--';
+ $user = \OC_User::getUser() ?? '--';
} else {
$user = '--';
}
diff --git a/lib/private/Security/Bruteforce/Backend/MemoryCacheBackend.php b/lib/private/Security/Bruteforce/Backend/MemoryCacheBackend.php
index 32571c72fae..bf076240bf8 100644
--- a/lib/private/Security/Bruteforce/Backend/MemoryCacheBackend.php
+++ b/lib/private/Security/Bruteforce/Backend/MemoryCacheBackend.php
@@ -19,7 +19,7 @@ class MemoryCacheBackend implements IBackend {
ICacheFactory $cacheFactory,
private ITimeFactory $timeFactory,
) {
- $this->cache = $cacheFactory->createDistributed(__CLASS__);
+ $this->cache = $cacheFactory->createDistributed(self::class);
}
private function hash(
diff --git a/lib/private/Security/RateLimiting/Backend/MemoryCacheBackend.php b/lib/private/Security/RateLimiting/Backend/MemoryCacheBackend.php
index 84eb9fbd084..4c33b49d05e 100644
--- a/lib/private/Security/RateLimiting/Backend/MemoryCacheBackend.php
+++ b/lib/private/Security/RateLimiting/Backend/MemoryCacheBackend.php
@@ -27,7 +27,7 @@ class MemoryCacheBackend implements IBackend {
ICacheFactory $cacheFactory,
private ITimeFactory $timeFactory,
) {
- $this->cache = $cacheFactory->createDistributed(__CLASS__);
+ $this->cache = $cacheFactory->createDistributed(self::class);
}
private function hash(
diff --git a/lib/private/User/Database.php b/lib/private/User/Database.php
index a80cc39a732..2d3808e9dc7 100644
--- a/lib/private/User/Database.php
+++ b/lib/private/User/Database.php
@@ -64,7 +64,7 @@ class Database extends ABackend implements
public function __construct($eventDispatcher = null, $table = 'users') {
$this->cache = new CappedMemoryCache();
$this->table = $table;
- $this->eventDispatcher = $eventDispatcher ? $eventDispatcher : \OCP\Server::get(IEventDispatcher::class);
+ $this->eventDispatcher = $eventDispatcher ?? \OCP\Server::get(IEventDispatcher::class);
}
/**
diff --git a/lib/public/Files/LockNotAcquiredException.php b/lib/public/Files/LockNotAcquiredException.php
index 19e0bbc2543..93d861c248f 100644
--- a/lib/public/Files/LockNotAcquiredException.php
+++ b/lib/public/Files/LockNotAcquiredException.php
@@ -35,6 +35,6 @@ class LockNotAcquiredException extends \Exception {
* @since 7.0.0
*/
public function __toString(): string {
- return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
+ return self::class . ": [{$this->code}]: {$this->message}\n";
}
}
diff --git a/lib/public/HintException.php b/lib/public/HintException.php
index 97abf777ab1..6d9684bddea 100644
--- a/lib/public/HintException.php
+++ b/lib/public/HintException.php
@@ -43,7 +43,7 @@ class HintException extends \Exception {
* @return string
*/
public function __toString(): string {
- return __CLASS__ . ": [{$this->code}]: {$this->message} ({$this->hint})\n";
+ return self::class . ": [{$this->code}]: {$this->message} ({$this->hint})\n";
}
/**
diff --git a/tests/Core/Command/Config/App/DeleteConfigTest.php b/tests/Core/Command/Config/App/DeleteConfigTest.php
index 643c7ca3ca1..ebbbb15e1b6 100644
--- a/tests/Core/Command/Config/App/DeleteConfigTest.php
+++ b/tests/Core/Command/Config/App/DeleteConfigTest.php
@@ -80,7 +80,7 @@ class DeleteConfigTest extends TestCase {
* @param int $expectedReturn
* @param string $expectedMessage
*/
- public function testDelete($configName, $configExists, $checkIfExists, $expectedReturn, $expectedMessage) {
+ public function testDelete($configName, $configExists, $checkIfExists, $expectedReturn, $expectedMessage): void {
$this->config->expects(($checkIfExists) ? $this->once() : $this->never())
->method('getAppKeys')
->with('app-name')
diff --git a/tests/Core/Command/Config/App/GetConfigTest.php b/tests/Core/Command/Config/App/GetConfigTest.php
index 150fceca92f..c1a6265db40 100644
--- a/tests/Core/Command/Config/App/GetConfigTest.php
+++ b/tests/Core/Command/Config/App/GetConfigTest.php
@@ -94,7 +94,7 @@ class GetConfigTest extends TestCase {
* @param int $expectedReturn
* @param string $expectedMessage
*/
- public function testGet($configName, $value, $configExists, $defaultValue, $hasDefault, $outputFormat, $expectedReturn, $expectedMessage) {
+ public function testGet($configName, $value, $configExists, $defaultValue, $hasDefault, $outputFormat, $expectedReturn, $expectedMessage): void {
if (!$expectedReturn) {
if ($configExists) {
$this->config->expects($this->once())
diff --git a/tests/Core/Command/Config/App/SetConfigTest.php b/tests/Core/Command/Config/App/SetConfigTest.php
index 6563dd13fc2..1d599bf3234 100644
--- a/tests/Core/Command/Config/App/SetConfigTest.php
+++ b/tests/Core/Command/Config/App/SetConfigTest.php
@@ -72,7 +72,7 @@ class SetConfigTest extends TestCase {
* @param bool $updated
* @param string $expectedMessage
*/
- public function testSet($configName, $newValue, $configExists, $updateOnly, $updated, $expectedMessage) {
+ public function testSet($configName, $newValue, $configExists, $updateOnly, $updated, $expectedMessage): void {
$this->config->expects($this->any())
->method('hasKey')
->with('app-name', $configName)
diff --git a/tests/Core/Command/Config/ImportTest.php b/tests/Core/Command/Config/ImportTest.php
index 91485955e60..0077f84f82b 100644
--- a/tests/Core/Command/Config/ImportTest.php
+++ b/tests/Core/Command/Config/ImportTest.php
@@ -53,7 +53,7 @@ class ImportTest extends TestCase {
*
* @param mixed $configValue
*/
- public function testValidateAppsArray($configValue) {
+ public function testValidateAppsArray($configValue): void {
$this->invokePrivate($this->command, 'validateAppsArray', [['app' => ['name' => $configValue]]]);
$this->assertTrue(true, 'Asserting that no exception is thrown');
}
@@ -72,7 +72,7 @@ class ImportTest extends TestCase {
*
* @param mixed $configValue
*/
- public function testValidateAppsArrayThrows($configValue) {
+ public function testValidateAppsArrayThrows($configValue): void {
try {
$this->invokePrivate($this->command, 'validateAppsArray', [['app' => ['name' => $configValue]]]);
$this->fail('Did not throw expected UnexpectedValueException');
@@ -102,7 +102,7 @@ class ImportTest extends TestCase {
*
* @param mixed $configValue
*/
- public function testCheckTypeRecursively($configValue) {
+ public function testCheckTypeRecursively($configValue): void {
$this->invokePrivate($this->command, 'checkTypeRecursively', [$configValue, 'name']);
$this->assertTrue(true, 'Asserting that no exception is thrown');
}
@@ -121,7 +121,7 @@ class ImportTest extends TestCase {
*
* @param mixed $configValue
*/
- public function testCheckTypeRecursivelyThrows($configValue) {
+ public function testCheckTypeRecursivelyThrows($configValue): void {
try {
$this->invokePrivate($this->command, 'checkTypeRecursively', [$configValue, 'name']);
$this->fail('Did not throw expected UnexpectedValueException');
@@ -143,7 +143,7 @@ class ImportTest extends TestCase {
*
* @param array $configArray
*/
- public function testValidateArray($configArray) {
+ public function testValidateArray($configArray): void {
$this->invokePrivate($this->command, 'validateArray', [$configArray]);
$this->assertTrue(true, 'Asserting that no exception is thrown');
}
@@ -162,7 +162,7 @@ class ImportTest extends TestCase {
* @param mixed $configArray
* @param string $expectedException
*/
- public function testValidateArrayThrows($configArray, $expectedException) {
+ public function testValidateArrayThrows($configArray, $expectedException): void {
try {
$this->invokePrivate($this->command, 'validateArray', [$configArray]);
$this->fail('Did not throw expected UnexpectedValueException');
diff --git a/tests/Core/Command/Config/ListConfigsTest.php b/tests/Core/Command/Config/ListConfigsTest.php
index 115296ed654..e9cf13773be 100644
--- a/tests/Core/Command/Config/ListConfigsTest.php
+++ b/tests/Core/Command/Config/ListConfigsTest.php
@@ -262,7 +262,7 @@ class ListConfigsTest extends TestCase {
* @param bool $private
* @param string $expected
*/
- public function testList($app, $systemConfigs, $systemConfigMap, $appConfig, $private, $expected) {
+ public function testList($app, $systemConfigs, $systemConfigMap, $appConfig, $private, $expected): void {
$this->systemConfig->expects($this->any())
->method('getKeys')
->willReturn($systemConfigs);
diff --git a/tests/Core/Command/Config/System/DeleteConfigTest.php b/tests/Core/Command/Config/System/DeleteConfigTest.php
index 9b5b018687e..872079ef4c2 100644
--- a/tests/Core/Command/Config/System/DeleteConfigTest.php
+++ b/tests/Core/Command/Config/System/DeleteConfigTest.php
@@ -80,7 +80,7 @@ class DeleteConfigTest extends TestCase {
* @param int $expectedReturn
* @param string $expectedMessage
*/
- public function testDelete($configName, $configExists, $checkIfExists, $expectedReturn, $expectedMessage) {
+ public function testDelete($configName, $configExists, $checkIfExists, $expectedReturn, $expectedMessage): void {
$this->systemConfig->expects(($checkIfExists) ? $this->once() : $this->never())
->method('getKeys')
->willReturn($configExists ? [$configName] : []);
@@ -175,7 +175,7 @@ class DeleteConfigTest extends TestCase {
* @param int $expectedReturn
* @param string $expectedMessage
*/
- public function testArrayDelete(array $configNames, $configKeyExists, $checkIfKeyExists, $configValue, $updateValue, $expectedReturn, $expectedMessage) {
+ public function testArrayDelete(array $configNames, $configKeyExists, $checkIfKeyExists, $configValue, $updateValue, $expectedReturn, $expectedMessage): void {
$this->systemConfig->expects(($checkIfKeyExists) ? $this->once() : $this->never())
->method('getKeys')
->willReturn($configKeyExists ? [$configNames[0]] : []);
diff --git a/tests/Core/Command/Config/System/GetConfigTest.php b/tests/Core/Command/Config/System/GetConfigTest.php
index db96331680b..f05d0e384ee 100644
--- a/tests/Core/Command/Config/System/GetConfigTest.php
+++ b/tests/Core/Command/Config/System/GetConfigTest.php
@@ -99,7 +99,7 @@ class GetConfigTest extends TestCase {
* @param int $expectedReturn
* @param string $expectedMessage
*/
- public function testGet($configNames, $value, $configExists, $defaultValue, $hasDefault, $outputFormat, $expectedReturn, $expectedMessage) {
+ public function testGet($configNames, $value, $configExists, $defaultValue, $hasDefault, $outputFormat, $expectedReturn, $expectedMessage): void {
if (is_array($configNames)) {
$configName = $configNames[0];
} else {
diff --git a/tests/Core/Command/Config/System/SetConfigTest.php b/tests/Core/Command/Config/System/SetConfigTest.php
index d5c54a5e720..2905af5c3d7 100644
--- a/tests/Core/Command/Config/System/SetConfigTest.php
+++ b/tests/Core/Command/Config/System/SetConfigTest.php
@@ -55,7 +55,7 @@ class SetConfigTest extends TestCase {
* @param mixed $existingData
* @param mixed $expectedValue
*/
- public function testSet($configNames, $newValue, $existingData, $expectedValue) {
+ public function testSet($configNames, $newValue, $existingData, $expectedValue): void {
$this->systemConfig->expects($this->once())
->method('setValue')
->with($configNames[0], $expectedValue);
@@ -88,7 +88,7 @@ class SetConfigTest extends TestCase {
/**
* @dataProvider setUpdateOnlyProvider
*/
- public function testSetUpdateOnly($configNames, $existingData) {
+ public function testSetUpdateOnly($configNames, $existingData): void {
$this->expectException(\UnexpectedValueException::class);
$this->systemConfig->expects($this->never())
@@ -135,7 +135,7 @@ class SetConfigTest extends TestCase {
/**
* @dataProvider castValueProvider
*/
- public function testCastValue($value, $type, $expectedValue) {
+ public function testCastValue($value, $type, $expectedValue): void {
$this->assertSame($expectedValue,
$this->invokePrivate($this->command, 'castValue', [$value, $type])
);
@@ -156,7 +156,7 @@ class SetConfigTest extends TestCase {
/**
* @dataProvider castValueInvalidProvider
*/
- public function testCastValueInvalid($value, $type) {
+ public function testCastValueInvalid($value, $type): void {
$this->expectException(\InvalidArgumentException::class);
$this->invokePrivate($this->command, 'castValue', [$value, $type]);
diff --git a/tests/Core/Command/Encryption/ChangeKeyStorageRootTest.php b/tests/Core/Command/Encryption/ChangeKeyStorageRootTest.php
index 4aed3e0b5bd..a1dcdfb51a9 100644
--- a/tests/Core/Command/Encryption/ChangeKeyStorageRootTest.php
+++ b/tests/Core/Command/Encryption/ChangeKeyStorageRootTest.php
@@ -1,362 +1,362 @@
-<?php
-/**
- * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
- * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
- * SPDX-License-Identifier: AGPL-3.0-only
- */
-
-namespace Tests\Core\Command\Encryption;
-
-use OC\Core\Command\Encryption\ChangeKeyStorageRoot;
-use OC\Encryption\Util;
-use OC\Files\View;
-use OCP\IConfig;
-use OCP\IUserManager;
-use OCP\UserInterface;
-use Symfony\Component\Console\Formatter\OutputFormatterInterface;
-use Symfony\Component\Console\Helper\QuestionHelper;
-use Symfony\Component\Console\Input\InputInterface;
-use Symfony\Component\Console\Output\OutputInterface;
-use Test\TestCase;
-
-class ChangeKeyStorageRootTest extends TestCase {
- /** @var ChangeKeyStorageRoot */
- protected $changeKeyStorageRoot;
-
- /** @var View | \PHPUnit\Framework\MockObject\MockObject */
- protected $view;
-
- /** @var IUserManager | \PHPUnit\Framework\MockObject\MockObject */
- protected $userManager;
-
- /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */
- protected $config;
-
- /** @var Util | \PHPUnit\Framework\MockObject\MockObject */
- protected $util;
-
- /** @var QuestionHelper | \PHPUnit\Framework\MockObject\MockObject */
- protected $questionHelper;
-
- /** @var InputInterface | \PHPUnit\Framework\MockObject\MockObject */
- protected $inputInterface;
-
- /** @var OutputInterface | \PHPUnit\Framework\MockObject\MockObject */
- protected $outputInterface;
-
- /** @var \OCP\UserInterface | \PHPUnit\Framework\MockObject\MockObject */
- protected $userInterface;
-
- protected function setUp(): void {
- parent::setUp();
-
- $this->view = $this->getMockBuilder(View::class)->getMock();
- $this->userManager = $this->getMockBuilder(IUserManager::class)->getMock();
- $this->config = $this->getMockBuilder(IConfig::class)->getMock();
- $this->util = $this->getMockBuilder(\OC\Encryption\Util::class)->disableOriginalConstructor()->getMock();
- $this->questionHelper = $this->getMockBuilder(QuestionHelper::class)->getMock();
- $this->inputInterface = $this->getMockBuilder(InputInterface::class)->getMock();
- $this->outputInterface = $this->getMockBuilder(OutputInterface::class)->getMock();
- $this->userInterface = $this->getMockBuilder(UserInterface::class)->getMock();
-
- /* We need format method to return a string */
- $outputFormatter = $this->createMock(OutputFormatterInterface::class);
- $outputFormatter->method('isDecorated')->willReturn(false);
- $outputFormatter->method('format')->willReturnArgument(0);
-
- $this->outputInterface->expects($this->any())->method('getFormatter')
- ->willReturn($outputFormatter);
-
- $this->changeKeyStorageRoot = new ChangeKeyStorageRoot(
- $this->view,
- $this->userManager,
- $this->config,
- $this->util,
- $this->questionHelper
- );
- }
-
- /**
- * @dataProvider dataTestExecute
- */
- public function testExecute($newRoot, $answer, $successMoveKey) {
- $changeKeyStorageRoot = $this->getMockBuilder(\OC\Core\Command\Encryption\ChangeKeyStorageRoot::class)
- ->setConstructorArgs(
- [
- $this->view,
- $this->userManager,
- $this->config,
- $this->util,
- $this->questionHelper
- ]
- )->setMethods(['moveAllKeys'])->getMock();
-
- $this->util->expects($this->once())->method('getKeyStorageRoot')
- ->willReturn('');
- $this->inputInterface->expects($this->once())->method('getArgument')
- ->with('newRoot')->willReturn($newRoot);
-
- if ($answer === true || $newRoot !== null) {
- $changeKeyStorageRoot->expects($this->once())->method('moveAllKeys')
- ->willReturn($successMoveKey);
- } else {
- $changeKeyStorageRoot->expects($this->never())->method('moveAllKeys');
- }
-
- if ($successMoveKey === true) {
- $this->util->expects($this->once())->method('setKeyStorageRoot');
- } else {
- $this->util->expects($this->never())->method('setKeyStorageRoot');
- }
-
- if ($newRoot === null) {
- $this->questionHelper->expects($this->once())->method('ask')->willReturn($answer);
- } else {
- $this->questionHelper->expects($this->never())->method('ask');
- }
-
- $this->invokePrivate(
- $changeKeyStorageRoot,
- 'execute',
- [$this->inputInterface, $this->outputInterface]
- );
- }
-
- public function dataTestExecute() {
- return [
- [null, true, true],
- [null, true, false],
- [null, false, null],
- ['/newRoot', null, true],
- ['/newRoot', null, false]
- ];
- }
-
- public function testMoveAllKeys() {
- /** @var \OC\Core\Command\Encryption\ChangeKeyStorageRoot $changeKeyStorageRoot */
- $changeKeyStorageRoot = $this->getMockBuilder(\OC\Core\Command\Encryption\ChangeKeyStorageRoot::class)
- ->setConstructorArgs(
- [
- $this->view,
- $this->userManager,
- $this->config,
- $this->util,
- $this->questionHelper
- ]
- )->setMethods(['prepareNewRoot', 'moveSystemKeys', 'moveUserKeys'])->getMock();
-
- $changeKeyStorageRoot->expects($this->once())->method('prepareNewRoot')->with('newRoot');
- $changeKeyStorageRoot->expects($this->once())->method('moveSystemKeys')->with('oldRoot', 'newRoot');
- $changeKeyStorageRoot->expects($this->once())->method('moveUserKeys')->with('oldRoot', 'newRoot', $this->outputInterface);
-
- $this->invokePrivate($changeKeyStorageRoot, 'moveAllKeys', ['oldRoot', 'newRoot', $this->outputInterface]);
- }
-
- public function testPrepareNewRoot() {
- $this->view->expects($this->once())->method('is_dir')->with('newRoot')
- ->willReturn(true);
-
- $this->view->expects($this->once())->method('file_put_contents')
- ->with('newRoot/' . \OC\Encryption\Keys\Storage::KEY_STORAGE_MARKER,
- 'Nextcloud will detect this folder as key storage root only if this file exists')->willReturn(true);
-
- $this->invokePrivate($this->changeKeyStorageRoot, 'prepareNewRoot', ['newRoot']);
- }
-
- /**
- * @dataProvider dataTestPrepareNewRootException
- *
- * @param bool $dirExists
- * @param bool $couldCreateFile
- */
- public function testPrepareNewRootException($dirExists, $couldCreateFile) {
- $this->expectException(\Exception::class);
-
- $this->view->expects($this->once())->method('is_dir')->with('newRoot')
- ->willReturn($dirExists);
- $this->view->expects($this->any())->method('file_put_contents')->willReturn($couldCreateFile);
-
- $this->invokePrivate($this->changeKeyStorageRoot, 'prepareNewRoot', ['newRoot']);
- }
-
- public function dataTestPrepareNewRootException() {
- return [
- [true, false],
- [true, null],
- [false, true]
- ];
- }
-
- /**
- * @dataProvider dataTestMoveSystemKeys
- *
- * @param bool $dirExists
- * @param bool $targetExists
- * @param bool $executeRename
- */
- public function testMoveSystemKeys($dirExists, $targetExists, $executeRename) {
- $changeKeyStorageRoot = $this->getMockBuilder(\OC\Core\Command\Encryption\ChangeKeyStorageRoot::class)
- ->setConstructorArgs(
- [
- $this->view,
- $this->userManager,
- $this->config,
- $this->util,
- $this->questionHelper
- ]
- )->setMethods(['targetExists'])->getMock();
-
- $this->view->expects($this->once())->method('is_dir')
- ->with('oldRoot/files_encryption')->willReturn($dirExists);
- $changeKeyStorageRoot->expects($this->any())->method('targetExists')
- ->with('newRoot/files_encryption')->willReturn($targetExists);
-
- if ($executeRename) {
- $this->view->expects($this->once())->method('rename')
- ->with('oldRoot/files_encryption', 'newRoot/files_encryption');
- } else {
- $this->view->expects($this->never())->method('rename');
- }
-
- $this->invokePrivate($changeKeyStorageRoot, 'moveSystemKeys', ['oldRoot', 'newRoot']);
- }
-
- public function dataTestMoveSystemKeys() {
- return [
- [true, false, true],
- [false, true, false],
- [true, true, false],
- [false, false, false]
- ];
- }
-
-
- public function testMoveUserKeys() {
- $changeKeyStorageRoot = $this->getMockBuilder(\OC\Core\Command\Encryption\ChangeKeyStorageRoot::class)
- ->setConstructorArgs(
- [
- $this->view,
- $this->userManager,
- $this->config,
- $this->util,
- $this->questionHelper
- ]
- )->setMethods(['setupUserFS', 'moveUserEncryptionFolder'])->getMock();
-
- $this->userManager->expects($this->once())->method('getBackends')
- ->willReturn([$this->userInterface]);
- $this->userInterface->expects($this->once())->method('getUsers')
- ->willReturn(['user1', 'user2']);
- $changeKeyStorageRoot->expects($this->exactly(2))->method('setupUserFS');
- $changeKeyStorageRoot->expects($this->exactly(2))->method('moveUserEncryptionFolder');
-
- $this->invokePrivate($changeKeyStorageRoot, 'moveUserKeys', ['oldRoot', 'newRoot', $this->outputInterface]);
- }
-
- /**
- * @dataProvider dataTestMoveUserEncryptionFolder
- *
- * @param bool $userExists
- * @param bool $isDir
- * @param bool $targetExists
- * @param bool $shouldRename
- */
- public function testMoveUserEncryptionFolder($userExists, $isDir, $targetExists, $shouldRename) {
- $changeKeyStorageRoot = $this->getMockBuilder(\OC\Core\Command\Encryption\ChangeKeyStorageRoot::class)
- ->setConstructorArgs(
- [
- $this->view,
- $this->userManager,
- $this->config,
- $this->util,
- $this->questionHelper
- ]
- )->setMethods(['targetExists', 'prepareParentFolder'])->getMock();
-
- $this->userManager->expects($this->once())->method('userExists')
- ->willReturn($userExists);
- $this->view->expects($this->any())->method('is_dir')
- ->willReturn($isDir);
- $changeKeyStorageRoot->expects($this->any())->method('targetExists')
- ->willReturn($targetExists);
-
- if ($shouldRename) {
- $changeKeyStorageRoot->expects($this->once())->method('prepareParentFolder')
- ->with('newRoot/user1');
- $this->view->expects($this->once())->method('rename')
- ->with('oldRoot/user1/files_encryption', 'newRoot/user1/files_encryption');
- } else {
- $changeKeyStorageRoot->expects($this->never())->method('prepareParentFolder');
- $this->view->expects($this->never())->method('rename');
- }
-
- $this->invokePrivate($changeKeyStorageRoot, 'moveUserEncryptionFolder', ['user1', 'oldRoot', 'newRoot']);
- }
-
- public function dataTestMoveUserEncryptionFolder() {
- return [
- [true, true, false, true],
- [true, false, true, false],
- [false, true, true, false],
- [false, false, true, false],
- [false, true, false, false],
- [false, true, true, false],
- [false, false, false, false]
- ];
- }
-
-
- /**
- * @dataProvider dataTestPrepareParentFolder
- */
- public function testPrepareParentFolder($path, $pathExists) {
- $this->view->expects($this->any())->method('file_exists')
- ->willReturnCallback(
- function ($fileExistsPath) use ($path, $pathExists) {
- if ($path === $fileExistsPath) {
- return $pathExists;
- }
- return false;
- }
- );
-
- if ($pathExists === false) {
- $subDirs = explode('/', ltrim($path, '/'));
- $this->view->expects($this->exactly(count($subDirs)))->method('mkdir');
- } else {
- $this->view->expects($this->never())->method('mkdir');
- }
-
- $this->invokePrivate(
- $this->changeKeyStorageRoot,
- 'prepareParentFolder',
- [$path]
- );
- }
-
- public function dataTestPrepareParentFolder() {
- return [
- ['/user/folder/sub_folder/keystorage', true],
- ['/user/folder/sub_folder/keystorage', false]
- ];
- }
-
- public function testTargetExists() {
- $this->view->expects($this->once())->method('file_exists')->with('path')
- ->willReturn(false);
-
- $this->assertFalse(
- $this->invokePrivate($this->changeKeyStorageRoot, 'targetExists', ['path'])
- );
- }
-
-
- public function testTargetExistsException() {
- $this->expectException(\Exception::class);
-
- $this->view->expects($this->once())->method('file_exists')->with('path')
- ->willReturn(true);
-
- $this->invokePrivate($this->changeKeyStorageRoot, 'targetExists', ['path']);
- }
-}
+<?php
+/**
+ * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
+ */
+
+namespace Tests\Core\Command\Encryption;
+
+use OC\Core\Command\Encryption\ChangeKeyStorageRoot;
+use OC\Encryption\Util;
+use OC\Files\View;
+use OCP\IConfig;
+use OCP\IUserManager;
+use OCP\UserInterface;
+use Symfony\Component\Console\Formatter\OutputFormatterInterface;
+use Symfony\Component\Console\Helper\QuestionHelper;
+use Symfony\Component\Console\Input\InputInterface;
+use Symfony\Component\Console\Output\OutputInterface;
+use Test\TestCase;
+
+class ChangeKeyStorageRootTest extends TestCase {
+ /** @var ChangeKeyStorageRoot */
+ protected $changeKeyStorageRoot;
+
+ /** @var View | \PHPUnit\Framework\MockObject\MockObject */
+ protected $view;
+
+ /** @var IUserManager | \PHPUnit\Framework\MockObject\MockObject */
+ protected $userManager;
+
+ /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */
+ protected $config;
+
+ /** @var Util | \PHPUnit\Framework\MockObject\MockObject */
+ protected $util;
+
+ /** @var QuestionHelper | \PHPUnit\Framework\MockObject\MockObject */
+ protected $questionHelper;
+
+ /** @var InputInterface | \PHPUnit\Framework\MockObject\MockObject */
+ protected $inputInterface;
+
+ /** @var OutputInterface | \PHPUnit\Framework\MockObject\MockObject */
+ protected $outputInterface;
+
+ /** @var \OCP\UserInterface | \PHPUnit\Framework\MockObject\MockObject */
+ protected $userInterface;
+
+ protected function setUp(): void {
+ parent::setUp();
+
+ $this->view = $this->getMockBuilder(View::class)->getMock();
+ $this->userManager = $this->getMockBuilder(IUserManager::class)->getMock();
+ $this->config = $this->getMockBuilder(IConfig::class)->getMock();
+ $this->util = $this->getMockBuilder(\OC\Encryption\Util::class)->disableOriginalConstructor()->getMock();
+ $this->questionHelper = $this->getMockBuilder(QuestionHelper::class)->getMock();
+ $this->inputInterface = $this->getMockBuilder(InputInterface::class)->getMock();
+ $this->outputInterface = $this->getMockBuilder(OutputInterface::class)->getMock();
+ $this->userInterface = $this->getMockBuilder(UserInterface::class)->getMock();
+
+ /* We need format method to return a string */
+ $outputFormatter = $this->createMock(OutputFormatterInterface::class);
+ $outputFormatter->method('isDecorated')->willReturn(false);
+ $outputFormatter->method('format')->willReturnArgument(0);
+
+ $this->outputInterface->expects($this->any())->method('getFormatter')
+ ->willReturn($outputFormatter);
+
+ $this->changeKeyStorageRoot = new ChangeKeyStorageRoot(
+ $this->view,
+ $this->userManager,
+ $this->config,
+ $this->util,
+ $this->questionHelper
+ );
+ }
+
+ /**
+ * @dataProvider dataTestExecute
+ */
+ public function testExecute($newRoot, $answer, $successMoveKey): void {
+ $changeKeyStorageRoot = $this->getMockBuilder(\OC\Core\Command\Encryption\ChangeKeyStorageRoot::class)
+ ->setConstructorArgs(
+ [
+ $this->view,
+ $this->userManager,
+ $this->config,
+ $this->util,
+ $this->questionHelper
+ ]
+ )->setMethods(['moveAllKeys'])->getMock();
+
+ $this->util->expects($this->once())->method('getKeyStorageRoot')
+ ->willReturn('');
+ $this->inputInterface->expects($this->once())->method('getArgument')
+ ->with('newRoot')->willReturn($newRoot);
+
+ if ($answer === true || $newRoot !== null) {
+ $changeKeyStorageRoot->expects($this->once())->method('moveAllKeys')
+ ->willReturn($successMoveKey);
+ } else {
+ $changeKeyStorageRoot->expects($this->never())->method('moveAllKeys');
+ }
+
+ if ($successMoveKey === true) {
+ $this->util->expects($this->once())->method('setKeyStorageRoot');
+ } else {
+ $this->util->expects($this->never())->method('setKeyStorageRoot');
+ }
+
+ if ($newRoot === null) {
+ $this->questionHelper->expects($this->once())->method('ask')->willReturn($answer);
+ } else {
+ $this->questionHelper->expects($this->never())->method('ask');
+ }
+
+ $this->invokePrivate(
+ $changeKeyStorageRoot,
+ 'execute',
+ [$this->inputInterface, $this->outputInterface]
+ );
+ }
+
+ public function dataTestExecute() {
+ return [
+ [null, true, true],
+ [null, true, false],
+ [null, false, null],
+ ['/newRoot', null, true],
+ ['/newRoot', null, false]
+ ];
+ }
+
+ public function testMoveAllKeys(): void {
+ /** @var \OC\Core\Command\Encryption\ChangeKeyStorageRoot $changeKeyStorageRoot */
+ $changeKeyStorageRoot = $this->getMockBuilder(\OC\Core\Command\Encryption\ChangeKeyStorageRoot::class)
+ ->setConstructorArgs(
+ [
+ $this->view,
+ $this->userManager,
+ $this->config,
+ $this->util,
+ $this->questionHelper
+ ]
+ )->setMethods(['prepareNewRoot', 'moveSystemKeys', 'moveUserKeys'])->getMock();
+
+ $changeKeyStorageRoot->expects($this->once())->method('prepareNewRoot')->with('newRoot');
+ $changeKeyStorageRoot->expects($this->once())->method('moveSystemKeys')->with('oldRoot', 'newRoot');
+ $changeKeyStorageRoot->expects($this->once())->method('moveUserKeys')->with('oldRoot', 'newRoot', $this->outputInterface);
+
+ $this->invokePrivate($changeKeyStorageRoot, 'moveAllKeys', ['oldRoot', 'newRoot', $this->outputInterface]);
+ }
+
+ public function testPrepareNewRoot(): void {
+ $this->view->expects($this->once())->method('is_dir')->with('newRoot')
+ ->willReturn(true);
+
+ $this->view->expects($this->once())->method('file_put_contents')
+ ->with('newRoot/' . \OC\Encryption\Keys\Storage::KEY_STORAGE_MARKER,
+ 'Nextcloud will detect this folder as key storage root only if this file exists')->willReturn(true);
+
+ $this->invokePrivate($this->changeKeyStorageRoot, 'prepareNewRoot', ['newRoot']);
+ }
+
+ /**
+ * @dataProvider dataTestPrepareNewRootException
+ *
+ * @param bool $dirExists
+ * @param bool $couldCreateFile
+ */
+ public function testPrepareNewRootException($dirExists, $couldCreateFile): void {
+ $this->expectException(\Exception::class);
+
+ $this->view->expects($this->once())->method('is_dir')->with('newRoot')
+ ->willReturn($dirExists);
+ $this->view->expects($this->any())->method('file_put_contents')->willReturn($couldCreateFile);
+
+ $this->invokePrivate($this->changeKeyStorageRoot, 'prepareNewRoot', ['newRoot']);
+ }
+
+ public function dataTestPrepareNewRootException() {
+ return [
+ [true, false],
+ [true, null],
+ [false, true]
+ ];
+ }
+
+ /**
+ * @dataProvider dataTestMoveSystemKeys
+ *
+ * @param bool $dirExists
+ * @param bool $targetExists
+ * @param bool $executeRename
+ */
+ public function testMoveSystemKeys($dirExists, $targetExists, $executeRename): void {
+ $changeKeyStorageRoot = $this->getMockBuilder(\OC\Core\Command\Encryption\ChangeKeyStorageRoot::class)
+ ->setConstructorArgs(
+ [
+ $this->view,
+ $this->userManager,
+ $this->config,
+ $this->util,
+ $this->questionHelper
+ ]
+ )->setMethods(['targetExists'])->getMock();
+
+ $this->view->expects($this->once())->method('is_dir')
+ ->with('oldRoot/files_encryption')->willReturn($dirExists);
+ $changeKeyStorageRoot->expects($this->any())->method('targetExists')
+ ->with('newRoot/files_encryption')->willReturn($targetExists);
+
+ if ($executeRename) {
+ $this->view->expects($this->once())->method('rename')
+ ->with('oldRoot/files_encryption', 'newRoot/files_encryption');
+ } else {
+ $this->view->expects($this->never())->method('rename');
+ }
+
+ $this->invokePrivate($changeKeyStorageRoot, 'moveSystemKeys', ['oldRoot', 'newRoot']);
+ }
+
+ public function dataTestMoveSystemKeys() {
+ return [
+ [true, false, true],
+ [false, true, false],
+ [true, true, false],
+ [false, false, false]
+ ];
+ }
+
+
+ public function testMoveUserKeys(): void {
+ $changeKeyStorageRoot = $this->getMockBuilder(\OC\Core\Command\Encryption\ChangeKeyStorageRoot::class)
+ ->setConstructorArgs(
+ [
+ $this->view,
+ $this->userManager,
+ $this->config,
+ $this->util,
+ $this->questionHelper
+ ]
+ )->setMethods(['setupUserFS', 'moveUserEncryptionFolder'])->getMock();
+
+ $this->userManager->expects($this->once())->method('getBackends')
+ ->willReturn([$this->userInterface]);
+ $this->userInterface->expects($this->once())->method('getUsers')
+ ->willReturn(['user1', 'user2']);
+ $changeKeyStorageRoot->expects($this->exactly(2))->method('setupUserFS');
+ $changeKeyStorageRoot->expects($this->exactly(2))->method('moveUserEncryptionFolder');
+
+ $this->invokePrivate($changeKeyStorageRoot, 'moveUserKeys', ['oldRoot', 'newRoot', $this->outputInterface]);
+ }
+
+ /**
+ * @dataProvider dataTestMoveUserEncryptionFolder
+ *
+ * @param bool $userExists
+ * @param bool $isDir
+ * @param bool $targetExists
+ * @param bool $shouldRename
+ */
+ public function testMoveUserEncryptionFolder($userExists, $isDir, $targetExists, $shouldRename): void {
+ $changeKeyStorageRoot = $this->getMockBuilder(\OC\Core\Command\Encryption\ChangeKeyStorageRoot::class)
+ ->setConstructorArgs(
+ [
+ $this->view,
+ $this->userManager,
+ $this->config,
+ $this->util,
+ $this->questionHelper
+ ]
+ )->setMethods(['targetExists', 'prepareParentFolder'])->getMock();
+
+ $this->userManager->expects($this->once())->method('userExists')
+ ->willReturn($userExists);
+ $this->view->expects($this->any())->method('is_dir')
+ ->willReturn($isDir);
+ $changeKeyStorageRoot->expects($this->any())->method('targetExists')
+ ->willReturn($targetExists);
+
+ if ($shouldRename) {
+ $changeKeyStorageRoot->expects($this->once())->method('prepareParentFolder')
+ ->with('newRoot/user1');
+ $this->view->expects($this->once())->method('rename')
+ ->with('oldRoot/user1/files_encryption', 'newRoot/user1/files_encryption');
+ } else {
+ $changeKeyStorageRoot->expects($this->never())->method('prepareParentFolder');
+ $this->view->expects($this->never())->method('rename');
+ }
+
+ $this->invokePrivate($changeKeyStorageRoot, 'moveUserEncryptionFolder', ['user1', 'oldRoot', 'newRoot']);
+ }
+
+ public function dataTestMoveUserEncryptionFolder() {
+ return [
+ [true, true, false, true],
+ [true, false, true, false],
+ [false, true, true, false],
+ [false, false, true, false],
+ [false, true, false, false],
+ [false, true, true, false],
+ [false, false, false, false]
+ ];
+ }
+
+
+ /**
+ * @dataProvider dataTestPrepareParentFolder
+ */
+ public function testPrepareParentFolder($path, $pathExists): void {
+ $this->view->expects($this->any())->method('file_exists')
+ ->willReturnCallback(
+ function ($fileExistsPath) use ($path, $pathExists) {
+ if ($path === $fileExistsPath) {
+ return $pathExists;
+ }
+ return false;
+ }
+ );
+
+ if ($pathExists === false) {
+ $subDirs = explode('/', ltrim($path, '/'));
+ $this->view->expects($this->exactly(count($subDirs)))->method('mkdir');
+ } else {
+ $this->view->expects($this->never())->method('mkdir');
+ }
+
+ $this->invokePrivate(
+ $this->changeKeyStorageRoot,
+ 'prepareParentFolder',
+ [$path]
+ );
+ }
+
+ public function dataTestPrepareParentFolder() {
+ return [
+ ['/user/folder/sub_folder/keystorage', true],
+ ['/user/folder/sub_folder/keystorage', false]
+ ];
+ }
+
+ public function testTargetExists(): void {
+ $this->view->expects($this->once())->method('file_exists')->with('path')
+ ->willReturn(false);
+
+ $this->assertFalse(
+ $this->invokePrivate($this->changeKeyStorageRoot, 'targetExists', ['path'])
+ );
+ }
+
+
+ public function testTargetExistsException(): void {
+ $this->expectException(\Exception::class);
+
+ $this->view->expects($this->once())->method('file_exists')->with('path')
+ ->willReturn(true);
+
+ $this->invokePrivate($this->changeKeyStorageRoot, 'targetExists', ['path']);
+ }
+}
diff --git a/tests/Core/Command/Encryption/DecryptAllTest.php b/tests/Core/Command/Encryption/DecryptAllTest.php
index 46cd2cfc4bc..6ed4cbbea99 100644
--- a/tests/Core/Command/Encryption/DecryptAllTest.php
+++ b/tests/Core/Command/Encryption/DecryptAllTest.php
@@ -70,7 +70,7 @@ class DecryptAllTest extends TestCase {
->with('files_trashbin')->willReturn(true);
}
- public function testMaintenanceAndTrashbin() {
+ public function testMaintenanceAndTrashbin(): void {
// on construct we enable single-user-mode and disable the trash bin
// on destruct we disable single-user-mode again and enable the trash bin
$this->config->expects($this->exactly(2))
@@ -108,7 +108,7 @@ class DecryptAllTest extends TestCase {
/**
* @dataProvider dataTestExecute
*/
- public function testExecute($encryptionEnabled, $continue) {
+ public function testExecute($encryptionEnabled, $continue): void {
$instance = new DecryptAll(
$this->encryptionManager,
$this->appManager,
@@ -162,7 +162,7 @@ class DecryptAllTest extends TestCase {
}
- public function testExecuteFailure() {
+ public function testExecuteFailure(): void {
$this->expectException(\Exception::class);
$instance = new DecryptAll(
diff --git a/tests/Core/Command/Encryption/DisableTest.php b/tests/Core/Command/Encryption/DisableTest.php
index 6c962399e11..913d03a8850 100644
--- a/tests/Core/Command/Encryption/DisableTest.php
+++ b/tests/Core/Command/Encryption/DisableTest.php
@@ -52,7 +52,7 @@ class DisableTest extends TestCase {
* @param bool $isUpdating
* @param string $expectedString
*/
- public function testDisable($oldStatus, $isUpdating, $expectedString) {
+ public function testDisable($oldStatus, $isUpdating, $expectedString): void {
$this->config->expects($this->once())
->method('getAppValue')
->with('core', 'encryption_enabled', $this->anything())
diff --git a/tests/Core/Command/Encryption/EnableTest.php b/tests/Core/Command/Encryption/EnableTest.php
index b535c80b0a8..2d463452add 100644
--- a/tests/Core/Command/Encryption/EnableTest.php
+++ b/tests/Core/Command/Encryption/EnableTest.php
@@ -65,7 +65,7 @@ class EnableTest extends TestCase {
* @param string $expectedString
* @param string $expectedDefaultModuleString
*/
- public function testEnable($oldStatus, $defaultModule, $availableModules, $isUpdating, $expectedString, $expectedDefaultModuleString) {
+ public function testEnable($oldStatus, $defaultModule, $availableModules, $isUpdating, $expectedString, $expectedDefaultModuleString): void {
if ($isUpdating) {
$this->config->expects($this->once())
->method('setAppValue')
diff --git a/tests/Core/Command/Encryption/EncryptAllTest.php b/tests/Core/Command/Encryption/EncryptAllTest.php
index 994aa43a938..933f919ba7f 100644
--- a/tests/Core/Command/Encryption/EncryptAllTest.php
+++ b/tests/Core/Command/Encryption/EncryptAllTest.php
@@ -67,7 +67,7 @@ class EncryptAllTest extends TestCase {
$this->consoleOutput = $this->getMockBuilder(OutputInterface::class)->getMock();
}
- public function testEncryptAll() {
+ public function testEncryptAll(): void {
// trash bin needs to be disabled in order to avoid adding dummy files to the users
// trash bin which gets deleted during the encryption process
$this->appManager->expects($this->once())->method('disableApp')->with('files_trashbin');
@@ -89,7 +89,7 @@ class EncryptAllTest extends TestCase {
/**
* @dataProvider dataTestExecute
*/
- public function testExecute($answer, $askResult) {
+ public function testExecute($answer, $askResult): void {
$command = new EncryptAll($this->encryptionManager, $this->appManager, $this->config, $this->questionHelper);
$this->encryptionManager->expects($this->once())->method('isEnabled')->willReturn(true);
@@ -115,7 +115,7 @@ class EncryptAllTest extends TestCase {
}
- public function testExecuteException() {
+ public function testExecuteException(): void {
$this->expectException(\Exception::class);
$command = new EncryptAll($this->encryptionManager, $this->appManager, $this->config, $this->questionHelper);
diff --git a/tests/Core/Command/Encryption/SetDefaultModuleTest.php b/tests/Core/Command/Encryption/SetDefaultModuleTest.php
index 9c4259fb04e..0a2c2a81c28 100644
--- a/tests/Core/Command/Encryption/SetDefaultModuleTest.php
+++ b/tests/Core/Command/Encryption/SetDefaultModuleTest.php
@@ -60,7 +60,7 @@ class SetDefaultModuleTest extends TestCase {
* @param bool $updateSuccess
* @param string $expectedString
*/
- public function testSetDefaultModule($oldModule, $newModule, $updateModule, $updateSuccess, $expectedString) {
+ public function testSetDefaultModule($oldModule, $newModule, $updateModule, $updateSuccess, $expectedString): void {
$this->consoleInput->expects($this->once())
->method('getArgument')
->with('module')
@@ -98,7 +98,7 @@ class SetDefaultModuleTest extends TestCase {
* @param bool $updateSuccess
* @param string $expectedString
*/
- public function testMaintenanceMode($oldModule, $newModule, $updateModule, $updateSuccess, $expectedString) {
+ public function testMaintenanceMode($oldModule, $newModule, $updateModule, $updateSuccess, $expectedString): void {
$this->consoleInput->expects($this->never())
->method('getArgument')
->with('module')
diff --git a/tests/Core/Command/Group/AddTest.php b/tests/Core/Command/Group/AddTest.php
index 76ef4a74f6a..c953199766f 100644
--- a/tests/Core/Command/Group/AddTest.php
+++ b/tests/Core/Command/Group/AddTest.php
@@ -43,7 +43,7 @@ class AddTest extends TestCase {
$this->output = $this->createMock(OutputInterface::class);
}
- public function testGroupExists() {
+ public function testGroupExists(): void {
$gid = 'myGroup';
$group = $this->createMock(IGroup::class);
$this->groupManager->method('get')
@@ -59,7 +59,7 @@ class AddTest extends TestCase {
$this->invokePrivate($this->command, 'execute', [$this->input, $this->output]);
}
- public function testAdd() {
+ public function testAdd(): void {
$gid = 'myGroup';
$group = $this->createMock(IGroup::class);
$group->method('getGID')
diff --git a/tests/Core/Command/Group/AddUserTest.php b/tests/Core/Command/Group/AddUserTest.php
index 8c8f4902a16..4bbf54f7b3f 100644
--- a/tests/Core/Command/Group/AddUserTest.php
+++ b/tests/Core/Command/Group/AddUserTest.php
@@ -51,7 +51,7 @@ class AddUserTest extends TestCase {
$this->output = $this->createMock(OutputInterface::class);
}
- public function testNoGroup() {
+ public function testNoGroup(): void {
$this->groupManager->method('get')
->with('myGroup')
->willReturn(null);
@@ -63,7 +63,7 @@ class AddUserTest extends TestCase {
$this->invokePrivate($this->command, 'execute', [$this->input, $this->output]);
}
- public function testNoUser() {
+ public function testNoUser(): void {
$group = $this->createMock(IGroup::class);
$this->groupManager->method('get')
->with('myGroup')
@@ -80,7 +80,7 @@ class AddUserTest extends TestCase {
$this->invokePrivate($this->command, 'execute', [$this->input, $this->output]);
}
- public function testAdd() {
+ public function testAdd(): void {
$group = $this->createMock(IGroup::class);
$this->groupManager->method('get')
->with('myGroup')
diff --git a/tests/Core/Command/Group/DeleteTest.php b/tests/Core/Command/Group/DeleteTest.php
index fe1aaff64bc..4b4f16feb76 100644
--- a/tests/Core/Command/Group/DeleteTest.php
+++ b/tests/Core/Command/Group/DeleteTest.php
@@ -36,7 +36,7 @@ class DeleteTest extends TestCase {
$this->output = $this->createMock(OutputInterface::class);
}
- public function testDoesNotExists() {
+ public function testDoesNotExists(): void {
$gid = 'myGroup';
$this->input->method('getArgument')
->willReturnCallback(function ($arg) use ($gid) {
@@ -58,7 +58,7 @@ class DeleteTest extends TestCase {
$this->invokePrivate($this->command, 'execute', [$this->input, $this->output]);
}
- public function testDeleteAdmin() {
+ public function testDeleteAdmin(): void {
$gid = 'admin';
$this->input->method('getArgument')
->willReturnCallback(function ($arg) use ($gid) {
@@ -77,7 +77,7 @@ class DeleteTest extends TestCase {
$this->invokePrivate($this->command, 'execute', [$this->input, $this->output]);
}
- public function testDeleteFailed() {
+ public function testDeleteFailed(): void {
$gid = 'myGroup';
$this->input->method('getArgument')
->willReturnCallback(function ($arg) use ($gid) {
@@ -103,7 +103,7 @@ class DeleteTest extends TestCase {
$this->invokePrivate($this->command, 'execute', [$this->input, $this->output]);
}
- public function testDelete() {
+ public function testDelete(): void {
$gid = 'myGroup';
$this->input->method('getArgument')
->willReturnCallback(function ($arg) use ($gid) {
diff --git a/tests/Core/Command/Group/InfoTest.php b/tests/Core/Command/Group/InfoTest.php
index 6f5a9cce02b..869b6741866 100644
--- a/tests/Core/Command/Group/InfoTest.php
+++ b/tests/Core/Command/Group/InfoTest.php
@@ -39,7 +39,7 @@ class InfoTest extends TestCase {
$this->output = $this->createMock(OutputInterface::class);
}
- public function testDoesNotExists() {
+ public function testDoesNotExists(): void {
$gid = 'myGroup';
$this->input->method('getArgument')
->willReturnCallback(function ($arg) use ($gid) {
@@ -59,7 +59,7 @@ class InfoTest extends TestCase {
$this->invokePrivate($this->command, 'execute', [$this->input, $this->output]);
}
- public function testInfo() {
+ public function testInfo(): void {
$gid = 'myGroup';
$this->input->method('getArgument')
->willReturnCallback(function ($arg) use ($gid) {
diff --git a/tests/Core/Command/Group/ListCommandTest.php b/tests/Core/Command/Group/ListCommandTest.php
index a995bdc0b20..93d472af388 100644
--- a/tests/Core/Command/Group/ListCommandTest.php
+++ b/tests/Core/Command/Group/ListCommandTest.php
@@ -40,7 +40,7 @@ class ListCommandTest extends TestCase {
$this->output = $this->createMock(OutputInterface::class);
}
- public function testExecute() {
+ public function testExecute(): void {
$group1 = $this->createMock(IGroup::class);
$group1->method('getGID')->willReturn('group1');
$group2 = $this->createMock(IGroup::class);
@@ -109,7 +109,7 @@ class ListCommandTest extends TestCase {
$this->invokePrivate($this->command, 'execute', [$this->input, $this->output]);
}
- public function testInfo() {
+ public function testInfo(): void {
$group1 = $this->createMock(IGroup::class);
$group1->method('getGID')->willReturn('group1');
$group1->method('getDisplayName')->willReturn('Group 1');
diff --git a/tests/Core/Command/Group/RemoveUserTest.php b/tests/Core/Command/Group/RemoveUserTest.php
index 47c782b6f44..98fe41784f1 100644
--- a/tests/Core/Command/Group/RemoveUserTest.php
+++ b/tests/Core/Command/Group/RemoveUserTest.php
@@ -51,7 +51,7 @@ class RemoveUserTest extends TestCase {
$this->output = $this->createMock(OutputInterface::class);
}
- public function testNoGroup() {
+ public function testNoGroup(): void {
$this->groupManager->method('get')
->with('myGroup')
->willReturn(null);
@@ -63,7 +63,7 @@ class RemoveUserTest extends TestCase {
$this->invokePrivate($this->command, 'execute', [$this->input, $this->output]);
}
- public function testNoUser() {
+ public function testNoUser(): void {
$group = $this->createMock(IGroup::class);
$this->groupManager->method('get')
->with('myGroup')
@@ -80,7 +80,7 @@ class RemoveUserTest extends TestCase {
$this->invokePrivate($this->command, 'execute', [$this->input, $this->output]);
}
- public function testAdd() {
+ public function testAdd(): void {
$group = $this->createMock(IGroup::class);
$this->groupManager->method('get')
->with('myGroup')
diff --git a/tests/Core/Command/Log/FileTest.php b/tests/Core/Command/Log/FileTest.php
index 35db7c6d718..08ff01e019d 100644
--- a/tests/Core/Command/Log/FileTest.php
+++ b/tests/Core/Command/Log/FileTest.php
@@ -36,7 +36,7 @@ class FileTest extends TestCase {
$this->command = new File($config);
}
- public function testEnable() {
+ public function testEnable(): void {
$this->config->method('getSystemValue')->willReturnArgument(1);
$this->consoleInput->method('getOption')
->willReturnMap([
@@ -49,7 +49,7 @@ class FileTest extends TestCase {
self::invokePrivate($this->command, 'execute', [$this->consoleInput, $this->consoleOutput]);
}
- public function testChangeFile() {
+ public function testChangeFile(): void {
$this->config->method('getSystemValue')->willReturnArgument(1);
$this->consoleInput->method('getOption')
->willReturnMap([
@@ -74,7 +74,7 @@ class FileTest extends TestCase {
/**
* @dataProvider changeRotateSizeProvider
*/
- public function testChangeRotateSize($optionValue, $configValue) {
+ public function testChangeRotateSize($optionValue, $configValue): void {
$this->config->method('getSystemValue')->willReturnArgument(1);
$this->consoleInput->method('getOption')
->willReturnMap([
@@ -87,7 +87,7 @@ class FileTest extends TestCase {
self::invokePrivate($this->command, 'execute', [$this->consoleInput, $this->consoleOutput]);
}
- public function testGetConfiguration() {
+ public function testGetConfiguration(): void {
$this->config->method('getSystemValue')
->willReturnMap([
['log_type', 'file', 'log_type_value'],
diff --git a/tests/Core/Command/Log/ManageTest.php b/tests/Core/Command/Log/ManageTest.php
index 5cba6dd626f..b354bb17076 100644
--- a/tests/Core/Command/Log/ManageTest.php
+++ b/tests/Core/Command/Log/ManageTest.php
@@ -36,7 +36,7 @@ class ManageTest extends TestCase {
$this->command = new Manage($config);
}
- public function testChangeBackend() {
+ public function testChangeBackend(): void {
$this->consoleInput->method('getOption')
->willReturnMap([
['backend', 'syslog']
@@ -48,7 +48,7 @@ class ManageTest extends TestCase {
self::invokePrivate($this->command, 'execute', [$this->consoleInput, $this->consoleOutput]);
}
- public function testChangeLevel() {
+ public function testChangeLevel(): void {
$this->consoleInput->method('getOption')
->willReturnMap([
['level', 'debug']
@@ -60,7 +60,7 @@ class ManageTest extends TestCase {
self::invokePrivate($this->command, 'execute', [$this->consoleInput, $this->consoleOutput]);
}
- public function testChangeTimezone() {
+ public function testChangeTimezone(): void {
$this->consoleInput->method('getOption')
->willReturnMap([
['timezone', 'UTC']
@@ -73,14 +73,14 @@ class ManageTest extends TestCase {
}
- public function testValidateBackend() {
+ public function testValidateBackend(): void {
$this->expectException(\InvalidArgumentException::class);
self::invokePrivate($this->command, 'validateBackend', ['notabackend']);
}
- public function testValidateTimezone() {
+ public function testValidateTimezone(): void {
$this->expectException(\Exception::class);
// this might need to be changed when humanity colonises Mars
@@ -102,14 +102,14 @@ class ManageTest extends TestCase {
/**
* @dataProvider convertLevelStringProvider
*/
- public function testConvertLevelString($levelString, $expectedInt) {
+ public function testConvertLevelString($levelString, $expectedInt): void {
$this->assertEquals($expectedInt,
self::invokePrivate($this->command, 'convertLevelString', [$levelString])
);
}
- public function testConvertLevelStringInvalid() {
+ public function testConvertLevelStringInvalid(): void {
$this->expectException(\InvalidArgumentException::class);
self::invokePrivate($this->command, 'convertLevelString', ['abc']);
@@ -128,20 +128,20 @@ class ManageTest extends TestCase {
/**
* @dataProvider convertLevelNumberProvider
*/
- public function testConvertLevelNumber($levelNum, $expectedString) {
+ public function testConvertLevelNumber($levelNum, $expectedString): void {
$this->assertEquals($expectedString,
self::invokePrivate($this->command, 'convertLevelNumber', [$levelNum])
);
}
- public function testConvertLevelNumberInvalid() {
+ public function testConvertLevelNumberInvalid(): void {
$this->expectException(\InvalidArgumentException::class);
self::invokePrivate($this->command, 'convertLevelNumber', [11]);
}
- public function testGetConfiguration() {
+ public function testGetConfiguration(): void {
$this->config->expects($this->exactly(3))
->method('getSystemValue')
->withConsecutive(
diff --git a/tests/Core/Command/Maintenance/DataFingerprintTest.php b/tests/Core/Command/Maintenance/DataFingerprintTest.php
index 03cf37b8f48..3d56d891bef 100644
--- a/tests/Core/Command/Maintenance/DataFingerprintTest.php
+++ b/tests/Core/Command/Maintenance/DataFingerprintTest.php
@@ -39,7 +39,7 @@ class DataFingerprintTest extends TestCase {
$this->command = new DataFingerprint($this->config, $this->timeFactory);
}
- public function testSetFingerPrint() {
+ public function testSetFingerPrint(): void {
$this->timeFactory->expects($this->once())
->method('getTime')
->willReturn(42);
diff --git a/tests/Core/Command/Maintenance/Mimetype/UpdateDBTest.php b/tests/Core/Command/Maintenance/Mimetype/UpdateDBTest.php
index a4169907167..d8c82de19ac 100644
--- a/tests/Core/Command/Maintenance/Mimetype/UpdateDBTest.php
+++ b/tests/Core/Command/Maintenance/Mimetype/UpdateDBTest.php
@@ -46,7 +46,7 @@ class UpdateDBTest extends TestCase {
$this->command = new UpdateDB($this->detector, $this->loader);
}
- public function testNoop() {
+ public function testNoop(): void {
$this->consoleInput->method('getOption')
->with('repair-filecache')
->willReturn(false);
@@ -74,7 +74,7 @@ class UpdateDBTest extends TestCase {
self::invokePrivate($this->command, 'execute', [$this->consoleInput, $this->consoleOutput]);
}
- public function testAddMimetype() {
+ public function testAddMimetype(): void {
$this->consoleInput->method('getOption')
->with('repair-filecache')
->willReturn(false);
@@ -115,7 +115,7 @@ class UpdateDBTest extends TestCase {
self::invokePrivate($this->command, 'execute', [$this->consoleInput, $this->consoleOutput]);
}
- public function testSkipComments() {
+ public function testSkipComments(): void {
$this->detector->expects($this->once())
->method('getAllMappings')
->willReturn([
@@ -127,7 +127,7 @@ class UpdateDBTest extends TestCase {
self::invokePrivate($this->command, 'execute', [$this->consoleInput, $this->consoleOutput]);
}
- public function testRepairFilecache() {
+ public function testRepairFilecache(): void {
$this->consoleInput->method('getOption')
->with('repair-filecache')
->willReturn(true);
diff --git a/tests/Core/Command/Maintenance/ModeTest.php b/tests/Core/Command/Maintenance/ModeTest.php
index 08ca1762da1..59b8bbfc045 100644
--- a/tests/Core/Command/Maintenance/ModeTest.php
+++ b/tests/Core/Command/Maintenance/ModeTest.php
@@ -124,7 +124,7 @@ class ModeTest extends TestCase {
bool $currentMaintenanceState,
$expectedMaintenanceState,
string $expectedOutput
- ) {
+ ): void {
$this->config->expects($this->any())
->method('getSystemValueBool')
->willReturn($currentMaintenanceState);
diff --git a/tests/Core/Command/Maintenance/UpdateTheme.php b/tests/Core/Command/Maintenance/UpdateTheme.php
index 25229b8997a..41b95d358d3 100644
--- a/tests/Core/Command/Maintenance/UpdateTheme.php
+++ b/tests/Core/Command/Maintenance/UpdateTheme.php
@@ -42,7 +42,7 @@ class UpdateThemeTest extends TestCase {
$this->command = new UpdateTheme($this->detector, $this->cacheFactory);
}
- public function testThemeUpdate() {
+ public function testThemeUpdate(): void {
$this->consoleInput->method('getOption')
->with('maintenance:theme:update')
->willReturn(true);
diff --git a/tests/Core/Command/Preview/RepairTest.php b/tests/Core/Command/Preview/RepairTest.php
index 4717ee05f09..e54f4dde3ad 100644
--- a/tests/Core/Command/Preview/RepairTest.php
+++ b/tests/Core/Command/Preview/RepairTest.php
@@ -116,7 +116,7 @@ class RepairTest extends TestCase {
/**
* @dataProvider emptyTestDataProvider
*/
- public function testEmptyExecute($directoryNames, $expectedOutput) {
+ public function testEmptyExecute($directoryNames, $expectedOutput): void {
$previewFolder = $this->getMockBuilder(Folder::class)
->getMock();
$directories = array_map(function ($element) {
diff --git a/tests/Core/Command/SystemTag/AddTest.php b/tests/Core/Command/SystemTag/AddTest.php
index 921b875dc4e..4dd0df7ffe0 100644
--- a/tests/Core/Command/SystemTag/AddTest.php
+++ b/tests/Core/Command/SystemTag/AddTest.php
@@ -40,7 +40,7 @@ class AddTest extends TestCase {
$this->output = $this->createMock(OutputInterface::class);
}
- public function testExecute() {
+ public function testExecute(): void {
$tagId = '42';
$tagName = 'wichtig';
$tagAccess = 'public';
@@ -82,7 +82,7 @@ class AddTest extends TestCase {
$this->invokePrivate($this->command, 'execute', [$this->input, $this->output]);
}
- public function testAlreadyExists() {
+ public function testAlreadyExists(): void {
$tagId = '42';
$tagName = 'wichtig';
$tagAccess = 'public';
diff --git a/tests/Core/Command/SystemTag/DeleteTest.php b/tests/Core/Command/SystemTag/DeleteTest.php
index a2ec3767272..78d073db6d6 100644
--- a/tests/Core/Command/SystemTag/DeleteTest.php
+++ b/tests/Core/Command/SystemTag/DeleteTest.php
@@ -39,7 +39,7 @@ class DeleteTest extends TestCase {
$this->output = $this->createMock(OutputInterface::class);
}
- public function testExecute() {
+ public function testExecute(): void {
$tagId = 69;
$this->input->method('getArgument')
@@ -57,7 +57,7 @@ class DeleteTest extends TestCase {
$this->invokePrivate($this->command, 'execute', [$this->input, $this->output]);
}
- public function testNotFound() {
+ public function testNotFound(): void {
$tagId = 69;
$this->input->method('getArgument')
diff --git a/tests/Core/Command/SystemTag/EditTest.php b/tests/Core/Command/SystemTag/EditTest.php
index 90a7df00753..1857da25ab0 100644
--- a/tests/Core/Command/SystemTag/EditTest.php
+++ b/tests/Core/Command/SystemTag/EditTest.php
@@ -40,7 +40,7 @@ class EditTest extends TestCase {
$this->output = $this->createMock(OutputInterface::class);
}
- public function testExecute() {
+ public function testExecute(): void {
$tagId = '5';
$tagName = 'unwichtige Dateien';
$newTagName = 'moderat wichtige Dateien';
@@ -93,7 +93,7 @@ class EditTest extends TestCase {
$this->invokePrivate($this->command, 'execute', [$this->input, $this->output]);
}
- public function testAlreadyExists() {
+ public function testAlreadyExists(): void {
$tagId = '5';
$tagName = 'unwichtige Dateien';
$tagUserVisible = false;
@@ -157,7 +157,7 @@ class EditTest extends TestCase {
$this->invokePrivate($this->command, 'execute', [$this->input, $this->output]);
}
- public function testNotFound() {
+ public function testNotFound(): void {
$tagId = '404';
$this->input->method('getArgument')
diff --git a/tests/Core/Command/SystemTag/ListCommandTest.php b/tests/Core/Command/SystemTag/ListCommandTest.php
index c7e213a782c..9f4c4072ffc 100644
--- a/tests/Core/Command/SystemTag/ListCommandTest.php
+++ b/tests/Core/Command/SystemTag/ListCommandTest.php
@@ -39,7 +39,7 @@ class ListCommandTest extends TestCase {
$this->output = $this->createMock(OutputInterface::class);
}
- public function testExecute() {
+ public function testExecute(): void {
$tag1 = $this->createMock(ISystemTag::class);
$tag1->method('getId')->willReturn('1');
$tag1->method('getName')->willReturn('public_tag');
diff --git a/tests/Core/Command/TwoFactorAuth/CleanupTest.php b/tests/Core/Command/TwoFactorAuth/CleanupTest.php
index 040bc08a858..1d4731ff0c2 100644
--- a/tests/Core/Command/TwoFactorAuth/CleanupTest.php
+++ b/tests/Core/Command/TwoFactorAuth/CleanupTest.php
@@ -36,7 +36,7 @@ class CleanupTest extends TestCase {
$this->cmd = new CommandTester($cmd);
}
- public function testCleanup() {
+ public function testCleanup(): void {
$this->registry->expects($this->once())
->method('cleanUp')
->with('u2f');
diff --git a/tests/Core/Command/TwoFactorAuth/DisableTest.php b/tests/Core/Command/TwoFactorAuth/DisableTest.php
index b123d09848a..ab6b10f8964 100644
--- a/tests/Core/Command/TwoFactorAuth/DisableTest.php
+++ b/tests/Core/Command/TwoFactorAuth/DisableTest.php
@@ -37,7 +37,7 @@ class DisableTest extends TestCase {
$this->command = new CommandTester($cmd);
}
- public function testInvalidUID() {
+ public function testInvalidUID(): void {
$this->userManager->expects($this->once())
->method('get')
->with('nope')
@@ -52,7 +52,7 @@ class DisableTest extends TestCase {
$this->assertStringContainsString('Invalid UID', $this->command->getDisplay());
}
- public function testEnableNotSupported() {
+ public function testEnableNotSupported(): void {
$user = $this->createMock(IUser::class);
$this->userManager->expects($this->once())
->method('get')
@@ -72,7 +72,7 @@ class DisableTest extends TestCase {
$this->assertStringContainsString('The provider does not support this operation', $this->command->getDisplay());
}
- public function testEnabled() {
+ public function testEnabled(): void {
$user = $this->createMock(IUser::class);
$this->userManager->expects($this->once())
->method('get')
diff --git a/tests/Core/Command/TwoFactorAuth/EnableTest.php b/tests/Core/Command/TwoFactorAuth/EnableTest.php
index f78085e72a1..7c34d6692c5 100644
--- a/tests/Core/Command/TwoFactorAuth/EnableTest.php
+++ b/tests/Core/Command/TwoFactorAuth/EnableTest.php
@@ -37,7 +37,7 @@ class EnableTest extends TestCase {
$this->command = new CommandTester($cmd);
}
- public function testInvalidUID() {
+ public function testInvalidUID(): void {
$this->userManager->expects($this->once())
->method('get')
->with('nope')
@@ -52,7 +52,7 @@ class EnableTest extends TestCase {
$this->assertStringContainsString('Invalid UID', $this->command->getDisplay());
}
- public function testEnableNotSupported() {
+ public function testEnableNotSupported(): void {
$user = $this->createMock(IUser::class);
$this->userManager->expects($this->once())
->method('get')
@@ -72,7 +72,7 @@ class EnableTest extends TestCase {
$this->assertStringContainsString('The provider does not support this operation', $this->command->getDisplay());
}
- public function testEnabled() {
+ public function testEnabled(): void {
$user = $this->createMock(IUser::class);
$this->userManager->expects($this->once())
->method('get')
diff --git a/tests/Core/Command/TwoFactorAuth/EnforceTest.php b/tests/Core/Command/TwoFactorAuth/EnforceTest.php
index e709ca2c55a..03118772377 100644
--- a/tests/Core/Command/TwoFactorAuth/EnforceTest.php
+++ b/tests/Core/Command/TwoFactorAuth/EnforceTest.php
@@ -32,7 +32,7 @@ class EnforceTest extends TestCase {
$this->command = new CommandTester($command);
}
- public function testEnforce() {
+ public function testEnforce(): void {
$this->mandatoryTwoFactor->expects($this->once())
->method('setState')
->with($this->equalTo(new EnforcementState(true)));
@@ -49,7 +49,7 @@ class EnforceTest extends TestCase {
$this->assertStringContainsString('Two-factor authentication is enforced for all users', $display);
}
- public function testEnforceForOneGroup() {
+ public function testEnforceForOneGroup(): void {
$this->mandatoryTwoFactor->expects($this->once())
->method('setState')
->with($this->equalTo(new EnforcementState(true, ['twofactorers'])));
@@ -67,7 +67,7 @@ class EnforceTest extends TestCase {
$this->assertStringContainsString('Two-factor authentication is enforced for members of the group(s) twofactorers', $display);
}
- public function testEnforceForAllExceptOneGroup() {
+ public function testEnforceForAllExceptOneGroup(): void {
$this->mandatoryTwoFactor->expects($this->once())
->method('setState')
->with($this->equalTo(new EnforcementState(true, [], ['yoloers'])));
@@ -85,7 +85,7 @@ class EnforceTest extends TestCase {
$this->assertStringContainsString('Two-factor authentication is enforced for all users, except members of yoloers', $display);
}
- public function testDisableEnforced() {
+ public function testDisableEnforced(): void {
$this->mandatoryTwoFactor->expects($this->once())
->method('setState')
->with(new EnforcementState(false));
@@ -102,7 +102,7 @@ class EnforceTest extends TestCase {
$this->assertStringContainsString('Two-factor authentication is not enforced', $display);
}
- public function testCurrentStateEnabled() {
+ public function testCurrentStateEnabled(): void {
$this->mandatoryTwoFactor->expects($this->once())
->method('getState')
->willReturn(new EnforcementState(true));
@@ -114,7 +114,7 @@ class EnforceTest extends TestCase {
$this->assertStringContainsString('Two-factor authentication is enforced for all users', $display);
}
- public function testCurrentStateDisabled() {
+ public function testCurrentStateDisabled(): void {
$this->mandatoryTwoFactor->expects($this->once())
->method('getState')
->willReturn(new EnforcementState(false));
diff --git a/tests/Core/Command/TwoFactorAuth/StateTest.php b/tests/Core/Command/TwoFactorAuth/StateTest.php
index 1d97d152a21..f4ca3c4e031 100644
--- a/tests/Core/Command/TwoFactorAuth/StateTest.php
+++ b/tests/Core/Command/TwoFactorAuth/StateTest.php
@@ -37,7 +37,7 @@ class StateTest extends TestCase {
$this->cmd = new CommandTester($cmd);
}
- public function testWrongUID() {
+ public function testWrongUID(): void {
$this->cmd->execute([
'uid' => 'nope',
]);
@@ -46,7 +46,7 @@ class StateTest extends TestCase {
$this->assertStringContainsString('Invalid UID', $output);
}
- public function testStateNoProvidersActive() {
+ public function testStateNoProvidersActive(): void {
$user = $this->createMock(IUser::class);
$this->userManager->expects($this->once())
->method('get')
@@ -69,7 +69,7 @@ class StateTest extends TestCase {
$this->assertStringContainsString('Two-factor authentication is not enabled for user eldora', $output);
}
- public function testStateOneProviderActive() {
+ public function testStateOneProviderActive(): void {
$user = $this->createMock(IUser::class);
$this->userManager->expects($this->once())
->method('get')
diff --git a/tests/Core/Command/User/AuthTokens/DeleteTest.php b/tests/Core/Command/User/AuthTokens/DeleteTest.php
index bd82475b206..8588c1d5d54 100644
--- a/tests/Core/Command/User/AuthTokens/DeleteTest.php
+++ b/tests/Core/Command/User/AuthTokens/DeleteTest.php
@@ -37,7 +37,7 @@ class DeleteTest extends TestCase {
$this->command = new Delete($tokenProvider);
}
- public function testDeleteTokenById() {
+ public function testDeleteTokenById(): void {
$this->consoleInput->expects($this->exactly(2))
->method('getArgument')
->withConsecutive(['uid'], ['id'])
@@ -56,7 +56,7 @@ class DeleteTest extends TestCase {
$this->assertSame(Command::SUCCESS, $result);
}
- public function testDeleteTokenByIdRequiresTokenId() {
+ public function testDeleteTokenByIdRequiresTokenId(): void {
$this->consoleInput->expects($this->exactly(2))
->method('getArgument')
->withConsecutive(['uid'], ['id'])
@@ -75,7 +75,7 @@ class DeleteTest extends TestCase {
$this->assertSame(Command::FAILURE, $result);
}
- public function testDeleteTokensLastUsedBefore() {
+ public function testDeleteTokensLastUsedBefore(): void {
$this->consoleInput->expects($this->exactly(2))
->method('getArgument')
->withConsecutive(['uid'], ['id'])
@@ -94,7 +94,7 @@ class DeleteTest extends TestCase {
$this->assertSame(Command::SUCCESS, $result);
}
- public function testLastUsedBeforeAcceptsIso8601Expanded() {
+ public function testLastUsedBeforeAcceptsIso8601Expanded(): void {
$this->consoleInput->expects($this->exactly(2))
->method('getArgument')
->withConsecutive(['uid'], ['id'])
@@ -113,7 +113,7 @@ class DeleteTest extends TestCase {
$this->assertSame(Command::SUCCESS, $result);
}
- public function testLastUsedBeforeAcceptsYmd() {
+ public function testLastUsedBeforeAcceptsYmd(): void {
$this->consoleInput->expects($this->exactly(2))
->method('getArgument')
->withConsecutive(['uid'], ['id'])
@@ -132,7 +132,7 @@ class DeleteTest extends TestCase {
$this->assertSame(Command::SUCCESS, $result);
}
- public function testIdAndLastUsedBeforeAreMutuallyExclusive() {
+ public function testIdAndLastUsedBeforeAreMutuallyExclusive(): void {
$this->consoleInput->expects($this->exactly(2))
->method('getArgument')
->withConsecutive(['uid'], ['id'])
diff --git a/tests/Core/Command/User/DeleteTest.php b/tests/Core/Command/User/DeleteTest.php
index 74b98b0246a..42244412d9f 100644
--- a/tests/Core/Command/User/DeleteTest.php
+++ b/tests/Core/Command/User/DeleteTest.php
@@ -52,7 +52,7 @@ class DeleteTest extends TestCase {
* @param bool $deleteSuccess
* @param string $expectedString
*/
- public function testValidUser($deleteSuccess, $expectedString) {
+ public function testValidUser($deleteSuccess, $expectedString): void {
$user = $this->getMockBuilder(IUser::class)->getMock();
$user->expects($this->once())
->method('delete')
@@ -75,7 +75,7 @@ class DeleteTest extends TestCase {
self::invokePrivate($this->command, 'execute', [$this->consoleInput, $this->consoleOutput]);
}
- public function testInvalidUser() {
+ public function testInvalidUser(): void {
$this->userManager->expects($this->once())
->method('get')
->with('user')
diff --git a/tests/Core/Command/User/DisableTest.php b/tests/Core/Command/User/DisableTest.php
index a080eb9379a..1e464ca93a5 100644
--- a/tests/Core/Command/User/DisableTest.php
+++ b/tests/Core/Command/User/DisableTest.php
@@ -34,7 +34,7 @@ class DisableTest extends TestCase {
$this->command = new Disable($this->userManager);
}
- public function testValidUser() {
+ public function testValidUser(): void {
$user = $this->createMock(IUser::class);
$user->expects($this->once())
->method('setEnabled')
@@ -57,7 +57,7 @@ class DisableTest extends TestCase {
self::invokePrivate($this->command, 'execute', [$this->consoleInput, $this->consoleOutput]);
}
- public function testInvalidUser() {
+ public function testInvalidUser(): void {
$this->userManager->expects($this->once())
->method('get')
->with('user')
diff --git a/tests/Core/Command/User/EnableTest.php b/tests/Core/Command/User/EnableTest.php
index 39af10f2ef3..b590530d93d 100644
--- a/tests/Core/Command/User/EnableTest.php
+++ b/tests/Core/Command/User/EnableTest.php
@@ -34,7 +34,7 @@ class EnableTest extends TestCase {
$this->command = new Enable($this->userManager);
}
- public function testValidUser() {
+ public function testValidUser(): void {
$user = $this->createMock(IUser::class);
$user->expects($this->once())
->method('setEnabled')
@@ -57,7 +57,7 @@ class EnableTest extends TestCase {
self::invokePrivate($this->command, 'execute', [$this->consoleInput, $this->consoleOutput]);
}
- public function testInvalidUser() {
+ public function testInvalidUser(): void {
$this->userManager->expects($this->once())
->method('get')
->with('user')
diff --git a/tests/Core/Command/User/LastSeenTest.php b/tests/Core/Command/User/LastSeenTest.php
index 1146c0664d4..014c981112e 100644
--- a/tests/Core/Command/User/LastSeenTest.php
+++ b/tests/Core/Command/User/LastSeenTest.php
@@ -51,7 +51,7 @@ class LastSeenTest extends TestCase {
* @param int $lastSeen
* @param string $expectedString
*/
- public function testValidUser($lastSeen, $expectedString) {
+ public function testValidUser($lastSeen, $expectedString): void {
$user = $this->getMockBuilder(IUser::class)->getMock();
$user->expects($this->once())
->method('getLastLogin')
@@ -74,7 +74,7 @@ class LastSeenTest extends TestCase {
self::invokePrivate($this->command, 'execute', [$this->consoleInput, $this->consoleOutput]);
}
- public function testInvalidUser() {
+ public function testInvalidUser(): void {
$this->userManager->expects($this->once())
->method('get')
->with('user')
diff --git a/tests/Core/Command/User/SettingTest.php b/tests/Core/Command/User/SettingTest.php
index 818b23af713..8c0edc46e72 100644
--- a/tests/Core/Command/User/SettingTest.php
+++ b/tests/Core/Command/User/SettingTest.php
@@ -185,7 +185,7 @@ class SettingTest extends TestCase {
* @param mixed $user
* @param string $expectedException
*/
- public function testCheckInput($arguments, $options, $parameterOptions, $user, $expectedException) {
+ public function testCheckInput($arguments, $options, $parameterOptions, $user, $expectedException): void {
$this->consoleInput->expects($this->any())
->method('getArgument')
->willReturnMap($arguments);
@@ -214,7 +214,7 @@ class SettingTest extends TestCase {
}
}
- public function testCheckInputExceptionCatch() {
+ public function testCheckInputExceptionCatch(): void {
$command = $this->getCommand(['checkInput']);
$command->expects($this->once())
->method('checkInput')
@@ -244,7 +244,7 @@ class SettingTest extends TestCase {
* @param string $expectedLine
* @param int $expectedReturn
*/
- public function testExecuteDelete($value, $errorIfNotExists, $expectedLine, $expectedReturn) {
+ public function testExecuteDelete($value, $errorIfNotExists, $expectedLine, $expectedReturn): void {
$command = $this->getCommand([
'writeArrayInOutputFormat',
'checkInput',
@@ -308,7 +308,7 @@ class SettingTest extends TestCase {
* @param string $expectedLine
* @param int $expectedReturn
*/
- public function testExecuteSet($value, $updateOnly, $expectedLine, $expectedReturn) {
+ public function testExecuteSet($value, $updateOnly, $expectedLine, $expectedReturn): void {
$command = $this->getCommand([
'writeArrayInOutputFormat',
'checkInput',
@@ -375,7 +375,7 @@ class SettingTest extends TestCase {
* @param string $expectedLine
* @param int $expectedReturn
*/
- public function testExecuteGet($value, $defaultValue, $expectedLine, $expectedReturn) {
+ public function testExecuteGet($value, $defaultValue, $expectedLine, $expectedReturn): void {
$command = $this->getCommand([
'writeArrayInOutputFormat',
'checkInput',
@@ -425,7 +425,7 @@ class SettingTest extends TestCase {
$this->assertEquals($expectedReturn, $this->invokePrivate($command, 'execute', [$this->consoleInput, $this->consoleOutput]));
}
- public function testExecuteList() {
+ public function testExecuteList(): void {
$command = $this->getCommand([
'writeArrayInOutputFormat',
'checkInput',
diff --git a/tests/Core/Controller/AppPasswordControllerTest.php b/tests/Core/Controller/AppPasswordControllerTest.php
index 6b7b023ab2e..f0246561145 100644
--- a/tests/Core/Controller/AppPasswordControllerTest.php
+++ b/tests/Core/Controller/AppPasswordControllerTest.php
@@ -86,7 +86,7 @@ class AppPasswordControllerTest extends TestCase {
);
}
- public function testGetAppPasswordWithAppPassword() {
+ public function testGetAppPasswordWithAppPassword(): void {
$this->session->method('exists')
->with('app_password')
->willReturn(true);
@@ -96,7 +96,7 @@ class AppPasswordControllerTest extends TestCase {
$this->controller->getAppPassword();
}
- public function testGetAppPasswordNoLoginCreds() {
+ public function testGetAppPasswordNoLoginCreds(): void {
$this->session->method('exists')
->with('app_password')
->willReturn(false);
@@ -108,7 +108,7 @@ class AppPasswordControllerTest extends TestCase {
$this->controller->getAppPassword();
}
- public function testGetAppPassword() {
+ public function testGetAppPassword(): void {
$credentials = $this->createMock(ICredentials::class);
$this->session->method('exists')
@@ -149,7 +149,7 @@ class AppPasswordControllerTest extends TestCase {
$this->controller->getAppPassword();
}
- public function testGetAppPasswordNoPassword() {
+ public function testGetAppPasswordNoPassword(): void {
$credentials = $this->createMock(ICredentials::class);
$this->session->method('exists')
@@ -190,7 +190,7 @@ class AppPasswordControllerTest extends TestCase {
$this->controller->getAppPassword();
}
- public function testDeleteAppPasswordNoAppPassword() {
+ public function testDeleteAppPasswordNoAppPassword(): void {
$this->session->method('exists')
->with('app_password')
->willReturn(false);
@@ -200,7 +200,7 @@ class AppPasswordControllerTest extends TestCase {
$this->controller->deleteAppPassword();
}
- public function testDeleteAppPasswordFails() {
+ public function testDeleteAppPasswordFails(): void {
$this->session->method('exists')
->with('app_password')
->willReturn(true);
@@ -217,7 +217,7 @@ class AppPasswordControllerTest extends TestCase {
$this->controller->deleteAppPassword();
}
- public function testDeleteAppPasswordSuccess() {
+ public function testDeleteAppPasswordSuccess(): void {
$this->session->method('exists')
->with('app_password')
->willReturn(true);
diff --git a/tests/Core/Controller/AutoCompleteControllerTest.php b/tests/Core/Controller/AutoCompleteControllerTest.php
index 2b82342276b..23bd03be7af 100644
--- a/tests/Core/Controller/AutoCompleteControllerTest.php
+++ b/tests/Core/Controller/AutoCompleteControllerTest.php
@@ -156,7 +156,7 @@ class AutoCompleteControllerTest extends TestCase {
/**
* @dataProvider searchDataProvider
*/
- public function testGet(array $searchResults, array $expected, string $searchTerm, ?string $itemType, ?string $itemId, ?string $sorter) {
+ public function testGet(array $searchResults, array $expected, string $searchTerm, ?string $itemType, ?string $itemId, ?string $sorter): void {
$this->collaboratorSearch->expects($this->once())
->method('search')
->willReturn([$searchResults, false]);
diff --git a/tests/Core/Controller/AvatarControllerTest.php b/tests/Core/Controller/AvatarControllerTest.php
index a1b0168dcd2..ac9a6d33488 100644
--- a/tests/Core/Controller/AvatarControllerTest.php
+++ b/tests/Core/Controller/AvatarControllerTest.php
@@ -1,566 +1,566 @@
-<?php
-/**
- * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
- * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
- * SPDX-License-Identifier: AGPL-3.0-only
- */
-
-namespace OC\Core\Controller;
-
-/**
- * Overwrite is_uploaded_file in the OC\Core\Controller namespace to allow
- * proper unit testing of the postAvatar call.
- */
-function is_uploaded_file($filename) {
- return file_exists($filename);
-}
-
-namespace Tests\Core\Controller;
-
-use OC\AppFramework\Utility\TimeFactory;
-use OC\Core\Controller\AvatarController;
-use OC\Core\Controller\GuestAvatarController;
-use OCP\AppFramework\Http;
-use OCP\Files\File;
-use OCP\Files\IRootFolder;
-use OCP\Files\NotFoundException;
-use OCP\Files\NotPermittedException;
-use OCP\Files\SimpleFS\ISimpleFile;
-use OCP\IAvatar;
-use OCP\IAvatarManager;
-use OCP\ICache;
-use OCP\IL10N;
-use OCP\IRequest;
-use OCP\IUser;
-use OCP\IUserManager;
-use Psr\Log\LoggerInterface;
-
-/**
- * Class AvatarControllerTest
- *
- * @package OC\Core\Controller
- */
-class AvatarControllerTest extends \Test\TestCase {
- /** @var AvatarController */
- private $avatarController;
- /** @var GuestAvatarController */
- private $guestAvatarController;
-
- /** @var IAvatar|\PHPUnit\Framework\MockObject\MockObject */
- private $avatarMock;
- /** @var IUser|\PHPUnit\Framework\MockObject\MockObject */
- private $userMock;
- /** @var ISimpleFile|\PHPUnit\Framework\MockObject\MockObject */
- private $avatarFile;
- /** @var IAvatarManager|\PHPUnit\Framework\MockObject\MockObject */
- private $avatarManager;
- /** @var ICache|\PHPUnit\Framework\MockObject\MockObject */
- private $cache;
- /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject */
- private $l;
- /** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */
- private $userManager;
- /** @var IRootFolder|\PHPUnit\Framework\MockObject\MockObject */
- private $rootFolder;
- /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */
- private $logger;
- /** @var IRequest|\PHPUnit\Framework\MockObject\MockObject */
- private $request;
- /** @var TimeFactory|\PHPUnit\Framework\MockObject\MockObject */
- private $timeFactory;
-
- protected function setUp(): void {
- parent::setUp();
-
- $this->avatarManager = $this->getMockBuilder(\OCP\IAvatarManager::class)->getMock();
- $this->cache = $this->getMockBuilder(\OCP\ICache::class)
- ->disableOriginalConstructor()->getMock();
- $this->l = $this->getMockBuilder(IL10N::class)->getMock();
- $this->l->method('t')->willReturnArgument(0);
- $this->userManager = $this->getMockBuilder(IUserManager::class)->getMock();
- $this->request = $this->getMockBuilder(IRequest::class)->getMock();
- $this->rootFolder = $this->getMockBuilder(\OCP\Files\IRootFolder::class)->getMock();
- $this->logger = $this->getMockBuilder(LoggerInterface::class)->getMock();
- $this->timeFactory = $this->getMockBuilder(\OC\AppFramework\Utility\TimeFactory::class)->getMock();
-
- $this->avatarMock = $this->getMockBuilder(\OCP\IAvatar::class)->getMock();
- $this->userMock = $this->getMockBuilder(IUser::class)->getMock();
-
- $this->guestAvatarController = new GuestAvatarController(
- 'core',
- $this->request,
- $this->avatarManager,
- $this->logger
- );
-
- $this->avatarController = new AvatarController(
- 'core',
- $this->request,
- $this->avatarManager,
- $this->cache,
- $this->l,
- $this->userManager,
- $this->rootFolder,
- $this->logger,
- 'userid',
- $this->timeFactory,
- $this->guestAvatarController,
- );
-
- // Configure userMock
- $this->userMock->method('getDisplayName')->willReturn('displayName');
- $this->userMock->method('getUID')->willReturn('userId');
- $this->userManager->method('get')
- ->willReturnMap([['userId', $this->userMock]]);
-
- $this->avatarFile = $this->getMockBuilder(ISimpleFile::class)->getMock();
- $this->avatarFile->method('getContent')->willReturn('image data');
- $this->avatarFile->method('getMimeType')->willReturn('image type');
- $this->avatarFile->method('getEtag')->willReturn('my etag');
- $this->avatarFile->method('getName')->willReturn('my name');
- $this->avatarFile->method('getMTime')->willReturn(42);
- }
-
- protected function tearDown(): void {
- parent::tearDown();
- }
-
- /**
- * Fetch an avatar if a user has no avatar
- */
- public function testGetAvatarNoAvatar() {
- $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
- $this->avatarMock->method('getFile')->will($this->throwException(new NotFoundException()));
- $response = $this->avatarController->getAvatar('userId', 32);
-
- //Comment out until JS is fixed
- $this->assertEquals(Http::STATUS_NOT_FOUND, $response->getStatus());
- }
-
- /**
- * Fetch the user's avatar
- */
- public function testGetAvatar() {
- $this->avatarMock->method('getFile')->willReturn($this->avatarFile);
- $this->avatarManager->method('getAvatar')->with('userId')->willReturn($this->avatarMock);
- $this->avatarMock->expects($this->once())
- ->method('isCustomAvatar')
- ->willReturn(true);
-
- $response = $this->avatarController->getAvatar('userId', 32);
-
- $this->assertEquals(Http::STATUS_OK, $response->getStatus());
- $this->assertArrayHasKey('Content-Type', $response->getHeaders());
- $this->assertEquals('image type', $response->getHeaders()['Content-Type']);
- $this->assertArrayHasKey('X-NC-IsCustomAvatar', $response->getHeaders());
- $this->assertEquals('1', $response->getHeaders()['X-NC-IsCustomAvatar']);
-
- $this->assertEquals('my etag', $response->getETag());
- }
-
- /**
- * Fetch the user's avatar
- */
- public function testGetGeneratedAvatar() {
- $this->avatarMock->method('getFile')->willReturn($this->avatarFile);
- $this->avatarManager->method('getAvatar')->with('userId')->willReturn($this->avatarMock);
-
- $response = $this->avatarController->getAvatar('userId', 32);
-
- $this->assertEquals(Http::STATUS_OK, $response->getStatus());
- $this->assertArrayHasKey('Content-Type', $response->getHeaders());
- $this->assertEquals('image type', $response->getHeaders()['Content-Type']);
- $this->assertArrayHasKey('X-NC-IsCustomAvatar', $response->getHeaders());
- $this->assertEquals('0', $response->getHeaders()['X-NC-IsCustomAvatar']);
-
- $this->assertEquals('my etag', $response->getETag());
- }
-
- /**
- * Fetch the avatar of a non-existing user
- */
- public function testGetAvatarNoUser() {
- $this->avatarManager
- ->method('getAvatar')
- ->with('userDoesNotExist')
- ->will($this->throwException(new \Exception('user does not exist')));
-
- $response = $this->avatarController->getAvatar('userDoesNotExist', 32);
-
- //Comment out until JS is fixed
- $this->assertEquals(Http::STATUS_NOT_FOUND, $response->getStatus());
- }
-
- public function testGetAvatarSize64(): void {
- $this->avatarMock->expects($this->once())
- ->method('getFile')
- ->with($this->equalTo(64))
- ->willReturn($this->avatarFile);
-
- $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
-
- $this->logger->expects($this->never())
- ->method('debug');
-
- $this->avatarController->getAvatar('userId', 64);
- }
-
- public function testGetAvatarSize512(): void {
- $this->avatarMock->expects($this->once())
- ->method('getFile')
- ->with($this->equalTo(512))
- ->willReturn($this->avatarFile);
-
- $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
-
- $this->logger->expects($this->never())
- ->method('debug');
-
- $this->avatarController->getAvatar('userId', 512);
- }
-
- /**
- * Small sizes return 64 and generate a log
- */
- public function testGetAvatarSizeTooSmall(): void {
- $this->avatarMock->expects($this->once())
- ->method('getFile')
- ->with($this->equalTo(64))
- ->willReturn($this->avatarFile);
-
- $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
-
- $this->logger->expects($this->once())
- ->method('debug')
- ->with('Avatar requested in deprecated size 32');
-
- $this->avatarController->getAvatar('userId', 32);
- }
-
- /**
- * Avatars between 64 and 512 are upgraded to 512
- */
- public function testGetAvatarSizeBetween(): void {
- $this->avatarMock->expects($this->once())
- ->method('getFile')
- ->with($this->equalTo(512))
- ->willReturn($this->avatarFile);
-
- $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
-
- $this->logger->expects($this->once())
- ->method('debug')
- ->with('Avatar requested in deprecated size 65');
-
- $this->avatarController->getAvatar('userId', 65);
- }
-
- /**
- * We do not support avatars larger than 512
- */
- public function testGetAvatarSizeTooBig(): void {
- $this->avatarMock->expects($this->once())
- ->method('getFile')
- ->with($this->equalTo(512))
- ->willReturn($this->avatarFile);
-
- $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
-
- $this->logger->expects($this->once())
- ->method('debug')
- ->with('Avatar requested in deprecated size 513');
-
- $this->avatarController->getAvatar('userId', 513);
- }
-
- /**
- * Remove an avatar
- */
- public function testDeleteAvatar() {
- $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
-
- $response = $this->avatarController->deleteAvatar();
- $this->assertEquals(Http::STATUS_OK, $response->getStatus());
- }
-
- /**
- * Test what happens if the removing of the avatar fails
- */
- public function testDeleteAvatarException() {
- $this->avatarMock->method('remove')->will($this->throwException(new \Exception('foo')));
- $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
-
- $this->logger->expects($this->once())
- ->method('error')
- ->with('foo', ['exception' => new \Exception('foo'), 'app' => 'core']);
- $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_BAD_REQUEST);
- $this->assertEquals($expectedResponse, $this->avatarController->deleteAvatar());
- }
-
- /**
- * Trying to get a tmp avatar when it is not available. 404
- */
- public function testTmpAvatarNoTmp() {
- $response = $this->avatarController->getTmpAvatar();
- $this->assertEquals(Http::STATUS_NOT_FOUND, $response->getStatus());
- }
-
- /**
- * Fetch tmp avatar
- */
- public function testTmpAvatarValid() {
- $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
-
- $response = $this->avatarController->getTmpAvatar();
- $this->assertEquals(Http::STATUS_OK, $response->getStatus());
- }
-
-
- /**
- * When trying to post a new avatar a path or image should be posted.
- */
- public function testPostAvatarNoPathOrImage() {
- $response = $this->avatarController->postAvatar(null);
-
- $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus());
- }
-
- /**
- * Test a correct post of an avatar using POST
- */
- public function testPostAvatarFile() {
- //Create temp file
- $fileName = tempnam('', 'avatarTest');
- $copyRes = copy(\OC::$SERVERROOT.'/tests/data/testimage.jpg', $fileName);
- $this->assertTrue($copyRes);
-
- //Create file in cache
- $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
-
- //Create request return
- $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [filesize(\OC::$SERVERROOT.'/tests/data/testimage.jpg')]];
- $this->request->method('getUploadedFile')->willReturn($reqRet);
-
- $response = $this->avatarController->postAvatar(null);
-
- //On correct upload always respond with the notsquare message
- $this->assertEquals('notsquare', $response->getData()['data']);
-
- //File should be deleted
- $this->assertFalse(file_exists($fileName));
- }
-
- /**
- * Test invalid post os an avatar using POST
- */
- public function testPostAvatarInvalidFile() {
- //Create request return
- $reqRet = ['error' => [1], 'tmp_name' => ['foo']];
- $this->request->method('getUploadedFile')->willReturn($reqRet);
-
- $response = $this->avatarController->postAvatar(null);
-
- $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus());
- }
-
- /**
- * Check what happens when we upload a GIF
- */
- public function testPostAvatarFileGif() {
- //Create temp file
- $fileName = tempnam('', 'avatarTest');
- $copyRes = copy(\OC::$SERVERROOT.'/tests/data/testimage.gif', $fileName);
- $this->assertTrue($copyRes);
-
- //Create file in cache
- $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.gif'));
-
- //Create request return
- $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [filesize(\OC::$SERVERROOT.'/tests/data/testimage.gif')]];
- $this->request->method('getUploadedFile')->willReturn($reqRet);
-
- $response = $this->avatarController->postAvatar(null);
-
- $this->assertEquals('Unknown filetype', $response->getData()['data']['message']);
-
- //File should be deleted
- $this->assertFalse(file_exists($fileName));
- }
-
- /**
- * Test posting avatar from existing file
- */
- public function testPostAvatarFromFile() {
- //Mock node API call
- $file = $this->getMockBuilder(\OCP\Files\File::class)
- ->disableOriginalConstructor()->getMock();
- $file->expects($this->once())
- ->method('getContent')
- ->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
- $file->expects($this->once())
- ->method('getMimeType')
- ->willReturn('image/jpeg');
- $userFolder = $this->getMockBuilder(\OCP\Files\Folder::class)->getMock();
- $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder);
- $userFolder->method('get')->willReturn($file);
-
- //Create request return
- $response = $this->avatarController->postAvatar('avatar.jpg');
-
- //On correct upload always respond with the notsquare message
- $this->assertEquals('notsquare', $response->getData()['data']);
- }
-
- /**
- * Test posting avatar from existing folder
- */
- public function testPostAvatarFromNoFile() {
- $file = $this->getMockBuilder(\OCP\Files\Node::class)->getMock();
- $userFolder = $this->getMockBuilder(\OCP\Files\Folder::class)->getMock();
- $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder);
- $userFolder
- ->method('get')
- ->with('folder')
- ->willReturn($file);
-
- //Create request return
- $response = $this->avatarController->postAvatar('folder');
-
- //On correct upload always respond with the notsquare message
- $this->assertEquals(['data' => ['message' => 'Please select a file.']], $response->getData());
- }
-
- public function testPostAvatarInvalidType() {
- $file = $this->getMockBuilder(\OCP\Files\File::class)
- ->disableOriginalConstructor()->getMock();
- $file->expects($this->never())
- ->method('getContent');
- $file->expects($this->exactly(2))
- ->method('getMimeType')
- ->willReturn('text/plain');
- $userFolder = $this->getMockBuilder(\OCP\Files\Folder::class)->getMock();
- $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder);
- $userFolder->method('get')->willReturn($file);
-
- $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'The selected file is not an image.']], Http::STATUS_BAD_REQUEST);
- $this->assertEquals($expectedResponse, $this->avatarController->postAvatar('avatar.jpg'));
- }
-
- public function testPostAvatarNotPermittedException() {
- $file = $this->getMockBuilder(\OCP\Files\File::class)
- ->disableOriginalConstructor()->getMock();
- $file->expects($this->once())
- ->method('getContent')
- ->willThrowException(new NotPermittedException());
- $file->expects($this->once())
- ->method('getMimeType')
- ->willReturn('image/jpeg');
- $userFolder = $this->getMockBuilder(\OCP\Files\Folder::class)->getMock();
- $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder);
- $userFolder->method('get')->willReturn($file);
-
- $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'The selected file cannot be read.']], Http::STATUS_BAD_REQUEST);
- $this->assertEquals($expectedResponse, $this->avatarController->postAvatar('avatar.jpg'));
- }
-
- /**
- * Test what happens if the upload of the avatar fails
- */
- public function testPostAvatarException() {
- $this->cache->expects($this->once())
- ->method('set')
- ->will($this->throwException(new \Exception('foo')));
- $file = $this->getMockBuilder(\OCP\Files\File::class)
- ->disableOriginalConstructor()->getMock();
- $file->expects($this->once())
- ->method('getContent')
- ->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
- $file->expects($this->once())
- ->method('getMimeType')
- ->willReturn('image/jpeg');
- $userFolder = $this->getMockBuilder(\OCP\Files\Folder::class)->getMock();
- $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder);
- $userFolder->method('get')->willReturn($file);
-
- $this->logger->expects($this->once())
- ->method('error')
- ->with('foo', ['exception' => new \Exception('foo'), 'app' => 'core']);
- $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_OK);
- $this->assertEquals($expectedResponse, $this->avatarController->postAvatar('avatar.jpg'));
- }
-
-
- /**
- * Test invalid crop argument
- */
- public function testPostCroppedAvatarInvalidCrop() {
- $response = $this->avatarController->postCroppedAvatar([]);
-
- $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus());
- }
-
- /**
- * Test no tmp avatar to crop
- */
- public function testPostCroppedAvatarNoTmpAvatar() {
- $response = $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 10]);
-
- $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus());
- }
-
- /**
- * Test with non square crop
- */
- public function testPostCroppedAvatarNoSquareCrop() {
- $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
-
- $this->avatarMock->method('set')->will($this->throwException(new \OC\NotSquareException));
- $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
- $response = $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 11]);
-
- $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus());
- }
-
- /**
- * Check for proper reply on proper crop argument
- */
- public function testPostCroppedAvatarValidCrop() {
- $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
- $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
- $response = $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 10]);
-
- $this->assertEquals(Http::STATUS_OK, $response->getStatus());
- $this->assertEquals('success', $response->getData()['status']);
- }
-
- /**
- * Test what happens if the cropping of the avatar fails
- */
- public function testPostCroppedAvatarException() {
- $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
-
- $this->avatarMock->method('set')->will($this->throwException(new \Exception('foo')));
- $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
-
- $this->logger->expects($this->once())
- ->method('error')
- ->with('foo', ['exception' => new \Exception('foo'), 'app' => 'core']);
- $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_BAD_REQUEST);
- $this->assertEquals($expectedResponse, $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 11]));
- }
-
-
- /**
- * Check for proper reply on proper crop argument
- */
- public function testFileTooBig() {
- $fileName = \OC::$SERVERROOT.'/tests/data/testimage.jpg';
- //Create request return
- $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [21 * 1024 * 1024]];
- $this->request->method('getUploadedFile')->willReturn($reqRet);
-
- $response = $this->avatarController->postAvatar(null);
-
- $this->assertEquals('File is too big', $response->getData()['data']['message']);
- }
-}
+<?php
+/**
+ * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
+ */
+
+namespace OC\Core\Controller;
+
+/**
+ * Overwrite is_uploaded_file in the OC\Core\Controller namespace to allow
+ * proper unit testing of the postAvatar call.
+ */
+function is_uploaded_file($filename) {
+ return file_exists($filename);
+}
+
+namespace Tests\Core\Controller;
+
+use OC\AppFramework\Utility\TimeFactory;
+use OC\Core\Controller\AvatarController;
+use OC\Core\Controller\GuestAvatarController;
+use OCP\AppFramework\Http;
+use OCP\Files\File;
+use OCP\Files\IRootFolder;
+use OCP\Files\NotFoundException;
+use OCP\Files\NotPermittedException;
+use OCP\Files\SimpleFS\ISimpleFile;
+use OCP\IAvatar;
+use OCP\IAvatarManager;
+use OCP\ICache;
+use OCP\IL10N;
+use OCP\IRequest;
+use OCP\IUser;
+use OCP\IUserManager;
+use Psr\Log\LoggerInterface;
+
+/**
+ * Class AvatarControllerTest
+ *
+ * @package OC\Core\Controller
+ */
+class AvatarControllerTest extends \Test\TestCase {
+ /** @var AvatarController */
+ private $avatarController;
+ /** @var GuestAvatarController */
+ private $guestAvatarController;
+
+ /** @var IAvatar|\PHPUnit\Framework\MockObject\MockObject */
+ private $avatarMock;
+ /** @var IUser|\PHPUnit\Framework\MockObject\MockObject */
+ private $userMock;
+ /** @var ISimpleFile|\PHPUnit\Framework\MockObject\MockObject */
+ private $avatarFile;
+ /** @var IAvatarManager|\PHPUnit\Framework\MockObject\MockObject */
+ private $avatarManager;
+ /** @var ICache|\PHPUnit\Framework\MockObject\MockObject */
+ private $cache;
+ /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject */
+ private $l;
+ /** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */
+ private $userManager;
+ /** @var IRootFolder|\PHPUnit\Framework\MockObject\MockObject */
+ private $rootFolder;
+ /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */
+ private $logger;
+ /** @var IRequest|\PHPUnit\Framework\MockObject\MockObject */
+ private $request;
+ /** @var TimeFactory|\PHPUnit\Framework\MockObject\MockObject */
+ private $timeFactory;
+
+ protected function setUp(): void {
+ parent::setUp();
+
+ $this->avatarManager = $this->getMockBuilder(\OCP\IAvatarManager::class)->getMock();
+ $this->cache = $this->getMockBuilder(\OCP\ICache::class)
+ ->disableOriginalConstructor()->getMock();
+ $this->l = $this->getMockBuilder(IL10N::class)->getMock();
+ $this->l->method('t')->willReturnArgument(0);
+ $this->userManager = $this->getMockBuilder(IUserManager::class)->getMock();
+ $this->request = $this->getMockBuilder(IRequest::class)->getMock();
+ $this->rootFolder = $this->getMockBuilder(\OCP\Files\IRootFolder::class)->getMock();
+ $this->logger = $this->getMockBuilder(LoggerInterface::class)->getMock();
+ $this->timeFactory = $this->getMockBuilder(\OC\AppFramework\Utility\TimeFactory::class)->getMock();
+
+ $this->avatarMock = $this->getMockBuilder(\OCP\IAvatar::class)->getMock();
+ $this->userMock = $this->getMockBuilder(IUser::class)->getMock();
+
+ $this->guestAvatarController = new GuestAvatarController(
+ 'core',
+ $this->request,
+ $this->avatarManager,
+ $this->logger
+ );
+
+ $this->avatarController = new AvatarController(
+ 'core',
+ $this->request,
+ $this->avatarManager,
+ $this->cache,
+ $this->l,
+ $this->userManager,
+ $this->rootFolder,
+ $this->logger,
+ 'userid',
+ $this->timeFactory,
+ $this->guestAvatarController,
+ );
+
+ // Configure userMock
+ $this->userMock->method('getDisplayName')->willReturn('displayName');
+ $this->userMock->method('getUID')->willReturn('userId');
+ $this->userManager->method('get')
+ ->willReturnMap([['userId', $this->userMock]]);
+
+ $this->avatarFile = $this->getMockBuilder(ISimpleFile::class)->getMock();
+ $this->avatarFile->method('getContent')->willReturn('image data');
+ $this->avatarFile->method('getMimeType')->willReturn('image type');
+ $this->avatarFile->method('getEtag')->willReturn('my etag');
+ $this->avatarFile->method('getName')->willReturn('my name');
+ $this->avatarFile->method('getMTime')->willReturn(42);
+ }
+
+ protected function tearDown(): void {
+ parent::tearDown();
+ }
+
+ /**
+ * Fetch an avatar if a user has no avatar
+ */
+ public function testGetAvatarNoAvatar(): void {
+ $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
+ $this->avatarMock->method('getFile')->will($this->throwException(new NotFoundException()));
+ $response = $this->avatarController->getAvatar('userId', 32);
+
+ //Comment out until JS is fixed
+ $this->assertEquals(Http::STATUS_NOT_FOUND, $response->getStatus());
+ }
+
+ /**
+ * Fetch the user's avatar
+ */
+ public function testGetAvatar(): void {
+ $this->avatarMock->method('getFile')->willReturn($this->avatarFile);
+ $this->avatarManager->method('getAvatar')->with('userId')->willReturn($this->avatarMock);
+ $this->avatarMock->expects($this->once())
+ ->method('isCustomAvatar')
+ ->willReturn(true);
+
+ $response = $this->avatarController->getAvatar('userId', 32);
+
+ $this->assertEquals(Http::STATUS_OK, $response->getStatus());
+ $this->assertArrayHasKey('Content-Type', $response->getHeaders());
+ $this->assertEquals('image type', $response->getHeaders()['Content-Type']);
+ $this->assertArrayHasKey('X-NC-IsCustomAvatar', $response->getHeaders());
+ $this->assertEquals('1', $response->getHeaders()['X-NC-IsCustomAvatar']);
+
+ $this->assertEquals('my etag', $response->getETag());
+ }
+
+ /**
+ * Fetch the user's avatar
+ */
+ public function testGetGeneratedAvatar(): void {
+ $this->avatarMock->method('getFile')->willReturn($this->avatarFile);
+ $this->avatarManager->method('getAvatar')->with('userId')->willReturn($this->avatarMock);
+
+ $response = $this->avatarController->getAvatar('userId', 32);
+
+ $this->assertEquals(Http::STATUS_OK, $response->getStatus());
+ $this->assertArrayHasKey('Content-Type', $response->getHeaders());
+ $this->assertEquals('image type', $response->getHeaders()['Content-Type']);
+ $this->assertArrayHasKey('X-NC-IsCustomAvatar', $response->getHeaders());
+ $this->assertEquals('0', $response->getHeaders()['X-NC-IsCustomAvatar']);
+
+ $this->assertEquals('my etag', $response->getETag());
+ }
+
+ /**
+ * Fetch the avatar of a non-existing user
+ */
+ public function testGetAvatarNoUser(): void {
+ $this->avatarManager
+ ->method('getAvatar')
+ ->with('userDoesNotExist')
+ ->will($this->throwException(new \Exception('user does not exist')));
+
+ $response = $this->avatarController->getAvatar('userDoesNotExist', 32);
+
+ //Comment out until JS is fixed
+ $this->assertEquals(Http::STATUS_NOT_FOUND, $response->getStatus());
+ }
+
+ public function testGetAvatarSize64(): void {
+ $this->avatarMock->expects($this->once())
+ ->method('getFile')
+ ->with($this->equalTo(64))
+ ->willReturn($this->avatarFile);
+
+ $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
+
+ $this->logger->expects($this->never())
+ ->method('debug');
+
+ $this->avatarController->getAvatar('userId', 64);
+ }
+
+ public function testGetAvatarSize512(): void {
+ $this->avatarMock->expects($this->once())
+ ->method('getFile')
+ ->with($this->equalTo(512))
+ ->willReturn($this->avatarFile);
+
+ $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
+
+ $this->logger->expects($this->never())
+ ->method('debug');
+
+ $this->avatarController->getAvatar('userId', 512);
+ }
+
+ /**
+ * Small sizes return 64 and generate a log
+ */
+ public function testGetAvatarSizeTooSmall(): void {
+ $this->avatarMock->expects($this->once())
+ ->method('getFile')
+ ->with($this->equalTo(64))
+ ->willReturn($this->avatarFile);
+
+ $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
+
+ $this->logger->expects($this->once())
+ ->method('debug')
+ ->with('Avatar requested in deprecated size 32');
+
+ $this->avatarController->getAvatar('userId', 32);
+ }
+
+ /**
+ * Avatars between 64 and 512 are upgraded to 512
+ */
+ public function testGetAvatarSizeBetween(): void {
+ $this->avatarMock->expects($this->once())
+ ->method('getFile')
+ ->with($this->equalTo(512))
+ ->willReturn($this->avatarFile);
+
+ $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
+
+ $this->logger->expects($this->once())
+ ->method('debug')
+ ->with('Avatar requested in deprecated size 65');
+
+ $this->avatarController->getAvatar('userId', 65);
+ }
+
+ /**
+ * We do not support avatars larger than 512
+ */
+ public function testGetAvatarSizeTooBig(): void {
+ $this->avatarMock->expects($this->once())
+ ->method('getFile')
+ ->with($this->equalTo(512))
+ ->willReturn($this->avatarFile);
+
+ $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
+
+ $this->logger->expects($this->once())
+ ->method('debug')
+ ->with('Avatar requested in deprecated size 513');
+
+ $this->avatarController->getAvatar('userId', 513);
+ }
+
+ /**
+ * Remove an avatar
+ */
+ public function testDeleteAvatar(): void {
+ $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
+
+ $response = $this->avatarController->deleteAvatar();
+ $this->assertEquals(Http::STATUS_OK, $response->getStatus());
+ }
+
+ /**
+ * Test what happens if the removing of the avatar fails
+ */
+ public function testDeleteAvatarException(): void {
+ $this->avatarMock->method('remove')->will($this->throwException(new \Exception('foo')));
+ $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
+
+ $this->logger->expects($this->once())
+ ->method('error')
+ ->with('foo', ['exception' => new \Exception('foo'), 'app' => 'core']);
+ $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_BAD_REQUEST);
+ $this->assertEquals($expectedResponse, $this->avatarController->deleteAvatar());
+ }
+
+ /**
+ * Trying to get a tmp avatar when it is not available. 404
+ */
+ public function testTmpAvatarNoTmp(): void {
+ $response = $this->avatarController->getTmpAvatar();
+ $this->assertEquals(Http::STATUS_NOT_FOUND, $response->getStatus());
+ }
+
+ /**
+ * Fetch tmp avatar
+ */
+ public function testTmpAvatarValid(): void {
+ $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
+
+ $response = $this->avatarController->getTmpAvatar();
+ $this->assertEquals(Http::STATUS_OK, $response->getStatus());
+ }
+
+
+ /**
+ * When trying to post a new avatar a path or image should be posted.
+ */
+ public function testPostAvatarNoPathOrImage(): void {
+ $response = $this->avatarController->postAvatar(null);
+
+ $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus());
+ }
+
+ /**
+ * Test a correct post of an avatar using POST
+ */
+ public function testPostAvatarFile(): void {
+ //Create temp file
+ $fileName = tempnam('', 'avatarTest');
+ $copyRes = copy(\OC::$SERVERROOT.'/tests/data/testimage.jpg', $fileName);
+ $this->assertTrue($copyRes);
+
+ //Create file in cache
+ $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
+
+ //Create request return
+ $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [filesize(\OC::$SERVERROOT.'/tests/data/testimage.jpg')]];
+ $this->request->method('getUploadedFile')->willReturn($reqRet);
+
+ $response = $this->avatarController->postAvatar(null);
+
+ //On correct upload always respond with the notsquare message
+ $this->assertEquals('notsquare', $response->getData()['data']);
+
+ //File should be deleted
+ $this->assertFalse(file_exists($fileName));
+ }
+
+ /**
+ * Test invalid post os an avatar using POST
+ */
+ public function testPostAvatarInvalidFile(): void {
+ //Create request return
+ $reqRet = ['error' => [1], 'tmp_name' => ['foo']];
+ $this->request->method('getUploadedFile')->willReturn($reqRet);
+
+ $response = $this->avatarController->postAvatar(null);
+
+ $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus());
+ }
+
+ /**
+ * Check what happens when we upload a GIF
+ */
+ public function testPostAvatarFileGif(): void {
+ //Create temp file
+ $fileName = tempnam('', 'avatarTest');
+ $copyRes = copy(\OC::$SERVERROOT.'/tests/data/testimage.gif', $fileName);
+ $this->assertTrue($copyRes);
+
+ //Create file in cache
+ $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.gif'));
+
+ //Create request return
+ $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [filesize(\OC::$SERVERROOT.'/tests/data/testimage.gif')]];
+ $this->request->method('getUploadedFile')->willReturn($reqRet);
+
+ $response = $this->avatarController->postAvatar(null);
+
+ $this->assertEquals('Unknown filetype', $response->getData()['data']['message']);
+
+ //File should be deleted
+ $this->assertFalse(file_exists($fileName));
+ }
+
+ /**
+ * Test posting avatar from existing file
+ */
+ public function testPostAvatarFromFile(): void {
+ //Mock node API call
+ $file = $this->getMockBuilder(\OCP\Files\File::class)
+ ->disableOriginalConstructor()->getMock();
+ $file->expects($this->once())
+ ->method('getContent')
+ ->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
+ $file->expects($this->once())
+ ->method('getMimeType')
+ ->willReturn('image/jpeg');
+ $userFolder = $this->getMockBuilder(\OCP\Files\Folder::class)->getMock();
+ $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder);
+ $userFolder->method('get')->willReturn($file);
+
+ //Create request return
+ $response = $this->avatarController->postAvatar('avatar.jpg');
+
+ //On correct upload always respond with the notsquare message
+ $this->assertEquals('notsquare', $response->getData()['data']);
+ }
+
+ /**
+ * Test posting avatar from existing folder
+ */
+ public function testPostAvatarFromNoFile(): void {
+ $file = $this->getMockBuilder(\OCP\Files\Node::class)->getMock();
+ $userFolder = $this->getMockBuilder(\OCP\Files\Folder::class)->getMock();
+ $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder);
+ $userFolder
+ ->method('get')
+ ->with('folder')
+ ->willReturn($file);
+
+ //Create request return
+ $response = $this->avatarController->postAvatar('folder');
+
+ //On correct upload always respond with the notsquare message
+ $this->assertEquals(['data' => ['message' => 'Please select a file.']], $response->getData());
+ }
+
+ public function testPostAvatarInvalidType(): void {
+ $file = $this->getMockBuilder(\OCP\Files\File::class)
+ ->disableOriginalConstructor()->getMock();
+ $file->expects($this->never())
+ ->method('getContent');
+ $file->expects($this->exactly(2))
+ ->method('getMimeType')
+ ->willReturn('text/plain');
+ $userFolder = $this->getMockBuilder(\OCP\Files\Folder::class)->getMock();
+ $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder);
+ $userFolder->method('get')->willReturn($file);
+
+ $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'The selected file is not an image.']], Http::STATUS_BAD_REQUEST);
+ $this->assertEquals($expectedResponse, $this->avatarController->postAvatar('avatar.jpg'));
+ }
+
+ public function testPostAvatarNotPermittedException(): void {
+ $file = $this->getMockBuilder(\OCP\Files\File::class)
+ ->disableOriginalConstructor()->getMock();
+ $file->expects($this->once())
+ ->method('getContent')
+ ->willThrowException(new NotPermittedException());
+ $file->expects($this->once())
+ ->method('getMimeType')
+ ->willReturn('image/jpeg');
+ $userFolder = $this->getMockBuilder(\OCP\Files\Folder::class)->getMock();
+ $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder);
+ $userFolder->method('get')->willReturn($file);
+
+ $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'The selected file cannot be read.']], Http::STATUS_BAD_REQUEST);
+ $this->assertEquals($expectedResponse, $this->avatarController->postAvatar('avatar.jpg'));
+ }
+
+ /**
+ * Test what happens if the upload of the avatar fails
+ */
+ public function testPostAvatarException(): void {
+ $this->cache->expects($this->once())
+ ->method('set')
+ ->will($this->throwException(new \Exception('foo')));
+ $file = $this->getMockBuilder(\OCP\Files\File::class)
+ ->disableOriginalConstructor()->getMock();
+ $file->expects($this->once())
+ ->method('getContent')
+ ->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
+ $file->expects($this->once())
+ ->method('getMimeType')
+ ->willReturn('image/jpeg');
+ $userFolder = $this->getMockBuilder(\OCP\Files\Folder::class)->getMock();
+ $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder);
+ $userFolder->method('get')->willReturn($file);
+
+ $this->logger->expects($this->once())
+ ->method('error')
+ ->with('foo', ['exception' => new \Exception('foo'), 'app' => 'core']);
+ $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_OK);
+ $this->assertEquals($expectedResponse, $this->avatarController->postAvatar('avatar.jpg'));
+ }
+
+
+ /**
+ * Test invalid crop argument
+ */
+ public function testPostCroppedAvatarInvalidCrop(): void {
+ $response = $this->avatarController->postCroppedAvatar([]);
+
+ $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus());
+ }
+
+ /**
+ * Test no tmp avatar to crop
+ */
+ public function testPostCroppedAvatarNoTmpAvatar(): void {
+ $response = $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 10]);
+
+ $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus());
+ }
+
+ /**
+ * Test with non square crop
+ */
+ public function testPostCroppedAvatarNoSquareCrop(): void {
+ $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
+
+ $this->avatarMock->method('set')->will($this->throwException(new \OC\NotSquareException));
+ $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
+ $response = $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 11]);
+
+ $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus());
+ }
+
+ /**
+ * Check for proper reply on proper crop argument
+ */
+ public function testPostCroppedAvatarValidCrop(): void {
+ $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
+ $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
+ $response = $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 10]);
+
+ $this->assertEquals(Http::STATUS_OK, $response->getStatus());
+ $this->assertEquals('success', $response->getData()['status']);
+ }
+
+ /**
+ * Test what happens if the cropping of the avatar fails
+ */
+ public function testPostCroppedAvatarException(): void {
+ $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
+
+ $this->avatarMock->method('set')->will($this->throwException(new \Exception('foo')));
+ $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
+
+ $this->logger->expects($this->once())
+ ->method('error')
+ ->with('foo', ['exception' => new \Exception('foo'), 'app' => 'core']);
+ $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_BAD_REQUEST);
+ $this->assertEquals($expectedResponse, $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 11]));
+ }
+
+
+ /**
+ * Check for proper reply on proper crop argument
+ */
+ public function testFileTooBig(): void {
+ $fileName = \OC::$SERVERROOT.'/tests/data/testimage.jpg';
+ //Create request return
+ $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [21 * 1024 * 1024]];
+ $this->request->method('getUploadedFile')->willReturn($reqRet);
+
+ $response = $this->avatarController->postAvatar(null);
+
+ $this->assertEquals('File is too big', $response->getData()['data']['message']);
+ }
+}
diff --git a/tests/Core/Controller/ChangePasswordControllerTest.php b/tests/Core/Controller/ChangePasswordControllerTest.php
index 93fb4196d35..a806b091477 100644
--- a/tests/Core/Controller/ChangePasswordControllerTest.php
+++ b/tests/Core/Controller/ChangePasswordControllerTest.php
@@ -60,7 +60,7 @@ class ChangePasswordControllerTest extends \Test\TestCase {
);
}
- public function testChangePersonalPasswordWrongPassword() {
+ public function testChangePersonalPasswordWrongPassword(): void {
$this->userSession->expects($this->once())
->method('getLoginName')
->willReturn($this->loginName);
@@ -82,7 +82,7 @@ class ChangePasswordControllerTest extends \Test\TestCase {
$this->assertEquals($expects, $actual);
}
- public function testChangePersonalPasswordCommonPassword() {
+ public function testChangePersonalPasswordCommonPassword(): void {
$this->userSession->expects($this->once())
->method('getLoginName')
->willReturn($this->loginName);
@@ -109,7 +109,7 @@ class ChangePasswordControllerTest extends \Test\TestCase {
$this->assertEquals($expects, $actual);
}
- public function testChangePersonalPasswordNoNewPassword() {
+ public function testChangePersonalPasswordNoNewPassword(): void {
$this->userSession->expects($this->once())
->method('getLoginName')
->willReturn($this->loginName);
@@ -132,7 +132,7 @@ class ChangePasswordControllerTest extends \Test\TestCase {
$this->assertEquals($expects, $res->getData());
}
- public function testChangePersonalPasswordCantSetPassword() {
+ public function testChangePersonalPasswordCantSetPassword(): void {
$this->userSession->expects($this->once())
->method('getLoginName')
->willReturn($this->loginName);
@@ -159,7 +159,7 @@ class ChangePasswordControllerTest extends \Test\TestCase {
$this->assertEquals($expects, $actual);
}
- public function testChangePersonalPassword() {
+ public function testChangePersonalPassword(): void {
$this->userSession->expects($this->once())
->method('getLoginName')
->willReturn($this->loginName);
diff --git a/tests/Core/Controller/ClientFlowLoginControllerTest.php b/tests/Core/Controller/ClientFlowLoginControllerTest.php
index 98f09f0f18c..a38f73c85a6 100644
--- a/tests/Core/Controller/ClientFlowLoginControllerTest.php
+++ b/tests/Core/Controller/ClientFlowLoginControllerTest.php
@@ -102,7 +102,7 @@ class ClientFlowLoginControllerTest extends TestCase {
);
}
- public function testShowAuthPickerPageNoClientOrOauthRequest() {
+ public function testShowAuthPickerPageNoClientOrOauthRequest(): void {
$expected = new StandaloneTemplateResponse(
'core',
'error',
@@ -121,7 +121,7 @@ class ClientFlowLoginControllerTest extends TestCase {
$this->assertEquals($expected, $this->clientFlowLoginController->showAuthPickerPage());
}
- public function testShowAuthPickerPageWithOcsHeader() {
+ public function testShowAuthPickerPageWithOcsHeader(): void {
$this->request
->method('getHeader')
->withConsecutive(
@@ -183,7 +183,7 @@ class ClientFlowLoginControllerTest extends TestCase {
$this->assertEquals($expected, $this->clientFlowLoginController->showAuthPickerPage());
}
- public function testShowAuthPickerPageWithOauth() {
+ public function testShowAuthPickerPageWithOauth(): void {
$this->request
->method('getHeader')
->withConsecutive(
@@ -253,7 +253,7 @@ class ClientFlowLoginControllerTest extends TestCase {
$this->assertEquals($expected, $this->clientFlowLoginController->showAuthPickerPage('MyClientIdentifier'));
}
- public function testGenerateAppPasswordWithInvalidToken() {
+ public function testGenerateAppPasswordWithInvalidToken(): void {
$this->session
->expects($this->once())
->method('get')
@@ -276,7 +276,7 @@ class ClientFlowLoginControllerTest extends TestCase {
$this->assertEquals($expected, $this->clientFlowLoginController->generateAppPassword('MyStateToken'));
}
- public function testGenerateAppPasswordWithSessionNotAvailableException() {
+ public function testGenerateAppPasswordWithSessionNotAvailableException(): void {
$this->session
->expects($this->once())
->method('get')
@@ -296,7 +296,7 @@ class ClientFlowLoginControllerTest extends TestCase {
$this->assertEquals($expected, $this->clientFlowLoginController->generateAppPassword('MyStateToken'));
}
- public function testGenerateAppPasswordWithInvalidTokenException() {
+ public function testGenerateAppPasswordWithInvalidTokenException(): void {
$this->session
->expects($this->once())
->method('get')
@@ -321,7 +321,7 @@ class ClientFlowLoginControllerTest extends TestCase {
$this->assertEquals($expected, $this->clientFlowLoginController->generateAppPassword('MyStateToken'));
}
- public function testGeneratePasswordWithPassword() {
+ public function testGeneratePasswordWithPassword(): void {
$this->session
->expects($this->once())
->method('get')
@@ -405,7 +405,7 @@ class ClientFlowLoginControllerTest extends TestCase {
* ["https://example.com/redirect.php?hello=world", "https://example.com/redirect.php?hello=world&state=MyOauthState&code=MyAccessCode"]
*
*/
- public function testGeneratePasswordWithPasswordForOauthClient($redirectUri, $redirectUrl) {
+ public function testGeneratePasswordWithPasswordForOauthClient($redirectUri, $redirectUrl): void {
$this->session
->method('get')
->withConsecutive(
@@ -490,7 +490,7 @@ class ClientFlowLoginControllerTest extends TestCase {
$this->assertEquals($expected, $this->clientFlowLoginController->generateAppPassword('MyStateToken', 'MyClientIdentifier'));
}
- public function testGeneratePasswordWithoutPassword() {
+ public function testGeneratePasswordWithoutPassword(): void {
$this->session
->expects($this->once())
->method('get')
@@ -621,7 +621,7 @@ class ClientFlowLoginControllerTest extends TestCase {
* @param string $protocol
* @param string $expected
*/
- public function testGeneratePasswordWithHttpsProxy(array $headers, $protocol, $expected) {
+ public function testGeneratePasswordWithHttpsProxy(array $headers, $protocol, $expected): void {
$this->session
->expects($this->once())
->method('get')
diff --git a/tests/Core/Controller/ClientFlowLoginV2ControllerTest.php b/tests/Core/Controller/ClientFlowLoginV2ControllerTest.php
index eefa2982c74..093b8a3442d 100644
--- a/tests/Core/Controller/ClientFlowLoginV2ControllerTest.php
+++ b/tests/Core/Controller/ClientFlowLoginV2ControllerTest.php
@@ -70,7 +70,7 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
);
}
- public function testPollInvalid() {
+ public function testPollInvalid(): void {
$this->loginFlowV2Service->method('poll')
->with('token')
->willThrowException(new LoginFlowV2NotFoundException());
@@ -81,7 +81,7 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
$this->assertSame(Http::STATUS_NOT_FOUND, $result->getStatus());
}
- public function testPollValid() {
+ public function testPollValid(): void {
$creds = new LoginFlowV2Credentials('server', 'login', 'pass');
$this->loginFlowV2Service->method('poll')
->with('token')
@@ -93,7 +93,7 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
$this->assertSame(Http::STATUS_OK, $result->getStatus());
}
- public function testLandingInvalid() {
+ public function testLandingInvalid(): void {
$this->session->expects($this->never())
->method($this->anything());
@@ -107,7 +107,7 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
$this->assertInstanceOf(Http\StandaloneTemplateResponse::class, $result);
}
- public function testLandingValid() {
+ public function testLandingValid(): void {
$this->session->expects($this->once())
->method('set')
->with('client.flow.v2.login.token', 'token');
@@ -127,7 +127,7 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
$this->assertSame('https://server/path', $result->getRedirectURL());
}
- public function testShowAuthPickerNoLoginToken() {
+ public function testShowAuthPickerNoLoginToken(): void {
$this->session->method('get')
->willReturn(null);
@@ -136,7 +136,7 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
$this->assertSame(Http::STATUS_FORBIDDEN, $result->getStatus());
}
- public function testShowAuthPickerInvalidLoginToken() {
+ public function testShowAuthPickerInvalidLoginToken(): void {
$this->session->method('get')
->with('client.flow.v2.login.token')
->willReturn('loginToken');
@@ -150,7 +150,7 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
$this->assertSame(Http::STATUS_FORBIDDEN, $result->getStatus());
}
- public function testShowAuthPickerValidLoginToken() {
+ public function testShowAuthPickerValidLoginToken(): void {
$this->session->method('get')
->with('client.flow.v2.login.token')
->willReturn('loginToken');
@@ -176,7 +176,7 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
$this->assertSame(Http::STATUS_FORBIDDEN, $result->getStatus());
}
- public function testGrantPageInvalidStateToken() {
+ public function testGrantPageInvalidStateToken(): void {
$this->session->method('get')
->willReturnCallback(function ($name) {
return null;
@@ -186,7 +186,7 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
$this->assertSame(Http::STATUS_FORBIDDEN, $result->getStatus());
}
- public function testGrantPageInvalidLoginToken() {
+ public function testGrantPageInvalidLoginToken(): void {
$this->session->method('get')
->willReturnCallback(function ($name) {
if ($name === 'client.flow.v2.state.token') {
@@ -206,7 +206,7 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
$this->assertSame(Http::STATUS_FORBIDDEN, $result->getStatus());
}
- public function testGrantPageValid() {
+ public function testGrantPageValid(): void {
$this->session->method('get')
->willReturnCallback(function ($name) {
if ($name === 'client.flow.v2.state.token') {
@@ -236,7 +236,7 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
}
- public function testGenerateAppPasswordInvalidStateToken() {
+ public function testGenerateAppPasswordInvalidStateToken(): void {
$this->session->method('get')
->willReturnCallback(function ($name) {
return null;
@@ -246,7 +246,7 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
$this->assertSame(Http::STATUS_FORBIDDEN, $result->getStatus());
}
- public function testGenerateAppPassworInvalidLoginToken() {
+ public function testGenerateAppPassworInvalidLoginToken(): void {
$this->session->method('get')
->willReturnCallback(function ($name) {
if ($name === 'client.flow.v2.state.token') {
@@ -266,7 +266,7 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
$this->assertSame(Http::STATUS_FORBIDDEN, $result->getStatus());
}
- public function testGenerateAppPassworValid() {
+ public function testGenerateAppPassworValid(): void {
$this->session->method('get')
->willReturnCallback(function ($name) {
if ($name === 'client.flow.v2.state.token') {
diff --git a/tests/Core/Controller/ContactsMenuControllerTest.php b/tests/Core/Controller/ContactsMenuControllerTest.php
index d688ea6682f..aa20e6726e2 100644
--- a/tests/Core/Controller/ContactsMenuControllerTest.php
+++ b/tests/Core/Controller/ContactsMenuControllerTest.php
@@ -35,7 +35,7 @@ class ContactsMenuControllerTest extends TestCase {
$this->controller = new ContactsMenuController($request, $this->userSession, $this->contactsManager);
}
- public function testIndex() {
+ public function testIndex(): void {
$user = $this->createMock(IUser::class);
$entries = [
$this->createMock(IEntry::class),
@@ -54,7 +54,7 @@ class ContactsMenuControllerTest extends TestCase {
$this->assertEquals($entries, $response);
}
- public function testFindOne() {
+ public function testFindOne(): void {
$user = $this->createMock(IUser::class);
$entry = $this->createMock(IEntry::class);
$this->userSession->expects($this->once())
@@ -70,7 +70,7 @@ class ContactsMenuControllerTest extends TestCase {
$this->assertEquals($entry, $response);
}
- public function testFindOne404() {
+ public function testFindOne404(): void {
$user = $this->createMock(IUser::class);
$this->userSession->expects($this->once())
->method('getUser')
diff --git a/tests/Core/Controller/CssControllerTest.php b/tests/Core/Controller/CssControllerTest.php
index 8064f36cddb..cae6f7989c4 100644
--- a/tests/Core/Controller/CssControllerTest.php
+++ b/tests/Core/Controller/CssControllerTest.php
@@ -56,7 +56,7 @@ class CssControllerTest extends TestCase {
);
}
- public function testNoCssFolderForApp() {
+ public function testNoCssFolderForApp(): void {
$this->appData->method('getFolder')
->with('myapp')
->willThrowException(new NotFoundException());
@@ -67,7 +67,7 @@ class CssControllerTest extends TestCase {
}
- public function testNoCssFile() {
+ public function testNoCssFile(): void {
$folder = $this->createMock(ISimpleFolder::class);
$this->appData->method('getFolder')
->with('myapp')
@@ -81,7 +81,7 @@ class CssControllerTest extends TestCase {
$this->assertInstanceOf(NotFoundResponse::class, $result);
}
- public function testGetFile() {
+ public function testGetFile(): void {
$folder = $this->createMock(ISimpleFolder::class);
$file = $this->createMock(ISimpleFile::class);
$file->method('getName')->willReturn('my name');
@@ -105,7 +105,7 @@ class CssControllerTest extends TestCase {
$this->assertEquals($expected, $result);
}
- public function testGetGzipFile() {
+ public function testGetGzipFile(): void {
$folder = $this->createMock(ISimpleFolder::class);
$gzipFile = $this->createMock(ISimpleFile::class);
$gzipFile->method('getName')->willReturn('my name');
@@ -134,7 +134,7 @@ class CssControllerTest extends TestCase {
$this->assertEquals($expected, $result);
}
- public function testGetGzipFileNotFound() {
+ public function testGetGzipFileNotFound(): void {
$folder = $this->createMock(ISimpleFolder::class);
$file = $this->createMock(ISimpleFile::class);
$file->method('getName')->willReturn('my name');
diff --git a/tests/Core/Controller/GuestAvatarControllerTest.php b/tests/Core/Controller/GuestAvatarControllerTest.php
index b2f60665948..1ad9e49f858 100644
--- a/tests/Core/Controller/GuestAvatarControllerTest.php
+++ b/tests/Core/Controller/GuestAvatarControllerTest.php
@@ -71,7 +71,7 @@ class GuestAvatarControllerTest extends \Test\TestCase {
/**
* Tests getAvatar returns the guest avatar.
*/
- public function testGetAvatar() {
+ public function testGetAvatar(): void {
$this->avatarManager->expects($this->once())
->method('getGuestAvatar')
->with('Peter')
diff --git a/tests/Core/Controller/JsControllerTest.php b/tests/Core/Controller/JsControllerTest.php
index 5aa853e4ed0..1500ed6eacf 100644
--- a/tests/Core/Controller/JsControllerTest.php
+++ b/tests/Core/Controller/JsControllerTest.php
@@ -56,7 +56,7 @@ class JsControllerTest extends TestCase {
);
}
- public function testNoCssFolderForApp() {
+ public function testNoCssFolderForApp(): void {
$this->appData->method('getFolder')
->with('myapp')
->willThrowException(new NotFoundException());
@@ -67,7 +67,7 @@ class JsControllerTest extends TestCase {
}
- public function testNoCssFile() {
+ public function testNoCssFile(): void {
$folder = $this->createMock(ISimpleFolder::class);
$this->appData->method('getFolder')
->with('myapp')
@@ -81,7 +81,7 @@ class JsControllerTest extends TestCase {
$this->assertInstanceOf(NotFoundResponse::class, $result);
}
- public function testGetFile() {
+ public function testGetFile(): void {
$folder = $this->createMock(ISimpleFolder::class);
$file = $this->createMock(ISimpleFile::class);
$file->method('getName')->willReturn('my name');
@@ -105,7 +105,7 @@ class JsControllerTest extends TestCase {
$this->assertEquals($expected, $result);
}
- public function testGetGzipFile() {
+ public function testGetGzipFile(): void {
$folder = $this->createMock(ISimpleFolder::class);
$gzipFile = $this->createMock(ISimpleFile::class);
$gzipFile->method('getName')->willReturn('my name');
@@ -134,7 +134,7 @@ class JsControllerTest extends TestCase {
$this->assertEquals($expected, $result);
}
- public function testGetGzipFileNotFound() {
+ public function testGetGzipFileNotFound(): void {
$folder = $this->createMock(ISimpleFolder::class);
$file = $this->createMock(ISimpleFile::class);
$file->method('getName')->willReturn('my name');
diff --git a/tests/Core/Controller/LoginControllerTest.php b/tests/Core/Controller/LoginControllerTest.php
index 50ecbe5e19c..a5ff6fd61a5 100644
--- a/tests/Core/Controller/LoginControllerTest.php
+++ b/tests/Core/Controller/LoginControllerTest.php
@@ -129,7 +129,7 @@ class LoginControllerTest extends TestCase {
);
}
- public function testLogoutWithoutToken() {
+ public function testLogoutWithoutToken(): void {
$this->request
->expects($this->once())
->method('getCookie')
@@ -156,7 +156,7 @@ class LoginControllerTest extends TestCase {
$this->assertEquals($expected, $this->loginController->logout());
}
- public function testLogoutNoClearSiteData() {
+ public function testLogoutNoClearSiteData(): void {
$this->request
->expects($this->once())
->method('getCookie')
@@ -179,7 +179,7 @@ class LoginControllerTest extends TestCase {
$this->assertEquals($expected, $this->loginController->logout());
}
- public function testLogoutWithToken() {
+ public function testLogoutWithToken(): void {
$this->request
->expects($this->once())
->method('getCookie')
@@ -216,7 +216,7 @@ class LoginControllerTest extends TestCase {
$this->assertEquals($expected, $this->loginController->logout());
}
- public function testShowLoginFormForLoggedInUsers() {
+ public function testShowLoginFormForLoggedInUsers(): void {
$this->userSession
->expects($this->once())
->method('isLoggedIn')
@@ -230,7 +230,7 @@ class LoginControllerTest extends TestCase {
$this->assertEquals($expectedResponse, $this->loginController->showLoginForm('', ''));
}
- public function testShowLoginFormWithErrorsInSession() {
+ public function testShowLoginFormWithErrorsInSession(): void {
$this->userSession
->expects($this->once())
->method('isLoggedIn')
@@ -285,7 +285,7 @@ class LoginControllerTest extends TestCase {
$this->assertEquals($expectedResponse, $this->loginController->showLoginForm('', ''));
}
- public function testShowLoginFormForFlowAuth() {
+ public function testShowLoginFormForFlowAuth(): void {
$this->userSession
->expects($this->once())
->method('isLoggedIn')
@@ -332,7 +332,7 @@ class LoginControllerTest extends TestCase {
* @dataProvider passwordResetDataProvider
*/
public function testShowLoginFormWithPasswordResetOption($canChangePassword,
- $expectedResult) {
+ $expectedResult): void {
$this->userSession
->expects($this->once())
->method('isLoggedIn')
@@ -381,7 +381,7 @@ class LoginControllerTest extends TestCase {
$this->assertEquals($expectedResponse, $this->loginController->showLoginForm('LdapUser', ''));
}
- public function testShowLoginFormForUserNamed0() {
+ public function testShowLoginFormForUserNamed0(): void {
$this->userSession
->expects($this->once())
->method('isLoggedIn')
@@ -468,7 +468,7 @@ class LoginControllerTest extends TestCase {
$this->assertEquals($expected, $response);
}
- public function testLoginWithValidCredentials() {
+ public function testLoginWithValidCredentials(): void {
$user = 'MyUserName';
$password = 'secret';
$loginChain = $this->createMock(LoginChain::class);
@@ -523,7 +523,7 @@ class LoginControllerTest extends TestCase {
$this->assertEquals($expected, $response);
}
- public function testLoginWithoutPassedCsrfCheckAndLoggedIn() {
+ public function testLoginWithoutPassedCsrfCheckAndLoggedIn(): void {
/** @var IUser|MockObject $user */
$user = $this->createMock(IUser::class);
$user->expects($this->any())
@@ -560,7 +560,7 @@ class LoginControllerTest extends TestCase {
$this->assertEquals($expected, $response);
}
- public function testLoginWithValidCredentialsAndRedirectUrl() {
+ public function testLoginWithValidCredentialsAndRedirectUrl(): void {
$user = 'MyUserName';
$password = 'secret';
$redirectUrl = 'https://next.cloud/apps/mail';
@@ -594,7 +594,7 @@ class LoginControllerTest extends TestCase {
$this->assertEquals($expected, $response);
}
- public function testToNotLeakLoginName() {
+ public function testToNotLeakLoginName(): void {
$loginChain = $this->createMock(LoginChain::class);
$this->request
->expects($this->once())
diff --git a/tests/Core/Controller/LostControllerTest.php b/tests/Core/Controller/LostControllerTest.php
index d6729a98caf..0f4a5f41f84 100644
--- a/tests/Core/Controller/LostControllerTest.php
+++ b/tests/Core/Controller/LostControllerTest.php
@@ -138,7 +138,7 @@ class LostControllerTest extends TestCase {
);
}
- public function testResetFormTokenError() {
+ public function testResetFormTokenError(): void {
$this->userManager->method('get')
->with('ValidTokenUser')
->willReturn($this->existingUser);
@@ -160,7 +160,7 @@ class LostControllerTest extends TestCase {
$this->assertEquals($expectedResponse, $response);
}
- public function testResetFormValidToken() {
+ public function testResetFormValidToken(): void {
$this->userManager->method('get')
->with('ValidTokenUser')
->willReturn($this->existingUser);
@@ -188,7 +188,7 @@ class LostControllerTest extends TestCase {
$this->assertEquals($expectedResponse, $response);
}
- public function testEmailUnsuccessful() {
+ public function testEmailUnsuccessful(): void {
$existingUser = 'ExistingUser';
$nonExistingUser = 'NonExistingUser';
$this->userManager
@@ -230,7 +230,7 @@ class LostControllerTest extends TestCase {
$this->assertEquals($expectedResponse, $response);
}
- public function testEmailSuccessful() {
+ public function testEmailSuccessful(): void {
$this->userManager
->expects($this->any())
->method('get')
@@ -287,7 +287,7 @@ class LostControllerTest extends TestCase {
$this->assertEquals($expectedResponse, $response);
}
- public function testEmailWithMailSuccessful() {
+ public function testEmailWithMailSuccessful(): void {
$this->userManager
->expects($this->any())
->method('get')
@@ -349,7 +349,7 @@ class LostControllerTest extends TestCase {
$this->assertEquals($expectedResponse, $response);
}
- public function testEmailCantSendException() {
+ public function testEmailCantSendException(): void {
$this->userManager
->expects($this->any())
->method('get')
@@ -409,7 +409,7 @@ class LostControllerTest extends TestCase {
$this->assertEquals($expectedResponse, $response);
}
- public function testSetPasswordUnsuccessful() {
+ public function testSetPasswordUnsuccessful(): void {
$this->config->method('getUserValue')
->with('ValidTokenUser', 'core', 'lostpassword', null)
->willReturn('encryptedData');
@@ -435,7 +435,7 @@ class LostControllerTest extends TestCase {
$this->assertSame($expectedResponse, $response->getData());
}
- public function testSetPasswordSuccessful() {
+ public function testSetPasswordSuccessful(): void {
$this->config->method('getUserValue')
->with('ValidTokenUser', 'core', 'lostpassword', null)
->willReturn('encryptedData');
@@ -463,7 +463,7 @@ class LostControllerTest extends TestCase {
$this->assertSame($expectedResponse, $response->getData());
}
- public function testSetPasswordExpiredToken() {
+ public function testSetPasswordExpiredToken(): void {
$this->config->method('getUserValue')
->with('ValidTokenUser', 'core', 'lostpassword', null)
->willReturn('encryptedData');
@@ -482,7 +482,7 @@ class LostControllerTest extends TestCase {
$this->assertSame($expectedResponse, $response->getData());
}
- public function testSetPasswordInvalidDataInDb() {
+ public function testSetPasswordInvalidDataInDb(): void {
$this->config->method('getUserValue')
->with('ValidTokenUser', 'core', 'lostpassword', null)
->willReturn('invalidEncryptedData');
@@ -502,7 +502,7 @@ class LostControllerTest extends TestCase {
$this->assertSame($expectedResponse, $response->getData());
}
- public function testIsSetPasswordWithoutTokenFailing() {
+ public function testIsSetPasswordWithoutTokenFailing(): void {
$this->config->method('getUserValue')
->with('ValidTokenUser', 'core', 'lostpassword', null)
->willReturn('aValidtoken');
@@ -521,7 +521,7 @@ class LostControllerTest extends TestCase {
$this->assertSame($expectedResponse, $response->getData());
}
- public function testSetPasswordForDisabledUser() {
+ public function testSetPasswordForDisabledUser(): void {
$user = $this->createMock(IUser::class);
$user->expects($this->any())
->method('isEnabled')
@@ -551,7 +551,7 @@ class LostControllerTest extends TestCase {
$this->assertSame($expectedResponse, $response->getData());
}
- public function testSendEmailNoEmail() {
+ public function testSendEmailNoEmail(): void {
$user = $this->createMock(IUser::class);
$user->expects($this->any())
->method('isEnabled')
@@ -574,7 +574,7 @@ class LostControllerTest extends TestCase {
$this->assertEquals($expectedResponse, $response);
}
- public function testSetPasswordEncryptionDontProceedPerUserKey() {
+ public function testSetPasswordEncryptionDontProceedPerUserKey(): void {
/** @var IEncryptionModule|MockObject $encryptionModule */
$encryptionModule = $this->createMock(IEncryptionModule::class);
$encryptionModule->expects($this->once())->method('needDetailedAccessList')->willReturn(true);
@@ -587,7 +587,7 @@ class LostControllerTest extends TestCase {
$this->assertSame($expectedResponse, $response->getData());
}
- public function testSetPasswordDontProceedMasterKey() {
+ public function testSetPasswordDontProceedMasterKey(): void {
$encryptionModule = $this->createMock(IEncryptionModule::class);
$encryptionModule->expects($this->once())->method('needDetailedAccessList')->willReturn(false);
$this->encryptionManager->expects($this->once())->method('getEncryptionModules')
@@ -615,7 +615,7 @@ class LostControllerTest extends TestCase {
$this->assertSame($expectedResponse, $response->getData());
}
- public function testTwoUsersWithSameEmail() {
+ public function testTwoUsersWithSameEmail(): void {
$user1 = $this->createMock(IUser::class);
$user1->expects($this->any())
->method('getEMailAddress')
@@ -707,7 +707,7 @@ class LostControllerTest extends TestCase {
$this->assertInstanceOf(IUser::class, $result);
}
- public function testTrimEmailInput() {
+ public function testTrimEmailInput(): void {
$this->userManager
->expects($this->once())
->method('getByEmail')
@@ -724,7 +724,7 @@ class LostControllerTest extends TestCase {
$this->assertEquals($expectedResponse, $response);
}
- public function testUsernameInput() {
+ public function testUsernameInput(): void {
$this->userManager
->expects($this->once())
->method('get')
diff --git a/tests/Core/Controller/NavigationControllerTest.php b/tests/Core/Controller/NavigationControllerTest.php
index 0d7c91d3034..4995bd2fed0 100644
--- a/tests/Core/Controller/NavigationControllerTest.php
+++ b/tests/Core/Controller/NavigationControllerTest.php
@@ -48,7 +48,7 @@ class NavigationControllerTest extends TestCase {
];
}
/** @dataProvider dataGetNavigation */
- public function testGetAppNavigation($absolute) {
+ public function testGetAppNavigation($absolute): void {
$this->navigationManager->expects($this->once())
->method('getAll')
->with('link')
@@ -77,7 +77,7 @@ class NavigationControllerTest extends TestCase {
}
/** @dataProvider dataGetNavigation */
- public function testGetSettingsNavigation($absolute) {
+ public function testGetSettingsNavigation($absolute): void {
$this->navigationManager->expects($this->once())
->method('getAll')
->with('settings')
@@ -108,7 +108,7 @@ class NavigationControllerTest extends TestCase {
}
}
- public function testGetAppNavigationEtagMatch() {
+ public function testGetAppNavigationEtagMatch(): void {
$navigation = [ ['id' => 'files', 'href' => '/index.php/apps/files', 'icon' => 'icon' ] ];
$this->request->expects($this->once())
->method('getHeader')
@@ -123,7 +123,7 @@ class NavigationControllerTest extends TestCase {
$this->assertEquals(Http::STATUS_NOT_MODIFIED, $actual->getStatus());
}
- public function testGetSettingsNavigationEtagMatch() {
+ public function testGetSettingsNavigationEtagMatch(): void {
$navigation = [ ['id' => 'logout', 'href' => '/index.php/apps/files', 'icon' => 'icon' ] ];
$this->request->expects($this->once())
->method('getHeader')
diff --git a/tests/Core/Controller/OCSControllerTest.php b/tests/Core/Controller/OCSControllerTest.php
index 19b87a97359..6fc5f54b8ef 100644
--- a/tests/Core/Controller/OCSControllerTest.php
+++ b/tests/Core/Controller/OCSControllerTest.php
@@ -68,7 +68,7 @@ class OCSControllerTest extends TestCase {
return new DataResponse($data);
}
- public function testGetCapabilities() {
+ public function testGetCapabilities(): void {
$this->userSession->expects($this->once())
->method('isLoggedIn')
->willReturn(true);
@@ -101,7 +101,7 @@ class OCSControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->getCapabilities());
}
- public function testGetCapabilitiesPublic() {
+ public function testGetCapabilitiesPublic(): void {
$this->userSession->expects($this->once())
->method('isLoggedIn')
->willReturn(false);
@@ -135,7 +135,7 @@ class OCSControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->getCapabilities());
}
- public function testPersonCheckValid() {
+ public function testPersonCheckValid(): void {
$this->userManager->method('checkPassword')
->with(
$this->equalTo('user'),
@@ -150,7 +150,7 @@ class OCSControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->personCheck('user', 'pass'));
}
- public function testPersonInvalid() {
+ public function testPersonInvalid(): void {
$this->userManager->method('checkPassword')
->with(
$this->equalTo('user'),
@@ -162,7 +162,7 @@ class OCSControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->personCheck('user', 'wrongpass'));
}
- public function testPersonNoLogin() {
+ public function testPersonNoLogin(): void {
$this->userManager->method('checkPassword')
->with(
$this->equalTo('user'),
@@ -173,7 +173,7 @@ class OCSControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->personCheck('', ''));
}
- public function testGetIdentityProofWithNotExistingUser() {
+ public function testGetIdentityProofWithNotExistingUser(): void {
$this->userManager
->expects($this->once())
->method('get')
@@ -184,7 +184,7 @@ class OCSControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->getIdentityProof('NotExistingUser'));
}
- public function testGetIdentityProof() {
+ public function testGetIdentityProof(): void {
$user = $this->createMock(IUser::class);
$key = $this->createMock(Key::class);
$this->userManager
diff --git a/tests/Core/Controller/PreviewControllerTest.php b/tests/Core/Controller/PreviewControllerTest.php
index 7c9a32eae38..4274f15e8ed 100644
--- a/tests/Core/Controller/PreviewControllerTest.php
+++ b/tests/Core/Controller/PreviewControllerTest.php
@@ -49,28 +49,28 @@ class PreviewControllerTest extends \Test\TestCase {
);
}
- public function testInvalidFile() {
+ public function testInvalidFile(): void {
$res = $this->controller->getPreview('');
$expected = new DataResponse([], Http::STATUS_BAD_REQUEST);
$this->assertEquals($expected, $res);
}
- public function testInvalidWidth() {
+ public function testInvalidWidth(): void {
$res = $this->controller->getPreview('file', 0);
$expected = new DataResponse([], Http::STATUS_BAD_REQUEST);
$this->assertEquals($expected, $res);
}
- public function testInvalidHeight() {
+ public function testInvalidHeight(): void {
$res = $this->controller->getPreview('file', 10, 0);
$expected = new DataResponse([], Http::STATUS_BAD_REQUEST);
$this->assertEquals($expected, $res);
}
- public function testFileNotFound() {
+ public function testFileNotFound(): void {
$userFolder = $this->createMock(Folder::class);
$this->rootFolder->method('getUserFolder')
->with($this->equalTo($this->userId))
@@ -86,7 +86,7 @@ class PreviewControllerTest extends \Test\TestCase {
$this->assertEquals($expected, $res);
}
- public function testNotAFile() {
+ public function testNotAFile(): void {
$userFolder = $this->createMock(Folder::class);
$this->rootFolder->method('getUserFolder')
->with($this->equalTo($this->userId))
@@ -103,7 +103,7 @@ class PreviewControllerTest extends \Test\TestCase {
$this->assertEquals($expected, $res);
}
- public function testNoPreviewAndNoIcon() {
+ public function testNoPreviewAndNoIcon(): void {
$userFolder = $this->createMock(Folder::class);
$this->rootFolder->method('getUserFolder')
->with($this->equalTo($this->userId))
@@ -124,7 +124,7 @@ class PreviewControllerTest extends \Test\TestCase {
$this->assertEquals($expected, $res);
}
- public function testForbiddenFile() {
+ public function testForbiddenFile(): void {
$userFolder = $this->createMock(Folder::class);
$this->rootFolder->method('getUserFolder')
->with($this->equalTo($this->userId))
@@ -148,7 +148,7 @@ class PreviewControllerTest extends \Test\TestCase {
$this->assertEquals($expected, $res);
}
- public function testNoPreview() {
+ public function testNoPreview(): void {
$userFolder = $this->createMock(Folder::class);
$this->rootFolder->method('getUserFolder')
->with($this->equalTo($this->userId))
@@ -180,7 +180,7 @@ class PreviewControllerTest extends \Test\TestCase {
$this->assertEquals($expected, $res);
}
- public function testValidPreview() {
+ public function testValidPreview(): void {
$userFolder = $this->createMock(Folder::class);
$this->rootFolder->method('getUserFolder')
->with($this->equalTo($this->userId))
diff --git a/tests/Core/Controller/TwoFactorChallengeControllerTest.php b/tests/Core/Controller/TwoFactorChallengeControllerTest.php
index 3e99c2cad14..11e18bd622a 100644
--- a/tests/Core/Controller/TwoFactorChallengeControllerTest.php
+++ b/tests/Core/Controller/TwoFactorChallengeControllerTest.php
@@ -75,7 +75,7 @@ class TwoFactorChallengeControllerTest extends TestCase {
->willReturn('logoutAttribute');
}
- public function testSelectChallenge() {
+ public function testSelectChallenge(): void {
$user = $this->getMockBuilder(IUser::class)->getMock();
$p1 = $this->createMock(IActivatableAtLogin::class);
$p1->method('getId')->willReturn('p1');
@@ -109,7 +109,7 @@ class TwoFactorChallengeControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->selectChallenge('/some/url'));
}
- public function testShowChallenge() {
+ public function testShowChallenge(): void {
$user = $this->createMock(IUser::class);
$provider = $this->createMock(IProvider::class);
$provider->method('getId')->willReturn('myprovider');
@@ -160,7 +160,7 @@ class TwoFactorChallengeControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->showChallenge('myprovider', '/re/dir/ect/url'));
}
- public function testShowInvalidChallenge() {
+ public function testShowInvalidChallenge(): void {
$user = $this->createMock(IUser::class);
$providerSet = new ProviderSet([], false);
@@ -181,7 +181,7 @@ class TwoFactorChallengeControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->showChallenge('myprovider', 'redirect/url'));
}
- public function testSolveChallenge() {
+ public function testSolveChallenge(): void {
$user = $this->createMock(IUser::class);
$provider = $this->createMock(IProvider::class);
@@ -206,7 +206,7 @@ class TwoFactorChallengeControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->solveChallenge('myprovider', 'token'));
}
- public function testSolveValidChallengeAndRedirect() {
+ public function testSolveValidChallengeAndRedirect(): void {
$user = $this->createMock(IUser::class);
$provider = $this->createMock(IProvider::class);
@@ -231,7 +231,7 @@ class TwoFactorChallengeControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->solveChallenge('myprovider', 'token', 'redirect%20url'));
}
- public function testSolveChallengeInvalidProvider() {
+ public function testSolveChallengeInvalidProvider(): void {
$user = $this->getMockBuilder(IUser::class)->getMock();
$this->userSession->expects($this->once())
@@ -251,7 +251,7 @@ class TwoFactorChallengeControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->solveChallenge('myprovider', 'token'));
}
- public function testSolveInvalidChallenge() {
+ public function testSolveInvalidChallenge(): void {
$user = $this->createMock(IUser::class);
$provider = $this->createMock(IProvider::class);
@@ -285,7 +285,7 @@ class TwoFactorChallengeControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->solveChallenge('myprovider', 'token', '/url'));
}
- public function testSolveChallengeTwoFactorException() {
+ public function testSolveChallengeTwoFactorException(): void {
$user = $this->createMock(IUser::class);
$provider = $this->createMock(IProvider::class);
$exception = new TwoFactorException('2FA failed');
@@ -353,7 +353,7 @@ class TwoFactorChallengeControllerTest extends TestCase {
$this->assertEquals($expected, $response);
}
- public function testSetUpInvalidProvider() {
+ public function testSetUpInvalidProvider(): void {
$user = $this->createMock(IUser::class);
$this->userSession->expects($this->once())
->method('getUser')
diff --git a/tests/Core/Controller/UserControllerTest.php b/tests/Core/Controller/UserControllerTest.php
index 09a22913fdc..979c723dd85 100644
--- a/tests/Core/Controller/UserControllerTest.php
+++ b/tests/Core/Controller/UserControllerTest.php
@@ -31,7 +31,7 @@ class UserControllerTest extends TestCase {
);
}
- public function testGetDisplayNames() {
+ public function testGetDisplayNames(): void {
$user = $this->createMock(IUser::class);
$user->method('getDisplayName')
->willReturn('FooDisplay Name');
diff --git a/tests/Core/Controller/WipeControllerTest.php b/tests/Core/Controller/WipeControllerTest.php
index f07fe4c9282..2cd315db5bf 100644
--- a/tests/Core/Controller/WipeControllerTest.php
+++ b/tests/Core/Controller/WipeControllerTest.php
@@ -50,7 +50,7 @@ class WipeControllerTest extends TestCase {
*
* @dataProvider dataTest
*/
- public function testCheckWipe(bool $valid, bool $couldPerform, bool $result) {
+ public function testCheckWipe(bool $valid, bool $couldPerform, bool $result): void {
if (!$valid) {
$this->remoteWipe->method('start')
->with('mytoken')
@@ -79,7 +79,7 @@ class WipeControllerTest extends TestCase {
*
* @dataProvider dataTest
*/
- public function testWipeDone(bool $valid, bool $couldPerform, bool $result) {
+ public function testWipeDone(bool $valid, bool $couldPerform, bool $result): void {
if (!$valid) {
$this->remoteWipe->method('finish')
->with('mytoken')
diff --git a/tests/Core/Data/LoginFlowV2CredentialsTest.php b/tests/Core/Data/LoginFlowV2CredentialsTest.php
index 0bb32f1c967..41575f33a9c 100644
--- a/tests/Core/Data/LoginFlowV2CredentialsTest.php
+++ b/tests/Core/Data/LoginFlowV2CredentialsTest.php
@@ -20,20 +20,20 @@ class LoginFlowV2CredentialsTest extends TestCase {
$this->fixture = new LoginFlowV2Credentials('server', 'login', 'pass');
}
- public function testImplementsJsonSerializable() {
+ public function testImplementsJsonSerializable(): void {
$this->assertTrue($this->fixture instanceof JsonSerializable);
}
/**
* Test getter functions.
*/
- public function testGetter() {
+ public function testGetter(): void {
$this->assertEquals('server', $this->fixture->getServer());
$this->assertEquals('login', $this->fixture->getLoginName());
$this->assertEquals('pass', $this->fixture->getAppPassword());
}
- public function testJsonSerialize() {
+ public function testJsonSerialize(): void {
$this->assertEquals(
[
'server' => 'server',
diff --git a/tests/Core/Middleware/TwoFactorMiddlewareTest.php b/tests/Core/Middleware/TwoFactorMiddlewareTest.php
index a245845a674..6b8bf1c76e0 100644
--- a/tests/Core/Middleware/TwoFactorMiddlewareTest.php
+++ b/tests/Core/Middleware/TwoFactorMiddlewareTest.php
@@ -82,7 +82,7 @@ class TwoFactorMiddlewareTest extends TestCase {
$this->controller = $this->createMock(Controller::class);
}
- public function testBeforeControllerNotLoggedIn() {
+ public function testBeforeControllerNotLoggedIn(): void {
$this->userSession->expects($this->once())
->method('isLoggedIn')
->willReturn(false);
@@ -93,7 +93,7 @@ class TwoFactorMiddlewareTest extends TestCase {
$this->middleware->beforeController($this->controller, 'index');
}
- public function testBeforeSetupController() {
+ public function testBeforeSetupController(): void {
$user = $this->createMock(IUser::class);
$controller = $this->createMock(ALoginSetupController::class);
$this->userSession->expects($this->any())
@@ -108,7 +108,7 @@ class TwoFactorMiddlewareTest extends TestCase {
$this->middleware->beforeController($controller, 'create');
}
- public function testBeforeControllerNoTwoFactorCheckNeeded() {
+ public function testBeforeControllerNoTwoFactorCheckNeeded(): void {
$user = $this->createMock(IUser::class);
$this->userSession->expects($this->once())
@@ -126,7 +126,7 @@ class TwoFactorMiddlewareTest extends TestCase {
}
- public function testBeforeControllerTwoFactorAuthRequired() {
+ public function testBeforeControllerTwoFactorAuthRequired(): void {
$this->expectException(TwoFactorAuthRequiredException::class);
$user = $this->createMock(IUser::class);
@@ -150,7 +150,7 @@ class TwoFactorMiddlewareTest extends TestCase {
}
- public function testBeforeControllerUserAlreadyLoggedIn() {
+ public function testBeforeControllerUserAlreadyLoggedIn(): void {
$this->expectException(UserAlreadyLoggedInException::class);
$user = $this->createMock(IUser::class);
@@ -179,7 +179,7 @@ class TwoFactorMiddlewareTest extends TestCase {
$this->middleware->beforeController($twoFactorChallengeController, 'index');
}
- public function testAfterExceptionTwoFactorAuthRequired() {
+ public function testAfterExceptionTwoFactorAuthRequired(): void {
$ex = new TwoFactorAuthRequiredException();
$this->urlGenerator->expects($this->once())
@@ -191,7 +191,7 @@ class TwoFactorMiddlewareTest extends TestCase {
$this->assertEquals($expected, $this->middleware->afterException($this->controller, 'index', $ex));
}
- public function testAfterException() {
+ public function testAfterException(): void {
$ex = new UserAlreadyLoggedInException();
$this->urlGenerator->expects($this->once())
@@ -203,7 +203,7 @@ class TwoFactorMiddlewareTest extends TestCase {
$this->assertEquals($expected, $this->middleware->afterException($this->controller, 'index', $ex));
}
- public function testRequires2FASetupDoneAnnotated() {
+ public function testRequires2FASetupDoneAnnotated(): void {
$user = $this->createMock(IUser::class);
$this->reflector
@@ -250,7 +250,7 @@ class TwoFactorMiddlewareTest extends TestCase {
/**
* @dataProvider dataRequires2FASetupDone
*/
- public function testRequires2FASetupDone(array $providers, bool $missingProviders, bool $expectEception) {
+ public function testRequires2FASetupDone(array $providers, bool $missingProviders, bool $expectEception): void {
$user = $this->createMock(IUser::class);
$this->reflector
diff --git a/tests/Core/Service/LoginFlowV2ServiceUnitTest.php b/tests/Core/Service/LoginFlowV2ServiceUnitTest.php
index 2e6407d4c00..2fb61a2ef08 100644
--- a/tests/Core/Service/LoginFlowV2ServiceUnitTest.php
+++ b/tests/Core/Service/LoginFlowV2ServiceUnitTest.php
@@ -127,7 +127,7 @@ class LoginFlowV2ServiceUnitTest extends TestCase {
* Tests for poll
*/
- public function testPollApptokenCouldNotBeDecrypted() {
+ public function testPollApptokenCouldNotBeDecrypted(): void {
$this->expectException(LoginFlowV2NotFoundException::class);
$this->expectExceptionMessage('Apptoken could not be decrypted');
@@ -148,7 +148,7 @@ class LoginFlowV2ServiceUnitTest extends TestCase {
$this->subjectUnderTest->poll('');
}
- public function testPollInvalidToken() {
+ public function testPollInvalidToken(): void {
$this->expectException(LoginFlowV2NotFoundException::class);
$this->expectExceptionMessage('Invalid token');
@@ -159,14 +159,14 @@ class LoginFlowV2ServiceUnitTest extends TestCase {
$this->subjectUnderTest->poll('');
}
- public function testPollTokenNotYetReady() {
+ public function testPollTokenNotYetReady(): void {
$this->expectException(LoginFlowV2NotFoundException::class);
$this->expectExceptionMessage('Token not yet ready');
$this->subjectUnderTest->poll('');
}
- public function testPollRemoveDataFromDb() {
+ public function testPollRemoveDataFromDb(): void {
[$encrypted, $privateKey] = $this->getOpenSSLEncryptedPublicAndPrivateKey('test_pass');
$this->crypto->expects($this->once())
@@ -208,7 +208,7 @@ class LoginFlowV2ServiceUnitTest extends TestCase {
* Tests for getByLoginToken
*/
- public function testGetByLoginToken() {
+ public function testGetByLoginToken(): void {
$loginFlowV2 = new LoginFlowV2();
$loginFlowV2->setLoginName('test_login');
$loginFlowV2->setServer('test_server');
@@ -226,7 +226,7 @@ class LoginFlowV2ServiceUnitTest extends TestCase {
$this->assertEquals('test', $result->getAppPassword());
}
- public function testGetByLoginTokenLoginTokenInvalid() {
+ public function testGetByLoginTokenLoginTokenInvalid(): void {
$this->expectException(LoginFlowV2NotFoundException::class);
$this->expectExceptionMessage('Login token invalid');
@@ -241,7 +241,7 @@ class LoginFlowV2ServiceUnitTest extends TestCase {
* Tests for startLoginFlow
*/
- public function testStartLoginFlow() {
+ public function testStartLoginFlow(): void {
$loginFlowV2 = new LoginFlowV2();
$this->mapper->expects($this->once())
@@ -254,7 +254,7 @@ class LoginFlowV2ServiceUnitTest extends TestCase {
$this->assertTrue($this->subjectUnderTest->startLoginFlow('test_token'));
}
- public function testStartLoginFlowDoesNotExistException() {
+ public function testStartLoginFlowDoesNotExistException(): void {
$this->mapper->expects($this->once())
->method('getByLoginToken')
->willThrowException(new DoesNotExistException(''));
@@ -266,7 +266,7 @@ class LoginFlowV2ServiceUnitTest extends TestCase {
* If an exception not of type DoesNotExistException is thrown,
* it is expected that it is not being handled by startLoginFlow.
*/
- public function testStartLoginFlowException() {
+ public function testStartLoginFlowException(): void {
$this->expectException(Exception::class);
$this->mapper->expects($this->once())
@@ -280,7 +280,7 @@ class LoginFlowV2ServiceUnitTest extends TestCase {
* Tests for flowDone
*/
- public function testFlowDone() {
+ public function testFlowDone(): void {
[,, $publicKey] = $this->getOpenSSLEncryptedPublicAndPrivateKey('test_pass');
$loginFlowV2 = new LoginFlowV2();
@@ -340,7 +340,7 @@ class LoginFlowV2ServiceUnitTest extends TestCase {
$this->assertEquals('server', $loginFlowV2->getServer());
}
- public function testFlowDoneDoesNotExistException() {
+ public function testFlowDoneDoesNotExistException(): void {
$this->mapper->expects($this->once())
->method('getByLoginToken')
->willThrowException(new DoesNotExistException(''));
@@ -354,7 +354,7 @@ class LoginFlowV2ServiceUnitTest extends TestCase {
$this->assertFalse($result);
}
- public function testFlowDonePasswordlessTokenException() {
+ public function testFlowDonePasswordlessTokenException(): void {
$this->tokenProvider->expects($this->once())
->method('getToken')
->willThrowException(new InvalidTokenException(''));
@@ -372,7 +372,7 @@ class LoginFlowV2ServiceUnitTest extends TestCase {
* Tests for createTokens
*/
- public function testCreateTokens() {
+ public function testCreateTokens(): void {
$this->config->expects($this->exactly(2))
->method('getSystemValue')
->willReturn($this->returnCallback(function ($key) {
diff --git a/tests/Test/Repair/Owncloud/CleanPreviewsBackgroundJobTest.php b/tests/Test/Repair/Owncloud/CleanPreviewsBackgroundJobTest.php
index 2138004c3dc..64db9459390 100644
--- a/tests/Test/Repair/Owncloud/CleanPreviewsBackgroundJobTest.php
+++ b/tests/Test/Repair/Owncloud/CleanPreviewsBackgroundJobTest.php
@@ -55,7 +55,7 @@ class CleanPreviewsBackgroundJobTest extends TestCase {
);
}
- public function testCleanupPreviewsUnfinished() {
+ public function testCleanupPreviewsUnfinished(): void {
$userFolder = $this->createMock(Folder::class);
$userRoot = $this->createMock(Folder::class);
$thumbnailFolder = $this->createMock(Folder::class);
@@ -100,7 +100,7 @@ class CleanPreviewsBackgroundJobTest extends TestCase {
$this->job->run(['uid' => 'myuid']);
}
- public function testCleanupPreviewsFinished() {
+ public function testCleanupPreviewsFinished(): void {
$userFolder = $this->createMock(Folder::class);
$userRoot = $this->createMock(Folder::class);
$thumbnailFolder = $this->createMock(Folder::class);
@@ -143,7 +143,7 @@ class CleanPreviewsBackgroundJobTest extends TestCase {
}
- public function testNoUserFolder() {
+ public function testNoUserFolder(): void {
$this->rootFolder->method('getUserFolder')
->with($this->equalTo('myuid'))
->willThrowException(new NotFoundException());
@@ -158,7 +158,7 @@ class CleanPreviewsBackgroundJobTest extends TestCase {
$this->job->run(['uid' => 'myuid']);
}
- public function testNoThumbnailFolder() {
+ public function testNoThumbnailFolder(): void {
$userFolder = $this->createMock(Folder::class);
$userRoot = $this->createMock(Folder::class);
@@ -182,7 +182,7 @@ class CleanPreviewsBackgroundJobTest extends TestCase {
$this->job->run(['uid' => 'myuid']);
}
- public function testNotPermittedToDelete() {
+ public function testNotPermittedToDelete(): void {
$userFolder = $this->createMock(Folder::class);
$userRoot = $this->createMock(Folder::class);
$thumbnailFolder = $this->createMock(Folder::class);
diff --git a/tests/Test/Repair/Owncloud/CleanPreviewsTest.php b/tests/Test/Repair/Owncloud/CleanPreviewsTest.php
index 10d2e5d216c..02f257a89b3 100644
--- a/tests/Test/Repair/Owncloud/CleanPreviewsTest.php
+++ b/tests/Test/Repair/Owncloud/CleanPreviewsTest.php
@@ -41,11 +41,11 @@ class CleanPreviewsTest extends TestCase {
);
}
- public function testGetName() {
+ public function testGetName(): void {
$this->assertSame('Add preview cleanup background jobs', $this->repair->getName());
}
- public function testRun() {
+ public function testRun(): void {
$user1 = $this->createMock(IUser::class);
$user1->method('getUID')
->willReturn('user1');
@@ -92,7 +92,7 @@ class CleanPreviewsTest extends TestCase {
}
- public function testRunAlreadyDoone() {
+ public function testRunAlreadyDoone(): void {
$this->userManager->expects($this->never())
->method($this->anything());
diff --git a/tests/Test/Repair/Owncloud/UpdateLanguageCodesTest.php b/tests/Test/Repair/Owncloud/UpdateLanguageCodesTest.php
index 879223bed4c..5bfd2e1e6d0 100644
--- a/tests/Test/Repair/Owncloud/UpdateLanguageCodesTest.php
+++ b/tests/Test/Repair/Owncloud/UpdateLanguageCodesTest.php
@@ -33,7 +33,7 @@ class UpdateLanguageCodesTest extends TestCase {
$this->config = $this->createMock(IConfig::class);
}
- public function testRun() {
+ public function testRun(): void {
$users = [
['userid' => 'user1', 'configvalue' => 'fi_FI'],
['userid' => 'user2', 'configvalue' => 'de'],
@@ -131,7 +131,7 @@ class UpdateLanguageCodesTest extends TestCase {
}
}
- public function testSecondRun() {
+ public function testSecondRun(): void {
/** @var IOutput|\PHPUnit_Framework_MockObject_MockObject $outputMock */
$outputMock = $this->createMock(IOutput::class);
$outputMock->expects($this->never())
diff --git a/tests/lib/Accounts/AccountManagerTest.php b/tests/lib/Accounts/AccountManagerTest.php
index 219e32f8c01..ee3c8df0a70 100644
--- a/tests/lib/Accounts/AccountManagerTest.php
+++ b/tests/lib/Accounts/AccountManagerTest.php
@@ -474,7 +474,7 @@ class AccountManagerTest extends TestCase {
* @dataProvider dataTrueFalse
*
*/
- public function testUpdateUser(array $newData, array $oldData, bool $insertNew, bool $updateExisting) {
+ public function testUpdateUser(array $newData, array $oldData, bool $insertNew, bool $updateExisting): void {
$accountManager = $this->getInstance(['getUser', 'insertNewUser', 'updateExistingUser']);
/** @var IUser $user */
$user = $this->createMock(IUser::class);
@@ -516,7 +516,7 @@ class AccountManagerTest extends TestCase {
];
}
- public function testAddMissingDefaults() {
+ public function testAddMissingDefaults(): void {
$user = $this->createMock(IUser::class);
$this->config
@@ -635,7 +635,7 @@ class AccountManagerTest extends TestCase {
$this->assertSame($expected, $result);
}
- public function testGetAccount() {
+ public function testGetAccount(): void {
$accountManager = $this->getInstance(['getUser']);
/** @var IUser $user */
$user = $this->createMock(IUser::class);
diff --git a/tests/lib/Accounts/AccountPropertyCollectionTest.php b/tests/lib/Accounts/AccountPropertyCollectionTest.php
index 83a39dca94f..fa4db10d3d9 100644
--- a/tests/lib/Accounts/AccountPropertyCollectionTest.php
+++ b/tests/lib/Accounts/AccountPropertyCollectionTest.php
@@ -40,7 +40,7 @@ class AccountPropertyCollectionTest extends TestCase {
return $mock;
}
- public function testSetAndGetProperties() {
+ public function testSetAndGetProperties(): void {
$propsBefore = $this->collection->getProperties();
$this->assertIsArray($propsBefore);
$this->assertEmpty($propsBefore);
@@ -57,7 +57,7 @@ class AccountPropertyCollectionTest extends TestCase {
$this->assertCount(count($props), $propsAfter);
}
- public function testSetPropertiesMixedInvalid() {
+ public function testSetPropertiesMixedInvalid(): void {
$props = [
$this->makePropertyMock(self::COLLECTION_NAME),
$this->makePropertyMock('sneaky_property'),
@@ -68,7 +68,7 @@ class AccountPropertyCollectionTest extends TestCase {
$this->collection->setProperties($props);
}
- public function testAddProperty() {
+ public function testAddProperty(): void {
$props = [
$this->makePropertyMock(self::COLLECTION_NAME),
$this->makePropertyMock(self::COLLECTION_NAME),
@@ -84,7 +84,7 @@ class AccountPropertyCollectionTest extends TestCase {
$this->assertNotFalse(array_search($additionalProperty, $propsAfter, true));
}
- public function testAddPropertyInvalid() {
+ public function testAddPropertyInvalid(): void {
$props = [
$this->makePropertyMock(self::COLLECTION_NAME),
$this->makePropertyMock(self::COLLECTION_NAME),
@@ -106,7 +106,7 @@ class AccountPropertyCollectionTest extends TestCase {
}
}
- public function testRemoveProperty() {
+ public function testRemoveProperty(): void {
$additionalProperty = $this->makePropertyMock(self::COLLECTION_NAME);
$props = [
$this->makePropertyMock(self::COLLECTION_NAME),
@@ -125,7 +125,7 @@ class AccountPropertyCollectionTest extends TestCase {
$this->assertFalse(array_search($additionalProperty, $propsAfter, true));
}
- public function testRemovePropertyNotFound() {
+ public function testRemovePropertyNotFound(): void {
$additionalProperty = $this->makePropertyMock(self::COLLECTION_NAME);
$props = [
$this->makePropertyMock(self::COLLECTION_NAME),
@@ -142,7 +142,7 @@ class AccountPropertyCollectionTest extends TestCase {
$this->assertCount(count($propsBefore), $propsAfter);
}
- public function testRemovePropertyByValue() {
+ public function testRemovePropertyByValue(): void {
$additionalProperty = $this->makePropertyMock(self::COLLECTION_NAME);
$additionalProperty->expects($this->any())
->method('getValue')
@@ -169,7 +169,7 @@ class AccountPropertyCollectionTest extends TestCase {
$this->assertFalse(array_search($additionalPropertyTwo, $propsAfter, true));
}
- public function testRemovePropertyByValueNotFound() {
+ public function testRemovePropertyByValueNotFound(): void {
$additionalProperty = $this->makePropertyMock(self::COLLECTION_NAME);
$additionalProperty->expects($this->any())
->method('getValue')
diff --git a/tests/lib/Accounts/AccountPropertyTest.php b/tests/lib/Accounts/AccountPropertyTest.php
index f8aefccdbaa..5df66eaa117 100644
--- a/tests/lib/Accounts/AccountPropertyTest.php
+++ b/tests/lib/Accounts/AccountPropertyTest.php
@@ -16,7 +16,7 @@ use Test\TestCase;
* @package Test\Accounts
*/
class AccountPropertyTest extends TestCase {
- public function testConstructor() {
+ public function testConstructor(): void {
$accountProperty = new AccountProperty(
IAccountManager::PROPERTY_WEBSITE,
'https://example.com',
@@ -30,7 +30,7 @@ class AccountPropertyTest extends TestCase {
$this->assertEquals(IAccountManager::VERIFIED, $accountProperty->getVerified());
}
- public function testSetValue() {
+ public function testSetValue(): void {
$accountProperty = new AccountProperty(
IAccountManager::PROPERTY_WEBSITE,
'https://example.com',
@@ -43,7 +43,7 @@ class AccountPropertyTest extends TestCase {
$this->assertEquals('https://example.org', $actualReturn->getValue());
}
- public function testSetScope() {
+ public function testSetScope(): void {
$accountProperty = new AccountProperty(
IAccountManager::PROPERTY_WEBSITE,
'https://example.com',
@@ -77,7 +77,7 @@ class AccountPropertyTest extends TestCase {
/**
* @dataProvider scopesProvider
*/
- public function testSetScopeMapping(string $storedScope, ?string $returnedScope) {
+ public function testSetScopeMapping(string $storedScope, ?string $returnedScope): void {
if ($returnedScope === null) {
$this->expectException(\InvalidArgumentException::class);
}
@@ -91,7 +91,7 @@ class AccountPropertyTest extends TestCase {
$this->assertEquals($returnedScope, $accountProperty->getScope());
}
- public function testSetVerified() {
+ public function testSetVerified(): void {
$accountProperty = new AccountProperty(
IAccountManager::PROPERTY_WEBSITE,
'https://example.com',
@@ -104,7 +104,7 @@ class AccountPropertyTest extends TestCase {
$this->assertEquals(IAccountManager::NOT_VERIFIED, $actualReturn->getVerified());
}
- public function testSetVerificationData() {
+ public function testSetVerificationData(): void {
$accountProperty = new AccountProperty(
IAccountManager::PROPERTY_WEBSITE,
'https://example.com',
@@ -118,7 +118,7 @@ class AccountPropertyTest extends TestCase {
$this->assertEquals($token, $actualReturn->getVerificationData());
}
- public function testJsonSerialize() {
+ public function testJsonSerialize(): void {
$accountProperty = new AccountProperty(
IAccountManager::PROPERTY_WEBSITE,
'https://example.com',
diff --git a/tests/lib/Accounts/AccountTest.php b/tests/lib/Accounts/AccountTest.php
index d9242b073af..34653bd864a 100644
--- a/tests/lib/Accounts/AccountTest.php
+++ b/tests/lib/Accounts/AccountTest.php
@@ -19,13 +19,13 @@ use Test\TestCase;
* @package Test\Accounts
*/
class AccountTest extends TestCase {
- public function testConstructor() {
+ public function testConstructor(): void {
$user = $this->createMock(IUser::class);
$account = new Account($user);
$this->assertEquals($user, $account->getUser());
}
- public function testSetProperty() {
+ public function testSetProperty(): void {
$user = $this->createMock(IUser::class);
$property = new AccountProperty(IAccountManager::PROPERTY_WEBSITE, 'https://example.com', IAccountManager::SCOPE_PUBLISHED, IAccountManager::NOT_VERIFIED, '');
$account = new Account($user);
@@ -33,7 +33,7 @@ class AccountTest extends TestCase {
$this->assertEquals($property, $account->getProperty(IAccountManager::PROPERTY_WEBSITE));
}
- public function testGetAndGetAllProperties() {
+ public function testGetAndGetAllProperties(): void {
$user = $this->createMock(IUser::class);
$properties = [
IAccountManager::PROPERTY_WEBSITE => new AccountProperty(IAccountManager::PROPERTY_WEBSITE, 'https://example.com', IAccountManager::SCOPE_PUBLISHED, IAccountManager::NOT_VERIFIED, ''),
@@ -53,7 +53,7 @@ class AccountTest extends TestCase {
$this->assertEquals(array_values($properties), \iterator_to_array($account->getAllProperties()));
}
- public function testSetAllPropertiesFromJson() {
+ public function testSetAllPropertiesFromJson(): void {
$user = $this->createMock(IUser::class);
$properties = [
IAccountManager::PROPERTY_DISPLAYNAME => new AccountProperty(IAccountManager::PROPERTY_DISPLAYNAME, 'Steve', IAccountManager::SCOPE_FEDERATED, IAccountManager::NOT_VERIFIED, ''),
@@ -78,7 +78,7 @@ class AccountTest extends TestCase {
$this->assertEquals($properties, $account->jsonSerialize());
}
- public function testGetFilteredProperties() {
+ public function testGetFilteredProperties(): void {
$user = $this->createMock(IUser::class);
$properties = [
IAccountManager::PROPERTY_WEBSITE => new AccountProperty(IAccountManager::PROPERTY_WEBSITE, 'https://example.com', IAccountManager::SCOPE_PUBLISHED, IAccountManager::NOT_VERIFIED, ''),
@@ -124,7 +124,7 @@ class AccountTest extends TestCase {
);
}
- public function testJsonSerialize() {
+ public function testJsonSerialize(): void {
$user = $this->createMock(IUser::class);
$properties = [
IAccountManager::PROPERTY_WEBSITE => new AccountProperty(IAccountManager::PROPERTY_WEBSITE, 'https://example.com', IAccountManager::SCOPE_PUBLISHED, IAccountManager::NOT_VERIFIED, ''),
diff --git a/tests/lib/Accounts/HooksTest.php b/tests/lib/Accounts/HooksTest.php
index df9420140d3..75772089f43 100644
--- a/tests/lib/Accounts/HooksTest.php
+++ b/tests/lib/Accounts/HooksTest.php
@@ -51,7 +51,7 @@ class HooksTest extends TestCase {
* @param $setDisplayName
* @param $error
*/
- public function testChangeUserHook($params, $data, $setEmail, $setDisplayName, $error) {
+ public function testChangeUserHook($params, $data, $setEmail, $setDisplayName, $error): void {
if ($error) {
$this->accountManager->expects($this->never())->method('updateAccount');
} else {
diff --git a/tests/lib/Activity/ManagerTest.php b/tests/lib/Activity/ManagerTest.php
index 931ea7e974e..c042a3a76a7 100644
--- a/tests/lib/Activity/ManagerTest.php
+++ b/tests/lib/Activity/ManagerTest.php
@@ -56,14 +56,14 @@ class ManagerTest extends TestCase {
$this->assertNotEmpty(self::invokePrivate($this->activityManager, 'getConsumers'));
}
- public function testGetConsumers() {
+ public function testGetConsumers(): void {
$consumers = self::invokePrivate($this->activityManager, 'getConsumers');
$this->assertNotEmpty($consumers);
}
- public function testGetConsumersInvalidConsumer() {
+ public function testGetConsumersInvalidConsumer(): void {
$this->expectException(\InvalidArgumentException::class);
$this->activityManager->registerConsumer(function () {
@@ -90,7 +90,7 @@ class ManagerTest extends TestCase {
* @param string $token
* @param array $users
*/
- public function testGetUserFromTokenThrowInvalidToken($token, $users) {
+ public function testGetUserFromTokenThrowInvalidToken($token, $users): void {
$this->expectException(\UnexpectedValueException::class);
$this->mockRSSToken($token, $token, $users);
@@ -112,7 +112,7 @@ class ManagerTest extends TestCase {
* @param string $token
* @param string $expected
*/
- public function testGetUserFromToken($userLoggedIn, $token, $expected) {
+ public function testGetUserFromToken($userLoggedIn, $token, $expected): void {
if ($userLoggedIn !== null) {
$this->mockUserSession($userLoggedIn);
}
@@ -152,7 +152,7 @@ class ManagerTest extends TestCase {
}
- public function testPublishExceptionNoApp() {
+ public function testPublishExceptionNoApp(): void {
$this->expectException(IncompleteActivityException::class);
$event = $this->activityManager->generateEvent();
@@ -160,7 +160,7 @@ class ManagerTest extends TestCase {
}
- public function testPublishExceptionNoType() {
+ public function testPublishExceptionNoType(): void {
$this->expectException(IncompleteActivityException::class);
$event = $this->activityManager->generateEvent();
@@ -169,7 +169,7 @@ class ManagerTest extends TestCase {
}
- public function testPublishExceptionNoAffectedUser() {
+ public function testPublishExceptionNoAffectedUser(): void {
$this->expectException(IncompleteActivityException::class);
$event = $this->activityManager->generateEvent();
@@ -179,7 +179,7 @@ class ManagerTest extends TestCase {
}
- public function testPublishExceptionNoSubject() {
+ public function testPublishExceptionNoSubject(): void {
$this->expectException(IncompleteActivityException::class);
$event = $this->activityManager->generateEvent();
@@ -201,7 +201,7 @@ class ManagerTest extends TestCase {
* @param string|null $author
* @param string $expected
*/
- public function testPublish($author, $expected) {
+ public function testPublish($author, $expected): void {
if ($author !== null) {
$authorObject = $this->getMockBuilder(IUser::class)
->disableOriginalConstructor()
@@ -239,7 +239,7 @@ class ManagerTest extends TestCase {
$this->activityManager->publish($event);
}
- public function testPublishAllManually() {
+ public function testPublishAllManually(): void {
$event = $this->activityManager->generateEvent();
$event->setApp('test_app')
->setType('test_type')
diff --git a/tests/lib/AllConfigTest.php b/tests/lib/AllConfigTest.php
index 11d4ff4ded5..ed3079e4c92 100644
--- a/tests/lib/AllConfigTest.php
+++ b/tests/lib/AllConfigTest.php
@@ -37,7 +37,7 @@ class AllConfigTest extends \Test\TestCase {
return new \OC\AllConfig($systemConfig, $connection);
}
- public function testDeleteUserValue() {
+ public function testDeleteUserValue(): void {
$config = $this->getConfig();
// preparation - add something to the database
@@ -58,7 +58,7 @@ class AllConfigTest extends \Test\TestCase {
$this->assertEquals(0, $actualCount, 'There was one value in the database and after the tests there should be no entry left.');
}
- public function testSetUserValue() {
+ public function testSetUserValue(): void {
$selectAllSQL = 'SELECT `userid`, `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?';
$config = $this->getConfig();
@@ -91,7 +91,7 @@ class AllConfigTest extends \Test\TestCase {
$config->deleteUserValue('userSet', 'appSet', 'keySet');
}
- public function testSetUserValueWithPreCondition() {
+ public function testSetUserValueWithPreCondition(): void {
$config = $this->getConfig();
$selectAllSQL = 'SELECT `userid`, `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?';
@@ -138,7 +138,7 @@ class AllConfigTest extends \Test\TestCase {
* @dataProvider dataSetUserValueUnexpectedValue
* @param mixed $value
*/
- public function testSetUserValueUnexpectedValue($value) {
+ public function testSetUserValueUnexpectedValue($value): void {
$this->expectException(\UnexpectedValueException::class);
$config = $this->getConfig();
@@ -146,7 +146,7 @@ class AllConfigTest extends \Test\TestCase {
}
- public function testSetUserValueWithPreConditionFailure() {
+ public function testSetUserValueWithPreConditionFailure(): void {
$this->expectException(\OCP\PreConditionNotMetException::class);
$config = $this->getConfig();
@@ -218,7 +218,7 @@ class AllConfigTest extends \Test\TestCase {
$config->deleteUserValue('userPreCond1', 'appPreCond', 'keyPreCond');
}
- public function testSetUserValueUnchanged() {
+ public function testSetUserValueUnchanged(): void {
// TODO - FIXME until the dependency injection is handled properly (in AllConfig)
$this->markTestSkipped('Skipped because this is just testable if database connection can be injected');
@@ -243,7 +243,7 @@ class AllConfigTest extends \Test\TestCase {
$config->setUserValue('userSetUnchanged', 'appSetUnchanged', 'keySetUnchanged', 'valueSetUnchanged');
}
- public function testGetUserValue() {
+ public function testGetUserValue(): void {
$config = $this->getConfig();
// setup - it therefore relies on the successful execution of the previous test
@@ -281,7 +281,7 @@ class AllConfigTest extends \Test\TestCase {
$this->assertEquals(0, count($result));
}
- public function testGetUserKeys() {
+ public function testGetUserKeys(): void {
$config = $this->getConfig();
// preparation - add something to the database
@@ -312,7 +312,7 @@ class AllConfigTest extends \Test\TestCase {
$this->connection->executeUpdate('DELETE FROM `*PREFIX*preferences`');
}
- public function testGetUserKeysAllInts() {
+ public function testGetUserKeysAllInts(): void {
$config = $this->getConfig();
// preparation - add something to the database
@@ -337,7 +337,7 @@ class AllConfigTest extends \Test\TestCase {
$this->connection->executeUpdate('DELETE FROM `*PREFIX*preferences`');
}
- public function testGetUserValueDefault() {
+ public function testGetUserValueDefault(): void {
$config = $this->getConfig();
$this->assertEquals('', $config->getUserValue('userGetUnset', 'appGetUnset', 'keyGetUnset'));
@@ -345,7 +345,7 @@ class AllConfigTest extends \Test\TestCase {
$this->assertEquals('foobar', $config->getUserValue('userGetUnset', 'appGetUnset', 'keyGetUnset', 'foobar'));
}
- public function testGetUserValueForUsers() {
+ public function testGetUserValueForUsers(): void {
$config = $this->getConfig();
// preparation - add something to the database
@@ -386,7 +386,7 @@ class AllConfigTest extends \Test\TestCase {
$this->connection->executeUpdate('DELETE FROM `*PREFIX*preferences`');
}
- public function testDeleteAllUserValues() {
+ public function testDeleteAllUserValues(): void {
$config = $this->getConfig();
// preparation - add something to the database
@@ -420,7 +420,7 @@ class AllConfigTest extends \Test\TestCase {
$this->connection->executeUpdate('DELETE FROM `*PREFIX*preferences`');
}
- public function testDeleteAppFromAllUsers() {
+ public function testDeleteAppFromAllUsers(): void {
$config = $this->getConfig();
// preparation - add something to the database
@@ -463,7 +463,7 @@ class AllConfigTest extends \Test\TestCase {
$this->connection->executeUpdate('DELETE FROM `*PREFIX*preferences`');
}
- public function testGetUsersForUserValue() {
+ public function testGetUsersForUserValue(): void {
// mock the check for the database to run the correct SQL statements for each database type
$systemConfig = $this->getMockBuilder(\OC\SystemConfig::class)
->disableOriginalConstructor()
@@ -494,7 +494,7 @@ class AllConfigTest extends \Test\TestCase {
$this->connection->executeUpdate('DELETE FROM `*PREFIX*preferences`');
}
- public function testGetUsersForUserValueCaseInsensitive() {
+ public function testGetUsersForUserValueCaseInsensitive(): void {
// mock the check for the database to run the correct SQL statements for each database type
$systemConfig = $this->createMock(SystemConfig::class);
$config = $this->getConfig($systemConfig);
diff --git a/tests/lib/App/AppManagerTest.php b/tests/lib/App/AppManagerTest.php
index ac470c00335..5c79a75bf0d 100644
--- a/tests/lib/App/AppManagerTest.php
+++ b/tests/lib/App/AppManagerTest.php
@@ -142,7 +142,7 @@ class AppManagerTest extends TestCase {
/**
* @dataProvider dataGetAppIcon
*/
- public function testGetAppIcon($callback, ?bool $dark, string|null $expected) {
+ public function testGetAppIcon($callback, ?bool $dark, string|null $expected): void {
$this->urlGenerator->expects($this->atLeastOnce())
->method('imagePath')
->willReturnCallback($callback);
@@ -229,7 +229,7 @@ class AppManagerTest extends TestCase {
];
}
- public function testEnableApp() {
+ public function testEnableApp(): void {
// making sure "files_trashbin" is disabled
if ($this->manager->isEnabledForUser('files_trashbin')) {
$this->manager->disableApp('files_trashbin');
@@ -239,13 +239,13 @@ class AppManagerTest extends TestCase {
$this->assertEquals('yes', $this->appConfig->getValue('files_trashbin', 'enabled', 'no'));
}
- public function testDisableApp() {
+ public function testDisableApp(): void {
$this->eventDispatcher->expects($this->once())->method('dispatchTyped')->with(new AppDisableEvent('files_trashbin'));
$this->manager->disableApp('files_trashbin');
$this->assertEquals('no', $this->appConfig->getValue('files_trashbin', 'enabled', 'no'));
}
- public function testNotEnableIfNotInstalled() {
+ public function testNotEnableIfNotInstalled(): void {
try {
$this->manager->enableApp('some_random_name_which_i_hope_is_not_an_app');
$this->assertFalse(true, 'If this line is reached the expected exception is not thrown.');
@@ -259,7 +259,7 @@ class AppManagerTest extends TestCase {
));
}
- public function testEnableAppForGroups() {
+ public function testEnableAppForGroups(): void {
$group1 = $this->createMock(IGroup::class);
$group1->method('getGID')
->willReturn('group1');
@@ -312,7 +312,7 @@ class AppManagerTest extends TestCase {
*
* @param array $appInfo
*/
- public function testEnableAppForGroupsAllowedTypes(array $appInfo) {
+ public function testEnableAppForGroupsAllowedTypes(array $appInfo): void {
$group1 = $this->createMock(IGroup::class);
$group1->method('getGID')
->willReturn('group1');
@@ -370,7 +370,7 @@ class AppManagerTest extends TestCase {
* @param string $type
*
*/
- public function testEnableAppForGroupsForbiddenTypes($type) {
+ public function testEnableAppForGroupsForbiddenTypes($type): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('test can\'t be enabled for groups.');
@@ -416,17 +416,17 @@ class AppManagerTest extends TestCase {
$manager->enableAppForGroups('test', $groups);
}
- public function testIsInstalledEnabled() {
+ public function testIsInstalledEnabled(): void {
$this->appConfig->setValue('test', 'enabled', 'yes');
$this->assertTrue($this->manager->isInstalled('test'));
}
- public function testIsInstalledDisabled() {
+ public function testIsInstalledDisabled(): void {
$this->appConfig->setValue('test', 'enabled', 'no');
$this->assertFalse($this->manager->isInstalled('test'));
}
- public function testIsInstalledEnabledForGroups() {
+ public function testIsInstalledEnabledForGroups(): void {
$this->appConfig->setValue('test', 'enabled', '["foo"]');
$this->assertTrue($this->manager->isInstalled('test'));
}
@@ -439,23 +439,23 @@ class AppManagerTest extends TestCase {
return $user;
}
- public function testIsEnabledForUserEnabled() {
+ public function testIsEnabledForUserEnabled(): void {
$this->appConfig->setValue('test', 'enabled', 'yes');
$user = $this->newUser('user1');
$this->assertTrue($this->manager->isEnabledForUser('test', $user));
}
- public function testIsEnabledForUserDisabled() {
+ public function testIsEnabledForUserDisabled(): void {
$this->appConfig->setValue('test', 'enabled', 'no');
$user = $this->newUser('user1');
$this->assertFalse($this->manager->isEnabledForUser('test', $user));
}
- public function testGetAppPath() {
+ public function testGetAppPath(): void {
$this->assertEquals(\OC::$SERVERROOT . '/apps/files', $this->manager->getAppPath('files'));
}
- public function testGetAppPathSymlink() {
+ public function testGetAppPathSymlink(): void {
$fakeAppDirname = sha1(uniqid('test', true));
$fakeAppPath = sys_get_temp_dir() . '/' . $fakeAppDirname;
$fakeAppLink = \OC::$SERVERROOT . '/' . $fakeAppDirname;
@@ -484,12 +484,12 @@ class AppManagerTest extends TestCase {
$this->assertEquals($fakeAppLink . '/test-test-app', $generatedAppPath);
}
- public function testGetAppPathFail() {
+ public function testGetAppPathFail(): void {
$this->expectException(AppPathNotFoundException::class);
$this->manager->getAppPath('testnotexisting');
}
- public function testIsEnabledForUserEnabledForGroup() {
+ public function testIsEnabledForUserEnabledForGroup(): void {
$user = $this->newUser('user1');
$this->groupManager->expects($this->once())
->method('getUserGroupIds')
@@ -500,7 +500,7 @@ class AppManagerTest extends TestCase {
$this->assertTrue($this->manager->isEnabledForUser('test', $user));
}
- public function testIsEnabledForUserDisabledForGroup() {
+ public function testIsEnabledForUserDisabledForGroup(): void {
$user = $this->newUser('user1');
$this->groupManager->expects($this->once())
->method('getUserGroupIds')
@@ -511,12 +511,12 @@ class AppManagerTest extends TestCase {
$this->assertFalse($this->manager->isEnabledForUser('test', $user));
}
- public function testIsEnabledForUserLoggedOut() {
+ public function testIsEnabledForUserLoggedOut(): void {
$this->appConfig->setValue('test', 'enabled', '["foo"]');
$this->assertFalse($this->manager->isEnabledForUser('test'));
}
- public function testIsEnabledForUserLoggedIn() {
+ public function testIsEnabledForUserLoggedIn(): void {
$user = $this->newUser('user1');
$this->userSession->expects($this->once())
@@ -531,7 +531,7 @@ class AppManagerTest extends TestCase {
$this->assertTrue($this->manager->isEnabledForUser('test'));
}
- public function testGetInstalledApps() {
+ public function testGetInstalledApps(): void {
$this->appConfig->setValue('test1', 'enabled', 'yes');
$this->appConfig->setValue('test2', 'enabled', 'no');
$this->appConfig->setValue('test3', 'enabled', '["foo"]');
@@ -554,7 +554,7 @@ class AppManagerTest extends TestCase {
$this->assertEquals($apps, $this->manager->getInstalledApps());
}
- public function testGetAppsForUser() {
+ public function testGetAppsForUser(): void {
$user = $this->newUser('user1');
$this->groupManager->expects($this->any())
->method('getUserGroupIds')
@@ -584,7 +584,7 @@ class AppManagerTest extends TestCase {
$this->assertEquals($enabled, $this->manager->getEnabledAppsForUser($user));
}
- public function testGetAppsNeedingUpgrade() {
+ public function testGetAppsNeedingUpgrade(): void {
/** @var AppManager|MockObject $manager */
$manager = $this->getMockBuilder(AppManager::class)
->setConstructorArgs([
@@ -642,7 +642,7 @@ class AppManagerTest extends TestCase {
$this->assertEquals('test4', $apps[1]['id']);
}
- public function testGetIncompatibleApps() {
+ public function testGetIncompatibleApps(): void {
/** @var AppManager|MockObject $manager */
$manager = $this->getMockBuilder(AppManager::class)
->setConstructorArgs([
@@ -694,7 +694,7 @@ class AppManagerTest extends TestCase {
$this->assertEquals('test3', $apps[1]['id']);
}
- public function testGetEnabledAppsForGroup() {
+ public function testGetEnabledAppsForGroup(): void {
$group = $this->createMock(IGroup::class);
$group->expects($this->any())
->method('getGID')
@@ -723,7 +723,7 @@ class AppManagerTest extends TestCase {
$this->assertEquals($enabled, $this->manager->getEnabledAppsForGroup($group));
}
- public function testGetAppRestriction() {
+ public function testGetAppRestriction(): void {
$this->appConfig->setValue('test1', 'enabled', 'yes');
$this->appConfig->setValue('test2', 'enabled', 'no');
$this->appConfig->setValue('test3', 'enabled', '["foo"]');
diff --git a/tests/lib/App/AppStore/Bundles/BundleBase.php b/tests/lib/App/AppStore/Bundles/BundleBase.php
index 4c31c49cdb1..28fb8a7736b 100644
--- a/tests/lib/App/AppStore/Bundles/BundleBase.php
+++ b/tests/lib/App/AppStore/Bundles/BundleBase.php
@@ -31,15 +31,15 @@ abstract class BundleBase extends TestCase {
});
}
- public function testGetIdentifier() {
+ public function testGetIdentifier(): void {
$this->assertSame($this->bundleIdentifier, $this->bundle->getIdentifier());
}
- public function testGetName() {
+ public function testGetName(): void {
$this->assertSame($this->bundleName, $this->bundle->getName());
}
- public function testGetAppIdentifiers() {
+ public function testGetAppIdentifiers(): void {
$this->assertSame($this->bundleAppIds, $this->bundle->getAppIdentifiers());
}
}
diff --git a/tests/lib/App/AppStore/Bundles/BundleFetcherTest.php b/tests/lib/App/AppStore/Bundles/BundleFetcherTest.php
index 484b81b5197..225dd78a1b4 100644
--- a/tests/lib/App/AppStore/Bundles/BundleFetcherTest.php
+++ b/tests/lib/App/AppStore/Bundles/BundleFetcherTest.php
@@ -32,7 +32,7 @@ class BundleFetcherTest extends TestCase {
);
}
- public function testGetBundles() {
+ public function testGetBundles(): void {
$expected = [
new EnterpriseBundle($this->l10n),
new HubBundle($this->l10n),
@@ -44,13 +44,13 @@ class BundleFetcherTest extends TestCase {
$this->assertEquals($expected, $this->bundleFetcher->getBundles());
}
- public function testGetBundleByIdentifier() {
+ public function testGetBundleByIdentifier(): void {
$this->assertEquals(new EnterpriseBundle($this->l10n), $this->bundleFetcher->getBundleByIdentifier('EnterpriseBundle'));
$this->assertEquals(new GroupwareBundle($this->l10n), $this->bundleFetcher->getBundleByIdentifier('GroupwareBundle'));
}
- public function testGetBundleByIdentifierWithException() {
+ public function testGetBundleByIdentifierWithException(): void {
$this->expectException(\BadMethodCallException::class);
$this->expectExceptionMessage('Bundle with specified identifier does not exist');
diff --git a/tests/lib/App/AppStore/Fetcher/AppDiscoverFetcherTest.php b/tests/lib/App/AppStore/Fetcher/AppDiscoverFetcherTest.php
index 82f40043971..fdc8b45cf70 100644
--- a/tests/lib/App/AppStore/Fetcher/AppDiscoverFetcherTest.php
+++ b/tests/lib/App/AppStore/Fetcher/AppDiscoverFetcherTest.php
@@ -34,7 +34,7 @@ class AppDiscoverFetcherTest extends FetcherBase {
);
}
- public function testAppstoreDisabled() {
+ public function testAppstoreDisabled(): void {
$this->config
->method('getSystemValueBool')
->willReturnCallback(function ($var, $default) {
@@ -50,7 +50,7 @@ class AppDiscoverFetcherTest extends FetcherBase {
$this->assertEquals([], $this->fetcher->get());
}
- public function testNoInternet() {
+ public function testNoInternet(): void {
$this->config
->method('getSystemValueBool')
->willReturnCallback(function ($var, $default) {
@@ -74,7 +74,7 @@ class AppDiscoverFetcherTest extends FetcherBase {
/**
* @dataProvider dataGetETag
*/
- public function testGetEtag(string|null $expected, bool $throws, string $content = '') {
+ public function testGetEtag(string|null $expected, bool $throws, string $content = ''): void {
$folder = $this->createMock(ISimpleFolder::class);
if (!$throws) {
$file = $this->createMock(ISimpleFile::class);
diff --git a/tests/lib/App/AppStore/Fetcher/AppFetcherTest.php b/tests/lib/App/AppStore/Fetcher/AppFetcherTest.php
index 9a04c11a1f3..61fe24be1a9 100644
--- a/tests/lib/App/AppStore/Fetcher/AppFetcherTest.php
+++ b/tests/lib/App/AppStore/Fetcher/AppFetcherTest.php
@@ -1856,7 +1856,7 @@ EJL3BaQAQaASSsvFrcozYxrQG4VzEg==
->willReturn('stable');
}
- public function testGetWithFilter() {
+ public function testGetWithFilter(): void {
$this->config->method('getSystemValueString')
->willReturnCallback(function ($key, $default) {
if ($key === 'version') {
@@ -1939,7 +1939,7 @@ EJL3BaQAQaASSsvFrcozYxrQG4VzEg==
$this->assertEquals(self::$expectedResponse['data'], $this->fetcher->get());
}
- public function testAppstoreDisabled() {
+ public function testAppstoreDisabled(): void {
$this->config
->method('getSystemValueString')
->willReturnCallback(function ($var, $default) {
@@ -1966,7 +1966,7 @@ EJL3BaQAQaASSsvFrcozYxrQG4VzEg==
}
- public function testNoInternet() {
+ public function testNoInternet(): void {
$this->config
->method('getSystemValueString')
->willReturnCallback(function ($var, $default) {
@@ -1994,7 +1994,7 @@ EJL3BaQAQaASSsvFrcozYxrQG4VzEg==
$this->assertEquals([], $this->fetcher->get());
}
- public function testSetVersion() {
+ public function testSetVersion(): void {
$this->config->method('getSystemValueString')
->willReturnCallback(function ($key, $default) {
if ($key === 'version') {
@@ -2078,7 +2078,7 @@ EJL3BaQAQaASSsvFrcozYxrQG4VzEg==
$this->assertEquals(self::$expectedResponse['data'], $this->fetcher->get());
}
- public function testGetAppsAllowlist() {
+ public function testGetAppsAllowlist(): void {
$this->config->method('getSystemValueString')
->willReturnCallback(function ($key, $default) {
if ($key === 'version') {
diff --git a/tests/lib/App/AppStore/Fetcher/CategoryFetcherTest.php b/tests/lib/App/AppStore/Fetcher/CategoryFetcherTest.php
index b7dbf6eccd8..0beb68bf03a 100644
--- a/tests/lib/App/AppStore/Fetcher/CategoryFetcherTest.php
+++ b/tests/lib/App/AppStore/Fetcher/CategoryFetcherTest.php
@@ -24,7 +24,7 @@ class CategoryFetcherTest extends FetcherBase {
);
}
- public function testAppstoreDisabled() {
+ public function testAppstoreDisabled(): void {
$this->config
->method('getSystemValueBool')
->willReturnCallback(function ($var, $default) {
@@ -40,7 +40,7 @@ class CategoryFetcherTest extends FetcherBase {
$this->assertEquals([], $this->fetcher->get());
}
- public function testNoInternet() {
+ public function testNoInternet(): void {
$this->config
->method('getSystemValueBool')
->willReturnCallback(function ($var, $default) {
diff --git a/tests/lib/App/AppStore/Fetcher/FetcherBase.php b/tests/lib/App/AppStore/Fetcher/FetcherBase.php
index f2bc981d4a6..95129b3114d 100644
--- a/tests/lib/App/AppStore/Fetcher/FetcherBase.php
+++ b/tests/lib/App/AppStore/Fetcher/FetcherBase.php
@@ -59,7 +59,7 @@ abstract class FetcherBase extends TestCase {
$this->registry = $this->createMock(IRegistry::class);
}
- public function testGetWithAlreadyExistingFileAndUpToDateTimestampAndVersion() {
+ public function testGetWithAlreadyExistingFileAndUpToDateTimestampAndVersion(): void {
$this->config
->method('getSystemValueString')
->willReturnCallback(function ($var, $default) {
@@ -100,7 +100,7 @@ abstract class FetcherBase extends TestCase {
$this->assertSame($expected, $this->fetcher->get());
}
- public function testGetWithNotExistingFileAndUpToDateTimestampAndVersion() {
+ public function testGetWithNotExistingFileAndUpToDateTimestampAndVersion(): void {
$this->config
->method('getSystemValueString')
->willReturnCallback(function ($var, $default) {
@@ -175,7 +175,7 @@ abstract class FetcherBase extends TestCase {
$this->assertSame($expected, $this->fetcher->get());
}
- public function testGetWithAlreadyExistingFileAndOutdatedTimestamp() {
+ public function testGetWithAlreadyExistingFileAndOutdatedTimestamp(): void {
$this->config->method('getSystemValueString')
->willReturnCallback(function ($key, $default) {
if ($key === 'version') {
@@ -249,7 +249,7 @@ abstract class FetcherBase extends TestCase {
$this->assertSame($expected, $this->fetcher->get());
}
- public function testGetWithAlreadyExistingFileAndNoVersion() {
+ public function testGetWithAlreadyExistingFileAndNoVersion(): void {
$this->config
->method('getSystemValueString')
->willReturnCallback(function ($var, $default) {
@@ -322,7 +322,7 @@ abstract class FetcherBase extends TestCase {
$this->assertSame($expected, $this->fetcher->get());
}
- public function testGetWithAlreadyExistingFileAndOutdatedVersion() {
+ public function testGetWithAlreadyExistingFileAndOutdatedVersion(): void {
$this->config
->method('getSystemValueString')
->willReturnCallback(function ($var, $default) {
@@ -394,7 +394,7 @@ abstract class FetcherBase extends TestCase {
$this->assertSame($expected, $this->fetcher->get());
}
- public function testGetWithExceptionInClient() {
+ public function testGetWithExceptionInClient(): void {
$this->config->method('getSystemValueString')
->willReturnArgument(1);
$this->config->method('getSystemValueBool')
@@ -430,7 +430,7 @@ abstract class FetcherBase extends TestCase {
$this->assertSame([], $this->fetcher->get());
}
- public function testGetMatchingETag() {
+ public function testGetMatchingETag(): void {
$this->config->method('getSystemValueString')
->willReturnCallback(function ($key, $default) {
if ($key === 'version') {
@@ -509,7 +509,7 @@ abstract class FetcherBase extends TestCase {
$this->assertSame($expected, $this->fetcher->get());
}
- public function testGetNoMatchingETag() {
+ public function testGetNoMatchingETag(): void {
$this->config->method('getSystemValueString')
->willReturnCallback(function ($key, $default) {
if ($key === 'version') {
@@ -594,7 +594,7 @@ abstract class FetcherBase extends TestCase {
}
- public function testFetchAfterUpgradeNoETag() {
+ public function testFetchAfterUpgradeNoETag(): void {
$this->config->method('getSystemValueString')
->willReturnCallback(function ($key, $default) {
if ($key === 'version') {
diff --git a/tests/lib/App/AppStore/Version/VersionParserTest.php b/tests/lib/App/AppStore/Version/VersionParserTest.php
index c461bf7c6cf..5bd9ee16b39 100644
--- a/tests/lib/App/AppStore/Version/VersionParserTest.php
+++ b/tests/lib/App/AppStore/Version/VersionParserTest.php
@@ -62,12 +62,12 @@ class VersionParserTest extends TestCase {
* @param Version $expected
*/
public function testGetVersion($input,
- Version $expected) {
+ Version $expected): void {
$this->assertEquals($expected, $this->versionParser->getVersion($input));
}
- public function testGetVersionException() {
+ public function testGetVersionException(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Version cannot be parsed: BogusVersion');
@@ -75,7 +75,7 @@ class VersionParserTest extends TestCase {
}
- public function testGetVersionExceptionWithMultiple() {
+ 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 68da79fdc8d..7fece37cf5f 100644
--- a/tests/lib/App/AppStore/Version/VersionTest.php
+++ b/tests/lib/App/AppStore/Version/VersionTest.php
@@ -10,12 +10,12 @@ use OC\App\AppStore\Version\Version;
use Test\TestCase;
class VersionTest extends TestCase {
- public function testGetMinimumVersion() {
+ public function testGetMinimumVersion(): void {
$version = new Version('9', '10');
$this->assertSame('9', $version->getMinimumVersion());
}
- public function testGetMaximumVersion() {
+ public function testGetMaximumVersion(): void {
$version = new Version('9', '10');
$this->assertSame('10', $version->getMaximumVersion());
}
diff --git a/tests/lib/App/CompareVersionTest.php b/tests/lib/App/CompareVersionTest.php
index b9af3a96b22..0d020428fed 100644
--- a/tests/lib/App/CompareVersionTest.php
+++ b/tests/lib/App/CompareVersionTest.php
@@ -58,21 +58,21 @@ class CompareVersionTest extends TestCase {
* @dataProvider comparisonData
*/
public function testComparison(string $actualVersion, string $requiredVersion,
- string $comparator, bool $expected) {
+ string $comparator, bool $expected): void {
$isCompatible = $this->compare->isCompatible($actualVersion, $requiredVersion,
$comparator);
$this->assertEquals($expected, $isCompatible);
}
- public function testInvalidServerVersion() {
+ public function testInvalidServerVersion(): void {
$actualVersion = '13';
$this->expectException(InvalidArgumentException::class);
$this->compare->isCompatible($actualVersion, '13.0.0');
}
- public function testInvalidRequiredVersion() {
+ public function testInvalidRequiredVersion(): void {
$actualVersion = '13.0.0';
$this->expectException(InvalidArgumentException::class);
diff --git a/tests/lib/App/DependencyAnalyzerTest.php b/tests/lib/App/DependencyAnalyzerTest.php
index 7572fd67c8c..31eeb77d7e5 100644
--- a/tests/lib/App/DependencyAnalyzerTest.php
+++ b/tests/lib/App/DependencyAnalyzerTest.php
@@ -74,7 +74,7 @@ class DependencyAnalyzerTest extends TestCase {
* @param string $maxVersion
* @param string $intSize
*/
- public function testPhpVersion($expectedMissing, $minVersion, $maxVersion, $intSize) {
+ public function testPhpVersion($expectedMissing, $minVersion, $maxVersion, $intSize): void {
$app = [
'dependencies' => [
'php' => []
@@ -100,7 +100,7 @@ class DependencyAnalyzerTest extends TestCase {
* @param $expectedMissing
* @param $databases
*/
- public function testDatabases($expectedMissing, $databases) {
+ public function testDatabases($expectedMissing, $databases): void {
$app = [
'dependencies' => [
]
@@ -120,7 +120,7 @@ class DependencyAnalyzerTest extends TestCase {
* @param string $expectedMissing
* @param string|null $commands
*/
- public function testCommand($expectedMissing, $commands) {
+ public function testCommand($expectedMissing, $commands): void {
$app = [
'dependencies' => [
]
@@ -139,7 +139,7 @@ class DependencyAnalyzerTest extends TestCase {
* @param $expectedMissing
* @param $libs
*/
- public function testLibs($expectedMissing, $libs) {
+ public function testLibs($expectedMissing, $libs): void {
$app = [
'dependencies' => [
]
@@ -159,7 +159,7 @@ class DependencyAnalyzerTest extends TestCase {
* @param $expectedMissing
* @param $oss
*/
- public function testOS($expectedMissing, $oss) {
+ public function testOS($expectedMissing, $oss): void {
$app = [
'dependencies' => []
];
@@ -178,7 +178,7 @@ class DependencyAnalyzerTest extends TestCase {
* @param $expectedMissing
* @param $oc
*/
- public function testOC($expectedMissing, $oc) {
+ public function testOC($expectedMissing, $oc): void {
$app = [
'dependencies' => []
];
diff --git a/tests/lib/App/InfoParserTest.php b/tests/lib/App/InfoParserTest.php
index 9affe3ff9ae..914741d05b1 100644
--- a/tests/lib/App/InfoParserTest.php
+++ b/tests/lib/App/InfoParserTest.php
@@ -34,14 +34,14 @@ class InfoParserTest extends TestCase {
/**
* @dataProvider providesInfoXml
*/
- public function testParsingValidXmlWithoutCache($expectedJson, $xmlFile) {
+ public function testParsingValidXmlWithoutCache($expectedJson, $xmlFile): void {
$this->parserTest($expectedJson, $xmlFile);
}
/**
* @dataProvider providesInfoXml
*/
- public function testParsingValidXmlWithCache($expectedJson, $xmlFile) {
+ public function testParsingValidXmlWithCache($expectedJson, $xmlFile): void {
$this->parserTest($expectedJson, $xmlFile, self::$cache);
}
diff --git a/tests/lib/App/PlatformRepositoryTest.php b/tests/lib/App/PlatformRepositoryTest.php
index e1eb7b16b40..921d24159c9 100644
--- a/tests/lib/App/PlatformRepositoryTest.php
+++ b/tests/lib/App/PlatformRepositoryTest.php
@@ -14,7 +14,7 @@ class PlatformRepositoryTest extends \Test\TestCase {
* @param $expected
* @param $input
*/
- public function testVersion($input, $expected) {
+ public function testVersion($input, $expected): void {
$pr = new OC\App\PlatformRepository();
$normalizedVersion = $pr->normalizeVersion($input);
$this->assertEquals($expected, $normalizedVersion);
diff --git a/tests/lib/AppConfigTest.php b/tests/lib/AppConfigTest.php
index 891b40c4c12..e6929484dc5 100644
--- a/tests/lib/AppConfigTest.php
+++ b/tests/lib/AppConfigTest.php
@@ -438,7 +438,7 @@ class AppConfigTest extends TestCase {
$this->assertSame('value', $config->getValueString('non-sensitive-app', 'non-lazy-key', 'default', lazy: true));
}
- public function testGetValueInt() {
+ public function testGetValueInt(): void {
$config = $this->generateAppConfig();
$this->assertSame(42, $config->getValueInt('typed', 'int', 0));
}
@@ -448,7 +448,7 @@ class AppConfigTest extends TestCase {
$this->assertSame(1, $config->getValueInt('typed-1', 'int', 1));
}
- public function testGetValueIntOnNonExistentKeyReturnsDefault() {
+ public function testGetValueIntOnNonExistentKeyReturnsDefault(): void {
$config = $this->generateAppConfig();
$this->assertSame(2, $config->getValueInt('typed', 'int-2', 2));
}
@@ -459,7 +459,7 @@ class AppConfigTest extends TestCase {
$config->getValueInt('typed', 'float');
}
- public function testGetValueFloat() {
+ public function testGetValueFloat(): void {
$config = $this->generateAppConfig();
$this->assertSame(3.14, $config->getValueFloat('typed', 'float', 0));
}
@@ -469,7 +469,7 @@ class AppConfigTest extends TestCase {
$this->assertSame(1.11, $config->getValueFloat('typed-1', 'float', 1.11));
}
- public function testGetValueFloatOnNonExistentKeyReturnsDefault() {
+ public function testGetValueFloatOnNonExistentKeyReturnsDefault(): void {
$config = $this->generateAppConfig();
$this->assertSame(2.22, $config->getValueFloat('typed', 'float-2', 2.22));
}
diff --git a/tests/lib/AppFramework/AppTest.php b/tests/lib/AppFramework/AppTest.php
index 9b29389b675..c23c94716f2 100644
--- a/tests/lib/AppFramework/AppTest.php
+++ b/tests/lib/AppFramework/AppTest.php
@@ -1,221 +1,221 @@
-<?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;
-
-use OC\AppFramework\App;
-use OC\AppFramework\Http\Dispatcher;
-use OCP\AppFramework\Controller;
-use OCP\AppFramework\Http;
-use OCP\AppFramework\Http\Response;
-
-function rrmdir($directory) {
- $files = array_diff(scandir($directory), ['.','..']);
- foreach ($files as $file) {
- if (is_dir($directory . '/' . $file)) {
- rrmdir($directory . '/' . $file);
- } else {
- unlink($directory . '/' . $file);
- }
- }
- return rmdir($directory);
-}
-
-
-class AppTest extends \Test\TestCase {
- private $container;
- private $io;
- private $api;
- private $controller;
- private $dispatcher;
- private $params;
- private $headers;
- private $output;
- private $controllerName;
- private $controllerMethod;
- private $appPath;
-
- protected function setUp(): void {
- parent::setUp();
-
- $this->container = new \OC\AppFramework\DependencyInjection\DIContainer('test', []);
- $this->controller = $this->createMock(Controller::class);
- $this->dispatcher = $this->createMock(Dispatcher::class);
- $this->io = $this->createMock(Http\IOutput::class);
-
- $this->headers = ['key' => 'value'];
- $this->output = 'hi';
- $this->controllerName = 'Controller';
- $this->controllerMethod = 'method';
-
- $this->container[$this->controllerName] = $this->controller;
- $this->container['Dispatcher'] = $this->dispatcher;
- $this->container[\OCP\AppFramework\Http\IOutput::class] = $this->io;
- $this->container['urlParams'] = ['_route' => 'not-profiler'];
-
- $this->appPath = __DIR__ . '/../../../apps/namespacetestapp';
- $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>';
- file_put_contents($infoXmlPath, $xml);
- }
-
-
- public function testControllerNameAndMethodAreBeingPassed() {
- $return = ['HTTP/2.0 200 OK', [], [], null, new Response()];
- $this->dispatcher->expects($this->once())
- ->method('dispatch')
- ->with($this->equalTo($this->controller),
- $this->equalTo($this->controllerMethod))
- ->willReturn($return);
-
- $this->io->expects($this->never())
- ->method('setOutput');
-
- App::main($this->controllerName, $this->controllerMethod,
- $this->container);
- }
-
-
- public function testBuildAppNamespace() {
- $ns = App::buildAppNamespace('someapp');
- $this->assertEquals('OCA\Someapp', $ns);
- }
-
-
- public function testBuildAppNamespaceCore() {
- $ns = App::buildAppNamespace('someapp', 'OC\\');
- $this->assertEquals('OC\Someapp', $ns);
- }
-
-
- public function testBuildAppNamespaceInfoXml() {
- $ns = App::buildAppNamespace('namespacetestapp', 'OCA\\');
- $this->assertEquals('OCA\NameSpaceTestApp', $ns);
- }
-
-
- protected function tearDown(): void {
- rrmdir($this->appPath);
- parent::tearDown();
- }
-
-
- public function testOutputIsPrinted() {
- $return = ['HTTP/2.0 200 OK', [], [], $this->output, new Response()];
- $this->dispatcher->expects($this->once())
- ->method('dispatch')
- ->with($this->equalTo($this->controller),
- $this->equalTo($this->controllerMethod))
- ->willReturn($return);
- $this->io->expects($this->once())
- ->method('setOutput')
- ->with($this->equalTo($this->output));
- App::main($this->controllerName, $this->controllerMethod, $this->container, []);
- }
-
- public function dataNoOutput() {
- return [
- ['HTTP/2.0 204 No content'],
- ['HTTP/2.0 304 Not modified'],
- ];
- }
-
- /**
- * @dataProvider dataNoOutput
- */
- public function testNoOutput(string $statusCode) {
- $return = [$statusCode, [], [], $this->output, new Response()];
- $this->dispatcher->expects($this->once())
- ->method('dispatch')
- ->with($this->equalTo($this->controller),
- $this->equalTo($this->controllerMethod))
- ->willReturn($return);
- $this->io->expects($this->once())
- ->method('setHeader')
- ->with($this->equalTo($statusCode));
- $this->io->expects($this->never())
- ->method('setOutput');
- App::main($this->controllerName, $this->controllerMethod, $this->container, []);
- }
-
-
- public function testCallbackIsCalled() {
- $mock = $this->getMockBuilder(\OCP\AppFramework\Http\ICallbackResponse::class)
- ->getMock();
-
- $return = ['HTTP/2.0 200 OK', [], [], $this->output, $mock];
- $this->dispatcher->expects($this->once())
- ->method('dispatch')
- ->with($this->equalTo($this->controller),
- $this->equalTo($this->controllerMethod))
- ->willReturn($return);
- $mock->expects($this->once())
- ->method('callback');
- App::main($this->controllerName, $this->controllerMethod, $this->container, []);
- }
-
- public function testCoreApp() {
- $this->container['AppName'] = 'core';
- $this->container['OC\Core\Controller\Foo'] = $this->controller;
- $this->container['urlParams'] = ['_route' => 'not-profiler'];
-
- $return = ['HTTP/2.0 200 OK', [], [], null, new Response()];
- $this->dispatcher->expects($this->once())
- ->method('dispatch')
- ->with($this->equalTo($this->controller),
- $this->equalTo($this->controllerMethod))
- ->willReturn($return);
-
- $this->io->expects($this->never())
- ->method('setOutput');
-
- App::main('Foo', $this->controllerMethod, $this->container);
- }
-
- public function testSettingsApp() {
- $this->container['AppName'] = 'settings';
- $this->container['OCA\Settings\Controller\Foo'] = $this->controller;
- $this->container['urlParams'] = ['_route' => 'not-profiler'];
-
- $return = ['HTTP/2.0 200 OK', [], [], null, new Response()];
- $this->dispatcher->expects($this->once())
- ->method('dispatch')
- ->with($this->equalTo($this->controller),
- $this->equalTo($this->controllerMethod))
- ->willReturn($return);
-
- $this->io->expects($this->never())
- ->method('setOutput');
-
- App::main('Foo', $this->controllerMethod, $this->container);
- }
-
- public function testApp() {
- $this->container['AppName'] = 'bar';
- $this->container['OCA\Bar\Controller\Foo'] = $this->controller;
- $this->container['urlParams'] = ['_route' => 'not-profiler'];
-
- $return = ['HTTP/2.0 200 OK', [], [], null, new Response()];
- $this->dispatcher->expects($this->once())
- ->method('dispatch')
- ->with($this->equalTo($this->controller),
- $this->equalTo($this->controllerMethod))
- ->willReturn($return);
-
- $this->io->expects($this->never())
- ->method('setOutput');
-
- App::main('Foo', $this->controllerMethod, $this->container);
- }
-}
+<?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;
+
+use OC\AppFramework\App;
+use OC\AppFramework\Http\Dispatcher;
+use OCP\AppFramework\Controller;
+use OCP\AppFramework\Http;
+use OCP\AppFramework\Http\Response;
+
+function rrmdir($directory) {
+ $files = array_diff(scandir($directory), ['.','..']);
+ foreach ($files as $file) {
+ if (is_dir($directory . '/' . $file)) {
+ rrmdir($directory . '/' . $file);
+ } else {
+ unlink($directory . '/' . $file);
+ }
+ }
+ return rmdir($directory);
+}
+
+
+class AppTest extends \Test\TestCase {
+ private $container;
+ private $io;
+ private $api;
+ private $controller;
+ private $dispatcher;
+ private $params;
+ private $headers;
+ private $output;
+ private $controllerName;
+ private $controllerMethod;
+ private $appPath;
+
+ protected function setUp(): void {
+ parent::setUp();
+
+ $this->container = new \OC\AppFramework\DependencyInjection\DIContainer('test', []);
+ $this->controller = $this->createMock(Controller::class);
+ $this->dispatcher = $this->createMock(Dispatcher::class);
+ $this->io = $this->createMock(Http\IOutput::class);
+
+ $this->headers = ['key' => 'value'];
+ $this->output = 'hi';
+ $this->controllerName = 'Controller';
+ $this->controllerMethod = 'method';
+
+ $this->container[$this->controllerName] = $this->controller;
+ $this->container['Dispatcher'] = $this->dispatcher;
+ $this->container[\OCP\AppFramework\Http\IOutput::class] = $this->io;
+ $this->container['urlParams'] = ['_route' => 'not-profiler'];
+
+ $this->appPath = __DIR__ . '/../../../apps/namespacetestapp';
+ $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>';
+ file_put_contents($infoXmlPath, $xml);
+ }
+
+
+ public function testControllerNameAndMethodAreBeingPassed(): void {
+ $return = ['HTTP/2.0 200 OK', [], [], null, new Response()];
+ $this->dispatcher->expects($this->once())
+ ->method('dispatch')
+ ->with($this->equalTo($this->controller),
+ $this->equalTo($this->controllerMethod))
+ ->willReturn($return);
+
+ $this->io->expects($this->never())
+ ->method('setOutput');
+
+ App::main($this->controllerName, $this->controllerMethod,
+ $this->container);
+ }
+
+
+ public function testBuildAppNamespace(): void {
+ $ns = App::buildAppNamespace('someapp');
+ $this->assertEquals('OCA\Someapp', $ns);
+ }
+
+
+ public function testBuildAppNamespaceCore(): void {
+ $ns = App::buildAppNamespace('someapp', 'OC\\');
+ $this->assertEquals('OC\Someapp', $ns);
+ }
+
+
+ public function testBuildAppNamespaceInfoXml(): void {
+ $ns = App::buildAppNamespace('namespacetestapp', 'OCA\\');
+ $this->assertEquals('OCA\NameSpaceTestApp', $ns);
+ }
+
+
+ protected function tearDown(): void {
+ rrmdir($this->appPath);
+ parent::tearDown();
+ }
+
+
+ public function testOutputIsPrinted(): void {
+ $return = ['HTTP/2.0 200 OK', [], [], $this->output, new Response()];
+ $this->dispatcher->expects($this->once())
+ ->method('dispatch')
+ ->with($this->equalTo($this->controller),
+ $this->equalTo($this->controllerMethod))
+ ->willReturn($return);
+ $this->io->expects($this->once())
+ ->method('setOutput')
+ ->with($this->equalTo($this->output));
+ App::main($this->controllerName, $this->controllerMethod, $this->container, []);
+ }
+
+ public function dataNoOutput() {
+ return [
+ ['HTTP/2.0 204 No content'],
+ ['HTTP/2.0 304 Not modified'],
+ ];
+ }
+
+ /**
+ * @dataProvider dataNoOutput
+ */
+ public function testNoOutput(string $statusCode): void {
+ $return = [$statusCode, [], [], $this->output, new Response()];
+ $this->dispatcher->expects($this->once())
+ ->method('dispatch')
+ ->with($this->equalTo($this->controller),
+ $this->equalTo($this->controllerMethod))
+ ->willReturn($return);
+ $this->io->expects($this->once())
+ ->method('setHeader')
+ ->with($this->equalTo($statusCode));
+ $this->io->expects($this->never())
+ ->method('setOutput');
+ App::main($this->controllerName, $this->controllerMethod, $this->container, []);
+ }
+
+
+ public function testCallbackIsCalled(): void {
+ $mock = $this->getMockBuilder(\OCP\AppFramework\Http\ICallbackResponse::class)
+ ->getMock();
+
+ $return = ['HTTP/2.0 200 OK', [], [], $this->output, $mock];
+ $this->dispatcher->expects($this->once())
+ ->method('dispatch')
+ ->with($this->equalTo($this->controller),
+ $this->equalTo($this->controllerMethod))
+ ->willReturn($return);
+ $mock->expects($this->once())
+ ->method('callback');
+ App::main($this->controllerName, $this->controllerMethod, $this->container, []);
+ }
+
+ public function testCoreApp(): void {
+ $this->container['AppName'] = 'core';
+ $this->container['OC\Core\Controller\Foo'] = $this->controller;
+ $this->container['urlParams'] = ['_route' => 'not-profiler'];
+
+ $return = ['HTTP/2.0 200 OK', [], [], null, new Response()];
+ $this->dispatcher->expects($this->once())
+ ->method('dispatch')
+ ->with($this->equalTo($this->controller),
+ $this->equalTo($this->controllerMethod))
+ ->willReturn($return);
+
+ $this->io->expects($this->never())
+ ->method('setOutput');
+
+ App::main('Foo', $this->controllerMethod, $this->container);
+ }
+
+ public function testSettingsApp(): void {
+ $this->container['AppName'] = 'settings';
+ $this->container['OCA\Settings\Controller\Foo'] = $this->controller;
+ $this->container['urlParams'] = ['_route' => 'not-profiler'];
+
+ $return = ['HTTP/2.0 200 OK', [], [], null, new Response()];
+ $this->dispatcher->expects($this->once())
+ ->method('dispatch')
+ ->with($this->equalTo($this->controller),
+ $this->equalTo($this->controllerMethod))
+ ->willReturn($return);
+
+ $this->io->expects($this->never())
+ ->method('setOutput');
+
+ App::main('Foo', $this->controllerMethod, $this->container);
+ }
+
+ public function testApp(): void {
+ $this->container['AppName'] = 'bar';
+ $this->container['OCA\Bar\Controller\Foo'] = $this->controller;
+ $this->container['urlParams'] = ['_route' => 'not-profiler'];
+
+ $return = ['HTTP/2.0 200 OK', [], [], null, new Response()];
+ $this->dispatcher->expects($this->once())
+ ->method('dispatch')
+ ->with($this->equalTo($this->controller),
+ $this->equalTo($this->controllerMethod))
+ ->willReturn($return);
+
+ $this->io->expects($this->never())
+ ->method('setOutput');
+
+ App::main('Foo', $this->controllerMethod, $this->container);
+ }
+}
diff --git a/tests/lib/AppFramework/Controller/ApiControllerTest.php b/tests/lib/AppFramework/Controller/ApiControllerTest.php
index 6dea9938225..9dd980f975f 100644
--- a/tests/lib/AppFramework/Controller/ApiControllerTest.php
+++ b/tests/lib/AppFramework/Controller/ApiControllerTest.php
@@ -21,7 +21,7 @@ class ApiControllerTest extends \Test\TestCase {
/** @var ChildApiController */
protected $controller;
- public function testCors() {
+ public function testCors(): void {
$request = new Request(
['server' => ['HTTP_ORIGIN' => 'test']],
$this->createMock(IRequestId::class),
diff --git a/tests/lib/AppFramework/Controller/AuthPublicShareControllerTest.php b/tests/lib/AppFramework/Controller/AuthPublicShareControllerTest.php
index bec1b7a2a63..d6e0321023e 100644
--- a/tests/lib/AppFramework/Controller/AuthPublicShareControllerTest.php
+++ b/tests/lib/AppFramework/Controller/AuthPublicShareControllerTest.php
@@ -51,13 +51,13 @@ class AuthPublicShareControllerTest extends \Test\TestCase {
])->getMock();
}
- public function testShowAuthenticate() {
+ public function testShowAuthenticate(): void {
$expects = new TemplateResponse('core', 'publicshareauth', [], 'guest');
$this->assertEquals($expects, $this->controller->showAuthenticate());
}
- public function testAuthenticateAuthenticated() {
+ public function testAuthenticateAuthenticated(): void {
$this->controller->method('isAuthenticated')
->willReturn(true);
@@ -74,7 +74,7 @@ class AuthPublicShareControllerTest extends \Test\TestCase {
$this->assertSame('myLink!', $result->getRedirectURL());
}
- public function testAuthenticateInvalidPassword() {
+ public function testAuthenticateInvalidPassword(): void {
$this->controller->setToken('token');
$this->controller->method('isPasswordProtected')
->willReturn(true);
@@ -94,7 +94,7 @@ class AuthPublicShareControllerTest extends \Test\TestCase {
$this->assertEquals($expects, $result);
}
- public function testAuthenticateValidPassword() {
+ public function testAuthenticateValidPassword(): void {
$this->controller->setToken('token');
$this->controller->method('isPasswordProtected')
->willReturn(true);
diff --git a/tests/lib/AppFramework/Controller/ControllerTest.php b/tests/lib/AppFramework/Controller/ControllerTest.php
index 7a6b3460947..7c466e3a5b7 100644
--- a/tests/lib/AppFramework/Controller/ControllerTest.php
+++ b/tests/lib/AppFramework/Controller/ControllerTest.php
@@ -79,21 +79,21 @@ class ControllerTest extends \Test\TestCase {
}
- public function testFormatResonseInvalidFormat() {
+ public function testFormatResonseInvalidFormat(): void {
$this->expectException(\DomainException::class);
$this->controller->buildResponse(null, 'test');
}
- public function testFormat() {
+ public function testFormat(): void {
$response = $this->controller->buildResponse(['hi'], 'json');
$this->assertEquals(['hi'], $response->getData());
}
- public function testFormatDataResponseJSON() {
+ public function testFormatDataResponseJSON(): void {
$expectedHeaders = [
'test' => 'something',
'Cache-Control' => 'no-cache, no-store, must-revalidate',
@@ -113,7 +113,7 @@ class ControllerTest extends \Test\TestCase {
}
- public function testCustomFormatter() {
+ public function testCustomFormatter(): void {
$response = $this->controller->custom('hi');
$response = $this->controller->buildResponse($response, 'json');
@@ -121,14 +121,14 @@ class ControllerTest extends \Test\TestCase {
}
- public function testDefaultResponderToJSON() {
+ public function testDefaultResponderToJSON(): void {
$responder = $this->controller->getResponderByHTTPHeader('*/*');
$this->assertEquals('json', $responder);
}
- public function testResponderAcceptHeaderParsed() {
+ public function testResponderAcceptHeaderParsed(): void {
$responder = $this->controller->getResponderByHTTPHeader(
'*/*, application/tom, application/json'
);
@@ -137,7 +137,7 @@ class ControllerTest extends \Test\TestCase {
}
- public function testResponderAcceptHeaderParsedUpperCase() {
+ public function testResponderAcceptHeaderParsedUpperCase(): void {
$responder = $this->controller->getResponderByHTTPHeader(
'*/*, apPlication/ToM, application/json'
);
diff --git a/tests/lib/AppFramework/Controller/OCSControllerTest.php b/tests/lib/AppFramework/Controller/OCSControllerTest.php
index ea86c01a364..027881074c9 100644
--- a/tests/lib/AppFramework/Controller/OCSControllerTest.php
+++ b/tests/lib/AppFramework/Controller/OCSControllerTest.php
@@ -20,7 +20,7 @@ class ChildOCSController extends OCSController {
class OCSControllerTest extends \Test\TestCase {
- public function testCors() {
+ public function testCors(): void {
$request = new Request(
[
'server' => [
@@ -45,7 +45,7 @@ class OCSControllerTest extends \Test\TestCase {
}
- public function testXML() {
+ public function testXML(): void {
$controller = new ChildOCSController('app', new Request(
[],
$this->createMock(IRequestId::class),
@@ -74,7 +74,7 @@ class OCSControllerTest extends \Test\TestCase {
$this->assertEquals($expected, $response->render());
}
- public function testJSON() {
+ public function testJSON(): void {
$controller = new ChildOCSController('app', new Request(
[],
$this->createMock(IRequestId::class),
@@ -91,7 +91,7 @@ class OCSControllerTest extends \Test\TestCase {
$this->assertEquals($expected, $response->render());
}
- public function testXMLV2() {
+ public function testXMLV2(): void {
$controller = new ChildOCSController('app', new Request(
[],
$this->createMock(IRequestId::class),
@@ -118,7 +118,7 @@ class OCSControllerTest extends \Test\TestCase {
$this->assertEquals($expected, $response->render());
}
- public function testJSONV2() {
+ public function testJSONV2(): void {
$controller = new ChildOCSController('app', new Request(
[],
$this->createMock(IRequestId::class),
diff --git a/tests/lib/AppFramework/Controller/PublicShareControllerTest.php b/tests/lib/AppFramework/Controller/PublicShareControllerTest.php
index be28843b03f..f8430d42ef1 100644
--- a/tests/lib/AppFramework/Controller/PublicShareControllerTest.php
+++ b/tests/lib/AppFramework/Controller/PublicShareControllerTest.php
@@ -50,7 +50,7 @@ class PublicShareControllerTest extends \Test\TestCase {
$this->session = $this->createMock(ISession::class);
}
- public function testGetToken() {
+ public function testGetToken(): void {
$controller = new TestController('app', $this->request, $this->session, 'hash', false);
$controller->setToken('test');
@@ -73,7 +73,7 @@ class PublicShareControllerTest extends \Test\TestCase {
/**
* @dataProvider dataIsAuthenticated
*/
- public function testIsAuthenticatedNotPasswordProtected(bool $protected, string $token1, string $token2, string $hash1, string $hash2, bool $expected) {
+ 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);
$this->session->method('get')
diff --git a/tests/lib/AppFramework/Db/EntityTest.php b/tests/lib/AppFramework/Db/EntityTest.php
index a521b480f8f..c426faa757d 100644
--- a/tests/lib/AppFramework/Db/EntityTest.php
+++ b/tests/lib/AppFramework/Db/EntityTest.php
@@ -59,7 +59,7 @@ class EntityTest extends \Test\TestCase {
}
- public function testResetUpdatedFields() {
+ public function testResetUpdatedFields(): void {
$entity = new TestEntity();
$entity->setId(3);
$entity->resetUpdatedFields();
@@ -68,7 +68,7 @@ class EntityTest extends \Test\TestCase {
}
- public function testFromRow() {
+ public function testFromRow(): void {
$row = [
'pre_name' => 'john',
'email' => 'john@something.com'
@@ -80,7 +80,7 @@ class EntityTest extends \Test\TestCase {
}
- public function testGetSetId() {
+ public function testGetSetId(): void {
$id = 3;
$this->entity->setId(3);
@@ -88,28 +88,28 @@ class EntityTest extends \Test\TestCase {
}
- public function testColumnToPropertyNoReplacement() {
+ public function testColumnToPropertyNoReplacement(): void {
$column = 'my';
$this->assertEquals('my',
$this->entity->columnToProperty($column));
}
- public function testColumnToProperty() {
+ public function testColumnToProperty(): void {
$column = 'my_attribute';
$this->assertEquals('myAttribute',
$this->entity->columnToProperty($column));
}
- public function testPropertyToColumnNoReplacement() {
+ public function testPropertyToColumnNoReplacement(): void {
$property = 'my';
$this->assertEquals('my',
$this->entity->propertyToColumn($property));
}
- public function testSetterMarksFieldUpdated() {
+ public function testSetterMarksFieldUpdated(): void {
$this->entity->setId(3);
$this->assertContains('id', array_keys($this->entity->getUpdatedFields()));
@@ -117,7 +117,7 @@ class EntityTest extends \Test\TestCase {
- public function testCallShouldOnlyWorkForGetterSetter() {
+ public function testCallShouldOnlyWorkForGetterSetter(): void {
$this->expectException(\BadFunctionCallException::class);
$this->entity->something();
@@ -125,21 +125,21 @@ class EntityTest extends \Test\TestCase {
- public function testGetterShouldFailIfAttributeNotDefined() {
+ public function testGetterShouldFailIfAttributeNotDefined(): void {
$this->expectException(\BadFunctionCallException::class);
$this->entity->getTest();
}
- public function testSetterShouldFailIfAttributeNotDefined() {
+ public function testSetterShouldFailIfAttributeNotDefined(): void {
$this->expectException(\BadFunctionCallException::class);
$this->entity->setTest();
}
- public function testFromRowShouldNotAssignEmptyArray() {
+ public function testFromRowShouldNotAssignEmptyArray(): void {
$row = [];
$entity2 = new TestEntity();
@@ -148,7 +148,7 @@ class EntityTest extends \Test\TestCase {
}
- public function testIdGetsConvertedToInt() {
+ public function testIdGetsConvertedToInt(): void {
$row = ['id' => '4'];
$this->entity = TestEntity::fromRow($row);
@@ -156,7 +156,7 @@ class EntityTest extends \Test\TestCase {
}
- public function testSetType() {
+ public function testSetType(): void {
$row = ['testId' => '4'];
$this->entity = TestEntity::fromRow($row);
@@ -164,7 +164,7 @@ class EntityTest extends \Test\TestCase {
}
- public function testFromParams() {
+ public function testFromParams(): void {
$params = [
'testId' => 4,
'email' => 'john@doe'
@@ -177,7 +177,7 @@ class EntityTest extends \Test\TestCase {
$this->assertTrue($entity instanceof TestEntity);
}
- public function testSlugify() {
+ public function testSlugify(): void {
$entity = new TestEntity();
$entity->setName('Slugify this!');
$this->assertEquals('slugify-this', $entity->slugify('name'));
@@ -186,20 +186,20 @@ class EntityTest extends \Test\TestCase {
}
- public function testSetterCasts() {
+ public function testSetterCasts(): void {
$entity = new TestEntity();
$entity->setId('3');
$this->assertSame(3, $entity->getId());
}
- public function testSetterDoesNotCastOnNull() {
+ public function testSetterDoesNotCastOnNull(): void {
$entity = new TestEntity();
$entity->setId(null);
$this->assertSame(null, $entity->getId());
}
- public function testSetterConvertsResourcesToStringProperly() {
+ public function testSetterConvertsResourcesToStringProperly(): void {
$string = 'Definitely a string';
$stream = fopen('php://memory', 'r+');
fwrite($stream, $string);
@@ -212,7 +212,7 @@ class EntityTest extends \Test\TestCase {
}
- public function testGetFieldTypes() {
+ public function testGetFieldTypes(): void {
$entity = new TestEntity();
$this->assertEquals([
'id' => 'integer',
@@ -224,20 +224,20 @@ class EntityTest extends \Test\TestCase {
}
- public function testGetItInt() {
+ public function testGetItInt(): void {
$entity = new TestEntity();
$entity->setId(3);
$this->assertEquals('integer', gettype($entity->getId()));
}
- public function testFieldsNotMarkedUpdatedIfNothingChanges() {
+ public function testFieldsNotMarkedUpdatedIfNothingChanges(): void {
$entity = new TestEntity('hey');
$entity->setName('hey');
$this->assertEquals(0, count($entity->getUpdatedFields()));
}
- public function testIsGetter() {
+ public function testIsGetter(): void {
$entity = new TestEntity();
$entity->setTrueOrFalse(false);
$entity->setAnotherBool(false);
@@ -246,7 +246,7 @@ class EntityTest extends \Test\TestCase {
}
- public function testIsGetterShoudFailForOtherType() {
+ public function testIsGetterShoudFailForOtherType(): void {
$this->expectException(\BadFunctionCallException::class);
$entity = new TestEntity();
diff --git a/tests/lib/AppFramework/Db/QBMapperTest.php b/tests/lib/AppFramework/Db/QBMapperTest.php
index 1f5250b1456..f08beca05ca 100644
--- a/tests/lib/AppFramework/Db/QBMapperTest.php
+++ b/tests/lib/AppFramework/Db/QBMapperTest.php
@@ -108,7 +108,7 @@ class QBMapperTest extends \Test\TestCase {
}
- public function testInsertEntityParameterTypeMapping() {
+ public function testInsertEntityParameterTypeMapping(): void {
$entity = new QBTestEntity();
$entity->setIntProp(123);
$entity->setBoolProp(true);
@@ -145,7 +145,7 @@ class QBMapperTest extends \Test\TestCase {
}
- public function testUpdateEntityParameterTypeMapping() {
+ public function testUpdateEntityParameterTypeMapping(): void {
$entity = new QBTestEntity();
$entity->setId(789);
$entity->setIntProp(123);
@@ -195,7 +195,7 @@ class QBMapperTest extends \Test\TestCase {
}
- public function testGetParameterTypeForProperty() {
+ public function testGetParameterTypeForProperty(): void {
$entity = new QBTestEntity();
$intType = $this->mapper->getParameterTypeForPropertyForTest($entity, 'intProp');
diff --git a/tests/lib/AppFramework/DependencyInjection/DIContainerTest.php b/tests/lib/AppFramework/DependencyInjection/DIContainerTest.php
index 94264f0de02..f3d2cff1ffd 100644
--- a/tests/lib/AppFramework/DependencyInjection/DIContainerTest.php
+++ b/tests/lib/AppFramework/DependencyInjection/DIContainerTest.php
@@ -35,24 +35,24 @@ class DIContainerTest extends \Test\TestCase {
}
- public function testProvidesRequest() {
+ public function testProvidesRequest(): void {
$this->assertTrue(isset($this->container['Request']));
}
- public function testProvidesMiddlewareDispatcher() {
+ public function testProvidesMiddlewareDispatcher(): void {
$this->assertTrue(isset($this->container['MiddlewareDispatcher']));
}
- public function testProvidesAppName() {
+ public function testProvidesAppName(): void {
$this->assertTrue(isset($this->container['AppName']));
}
- public function testAppNameIsSetCorrectly() {
+ public function testAppNameIsSetCorrectly(): void {
$this->assertEquals('name', $this->container['AppName']);
}
- public function testMiddlewareDispatcherIncludesSecurityMiddleware() {
+ public function testMiddlewareDispatcherIncludesSecurityMiddleware(): void {
$this->container['Request'] = new Request(
['method' => 'GET'],
$this->createMock(IRequestId::class),
@@ -135,7 +135,7 @@ class DIContainerTest extends \Test\TestCase {
$this->fail('Bootstrap registered middleware not found');
}
- public function testInvalidAppClass() {
+ public function testInvalidAppClass(): void {
$this->expectException(QueryException::class);
$this->container->query('\OCA\Name\Foo');
}
diff --git a/tests/lib/AppFramework/DependencyInjection/DIIntergrationTests.php b/tests/lib/AppFramework/DependencyInjection/DIIntergrationTests.php
index ad126ad99e2..54c691d2392 100644
--- a/tests/lib/AppFramework/DependencyInjection/DIIntergrationTests.php
+++ b/tests/lib/AppFramework/DependencyInjection/DIIntergrationTests.php
@@ -48,7 +48,7 @@ class DIIntergrationTests extends TestCase {
$this->container = new DIContainer('App1', [], $this->server);
}
- public function testInjectFromServer() {
+ public function testInjectFromServer(): void {
$this->server->registerService(Interface1::class, function () {
return new ClassA1();
});
@@ -64,7 +64,7 @@ class DIIntergrationTests extends TestCase {
$this->assertSame(ClassA1::class, get_class($res->interface1));
}
- public function testInjectDepFromServer() {
+ public function testInjectDepFromServer(): void {
$this->server->registerService(Interface1::class, function () {
return new ClassA1();
});
@@ -80,7 +80,7 @@ class DIIntergrationTests extends TestCase {
$this->assertSame(ClassA1::class, get_class($res->interface1));
}
- public function testOverwriteDepFromServer() {
+ public function testOverwriteDepFromServer(): void {
$this->server->registerService(Interface1::class, function () {
return new ClassA1();
});
@@ -100,7 +100,7 @@ class DIIntergrationTests extends TestCase {
$this->assertSame(ClassA2::class, get_class($res->interface1));
}
- public function testIgnoreOverwriteInServerClass() {
+ public function testIgnoreOverwriteInServerClass(): void {
$this->server->registerService(Interface1::class, function () {
return new ClassA1();
});
diff --git a/tests/lib/AppFramework/Http/ContentSecurityPolicyTest.php b/tests/lib/AppFramework/Http/ContentSecurityPolicyTest.php
index 465f9ee0a07..aa2b29418e4 100644
--- a/tests/lib/AppFramework/Http/ContentSecurityPolicyTest.php
+++ b/tests/lib/AppFramework/Http/ContentSecurityPolicyTest.php
@@ -23,19 +23,19 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->contentSecurityPolicy = new ContentSecurityPolicy();
}
- public function testGetPolicyDefault() {
+ public function testGetPolicyDefault(): void {
$defaultPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->assertSame($defaultPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyScriptDomainValid() {
+ public function testGetPolicyScriptDomainValid(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self' www.nextcloud.com;style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedScriptDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyScriptDomainValidMultiple() {
+ public function testGetPolicyScriptDomainValidMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self' www.nextcloud.com www.nextcloud.org;style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedScriptDomain('www.nextcloud.com');
@@ -43,7 +43,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowScriptDomain() {
+ public function testGetPolicyDisallowScriptDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedScriptDomain('www.nextcloud.com');
@@ -51,7 +51,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowScriptDomainMultiple() {
+ public function testGetPolicyDisallowScriptDomainMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self' www.nextcloud.com;style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedScriptDomain('www.nextcloud.com');
@@ -59,7 +59,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowScriptDomainMultipleStacked() {
+ public function testGetPolicyDisallowScriptDomainMultipleStacked(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedScriptDomain('www.nextcloud.com');
@@ -67,21 +67,21 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyScriptDisallowEval() {
+ public function testGetPolicyScriptDisallowEval(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->allowEvalScript(false);
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyStyleDomainValid() {
+ public function testGetPolicyStyleDomainValid(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' www.nextcloud.com 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedStyleDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyStyleDomainValidMultiple() {
+ public function testGetPolicyStyleDomainValidMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' www.nextcloud.com www.nextcloud.org 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedStyleDomain('www.nextcloud.com');
@@ -89,7 +89,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowStyleDomain() {
+ public function testGetPolicyDisallowStyleDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedStyleDomain('www.nextcloud.com');
@@ -97,7 +97,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowStyleDomainMultiple() {
+ public function testGetPolicyDisallowStyleDomainMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' www.nextcloud.com 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedStyleDomain('www.nextcloud.com');
@@ -105,7 +105,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowStyleDomainMultipleStacked() {
+ public function testGetPolicyDisallowStyleDomainMultipleStacked(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedStyleDomain('www.nextcloud.com');
@@ -113,35 +113,35 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyStyleAllowInline() {
+ public function testGetPolicyStyleAllowInline(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->allowInlineStyle(true);
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyStyleAllowInlineWithDomain() {
+ public function testGetPolicyStyleAllowInlineWithDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' www.nextcloud.com 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedStyleDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyStyleDisallowInline() {
+ public function testGetPolicyStyleDisallowInline(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->allowInlineStyle(false);
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyImageDomainValid() {
+ public function testGetPolicyImageDomainValid(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob: www.nextcloud.com;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedImageDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyImageDomainValidMultiple() {
+ public function testGetPolicyImageDomainValidMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob: www.nextcloud.com www.nextcloud.org;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedImageDomain('www.nextcloud.com');
@@ -149,7 +149,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowImageDomain() {
+ public function testGetPolicyDisallowImageDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedImageDomain('www.nextcloud.com');
@@ -157,7 +157,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowImageDomainMultiple() {
+ public function testGetPolicyDisallowImageDomainMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob: www.nextcloud.com;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedImageDomain('www.nextcloud.com');
@@ -165,7 +165,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowImageDomainMultipleStakes() {
+ public function testGetPolicyDisallowImageDomainMultipleStakes(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedImageDomain('www.nextcloud.com');
@@ -173,14 +173,14 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyFontDomainValid() {
+ public function testGetPolicyFontDomainValid(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data: www.nextcloud.com;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedFontDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyFontDomainValidMultiple() {
+ public function testGetPolicyFontDomainValidMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data: www.nextcloud.com www.nextcloud.org;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedFontDomain('www.nextcloud.com');
@@ -188,7 +188,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowFontDomain() {
+ public function testGetPolicyDisallowFontDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedFontDomain('www.nextcloud.com');
@@ -196,7 +196,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowFontDomainMultiple() {
+ public function testGetPolicyDisallowFontDomainMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data: www.nextcloud.com;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedFontDomain('www.nextcloud.com');
@@ -204,7 +204,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowFontDomainMultipleStakes() {
+ public function testGetPolicyDisallowFontDomainMultipleStakes(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedFontDomain('www.nextcloud.com');
@@ -212,14 +212,14 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyConnectDomainValid() {
+ public function testGetPolicyConnectDomainValid(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self' www.nextcloud.com;media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedConnectDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyConnectDomainValidMultiple() {
+ public function testGetPolicyConnectDomainValidMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self' www.nextcloud.com www.nextcloud.org;media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedConnectDomain('www.nextcloud.com');
@@ -227,7 +227,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowConnectDomain() {
+ public function testGetPolicyDisallowConnectDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedConnectDomain('www.nextcloud.com');
@@ -235,7 +235,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowConnectDomainMultiple() {
+ public function testGetPolicyDisallowConnectDomainMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self' www.nextcloud.com;media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedConnectDomain('www.nextcloud.com');
@@ -243,7 +243,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowConnectDomainMultipleStakes() {
+ public function testGetPolicyDisallowConnectDomainMultipleStakes(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedConnectDomain('www.nextcloud.com');
@@ -251,14 +251,14 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyMediaDomainValid() {
+ public function testGetPolicyMediaDomainValid(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self' www.nextcloud.com;frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedMediaDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyMediaDomainValidMultiple() {
+ public function testGetPolicyMediaDomainValidMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self' www.nextcloud.com www.nextcloud.org;frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedMediaDomain('www.nextcloud.com');
@@ -266,7 +266,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowMediaDomain() {
+ public function testGetPolicyDisallowMediaDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedMediaDomain('www.nextcloud.com');
@@ -274,7 +274,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowMediaDomainMultiple() {
+ public function testGetPolicyDisallowMediaDomainMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self' www.nextcloud.com;frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedMediaDomain('www.nextcloud.com');
@@ -282,7 +282,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowMediaDomainMultipleStakes() {
+ public function testGetPolicyDisallowMediaDomainMultipleStakes(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedMediaDomain('www.nextcloud.com');
@@ -290,14 +290,14 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyObjectDomainValid() {
+ public function testGetPolicyObjectDomainValid(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';object-src www.nextcloud.com;frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedObjectDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyObjectDomainValidMultiple() {
+ public function testGetPolicyObjectDomainValidMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';object-src www.nextcloud.com www.nextcloud.org;frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedObjectDomain('www.nextcloud.com');
@@ -305,7 +305,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowObjectDomain() {
+ public function testGetPolicyDisallowObjectDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedObjectDomain('www.nextcloud.com');
@@ -313,7 +313,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowObjectDomainMultiple() {
+ public function testGetPolicyDisallowObjectDomainMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';object-src www.nextcloud.com;frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedObjectDomain('www.nextcloud.com');
@@ -321,7 +321,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowObjectDomainMultipleStakes() {
+ public function testGetPolicyDisallowObjectDomainMultipleStakes(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedObjectDomain('www.nextcloud.com');
@@ -329,14 +329,14 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetAllowedFrameDomain() {
+ public function testGetAllowedFrameDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-src www.nextcloud.com;frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedFrameDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyFrameDomainValidMultiple() {
+ public function testGetPolicyFrameDomainValidMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-src www.nextcloud.com www.nextcloud.org;frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedFrameDomain('www.nextcloud.com');
@@ -344,7 +344,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowFrameDomain() {
+ public function testGetPolicyDisallowFrameDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedFrameDomain('www.nextcloud.com');
@@ -352,7 +352,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowFrameDomainMultiple() {
+ public function testGetPolicyDisallowFrameDomainMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-src www.nextcloud.com;frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedFrameDomain('www.nextcloud.com');
@@ -360,7 +360,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowFrameDomainMultipleStakes() {
+ public function testGetPolicyDisallowFrameDomainMultipleStakes(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedFrameDomain('www.nextcloud.com');
@@ -368,14 +368,14 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetAllowedChildSrcDomain() {
+ public function testGetAllowedChildSrcDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';child-src child.nextcloud.com;frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedChildSrcDomain('child.nextcloud.com');
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyChildSrcValidMultiple() {
+ public function testGetPolicyChildSrcValidMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';child-src child.nextcloud.com child.nextcloud.org;frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedChildSrcDomain('child.nextcloud.com');
@@ -383,7 +383,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowChildSrcDomain() {
+ public function testGetPolicyDisallowChildSrcDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedChildSrcDomain('www.nextcloud.com');
@@ -391,7 +391,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowChildSrcDomainMultiple() {
+ public function testGetPolicyDisallowChildSrcDomainMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';child-src www.nextcloud.com;frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedChildSrcDomain('www.nextcloud.com');
@@ -399,7 +399,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowChildSrcDomainMultipleStakes() {
+ public function testGetPolicyDisallowChildSrcDomainMultipleStakes(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedChildSrcDomain('www.nextcloud.com');
@@ -409,14 +409,14 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
- public function testGetAllowedFrameAncestorDomain() {
+ public function testGetAllowedFrameAncestorDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self' sub.nextcloud.com;form-action 'self'";
$this->contentSecurityPolicy->addAllowedFrameAncestorDomain('sub.nextcloud.com');
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyFrameAncestorValidMultiple() {
+ public function testGetPolicyFrameAncestorValidMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self' sub.nextcloud.com foo.nextcloud.com;form-action 'self'";
$this->contentSecurityPolicy->addAllowedFrameAncestorDomain('sub.nextcloud.com');
@@ -424,7 +424,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowFrameAncestorDomain() {
+ public function testGetPolicyDisallowFrameAncestorDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedFrameAncestorDomain('www.nextcloud.com');
@@ -432,7 +432,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowFrameAncestorDomainMultiple() {
+ public function testGetPolicyDisallowFrameAncestorDomainMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self' www.nextcloud.com;form-action 'self'";
$this->contentSecurityPolicy->addAllowedFrameAncestorDomain('www.nextcloud.com');
@@ -440,7 +440,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowFrameAncestorDomainMultipleStakes() {
+ public function testGetPolicyDisallowFrameAncestorDomainMultipleStakes(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->addAllowedChildSrcDomain('www.nextcloud.com');
@@ -448,21 +448,21 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyUnsafeEval() {
+ public function testGetPolicyUnsafeEval(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->allowEvalScript(true);
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyUnsafeWasmEval() {
+ public function testGetPolicyUnsafeWasmEval(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self' 'wasm-unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->allowEvalWasm(true);
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyNonce() {
+ public function testGetPolicyNonce(): void {
$nonce = base64_encode('my-nonce');
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'nonce-$nonce';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
@@ -471,7 +471,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyNonceDefault() {
+ public function testGetPolicyNonceDefault(): void {
$nonce = base64_encode('my-nonce');
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'nonce-$nonce';script-src-elem 'strict-dynamic' 'nonce-$nonce';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
@@ -479,7 +479,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyNonceStrictDynamic() {
+ public function testGetPolicyNonceStrictDynamic(): void {
$nonce = base64_encode('my-nonce');
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'strict-dynamic' 'nonce-$nonce';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
@@ -489,7 +489,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyNonceStrictDynamicDefault() {
+ public function testGetPolicyNonceStrictDynamicDefault(): void {
$nonce = base64_encode('my-nonce');
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'strict-dynamic' 'nonce-$nonce';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
@@ -498,14 +498,14 @@ class ContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyStrictDynamicOnScriptsOff() {
+ public function testGetPolicyStrictDynamicOnScriptsOff(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->useStrictDynamicOnScripts(false);
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyStrictDynamicAndStrictDynamicOnScripts() {
+ public function testGetPolicyStrictDynamicAndStrictDynamicOnScripts(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self';form-action 'self'";
$this->contentSecurityPolicy->useStrictDynamic(true);
diff --git a/tests/lib/AppFramework/Http/DataResponseTest.php b/tests/lib/AppFramework/Http/DataResponseTest.php
index 39f7e76ea0c..7ae19e7d5d8 100644
--- a/tests/lib/AppFramework/Http/DataResponseTest.php
+++ b/tests/lib/AppFramework/Http/DataResponseTest.php
@@ -24,7 +24,7 @@ class DataResponseTest extends \Test\TestCase {
}
- public function testSetData() {
+ public function testSetData(): void {
$params = ['hi', 'yo'];
$this->response->setData($params);
@@ -32,7 +32,7 @@ class DataResponseTest extends \Test\TestCase {
}
- public function testConstructorAllowsToSetData() {
+ public function testConstructorAllowsToSetData(): void {
$data = ['hi'];
$code = 300;
$response = new DataResponse($data, $code);
@@ -42,7 +42,7 @@ class DataResponseTest extends \Test\TestCase {
}
- public function testConstructorAllowsToSetHeaders() {
+ public function testConstructorAllowsToSetHeaders(): void {
$data = ['hi'];
$code = 300;
$headers = ['test' => 'something'];
@@ -63,7 +63,7 @@ class DataResponseTest extends \Test\TestCase {
}
- public function testChainability() {
+ public function testChainability(): void {
$params = ['hi', 'yo'];
$this->response->setData($params)
->setStatus(Http::STATUS_NOT_FOUND);
diff --git a/tests/lib/AppFramework/Http/DispatcherTest.php b/tests/lib/AppFramework/Http/DispatcherTest.php
index 818c8041cdb..8ed8732ba7f 100644
--- a/tests/lib/AppFramework/Http/DispatcherTest.php
+++ b/tests/lib/AppFramework/Http/DispatcherTest.php
@@ -230,7 +230,7 @@ class DispatcherTest extends \Test\TestCase {
}
- public function testDispatcherReturnsArrayWith2Entries() {
+ public function testDispatcherReturnsArrayWith2Entries(): void {
$this->setMiddlewareExpectations('');
$response = $this->dispatcher->dispatch($this->controller, $this->controllerMethod);
@@ -240,7 +240,7 @@ class DispatcherTest extends \Test\TestCase {
}
- public function testHeadersAndOutputAreReturned() {
+ public function testHeadersAndOutputAreReturned(): void {
$out = 'yo';
$httpHeaders = 'Http';
$responseHeaders = ['hell' => 'yeah'];
@@ -255,7 +255,7 @@ class DispatcherTest extends \Test\TestCase {
}
- public function testExceptionCallsAfterException() {
+ public function testExceptionCallsAfterException(): void {
$out = 'yo';
$httpHeaders = 'Http';
$responseHeaders = ['hell' => 'yeah'];
@@ -270,7 +270,7 @@ class DispatcherTest extends \Test\TestCase {
}
- public function testExceptionThrowsIfCanNotBeHandledByAfterException() {
+ public function testExceptionThrowsIfCanNotBeHandledByAfterException(): void {
$out = 'yo';
$httpHeaders = 'Http';
$responseHeaders = ['hell' => 'yeah'];
@@ -300,7 +300,7 @@ class DispatcherTest extends \Test\TestCase {
}
- public function testControllerParametersInjected() {
+ public function testControllerParametersInjected(): void {
$this->request = new Request(
[
'post' => [
@@ -332,7 +332,7 @@ class DispatcherTest extends \Test\TestCase {
}
- public function testControllerParametersInjectedDefaultOverwritten() {
+ public function testControllerParametersInjectedDefaultOverwritten(): void {
$this->request = new Request(
[
'post' => [
@@ -366,7 +366,7 @@ class DispatcherTest extends \Test\TestCase {
- public function testResponseTransformedByUrlFormat() {
+ public function testResponseTransformedByUrlFormat(): void {
$this->request = new Request(
[
'post' => [
@@ -401,7 +401,7 @@ class DispatcherTest extends \Test\TestCase {
}
- public function testResponseTransformsDataResponse() {
+ public function testResponseTransformsDataResponse(): void {
$this->request = new Request(
[
'post' => [
@@ -436,7 +436,7 @@ class DispatcherTest extends \Test\TestCase {
}
- public function testResponseTransformedByAcceptHeader() {
+ public function testResponseTransformedByAcceptHeader(): void {
$this->request = new Request(
[
'post' => [
@@ -472,7 +472,7 @@ class DispatcherTest extends \Test\TestCase {
}
- public function testResponsePrimarilyTransformedByParameterFormat() {
+ public function testResponsePrimarilyTransformedByParameterFormat(): void {
$this->request = new Request(
[
'post' => [
diff --git a/tests/lib/AppFramework/Http/DownloadResponseTest.php b/tests/lib/AppFramework/Http/DownloadResponseTest.php
index 425e5ecde1f..8ac5954e00d 100644
--- a/tests/lib/AppFramework/Http/DownloadResponseTest.php
+++ b/tests/lib/AppFramework/Http/DownloadResponseTest.php
@@ -19,7 +19,7 @@ class DownloadResponseTest extends \Test\TestCase {
parent::setUp();
}
- public function testHeaders() {
+ public function testHeaders(): void {
$response = new ChildDownloadResponse('file', 'content');
$headers = $response->getHeaders();
@@ -30,7 +30,7 @@ class DownloadResponseTest extends \Test\TestCase {
/**
* @dataProvider filenameEncodingProvider
*/
- public function testFilenameEncoding(string $input, string $expected) {
+ public function testFilenameEncoding(string $input, string $expected): void {
$response = new ChildDownloadResponse($input, 'content');
$headers = $response->getHeaders();
diff --git a/tests/lib/AppFramework/Http/EmptyContentSecurityPolicyTest.php b/tests/lib/AppFramework/Http/EmptyContentSecurityPolicyTest.php
index 28158414351..3110f632fa7 100644
--- a/tests/lib/AppFramework/Http/EmptyContentSecurityPolicyTest.php
+++ b/tests/lib/AppFramework/Http/EmptyContentSecurityPolicyTest.php
@@ -23,19 +23,19 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->contentSecurityPolicy = new EmptyContentSecurityPolicy();
}
- public function testGetPolicyDefault() {
+ public function testGetPolicyDefault(): void {
$defaultPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';frame-ancestors 'none'";
$this->assertSame($defaultPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyScriptDomainValid() {
+ public function testGetPolicyScriptDomainValid(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src www.nextcloud.com;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedScriptDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyScriptDomainValidMultiple() {
+ public function testGetPolicyScriptDomainValidMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src www.nextcloud.com www.nextcloud.org;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedScriptDomain('www.nextcloud.com');
@@ -43,7 +43,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowScriptDomain() {
+ public function testGetPolicyDisallowScriptDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedScriptDomain('www.nextcloud.com');
@@ -51,7 +51,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowScriptDomainMultiple() {
+ public function testGetPolicyDisallowScriptDomainMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src www.nextcloud.com;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedScriptDomain('www.nextcloud.com');
@@ -59,7 +59,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowScriptDomainMultipleStacked() {
+ public function testGetPolicyDisallowScriptDomainMultipleStacked(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedScriptDomain('www.nextcloud.com');
@@ -67,28 +67,28 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyScriptAllowEval() {
+ public function testGetPolicyScriptAllowEval(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'unsafe-eval';frame-ancestors 'none'";
$this->contentSecurityPolicy->allowEvalScript(true);
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyScriptAllowWasmEval() {
+ public function testGetPolicyScriptAllowWasmEval(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'wasm-unsafe-eval';frame-ancestors 'none'";
$this->contentSecurityPolicy->allowEvalWasm(true);
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyStyleDomainValid() {
+ public function testGetPolicyStyleDomainValid(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';style-src www.nextcloud.com;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedStyleDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyStyleDomainValidMultiple() {
+ public function testGetPolicyStyleDomainValidMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';style-src www.nextcloud.com www.nextcloud.org;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedStyleDomain('www.nextcloud.com');
@@ -96,7 +96,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowStyleDomain() {
+ public function testGetPolicyDisallowStyleDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedStyleDomain('www.nextcloud.com');
@@ -104,7 +104,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowStyleDomainMultiple() {
+ public function testGetPolicyDisallowStyleDomainMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';style-src www.nextcloud.com;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedStyleDomain('www.nextcloud.com');
@@ -112,7 +112,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowStyleDomainMultipleStacked() {
+ public function testGetPolicyDisallowStyleDomainMultipleStacked(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedStyleDomain('www.nextcloud.com');
@@ -120,14 +120,14 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyStyleAllowInline() {
+ public function testGetPolicyStyleAllowInline(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';style-src 'unsafe-inline';frame-ancestors 'none'";
$this->contentSecurityPolicy->allowInlineStyle(true);
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyStyleAllowInlineWithDomain() {
+ public function testGetPolicyStyleAllowInlineWithDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';style-src www.nextcloud.com 'unsafe-inline';frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedStyleDomain('www.nextcloud.com');
@@ -135,21 +135,21 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyStyleDisallowInline() {
+ public function testGetPolicyStyleDisallowInline(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';frame-ancestors 'none'";
$this->contentSecurityPolicy->allowInlineStyle(false);
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyImageDomainValid() {
+ public function testGetPolicyImageDomainValid(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';img-src www.nextcloud.com;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedImageDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyImageDomainValidMultiple() {
+ public function testGetPolicyImageDomainValidMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';img-src www.nextcloud.com www.nextcloud.org;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedImageDomain('www.nextcloud.com');
@@ -157,7 +157,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowImageDomain() {
+ public function testGetPolicyDisallowImageDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedImageDomain('www.nextcloud.com');
@@ -165,7 +165,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowImageDomainMultiple() {
+ public function testGetPolicyDisallowImageDomainMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';img-src www.nextcloud.com;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedImageDomain('www.nextcloud.com');
@@ -173,7 +173,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowImageDomainMultipleStakes() {
+ public function testGetPolicyDisallowImageDomainMultipleStakes(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedImageDomain('www.nextcloud.com');
@@ -181,14 +181,14 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyFontDomainValid() {
+ public function testGetPolicyFontDomainValid(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';font-src www.nextcloud.com;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedFontDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyFontDomainValidMultiple() {
+ public function testGetPolicyFontDomainValidMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';font-src www.nextcloud.com www.nextcloud.org;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedFontDomain('www.nextcloud.com');
@@ -196,7 +196,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowFontDomain() {
+ public function testGetPolicyDisallowFontDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedFontDomain('www.nextcloud.com');
@@ -204,7 +204,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowFontDomainMultiple() {
+ public function testGetPolicyDisallowFontDomainMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';font-src www.nextcloud.com;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedFontDomain('www.nextcloud.com');
@@ -212,7 +212,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowFontDomainMultipleStakes() {
+ public function testGetPolicyDisallowFontDomainMultipleStakes(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedFontDomain('www.nextcloud.com');
@@ -220,14 +220,14 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyConnectDomainValid() {
+ public function testGetPolicyConnectDomainValid(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';connect-src www.nextcloud.com;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedConnectDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyConnectDomainValidMultiple() {
+ public function testGetPolicyConnectDomainValidMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';connect-src www.nextcloud.com www.nextcloud.org;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedConnectDomain('www.nextcloud.com');
@@ -235,7 +235,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowConnectDomain() {
+ public function testGetPolicyDisallowConnectDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedConnectDomain('www.nextcloud.com');
@@ -243,7 +243,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowConnectDomainMultiple() {
+ public function testGetPolicyDisallowConnectDomainMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';connect-src www.nextcloud.com;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedConnectDomain('www.nextcloud.com');
@@ -251,7 +251,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowConnectDomainMultipleStakes() {
+ public function testGetPolicyDisallowConnectDomainMultipleStakes(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedConnectDomain('www.nextcloud.com');
@@ -259,14 +259,14 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyMediaDomainValid() {
+ public function testGetPolicyMediaDomainValid(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';media-src www.nextcloud.com;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedMediaDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyMediaDomainValidMultiple() {
+ public function testGetPolicyMediaDomainValidMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';media-src www.nextcloud.com www.nextcloud.org;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedMediaDomain('www.nextcloud.com');
@@ -274,7 +274,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowMediaDomain() {
+ public function testGetPolicyDisallowMediaDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedMediaDomain('www.nextcloud.com');
@@ -282,7 +282,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowMediaDomainMultiple() {
+ public function testGetPolicyDisallowMediaDomainMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';media-src www.nextcloud.com;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedMediaDomain('www.nextcloud.com');
@@ -290,7 +290,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowMediaDomainMultipleStakes() {
+ public function testGetPolicyDisallowMediaDomainMultipleStakes(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedMediaDomain('www.nextcloud.com');
@@ -298,14 +298,14 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyObjectDomainValid() {
+ public function testGetPolicyObjectDomainValid(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';object-src www.nextcloud.com;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedObjectDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyObjectDomainValidMultiple() {
+ public function testGetPolicyObjectDomainValidMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';object-src www.nextcloud.com www.nextcloud.org;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedObjectDomain('www.nextcloud.com');
@@ -313,7 +313,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowObjectDomain() {
+ public function testGetPolicyDisallowObjectDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedObjectDomain('www.nextcloud.com');
@@ -321,7 +321,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowObjectDomainMultiple() {
+ public function testGetPolicyDisallowObjectDomainMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';object-src www.nextcloud.com;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedObjectDomain('www.nextcloud.com');
@@ -329,7 +329,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowObjectDomainMultipleStakes() {
+ public function testGetPolicyDisallowObjectDomainMultipleStakes(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedObjectDomain('www.nextcloud.com');
@@ -337,14 +337,14 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetAllowedFrameDomain() {
+ public function testGetAllowedFrameDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';frame-src www.nextcloud.com;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedFrameDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyFrameDomainValidMultiple() {
+ public function testGetPolicyFrameDomainValidMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';frame-src www.nextcloud.com www.nextcloud.org;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedFrameDomain('www.nextcloud.com');
@@ -352,7 +352,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowFrameDomain() {
+ public function testGetPolicyDisallowFrameDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedFrameDomain('www.nextcloud.com');
@@ -360,7 +360,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowFrameDomainMultiple() {
+ public function testGetPolicyDisallowFrameDomainMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';frame-src www.nextcloud.com;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedFrameDomain('www.nextcloud.com');
@@ -368,7 +368,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowFrameDomainMultipleStakes() {
+ public function testGetPolicyDisallowFrameDomainMultipleStakes(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedFrameDomain('www.nextcloud.com');
@@ -376,14 +376,14 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetAllowedChildSrcDomain() {
+ public function testGetAllowedChildSrcDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';child-src child.nextcloud.com;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedChildSrcDomain('child.nextcloud.com');
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyChildSrcValidMultiple() {
+ public function testGetPolicyChildSrcValidMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';child-src child.nextcloud.com child.nextcloud.org;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedChildSrcDomain('child.nextcloud.com');
@@ -391,7 +391,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowChildSrcDomain() {
+ public function testGetPolicyDisallowChildSrcDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedChildSrcDomain('www.nextcloud.com');
@@ -399,7 +399,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowChildSrcDomainMultiple() {
+ public function testGetPolicyDisallowChildSrcDomainMultiple(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';child-src www.nextcloud.com;frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedChildSrcDomain('www.nextcloud.com');
@@ -407,7 +407,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyDisallowChildSrcDomainMultipleStakes() {
+ public function testGetPolicyDisallowChildSrcDomainMultipleStakes(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedChildSrcDomain('www.nextcloud.com');
@@ -415,7 +415,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyWithJsNonceAndScriptDomains() {
+ public function testGetPolicyWithJsNonceAndScriptDomains(): void {
$nonce = base64_encode('MyJsNonce');
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'nonce-$nonce' www.nextcloud.com www.nextcloud.org;frame-ancestors 'none'";
@@ -425,7 +425,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyWithJsNonceAndStrictDynamic() {
+ public function testGetPolicyWithJsNonceAndStrictDynamic(): void {
$nonce = base64_encode('MyJsNonce');
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'strict-dynamic' 'nonce-$nonce' www.nextcloud.com;frame-ancestors 'none'";
@@ -435,7 +435,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyWithJsNonceAndStrictDynamicAndStrictDynamicOnScripts() {
+ public function testGetPolicyWithJsNonceAndStrictDynamicAndStrictDynamicOnScripts(): void {
$nonce = base64_encode('MyJsNonce');
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'strict-dynamic' 'nonce-$nonce' www.nextcloud.com;frame-ancestors 'none'";
@@ -447,7 +447,7 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyWithJsNonceAndStrictDynamicOnScripts() {
+ public function testGetPolicyWithJsNonceAndStrictDynamicOnScripts(): void {
$nonce = base64_encode('MyJsNonce');
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'nonce-$nonce' www.nextcloud.com;script-src-elem 'strict-dynamic' 'nonce-$nonce' www.nextcloud.com;frame-ancestors 'none'";
@@ -457,14 +457,14 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyWithStrictDynamicOnScripts() {
+ public function testGetPolicyWithStrictDynamicOnScripts(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';frame-ancestors 'none'";
$this->contentSecurityPolicy->useStrictDynamicOnScripts(true);
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyWithJsNonceAndSelfScriptDomain() {
+ public function testGetPolicyWithJsNonceAndSelfScriptDomain(): void {
$nonce = base64_encode('MyJsNonce');
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'nonce-$nonce';frame-ancestors 'none'";
@@ -473,21 +473,21 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyWithoutJsNonceAndSelfScriptDomain() {
+ public function testGetPolicyWithoutJsNonceAndSelfScriptDomain(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';frame-ancestors 'none'";
$this->contentSecurityPolicy->addAllowedScriptDomain("'self'");
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyWithReportUri() {
+ public function testGetPolicyWithReportUri(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';frame-ancestors 'none';report-uri https://my-report-uri.com";
$this->contentSecurityPolicy->addReportTo('https://my-report-uri.com');
$this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy());
}
- public function testGetPolicyWithMultipleReportUri() {
+ public function testGetPolicyWithMultipleReportUri(): void {
$expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';frame-ancestors 'none';report-uri https://my-report-uri.com https://my-other-report-uri.com";
$this->contentSecurityPolicy->addReportTo('https://my-report-uri.com');
diff --git a/tests/lib/AppFramework/Http/EmptyFeaturePolicyTest.php b/tests/lib/AppFramework/Http/EmptyFeaturePolicyTest.php
index ca65fcd978c..71342485552 100644
--- a/tests/lib/AppFramework/Http/EmptyFeaturePolicyTest.php
+++ b/tests/lib/AppFramework/Http/EmptyFeaturePolicyTest.php
@@ -19,19 +19,19 @@ class EmptyFeaturePolicyTest extends \Test\TestCase {
$this->policy = new EmptyFeaturePolicy();
}
- public function testGetPolicyDefault() {
+ public function testGetPolicyDefault(): void {
$defaultPolicy = "autoplay 'none';camera 'none';fullscreen 'none';geolocation 'none';microphone 'none';payment 'none'";
$this->assertSame($defaultPolicy, $this->policy->buildPolicy());
}
- public function testGetPolicyAutoplayDomainValid() {
+ public function testGetPolicyAutoplayDomainValid(): void {
$expectedPolicy = "autoplay www.nextcloud.com;camera 'none';fullscreen 'none';geolocation 'none';microphone 'none';payment 'none'";
$this->policy->addAllowedAutoplayDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->policy->buildPolicy());
}
- public function testGetPolicyAutoplayDomainValidMultiple() {
+ public function testGetPolicyAutoplayDomainValidMultiple(): void {
$expectedPolicy = "autoplay www.nextcloud.com www.nextcloud.org;camera 'none';fullscreen 'none';geolocation 'none';microphone 'none';payment 'none'";
$this->policy->addAllowedAutoplayDomain('www.nextcloud.com');
@@ -39,14 +39,14 @@ class EmptyFeaturePolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->policy->buildPolicy());
}
- public function testGetPolicyCameraDomainValid() {
+ public function testGetPolicyCameraDomainValid(): void {
$expectedPolicy = "autoplay 'none';camera www.nextcloud.com;fullscreen 'none';geolocation 'none';microphone 'none';payment 'none'";
$this->policy->addAllowedCameraDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->policy->buildPolicy());
}
- public function testGetPolicyCameraDomainValidMultiple() {
+ public function testGetPolicyCameraDomainValidMultiple(): void {
$expectedPolicy = "autoplay 'none';camera www.nextcloud.com www.nextcloud.org;fullscreen 'none';geolocation 'none';microphone 'none';payment 'none'";
$this->policy->addAllowedCameraDomain('www.nextcloud.com');
@@ -54,14 +54,14 @@ class EmptyFeaturePolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->policy->buildPolicy());
}
- public function testGetPolicyFullScreenDomainValid() {
+ public function testGetPolicyFullScreenDomainValid(): void {
$expectedPolicy = "autoplay 'none';camera 'none';fullscreen www.nextcloud.com;geolocation 'none';microphone 'none';payment 'none'";
$this->policy->addAllowedFullScreenDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->policy->buildPolicy());
}
- public function testGetPolicyFullScreenDomainValidMultiple() {
+ public function testGetPolicyFullScreenDomainValidMultiple(): void {
$expectedPolicy = "autoplay 'none';camera 'none';fullscreen www.nextcloud.com www.nextcloud.org;geolocation 'none';microphone 'none';payment 'none'";
$this->policy->addAllowedFullScreenDomain('www.nextcloud.com');
@@ -69,14 +69,14 @@ class EmptyFeaturePolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->policy->buildPolicy());
}
- public function testGetPolicyGeoLocationDomainValid() {
+ public function testGetPolicyGeoLocationDomainValid(): void {
$expectedPolicy = "autoplay 'none';camera 'none';fullscreen 'none';geolocation www.nextcloud.com;microphone 'none';payment 'none'";
$this->policy->addAllowedGeoLocationDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->policy->buildPolicy());
}
- public function testGetPolicyGeoLocationDomainValidMultiple() {
+ public function testGetPolicyGeoLocationDomainValidMultiple(): void {
$expectedPolicy = "autoplay 'none';camera 'none';fullscreen 'none';geolocation www.nextcloud.com www.nextcloud.org;microphone 'none';payment 'none'";
$this->policy->addAllowedGeoLocationDomain('www.nextcloud.com');
@@ -84,14 +84,14 @@ class EmptyFeaturePolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->policy->buildPolicy());
}
- public function testGetPolicyMicrophoneDomainValid() {
+ public function testGetPolicyMicrophoneDomainValid(): void {
$expectedPolicy = "autoplay 'none';camera 'none';fullscreen 'none';geolocation 'none';microphone www.nextcloud.com;payment 'none'";
$this->policy->addAllowedMicrophoneDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->policy->buildPolicy());
}
- public function testGetPolicyMicrophoneDomainValidMultiple() {
+ public function testGetPolicyMicrophoneDomainValidMultiple(): void {
$expectedPolicy = "autoplay 'none';camera 'none';fullscreen 'none';geolocation 'none';microphone www.nextcloud.com www.nextcloud.org;payment 'none'";
$this->policy->addAllowedMicrophoneDomain('www.nextcloud.com');
@@ -99,14 +99,14 @@ class EmptyFeaturePolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->policy->buildPolicy());
}
- public function testGetPolicyPaymentDomainValid() {
+ public function testGetPolicyPaymentDomainValid(): void {
$expectedPolicy = "autoplay 'none';camera 'none';fullscreen 'none';geolocation 'none';microphone 'none';payment www.nextcloud.com";
$this->policy->addAllowedPaymentDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->policy->buildPolicy());
}
- public function testGetPolicyPaymentDomainValidMultiple() {
+ public function testGetPolicyPaymentDomainValidMultiple(): void {
$expectedPolicy = "autoplay 'none';camera 'none';fullscreen 'none';geolocation 'none';microphone 'none';payment www.nextcloud.com www.nextcloud.org";
$this->policy->addAllowedPaymentDomain('www.nextcloud.com');
diff --git a/tests/lib/AppFramework/Http/FeaturePolicyTest.php b/tests/lib/AppFramework/Http/FeaturePolicyTest.php
index ce6a87406e8..6ea990fb111 100644
--- a/tests/lib/AppFramework/Http/FeaturePolicyTest.php
+++ b/tests/lib/AppFramework/Http/FeaturePolicyTest.php
@@ -19,19 +19,19 @@ class FeaturePolicyTest extends \Test\TestCase {
$this->policy = new FeaturePolicy();
}
- public function testGetPolicyDefault() {
+ public function testGetPolicyDefault(): void {
$defaultPolicy = "autoplay 'self';camera 'none';fullscreen 'self';geolocation 'none';microphone 'none';payment 'none'";
$this->assertSame($defaultPolicy, $this->policy->buildPolicy());
}
- public function testGetPolicyAutoplayDomainValid() {
+ public function testGetPolicyAutoplayDomainValid(): void {
$expectedPolicy = "autoplay 'self' www.nextcloud.com;camera 'none';fullscreen 'self';geolocation 'none';microphone 'none';payment 'none'";
$this->policy->addAllowedAutoplayDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->policy->buildPolicy());
}
- public function testGetPolicyAutoplayDomainValidMultiple() {
+ public function testGetPolicyAutoplayDomainValidMultiple(): void {
$expectedPolicy = "autoplay 'self' www.nextcloud.com www.nextcloud.org;camera 'none';fullscreen 'self';geolocation 'none';microphone 'none';payment 'none'";
$this->policy->addAllowedAutoplayDomain('www.nextcloud.com');
@@ -39,14 +39,14 @@ class FeaturePolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->policy->buildPolicy());
}
- public function testGetPolicyCameraDomainValid() {
+ public function testGetPolicyCameraDomainValid(): void {
$expectedPolicy = "autoplay 'self';camera www.nextcloud.com;fullscreen 'self';geolocation 'none';microphone 'none';payment 'none'";
$this->policy->addAllowedCameraDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->policy->buildPolicy());
}
- public function testGetPolicyCameraDomainValidMultiple() {
+ public function testGetPolicyCameraDomainValidMultiple(): void {
$expectedPolicy = "autoplay 'self';camera www.nextcloud.com www.nextcloud.org;fullscreen 'self';geolocation 'none';microphone 'none';payment 'none'";
$this->policy->addAllowedCameraDomain('www.nextcloud.com');
@@ -54,14 +54,14 @@ class FeaturePolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->policy->buildPolicy());
}
- public function testGetPolicyFullScreenDomainValid() {
+ public function testGetPolicyFullScreenDomainValid(): void {
$expectedPolicy = "autoplay 'self';camera 'none';fullscreen 'self' www.nextcloud.com;geolocation 'none';microphone 'none';payment 'none'";
$this->policy->addAllowedFullScreenDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->policy->buildPolicy());
}
- public function testGetPolicyFullScreenDomainValidMultiple() {
+ public function testGetPolicyFullScreenDomainValidMultiple(): void {
$expectedPolicy = "autoplay 'self';camera 'none';fullscreen 'self' www.nextcloud.com www.nextcloud.org;geolocation 'none';microphone 'none';payment 'none'";
$this->policy->addAllowedFullScreenDomain('www.nextcloud.com');
@@ -69,14 +69,14 @@ class FeaturePolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->policy->buildPolicy());
}
- public function testGetPolicyGeoLocationDomainValid() {
+ public function testGetPolicyGeoLocationDomainValid(): void {
$expectedPolicy = "autoplay 'self';camera 'none';fullscreen 'self';geolocation www.nextcloud.com;microphone 'none';payment 'none'";
$this->policy->addAllowedGeoLocationDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->policy->buildPolicy());
}
- public function testGetPolicyGeoLocationDomainValidMultiple() {
+ public function testGetPolicyGeoLocationDomainValidMultiple(): void {
$expectedPolicy = "autoplay 'self';camera 'none';fullscreen 'self';geolocation www.nextcloud.com www.nextcloud.org;microphone 'none';payment 'none'";
$this->policy->addAllowedGeoLocationDomain('www.nextcloud.com');
@@ -84,14 +84,14 @@ class FeaturePolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->policy->buildPolicy());
}
- public function testGetPolicyMicrophoneDomainValid() {
+ public function testGetPolicyMicrophoneDomainValid(): void {
$expectedPolicy = "autoplay 'self';camera 'none';fullscreen 'self';geolocation 'none';microphone www.nextcloud.com;payment 'none'";
$this->policy->addAllowedMicrophoneDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->policy->buildPolicy());
}
- public function testGetPolicyMicrophoneDomainValidMultiple() {
+ public function testGetPolicyMicrophoneDomainValidMultiple(): void {
$expectedPolicy = "autoplay 'self';camera 'none';fullscreen 'self';geolocation 'none';microphone www.nextcloud.com www.nextcloud.org;payment 'none'";
$this->policy->addAllowedMicrophoneDomain('www.nextcloud.com');
@@ -99,14 +99,14 @@ class FeaturePolicyTest extends \Test\TestCase {
$this->assertSame($expectedPolicy, $this->policy->buildPolicy());
}
- public function testGetPolicyPaymentDomainValid() {
+ public function testGetPolicyPaymentDomainValid(): void {
$expectedPolicy = "autoplay 'self';camera 'none';fullscreen 'self';geolocation 'none';microphone 'none';payment www.nextcloud.com";
$this->policy->addAllowedPaymentDomain('www.nextcloud.com');
$this->assertSame($expectedPolicy, $this->policy->buildPolicy());
}
- public function testGetPolicyPaymentDomainValidMultiple() {
+ public function testGetPolicyPaymentDomainValidMultiple(): void {
$expectedPolicy = "autoplay 'self';camera 'none';fullscreen 'self';geolocation 'none';microphone 'none';payment www.nextcloud.com www.nextcloud.org";
$this->policy->addAllowedPaymentDomain('www.nextcloud.com');
diff --git a/tests/lib/AppFramework/Http/FileDisplayResponseTest.php b/tests/lib/AppFramework/Http/FileDisplayResponseTest.php
index bb8c9323794..029cdab630a 100644
--- a/tests/lib/AppFramework/Http/FileDisplayResponseTest.php
+++ b/tests/lib/AppFramework/Http/FileDisplayResponseTest.php
@@ -1,93 +1,93 @@
-<?php
-/**
- * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
- * SPDX-License-Identifier: AGPL-3.0-or-later
- */
-
-namespace Test\AppFramework\Http;
-
-use OCP\AppFramework\Http;
-use OCP\AppFramework\Http\FileDisplayResponse;
-use OCP\Files\File;
-
-class FileDisplayResponseTest extends \Test\TestCase {
- /** @var File|\PHPUnit\Framework\MockObject\MockObject */
- private $file;
-
- /** @var FileDisplayResponse */
- private $response;
-
- protected function setUp(): void {
- $this->file = $this->getMockBuilder(\OCP\Files\File::class)
- ->getMock();
-
- $this->file->expects($this->once())
- ->method('getETag')
- ->willReturn('myETag');
- $this->file->expects($this->once())
- ->method('getName')
- ->willReturn('myFileName');
- $this->file->expects($this->once())
- ->method('getMTime')
- ->willReturn(1464825600);
-
- $this->response = new FileDisplayResponse($this->file);
- }
-
- public function testHeader() {
- $headers = $this->response->getHeaders();
- $this->assertArrayHasKey('Content-Disposition', $headers);
- $this->assertSame('inline; filename="myFileName"', $headers['Content-Disposition']);
- }
-
- public function testETag() {
- $this->assertSame('myETag', $this->response->getETag());
- }
-
- public function testLastModified() {
- $lastModified = $this->response->getLastModified();
- $this->assertNotNull($lastModified);
- $this->assertSame(1464825600, $lastModified->getTimestamp());
- }
-
- public function test304() {
- $output = $this->getMockBuilder(\OCP\AppFramework\Http\IOutput::class)
- ->disableOriginalConstructor()
- ->getMock();
-
- $output->expects($this->any())
- ->method('getHttpResponseCode')
- ->willReturn(Http::STATUS_NOT_MODIFIED);
- $output->expects($this->never())
- ->method('setOutput');
- $this->file->expects($this->never())
- ->method('getContent');
-
- $this->response->callback($output);
- }
-
-
- public function testNon304() {
- $output = $this->getMockBuilder(\OCP\AppFramework\Http\IOutput::class)
- ->disableOriginalConstructor()
- ->getMock();
-
- $output->expects($this->any())
- ->method('getHttpResponseCode')
- ->willReturn(Http::STATUS_OK);
- $output->expects($this->once())
- ->method('setOutput')
- ->with($this->equalTo('my data'));
- $output->expects($this->once())
- ->method('setHeader')
- ->with($this->equalTo('Content-Length: 42'));
- $this->file->expects($this->once())
- ->method('getContent')
- ->willReturn('my data');
- $this->file->expects($this->any())
- ->method('getSize')
- ->willReturn(42);
-
- $this->response->callback($output);
- }
-}
+<?php
+/**
+ * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+
+namespace Test\AppFramework\Http;
+
+use OCP\AppFramework\Http;
+use OCP\AppFramework\Http\FileDisplayResponse;
+use OCP\Files\File;
+
+class FileDisplayResponseTest extends \Test\TestCase {
+ /** @var File|\PHPUnit\Framework\MockObject\MockObject */
+ private $file;
+
+ /** @var FileDisplayResponse */
+ private $response;
+
+ protected function setUp(): void {
+ $this->file = $this->getMockBuilder(\OCP\Files\File::class)
+ ->getMock();
+
+ $this->file->expects($this->once())
+ ->method('getETag')
+ ->willReturn('myETag');
+ $this->file->expects($this->once())
+ ->method('getName')
+ ->willReturn('myFileName');
+ $this->file->expects($this->once())
+ ->method('getMTime')
+ ->willReturn(1464825600);
+
+ $this->response = new FileDisplayResponse($this->file);
+ }
+
+ public function testHeader(): void {
+ $headers = $this->response->getHeaders();
+ $this->assertArrayHasKey('Content-Disposition', $headers);
+ $this->assertSame('inline; filename="myFileName"', $headers['Content-Disposition']);
+ }
+
+ public function testETag(): void {
+ $this->assertSame('myETag', $this->response->getETag());
+ }
+
+ public function testLastModified(): void {
+ $lastModified = $this->response->getLastModified();
+ $this->assertNotNull($lastModified);
+ $this->assertSame(1464825600, $lastModified->getTimestamp());
+ }
+
+ public function test304(): void {
+ $output = $this->getMockBuilder(\OCP\AppFramework\Http\IOutput::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $output->expects($this->any())
+ ->method('getHttpResponseCode')
+ ->willReturn(Http::STATUS_NOT_MODIFIED);
+ $output->expects($this->never())
+ ->method('setOutput');
+ $this->file->expects($this->never())
+ ->method('getContent');
+
+ $this->response->callback($output);
+ }
+
+
+ public function testNon304(): void {
+ $output = $this->getMockBuilder(\OCP\AppFramework\Http\IOutput::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $output->expects($this->any())
+ ->method('getHttpResponseCode')
+ ->willReturn(Http::STATUS_OK);
+ $output->expects($this->once())
+ ->method('setOutput')
+ ->with($this->equalTo('my data'));
+ $output->expects($this->once())
+ ->method('setHeader')
+ ->with($this->equalTo('Content-Length: 42'));
+ $this->file->expects($this->once())
+ ->method('getContent')
+ ->willReturn('my data');
+ $this->file->expects($this->any())
+ ->method('getSize')
+ ->willReturn(42);
+
+ $this->response->callback($output);
+ }
+}
diff --git a/tests/lib/AppFramework/Http/HttpTest.php b/tests/lib/AppFramework/Http/HttpTest.php
index 46d2bb9d17a..d3ec8438554 100644
--- a/tests/lib/AppFramework/Http/HttpTest.php
+++ b/tests/lib/AppFramework/Http/HttpTest.php
@@ -26,19 +26,19 @@ class HttpTest extends \Test\TestCase {
}
- public function testProtocol() {
+ public function testProtocol(): void {
$header = $this->http->getStatusHeader(Http::STATUS_TEMPORARY_REDIRECT);
$this->assertEquals('HTTP/1.1 307 Temporary Redirect', $header);
}
- public function testProtocol10() {
+ public function testProtocol10(): void {
$this->http = new Http($this->server, 'HTTP/1.0');
$header = $this->http->getStatusHeader(Http::STATUS_OK);
$this->assertEquals('HTTP/1.0 200 OK', $header);
}
- public function testTempRedirectBecomesFoundInHttp10() {
+ public function testTempRedirectBecomesFoundInHttp10(): void {
$http = new Http([], 'HTTP/1.0');
$header = $http->getStatusHeader(Http::STATUS_TEMPORARY_REDIRECT);
diff --git a/tests/lib/AppFramework/Http/JSONResponseTest.php b/tests/lib/AppFramework/Http/JSONResponseTest.php
index bacc5999348..175ed852c7b 100644
--- a/tests/lib/AppFramework/Http/JSONResponseTest.php
+++ b/tests/lib/AppFramework/Http/JSONResponseTest.php
@@ -23,13 +23,13 @@ class JSONResponseTest extends \Test\TestCase {
}
- public function testHeader() {
+ public function testHeader(): void {
$headers = $this->json->getHeaders();
$this->assertEquals('application/json; charset=utf-8', $headers['Content-Type']);
}
- public function testSetData() {
+ public function testSetData(): void {
$params = ['hi', 'yo'];
$this->json->setData($params);
@@ -37,7 +37,7 @@ class JSONResponseTest extends \Test\TestCase {
}
- public function testSetRender() {
+ public function testSetRender(): void {
$params = ['test' => 'hi'];
$this->json->setData($params);
@@ -65,13 +65,13 @@ class JSONResponseTest extends \Test\TestCase {
* @param array $input
* @param string $expected
*/
- public function testRender(array $input, $expected) {
+ public function testRender(array $input, $expected): void {
$this->json->setData($input);
$this->assertEquals($expected, $this->json->render());
}
- public function testRenderWithNonUtf8Encoding() {
+ public function testRenderWithNonUtf8Encoding(): void {
$this->expectException(\JsonException::class);
$this->expectExceptionMessage('Malformed UTF-8 characters, possibly incorrectly encoded');
@@ -80,7 +80,7 @@ class JSONResponseTest extends \Test\TestCase {
$this->json->render();
}
- public function testConstructorAllowsToSetData() {
+ public function testConstructorAllowsToSetData(): void {
$data = ['hi'];
$code = 300;
$response = new JSONResponse($data, $code);
@@ -90,7 +90,7 @@ class JSONResponseTest extends \Test\TestCase {
$this->assertEquals($code, $response->getStatus());
}
- public function testChainability() {
+ public function testChainability(): void {
$params = ['hi', 'yo'];
$this->json->setData($params)
->setStatus(Http::STATUS_NOT_FOUND);
diff --git a/tests/lib/AppFramework/Http/OutputTest.php b/tests/lib/AppFramework/Http/OutputTest.php
index cad49ae77ba..58b17c08141 100644
--- a/tests/lib/AppFramework/Http/OutputTest.php
+++ b/tests/lib/AppFramework/Http/OutputTest.php
@@ -9,19 +9,19 @@ namespace Test\AppFramework\Http;
use OC\AppFramework\Http\Output;
class OutputTest extends \Test\TestCase {
- public function testSetOutput() {
+ public function testSetOutput(): void {
$this->expectOutputString('foo');
$output = new Output('');
$output->setOutput('foo');
}
- public function testSetReadfile() {
+ public function testSetReadfile(): void {
$this->expectOutputString(file_get_contents(__FILE__));
$output = new Output('');
$output->setReadfile(__FILE__);
}
- public function testSetReadfileStream() {
+ public function testSetReadfileStream(): void {
$this->expectOutputString(file_get_contents(__FILE__));
$output = new Output('');
$output->setReadfile(fopen(__FILE__, 'r'));
diff --git a/tests/lib/AppFramework/Http/PublicTemplateResponseTest.php b/tests/lib/AppFramework/Http/PublicTemplateResponseTest.php
index 6b6e6fd429c..d963705bc24 100644
--- a/tests/lib/AppFramework/Http/PublicTemplateResponseTest.php
+++ b/tests/lib/AppFramework/Http/PublicTemplateResponseTest.php
@@ -12,12 +12,12 @@ use OCP\AppFramework\Http\Template\PublicTemplateResponse;
use Test\TestCase;
class PublicTemplateResponseTest extends TestCase {
- public function testSetParamsConstructor() {
+ public function testSetParamsConstructor(): void {
$template = new PublicTemplateResponse('app', 'home', ['key' => 'value']);
$this->assertEquals(['key' => 'value'], $template->getParams());
}
- public function testAdditionalElements() {
+ public function testAdditionalElements(): void {
$template = new PublicTemplateResponse('app', 'home', ['key' => 'value']);
$template->setHeaderTitle('Header');
$template->setHeaderDetails('Details');
@@ -26,7 +26,7 @@ class PublicTemplateResponseTest extends TestCase {
$this->assertEquals('Details', $template->getHeaderDetails());
}
- public function testActionSingle() {
+ public function testActionSingle(): void {
$actions = [
new Http\Template\SimpleMenuAction('link', 'Download', 'download', 'downloadLink', 0)
];
@@ -39,7 +39,7 @@ class PublicTemplateResponseTest extends TestCase {
}
- public function testActionMultiple() {
+ public function testActionMultiple(): void {
$actions = [
new Http\Template\SimpleMenuAction('link1', 'Download1', 'download1', 'downloadLink1', 100),
new Http\Template\SimpleMenuAction('link2', 'Download2', 'download2', 'downloadLink2', 20),
@@ -54,7 +54,7 @@ class PublicTemplateResponseTest extends TestCase {
}
- public function testGetRenderAs() {
+ public function testGetRenderAs(): void {
$template = new PublicTemplateResponse('app', 'home', ['key' => 'value']);
$this->assertEquals(['key' => 'value'], $template->getParams());
$this->assertEquals('public', $template->getRenderAs());
diff --git a/tests/lib/AppFramework/Http/RedirectResponseTest.php b/tests/lib/AppFramework/Http/RedirectResponseTest.php
index dd0142b77a7..f6319782e79 100644
--- a/tests/lib/AppFramework/Http/RedirectResponseTest.php
+++ b/tests/lib/AppFramework/Http/RedirectResponseTest.php
@@ -23,7 +23,7 @@ class RedirectResponseTest extends \Test\TestCase {
}
- public function testHeaders() {
+ public function testHeaders(): void {
$headers = $this->response->getHeaders();
$this->assertEquals('/url', $headers['Location']);
$this->assertEquals(Http::STATUS_SEE_OTHER,
@@ -31,7 +31,7 @@ class RedirectResponseTest extends \Test\TestCase {
}
- public function testGetRedirectUrl() {
+ public function testGetRedirectUrl(): void {
$this->assertEquals('/url', $this->response->getRedirectUrl());
}
}
diff --git a/tests/lib/AppFramework/Http/RequestTest.php b/tests/lib/AppFramework/Http/RequestTest.php
index 1d448780feb..2286a6da0e5 100644
--- a/tests/lib/AppFramework/Http/RequestTest.php
+++ b/tests/lib/AppFramework/Http/RequestTest.php
@@ -47,7 +47,7 @@ class RequestTest extends \Test\TestCase {
parent::tearDown();
}
- public function testRequestAccessors() {
+ public function testRequestAccessors(): void {
$vars = [
'get' => ['name' => 'John Q. Public', 'nickname' => 'Joey'],
'method' => 'GET',
@@ -77,7 +77,7 @@ class RequestTest extends \Test\TestCase {
}
// urlParams has precedence over POST which has precedence over GET
- public function testPrecedence() {
+ public function testPrecedence(): void {
$vars = [
'get' => ['name' => 'John Q. Public', 'nickname' => 'Joey'],
'post' => ['name' => 'Jane Doe', 'nickname' => 'Janey'],
@@ -100,7 +100,7 @@ class RequestTest extends \Test\TestCase {
- public function testImmutableArrayAccess() {
+ public function testImmutableArrayAccess(): void {
$this->expectException(\RuntimeException::class);
$vars = [
@@ -120,7 +120,7 @@ class RequestTest extends \Test\TestCase {
}
- public function testImmutableMagicAccess() {
+ public function testImmutableMagicAccess(): void {
$this->expectException(\RuntimeException::class);
$vars = [
@@ -140,7 +140,7 @@ class RequestTest extends \Test\TestCase {
}
- public function testGetTheMethodRight() {
+ public function testGetTheMethodRight(): void {
$this->expectException(\LogicException::class);
$vars = [
@@ -159,7 +159,7 @@ class RequestTest extends \Test\TestCase {
$request->post;
}
- public function testTheMethodIsRight() {
+ public function testTheMethodIsRight(): void {
$vars = [
'get' => ['name' => 'John Q. Public', 'nickname' => 'Joey'],
'method' => 'GET',
@@ -179,7 +179,7 @@ class RequestTest extends \Test\TestCase {
$this->assertSame('Joey', $result['nickname']);
}
- public function testJsonPost() {
+ public function testJsonPost(): void {
global $data;
$data = '{"name": "John Q. Public", "nickname": "Joey"}';
$vars = [
@@ -203,7 +203,7 @@ class RequestTest extends \Test\TestCase {
$this->assertSame('Joey', $request['nickname']);
}
- public function testScimJsonPost() {
+ public function testScimJsonPost(): void {
global $data;
$data = '{"userName":"testusername", "displayName":"Example User"}';
$vars = [
@@ -227,7 +227,7 @@ class RequestTest extends \Test\TestCase {
$this->assertSame('Example User', $request['displayName']);
}
- public function testCustomJsonPost() {
+ public function testCustomJsonPost(): void {
global $data;
$data = '{"propertyA":"sometestvalue", "propertyB":"someothertestvalue"}';
@@ -262,7 +262,7 @@ class RequestTest extends \Test\TestCase {
/**
* @dataProvider notJsonDataProvider
*/
- public function testNotJsonPost($testData) {
+ public function testNotJsonPost($testData): void {
global $data;
$data = $testData;
$vars = [
@@ -283,7 +283,7 @@ class RequestTest extends \Test\TestCase {
// ensure there's no error attempting to decode the content
}
- public function testNotScimJsonPost() {
+ public function testNotScimJsonPost(): void {
global $data;
$data = 'this is not valid scim json';
$vars = [
@@ -304,7 +304,7 @@ class RequestTest extends \Test\TestCase {
// ensure there's no error attempting to decode the content
}
- public function testNotCustomJsonPost() {
+ public function testNotCustomJsonPost(): void {
global $data;
$data = 'this is not valid json';
$vars = [
@@ -325,7 +325,7 @@ class RequestTest extends \Test\TestCase {
// ensure there's no error attempting to decode the content
}
- public function testPatch() {
+ public function testPatch(): void {
global $data;
$data = http_build_query(['name' => 'John Q. Public', 'nickname' => 'Joey'], '', '&');
@@ -349,7 +349,7 @@ class RequestTest extends \Test\TestCase {
$this->assertSame('Joey', $result['nickname']);
}
- public function testJsonPatchAndPut() {
+ public function testJsonPatchAndPut(): void {
global $data;
// PUT content
@@ -395,7 +395,7 @@ class RequestTest extends \Test\TestCase {
$this->assertSame(null, $result['nickname']);
}
- public function testScimJsonPatchAndPut() {
+ public function testScimJsonPatchAndPut(): void {
global $data;
// PUT content
@@ -441,7 +441,7 @@ class RequestTest extends \Test\TestCase {
$this->assertSame(null, $result['displayName']);
}
- public function testCustomJsonPatchAndPut() {
+ public function testCustomJsonPatchAndPut(): void {
global $data;
// PUT content
@@ -487,7 +487,7 @@ class RequestTest extends \Test\TestCase {
$this->assertSame(null, $result['propertyB']);
}
- public function testPutStream() {
+ public function testPutStream(): void {
global $data;
$data = file_get_contents(__DIR__ . '/../../../data/testimage.png');
@@ -522,7 +522,7 @@ class RequestTest extends \Test\TestCase {
}
- public function testSetUrlParameters() {
+ public function testSetUrlParameters(): void {
$vars = [
'post' => [],
'method' => 'POST',
@@ -771,7 +771,7 @@ class RequestTest extends \Test\TestCase {
* @param mixed $input
* @param string $expected
*/
- public function testGetHttpProtocol($input, $expected) {
+ public function testGetHttpProtocol($input, $expected): void {
$request = new Request(
[
'server' => [
@@ -787,7 +787,7 @@ class RequestTest extends \Test\TestCase {
$this->assertSame($expected, $request->getHttpProtocol());
}
- public function testGetServerProtocolWithOverride() {
+ public function testGetServerProtocolWithOverride(): void {
$this->config
->expects($this->exactly(3))
->method('getSystemValueString')
@@ -807,7 +807,7 @@ class RequestTest extends \Test\TestCase {
$this->assertSame('customProtocol', $request->getServerProtocol());
}
- public function testGetServerProtocolWithProtoValid() {
+ public function testGetServerProtocolWithProtoValid(): void {
$this->config
->method('getSystemValue')
->willReturnCallback(function ($key, $default) {
@@ -848,7 +848,7 @@ class RequestTest extends \Test\TestCase {
$this->assertSame('http', $requestHttp->getServerProtocol());
}
- public function testGetServerProtocolWithHttpsServerValueOn() {
+ public function testGetServerProtocolWithHttpsServerValueOn(): void {
$this->config
->method('getSystemValue')
->willReturnCallback(function ($key, $default) {
@@ -869,7 +869,7 @@ class RequestTest extends \Test\TestCase {
$this->assertSame('https', $request->getServerProtocol());
}
- public function testGetServerProtocolWithHttpsServerValueOff() {
+ public function testGetServerProtocolWithHttpsServerValueOff(): void {
$this->config
->method('getSystemValue')
->willReturnCallback(function ($key, $default) {
@@ -890,7 +890,7 @@ class RequestTest extends \Test\TestCase {
$this->assertSame('http', $request->getServerProtocol());
}
- public function testGetServerProtocolWithHttpsServerValueEmpty() {
+ public function testGetServerProtocolWithHttpsServerValueEmpty(): void {
$this->config
->method('getSystemValue')
->willReturnCallback(function ($key, $default) {
@@ -911,7 +911,7 @@ class RequestTest extends \Test\TestCase {
$this->assertSame('http', $request->getServerProtocol());
}
- public function testGetServerProtocolDefault() {
+ public function testGetServerProtocolDefault(): void {
$this->config
->method('getSystemValue')
->willReturnCallback(function ($key, $default) {
@@ -928,7 +928,7 @@ class RequestTest extends \Test\TestCase {
$this->assertSame('http', $request->getServerProtocol());
}
- public function testGetServerProtocolBehindLoadBalancers() {
+ public function testGetServerProtocolBehindLoadBalancers(): void {
$this->config
->method('getSystemValue')
->willReturnCallback(function ($key, $default) {
@@ -961,7 +961,7 @@ class RequestTest extends \Test\TestCase {
* @param array $userAgent
* @param bool $matches
*/
- public function testUserAgent($testAgent, $userAgent, $matches) {
+ public function testUserAgent($testAgent, $userAgent, $matches): void {
$request = new Request(
[
'server' => [
@@ -983,7 +983,7 @@ class RequestTest extends \Test\TestCase {
* @param array $userAgent
* @param bool $matches
*/
- public function testUndefinedUserAgent($testAgent, $userAgent, $matches) {
+ public function testUndefinedUserAgent($testAgent, $userAgent, $matches): void {
$request = new Request(
[],
$this->requestId,
@@ -1174,7 +1174,7 @@ class RequestTest extends \Test\TestCase {
$this->assertSame($version, $matches[1]);
}
- public function testInsecureServerHostServerNameHeader() {
+ public function testInsecureServerHostServerNameHeader(): void {
$request = new Request(
[
'server' => [
@@ -1190,7 +1190,7 @@ class RequestTest extends \Test\TestCase {
$this->assertSame('from.server.name:8080', $request->getInsecureServerHost());
}
- public function testInsecureServerHostHttpHostHeader() {
+ public function testInsecureServerHostHttpHostHeader(): void {
$request = new Request(
[
'server' => [
@@ -1207,7 +1207,7 @@ class RequestTest extends \Test\TestCase {
$this->assertSame('from.host.header:8080', $request->getInsecureServerHost());
}
- public function testInsecureServerHostHttpFromForwardedHeaderSingle() {
+ public function testInsecureServerHostHttpFromForwardedHeaderSingle(): void {
$this->config
->method('getSystemValue')
->willReturnCallback(function ($key, $default) {
@@ -1236,7 +1236,7 @@ class RequestTest extends \Test\TestCase {
$this->assertSame('from.forwarded.host:8080', $request->getInsecureServerHost());
}
- public function testInsecureServerHostHttpFromForwardedHeaderStacked() {
+ public function testInsecureServerHostHttpFromForwardedHeaderStacked(): void {
$this->config
->method('getSystemValue')
->willReturnCallback(function ($key, $default) {
@@ -1265,7 +1265,7 @@ class RequestTest extends \Test\TestCase {
$this->assertSame('from.forwarded.host2:8080', $request->getInsecureServerHost());
}
- public function testGetServerHostWithOverwriteHost() {
+ public function testGetServerHostWithOverwriteHost(): void {
$this->config
->method('getSystemValueString')
->willReturnCallback(function ($key, $default) {
@@ -1289,7 +1289,7 @@ class RequestTest extends \Test\TestCase {
$this->assertSame('my.overwritten.host', $request->getServerHost());
}
- public function testGetServerHostWithTrustedDomain() {
+ public function testGetServerHostWithTrustedDomain(): void {
$this->config
->method('getSystemValue')
->willReturnCallback(function ($key, $default) {
@@ -1318,7 +1318,7 @@ class RequestTest extends \Test\TestCase {
$this->assertSame('my.trusted.host', $request->getServerHost());
}
- public function testGetServerHostWithUntrustedDomain() {
+ public function testGetServerHostWithUntrustedDomain(): void {
$this->config
->method('getSystemValue')
->willReturnCallback(function ($key, $default) {
@@ -1347,7 +1347,7 @@ class RequestTest extends \Test\TestCase {
$this->assertSame('my.trusted.host', $request->getServerHost());
}
- public function testGetServerHostWithNoTrustedDomain() {
+ public function testGetServerHostWithNoTrustedDomain(): void {
$this->config
->method('getSystemValue')
->willReturnCallback(function ($key, $default) {
@@ -1390,7 +1390,7 @@ class RequestTest extends \Test\TestCase {
* @param $expected
* @param $trustedDomain
*/
- public function testGetServerHostTrustedDomain($expected, $trustedDomain) {
+ public function testGetServerHostTrustedDomain($expected, $trustedDomain): void {
$this->config
->method('getSystemValue')
->willReturnCallback(function ($key, $default) use ($trustedDomain) {
@@ -1419,7 +1419,7 @@ class RequestTest extends \Test\TestCase {
$this->assertSame($expected, $request->getServerHost());
}
- public function testGetOverwriteHostDefaultNull() {
+ public function testGetOverwriteHostDefaultNull(): void {
$this->config
->expects($this->once())
->method('getSystemValueString')
@@ -1436,7 +1436,7 @@ class RequestTest extends \Test\TestCase {
$this->assertNull(self::invokePrivate($request, 'getOverwriteHost'));
}
- public function testGetOverwriteHostWithOverwrite() {
+ public function testGetOverwriteHostWithOverwrite(): void {
$this->config
->expects($this->exactly(3))
->method('getSystemValueString')
@@ -1457,7 +1457,7 @@ class RequestTest extends \Test\TestCase {
}
- public function testGetPathInfoNotProcessible() {
+ public function testGetPathInfoNotProcessible(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The requested uri(/foo.php) cannot be processed by the script \'/var/www/index.php\')');
@@ -1478,7 +1478,7 @@ class RequestTest extends \Test\TestCase {
}
- public function testGetRawPathInfoNotProcessible() {
+ public function testGetRawPathInfoNotProcessible(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The requested uri(/foo.php) cannot be processed by the script \'/var/www/index.php\')');
@@ -1504,7 +1504,7 @@ class RequestTest extends \Test\TestCase {
* @param string $scriptName
* @param string $expected
*/
- public function testGetPathInfoWithoutSetEnvGeneric($requestUri, $scriptName, $expected) {
+ public function testGetPathInfoWithoutSetEnvGeneric($requestUri, $scriptName, $expected): void {
$request = new Request(
[
'server' => [
@@ -1527,7 +1527,7 @@ class RequestTest extends \Test\TestCase {
* @param string $scriptName
* @param string $expected
*/
- public function testGetRawPathInfoWithoutSetEnvGeneric($requestUri, $scriptName, $expected) {
+ public function testGetRawPathInfoWithoutSetEnvGeneric($requestUri, $scriptName, $expected): void {
$request = new Request(
[
'server' => [
@@ -1550,7 +1550,7 @@ class RequestTest extends \Test\TestCase {
* @param string $scriptName
* @param string $expected
*/
- public function testGetRawPathInfoWithoutSetEnv($requestUri, $scriptName, $expected) {
+ public function testGetRawPathInfoWithoutSetEnv($requestUri, $scriptName, $expected): void {
$request = new Request(
[
'server' => [
@@ -1573,7 +1573,7 @@ class RequestTest extends \Test\TestCase {
* @param string $scriptName
* @param string $expected
*/
- public function testGetPathInfoWithoutSetEnv($requestUri, $scriptName, $expected) {
+ public function testGetPathInfoWithoutSetEnv($requestUri, $scriptName, $expected): void {
$request = new Request(
[
'server' => [
@@ -1623,7 +1623,7 @@ class RequestTest extends \Test\TestCase {
];
}
- public function testGetRequestUriWithoutOverwrite() {
+ public function testGetRequestUriWithoutOverwrite(): void {
$this->config
->expects($this->once())
->method('getSystemValueString')
@@ -1655,7 +1655,7 @@ class RequestTest extends \Test\TestCase {
/**
* @dataProvider providesGetRequestUriWithOverwriteData
*/
- public function testGetRequestUriWithOverwrite($expectedUri, $overwriteWebRoot, $overwriteCondAddr, $remoteAddr = '') {
+ public function testGetRequestUriWithOverwrite($expectedUri, $overwriteWebRoot, $overwriteCondAddr, $remoteAddr = ''): void {
$this->config
->expects($this->exactly(2))
->method('getSystemValueString')
@@ -1688,7 +1688,7 @@ class RequestTest extends \Test\TestCase {
$this->assertSame($expectedUri, $request->getRequestUri());
}
- public function testPassesCSRFCheckWithGet() {
+ public function testPassesCSRFCheckWithGet(): void {
/** @var Request $request */
$request = $this->getMockBuilder(\OC\AppFramework\Http\Request::class)
->setMethods(['getScriptName'])
@@ -1718,7 +1718,7 @@ class RequestTest extends \Test\TestCase {
$this->assertTrue($request->passesCSRFCheck());
}
- public function testPassesCSRFCheckWithPost() {
+ public function testPassesCSRFCheckWithPost(): void {
/** @var Request $request */
$request = $this->getMockBuilder(\OC\AppFramework\Http\Request::class)
->setMethods(['getScriptName'])
@@ -1748,7 +1748,7 @@ class RequestTest extends \Test\TestCase {
$this->assertTrue($request->passesCSRFCheck());
}
- public function testPassesCSRFCheckWithHeader() {
+ public function testPassesCSRFCheckWithHeader(): void {
/** @var Request $request */
$request = $this->getMockBuilder(\OC\AppFramework\Http\Request::class)
->setMethods(['getScriptName'])
@@ -1778,7 +1778,7 @@ class RequestTest extends \Test\TestCase {
$this->assertTrue($request->passesCSRFCheck());
}
- public function testPassesCSRFCheckWithGetAndWithoutCookies() {
+ public function testPassesCSRFCheckWithGetAndWithoutCookies(): void {
/** @var Request $request */
$request = $this->getMockBuilder(\OC\AppFramework\Http\Request::class)
->setMethods(['getScriptName'])
@@ -1802,7 +1802,7 @@ class RequestTest extends \Test\TestCase {
$this->assertTrue($request->passesCSRFCheck());
}
- public function testPassesCSRFCheckWithPostAndWithoutCookies() {
+ public function testPassesCSRFCheckWithPostAndWithoutCookies(): void {
/** @var Request $request */
$request = $this->getMockBuilder(\OC\AppFramework\Http\Request::class)
->setMethods(['getScriptName'])
@@ -1826,7 +1826,7 @@ class RequestTest extends \Test\TestCase {
$this->assertTrue($request->passesCSRFCheck());
}
- public function testPassesCSRFCheckWithHeaderAndWithoutCookies() {
+ public function testPassesCSRFCheckWithHeaderAndWithoutCookies(): void {
/** @var Request $request */
$request = $this->getMockBuilder(\OC\AppFramework\Http\Request::class)
->setMethods(['getScriptName'])
@@ -1850,7 +1850,7 @@ class RequestTest extends \Test\TestCase {
$this->assertTrue($request->passesCSRFCheck());
}
- public function testFailsCSRFCheckWithHeaderAndNotAllChecksPassing() {
+ public function testFailsCSRFCheckWithHeaderAndNotAllChecksPassing(): void {
/** @var Request $request */
$request = $this->getMockBuilder(\OC\AppFramework\Http\Request::class)
->setMethods(['getScriptName'])
@@ -1877,7 +1877,7 @@ class RequestTest extends \Test\TestCase {
$this->assertFalse($request->passesCSRFCheck());
}
- public function testPassesStrictCookieCheckWithAllCookiesAndStrict() {
+ public function testPassesStrictCookieCheckWithAllCookiesAndStrict(): void {
/** @var Request $request */
$request = $this->getMockBuilder(\OC\AppFramework\Http\Request::class)
->setMethods(['getScriptName', 'getCookieParams'])
@@ -1909,7 +1909,7 @@ class RequestTest extends \Test\TestCase {
$this->assertTrue($request->passesStrictCookieCheck());
}
- public function testFailsStrictCookieCheckWithAllCookiesAndMissingStrict() {
+ public function testFailsStrictCookieCheckWithAllCookiesAndMissingStrict(): void {
/** @var Request $request */
$request = $this->getMockBuilder(\OC\AppFramework\Http\Request::class)
->setMethods(['getScriptName', 'getCookieParams'])
@@ -1941,7 +1941,7 @@ class RequestTest extends \Test\TestCase {
$this->assertFalse($request->passesStrictCookieCheck());
}
- public function testGetCookieParams() {
+ public function testGetCookieParams(): void {
/** @var Request $request */
$request = $this->getMockBuilder(Request::class)
->setMethods(['getScriptName'])
@@ -1957,7 +1957,7 @@ class RequestTest extends \Test\TestCase {
$this->assertSame(session_get_cookie_params(), $actual);
}
- public function testPassesStrictCookieCheckWithAllCookies() {
+ public function testPassesStrictCookieCheckWithAllCookies(): void {
/** @var Request $request */
$request = $this->getMockBuilder(\OC\AppFramework\Http\Request::class)
->setMethods(['getScriptName'])
@@ -1982,7 +1982,7 @@ class RequestTest extends \Test\TestCase {
$this->assertTrue($request->passesStrictCookieCheck());
}
- public function testPassesStrictCookieCheckWithRandomCookies() {
+ public function testPassesStrictCookieCheckWithRandomCookies(): void {
/** @var Request $request */
$request = $this->getMockBuilder(\OC\AppFramework\Http\Request::class)
->setMethods(['getScriptName'])
@@ -2005,7 +2005,7 @@ class RequestTest extends \Test\TestCase {
$this->assertTrue($request->passesStrictCookieCheck());
}
- public function testFailsStrictCookieCheckWithSessionCookie() {
+ public function testFailsStrictCookieCheckWithSessionCookie(): void {
/** @var Request $request */
$request = $this->getMockBuilder(\OC\AppFramework\Http\Request::class)
->setMethods(['getScriptName'])
@@ -2028,7 +2028,7 @@ class RequestTest extends \Test\TestCase {
$this->assertFalse($request->passesStrictCookieCheck());
}
- public function testFailsStrictCookieCheckWithRememberMeCookie() {
+ public function testFailsStrictCookieCheckWithRememberMeCookie(): void {
/** @var Request $request */
$request = $this->getMockBuilder(\OC\AppFramework\Http\Request::class)
->setMethods(['getScriptName'])
@@ -2051,7 +2051,7 @@ class RequestTest extends \Test\TestCase {
$this->assertFalse($request->passesStrictCookieCheck());
}
- public function testFailsCSRFCheckWithPostAndWithCookies() {
+ public function testFailsCSRFCheckWithPostAndWithCookies(): void {
/** @var Request $request */
$request = $this->getMockBuilder(\OC\AppFramework\Http\Request::class)
->setMethods(['getScriptName'])
@@ -2078,7 +2078,7 @@ class RequestTest extends \Test\TestCase {
$this->assertFalse($request->passesCSRFCheck());
}
- public function testFailStrictCookieCheckWithOnlyLaxCookie() {
+ public function testFailStrictCookieCheckWithOnlyLaxCookie(): void {
/** @var Request $request */
$request = $this->getMockBuilder(\OC\AppFramework\Http\Request::class)
->setMethods(['getScriptName'])
@@ -2102,7 +2102,7 @@ class RequestTest extends \Test\TestCase {
$this->assertFalse($request->passesStrictCookieCheck());
}
- public function testFailStrictCookieCheckWithOnlyStrictCookie() {
+ public function testFailStrictCookieCheckWithOnlyStrictCookie(): void {
/** @var Request $request */
$request = $this->getMockBuilder(\OC\AppFramework\Http\Request::class)
->setMethods(['getScriptName'])
@@ -2126,7 +2126,7 @@ class RequestTest extends \Test\TestCase {
$this->assertFalse($request->passesStrictCookieCheck());
}
- public function testPassesLaxCookieCheck() {
+ public function testPassesLaxCookieCheck(): void {
/** @var Request $request */
$request = $this->getMockBuilder(\OC\AppFramework\Http\Request::class)
->setMethods(['getScriptName'])
@@ -2150,7 +2150,7 @@ class RequestTest extends \Test\TestCase {
$this->assertTrue($request->passesLaxCookieCheck());
}
- public function testFailsLaxCookieCheckWithOnlyStrictCookie() {
+ public function testFailsLaxCookieCheckWithOnlyStrictCookie(): void {
/** @var Request $request */
$request = $this->getMockBuilder(\OC\AppFramework\Http\Request::class)
->setMethods(['getScriptName'])
@@ -2174,7 +2174,7 @@ class RequestTest extends \Test\TestCase {
$this->assertFalse($request->passesLaxCookieCheck());
}
- public function testSkipCookieCheckForOCSRequests() {
+ public function testSkipCookieCheckForOCSRequests(): void {
/** @var Request $request */
$request = $this->getMockBuilder(\OC\AppFramework\Http\Request::class)
->setMethods(['getScriptName'])
@@ -2214,7 +2214,7 @@ class RequestTest extends \Test\TestCase {
* @dataProvider invalidTokenDataProvider
* @param string $invalidToken
*/
- public function testPassesCSRFCheckWithInvalidToken($invalidToken) {
+ public function testPassesCSRFCheckWithInvalidToken($invalidToken): void {
/** @var Request $request */
$request = $this->getMockBuilder(\OC\AppFramework\Http\Request::class)
->setMethods(['getScriptName'])
@@ -2241,7 +2241,7 @@ class RequestTest extends \Test\TestCase {
$this->assertFalse($request->passesCSRFCheck());
}
- public function testPassesCSRFCheckWithoutTokenFail() {
+ public function testPassesCSRFCheckWithoutTokenFail(): void {
/** @var Request $request */
$request = $this->getMockBuilder(\OC\AppFramework\Http\Request::class)
->setMethods(['getScriptName'])
@@ -2257,7 +2257,7 @@ class RequestTest extends \Test\TestCase {
$this->assertFalse($request->passesCSRFCheck());
}
- public function testPassesCSRFCheckWithOCSAPIRequestHeader() {
+ public function testPassesCSRFCheckWithOCSAPIRequestHeader(): void {
/** @var Request $request */
$request = $this->getMockBuilder(\OC\AppFramework\Http\Request::class)
->setMethods(['getScriptName'])
diff --git a/tests/lib/AppFramework/Http/ResponseTest.php b/tests/lib/AppFramework/Http/ResponseTest.php
index d01d29e7071..28614b14b40 100644
--- a/tests/lib/AppFramework/Http/ResponseTest.php
+++ b/tests/lib/AppFramework/Http/ResponseTest.php
@@ -24,14 +24,14 @@ class ResponseTest extends \Test\TestCase {
}
- public function testAddHeader() {
+ public function testAddHeader(): void {
$this->childResponse->addHeader(' hello ', 'world');
$headers = $this->childResponse->getHeaders();
$this->assertEquals('world', $headers['hello']);
}
- public function testSetHeaders() {
+ public function testSetHeaders(): void {
$expected = [
'Last-Modified' => 1,
'ETag' => 3,
@@ -50,7 +50,7 @@ class ResponseTest extends \Test\TestCase {
$this->assertEquals($expected, $headers);
}
- public function testOverwriteCsp() {
+ public function testOverwriteCsp(): void {
$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'",
];
@@ -62,31 +62,31 @@ class ResponseTest extends \Test\TestCase {
$this->assertEquals(array_merge($expected, $headers), $headers);
}
- public function testGetCsp() {
+ public function testGetCsp(): void {
$policy = new Http\ContentSecurityPolicy();
$this->childResponse->setContentSecurityPolicy($policy);
$this->assertEquals($policy, $this->childResponse->getContentSecurityPolicy());
}
- public function testGetCspEmpty() {
+ public function testGetCspEmpty(): void {
$this->assertEquals(new Http\EmptyContentSecurityPolicy(), $this->childResponse->getContentSecurityPolicy());
}
- public function testAddHeaderValueNullDeletesIt() {
+ public function testAddHeaderValueNullDeletesIt(): void {
$this->childResponse->addHeader('hello', 'world');
$this->childResponse->addHeader('hello', null);
$this->assertEquals(5, count($this->childResponse->getHeaders()));
}
- public function testCacheHeadersAreDisabledByDefault() {
+ public function testCacheHeadersAreDisabledByDefault(): void {
$headers = $this->childResponse->getHeaders();
$this->assertEquals('no-cache, no-store, must-revalidate', $headers['Cache-Control']);
}
- public function testAddCookie() {
+ public function testAddCookie(): void {
$this->childResponse->addCookie('foo', 'bar');
$this->childResponse->addCookie('bar', 'foo', new \DateTime('1970-01-01'));
@@ -106,7 +106,7 @@ class ResponseTest extends \Test\TestCase {
}
- public function testSetCookies() {
+ public function testSetCookies(): void {
$expected = [
'foo' => [
'value' => 'bar',
@@ -125,7 +125,7 @@ class ResponseTest extends \Test\TestCase {
}
- public function testInvalidateCookie() {
+ public function testInvalidateCookie(): void {
$this->childResponse->addCookie('foo', 'bar');
$this->childResponse->invalidateCookie('foo');
$expected = [
@@ -142,7 +142,7 @@ class ResponseTest extends \Test\TestCase {
}
- public function testInvalidateCookies() {
+ public function testInvalidateCookies(): void {
$this->childResponse->addCookie('foo', 'bar');
$this->childResponse->addCookie('bar', 'foo');
$expected = [
@@ -179,12 +179,12 @@ class ResponseTest extends \Test\TestCase {
}
- public function testRenderReturnNullByDefault() {
+ public function testRenderReturnNullByDefault(): void {
$this->assertEquals(null, $this->childResponse->render());
}
- public function testGetStatus() {
+ public function testGetStatus(): void {
$default = $this->childResponse->getStatus();
$this->childResponse->setStatus(Http::STATUS_NOT_FOUND);
@@ -194,13 +194,13 @@ class ResponseTest extends \Test\TestCase {
}
- public function testGetEtag() {
+ public function testGetEtag(): void {
$this->childResponse->setEtag('hi');
$this->assertSame('hi', $this->childResponse->getEtag());
}
- public function testGetLastModified() {
+ public function testGetLastModified(): void {
$lastModified = new \DateTime('now', new \DateTimeZone('GMT'));
$lastModified->setTimestamp(1);
$this->childResponse->setLastModified($lastModified);
@@ -209,7 +209,7 @@ class ResponseTest extends \Test\TestCase {
- public function testCacheSecondsZero() {
+ public function testCacheSecondsZero(): void {
$this->childResponse->cacheFor(0);
$headers = $this->childResponse->getHeaders();
@@ -218,7 +218,7 @@ class ResponseTest extends \Test\TestCase {
}
- public function testCacheSeconds() {
+ public function testCacheSeconds(): void {
$time = $this->createMock(ITimeFactory::class);
$time->method('getTime')
->willReturn(1234567);
@@ -234,7 +234,7 @@ class ResponseTest extends \Test\TestCase {
- public function testEtagLastModifiedHeaders() {
+ public function testEtagLastModifiedHeaders(): void {
$lastModified = new \DateTime('now', new \DateTimeZone('GMT'));
$lastModified->setTimestamp(1);
$this->childResponse->setLastModified($lastModified);
@@ -242,7 +242,7 @@ class ResponseTest extends \Test\TestCase {
$this->assertEquals('Thu, 01 Jan 1970 00:00:01 +0000', $headers['Last-Modified']);
}
- public function testChainability() {
+ public function testChainability(): void {
$lastModified = new \DateTime('now', new \DateTimeZone('GMT'));
$lastModified->setTimestamp(1);
@@ -262,13 +262,13 @@ class ResponseTest extends \Test\TestCase {
$headers['Cache-Control']);
}
- public function testThrottle() {
+ public function testThrottle(): void {
$this->assertFalse($this->childResponse->isThrottled());
$this->childResponse->throttle();
$this->assertTrue($this->childResponse->isThrottled());
}
- public function testGetThrottleMetadata() {
+ public function testGetThrottleMetadata(): void {
$this->childResponse->throttle(['foo' => 'bar']);
$this->assertSame(['foo' => 'bar'], $this->childResponse->getThrottleMetadata());
}
diff --git a/tests/lib/AppFramework/Http/StreamResponseTest.php b/tests/lib/AppFramework/Http/StreamResponseTest.php
index 67e7cc2f161..2148598f041 100644
--- a/tests/lib/AppFramework/Http/StreamResponseTest.php
+++ b/tests/lib/AppFramework/Http/StreamResponseTest.php
@@ -23,7 +23,7 @@ class StreamResponseTest extends \Test\TestCase {
->getMock();
}
- public function testOutputNotModified() {
+ public function testOutputNotModified(): void {
$path = __FILE__;
$this->output->expects($this->once())
->method('getHttpResponseCode')
@@ -35,7 +35,7 @@ class StreamResponseTest extends \Test\TestCase {
$response->callback($this->output);
}
- public function testOutputOk() {
+ public function testOutputOk(): void {
$path = __FILE__;
$this->output->expects($this->once())
->method('getHttpResponseCode')
@@ -49,7 +49,7 @@ class StreamResponseTest extends \Test\TestCase {
$response->callback($this->output);
}
- public function testOutputNotFound() {
+ public function testOutputNotFound(): void {
$path = __FILE__ . 'test';
$this->output->expects($this->once())
->method('getHttpResponseCode')
@@ -64,7 +64,7 @@ class StreamResponseTest extends \Test\TestCase {
$response->callback($this->output);
}
- public function testOutputReadFileError() {
+ public function testOutputReadFileError(): void {
$path = __FILE__;
$this->output->expects($this->once())
->method('getHttpResponseCode')
diff --git a/tests/lib/AppFramework/Http/TemplateResponseTest.php b/tests/lib/AppFramework/Http/TemplateResponseTest.php
index df9824d3032..ad0fe808b76 100644
--- a/tests/lib/AppFramework/Http/TemplateResponseTest.php
+++ b/tests/lib/AppFramework/Http/TemplateResponseTest.php
@@ -24,7 +24,7 @@ class TemplateResponseTest extends \Test\TestCase {
}
- public function testSetParamsConstructor() {
+ public function testSetParamsConstructor(): void {
$params = ['hi' => 'yo'];
$this->tpl = new TemplateResponse('app', 'home', $params);
@@ -32,7 +32,7 @@ class TemplateResponseTest extends \Test\TestCase {
}
- public function testSetRenderAsConstructor() {
+ public function testSetRenderAsConstructor(): void {
$renderAs = 'myrender';
$this->tpl = new TemplateResponse('app', 'home', [], $renderAs);
@@ -40,7 +40,7 @@ class TemplateResponseTest extends \Test\TestCase {
}
- public function testSetParams() {
+ public function testSetParams(): void {
$params = ['hi' => 'yo'];
$this->tpl->setParams($params);
@@ -48,17 +48,17 @@ class TemplateResponseTest extends \Test\TestCase {
}
- public function testGetTemplateName() {
+ public function testGetTemplateName(): void {
$this->assertEquals('home', $this->tpl->getTemplateName());
}
- public function testGetRenderAs() {
+ public function testGetRenderAs(): void {
$render = 'myrender';
$this->tpl->renderAs($render);
$this->assertEquals($render, $this->tpl->getRenderAs());
}
- public function testChainability() {
+ public function testChainability(): void {
$params = ['hi' => 'yo'];
$this->tpl->setParams($params)
->setStatus(Http::STATUS_NOT_FOUND);
diff --git a/tests/lib/AppFramework/Middleware/AdditionalScriptsMiddlewareTest.php b/tests/lib/AppFramework/Middleware/AdditionalScriptsMiddlewareTest.php
index 890735008fc..22b1b13aaee 100644
--- a/tests/lib/AppFramework/Middleware/AdditionalScriptsMiddlewareTest.php
+++ b/tests/lib/AppFramework/Middleware/AdditionalScriptsMiddlewareTest.php
@@ -44,7 +44,7 @@ class AdditionalScriptsMiddlewareTest extends \Test\TestCase {
$this->controller = $this->createMock(Controller::class);
}
- public function testNoTemplateResponse() {
+ public function testNoTemplateResponse(): void {
$this->userSession->expects($this->never())
->method($this->anything());
$this->dispatcher->expects($this->never())
@@ -53,7 +53,7 @@ class AdditionalScriptsMiddlewareTest extends \Test\TestCase {
$this->middleWare->afterController($this->controller, 'myMethod', $this->createMock(Response::class));
}
- public function testPublicShareController() {
+ public function testPublicShareController(): void {
$this->userSession->expects($this->never())
->method($this->anything());
$this->dispatcher->expects($this->never())
@@ -62,7 +62,7 @@ class AdditionalScriptsMiddlewareTest extends \Test\TestCase {
$this->middleWare->afterController($this->createMock(PublicShareController::class), 'myMethod', $this->createMock(Response::class));
}
- public function testStandaloneTemplateResponse() {
+ public function testStandaloneTemplateResponse(): void {
$this->userSession->expects($this->never())
->method($this->anything());
$this->dispatcher->expects($this->once())
@@ -78,7 +78,7 @@ class AdditionalScriptsMiddlewareTest extends \Test\TestCase {
$this->middleWare->afterController($this->controller, 'myMethod', $this->createMock(StandaloneTemplateResponse::class));
}
- public function testTemplateResponseNotLoggedIn() {
+ public function testTemplateResponseNotLoggedIn(): void {
$this->userSession->method('isLoggedIn')
->willReturn(false);
$this->dispatcher->expects($this->once())
@@ -94,7 +94,7 @@ class AdditionalScriptsMiddlewareTest extends \Test\TestCase {
$this->middleWare->afterController($this->controller, 'myMethod', $this->createMock(TemplateResponse::class));
}
- public function testTemplateResponseLoggedIn() {
+ public function testTemplateResponseLoggedIn(): void {
$events = [];
$this->userSession->method('isLoggedIn')
diff --git a/tests/lib/AppFramework/Middleware/CompressionMiddlewareTest.php b/tests/lib/AppFramework/Middleware/CompressionMiddlewareTest.php
index a0848b70796..010ce3fff6d 100644
--- a/tests/lib/AppFramework/Middleware/CompressionMiddlewareTest.php
+++ b/tests/lib/AppFramework/Middleware/CompressionMiddlewareTest.php
@@ -36,7 +36,7 @@ class CompressionMiddlewareTest extends \Test\TestCase {
$this->controller = $this->createMock(Controller::class);
}
- public function testGzipOCSV1() {
+ public function testGzipOCSV1(): void {
$this->request->method('getHeader')
->with('Accept-Encoding')
->willReturn('gzip');
@@ -58,7 +58,7 @@ class CompressionMiddlewareTest extends \Test\TestCase {
$this->assertSame($output, gzdecode($result));
}
- public function testGzipOCSV2() {
+ public function testGzipOCSV2(): void {
$this->request->method('getHeader')
->with('Accept-Encoding')
->willReturn('gzip');
@@ -80,7 +80,7 @@ class CompressionMiddlewareTest extends \Test\TestCase {
$this->assertSame($output, gzdecode($result));
}
- public function testGzipJSONResponse() {
+ public function testGzipJSONResponse(): void {
$this->request->method('getHeader')
->with('Accept-Encoding')
->willReturn('gzip');
@@ -102,7 +102,7 @@ class CompressionMiddlewareTest extends \Test\TestCase {
$this->assertSame($output, gzdecode($result));
}
- public function testNoGzipDataResponse() {
+ public function testNoGzipDataResponse(): void {
$this->request->method('getHeader')
->with('Accept-Encoding')
->willReturn('gzip');
@@ -122,7 +122,7 @@ class CompressionMiddlewareTest extends \Test\TestCase {
$this->assertSame($output, $result);
}
- public function testNoGzipNo200() {
+ public function testNoGzipNo200(): void {
$this->request->method('getHeader')
->with('Accept-Encoding')
->willReturn('gzip');
diff --git a/tests/lib/AppFramework/Middleware/MiddlewareDispatcherTest.php b/tests/lib/AppFramework/Middleware/MiddlewareDispatcherTest.php
index f4921ba7519..df3829d39fb 100644
--- a/tests/lib/AppFramework/Middleware/MiddlewareDispatcherTest.php
+++ b/tests/lib/AppFramework/Middleware/MiddlewareDispatcherTest.php
@@ -129,7 +129,7 @@ class MiddlewareDispatcherTest extends \Test\TestCase {
}
- public function testAfterExceptionShouldReturnResponseOfMiddleware() {
+ public function testAfterExceptionShouldReturnResponseOfMiddleware(): void {
$response = new Response();
$m1 = $this->getMockBuilder(\OCP\AppFramework\Middleware::class)
->setMethods(['afterException', 'beforeController'])
@@ -152,7 +152,7 @@ class MiddlewareDispatcherTest extends \Test\TestCase {
}
- public function testAfterExceptionShouldThrowAgainWhenNotHandled() {
+ public function testAfterExceptionShouldThrowAgainWhenNotHandled(): void {
$m1 = new TestMiddleware(false);
$m2 = new TestMiddleware(true);
@@ -165,7 +165,7 @@ class MiddlewareDispatcherTest extends \Test\TestCase {
}
- public function testBeforeControllerCorrectArguments() {
+ public function testBeforeControllerCorrectArguments(): void {
$m1 = $this->getMiddleware();
$this->dispatcher->beforeController($this->controller, $this->method);
@@ -174,7 +174,7 @@ class MiddlewareDispatcherTest extends \Test\TestCase {
}
- public function testAfterControllerCorrectArguments() {
+ public function testAfterControllerCorrectArguments(): void {
$m1 = $this->getMiddleware();
$this->dispatcher->afterController($this->controller, $this->method, $this->response);
@@ -185,7 +185,7 @@ class MiddlewareDispatcherTest extends \Test\TestCase {
}
- public function testAfterExceptionCorrectArguments() {
+ public function testAfterExceptionCorrectArguments(): void {
$m1 = $this->getMiddleware();
$this->expectException(\Exception::class);
@@ -199,7 +199,7 @@ class MiddlewareDispatcherTest extends \Test\TestCase {
}
- public function testBeforeOutputCorrectArguments() {
+ public function testBeforeOutputCorrectArguments(): void {
$m1 = $this->getMiddleware();
$this->dispatcher->beforeOutput($this->controller, $this->method, $this->out);
@@ -210,7 +210,7 @@ class MiddlewareDispatcherTest extends \Test\TestCase {
}
- public function testBeforeControllerOrder() {
+ public function testBeforeControllerOrder(): void {
$m1 = $this->getMiddleware();
$m2 = $this->getMiddleware();
@@ -220,7 +220,7 @@ class MiddlewareDispatcherTest extends \Test\TestCase {
$this->assertEquals(2, $m2->beforeControllerOrder);
}
- public function testAfterControllerOrder() {
+ public function testAfterControllerOrder(): void {
$m1 = $this->getMiddleware();
$m2 = $this->getMiddleware();
@@ -231,7 +231,7 @@ class MiddlewareDispatcherTest extends \Test\TestCase {
}
- public function testAfterExceptionOrder() {
+ public function testAfterExceptionOrder(): void {
$m1 = $this->getMiddleware();
$m2 = $this->getMiddleware();
@@ -244,7 +244,7 @@ class MiddlewareDispatcherTest extends \Test\TestCase {
}
- public function testBeforeOutputOrder() {
+ public function testBeforeOutputOrder(): void {
$m1 = $this->getMiddleware();
$m2 = $this->getMiddleware();
@@ -255,7 +255,7 @@ class MiddlewareDispatcherTest extends \Test\TestCase {
}
- public function testExceptionShouldRunAfterExceptionOfOnlyPreviouslyExecutedMiddlewares() {
+ public function testExceptionShouldRunAfterExceptionOfOnlyPreviouslyExecutedMiddlewares(): void {
$m1 = $this->getMiddleware();
$m2 = $this->getMiddleware(true);
$m3 = $this->createMock(Middleware::class);
diff --git a/tests/lib/AppFramework/Middleware/NotModifiedMiddlewareTest.php b/tests/lib/AppFramework/Middleware/NotModifiedMiddlewareTest.php
index e41bb45e069..58ae6b13aed 100644
--- a/tests/lib/AppFramework/Middleware/NotModifiedMiddlewareTest.php
+++ b/tests/lib/AppFramework/Middleware/NotModifiedMiddlewareTest.php
@@ -56,7 +56,7 @@ class NotModifiedMiddlewareTest extends \Test\TestCase {
/**
* @dataProvider dataModified
*/
- public function testMiddleware(?string $etag, string $etagHeader, ?\DateTime $lastModified, string $lastModifiedHeader, bool $notModifiedSet) {
+ 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) {
if ($name === 'IF_NONE_MATCH') {
diff --git a/tests/lib/AppFramework/Middleware/OCSMiddlewareTest.php b/tests/lib/AppFramework/Middleware/OCSMiddlewareTest.php
index 28b2ba34fca..6724f841c5e 100644
--- a/tests/lib/AppFramework/Middleware/OCSMiddlewareTest.php
+++ b/tests/lib/AppFramework/Middleware/OCSMiddlewareTest.php
@@ -74,7 +74,7 @@ class OCSMiddlewareTest extends \Test\TestCase {
* @param string $message
* @param int $code
*/
- public function testAfterExceptionOCSv1($controller, $exception, $forward, $message = '', $code = 0) {
+ public function testAfterExceptionOCSv1($controller, $exception, $forward, $message = '', $code = 0): void {
$this->request
->method('getScriptName')
->willReturn('/ocs/v1.php');
@@ -110,7 +110,7 @@ class OCSMiddlewareTest extends \Test\TestCase {
* @param string $message
* @param int $code
*/
- public function testAfterExceptionOCSv2($controller, $exception, $forward, $message = '', $code = 0) {
+ public function testAfterExceptionOCSv2($controller, $exception, $forward, $message = '', $code = 0): void {
$this->request
->method('getScriptName')
->willReturn('/ocs/v2.php');
@@ -144,7 +144,7 @@ class OCSMiddlewareTest extends \Test\TestCase {
* @param string $message
* @param int $code
*/
- public function testAfterExceptionOCSv2SubFolder($controller, $exception, $forward, $message = '', $code = 0) {
+ public function testAfterExceptionOCSv2SubFolder($controller, $exception, $forward, $message = '', $code = 0): void {
$this->request
->method('getScriptName')
->willReturn('/mysubfolder/ocs/v2.php');
@@ -201,7 +201,7 @@ class OCSMiddlewareTest extends \Test\TestCase {
* @param bool $converted
* @param int $convertedOCSStatus
*/
- public function testAfterController($controller, $response, $converted, $convertedOCSStatus = 0) {
+ public function testAfterController($controller, $response, $converted, $convertedOCSStatus = 0): void {
$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 64a9efbfe60..8433aa93f4a 100644
--- a/tests/lib/AppFramework/Middleware/PublicShare/PublicShareMiddlewareTest.php
+++ b/tests/lib/AppFramework/Middleware/PublicShare/PublicShareMiddlewareTest.php
@@ -51,7 +51,7 @@ class PublicShareMiddlewareTest extends \Test\TestCase {
);
}
- public function testBeforeControllerNoPublicShareController() {
+ public function testBeforeControllerNoPublicShareController(): void {
$controller = $this->createMock(Controller::class);
$this->middleware->beforeController($controller, 'method');
@@ -69,7 +69,7 @@ class PublicShareMiddlewareTest extends \Test\TestCase {
/**
* @dataProvider dataShareApi
*/
- public function testBeforeControllerShareApiDisabled(string $shareApi, string $shareLinks) {
+ public function testBeforeControllerShareApiDisabled(string $shareApi, string $shareLinks): void {
$controller = $this->createMock(PublicShareController::class);
$this->config->method('getAppValue')
@@ -82,7 +82,7 @@ class PublicShareMiddlewareTest extends \Test\TestCase {
$this->middleware->beforeController($controller, 'mehod');
}
- public function testBeforeControllerNoTokenParam() {
+ public function testBeforeControllerNoTokenParam(): void {
$controller = $this->createMock(PublicShareController::class);
$this->config->method('getAppValue')
@@ -95,7 +95,7 @@ class PublicShareMiddlewareTest extends \Test\TestCase {
$this->middleware->beforeController($controller, 'mehod');
}
- public function testBeforeControllerInvalidToken() {
+ public function testBeforeControllerInvalidToken(): void {
$controller = $this->createMock(PublicShareController::class);
$this->config->method('getAppValue')
@@ -117,7 +117,7 @@ class PublicShareMiddlewareTest extends \Test\TestCase {
$this->middleware->beforeController($controller, 'mehod');
}
- public function testBeforeControllerValidTokenNotAuthenticated() {
+ public function testBeforeControllerValidTokenNotAuthenticated(): void {
$controller = $this->getMockBuilder(PublicShareController::class)
->setConstructorArgs(['app', $this->request, $this->session])
->getMock();
@@ -142,7 +142,7 @@ class PublicShareMiddlewareTest extends \Test\TestCase {
$this->middleware->beforeController($controller, 'mehod');
}
- public function testBeforeControllerValidTokenAuthenticateMethod() {
+ public function testBeforeControllerValidTokenAuthenticateMethod(): void {
$controller = $this->getMockBuilder(PublicShareController::class)
->setConstructorArgs(['app', $this->request, $this->session])
->getMock();
@@ -167,7 +167,7 @@ class PublicShareMiddlewareTest extends \Test\TestCase {
$this->assertTrue(true);
}
- public function testBeforeControllerValidTokenShowAuthenticateMethod() {
+ public function testBeforeControllerValidTokenShowAuthenticateMethod(): void {
$controller = $this->getMockBuilder(PublicShareController::class)
->setConstructorArgs(['app', $this->request, $this->session])
->getMock();
@@ -192,7 +192,7 @@ class PublicShareMiddlewareTest extends \Test\TestCase {
$this->assertTrue(true);
}
- public function testBeforeControllerAuthPublicShareController() {
+ public function testBeforeControllerAuthPublicShareController(): void {
$controller = $this->getMockBuilder(AuthPublicShareController::class)
->setConstructorArgs(['app', $this->request, $this->session, $this->createMock(IURLGenerator::class)])
->getMock();
@@ -221,7 +221,7 @@ class PublicShareMiddlewareTest extends \Test\TestCase {
$this->middleware->beforeController($controller, 'method');
}
- public function testAfterExceptionNoPublicShareController() {
+ public function testAfterExceptionNoPublicShareController(): void {
$controller = $this->createMock(Controller::class);
$exception = new \Exception();
@@ -232,7 +232,7 @@ class PublicShareMiddlewareTest extends \Test\TestCase {
}
}
- public function testAfterExceptionPublicShareControllerNotFoundException() {
+ public function testAfterExceptionPublicShareControllerNotFoundException(): void {
$controller = $this->createMock(PublicShareController::class);
$exception = new NotFoundException();
@@ -241,7 +241,7 @@ class PublicShareMiddlewareTest extends \Test\TestCase {
$this->assertEquals($result->getStatus(), Http::STATUS_NOT_FOUND);
}
- public function testAfterExceptionPublicShareController() {
+ public function testAfterExceptionPublicShareController(): void {
$controller = $this->createMock(PublicShareController::class);
$exception = new \Exception();
@@ -252,7 +252,7 @@ class PublicShareMiddlewareTest extends \Test\TestCase {
}
}
- public function testAfterExceptionAuthPublicShareController() {
+ public function testAfterExceptionAuthPublicShareController(): void {
$controller = $this->getMockBuilder(AuthPublicShareController::class)
->setConstructorArgs([
'app',
diff --git a/tests/lib/AppFramework/Middleware/Security/CORSMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/CORSMiddlewareTest.php
index 00538dda4b0..b703b10c554 100644
--- a/tests/lib/AppFramework/Middleware/Security/CORSMiddlewareTest.php
+++ b/tests/lib/AppFramework/Middleware/Security/CORSMiddlewareTest.php
@@ -308,7 +308,7 @@ class CORSMiddlewareTest extends \Test\TestCase {
$middleware->beforeController($this->controller, $method);
}
- public function testAfterExceptionWithSecurityExceptionNoStatus() {
+ public function testAfterExceptionWithSecurityExceptionNoStatus(): void {
$request = new Request(
['server' => [
'PHP_AUTH_USER' => 'user',
@@ -324,7 +324,7 @@ class CORSMiddlewareTest extends \Test\TestCase {
$this->assertEquals($expected, $response);
}
- public function testAfterExceptionWithSecurityExceptionWithStatus() {
+ public function testAfterExceptionWithSecurityExceptionWithStatus(): void {
$request = new Request(
['server' => [
'PHP_AUTH_USER' => 'user',
@@ -340,7 +340,7 @@ class CORSMiddlewareTest extends \Test\TestCase {
$this->assertEquals($expected, $response);
}
- public function testAfterExceptionWithRegularException() {
+ public function testAfterExceptionWithRegularException(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('A regular exception');
diff --git a/tests/lib/AppFramework/Middleware/Security/CSPMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/CSPMiddlewareTest.php
index dd6ee9531b2..b0b41b27cb9 100644
--- a/tests/lib/AppFramework/Middleware/Security/CSPMiddlewareTest.php
+++ b/tests/lib/AppFramework/Middleware/Security/CSPMiddlewareTest.php
@@ -39,7 +39,7 @@ class CSPMiddlewareTest extends \Test\TestCase {
);
}
- public function testAfterController() {
+ public function testAfterController(): void {
$this->cspNonceManager
->expects($this->once())
->method('browserSupportsCspV3')
@@ -71,7 +71,7 @@ class CSPMiddlewareTest extends \Test\TestCase {
$this->middleware->afterController($this->controller, 'test', $response);
}
- public function testAfterControllerEmptyCSP() {
+ public function testAfterControllerEmptyCSP(): void {
$response = $this->createMock(Response::class);
$emptyPolicy = new EmptyContentSecurityPolicy();
$response->expects($this->any())
@@ -83,7 +83,7 @@ class CSPMiddlewareTest extends \Test\TestCase {
$this->middleware->afterController($this->controller, 'test', $response);
}
- public function testAfterControllerWithContentSecurityPolicy3Support() {
+ public function testAfterControllerWithContentSecurityPolicy3Support(): void {
$this->cspNonceManager
->expects($this->once())
->method('browserSupportsCspV3')
diff --git a/tests/lib/AppFramework/Middleware/Security/FeaturePolicyMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/FeaturePolicyMiddlewareTest.php
index 1cdd99b1aae..55a70d4c040 100644
--- a/tests/lib/AppFramework/Middleware/Security/FeaturePolicyMiddlewareTest.php
+++ b/tests/lib/AppFramework/Middleware/Security/FeaturePolicyMiddlewareTest.php
@@ -34,7 +34,7 @@ class FeaturePolicyMiddlewareTest extends \Test\TestCase {
);
}
- public function testAfterController() {
+ public function testAfterController(): void {
$response = $this->createMock(Response::class);
$defaultPolicy = new FeaturePolicy();
$defaultPolicy->addAllowedCameraDomain('defaultpolicy');
@@ -56,7 +56,7 @@ class FeaturePolicyMiddlewareTest extends \Test\TestCase {
$this->middleware->afterController($this->controller, 'test', $response);
}
- public function testAfterControllerEmptyCSP() {
+ public function testAfterControllerEmptyCSP(): void {
$response = $this->createMock(Response::class);
$emptyPolicy = new EmptyFeaturePolicy();
$response->method('getFeaturePolicy')
diff --git a/tests/lib/AppFramework/Middleware/Security/PasswordConfirmationMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/PasswordConfirmationMiddlewareTest.php
index a9f3258e8d3..148335d270f 100644
--- a/tests/lib/AppFramework/Middleware/Security/PasswordConfirmationMiddlewareTest.php
+++ b/tests/lib/AppFramework/Middleware/Security/PasswordConfirmationMiddlewareTest.php
@@ -61,7 +61,7 @@ class PasswordConfirmationMiddlewareTest extends TestCase {
);
}
- public function testNoAnnotationNorAttribute() {
+ public function testNoAnnotationNorAttribute(): void {
$this->reflector->reflect($this->controller, __FUNCTION__);
$this->session->expects($this->never())
->method($this->anything());
@@ -71,7 +71,7 @@ class PasswordConfirmationMiddlewareTest extends TestCase {
$this->middleware->beforeController($this->controller, __FUNCTION__);
}
- public function testDifferentAnnotation() {
+ public function testDifferentAnnotation(): void {
$this->reflector->reflect($this->controller, __FUNCTION__);
$this->session->expects($this->never())
->method($this->anything());
@@ -84,7 +84,7 @@ class PasswordConfirmationMiddlewareTest extends TestCase {
/**
* @dataProvider dataProvider
*/
- public function testAnnotation($backend, $lastConfirm, $currentTime, $exception) {
+ public function testAnnotation($backend, $lastConfirm, $currentTime, $exception): void {
$this->reflector->reflect($this->controller, __FUNCTION__);
$this->user->method('getBackendClassName')
@@ -119,7 +119,7 @@ class PasswordConfirmationMiddlewareTest extends TestCase {
/**
* @dataProvider dataProvider
*/
- public function testAttribute($backend, $lastConfirm, $currentTime, $exception) {
+ public function testAttribute($backend, $lastConfirm, $currentTime, $exception): void {
$this->reflector->reflect($this->controller, __FUNCTION__);
$this->user->method('getBackendClassName')
@@ -164,7 +164,7 @@ class PasswordConfirmationMiddlewareTest extends TestCase {
];
}
- public function testSSO() {
+ public function testSSO(): void {
static $sessionId = 'mySession1d';
$this->reflector->reflect($this->controller, __FUNCTION__);
diff --git a/tests/lib/AppFramework/Middleware/Security/SameSiteCookieMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/SameSiteCookieMiddlewareTest.php
index b4d7ee10f7c..0ca4a455cba 100644
--- a/tests/lib/AppFramework/Middleware/Security/SameSiteCookieMiddlewareTest.php
+++ b/tests/lib/AppFramework/Middleware/Security/SameSiteCookieMiddlewareTest.php
@@ -33,7 +33,7 @@ class SameSiteCookieMiddlewareTest extends TestCase {
$this->middleware = new SameSiteCookieMiddleware($this->request, $this->reflector);
}
- public function testBeforeControllerNoIndex() {
+ public function testBeforeControllerNoIndex(): void {
$this->request->method('getScriptName')
->willReturn('/ocs/v2.php');
@@ -41,7 +41,7 @@ class SameSiteCookieMiddlewareTest extends TestCase {
$this->addToAssertionCount(1);
}
- public function testBeforeControllerIndexHasAnnotation() {
+ public function testBeforeControllerIndexHasAnnotation(): void {
$this->request->method('getScriptName')
->willReturn('/index.php');
@@ -53,7 +53,7 @@ class SameSiteCookieMiddlewareTest extends TestCase {
$this->addToAssertionCount(1);
}
- public function testBeforeControllerIndexNoAnnotationPassingCheck() {
+ public function testBeforeControllerIndexNoAnnotationPassingCheck(): void {
$this->request->method('getScriptName')
->willReturn('/index.php');
@@ -68,7 +68,7 @@ class SameSiteCookieMiddlewareTest extends TestCase {
$this->addToAssertionCount(1);
}
- public function testBeforeControllerIndexNoAnnotationFailingCheck() {
+ public function testBeforeControllerIndexNoAnnotationFailingCheck(): void {
$this->expectException(LaxSameSiteCookieFailedException::class);
$this->request->method('getScriptName')
@@ -84,7 +84,7 @@ class SameSiteCookieMiddlewareTest extends TestCase {
$this->middleware->beforeController($this->createMock(Controller::class), 'foo');
}
- public function testAfterExceptionNoLaxCookie() {
+ public function testAfterExceptionNoLaxCookie(): void {
$ex = new SecurityException();
try {
@@ -95,7 +95,7 @@ class SameSiteCookieMiddlewareTest extends TestCase {
}
}
- public function testAfterExceptionLaxCookie() {
+ public function testAfterExceptionLaxCookie(): void {
$ex = new LaxSameSiteCookieFailedException();
$this->request->method('getRequestUri')
diff --git a/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php
index b7af6984237..07e368fd1e6 100644
--- a/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php
+++ b/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php
@@ -347,7 +347,7 @@ class SecurityMiddlewareTest extends \Test\TestCase {
/**
* @dataProvider dataNoCSRFRequiredPublicPage
*/
- public function testNoCsrfCheck(string $method) {
+ public function testNoCsrfCheck(string $method): void {
$this->request->expects($this->never())
->method('passesCSRFCheck')
->willReturn(false);
@@ -591,13 +591,13 @@ class SecurityMiddlewareTest extends \Test\TestCase {
}
- public function testAfterExceptionNotCaughtThrowsItAgain() {
+ public function testAfterExceptionNotCaughtThrowsItAgain(): void {
$ex = new \Exception();
$this->expectException(\Exception::class);
$this->middleware->afterException($this->controller, 'test', $ex);
}
- public function testAfterExceptionReturnsRedirectForNotLoggedInUser() {
+ public function testAfterExceptionReturnsRedirectForNotLoggedInUser(): void {
$this->request = new Request(
[
'server' =>
@@ -632,7 +632,7 @@ class SecurityMiddlewareTest extends \Test\TestCase {
$this->assertEquals($expected, $response);
}
- public function testAfterExceptionRedirectsToWebRootAfterStrictCookieFail() {
+ public function testAfterExceptionRedirectsToWebRootAfterStrictCookieFail(): void {
$this->request = new Request(
[
'server' => [
@@ -677,7 +677,7 @@ class SecurityMiddlewareTest extends \Test\TestCase {
* @dataProvider exceptionProvider
* @param SecurityException $exception
*/
- public function testAfterExceptionReturnsTemplateResponse(SecurityException $exception) {
+ public function testAfterExceptionReturnsTemplateResponse(SecurityException $exception): void {
$this->request = new Request(
[
'server' =>
@@ -703,7 +703,7 @@ class SecurityMiddlewareTest extends \Test\TestCase {
$this->assertEquals($expected, $response);
}
- public function testAfterAjaxExceptionReturnsJSONError() {
+ public function testAfterAjaxExceptionReturnsJSONError(): void {
$response = $this->middleware->afterException($this->controller, 'test',
$this->secAjaxException);
diff --git a/tests/lib/AppFramework/Routing/RoutingTest.php b/tests/lib/AppFramework/Routing/RoutingTest.php
index 00b586e6cc4..32b57e7bf21 100644
--- a/tests/lib/AppFramework/Routing/RoutingTest.php
+++ b/tests/lib/AppFramework/Routing/RoutingTest.php
@@ -20,7 +20,7 @@ use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
class RoutingTest extends \Test\TestCase {
- public function testSimpleRoute() {
+ public function testSimpleRoute(): void {
$routes = ['routes' => [
['name' => 'folders#open', 'url' => '/folders/{folderId}/open', 'verb' => 'GET']
]];
@@ -28,7 +28,7 @@ class RoutingTest extends \Test\TestCase {
$this->assertSimpleRoute($routes, 'folders.open', 'GET', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open');
}
- public function testSimpleRouteWithUnderScoreNames() {
+ public function testSimpleRouteWithUnderScoreNames(): void {
$routes = ['routes' => [
['name' => 'admin_folders#open_current', 'url' => '/folders/{folderId}/open', 'verb' => 'delete', 'root' => '']
]];
@@ -36,7 +36,7 @@ class RoutingTest extends \Test\TestCase {
$this->assertSimpleRoute($routes, 'admin_folders.open_current', 'DELETE', '/folders/{folderId}/open', 'AdminFoldersController', 'openCurrent', [], [], '', true);
}
- public function testSimpleOCSRoute() {
+ public function testSimpleOCSRoute(): void {
$routes = ['ocs' => [
['name' => 'folders#open', 'url' => '/folders/{folderId}/open', 'verb' => 'GET']
]
@@ -45,7 +45,7 @@ class RoutingTest extends \Test\TestCase {
$this->assertSimpleOCSRoute($routes, 'folders.open', 'GET', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open');
}
- public function testSimpleRouteWithMissingVerb() {
+ public function testSimpleRouteWithMissingVerb(): void {
$routes = ['routes' => [
['name' => 'folders#open', 'url' => '/folders/{folderId}/open']
]];
@@ -53,7 +53,7 @@ class RoutingTest extends \Test\TestCase {
$this->assertSimpleRoute($routes, 'folders.open', 'GET', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open');
}
- public function testSimpleOCSRouteWithMissingVerb() {
+ public function testSimpleOCSRouteWithMissingVerb(): void {
$routes = ['ocs' => [
['name' => 'folders#open', 'url' => '/folders/{folderId}/open']
]
@@ -62,7 +62,7 @@ class RoutingTest extends \Test\TestCase {
$this->assertSimpleOCSRoute($routes, 'folders.open', 'GET', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open');
}
- public function testSimpleRouteWithLowercaseVerb() {
+ public function testSimpleRouteWithLowercaseVerb(): void {
$routes = ['routes' => [
['name' => 'folders#open', 'url' => '/folders/{folderId}/open', 'verb' => 'delete']
]];
@@ -70,7 +70,7 @@ class RoutingTest extends \Test\TestCase {
$this->assertSimpleRoute($routes, 'folders.open', 'DELETE', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open');
}
- public function testSimpleOCSRouteWithLowercaseVerb() {
+ public function testSimpleOCSRouteWithLowercaseVerb(): void {
$routes = ['ocs' => [
['name' => 'folders#open', 'url' => '/folders/{folderId}/open', 'verb' => 'delete']
]
@@ -79,7 +79,7 @@ class RoutingTest extends \Test\TestCase {
$this->assertSimpleOCSRoute($routes, 'folders.open', 'DELETE', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open');
}
- public function testSimpleRouteWithRequirements() {
+ public function testSimpleRouteWithRequirements(): void {
$routes = ['routes' => [
['name' => 'folders#open', 'url' => '/folders/{folderId}/open', 'verb' => 'delete', 'requirements' => ['something']]
]];
@@ -87,7 +87,7 @@ class RoutingTest extends \Test\TestCase {
$this->assertSimpleRoute($routes, 'folders.open', 'DELETE', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open', ['something']);
}
- public function testSimpleOCSRouteWithRequirements() {
+ public function testSimpleOCSRouteWithRequirements(): void {
$routes = ['ocs' => [
['name' => 'folders#open', 'url' => '/folders/{folderId}/open', 'verb' => 'delete', 'requirements' => ['something']]
]
@@ -96,7 +96,7 @@ class RoutingTest extends \Test\TestCase {
$this->assertSimpleOCSRoute($routes, 'folders.open', 'DELETE', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open', ['something']);
}
- public function testSimpleRouteWithDefaults() {
+ public function testSimpleRouteWithDefaults(): void {
$routes = ['routes' => [
['name' => 'folders#open', 'url' => '/folders/{folderId}/open', 'verb' => 'delete', [], 'defaults' => ['param' => 'foobar']]
]];
@@ -105,7 +105,7 @@ class RoutingTest extends \Test\TestCase {
}
- public function testSimpleOCSRouteWithDefaults() {
+ public function testSimpleOCSRouteWithDefaults(): void {
$routes = ['ocs' => [
['name' => 'folders#open', 'url' => '/folders/{folderId}/open', 'verb' => 'delete', 'defaults' => ['param' => 'foobar']]
]
@@ -114,7 +114,7 @@ class RoutingTest extends \Test\TestCase {
$this->assertSimpleOCSRoute($routes, 'folders.open', 'DELETE', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open', [], ['param' => 'foobar']);
}
- public function testSimpleRouteWithPostfix() {
+ public function testSimpleRouteWithPostfix(): void {
$routes = ['routes' => [
['name' => 'folders#open', 'url' => '/folders/{folderId}/open', 'verb' => 'delete', 'postfix' => '_something']
]];
@@ -122,7 +122,7 @@ class RoutingTest extends \Test\TestCase {
$this->assertSimpleRoute($routes, 'folders.open', 'DELETE', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open', [], [], '_something');
}
- public function testSimpleOCSRouteWithPostfix() {
+ public function testSimpleOCSRouteWithPostfix(): void {
$routes = ['ocs' => [
['name' => 'folders#open', 'url' => '/folders/{folderId}/open', 'verb' => 'delete', 'postfix' => '_something']
]
@@ -132,7 +132,7 @@ class RoutingTest extends \Test\TestCase {
}
- public function testSimpleRouteWithBrokenName() {
+ public function testSimpleRouteWithBrokenName(): void {
$this->expectException(\UnexpectedValueException::class);
$routes = ['routes' => [
@@ -160,7 +160,7 @@ class RoutingTest extends \Test\TestCase {
}
- public function testSimpleOCSRouteWithBrokenName() {
+ public function testSimpleOCSRouteWithBrokenName(): void {
$this->expectException(\UnexpectedValueException::class);
$routes = ['ocs' => [
@@ -187,7 +187,7 @@ class RoutingTest extends \Test\TestCase {
$config->register();
}
- public function testSimpleOCSRouteWithUnderScoreNames() {
+ public function testSimpleOCSRouteWithUnderScoreNames(): void {
$routes = ['ocs' => [
['name' => 'admin_folders#open_current', 'url' => '/folders/{folderId}/open', 'verb' => 'delete']
]];
@@ -195,31 +195,31 @@ class RoutingTest extends \Test\TestCase {
$this->assertSimpleOCSRoute($routes, 'admin_folders.open_current', 'DELETE', '/apps/app1/folders/{folderId}/open', 'AdminFoldersController', 'openCurrent');
}
- public function testOCSResource() {
+ public function testOCSResource(): void {
$routes = ['ocs-resources' => ['account' => ['url' => '/accounts']]];
$this->assertOCSResource($routes, 'account', '/apps/app1/accounts', 'AccountController', 'id');
}
- public function testOCSResourceWithUnderScoreName() {
+ 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() {
+ 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() {
+ public function testResource(): void {
$routes = ['resources' => ['account' => ['url' => '/accounts']]];
$this->assertResource($routes, 'account', '/apps/app1/accounts', 'AccountController', 'id');
}
- public function testResourceWithUnderScoreName() {
+ public function testResourceWithUnderScoreName(): void {
$routes = ['resources' => ['admin_accounts' => ['url' => '/admin/accounts']]];
$this->assertResource($routes, 'admin_accounts', '/apps/app1/admin/accounts', 'AdminAccountsController', 'id');
diff --git a/tests/lib/AppFramework/Utility/ControllerMethodReflectorTest.php b/tests/lib/AppFramework/Utility/ControllerMethodReflectorTest.php
index db58416859d..ff0d0972950 100644
--- a/tests/lib/AppFramework/Utility/ControllerMethodReflectorTest.php
+++ b/tests/lib/AppFramework/Utility/ControllerMethodReflectorTest.php
@@ -56,7 +56,7 @@ class ControllerMethodReflectorTest extends \Test\TestCase {
/**
* @Annotation
*/
- public function testReadAnnotation() {
+ public function testReadAnnotation(): void {
$reader = new ControllerMethodReflector();
$reader->reflect(
\Test\AppFramework\Utility\ControllerMethodReflectorTest::class,
@@ -69,10 +69,10 @@ class ControllerMethodReflectorTest extends \Test\TestCase {
/**
* @Annotation(parameter=value)
*/
- public function testGetAnnotationParameterSingle() {
+ public function testGetAnnotationParameterSingle(): void {
$reader = new ControllerMethodReflector();
$reader->reflect(
- __CLASS__,
+ self::class,
__FUNCTION__
);
@@ -82,10 +82,10 @@ class ControllerMethodReflectorTest extends \Test\TestCase {
/**
* @Annotation(parameter1=value1, parameter2=value2,parameter3=value3)
*/
- public function testGetAnnotationParameterMultiple() {
+ public function testGetAnnotationParameterMultiple(): void {
$reader = new ControllerMethodReflector();
$reader->reflect(
- __CLASS__,
+ self::class,
__FUNCTION__
);
@@ -98,7 +98,7 @@ class ControllerMethodReflectorTest extends \Test\TestCase {
* @Annotation
* @param test
*/
- public function testReadAnnotationNoLowercase() {
+ public function testReadAnnotationNoLowercase(): void {
$reader = new ControllerMethodReflector();
$reader->reflect(
\Test\AppFramework\Utility\ControllerMethodReflectorTest::class,
@@ -114,7 +114,7 @@ class ControllerMethodReflectorTest extends \Test\TestCase {
* @Annotation
* @param int $test
*/
- public function testReadTypeIntAnnotations() {
+ public function testReadTypeIntAnnotations(): void {
$reader = new ControllerMethodReflector();
$reader->reflect(
\Test\AppFramework\Utility\ControllerMethodReflectorTest::class,
@@ -135,7 +135,7 @@ class ControllerMethodReflectorTest extends \Test\TestCase {
/**
* @requires PHP 7
*/
- public function testReadTypeIntAnnotationsScalarTypes() {
+ public function testReadTypeIntAnnotationsScalarTypes(): void {
$reader = new ControllerMethodReflector();
$reader->reflect(
\Test\AppFramework\Utility\ControllerMethodReflectorTest::class,
@@ -153,7 +153,7 @@ class ControllerMethodReflectorTest extends \Test\TestCase {
* @Annotation
* @param double $test something special
*/
- public function testReadTypeDoubleAnnotations() {
+ public function testReadTypeDoubleAnnotations(): void {
$reader = new ControllerMethodReflector();
$reader->reflect(
\Test\AppFramework\Utility\ControllerMethodReflectorTest::class,
@@ -167,7 +167,7 @@ class ControllerMethodReflectorTest extends \Test\TestCase {
* @Annotation
* @param string $foo
*/
- public function testReadTypeWhitespaceAnnotations() {
+ public function testReadTypeWhitespaceAnnotations(): void {
$reader = new ControllerMethodReflector();
$reader->reflect(
\Test\AppFramework\Utility\ControllerMethodReflectorTest::class,
@@ -180,7 +180,7 @@ class ControllerMethodReflectorTest extends \Test\TestCase {
public function arguments($arg, $arg2 = 'hi') {
}
- public function testReflectParameters() {
+ public function testReflectParameters(): void {
$reader = new ControllerMethodReflector();
$reader->reflect(
\Test\AppFramework\Utility\ControllerMethodReflectorTest::class,
@@ -193,7 +193,7 @@ class ControllerMethodReflectorTest extends \Test\TestCase {
public function arguments2($arg) {
}
- public function testReflectParameters2() {
+ public function testReflectParameters2(): void {
$reader = new ControllerMethodReflector();
$reader->reflect(
\Test\AppFramework\Utility\ControllerMethodReflectorTest::class,
@@ -204,7 +204,7 @@ class ControllerMethodReflectorTest extends \Test\TestCase {
}
- public function testInheritance() {
+ public function testInheritance(): void {
$reader = new ControllerMethodReflector();
$reader->reflect(\Test\AppFramework\Utility\EndController::class, 'test');
@@ -212,7 +212,7 @@ class ControllerMethodReflectorTest extends \Test\TestCase {
}
- public function testInheritanceOverride() {
+ public function testInheritanceOverride(): void {
$reader = new ControllerMethodReflector();
$reader->reflect(\Test\AppFramework\Utility\EndController::class, 'test2');
@@ -221,14 +221,14 @@ class ControllerMethodReflectorTest extends \Test\TestCase {
}
- public function testInheritanceOverrideNoDocblock() {
+ public function testInheritanceOverrideNoDocblock(): void {
$reader = new ControllerMethodReflector();
$reader->reflect(\Test\AppFramework\Utility\EndController::class, 'test3');
$this->assertFalse($reader->hasAnnotation('Annotation'));
}
- public function testRangeDetection() {
+ public function testRangeDetection(): void {
$reader = new ControllerMethodReflector();
$reader->reflect(\Test\AppFramework\Utility\EndController::class, 'test4');
diff --git a/tests/lib/AppFramework/Utility/SimpleContainerTest.php b/tests/lib/AppFramework/Utility/SimpleContainerTest.php
index b389282e660..34fe8755b17 100644
--- a/tests/lib/AppFramework/Utility/SimpleContainerTest.php
+++ b/tests/lib/AppFramework/Utility/SimpleContainerTest.php
@@ -1,255 +1,255 @@
-<?php
-
-declare(strict_types=1);
-
-/**
- * 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\Utility;
-
-use OC\AppFramework\Utility\SimpleContainer;
-use Psr\Container\NotFoundExceptionInterface;
-
-interface TestInterface {
-}
-
-class ClassEmptyConstructor implements IInterfaceConstructor {
-}
-
-class ClassSimpleConstructor implements IInterfaceConstructor {
- public $test;
- public function __construct($test) {
- $this->test = $test;
- }
-}
-
-class ClassComplexConstructor {
- public $class;
- public $test;
- public function __construct(ClassSimpleConstructor $class, $test) {
- $this->class = $class;
- $this->test = $test;
- }
-}
-
-class ClassNullableUntypedConstructorArg {
- public function __construct($class) {
- }
-}
-class ClassNullableTypedConstructorArg {
- public $class;
- public function __construct(?\Some\Class $class) {
- $this->class = $class;
- }
-}
-
-interface IInterfaceConstructor {
-}
-class ClassInterfaceConstructor {
- public $class;
- public $test;
- public function __construct(IInterfaceConstructor $class, $test) {
- $this->class = $class;
- $this->test = $test;
- }
-}
-
-
-class SimpleContainerTest extends \Test\TestCase {
- private $container;
-
- protected function setUp(): void {
- $this->container = new SimpleContainer();
- }
-
-
-
- public function testRegister() {
- $this->container->registerParameter('test', 'abc');
- $this->assertEquals('abc', $this->container->query('test'));
- }
-
-
- /**
- * Test querying a class that is not registered without autoload enabled
- */
- public function testNothingRegistered() {
- try {
- $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(NotFoundExceptionInterface::class, $exception);
- }
- }
-
-
- /**
- * Test querying a class that is not registered with autoload enabled
- */
- public function testNothingRegistered_autoload() {
- try {
- $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(NotFoundExceptionInterface::class, $exception);
- }
- }
-
-
-
- public function testNotAClass() {
- $this->expectException(\OCP\AppFramework\QueryException::class);
-
- $this->container->query(\Test\AppFramework\Utility\TestInterface::class);
- }
-
-
- public function testNoConstructorClass() {
- $object = $this->container->query(\Test\AppFramework\Utility\ClassEmptyConstructor::class);
- $this->assertTrue($object instanceof ClassEmptyConstructor);
- }
-
-
- public function testInstancesOnlyOnce() {
- $object = $this->container->query(\Test\AppFramework\Utility\ClassEmptyConstructor::class);
- $object2 = $this->container->query(\Test\AppFramework\Utility\ClassEmptyConstructor::class);
- $this->assertSame($object, $object2);
- }
-
- public function testConstructorSimple() {
- $this->container->registerParameter('test', 'abc');
- $object = $this->container->query(
- \Test\AppFramework\Utility\ClassSimpleConstructor::class
- );
- $this->assertTrue($object instanceof ClassSimpleConstructor);
- $this->assertEquals('abc', $object->test);
- }
-
-
- public function testConstructorComplex() {
- $this->container->registerParameter('test', 'abc');
- $object = $this->container->query(
- \Test\AppFramework\Utility\ClassComplexConstructor::class
- );
- $this->assertTrue($object instanceof ClassComplexConstructor);
- $this->assertEquals('abc', $object->class->test);
- $this->assertEquals('abc', $object->test);
- }
-
-
- public function testConstructorComplexInterface() {
- $this->container->registerParameter('test', 'abc');
- $this->container->registerService(
- \Test\AppFramework\Utility\IInterfaceConstructor::class, function ($c) {
- return $c->query(\Test\AppFramework\Utility\ClassSimpleConstructor::class);
- });
- $object = $this->container->query(
- \Test\AppFramework\Utility\ClassInterfaceConstructor::class
- );
- $this->assertTrue($object instanceof ClassInterfaceConstructor);
- $this->assertEquals('abc', $object->class->test);
- $this->assertEquals('abc', $object->test);
- }
-
-
- public function testOverrideService() {
- $this->container->registerService(
- \Test\AppFramework\Utility\IInterfaceConstructor::class, function ($c) {
- return $c->query(\Test\AppFramework\Utility\ClassSimpleConstructor::class);
- });
- $this->container->registerService(
- \Test\AppFramework\Utility\IInterfaceConstructor::class, function ($c) {
- return $c->query(\Test\AppFramework\Utility\ClassEmptyConstructor::class);
- });
- $object = $this->container->query(
- \Test\AppFramework\Utility\IInterfaceConstructor::class
- );
- $this->assertTrue($object instanceof ClassEmptyConstructor);
- }
-
- public function testRegisterAliasParamter() {
- $this->container->registerParameter('test', 'abc');
- $this->container->registerAlias('test1', 'test');
- $this->assertEquals('abc', $this->container->query('test1'));
- }
-
- public function testRegisterAliasService() {
- $this->container->registerService('test', function () {
- return new \StdClass;
- }, true);
- $this->container->registerAlias('test1', 'test');
- $this->assertSame(
- $this->container->query('test'), $this->container->query('test'));
- $this->assertSame(
- $this->container->query('test1'), $this->container->query('test1'));
- $this->assertSame(
- $this->container->query('test'), $this->container->query('test1'));
- }
-
- public function sanitizeNameProvider() {
- return [
- ['ABC\\Foo', 'ABC\\Foo'],
- ['\\ABC\\Foo', '\\ABC\\Foo'],
- ['\\ABC\\Foo', 'ABC\\Foo'],
- ['ABC\\Foo', '\\ABC\\Foo'],
- ];
- }
-
- /**
- * @dataProvider sanitizeNameProvider
- */
- public function testSanitizeName($register, $query) {
- $this->container->registerService($register, function () {
- return 'abc';
- });
- $this->assertEquals('abc', $this->container->query($query));
- }
-
-
- public function testConstructorComplexNoTestParameterFound() {
- $this->expectException(\OCP\AppFramework\QueryException::class);
-
- $object = $this->container->query(
- \Test\AppFramework\Utility\ClassComplexConstructor::class
- );
- }
-
- public function testRegisterFactory() {
- $this->container->registerService('test', function () {
- return new \StdClass();
- }, false);
- $this->assertNotSame(
- $this->container->query('test'), $this->container->query('test'));
- }
-
- public function testRegisterAliasFactory() {
- $this->container->registerService('test', function () {
- return new \StdClass();
- }, false);
- $this->container->registerAlias('test1', 'test');
- $this->assertNotSame(
- $this->container->query('test'), $this->container->query('test'));
- $this->assertNotSame(
- $this->container->query('test1'), $this->container->query('test1'));
- $this->assertNotSame(
- $this->container->query('test'), $this->container->query('test1'));
- }
-
- public function testQueryUntypedNullable(): void {
- $this->expectException(\OCP\AppFramework\QueryException::class);
-
- $this->container->query(ClassNullableUntypedConstructorArg::class);
- }
-
- public function testQueryTypedNullable(): void {
- /** @var ClassNullableTypedConstructorArg $service */
- $service = $this->container->query(ClassNullableTypedConstructorArg::class);
-
- self::assertNull($service->class);
- }
-}
+<?php
+
+declare(strict_types=1);
+
+/**
+ * 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\Utility;
+
+use OC\AppFramework\Utility\SimpleContainer;
+use Psr\Container\NotFoundExceptionInterface;
+
+interface TestInterface {
+}
+
+class ClassEmptyConstructor implements IInterfaceConstructor {
+}
+
+class ClassSimpleConstructor implements IInterfaceConstructor {
+ public $test;
+ public function __construct($test) {
+ $this->test = $test;
+ }
+}
+
+class ClassComplexConstructor {
+ public $class;
+ public $test;
+ public function __construct(ClassSimpleConstructor $class, $test) {
+ $this->class = $class;
+ $this->test = $test;
+ }
+}
+
+class ClassNullableUntypedConstructorArg {
+ public function __construct($class) {
+ }
+}
+class ClassNullableTypedConstructorArg {
+ public $class;
+ public function __construct(?\Some\Class $class) {
+ $this->class = $class;
+ }
+}
+
+interface IInterfaceConstructor {
+}
+class ClassInterfaceConstructor {
+ public $class;
+ public $test;
+ public function __construct(IInterfaceConstructor $class, $test) {
+ $this->class = $class;
+ $this->test = $test;
+ }
+}
+
+
+class SimpleContainerTest extends \Test\TestCase {
+ private $container;
+
+ protected function setUp(): void {
+ $this->container = new SimpleContainer();
+ }
+
+
+
+ public function testRegister(): void {
+ $this->container->registerParameter('test', 'abc');
+ $this->assertEquals('abc', $this->container->query('test'));
+ }
+
+
+ /**
+ * Test querying a class that is not registered without autoload enabled
+ */
+ public function testNothingRegistered(): void {
+ try {
+ $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(NotFoundExceptionInterface::class, $exception);
+ }
+ }
+
+
+ /**
+ * Test querying a class that is not registered with autoload enabled
+ */
+ public function testNothingRegistered_autoload(): void {
+ try {
+ $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(NotFoundExceptionInterface::class, $exception);
+ }
+ }
+
+
+
+ public function testNotAClass(): void {
+ $this->expectException(\OCP\AppFramework\QueryException::class);
+
+ $this->container->query(\Test\AppFramework\Utility\TestInterface::class);
+ }
+
+
+ public function testNoConstructorClass(): void {
+ $object = $this->container->query(\Test\AppFramework\Utility\ClassEmptyConstructor::class);
+ $this->assertTrue($object instanceof ClassEmptyConstructor);
+ }
+
+
+ public function testInstancesOnlyOnce(): void {
+ $object = $this->container->query(\Test\AppFramework\Utility\ClassEmptyConstructor::class);
+ $object2 = $this->container->query(\Test\AppFramework\Utility\ClassEmptyConstructor::class);
+ $this->assertSame($object, $object2);
+ }
+
+ public function testConstructorSimple(): void {
+ $this->container->registerParameter('test', 'abc');
+ $object = $this->container->query(
+ \Test\AppFramework\Utility\ClassSimpleConstructor::class
+ );
+ $this->assertTrue($object instanceof ClassSimpleConstructor);
+ $this->assertEquals('abc', $object->test);
+ }
+
+
+ public function testConstructorComplex(): void {
+ $this->container->registerParameter('test', 'abc');
+ $object = $this->container->query(
+ \Test\AppFramework\Utility\ClassComplexConstructor::class
+ );
+ $this->assertTrue($object instanceof ClassComplexConstructor);
+ $this->assertEquals('abc', $object->class->test);
+ $this->assertEquals('abc', $object->test);
+ }
+
+
+ public function testConstructorComplexInterface(): void {
+ $this->container->registerParameter('test', 'abc');
+ $this->container->registerService(
+ \Test\AppFramework\Utility\IInterfaceConstructor::class, function ($c) {
+ return $c->query(\Test\AppFramework\Utility\ClassSimpleConstructor::class);
+ });
+ $object = $this->container->query(
+ \Test\AppFramework\Utility\ClassInterfaceConstructor::class
+ );
+ $this->assertTrue($object instanceof ClassInterfaceConstructor);
+ $this->assertEquals('abc', $object->class->test);
+ $this->assertEquals('abc', $object->test);
+ }
+
+
+ public function testOverrideService(): void {
+ $this->container->registerService(
+ \Test\AppFramework\Utility\IInterfaceConstructor::class, function ($c) {
+ return $c->query(\Test\AppFramework\Utility\ClassSimpleConstructor::class);
+ });
+ $this->container->registerService(
+ \Test\AppFramework\Utility\IInterfaceConstructor::class, function ($c) {
+ return $c->query(\Test\AppFramework\Utility\ClassEmptyConstructor::class);
+ });
+ $object = $this->container->query(
+ \Test\AppFramework\Utility\IInterfaceConstructor::class
+ );
+ $this->assertTrue($object instanceof ClassEmptyConstructor);
+ }
+
+ public function testRegisterAliasParamter(): void {
+ $this->container->registerParameter('test', 'abc');
+ $this->container->registerAlias('test1', 'test');
+ $this->assertEquals('abc', $this->container->query('test1'));
+ }
+
+ public function testRegisterAliasService(): void {
+ $this->container->registerService('test', function () {
+ return new \StdClass;
+ }, true);
+ $this->container->registerAlias('test1', 'test');
+ $this->assertSame(
+ $this->container->query('test'), $this->container->query('test'));
+ $this->assertSame(
+ $this->container->query('test1'), $this->container->query('test1'));
+ $this->assertSame(
+ $this->container->query('test'), $this->container->query('test1'));
+ }
+
+ public function sanitizeNameProvider() {
+ return [
+ ['ABC\\Foo', 'ABC\\Foo'],
+ ['\\ABC\\Foo', '\\ABC\\Foo'],
+ ['\\ABC\\Foo', 'ABC\\Foo'],
+ ['ABC\\Foo', '\\ABC\\Foo'],
+ ];
+ }
+
+ /**
+ * @dataProvider sanitizeNameProvider
+ */
+ public function testSanitizeName($register, $query): void {
+ $this->container->registerService($register, function () {
+ return 'abc';
+ });
+ $this->assertEquals('abc', $this->container->query($query));
+ }
+
+
+ public function testConstructorComplexNoTestParameterFound(): void {
+ $this->expectException(\OCP\AppFramework\QueryException::class);
+
+ $object = $this->container->query(
+ \Test\AppFramework\Utility\ClassComplexConstructor::class
+ );
+ }
+
+ public function testRegisterFactory(): void {
+ $this->container->registerService('test', function () {
+ return new \StdClass();
+ }, false);
+ $this->assertNotSame(
+ $this->container->query('test'), $this->container->query('test'));
+ }
+
+ public function testRegisterAliasFactory(): void {
+ $this->container->registerService('test', function () {
+ return new \StdClass();
+ }, false);
+ $this->container->registerAlias('test1', 'test');
+ $this->assertNotSame(
+ $this->container->query('test'), $this->container->query('test'));
+ $this->assertNotSame(
+ $this->container->query('test1'), $this->container->query('test1'));
+ $this->assertNotSame(
+ $this->container->query('test'), $this->container->query('test1'));
+ }
+
+ public function testQueryUntypedNullable(): void {
+ $this->expectException(\OCP\AppFramework\QueryException::class);
+
+ $this->container->query(ClassNullableUntypedConstructorArg::class);
+ }
+
+ public function testQueryTypedNullable(): void {
+ /** @var ClassNullableTypedConstructorArg $service */
+ $service = $this->container->query(ClassNullableTypedConstructorArg::class);
+
+ self::assertNull($service->class);
+ }
+}
diff --git a/tests/lib/AppTest.php b/tests/lib/AppTest.php
index 4364b7bbc2f..e6759170fb1 100644
--- a/tests/lib/AppTest.php
+++ b/tests/lib/AppTest.php
@@ -308,14 +308,14 @@ class AppTest extends \Test\TestCase {
/**
* @dataProvider appVersionsProvider
*/
- public function testIsAppCompatible($ocVersion, $appInfo, $expectedResult) {
+ public function testIsAppCompatible($ocVersion, $appInfo, $expectedResult): void {
$this->assertEquals($expectedResult, \OC_App::isAppCompatible($ocVersion, $appInfo));
}
/**
* Tests that the app order is correct
*/
- public function testGetEnabledAppsIsSorted() {
+ public function testGetEnabledAppsIsSorted(): void {
$apps = \OC_App::getEnabledApps();
// copy array
$sortedApps = $apps;
@@ -457,7 +457,7 @@ class AppTest extends \Test\TestCase {
*
* @dataProvider appConfigValuesProvider
*/
- public function testEnabledApps($user, $expectedApps, $forceAll) {
+ public function testEnabledApps($user, $expectedApps, $forceAll): void {
$userManager = \OC::$server->getUserManager();
$groupManager = \OC::$server->getGroupManager();
$user1 = $userManager->createUser(self::TEST_USER1, 'NotAnEasyPassword123456+');
@@ -506,7 +506,7 @@ class AppTest extends \Test\TestCase {
* Test isEnabledApps() with cache, not re-reading the list of
* enabled apps more than once when a user is set.
*/
- public function testEnabledAppsCache() {
+ public function testEnabledAppsCache(): void {
$userManager = \OC::$server->getUserManager();
$user1 = $userManager->createUser(self::TEST_USER1, 'NotAnEasyPassword123456+');
@@ -615,18 +615,18 @@ class AppTest extends \Test\TestCase {
* @param array $data
* @param array $expected
*/
- public function testParseAppInfo(array $data, array $expected) {
+ public function testParseAppInfo(array $data, array $expected): void {
$this->assertSame($expected, \OC_App::parseAppInfo($data));
}
- public function testParseAppInfoL10N() {
+ public function testParseAppInfoL10N(): void {
$parser = new InfoParser();
$data = $parser->parse(\OC::$SERVERROOT. '/tests/data/app/description-multi-lang.xml');
$this->assertEquals('English', \OC_App::parseAppInfo($data, 'en')['description']);
$this->assertEquals('German', \OC_App::parseAppInfo($data, 'de')['description']);
}
- public function testParseAppInfoL10NSingleLanguage() {
+ public function testParseAppInfoL10NSingleLanguage(): void {
$parser = new InfoParser();
$data = $parser->parse(\OC::$SERVERROOT. '/tests/data/app/description-single-lang.xml');
$this->assertEquals('English', \OC_App::parseAppInfo($data, 'en')['description']);
diff --git a/tests/lib/Archive/TestBase.php b/tests/lib/Archive/TestBase.php
index 6475b49e549..3f2d8c9561e 100644
--- a/tests/lib/Archive/TestBase.php
+++ b/tests/lib/Archive/TestBase.php
@@ -24,7 +24,7 @@ abstract class TestBase extends \Test\TestCase {
*/
abstract protected function getNew();
- public function testGetFiles() {
+ public function testGetFiles(): void {
$this->instance = $this->getExisting();
$allFiles = $this->instance->getFiles();
$expected = ['lorem.txt','logo-wide.png','dir/', 'dir/lorem.txt'];
@@ -50,7 +50,7 @@ abstract class TestBase extends \Test\TestCase {
}
}
- public function testContent() {
+ public function testContent(): void {
$this->instance = $this->getExisting();
$dir = \OC::$SERVERROOT.'/tests/data';
$textFile = $dir.'/lorem.txt';
@@ -61,7 +61,7 @@ abstract class TestBase extends \Test\TestCase {
$this->assertEquals(file_get_contents($textFile), file_get_contents($tmpFile));
}
- public function testWrite() {
+ public function testWrite(): void {
$dir = \OC::$SERVERROOT.'/tests/data';
$textFile = $dir.'/lorem.txt';
$this->instance = $this->getNew();
@@ -76,7 +76,7 @@ abstract class TestBase extends \Test\TestCase {
$this->assertEquals('foobar', $this->instance->getFile('lorem.txt'));
}
- public function testReadStream() {
+ public function testReadStream(): void {
$dir = \OC::$SERVERROOT.'/tests/data';
$this->instance = $this->getExisting();
$fh = $this->instance->getStream('lorem.txt', 'r');
@@ -85,7 +85,7 @@ abstract class TestBase extends \Test\TestCase {
fclose($fh);
$this->assertEquals(file_get_contents($dir.'/lorem.txt'), $content);
}
- public function testWriteStream() {
+ public function testWriteStream(): void {
$dir = \OC::$SERVERROOT.'/tests/data';
$this->instance = $this->getNew();
$fh = $this->instance->getStream('lorem.txt', 'w');
@@ -96,7 +96,7 @@ abstract class TestBase extends \Test\TestCase {
$this->assertTrue($this->instance->fileExists('lorem.txt'));
$this->assertEquals(file_get_contents($dir.'/lorem.txt'), $this->instance->getFile('lorem.txt'));
}
- public function testFolder() {
+ public function testFolder(): void {
$this->instance = $this->getNew();
$this->assertFalse($this->instance->fileExists('/test'));
$this->assertFalse($this->instance->fileExists('/test/'));
@@ -107,7 +107,7 @@ abstract class TestBase extends \Test\TestCase {
$this->assertFalse($this->instance->fileExists('/test'));
$this->assertFalse($this->instance->fileExists('/test/'));
}
- public function testExtract() {
+ public function testExtract(): void {
$dir = \OC::$SERVERROOT.'/tests/data';
$this->instance = $this->getExisting();
$tmpDir = \OC::$server->getTempManager()->getTemporaryFolder();
@@ -118,7 +118,7 @@ abstract class TestBase extends \Test\TestCase {
$this->assertEquals(file_get_contents($dir.'/lorem.txt'), file_get_contents($tmpDir.'lorem.txt'));
\OCP\Files::rmdirr($tmpDir);
}
- public function testMoveRemove() {
+ public function testMoveRemove(): void {
$dir = \OC::$SERVERROOT.'/tests/data';
$textFile = $dir.'/lorem.txt';
$this->instance = $this->getNew();
@@ -131,7 +131,7 @@ abstract class TestBase extends \Test\TestCase {
$this->instance->remove('target.txt');
$this->assertFalse($this->instance->fileExists('target.txt'));
}
- public function testRecursive() {
+ public function testRecursive(): void {
$dir = \OC::$SERVERROOT.'/tests/data';
$this->instance = $this->getNew();
$this->instance->addRecursive('/dir', $dir);
diff --git a/tests/lib/Authentication/Events/RemoteWipeFinishedTest.php b/tests/lib/Authentication/Events/RemoteWipeFinishedTest.php
index c8fd688d154..c89b1e4108f 100644
--- a/tests/lib/Authentication/Events/RemoteWipeFinishedTest.php
+++ b/tests/lib/Authentication/Events/RemoteWipeFinishedTest.php
@@ -14,7 +14,7 @@ use OC\Authentication\Token\IToken;
use Test\TestCase;
class RemoteWipeFinishedTest extends TestCase {
- public function testGetToken() {
+ public function testGetToken(): void {
$token = $this->createMock(IToken::class);
$event = new RemoteWipeFinished($token);
diff --git a/tests/lib/Authentication/Events/RemoteWipeStartedTest.php b/tests/lib/Authentication/Events/RemoteWipeStartedTest.php
index 27bd10dea05..fc297f7c087 100644
--- a/tests/lib/Authentication/Events/RemoteWipeStartedTest.php
+++ b/tests/lib/Authentication/Events/RemoteWipeStartedTest.php
@@ -14,7 +14,7 @@ use OC\Authentication\Token\IToken;
use Test\TestCase;
class RemoteWipeStartedTest extends TestCase {
- public function testGetToken() {
+ public function testGetToken(): void {
$token = $this->createMock(IToken::class);
$event = new RemoteWipeStarted($token);
diff --git a/tests/lib/Authentication/Listeners/RemoteWipeActivityListenerTest.php b/tests/lib/Authentication/Listeners/RemoteWipeActivityListenerTest.php
index d1cbaae22fb..e2f957ab69a 100644
--- a/tests/lib/Authentication/Listeners/RemoteWipeActivityListenerTest.php
+++ b/tests/lib/Authentication/Listeners/RemoteWipeActivityListenerTest.php
@@ -43,7 +43,7 @@ class RemoteWipeActivityListenerTest extends TestCase {
);
}
- public function testHandleUnrelated() {
+ public function testHandleUnrelated(): void {
$event = new Event();
$this->listener->handle($event);
@@ -51,7 +51,7 @@ class RemoteWipeActivityListenerTest extends TestCase {
$this->addToAssertionCount(1);
}
- public function testHandleRemoteWipeStarted() {
+ public function testHandleRemoteWipeStarted(): void {
/** @var IToken|MockObject $token */
$token = $this->createMock(IToken::class);
$event = new RemoteWipeStarted($token);
@@ -87,7 +87,7 @@ class RemoteWipeActivityListenerTest extends TestCase {
$this->listener->handle($event);
}
- public function testHandleRemoteWipeStartedCanNotPublish() {
+ public function testHandleRemoteWipeStartedCanNotPublish(): void {
$token = $this->createMock(IToken::class);
$event = new RemoteWipeStarted($token);
$this->activityManager->expects($this->once())
@@ -99,7 +99,7 @@ class RemoteWipeActivityListenerTest extends TestCase {
$this->listener->handle($event);
}
- public function testHandleRemoteWipeFinished() {
+ public function testHandleRemoteWipeFinished(): void {
/** @var IToken|MockObject $token */
$token = $this->createMock(IToken::class);
$event = new RemoteWipeFinished($token);
diff --git a/tests/lib/Authentication/Listeners/RemoteWipeEmailListenerTest.php b/tests/lib/Authentication/Listeners/RemoteWipeEmailListenerTest.php
index 27dd85d9961..1c45add4e31 100644
--- a/tests/lib/Authentication/Listeners/RemoteWipeEmailListenerTest.php
+++ b/tests/lib/Authentication/Listeners/RemoteWipeEmailListenerTest.php
@@ -66,14 +66,14 @@ class RemoteWipeEmailListenerTest extends TestCase {
}
- public function testHandleUnrelated() {
+ public function testHandleUnrelated(): void {
$event = new Event();
$this->mailer->expects($this->never())->method('send');
$this->listener->handle($event);
}
- public function testHandleRemoteWipeStartedInvalidUser() {
+ public function testHandleRemoteWipeStartedInvalidUser(): void {
/** @var IToken|MockObject $token */
$token = $this->createMock(IToken::class);
$event = new RemoteWipeStarted($token);
@@ -87,7 +87,7 @@ class RemoteWipeEmailListenerTest extends TestCase {
$this->listener->handle($event);
}
- public function testHandleRemoteWipeStartedNoEmailSet() {
+ public function testHandleRemoteWipeStartedNoEmailSet(): void {
/** @var IToken|MockObject $token */
$token = $this->createMock(IToken::class);
$event = new RemoteWipeStarted($token);
@@ -103,7 +103,7 @@ class RemoteWipeEmailListenerTest extends TestCase {
$this->listener->handle($event);
}
- public function testHandleRemoteWipeStartedTransmissionError() {
+ public function testHandleRemoteWipeStartedTransmissionError(): void {
/** @var IToken|MockObject $token */
$token = $this->createMock(IToken::class);
$event = new RemoteWipeStarted($token);
@@ -123,7 +123,7 @@ class RemoteWipeEmailListenerTest extends TestCase {
$this->listener->handle($event);
}
- public function testHandleRemoteWipeStarted() {
+ public function testHandleRemoteWipeStarted(): void {
/** @var IToken|MockObject $token */
$token = $this->createMock(IToken::class);
$event = new RemoteWipeStarted($token);
@@ -148,7 +148,7 @@ class RemoteWipeEmailListenerTest extends TestCase {
$this->listener->handle($event);
}
- public function testHandleRemoteWipeFinishedInvalidUser() {
+ public function testHandleRemoteWipeFinishedInvalidUser(): void {
/** @var IToken|MockObject $token */
$token = $this->createMock(IToken::class);
$event = new RemoteWipeFinished($token);
@@ -162,7 +162,7 @@ class RemoteWipeEmailListenerTest extends TestCase {
$this->listener->handle($event);
}
- public function testHandleRemoteWipeFinishedNoEmailSet() {
+ public function testHandleRemoteWipeFinishedNoEmailSet(): void {
/** @var IToken|MockObject $token */
$token = $this->createMock(IToken::class);
$event = new RemoteWipeFinished($token);
@@ -178,7 +178,7 @@ class RemoteWipeEmailListenerTest extends TestCase {
$this->listener->handle($event);
}
- public function testHandleRemoteWipeFinishedTransmissionError() {
+ public function testHandleRemoteWipeFinishedTransmissionError(): void {
/** @var IToken|MockObject $token */
$token = $this->createMock(IToken::class);
$event = new RemoteWipeFinished($token);
@@ -198,7 +198,7 @@ class RemoteWipeEmailListenerTest extends TestCase {
$this->listener->handle($event);
}
- public function testHandleRemoteWipeFinished() {
+ public function testHandleRemoteWipeFinished(): void {
/** @var IToken|MockObject $token */
$token = $this->createMock(IToken::class);
$event = new RemoteWipeFinished($token);
diff --git a/tests/lib/Authentication/Listeners/RemoteWipeNotificationsListenerTest.php b/tests/lib/Authentication/Listeners/RemoteWipeNotificationsListenerTest.php
index d223f0d05a1..53fa502b199 100644
--- a/tests/lib/Authentication/Listeners/RemoteWipeNotificationsListenerTest.php
+++ b/tests/lib/Authentication/Listeners/RemoteWipeNotificationsListenerTest.php
@@ -44,7 +44,7 @@ class RemoteWipeNotificationsListenerTest extends TestCase {
);
}
- public function testHandleUnrelated() {
+ public function testHandleUnrelated(): void {
$event = new Event();
$this->listener->handle($event);
@@ -52,7 +52,7 @@ class RemoteWipeNotificationsListenerTest extends TestCase {
$this->addToAssertionCount(1);
}
- public function testHandleRemoteWipeStarted() {
+ public function testHandleRemoteWipeStarted(): void {
$token = $this->createMock(IToken::class);
$event = new RemoteWipeStarted($token);
$notification = $this->createMock(INotification::class);
@@ -92,7 +92,7 @@ class RemoteWipeNotificationsListenerTest extends TestCase {
$this->listener->handle($event);
}
- public function testHandleRemoteWipeFinished() {
+ public function testHandleRemoteWipeFinished(): void {
$token = $this->createMock(IToken::class);
$event = new RemoteWipeFinished($token);
$notification = $this->createMock(INotification::class);
diff --git a/tests/lib/Authentication/Login/ClearLostPasswordTokensCommandTest.php b/tests/lib/Authentication/Login/ClearLostPasswordTokensCommandTest.php
index 1a97f0e345b..025612e963e 100644
--- a/tests/lib/Authentication/Login/ClearLostPasswordTokensCommandTest.php
+++ b/tests/lib/Authentication/Login/ClearLostPasswordTokensCommandTest.php
@@ -27,7 +27,7 @@ class ClearLostPasswordTokensCommandTest extends ALoginCommandTest {
);
}
- public function testProcess() {
+ public function testProcess(): void {
$data = $this->getLoggedInLoginData();
$this->user->expects($this->once())
->method('getUID')
diff --git a/tests/lib/Authentication/Login/CompleteLoginCommandTest.php b/tests/lib/Authentication/Login/CompleteLoginCommandTest.php
index eeb39d5173d..4ddb26e7648 100644
--- a/tests/lib/Authentication/Login/CompleteLoginCommandTest.php
+++ b/tests/lib/Authentication/Login/CompleteLoginCommandTest.php
@@ -27,7 +27,7 @@ class CompleteLoginCommandTest extends ALoginCommandTest {
);
}
- public function testProcess() {
+ public function testProcess(): void {
$data = $this->getLoggedInLoginData();
$this->session->expects($this->once())
->method('completeLogin')
diff --git a/tests/lib/Authentication/Login/CreateSessionTokenCommandTest.php b/tests/lib/Authentication/Login/CreateSessionTokenCommandTest.php
index 049b6b1c94b..fd6a154ef5d 100644
--- a/tests/lib/Authentication/Login/CreateSessionTokenCommandTest.php
+++ b/tests/lib/Authentication/Login/CreateSessionTokenCommandTest.php
@@ -34,7 +34,7 @@ class CreateSessionTokenCommandTest extends ALoginCommandTest {
);
}
- public function testProcess() {
+ public function testProcess(): void {
$data = $this->getLoggedInLoginData();
$this->config->expects($this->once())
->method('getSystemValueInt')
@@ -67,7 +67,7 @@ class CreateSessionTokenCommandTest extends ALoginCommandTest {
$this->assertTrue($result->isSuccess());
}
- public function testProcessDoNotRemember() {
+ public function testProcessDoNotRemember(): void {
$data = $this->getLoggedInLoginData();
$this->config->expects($this->once())
->method('getSystemValueInt')
diff --git a/tests/lib/Authentication/Login/EmailLoginCommandTest.php b/tests/lib/Authentication/Login/EmailLoginCommandTest.php
index 236825e77bb..b34d0d95f4f 100644
--- a/tests/lib/Authentication/Login/EmailLoginCommandTest.php
+++ b/tests/lib/Authentication/Login/EmailLoginCommandTest.php
@@ -28,7 +28,7 @@ class EmailLoginCommandTest extends ALoginCommandTest {
);
}
- public function testProcessAlreadyLoggedIn() {
+ public function testProcessAlreadyLoggedIn(): void {
$data = $this->getLoggedInLoginData();
$result = $this->cmd->process($data);
@@ -36,7 +36,7 @@ class EmailLoginCommandTest extends ALoginCommandTest {
$this->assertTrue($result->isSuccess());
}
- public function testProcessNotAnEmailLogin() {
+ public function testProcessNotAnEmailLogin(): void {
$data = $this->getFailedLoginData();
$this->userManager->expects($this->never())
->method('getByEmail')
@@ -48,7 +48,7 @@ class EmailLoginCommandTest extends ALoginCommandTest {
$this->assertTrue($result->isSuccess());
}
- public function testProcessDuplicateEmailLogin() {
+ public function testProcessDuplicateEmailLogin(): void {
$data = $this->getFailedLoginData();
$data->setUsername('user@example.com');
$this->userManager->expects($this->once())
@@ -64,7 +64,7 @@ class EmailLoginCommandTest extends ALoginCommandTest {
$this->assertTrue($result->isSuccess());
}
- public function testProcessUidIsEmail() {
+ public function testProcessUidIsEmail(): void {
$email = 'user@domain.com';
$data = $this->getFailedLoginData();
$data->setUsername($email);
@@ -88,7 +88,7 @@ class EmailLoginCommandTest extends ALoginCommandTest {
$this->assertEquals($email, $data->getUsername());
}
- public function testProcessWrongPassword() {
+ public function testProcessWrongPassword(): void {
$email = 'user@domain.com';
$data = $this->getFailedLoginData();
$data->setUsername($email);
@@ -117,7 +117,7 @@ class EmailLoginCommandTest extends ALoginCommandTest {
$this->assertEquals($email, $data->getUsername());
}
- public function testProcess() {
+ public function testProcess(): void {
$email = 'user@domain.com';
$data = $this->getFailedLoginData();
$data->setUsername($email);
diff --git a/tests/lib/Authentication/Login/FinishRememberedLoginCommandTest.php b/tests/lib/Authentication/Login/FinishRememberedLoginCommandTest.php
index 9f9a36faf9f..4eb4f94055f 100644
--- a/tests/lib/Authentication/Login/FinishRememberedLoginCommandTest.php
+++ b/tests/lib/Authentication/Login/FinishRememberedLoginCommandTest.php
@@ -32,7 +32,7 @@ class FinishRememberedLoginCommandTest extends ALoginCommandTest {
);
}
- public function testProcessNotRememberedLogin() {
+ public function testProcessNotRememberedLogin(): void {
$data = $this->getLoggedInLoginData();
$data->setRememberLogin(false);
$this->userSession->expects($this->never())
@@ -43,7 +43,7 @@ class FinishRememberedLoginCommandTest extends ALoginCommandTest {
$this->assertTrue($result->isSuccess());
}
- public function testProcess() {
+ public function testProcess(): void {
$data = $this->getLoggedInLoginData();
$this->config->expects($this->once())
->method('getSystemValueBool')
@@ -58,7 +58,7 @@ class FinishRememberedLoginCommandTest extends ALoginCommandTest {
$this->assertTrue($result->isSuccess());
}
- public function testProcessNotRemeberedLoginWithAutologout() {
+ public function testProcessNotRemeberedLoginWithAutologout(): void {
$data = $this->getLoggedInLoginData();
$this->config->expects($this->once())
->method('getSystemValueBool')
diff --git a/tests/lib/Authentication/Login/LoggedInCheckCommandTest.php b/tests/lib/Authentication/Login/LoggedInCheckCommandTest.php
index bb5d6235f86..ce783050921 100644
--- a/tests/lib/Authentication/Login/LoggedInCheckCommandTest.php
+++ b/tests/lib/Authentication/Login/LoggedInCheckCommandTest.php
@@ -34,7 +34,7 @@ class LoggedInCheckCommandTest extends ALoginCommandTest {
);
}
- public function testProcessSuccessfulLogin() {
+ public function testProcessSuccessfulLogin(): void {
$data = $this->getLoggedInLoginData();
$result = $this->cmd->process($data);
@@ -42,7 +42,7 @@ class LoggedInCheckCommandTest extends ALoginCommandTest {
$this->assertTrue($result->isSuccess());
}
- public function testProcessFailedLogin() {
+ public function testProcessFailedLogin(): void {
$data = $this->getFailedLoginData();
$this->logger->expects($this->once())
->method('warning');
diff --git a/tests/lib/Authentication/Login/PreLoginHookCommandTest.php b/tests/lib/Authentication/Login/PreLoginHookCommandTest.php
index 824042e1dee..b6d826f1c21 100644
--- a/tests/lib/Authentication/Login/PreLoginHookCommandTest.php
+++ b/tests/lib/Authentication/Login/PreLoginHookCommandTest.php
@@ -28,7 +28,7 @@ class PreLoginHookCommandTest extends ALoginCommandTest {
);
}
- public function testProcess() {
+ public function testProcess(): void {
$data = $this->getBasicLoginData();
$this->userManager->expects($this->once())
->method('emit')
diff --git a/tests/lib/Authentication/Login/SetUserTimezoneCommandTest.php b/tests/lib/Authentication/Login/SetUserTimezoneCommandTest.php
index 068516b933b..d4e15f68257 100644
--- a/tests/lib/Authentication/Login/SetUserTimezoneCommandTest.php
+++ b/tests/lib/Authentication/Login/SetUserTimezoneCommandTest.php
@@ -33,7 +33,7 @@ class SetUserTimezoneCommandTest extends ALoginCommandTest {
);
}
- public function testProcessNoTimezoneSet() {
+ public function testProcessNoTimezoneSet(): void {
$data = $this->getLoggedInLoginData();
$this->config->expects($this->never())
->method('setUserValue');
@@ -45,7 +45,7 @@ class SetUserTimezoneCommandTest extends ALoginCommandTest {
$this->assertTrue($result->isSuccess());
}
- public function testProcess() {
+ public function testProcess(): void {
$data = $this->getLoggedInLoginDataWithTimezone();
$this->user->expects($this->once())
->method('getUID')
diff --git a/tests/lib/Authentication/Login/TwoFactorCommandTest.php b/tests/lib/Authentication/Login/TwoFactorCommandTest.php
index 54f634618fd..af7d7446bfb 100644
--- a/tests/lib/Authentication/Login/TwoFactorCommandTest.php
+++ b/tests/lib/Authentication/Login/TwoFactorCommandTest.php
@@ -42,7 +42,7 @@ class TwoFactorCommandTest extends ALoginCommandTest {
);
}
- public function testNotTwoFactorAuthenticated() {
+ public function testNotTwoFactorAuthenticated(): void {
$data = $this->getLoggedInLoginData();
$this->twoFactorManager->expects($this->once())
->method('isTwoFactorAuthenticated')
@@ -55,7 +55,7 @@ class TwoFactorCommandTest extends ALoginCommandTest {
$this->assertTrue($result->isSuccess());
}
- public function testProcessOneActiveProvider() {
+ public function testProcessOneActiveProvider(): void {
$data = $this->getLoggedInLoginData();
$this->twoFactorManager->expects($this->once())
->method('isTwoFactorAuthenticated')
@@ -99,7 +99,7 @@ class TwoFactorCommandTest extends ALoginCommandTest {
$this->assertEquals('two/factor/url', $result->getRedirectUrl());
}
- public function testProcessMissingProviders() {
+ public function testProcessMissingProviders(): void {
$data = $this->getLoggedInLoginData();
$this->twoFactorManager->expects($this->once())
->method('isTwoFactorAuthenticated')
@@ -140,7 +140,7 @@ class TwoFactorCommandTest extends ALoginCommandTest {
$this->assertEquals('two/factor/url', $result->getRedirectUrl());
}
- public function testProcessTwoActiveProviders() {
+ public function testProcessTwoActiveProviders(): void {
$data = $this->getLoggedInLoginData();
$this->twoFactorManager->expects($this->once())
->method('isTwoFactorAuthenticated')
@@ -186,7 +186,7 @@ class TwoFactorCommandTest extends ALoginCommandTest {
$this->assertEquals('two/factor/url', $result->getRedirectUrl());
}
- public function testProcessFailingProviderAndEnforcedButNoSetupProviders() {
+ public function testProcessFailingProviderAndEnforcedButNoSetupProviders(): void {
$data = $this->getLoggedInLoginData();
$this->twoFactorManager->expects($this->once())
->method('isTwoFactorAuthenticated')
@@ -221,7 +221,7 @@ class TwoFactorCommandTest extends ALoginCommandTest {
$this->assertEquals('two/factor/url', $result->getRedirectUrl());
}
- public function testProcessFailingProviderAndEnforced() {
+ public function testProcessFailingProviderAndEnforced(): void {
$data = $this->getLoggedInLoginData();
$this->twoFactorManager->expects($this->once())
->method('isTwoFactorAuthenticated')
@@ -259,7 +259,7 @@ class TwoFactorCommandTest extends ALoginCommandTest {
$this->assertEquals('two/factor/url', $result->getRedirectUrl());
}
- public function testProcessNoProvidersButEnforced() {
+ public function testProcessNoProvidersButEnforced(): void {
$data = $this->getLoggedInLoginData();
$this->twoFactorManager->expects($this->once())
->method('isTwoFactorAuthenticated')
@@ -294,7 +294,7 @@ class TwoFactorCommandTest extends ALoginCommandTest {
$this->assertEquals('two/factor/url', $result->getRedirectUrl());
}
- public function testProcessWithRedirectUrl() {
+ public function testProcessWithRedirectUrl(): void {
$data = $this->getLoggedInLoginDataWithRedirectUrl();
$this->twoFactorManager->expects($this->once())
->method('isTwoFactorAuthenticated')
diff --git a/tests/lib/Authentication/Login/UidLoginCommandTest.php b/tests/lib/Authentication/Login/UidLoginCommandTest.php
index e56c4323fd4..3073aac1859 100644
--- a/tests/lib/Authentication/Login/UidLoginCommandTest.php
+++ b/tests/lib/Authentication/Login/UidLoginCommandTest.php
@@ -27,7 +27,7 @@ class UidLoginCommandTest extends ALoginCommandTest {
);
}
- public function testProcessFailingLogin() {
+ public function testProcessFailingLogin(): void {
$data = $this->getBasicLoginData();
$this->userManager->expects($this->once())
->method('checkPasswordNoLogging')
@@ -43,7 +43,7 @@ class UidLoginCommandTest extends ALoginCommandTest {
$this->assertFalse($data->getUser());
}
- public function testProcess() {
+ public function testProcess(): void {
$data = $this->getBasicLoginData();
$this->userManager->expects($this->once())
->method('checkPasswordNoLogging')
diff --git a/tests/lib/Authentication/Login/UpdateLastPasswordConfirmCommandTest.php b/tests/lib/Authentication/Login/UpdateLastPasswordConfirmCommandTest.php
index d471b73659f..f5760f3f232 100644
--- a/tests/lib/Authentication/Login/UpdateLastPasswordConfirmCommandTest.php
+++ b/tests/lib/Authentication/Login/UpdateLastPasswordConfirmCommandTest.php
@@ -27,7 +27,7 @@ class UpdateLastPasswordConfirmCommandTest extends ALoginCommandTest {
);
}
- public function testProcess() {
+ public function testProcess(): void {
$data = $this->getLoggedInLoginData();
$this->user->expects($this->once())
->method('getLastLogin')
diff --git a/tests/lib/Authentication/Login/UserDisabledCheckCommandTest.php b/tests/lib/Authentication/Login/UserDisabledCheckCommandTest.php
index a36fb5c70bd..84b1018e5fa 100644
--- a/tests/lib/Authentication/Login/UserDisabledCheckCommandTest.php
+++ b/tests/lib/Authentication/Login/UserDisabledCheckCommandTest.php
@@ -34,7 +34,7 @@ class UserDisabledCheckCommandTest extends ALoginCommandTest {
);
}
- public function testProcessNonExistingUser() {
+ public function testProcessNonExistingUser(): void {
$data = $this->getBasicLoginData();
$this->userManager->expects($this->once())
->method('get')
@@ -46,7 +46,7 @@ class UserDisabledCheckCommandTest extends ALoginCommandTest {
$this->assertTrue($result->isSuccess());
}
- public function testProcessDisabledUser() {
+ public function testProcessDisabledUser(): void {
$data = $this->getBasicLoginData();
$this->userManager->expects($this->once())
->method('get')
@@ -62,7 +62,7 @@ class UserDisabledCheckCommandTest extends ALoginCommandTest {
$this->assertSame(LoginController::LOGIN_MSG_USERDISABLED, $result->getErrorMessage());
}
- public function testProcess() {
+ public function testProcess(): void {
$data = $this->getBasicLoginData();
$this->userManager->expects($this->once())
->method('get')
diff --git a/tests/lib/Authentication/LoginCredentials/CredentialsTest.php b/tests/lib/Authentication/LoginCredentials/CredentialsTest.php
index ed3ea469653..a64ad6c9b76 100644
--- a/tests/lib/Authentication/LoginCredentials/CredentialsTest.php
+++ b/tests/lib/Authentication/LoginCredentials/CredentialsTest.php
@@ -33,15 +33,15 @@ class CredentialsTest extends TestCase {
$this->credentials = new Credentials($this->uid, $this->user, $this->password);
}
- public function testGetUID() {
+ public function testGetUID(): void {
$this->assertEquals($this->uid, $this->credentials->getUID());
}
- public function testGetUserName() {
+ public function testGetUserName(): void {
$this->assertEquals($this->user, $this->credentials->getLoginName());
}
- public function testGetPassword() {
+ public function testGetPassword(): void {
$this->assertEquals($this->password, $this->credentials->getPassword());
}
}
diff --git a/tests/lib/Authentication/LoginCredentials/StoreTest.php b/tests/lib/Authentication/LoginCredentials/StoreTest.php
index 06dd2527930..6f1e3a6d750 100644
--- a/tests/lib/Authentication/LoginCredentials/StoreTest.php
+++ b/tests/lib/Authentication/LoginCredentials/StoreTest.php
@@ -43,7 +43,7 @@ class StoreTest extends TestCase {
$this->store = new Store($this->session, $this->logger, $this->tokenProvider);
}
- public function testAuthenticate() {
+ public function testAuthenticate(): void {
$params = [
'run' => true,
'uid' => 'user123',
@@ -57,14 +57,14 @@ class StoreTest extends TestCase {
$this->store->authenticate($params);
}
- public function testSetSession() {
+ public function testSetSession(): void {
$session = $this->createMock(ISession::class);
$this->store->setSession($session);
$this->addToAssertionCount(1);
}
- public function testGetLoginCredentialsNoTokenProvider() {
+ public function testGetLoginCredentialsNoTokenProvider(): void {
$this->store = new Store($this->session, $this->logger, null);
$this->expectException(CredentialsUnavailableException::class);
@@ -72,7 +72,7 @@ class StoreTest extends TestCase {
$this->store->getLoginCredentials();
}
- public function testGetLoginCredentials() {
+ public function testGetLoginCredentials(): void {
$uid = 'uid';
$user = 'user123';
$password = 'passme';
@@ -101,7 +101,7 @@ class StoreTest extends TestCase {
$this->assertEquals($expected, $creds);
}
- public function testGetLoginCredentialsSessionNotAvailable() {
+ public function testGetLoginCredentialsSessionNotAvailable(): void {
$this->session->expects($this->once())
->method('getId')
->will($this->throwException(new SessionNotAvailableException()));
@@ -110,7 +110,7 @@ class StoreTest extends TestCase {
$this->store->getLoginCredentials();
}
- public function testGetLoginCredentialsInvalidToken() {
+ public function testGetLoginCredentialsInvalidToken(): void {
$this->session->expects($this->once())
->method('getId')
->willReturn('sess2233');
@@ -123,7 +123,7 @@ class StoreTest extends TestCase {
$this->store->getLoginCredentials();
}
- public function testGetLoginCredentialsPartialCredentialsAndSessionName() {
+ public function testGetLoginCredentialsPartialCredentialsAndSessionName(): void {
$uid = 'id987';
$user = 'user987';
$password = '7389374';
@@ -161,7 +161,7 @@ class StoreTest extends TestCase {
$this->assertEquals($expected, $actual);
}
- public function testGetLoginCredentialsPartialCredentials() {
+ public function testGetLoginCredentialsPartialCredentials(): void {
$uid = 'id987';
$password = '7389374';
@@ -198,7 +198,7 @@ class StoreTest extends TestCase {
$this->assertEquals($expected, $actual);
}
- public function testGetLoginCredentialsInvalidTokenLoginCredentials() {
+ public function testGetLoginCredentialsInvalidTokenLoginCredentials(): void {
$uid = 'id987';
$user = 'user987';
$password = '7389374';
@@ -225,7 +225,7 @@ class StoreTest extends TestCase {
$this->assertEquals($expected, $actual);
}
- public function testGetLoginCredentialsPasswordlessToken() {
+ public function testGetLoginCredentialsPasswordlessToken(): void {
$this->session->expects($this->once())
->method('getId')
->willReturn('sess2233');
diff --git a/tests/lib/Authentication/Token/ManagerTest.php b/tests/lib/Authentication/Token/ManagerTest.php
index 98baffed14b..4fde9817d09 100644
--- a/tests/lib/Authentication/Token/ManagerTest.php
+++ b/tests/lib/Authentication/Token/ManagerTest.php
@@ -33,7 +33,7 @@ class ManagerTest extends TestCase {
);
}
- public function testGenerateToken() {
+ public function testGenerateToken(): void {
$token = new PublicKeyToken();
$this->publicKeyTokenProvider->expects($this->once())
@@ -61,7 +61,7 @@ class ManagerTest extends TestCase {
$this->assertSame($token, $actual);
}
- public function testGenerateConflictingToken() {
+ public function testGenerateConflictingToken(): void {
/** @var MockObject|UniqueConstraintViolationException $exception */
$exception = $this->createMock(UniqueConstraintViolationException::class);
@@ -97,7 +97,7 @@ class ManagerTest extends TestCase {
$this->assertSame($token, $actual);
}
- public function testGenerateTokenTooLongName() {
+ public function testGenerateTokenTooLongName(): void {
$token = $this->createMock(IToken::class);
$token->method('getName')
->willReturn(str_repeat('a', 120) . '…');
@@ -160,7 +160,7 @@ class ManagerTest extends TestCase {
/**
* @dataProvider tokenData
*/
- public function testUpdateToken(IToken $token) {
+ public function testUpdateToken(IToken $token): void {
$this->setNoCall($token);
$this->setCall($token, 'updateToken');
$this->setException($token);
@@ -171,7 +171,7 @@ class ManagerTest extends TestCase {
/**
* @dataProvider tokenData
*/
- public function testUpdateTokenActivity(IToken $token) {
+ public function testUpdateTokenActivity(IToken $token): void {
$this->setNoCall($token);
$this->setCall($token, 'updateTokenActivity');
$this->setException($token);
@@ -182,7 +182,7 @@ class ManagerTest extends TestCase {
/**
* @dataProvider tokenData
*/
- public function testGetPassword(IToken $token) {
+ public function testGetPassword(IToken $token): void {
$this->setNoCall($token);
$this->setCall($token, 'getPassword', 'password');
$this->setException($token);
@@ -195,7 +195,7 @@ class ManagerTest extends TestCase {
/**
* @dataProvider tokenData
*/
- public function testSetPassword(IToken $token) {
+ public function testSetPassword(IToken $token): void {
$this->setNoCall($token);
$this->setCall($token, 'setPassword');
$this->setException($token);
@@ -203,7 +203,7 @@ class ManagerTest extends TestCase {
$this->manager->setPassword($token, 'tokenId', 'password');
}
- public function testInvalidateTokens() {
+ public function testInvalidateTokens(): void {
$this->publicKeyTokenProvider->expects($this->once())
->method('invalidateToken')
->with('token');
@@ -211,7 +211,7 @@ class ManagerTest extends TestCase {
$this->manager->invalidateToken('token');
}
- public function testInvalidateTokenById() {
+ public function testInvalidateTokenById(): void {
$this->publicKeyTokenProvider->expects($this->once())
->method('invalidateTokenById')
->with('uid', 42);
@@ -219,14 +219,14 @@ class ManagerTest extends TestCase {
$this->manager->invalidateTokenById('uid', 42);
}
- public function testInvalidateOldTokens() {
+ public function testInvalidateOldTokens(): void {
$this->publicKeyTokenProvider->expects($this->once())
->method('invalidateOldTokens');
$this->manager->invalidateOldTokens();
}
- public function testInvalidateLastUsedBefore() {
+ public function testInvalidateLastUsedBefore(): void {
$this->publicKeyTokenProvider->expects($this->once())
->method('invalidateLastUsedBefore')
->with('user', 946684800);
@@ -234,7 +234,7 @@ class ManagerTest extends TestCase {
$this->manager->invalidateLastUsedBefore('user', 946684800);
}
- public function testGetTokenByUser() {
+ public function testGetTokenByUser(): void {
$t1 = new PublicKeyToken();
$t2 = new PublicKeyToken();
@@ -247,7 +247,7 @@ class ManagerTest extends TestCase {
$this->assertEquals([$t1, $t2], $result);
}
- public function testRenewSessionTokenPublicKey() {
+ public function testRenewSessionTokenPublicKey(): void {
$this->publicKeyTokenProvider->expects($this->once())
->method('renewSessionToken')
->with('oldId', 'newId');
@@ -255,7 +255,7 @@ class ManagerTest extends TestCase {
$this->manager->renewSessionToken('oldId', 'newId');
}
- public function testRenewSessionInvalid() {
+ public function testRenewSessionInvalid(): void {
$this->publicKeyTokenProvider->expects($this->once())
->method('renewSessionToken')
->with('oldId', 'newId')
@@ -265,7 +265,7 @@ class ManagerTest extends TestCase {
$this->manager->renewSessionToken('oldId', 'newId');
}
- public function testGetTokenByIdPublicKey() {
+ public function testGetTokenByIdPublicKey(): void {
$token = $this->createMock(IToken::class);
$this->publicKeyTokenProvider->expects($this->once())
@@ -276,7 +276,7 @@ class ManagerTest extends TestCase {
$this->assertSame($token, $this->manager->getTokenById(42));
}
- public function testGetTokenByIdInvalid() {
+ public function testGetTokenByIdInvalid(): void {
$this->publicKeyTokenProvider->expects($this->once())
->method('getTokenById')
->with(42)
@@ -286,7 +286,7 @@ class ManagerTest extends TestCase {
$this->manager->getTokenById(42);
}
- public function testGetTokenPublicKey() {
+ public function testGetTokenPublicKey(): void {
$token = new PublicKeyToken();
$this->publicKeyTokenProvider
@@ -297,7 +297,7 @@ class ManagerTest extends TestCase {
$this->assertSame($token, $this->manager->getToken('tokenId'));
}
- public function testGetTokenInvalid() {
+ public function testGetTokenInvalid(): void {
$this->publicKeyTokenProvider
->method('getToken')
->with('tokenId')
@@ -307,12 +307,12 @@ class ManagerTest extends TestCase {
$this->manager->getToken('tokenId');
}
- public function testRotateInvalid() {
+ public function testRotateInvalid(): void {
$this->expectException(InvalidTokenException::class);
$this->manager->rotate($this->createMock(IToken::class), 'oldId', 'newId');
}
- public function testRotatePublicKey() {
+ public function testRotatePublicKey(): void {
$token = new PublicKeyToken();
$this->publicKeyTokenProvider
@@ -323,7 +323,7 @@ class ManagerTest extends TestCase {
$this->assertSame($token, $this->manager->rotate($token, 'oldId', 'newId'));
}
- public function testMarkPasswordInvalidPublicKey() {
+ public function testMarkPasswordInvalidPublicKey(): void {
$token = $this->createMock(PublicKeyToken::class);
$this->publicKeyTokenProvider->expects($this->once())
@@ -333,13 +333,13 @@ class ManagerTest extends TestCase {
$this->manager->markPasswordInvalid($token, 'tokenId');
}
- public function testMarkPasswordInvalidInvalidToken() {
+ public function testMarkPasswordInvalidInvalidToken(): void {
$this->expectException(InvalidTokenException::class);
$this->manager->markPasswordInvalid($this->createMock(IToken::class), 'tokenId');
}
- public function testUpdatePasswords() {
+ public function testUpdatePasswords(): void {
$this->publicKeyTokenProvider->expects($this->once())
->method('updatePasswords')
->with('uid', 'pass');
@@ -347,7 +347,7 @@ class ManagerTest extends TestCase {
$this->manager->updatePasswords('uid', 'pass');
}
- public function testInvalidateTokensOfUserNoClientName() {
+ public function testInvalidateTokensOfUserNoClientName(): void {
$t1 = new PublicKeyToken();
$t2 = new PublicKeyToken();
$t1->setId(123);
@@ -368,7 +368,7 @@ class ManagerTest extends TestCase {
$this->manager->invalidateTokensOfUser('theUser', null);
}
- public function testInvalidateTokensOfUserClientNameGiven() {
+ public function testInvalidateTokensOfUserClientNameGiven(): void {
$t1 = new PublicKeyToken();
$t2 = new PublicKeyToken();
$t3 = new PublicKeyToken();
diff --git a/tests/lib/Authentication/Token/PublicKeyTokenMapperTest.php b/tests/lib/Authentication/Token/PublicKeyTokenMapperTest.php
index 137618a965a..7cc4e77ecb2 100644
--- a/tests/lib/Authentication/Token/PublicKeyTokenMapperTest.php
+++ b/tests/lib/Authentication/Token/PublicKeyTokenMapperTest.php
@@ -121,7 +121,7 @@ class PublicKeyTokenMapperTest extends TestCase {
return (int)$result['count'];
}
- public function testInvalidate() {
+ public function testInvalidate(): void {
$token = '9c5a2e661482b65597408a6bb6c4a3d1af36337381872ac56e445a06cdb7fea2b1039db707545c11027a4966919918b19d875a8b774840b18c6cbb7ae56fe206';
$this->mapper->invalidate($token);
@@ -129,7 +129,7 @@ class PublicKeyTokenMapperTest extends TestCase {
$this->assertSame(4, $this->getNumberOfTokens());
}
- public function testInvalidateInvalid() {
+ public function testInvalidateInvalid(): void {
$token = 'youwontfindthisoneinthedatabase';
$this->mapper->invalidate($token);
@@ -137,7 +137,7 @@ class PublicKeyTokenMapperTest extends TestCase {
$this->assertSame(5, $this->getNumberOfTokens());
}
- public function testInvalidateOld() {
+ public function testInvalidateOld(): void {
$olderThan = $this->time - 60 * 60; // One hour
$this->mapper->invalidateOld($olderThan);
@@ -145,7 +145,7 @@ class PublicKeyTokenMapperTest extends TestCase {
$this->assertSame(4, $this->getNumberOfTokens());
}
- public function testInvalidateLastUsedBefore() {
+ public function testInvalidateLastUsedBefore(): void {
$before = $this->time - 60 * 2; // Two minutes
$this->mapper->invalidateLastUsedBefore('user3', $before);
@@ -153,7 +153,7 @@ class PublicKeyTokenMapperTest extends TestCase {
$this->assertSame(4, $this->getNumberOfTokens());
}
- public function testGetToken() {
+ public function testGetToken(): void {
$token = new PublicKeyToken();
$token->setUid('user2');
$token->setLoginName('User2');
@@ -177,7 +177,7 @@ class PublicKeyTokenMapperTest extends TestCase {
}
- public function testGetInvalidToken() {
+ public function testGetInvalidToken(): void {
$this->expectException(\OCP\AppFramework\Db\DoesNotExistException::class);
$token = 'thisisaninvalidtokenthatisnotinthedatabase';
@@ -185,7 +185,7 @@ class PublicKeyTokenMapperTest extends TestCase {
$this->mapper->getToken($token);
}
- public function testGetTokenById() {
+ public function testGetTokenById(): void {
$token = new PublicKeyToken();
$token->setUid('user2');
$token->setLoginName('User2');
@@ -209,14 +209,14 @@ class PublicKeyTokenMapperTest extends TestCase {
}
- public function testGetTokenByIdNotFound() {
+ public function testGetTokenByIdNotFound(): void {
$this->expectException(\OCP\AppFramework\Db\DoesNotExistException::class);
$this->mapper->getTokenById(-1);
}
- public function testGetInvalidTokenById() {
+ public function testGetInvalidTokenById(): void {
$this->expectException(\OCP\AppFramework\Db\DoesNotExistException::class);
$id = '42';
@@ -224,15 +224,15 @@ class PublicKeyTokenMapperTest extends TestCase {
$this->mapper->getToken($id);
}
- public function testGetTokenByUser() {
+ public function testGetTokenByUser(): void {
$this->assertCount(2, $this->mapper->getTokenByUser('user1'));
}
- public function testGetTokenByUserNotFound() {
+ public function testGetTokenByUserNotFound(): void {
$this->assertCount(0, $this->mapper->getTokenByUser('user1000'));
}
- public function testGetById() {
+ public function testGetById(): void {
/** @var IUser|\PHPUnit\Framework\MockObject\MockObject $user */
$user = $this->createMock(IUser::class);
$qb = $this->dbConnection->getQueryBuilder();
@@ -246,7 +246,7 @@ class PublicKeyTokenMapperTest extends TestCase {
$this->assertEquals('user1', $token->getUID());
}
- public function testDeleteByName() {
+ public function testDeleteByName(): void {
$qb = $this->dbConnection->getQueryBuilder();
$qb->select('name')
->from('authtoken')
@@ -257,7 +257,7 @@ class PublicKeyTokenMapperTest extends TestCase {
$this->assertEquals(4, $this->getNumberOfTokens());
}
- public function testHasExpiredTokens() {
+ public function testHasExpiredTokens(): void {
$this->assertFalse($this->mapper->hasExpiredTokens('user1'));
$this->assertTrue($this->mapper->hasExpiredTokens('user3'));
}
diff --git a/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php b/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php
index e2ca4350f29..be90d60c64f 100644
--- a/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php
+++ b/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php
@@ -84,7 +84,7 @@ class PublicKeyTokenProviderTest extends TestCase {
);
}
- public function testGenerateToken() {
+ public function testGenerateToken(): void {
$token = 'tokentokentokentokentoken';
$uid = 'user';
$user = 'User';
@@ -129,7 +129,7 @@ class PublicKeyTokenProviderTest extends TestCase {
$this->tokenProvider->getPassword($actual, $token);
}
- public function testGenerateTokenLongPassword() {
+ public function testGenerateTokenLongPassword(): void {
$token = 'tokentokentokentokentoken';
$uid = 'user';
$user = 'User';
@@ -148,7 +148,7 @@ class PublicKeyTokenProviderTest extends TestCase {
$actual = $this->tokenProvider->generateToken($token, $uid, $user, $password, $name, $type, IToken::DO_NOT_REMEMBER);
}
- public function testGenerateTokenInvalidName() {
+ public function testGenerateTokenInvalidName(): void {
$token = 'tokentokentokentokentoken';
$uid = 'user';
$user = 'User';
@@ -173,7 +173,7 @@ class PublicKeyTokenProviderTest extends TestCase {
$this->assertSame($password, $this->tokenProvider->getPassword($actual, $token));
}
- public function testUpdateToken() {
+ public function testUpdateToken(): void {
$tk = new PublicKeyToken();
$this->mapper->expects($this->once())
->method('updateActivity')
@@ -189,7 +189,7 @@ class PublicKeyTokenProviderTest extends TestCase {
$this->assertEquals($this->time, $tk->getLastActivity());
}
- public function testUpdateTokenDebounce() {
+ public function testUpdateTokenDebounce(): void {
$tk = new PublicKeyToken();
$this->config->method('getSystemValueInt')
->willReturnCallback(function ($value, $default) {
@@ -204,7 +204,7 @@ class PublicKeyTokenProviderTest extends TestCase {
$this->tokenProvider->updateTokenActivity($tk);
}
- public function testGetTokenByUser() {
+ public function testGetTokenByUser(): void {
$this->mapper->expects($this->once())
->method('getTokenByUser')
->with('uid')
@@ -213,7 +213,7 @@ class PublicKeyTokenProviderTest extends TestCase {
$this->assertEquals(['token'], $this->tokenProvider->getTokenByUser('uid'));
}
- public function testGetPassword() {
+ public function testGetPassword(): void {
$token = 'tokentokentokentokentoken';
$uid = 'user';
$user = 'User';
@@ -231,7 +231,7 @@ class PublicKeyTokenProviderTest extends TestCase {
}
- public function testGetPasswordPasswordLessToken() {
+ public function testGetPasswordPasswordLessToken(): void {
$this->expectException(\OC\Authentication\Exceptions\PasswordlessTokenException::class);
$token = 'token1234';
@@ -242,7 +242,7 @@ class PublicKeyTokenProviderTest extends TestCase {
}
- public function testGetPasswordInvalidToken() {
+ public function testGetPasswordInvalidToken(): void {
$this->expectException(\OC\Authentication\Exceptions\InvalidTokenException::class);
$token = 'tokentokentokentokentoken';
@@ -261,7 +261,7 @@ class PublicKeyTokenProviderTest extends TestCase {
$this->tokenProvider->getPassword($actual, 'wrongtoken');
}
- public function testSetPassword() {
+ public function testSetPassword(): void {
$token = 'tokentokentokentokentoken';
$uid = 'user';
$user = 'User';
@@ -293,7 +293,7 @@ class PublicKeyTokenProviderTest extends TestCase {
}
- public function testSetPasswordInvalidToken() {
+ public function testSetPasswordInvalidToken(): void {
$this->expectException(\OC\Authentication\Exceptions\InvalidTokenException::class);
$token = $this->createMock(IToken::class);
@@ -303,7 +303,7 @@ class PublicKeyTokenProviderTest extends TestCase {
$this->tokenProvider->setPassword($token, $tokenId, $password);
}
- public function testInvalidateToken() {
+ public function testInvalidateToken(): void {
$this->mapper->expects($this->exactly(2))
->method('invalidate')
->withConsecutive(
@@ -314,7 +314,7 @@ class PublicKeyTokenProviderTest extends TestCase {
$this->tokenProvider->invalidateToken('token7');
}
- public function testInvalidateTokenById() {
+ public function testInvalidateTokenById(): void {
$id = 123;
$this->mapper->expects($this->once())
@@ -348,7 +348,7 @@ class PublicKeyTokenProviderTest extends TestCase {
$this->tokenProvider->invalidateOldTokens();
}
- public function testInvalidateLastUsedBefore() {
+ public function testInvalidateLastUsedBefore(): void {
$this->mapper->expects($this->once())
->method('invalidateLastUsedBefore')
->with('user', 946684800);
@@ -356,7 +356,7 @@ class PublicKeyTokenProviderTest extends TestCase {
$this->tokenProvider->invalidateLastUsedBefore('user', 946684800);
}
- public function testRenewSessionTokenWithoutPassword() {
+ public function testRenewSessionTokenWithoutPassword(): void {
$token = 'oldIdtokentokentokentoken';
$uid = 'user';
$user = 'User';
@@ -450,7 +450,7 @@ class PublicKeyTokenProviderTest extends TestCase {
$this->assertSame($token, $this->tokenProvider->getToken('unhashedTokentokentokentokentoken'));
}
- public function testGetInvalidToken() {
+ public function testGetInvalidToken(): void {
$this->expectException(InvalidTokenException::class);
$this->mapper->expects($this->exactly(2))
@@ -467,7 +467,7 @@ class PublicKeyTokenProviderTest extends TestCase {
$this->tokenProvider->getToken('unhashedTokentokentokentokentoken');
}
- public function testGetExpiredToken() {
+ public function testGetExpiredToken(): void {
$token = 'tokentokentokentokentoken';
$uid = 'user';
$user = 'User';
@@ -493,7 +493,7 @@ class PublicKeyTokenProviderTest extends TestCase {
}
}
- public function testGetTokenById() {
+ public function testGetTokenById(): void {
$token = $this->createMock(PublicKeyToken::class);
$this->mapper->expects($this->once())
@@ -504,7 +504,7 @@ class PublicKeyTokenProviderTest extends TestCase {
$this->assertSame($token, $this->tokenProvider->getTokenById(42));
}
- public function testGetInvalidTokenById() {
+ public function testGetInvalidTokenById(): void {
$this->expectException(InvalidTokenException::class);
$this->mapper->expects($this->once())
@@ -515,7 +515,7 @@ class PublicKeyTokenProviderTest extends TestCase {
$this->tokenProvider->getTokenById(42);
}
- public function testGetExpiredTokenById() {
+ public function testGetExpiredTokenById(): void {
$token = new PublicKeyToken();
$token->setExpires(42);
@@ -532,7 +532,7 @@ class PublicKeyTokenProviderTest extends TestCase {
}
}
- public function testRotate() {
+ public function testRotate(): void {
$token = 'oldtokentokentokentokentoken';
$uid = 'user';
$user = 'User';
@@ -551,7 +551,7 @@ class PublicKeyTokenProviderTest extends TestCase {
$this->assertSame('password', $this->tokenProvider->getPassword($new, 'newtokentokentokentokentoken'));
}
- public function testRotateNoPassword() {
+ public function testRotateNoPassword(): void {
$token = 'oldtokentokentokentokentoken';
$uid = 'user';
$user = 'User';
@@ -571,7 +571,7 @@ class PublicKeyTokenProviderTest extends TestCase {
$this->assertNull($new->getPassword());
}
- public function testMarkPasswordInvalidInvalidToken() {
+ public function testMarkPasswordInvalidInvalidToken(): void {
$token = $this->createMock(IToken::class);
$this->expectException(InvalidTokenException::class);
@@ -579,7 +579,7 @@ class PublicKeyTokenProviderTest extends TestCase {
$this->tokenProvider->markPasswordInvalid($token, 'tokenId');
}
- public function testMarkPasswordInvalid() {
+ public function testMarkPasswordInvalid(): void {
$token = $this->createMock(PublicKeyToken::class);
$token->expects($this->once())
@@ -592,7 +592,7 @@ class PublicKeyTokenProviderTest extends TestCase {
$this->tokenProvider->markPasswordInvalid($token, 'tokenId');
}
- public function testUpdatePasswords() {
+ public function testUpdatePasswords(): void {
$uid = 'myUID';
$token1 = $this->tokenProvider->generateToken(
'foobetokentokentokentoken',
diff --git a/tests/lib/Authentication/Token/PublicKeyTokenTest.php b/tests/lib/Authentication/Token/PublicKeyTokenTest.php
index cc8890002e9..5f5f29c865f 100644
--- a/tests/lib/Authentication/Token/PublicKeyTokenTest.php
+++ b/tests/lib/Authentication/Token/PublicKeyTokenTest.php
@@ -13,7 +13,7 @@ use OCP\Authentication\Token\IToken;
use Test\TestCase;
class PublicKeyTokenTest extends TestCase {
- public function testSetScopeAsArray() {
+ public function testSetScopeAsArray(): void {
$scope = [IToken::SCOPE_FILESYSTEM => false];
$token = new PublicKeyToken();
$token->setScope($scope);
@@ -21,7 +21,7 @@ class PublicKeyTokenTest extends TestCase {
$this->assertEquals($scope, $token->getScopeAsArray());
}
- public function testDefaultScope() {
+ public function testDefaultScope(): void {
$scope = [IToken::SCOPE_FILESYSTEM => true];
$token = new PublicKeyToken();
$this->assertEquals($scope, $token->getScopeAsArray());
diff --git a/tests/lib/Authentication/Token/RemoteWipeTest.php b/tests/lib/Authentication/Token/RemoteWipeTest.php
index 1c4a0f73d84..ca09767c759 100644
--- a/tests/lib/Authentication/Token/RemoteWipeTest.php
+++ b/tests/lib/Authentication/Token/RemoteWipeTest.php
@@ -106,7 +106,7 @@ class RemoteWipeTest extends TestCase {
$this->assertTrue($result);
}
- public function testStartWipingNotAWipeToken() {
+ public function testStartWipingNotAWipeToken(): void {
$token = $this->createMock(IToken::class);
$this->tokenProvider->expects($this->once())
->method('getToken')
@@ -120,7 +120,7 @@ class RemoteWipeTest extends TestCase {
$this->assertFalse($result);
}
- public function testStartWiping() {
+ public function testStartWiping(): void {
$token = $this->createMock(IToken::class);
$this->tokenProvider->expects($this->once())
->method('getToken')
@@ -137,7 +137,7 @@ class RemoteWipeTest extends TestCase {
$this->assertTrue($result);
}
- public function testFinishWipingNotAWipeToken() {
+ public function testFinishWipingNotAWipeToken(): void {
$token = $this->createMock(IToken::class);
$this->tokenProvider->expects($this->once())
->method('getToken')
diff --git a/tests/lib/Authentication/TwoFactorAuth/Db/ProviderUserAssignmentDaoTest.php b/tests/lib/Authentication/TwoFactorAuth/Db/ProviderUserAssignmentDaoTest.php
index 56acba46ef0..7a1ea64ca9a 100644
--- a/tests/lib/Authentication/TwoFactorAuth/Db/ProviderUserAssignmentDaoTest.php
+++ b/tests/lib/Authentication/TwoFactorAuth/Db/ProviderUserAssignmentDaoTest.php
@@ -35,7 +35,7 @@ class ProviderUserAssignmentDaoTest extends TestCase {
$this->dao = new ProviderUserAssignmentDao($this->dbConn);
}
- public function testGetState() {
+ public function testGetState(): void {
$qb = $this->dbConn->getQueryBuilder();
$q1 = $qb->insert(ProviderUserAssignmentDao::TABLE_NAME)->values([
'provider_id' => $qb->createNamedParameter('twofactor_u2f'),
@@ -59,7 +59,7 @@ class ProviderUserAssignmentDaoTest extends TestCase {
$this->assertEquals($expected, $state);
}
- public function testPersist() {
+ public function testPersist(): void {
$qb = $this->dbConn->getQueryBuilder();
$this->dao->persist('twofactor_totp', 'user123', 0);
@@ -76,7 +76,7 @@ class ProviderUserAssignmentDaoTest extends TestCase {
$this->assertCount(1, $data);
}
- public function testPersistTwice() {
+ public function testPersistTwice(): void {
$qb = $this->dbConn->getQueryBuilder();
$this->dao->persist('twofactor_totp', 'user123', 0);
@@ -95,7 +95,7 @@ class ProviderUserAssignmentDaoTest extends TestCase {
$this->assertCount(1, $data);
}
- public function testPersistSameStateTwice() {
+ public function testPersistSameStateTwice(): void {
$qb = $this->dbConn->getQueryBuilder();
$this->dao->persist('twofactor_totp', 'user123', 1);
@@ -114,7 +114,7 @@ class ProviderUserAssignmentDaoTest extends TestCase {
$this->assertCount(1, $data);
}
- public function testDeleteByUser() {
+ public function testDeleteByUser(): void {
$this->dao->persist('twofactor_fail', 'user1', 1);
$this->dao->persist('twofactor_u2f', 'user1', 1);
$this->dao->persist('twofactor_fail', 'user2', 0);
@@ -143,7 +143,7 @@ class ProviderUserAssignmentDaoTest extends TestCase {
$this->assertCount(2, $statesUser2);
}
- public function testDeleteAll() {
+ public function testDeleteAll(): void {
$this->dao->persist('twofactor_fail', 'user1', 1);
$this->dao->persist('twofactor_u2f', 'user1', 1);
$this->dao->persist('twofactor_fail', 'user2', 0);
diff --git a/tests/lib/Authentication/TwoFactorAuth/EnforcementStateTest.php b/tests/lib/Authentication/TwoFactorAuth/EnforcementStateTest.php
index bf09b3d8ca3..5323a36867a 100644
--- a/tests/lib/Authentication/TwoFactorAuth/EnforcementStateTest.php
+++ b/tests/lib/Authentication/TwoFactorAuth/EnforcementStateTest.php
@@ -17,25 +17,25 @@ use OC\Authentication\TwoFactorAuth\EnforcementState;
use Test\TestCase;
class EnforcementStateTest extends TestCase {
- public function testIsEnforced() {
+ public function testIsEnforced(): void {
$state = new EnforcementState(true);
$this->assertTrue($state->isEnforced());
}
- public function testGetEnforcedGroups() {
+ public function testGetEnforcedGroups(): void {
$state = new EnforcementState(true, ['twofactorers']);
$this->assertEquals(['twofactorers'], $state->getEnforcedGroups());
}
- public function testGetExcludedGroups() {
+ public function testGetExcludedGroups(): void {
$state = new EnforcementState(true, [], ['yoloers']);
$this->assertEquals(['yoloers'], $state->getExcludedGroups());
}
- public function testJsonSerialize() {
+ public function testJsonSerialize(): void {
$state = new EnforcementState(true, ['twofactorers'], ['yoloers']);
$expected = [
'enforced' => true,
diff --git a/tests/lib/Authentication/TwoFactorAuth/ManagerTest.php b/tests/lib/Authentication/TwoFactorAuth/ManagerTest.php
index 6e5e4e1eea1..54ea67d76e4 100644
--- a/tests/lib/Authentication/TwoFactorAuth/ManagerTest.php
+++ b/tests/lib/Authentication/TwoFactorAuth/ManagerTest.php
@@ -135,7 +135,7 @@ class ManagerTest extends TestCase {
]);
}
- public function testIsTwoFactorAuthenticatedEnforced() {
+ public function testIsTwoFactorAuthenticatedEnforced(): void {
$this->mandatoryTwoFactor->expects($this->once())
->method('isEnforcedFor')
->with($this->user)
@@ -146,7 +146,7 @@ class ManagerTest extends TestCase {
$this->assertTrue($enabled);
}
- public function testIsTwoFactorAuthenticatedNoProviders() {
+ public function testIsTwoFactorAuthenticatedNoProviders(): void {
$this->mandatoryTwoFactor->expects($this->once())
->method('isEnforcedFor')
->with($this->user)
@@ -161,7 +161,7 @@ class ManagerTest extends TestCase {
$this->assertFalse($this->manager->isTwoFactorAuthenticated($this->user));
}
- public function testIsTwoFactorAuthenticatedOnlyBackupCodes() {
+ public function testIsTwoFactorAuthenticatedOnlyBackupCodes(): void {
$this->mandatoryTwoFactor->expects($this->once())
->method('isEnforcedFor')
->with($this->user)
@@ -184,7 +184,7 @@ class ManagerTest extends TestCase {
$this->assertFalse($this->manager->isTwoFactorAuthenticated($this->user));
}
- public function testIsTwoFactorAuthenticatedFailingProviders() {
+ public function testIsTwoFactorAuthenticatedFailingProviders(): void {
$this->mandatoryTwoFactor->expects($this->once())
->method('isEnforcedFor')
->with($this->user)
@@ -219,7 +219,7 @@ class ManagerTest extends TestCase {
*
* @dataProvider providerStatesFixData
*/
- public function testIsTwoFactorAuthenticatedFixesProviderStates(bool $providerEnabled, bool $expected) {
+ public function testIsTwoFactorAuthenticatedFixesProviderStates(bool $providerEnabled, bool $expected): void {
$this->providerRegistry->expects($this->once())
->method('getProviderStates')
->willReturn([]); // Nothing registered yet
@@ -251,7 +251,7 @@ class ManagerTest extends TestCase {
$this->assertEquals($expected, $this->manager->isTwoFactorAuthenticated($this->user));
}
- public function testGetProvider() {
+ public function testGetProvider(): void {
$this->providerRegistry->expects($this->once())
->method('getProviderStates')
->with($this->user)
@@ -268,7 +268,7 @@ class ManagerTest extends TestCase {
$this->assertSame($this->fakeProvider, $provider);
}
- public function testGetInvalidProvider() {
+ public function testGetInvalidProvider(): void {
$this->providerRegistry->expects($this->once())
->method('getProviderStates')
->with($this->user)
@@ -283,7 +283,7 @@ class ManagerTest extends TestCase {
$this->assertNull($provider);
}
- public function testGetLoginSetupProviders() {
+ public function testGetLoginSetupProviders(): void {
$provider1 = $this->createMock(IProvider::class);
$provider2 = $this->createMock(IActivatableAtLogin::class);
$this->providerLoader->expects($this->once())
@@ -300,7 +300,7 @@ class ManagerTest extends TestCase {
$this->assertSame($provider2, reset($providers));
}
- public function testGetProviders() {
+ public function testGetProviders(): void {
$this->providerRegistry->expects($this->once())
->method('getProviderStates')
->with($this->user)
@@ -322,7 +322,7 @@ class ManagerTest extends TestCase {
$this->assertFalse($providerSet->isProviderMissing());
}
- public function testGetProvidersOneMissing() {
+ public function testGetProvidersOneMissing(): void {
$this->providerRegistry->expects($this->once())
->method('getProviderStates')
->with($this->user)
@@ -342,7 +342,7 @@ class ManagerTest extends TestCase {
$this->assertTrue($providerSet->isProviderMissing());
}
- public function testVerifyChallenge() {
+ public function testVerifyChallenge(): void {
$this->prepareProviders();
$challenge = 'passme';
@@ -412,7 +412,7 @@ class ManagerTest extends TestCase {
$this->assertTrue($result);
}
- public function testVerifyChallengeInvalidProviderId() {
+ public function testVerifyChallengeInvalidProviderId(): void {
$this->prepareProviders();
$challenge = 'passme';
@@ -425,7 +425,7 @@ class ManagerTest extends TestCase {
$this->assertFalse($this->manager->verifyChallenge('dontexist', $this->user, $challenge));
}
- public function testVerifyInvalidChallenge() {
+ public function testVerifyInvalidChallenge(): void {
$this->prepareProviders();
$challenge = 'dontpassme';
@@ -471,7 +471,7 @@ class ManagerTest extends TestCase {
$this->assertFalse($this->manager->verifyChallenge('email', $this->user, $challenge));
}
- public function testNeedsSecondFactor() {
+ public function testNeedsSecondFactor(): void {
$user = $this->createMock(IUser::class);
$this->session->expects($this->exactly(3))
->method('exists')
@@ -522,7 +522,7 @@ class ManagerTest extends TestCase {
$this->assertTrue($manager->needsSecondFactor($user));
}
- public function testNeedsSecondFactorUserIsNull() {
+ public function testNeedsSecondFactorUserIsNull(): void {
$user = null;
$this->session->expects($this->never())
->method('exists');
@@ -530,7 +530,7 @@ class ManagerTest extends TestCase {
$this->assertFalse($this->manager->needsSecondFactor($user));
}
- public function testNeedsSecondFactorWithNoProviderAvailableAnymore() {
+ public function testNeedsSecondFactorWithNoProviderAvailableAnymore(): void {
$this->prepareNoProviders();
$user = null;
@@ -545,7 +545,7 @@ class ManagerTest extends TestCase {
$this->assertFalse($this->manager->needsSecondFactor($user));
}
- public function testPrepareTwoFactorLogin() {
+ public function testPrepareTwoFactorLogin(): void {
$this->user->method('getUID')
->willReturn('ferdinand');
@@ -575,7 +575,7 @@ class ManagerTest extends TestCase {
$this->manager->prepareTwoFactorLogin($this->user, true);
}
- public function testPrepareTwoFactorLoginDontRemember() {
+ public function testPrepareTwoFactorLoginDontRemember(): void {
$this->user->method('getUID')
->willReturn('ferdinand');
@@ -604,7 +604,7 @@ class ManagerTest extends TestCase {
$this->manager->prepareTwoFactorLogin($this->user, false);
}
- public function testNeedsSecondFactorSessionAuth() {
+ public function testNeedsSecondFactorSessionAuth(): void {
$user = $this->createMock(IUser::class);
$user->method('getUID')
->willReturn('user');
@@ -639,7 +639,7 @@ class ManagerTest extends TestCase {
$this->assertFalse($this->manager->needsSecondFactor($user));
}
- public function testNeedsSecondFactorSessionAuthFailDBPass() {
+ public function testNeedsSecondFactorSessionAuthFailDBPass(): void {
$user = $this->createMock(IUser::class);
$user->method('getUID')
->willReturn('user');
@@ -670,7 +670,7 @@ class ManagerTest extends TestCase {
$this->assertFalse($this->manager->needsSecondFactor($user));
}
- public function testNeedsSecondFactorInvalidToken() {
+ public function testNeedsSecondFactorInvalidToken(): void {
$this->prepareNoProviders();
$user = $this->createMock(IUser::class);
@@ -691,7 +691,7 @@ class ManagerTest extends TestCase {
$this->assertFalse($this->manager->needsSecondFactor($user));
}
- public function testNeedsSecondFactorAppPassword() {
+ public function testNeedsSecondFactorAppPassword(): void {
$user = $this->createMock(IUser::class);
$this->session->method('exists')
->willReturnMap([
diff --git a/tests/lib/Authentication/TwoFactorAuth/MandatoryTwoFactorTest.php b/tests/lib/Authentication/TwoFactorAuth/MandatoryTwoFactorTest.php
index 1d6127fa928..d2ecd3c509c 100644
--- a/tests/lib/Authentication/TwoFactorAuth/MandatoryTwoFactorTest.php
+++ b/tests/lib/Authentication/TwoFactorAuth/MandatoryTwoFactorTest.php
@@ -36,7 +36,7 @@ class MandatoryTwoFactorTest extends TestCase {
$this->mandatoryTwoFactor = new MandatoryTwoFactor($this->config, $this->groupManager);
}
- public function testIsNotEnforced() {
+ public function testIsNotEnforced(): void {
$this->config
->method('getSystemValue')
->willReturnMap([
@@ -50,7 +50,7 @@ class MandatoryTwoFactorTest extends TestCase {
$this->assertFalse($state->isEnforced());
}
- public function testIsEnforced() {
+ public function testIsEnforced(): void {
$this->config
->method('getSystemValue')
->willReturnMap([
@@ -64,7 +64,7 @@ class MandatoryTwoFactorTest extends TestCase {
$this->assertTrue($state->isEnforced());
}
- public function testIsNotEnforcedForAnybody() {
+ public function testIsNotEnforcedForAnybody(): void {
$user = $this->createMock(IUser::class);
$user->method('getUID')->willReturn('user123');
$this->config
@@ -80,7 +80,7 @@ class MandatoryTwoFactorTest extends TestCase {
$this->assertFalse($isEnforced);
}
- public function testIsEnforcedForAGroupMember() {
+ public function testIsEnforcedForAGroupMember(): void {
$user = $this->createMock(IUser::class);
$user->method('getUID')->willReturn('user123');
$this->config
@@ -100,7 +100,7 @@ class MandatoryTwoFactorTest extends TestCase {
$this->assertTrue($isEnforced);
}
- public function testIsEnforcedForOtherGroups() {
+ public function testIsEnforcedForOtherGroups(): void {
$user = $this->createMock(IUser::class);
$user->method('getUID')->willReturn('user123');
$this->config
@@ -118,7 +118,7 @@ class MandatoryTwoFactorTest extends TestCase {
$this->assertFalse($isEnforced);
}
- public function testIsEnforcedButMemberOfExcludedGroup() {
+ public function testIsEnforcedButMemberOfExcludedGroup(): void {
$user = $this->createMock(IUser::class);
$user->method('getUID')->willReturn('user123');
$this->config
@@ -138,7 +138,7 @@ class MandatoryTwoFactorTest extends TestCase {
$this->assertFalse($isEnforced);
}
- public function testSetEnforced() {
+ public function testSetEnforced(): void {
$this->config
->expects($this->exactly(3))
->method('setSystemValue')
@@ -151,7 +151,7 @@ class MandatoryTwoFactorTest extends TestCase {
$this->mandatoryTwoFactor->setState(new EnforcementState(true));
}
- public function testSetEnforcedForGroups() {
+ public function testSetEnforcedForGroups(): void {
$this->config
->expects($this->exactly(3))
->method('setSystemValue')
@@ -164,7 +164,7 @@ class MandatoryTwoFactorTest extends TestCase {
$this->mandatoryTwoFactor->setState(new EnforcementState(true, ['twofactorers'], ['yoloers']));
}
- public function testSetNotEnforced() {
+ public function testSetNotEnforced(): void {
$this->config
->expects($this->exactly(3))
->method('setSystemValue')
diff --git a/tests/lib/Authentication/TwoFactorAuth/ProviderLoaderTest.php b/tests/lib/Authentication/TwoFactorAuth/ProviderLoaderTest.php
index bbbb8e8e55a..6eb3b7dfb26 100644
--- a/tests/lib/Authentication/TwoFactorAuth/ProviderLoaderTest.php
+++ b/tests/lib/Authentication/TwoFactorAuth/ProviderLoaderTest.php
@@ -47,7 +47,7 @@ class ProviderLoaderTest extends TestCase {
}
- public function testFailHardIfProviderCanNotBeLoaded() {
+ public function testFailHardIfProviderCanNotBeLoaded(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Could not load two-factor auth provider \\OCA\\MyFaulty2faApp\\DoesNotExist');
@@ -69,7 +69,7 @@ class ProviderLoaderTest extends TestCase {
$this->loader->getProviders($this->user);
}
- public function testGetProviders() {
+ public function testGetProviders(): void {
$provider = $this->createMock(IProvider::class);
$provider->method('getId')->willReturn('test');
\OC::$server->registerService('\\OCA\\TwoFactorTest\\Provider', function () use ($provider) {
@@ -93,7 +93,7 @@ class ProviderLoaderTest extends TestCase {
$this->assertSame($provider, $providers['test']);
}
- public function testGetProvidersBootstrap() {
+ public function testGetProvidersBootstrap(): void {
$provider = $this->createMock(IProvider::class);
$provider->method('getId')->willReturn('test');
diff --git a/tests/lib/Authentication/TwoFactorAuth/ProviderManagerTest.php b/tests/lib/Authentication/TwoFactorAuth/ProviderManagerTest.php
index 0e8cf122080..34248f11f21 100644
--- a/tests/lib/Authentication/TwoFactorAuth/ProviderManagerTest.php
+++ b/tests/lib/Authentication/TwoFactorAuth/ProviderManagerTest.php
@@ -42,14 +42,14 @@ class ProviderManagerTest extends TestCase {
}
- public function testTryEnableInvalidProvider() {
+ public function testTryEnableInvalidProvider(): void {
$this->expectException(\OC\Authentication\Exceptions\InvalidProviderException::class);
$user = $this->createMock(IUser::class);
$this->providerManager->tryEnableProviderFor('none', $user);
}
- public function testTryEnableUnsupportedProvider() {
+ public function testTryEnableUnsupportedProvider(): void {
$user = $this->createMock(IUser::class);
$provider = $this->createMock(IProvider::class);
$this->providerLoader->expects($this->once())
@@ -66,7 +66,7 @@ class ProviderManagerTest extends TestCase {
$this->assertFalse($res);
}
- public function testTryEnableProvider() {
+ public function testTryEnableProvider(): void {
$user = $this->createMock(IUser::class);
$provider = $this->createMock(IActivatableByAdmin::class);
$this->providerLoader->expects($this->once())
@@ -88,14 +88,14 @@ class ProviderManagerTest extends TestCase {
}
- public function testTryDisableInvalidProvider() {
+ public function testTryDisableInvalidProvider(): void {
$this->expectException(\OC\Authentication\Exceptions\InvalidProviderException::class);
$user = $this->createMock(IUser::class);
$this->providerManager->tryDisableProviderFor('none', $user);
}
- public function testTryDisableUnsupportedProvider() {
+ public function testTryDisableUnsupportedProvider(): void {
$user = $this->createMock(IUser::class);
$provider = $this->createMock(IProvider::class);
$this->providerLoader->expects($this->once())
@@ -112,7 +112,7 @@ class ProviderManagerTest extends TestCase {
$this->assertFalse($res);
}
- public function testTryDisableProvider() {
+ public function testTryDisableProvider(): void {
$user = $this->createMock(IUser::class);
$provider = $this->createMock(IDeactivatableByAdmin::class);
$this->providerLoader->expects($this->once())
diff --git a/tests/lib/Authentication/TwoFactorAuth/ProviderSetTest.php b/tests/lib/Authentication/TwoFactorAuth/ProviderSetTest.php
index b6b9640cd9b..568b83567f8 100644
--- a/tests/lib/Authentication/TwoFactorAuth/ProviderSetTest.php
+++ b/tests/lib/Authentication/TwoFactorAuth/ProviderSetTest.php
@@ -18,7 +18,7 @@ class ProviderSetTest extends TestCase {
/** @var ProviderSet */
private $providerSet;
- public function testIndexesProviders() {
+ public function testIndexesProviders(): void {
$p1 = $this->createMock(IProvider::class);
$p1->method('getId')->willReturn('p1');
$p2 = $this->createMock(IProvider::class);
@@ -33,7 +33,7 @@ class ProviderSetTest extends TestCase {
$this->assertEquals($expected, $set->getProviders());
}
- public function testGet3rdPartyProviders() {
+ public function testGet3rdPartyProviders(): void {
$p1 = $this->createMock(IProvider::class);
$p1->method('getId')->willReturn('p1');
$p2 = $this->createMock(IProvider::class);
@@ -50,7 +50,7 @@ class ProviderSetTest extends TestCase {
$this->assertEquals($expected, $set->getPrimaryProviders());
}
- public function testGetProvider() {
+ public function testGetProvider(): void {
$p1 = $this->createMock(IProvider::class);
$p1->method('getId')->willReturn('p1');
@@ -60,14 +60,14 @@ class ProviderSetTest extends TestCase {
$this->assertEquals($p1, $provider);
}
- public function testGetProviderNotFound() {
+ public function testGetProviderNotFound(): void {
$set = new ProviderSet([], false);
$provider = $set->getProvider('p1');
$this->assertNull($provider);
}
- public function testIsProviderMissing() {
+ public function testIsProviderMissing(): void {
$set = new ProviderSet([], true);
$this->assertTrue($set->isProviderMissing());
diff --git a/tests/lib/Authentication/TwoFactorAuth/RegistryTest.php b/tests/lib/Authentication/TwoFactorAuth/RegistryTest.php
index 7485fe377ee..77e619d03a2 100644
--- a/tests/lib/Authentication/TwoFactorAuth/RegistryTest.php
+++ b/tests/lib/Authentication/TwoFactorAuth/RegistryTest.php
@@ -42,7 +42,7 @@ class RegistryTest extends TestCase {
$this->registry = new Registry($this->dao, $this->dispatcher);
}
- public function testGetProviderStates() {
+ public function testGetProviderStates(): void {
$user = $this->createMock(IUser::class);
$user->expects($this->once())->method('getUID')->willReturn('user123');
$state = [
@@ -55,7 +55,7 @@ class RegistryTest extends TestCase {
$this->assertEquals($state, $actual);
}
- public function testEnableProvider() {
+ public function testEnableProvider(): void {
$user = $this->createMock(IUser::class);
$provider = $this->createMock(IProvider::class);
$user->expects($this->once())->method('getUID')->willReturn('user123');
@@ -81,7 +81,7 @@ class RegistryTest extends TestCase {
$this->registry->enableProviderFor($provider, $user);
}
- public function testDisableProvider() {
+ public function testDisableProvider(): void {
$user = $this->createMock(IUser::class);
$provider = $this->createMock(IProvider::class);
$user->expects($this->once())->method('getUID')->willReturn('user123');
@@ -108,7 +108,7 @@ class RegistryTest extends TestCase {
$this->registry->disableProviderFor($provider, $user);
}
- public function testDeleteUserData() {
+ public function testDeleteUserData(): void {
$user = $this->createMock(IUser::class);
$user->expects($this->once())->method('getUID')->willReturn('user123');
$this->dao->expects($this->once())
@@ -129,7 +129,7 @@ class RegistryTest extends TestCase {
$this->registry->deleteUserData($user);
}
- public function testCleanUp() {
+ public function testCleanUp(): void {
$this->dao->expects($this->once())
->method('deleteAll')
->with('twofactor_u2f');
diff --git a/tests/lib/AutoLoaderTest.php b/tests/lib/AutoLoaderTest.php
index 6992afd19d3..f16fb44cb5a 100644
--- a/tests/lib/AutoLoaderTest.php
+++ b/tests/lib/AutoLoaderTest.php
@@ -18,40 +18,40 @@ class AutoLoaderTest extends TestCase {
$this->loader = new \OC\AutoLoader([]);
}
- public function testLegacyPath() {
+ public function testLegacyPath(): void {
$this->assertEquals([
\OC::$SERVERROOT . '/lib/private/legacy/files.php',
], $this->loader->findClass('OC_Files'));
}
- public function testLoadTestTestCase() {
+ public function testLoadTestTestCase(): void {
$this->assertEquals([
\OC::$SERVERROOT . '/tests/lib/TestCase.php'
], $this->loader->findClass(\Test\TestCase::class));
}
- public function testLoadCore() {
+ public function testLoadCore(): void {
$this->assertEquals([
\OC::$SERVERROOT . '/lib/private/legacy/foo/bar.php',
], $this->loader->findClass('OC_Foo_Bar'));
}
- public function testLoadPublicNamespace() {
+ public function testLoadPublicNamespace(): void {
$this->assertEquals([], $this->loader->findClass('OCP\Foo\Bar'));
}
- public function testLoadAppNamespace() {
+ 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() {
+ public function testLoadCoreNamespaceCore(): void {
$this->assertEquals([], $this->loader->findClass('OC\Core\Foo\Bar'));
}
- public function testLoadCoreNamespaceSettings() {
+ 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 6995edb8004..25e8e1563f5 100644
--- a/tests/lib/Avatar/AvatarManagerTest.php
+++ b/tests/lib/Avatar/AvatarManagerTest.php
@@ -71,7 +71,7 @@ class AvatarManagerTest extends \Test\TestCase {
);
}
- public function testGetAvatarInvalidUser() {
+ public function testGetAvatarInvalidUser(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('user does not exist');
@@ -84,7 +84,7 @@ class AvatarManagerTest extends \Test\TestCase {
$this->avatarManager->getAvatar('invalidUser');
}
- public function testGetAvatarForSelf() {
+ public function testGetAvatarForSelf(): void {
$user = $this->createMock(User::class);
$user
->expects($this->any())
@@ -139,7 +139,7 @@ class AvatarManagerTest extends \Test\TestCase {
$this->assertEquals($expected, $this->avatarManager->getAvatar('valid-user'));
}
- public function testGetAvatarValidUserDifferentCasing() {
+ public function testGetAvatarValidUserDifferentCasing(): void {
$user = $this->createMock(User::class);
$this->userManager->expects($this->once())
->method('get')
@@ -206,7 +206,7 @@ class AvatarManagerTest extends \Test\TestCase {
/**
* @dataProvider dataGetAvatarScopes
*/
- public function testGetAvatarScopes($avatarScope, $isPublicCall, $isKnownUser, $expectedPlaceholder) {
+ public function testGetAvatarScopes($avatarScope, $isPublicCall, $isKnownUser, $expectedPlaceholder): void {
if ($isPublicCall) {
$requestingUser = null;
} else {
diff --git a/tests/lib/Avatar/GuestAvatarTest.php b/tests/lib/Avatar/GuestAvatarTest.php
index e71cabaa624..8188684b51f 100644
--- a/tests/lib/Avatar/GuestAvatarTest.php
+++ b/tests/lib/Avatar/GuestAvatarTest.php
@@ -44,7 +44,7 @@ class GuestAvatarTest extends TestCase {
* For the test a static name "einstein" is used and
* the generated image is compared with an expected one.
*/
- public function testGet() {
+ public function testGet(): void {
$this->markTestSkipped('TODO: Disable because fails on drone');
$avatar = $this->guestAvatar->getFile(32);
self::assertInstanceOf(InMemoryFile::class, $avatar);
@@ -59,7 +59,7 @@ class GuestAvatarTest extends TestCase {
*
* @return void
*/
- public function testIsCustomAvatar() {
+ public function testIsCustomAvatar(): void {
self::assertFalse($this->guestAvatar->isCustomAvatar());
}
}
diff --git a/tests/lib/Avatar/UserAvatarTest.php b/tests/lib/Avatar/UserAvatarTest.php
index fde2ccef5c3..0e2bfe6872f 100644
--- a/tests/lib/Avatar/UserAvatarTest.php
+++ b/tests/lib/Avatar/UserAvatarTest.php
@@ -50,7 +50,7 @@ class UserAvatarTest extends \Test\TestCase {
];
}
- public function testGetNoAvatar() {
+ public function testGetNoAvatar(): void {
$file = $this->createMock(ISimpleFile::class);
$this->folder->method('newFile')
->willReturn($file);
@@ -85,7 +85,7 @@ class UserAvatarTest extends \Test\TestCase {
$this->assertTrue($result->valid());
}
- public function testGetAvatarSizeMatch() {
+ public function testGetAvatarSizeMatch(): void {
$this->folder->method('fileExists')
->willReturnMap([
['avatar.jpg', true],
@@ -103,7 +103,7 @@ class UserAvatarTest extends \Test\TestCase {
$this->assertEquals($expected->data(), $this->avatar->get(128)->data());
}
- public function testGetAvatarSizeMinusOne() {
+ public function testGetAvatarSizeMinusOne(): void {
$this->folder->method('fileExists')
->willReturnMap([
['avatar.jpg', true],
@@ -120,7 +120,7 @@ class UserAvatarTest extends \Test\TestCase {
$this->assertEquals($expected->data(), $this->avatar->get(-1)->data());
}
- public function testGetAvatarNoSizeMatch() {
+ public function testGetAvatarNoSizeMatch(): void {
$this->folder->method('fileExists')
->willReturnMap([
['avatar.jpg', false],
@@ -164,11 +164,11 @@ class UserAvatarTest extends \Test\TestCase {
$this->assertEquals($expected2->data(), $this->avatar->get(32)->data());
}
- public function testExistsNo() {
+ public function testExistsNo(): void {
$this->assertFalse($this->avatar->exists());
}
- public function testExiststJPG() {
+ public function testExiststJPG(): void {
$this->folder->method('fileExists')
->willReturnMap([
['avatar.jpg', true],
@@ -177,7 +177,7 @@ class UserAvatarTest extends \Test\TestCase {
$this->assertTrue($this->avatar->exists());
}
- public function testExistsPNG() {
+ public function testExistsPNG(): void {
$this->folder->method('fileExists')
->willReturnMap([
['avatar.jpg', false],
@@ -186,7 +186,7 @@ class UserAvatarTest extends \Test\TestCase {
$this->assertTrue($this->avatar->exists());
}
- public function testSetAvatar() {
+ public function testSetAvatar(): void {
$avatarFileJPG = $this->createMock(File::class);
$avatarFileJPG->method('getName')
->willReturn('avatar.jpg');
@@ -232,7 +232,7 @@ class UserAvatarTest extends \Test\TestCase {
$this->avatar->set($image->data());
}
- public function testGenerateSvgAvatar() {
+ public function testGenerateSvgAvatar(): void {
$avatar = $this->invokePrivate($this->avatar, 'getAvatarVector', [64, false]);
$svg = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>
@@ -247,7 +247,7 @@ class UserAvatarTest extends \Test\TestCase {
/**
* @dataProvider avatarTextData
*/
- public function testGetAvatarText($displayName, $expectedAvatarText) {
+ public function testGetAvatarText($displayName, $expectedAvatarText): void {
$user = $this->getUserWithDisplayName($displayName);
$avatar = $this->getUserAvatar($user);
@@ -255,12 +255,12 @@ class UserAvatarTest extends \Test\TestCase {
$this->assertEquals($expectedAvatarText, $avatarText);
}
- public function testHashToInt() {
+ public function testHashToInt(): void {
$hashToInt = $this->invokePrivate($this->avatar, 'hashToInt', ['abcdef', 18]);
$this->assertTrue(gettype($hashToInt) === 'integer');
}
- public function testMixPalette() {
+ public function testMixPalette(): void {
$colorFrom = new \OCP\Color(0, 0, 0);
$colorTo = new \OCP\Color(6, 12, 18);
$steps = 6;
diff --git a/tests/lib/BackgroundJob/JobListTest.php b/tests/lib/BackgroundJob/JobListTest.php
index 7dfaf158f85..42ce5c628cd 100644
--- a/tests/lib/BackgroundJob/JobListTest.php
+++ b/tests/lib/BackgroundJob/JobListTest.php
@@ -87,7 +87,7 @@ class JobListTest extends TestCase {
* @dataProvider argumentProvider
* @param $argument
*/
- public function testAddRemove($argument) {
+ public function testAddRemove($argument): void {
$existingJobs = $this->getAllSorted();
$job = new TestJob();
$this->instance->add($job, $argument);
@@ -109,7 +109,7 @@ class JobListTest extends TestCase {
* @dataProvider argumentProvider
* @param $argument
*/
- public function testRemoveDifferentArgument($argument) {
+ public function testRemoveDifferentArgument($argument): void {
$existingJobs = $this->getAllSorted();
$job = new TestJob();
$this->instance->add($job, $argument);
@@ -130,7 +130,7 @@ class JobListTest extends TestCase {
* @dataProvider argumentProvider
* @param $argument
*/
- public function testHas($argument) {
+ public function testHas($argument): void {
$job = new TestJob();
$this->assertFalse($this->instance->has($job, $argument));
$this->instance->add($job, $argument);
@@ -146,7 +146,7 @@ class JobListTest extends TestCase {
* @dataProvider argumentProvider
* @param $argument
*/
- public function testHasDifferentArgument($argument) {
+ public function testHasDifferentArgument($argument): void {
$job = new TestJob();
$this->instance->add($job, $argument);
@@ -170,7 +170,7 @@ class JobListTest extends TestCase {
$query->execute();
}
- public function testGetNext() {
+ public function testGetNext(): void {
$job = new TestJob();
$this->createTempJob(get_class($job), 1, 0, 12345);
$this->createTempJob(get_class($job), 2, 0, 12346);
@@ -186,7 +186,7 @@ class JobListTest extends TestCase {
$this->assertEquals($savedJob1, $nextJob);
}
- public function testGetNextSkipReserved() {
+ public function testGetNextSkipReserved(): void {
$job = new TestJob();
$this->createTempJob(get_class($job), 1, 123456789, 12345);
$this->createTempJob(get_class($job), 2, 0, 12346);
@@ -200,7 +200,7 @@ class JobListTest extends TestCase {
$this->assertEquals(2, $nextJob->getArgument());
}
- public function testGetNextSkipNonExisting() {
+ public function testGetNextSkipNonExisting(): void {
$job = new TestJob();
$this->createTempJob('\OC\Non\Existing\Class', 1, 0, 12345);
$this->createTempJob(get_class($job), 2, 0, 12346);
@@ -218,7 +218,7 @@ class JobListTest extends TestCase {
* @dataProvider argumentProvider
* @param $argument
*/
- public function testGetById($argument) {
+ public function testGetById($argument): void {
$job = new TestJob();
$this->instance->add($job, $argument);
@@ -229,7 +229,7 @@ class JobListTest extends TestCase {
$this->assertEquals($addedJob, $this->instance->getById($addedJob->getId()));
}
- public function testSetLastRun() {
+ public function testSetLastRun(): void {
$job = new TestJob();
$this->instance->add($job);
@@ -247,7 +247,7 @@ class JobListTest extends TestCase {
$this->assertLessThanOrEqual($timeEnd, $addedJob->getLastRun());
}
- public function testHasReservedJobs() {
+ public function testHasReservedJobs(): void {
$this->clearJobsList();
$this->timeFactory->expects($this->atLeastOnce())
@@ -278,7 +278,7 @@ class JobListTest extends TestCase {
$this->assertTrue($this->instance->hasReservedJob(TestJob::class));
}
- public function testHasReservedJobsAndParallelAwareJob() {
+ public function testHasReservedJobsAndParallelAwareJob(): void {
$this->clearJobsList();
$this->timeFactory->expects($this->atLeastOnce())
diff --git a/tests/lib/BackgroundJob/JobTest.php b/tests/lib/BackgroundJob/JobTest.php
index fa89a06c8f5..9024742f432 100644
--- a/tests/lib/BackgroundJob/JobTest.php
+++ b/tests/lib/BackgroundJob/JobTest.php
@@ -24,7 +24,7 @@ class JobTest extends \Test\TestCase {
\OC::$server->registerService(LoggerInterface::class, fn ($c) => $this->logger);
}
- public function testRemoveAfterException() {
+ public function testRemoveAfterException(): void {
$jobList = new DummyJobList();
$e = new \Exception();
$job = new TestJob($this->timeFactory, $this, function () use ($e) {
@@ -41,7 +41,7 @@ class JobTest extends \Test\TestCase {
$this->assertCount(1, $jobList->getAll());
}
- public function testRemoveAfterError() {
+ public function testRemoveAfterError(): void {
$jobList = new DummyJobList();
$job = new TestJob($this->timeFactory, $this, function () {
$test = null;
diff --git a/tests/lib/BackgroundJob/QueuedJobTest.php b/tests/lib/BackgroundJob/QueuedJobTest.php
index ab4bacb201e..893f476bb5f 100644
--- a/tests/lib/BackgroundJob/QueuedJobTest.php
+++ b/tests/lib/BackgroundJob/QueuedJobTest.php
@@ -27,7 +27,7 @@ class QueuedJobTest extends \Test\TestCase {
$this->jobList = new DummyJobList();
}
- public function testJobShouldBeRemovedNew() {
+ public function testJobShouldBeRemovedNew(): void {
$job = new TestQueuedJobNew(\OCP\Server::get(ITimeFactory::class));
$job->setId(42);
$this->jobList->add($job);
diff --git a/tests/lib/BackgroundJob/TimedJobTest.php b/tests/lib/BackgroundJob/TimedJobTest.php
index 0ae245d1ff8..ad0f54ebe4a 100644
--- a/tests/lib/BackgroundJob/TimedJobTest.php
+++ b/tests/lib/BackgroundJob/TimedJobTest.php
@@ -34,7 +34,7 @@ class TimedJobTest extends \Test\TestCase {
$this->time = \OCP\Server::get(ITimeFactory::class);
}
- public function testShouldRunAfterIntervalNew() {
+ public function testShouldRunAfterIntervalNew(): void {
$job = new TestTimedJobNew($this->time);
$job->setId(42);
$this->jobList->add($job);
@@ -44,7 +44,7 @@ class TimedJobTest extends \Test\TestCase {
$this->assertTrue($job->ran);
}
- public function testShouldNotRunWithinIntervalNew() {
+ public function testShouldNotRunWithinIntervalNew(): void {
$job = new TestTimedJobNew($this->time);
$job->setId(42);
$this->jobList->add($job);
@@ -54,7 +54,7 @@ class TimedJobTest extends \Test\TestCase {
$this->assertFalse($job->ran);
}
- public function testShouldNotTwiceNew() {
+ public function testShouldNotTwiceNew(): void {
$job = new TestTimedJobNew($this->time);
$job->setId(42);
$this->jobList->add($job);
diff --git a/tests/lib/Cache/CappedMemoryCacheTest.php b/tests/lib/Cache/CappedMemoryCacheTest.php
index 6d1c7e6e372..f2ed1a5ee0d 100644
--- a/tests/lib/Cache/CappedMemoryCacheTest.php
+++ b/tests/lib/Cache/CappedMemoryCacheTest.php
@@ -18,7 +18,7 @@ class CappedMemoryCacheTest extends TestCache {
$this->instance = new \OCP\Cache\CappedMemoryCache();
}
- public function testSetOverCap() {
+ public function testSetOverCap(): void {
$instance = new \OCP\Cache\CappedMemoryCache(3);
$instance->set('1', 'a');
@@ -34,7 +34,7 @@ class CappedMemoryCacheTest extends TestCache {
$this->assertTrue($instance->hasKey('5'));
}
- public function testClear() {
+ public function testClear(): void {
$value = 'ipsum lorum';
$this->instance->set('1_value1', $value);
$this->instance->set('1_value2', $value);
@@ -48,7 +48,7 @@ class CappedMemoryCacheTest extends TestCache {
$this->assertFalse($this->instance->hasKey('3_value1'));
}
- public function testIndirectSet() {
+ public function testIndirectSet(): void {
$this->instance->set('array', []);
$this->instance['array'][] = 'foo';
diff --git a/tests/lib/Cache/FileCacheTest.php b/tests/lib/Cache/FileCacheTest.php
index ef738eaaacf..1d12147af0d 100644
--- a/tests/lib/Cache/FileCacheTest.php
+++ b/tests/lib/Cache/FileCacheTest.php
@@ -97,7 +97,7 @@ class FileCacheTest extends TestCache {
return $mockStorage;
}
- public function testGarbageCollectOldKeys() {
+ public function testGarbageCollectOldKeys(): void {
$mockStorage = $this->setupMockStorage();
$mockStorage->expects($this->atLeastOnce())
@@ -112,7 +112,7 @@ class FileCacheTest extends TestCache {
$this->instance->gc();
}
- public function testGarbageCollectLeaveRecentKeys() {
+ public function testGarbageCollectLeaveRecentKeys(): void {
$mockStorage = $this->setupMockStorage();
$mockStorage->expects($this->atLeastOnce())
@@ -135,7 +135,7 @@ class FileCacheTest extends TestCache {
/**
* @dataProvider lockExceptionProvider
*/
- public function testGarbageCollectIgnoreLockedKeys($testException) {
+ public function testGarbageCollectIgnoreLockedKeys($testException): void {
$mockStorage = $this->setupMockStorage();
$mockStorage->expects($this->atLeastOnce())
diff --git a/tests/lib/Cache/TestCache.php b/tests/lib/Cache/TestCache.php
index 1ed52ad5170..3245cd90a38 100644
--- a/tests/lib/Cache/TestCache.php
+++ b/tests/lib/Cache/TestCache.php
@@ -21,7 +21,7 @@ abstract class TestCache extends \Test\TestCase {
parent::tearDown();
}
- public function testSimple() {
+ public function testSimple(): void {
$this->assertNull($this->instance->get('value1'));
$this->assertFalse($this->instance->hasKey('value1'));
@@ -50,7 +50,7 @@ abstract class TestCache extends \Test\TestCase {
$this->assertFalse($this->instance->hasKey('value1'));
}
- public function testClear() {
+ public function testClear(): void {
$value = 'ipsum lorum';
$this->instance->set('1_value1', $value . '1');
$this->instance->set('1_value2', $value . '2');
diff --git a/tests/lib/Calendar/ManagerTest.php b/tests/lib/Calendar/ManagerTest.php
index 93fa21cf174..3d1a46d3f2a 100644
--- a/tests/lib/Calendar/ManagerTest.php
+++ b/tests/lib/Calendar/ManagerTest.php
@@ -60,7 +60,7 @@ class ManagerTest extends TestCase {
/**
* @dataProvider searchProvider
*/
- public function testSearch($search1, $search2, $expected) {
+ public function testSearch($search1, $search2, $expected): void {
/** @var ICalendar | MockObject $calendar1 */
$calendar1 = $this->createMock(ICalendar::class);
$calendar1->method('getKey')->willReturn('simple:1');
@@ -87,7 +87,7 @@ class ManagerTest extends TestCase {
/**
* @dataProvider searchProvider
*/
- public function testSearchOptions($search1, $search2, $expected) {
+ public function testSearchOptions($search1, $search2, $expected): void {
/** @var ICalendar | MockObject $calendar1 */
$calendar1 = $this->createMock(ICalendar::class);
$calendar1->method('getKey')->willReturn('simple:1');
@@ -168,7 +168,7 @@ class ManagerTest extends TestCase {
];
}
- public function testRegisterUnregister() {
+ public function testRegisterUnregister(): void {
/** @var ICalendar | MockObject $calendar1 */
$calendar1 = $this->createMock(ICalendar::class);
$calendar1->method('getKey')->willReturn('key1');
@@ -192,7 +192,7 @@ class ManagerTest extends TestCase {
$this->assertContains($calendar2, $result);
}
- public function testGetCalendars() {
+ public function testGetCalendars(): void {
/** @var ICalendar | MockObject $calendar1 */
$calendar1 = $this->createMock(ICalendar::class);
$calendar1->method('getKey')->willReturn('key1');
@@ -216,12 +216,12 @@ class ManagerTest extends TestCase {
$this->assertCount(0, $result);
}
- public function testEnabledIfNot() {
+ public function testEnabledIfNot(): void {
$isEnabled = $this->manager->isEnabled();
$this->assertFalse($isEnabled);
}
- public function testIfEnabledIfSo() {
+ public function testIfEnabledIfSo(): void {
/** @var ICalendar | MockObject $calendar */
$calendar = $this->createMock(ICalendar::class);
$this->manager->registerCalendar($calendar);
diff --git a/tests/lib/CapabilitiesManagerTest.php b/tests/lib/CapabilitiesManagerTest.php
index 14b83e3dda3..23909a91c5a 100644
--- a/tests/lib/CapabilitiesManagerTest.php
+++ b/tests/lib/CapabilitiesManagerTest.php
@@ -29,7 +29,7 @@ class CapabilitiesManagerTest extends TestCase {
/**
* Test no capabilities
*/
- public function testNoCapabilities() {
+ public function testNoCapabilities(): void {
$res = $this->manager->getCapabilities();
$this->assertEmpty($res);
}
@@ -37,7 +37,7 @@ class CapabilitiesManagerTest extends TestCase {
/**
* Test a valid capabilitie
*/
- public function testValidCapability() {
+ public function testValidCapability(): void {
$this->manager->registerCapability(function () {
return new SimpleCapability();
});
@@ -49,7 +49,7 @@ class CapabilitiesManagerTest extends TestCase {
/**
* Test a public capabilitie
*/
- public function testPublicCapability() {
+ public function testPublicCapability(): void {
$this->manager->registerCapability(function () {
return new PublicSimpleCapability1();
});
@@ -67,7 +67,7 @@ class CapabilitiesManagerTest extends TestCase {
/**
* Test that we need something that implents ICapability
*/
- public function testNoICapability() {
+ public function testNoICapability(): void {
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('The given Capability (Test\\NoCapability) does not implement the ICapability interface');
@@ -82,7 +82,7 @@ class CapabilitiesManagerTest extends TestCase {
/**
* Test a bunch of merged Capabilities
*/
- public function testMergedCapabilities() {
+ public function testMergedCapabilities(): void {
$this->manager->registerCapability(function () {
return new SimpleCapability();
});
@@ -108,7 +108,7 @@ class CapabilitiesManagerTest extends TestCase {
/**
* Test deep identical capabilities
*/
- public function testDeepIdenticalCapabilities() {
+ public function testDeepIdenticalCapabilities(): void {
$this->manager->registerCapability(function () {
return new DeepCapability();
});
@@ -128,7 +128,7 @@ class CapabilitiesManagerTest extends TestCase {
$this->assertEquals($expected, $res);
}
- public function testInvalidCapability() {
+ public function testInvalidCapability(): void {
$this->manager->registerCapability(function () {
throw new QueryException();
});
diff --git a/tests/lib/Collaboration/Collaborators/GroupPluginTest.php b/tests/lib/Collaboration/Collaborators/GroupPluginTest.php
index f9ac2c408db..e52ae95bf34 100644
--- a/tests/lib/Collaboration/Collaborators/GroupPluginTest.php
+++ b/tests/lib/Collaboration/Collaborators/GroupPluginTest.php
@@ -441,7 +441,7 @@ class GroupPluginTest extends TestCase {
array $expected,
bool $reachedEnd,
$singleGroup
- ) {
+ ): void {
$this->config->expects($this->any())
->method('getAppValue')
->willReturnCallback(
diff --git a/tests/lib/Collaboration/Collaborators/LookupPluginTest.php b/tests/lib/Collaboration/Collaborators/LookupPluginTest.php
index 631d6ce0296..b54ca3ee4c3 100644
--- a/tests/lib/Collaboration/Collaborators/LookupPluginTest.php
+++ b/tests/lib/Collaboration/Collaborators/LookupPluginTest.php
@@ -69,7 +69,7 @@ class LookupPluginTest extends TestCase {
);
}
- public function testSearchNoLookupServerURI() {
+ public function testSearchNoLookupServerURI(): void {
$this->config->expects($this->once())
->method('getAppValue')
->with('files_sharing', 'lookupServerEnabled', 'yes')
@@ -98,7 +98,7 @@ class LookupPluginTest extends TestCase {
$this->plugin->search('foobar', 10, 0, $searchResult);
}
- public function testSearchNoInternet() {
+ public function testSearchNoInternet(): void {
$this->config->expects($this->once())
->method('getAppValue')
->with('files_sharing', 'lookupServerEnabled', 'yes')
@@ -126,7 +126,7 @@ class LookupPluginTest extends TestCase {
* @dataProvider searchDataProvider
* @param array $searchParams
*/
- public function testSearch(array $searchParams) {
+ public function testSearch(array $searchParams): void {
$type = new SearchResultType('lookup');
/** @var ISearchResult|MockObject $searchResult */
@@ -189,7 +189,7 @@ class LookupPluginTest extends TestCase {
* @param bool $GSEnabled
* @param bool $LookupEnabled
*/
- public function testSearchEnableDisableLookupServer(array $searchParams, $GSEnabled, $LookupEnabled) {
+ public function testSearchEnableDisableLookupServer(array $searchParams, $GSEnabled, $LookupEnabled): void {
$type = new SearchResultType('lookup');
/** @var ISearchResult|MockObject $searchResult */
@@ -258,7 +258,7 @@ class LookupPluginTest extends TestCase {
}
- public function testSearchLookupServerDisabled() {
+ public function testSearchLookupServerDisabled(): void {
$this->config->expects($this->once())
->method('getAppValue')
->with('files_sharing', 'lookupServerEnabled', 'yes')
diff --git a/tests/lib/Collaboration/Collaborators/MailPluginTest.php b/tests/lib/Collaboration/Collaborators/MailPluginTest.php
index 251b9905904..8ec1bcdeec0 100644
--- a/tests/lib/Collaboration/Collaborators/MailPluginTest.php
+++ b/tests/lib/Collaboration/Collaborators/MailPluginTest.php
@@ -94,7 +94,7 @@ class MailPluginTest extends TestCase {
* @param array $expected
* @param bool $reachedEnd
*/
- public function testSearch($searchTerm, $contacts, $shareeEnumeration, $expected, $exactIdMatch, $reachedEnd, $validEmail) {
+ public function testSearch($searchTerm, $contacts, $shareeEnumeration, $expected, $exactIdMatch, $reachedEnd, $validEmail): void {
$this->config->expects($this->any())
->method('getAppValue')
->willReturnCallback(
@@ -577,7 +577,7 @@ class MailPluginTest extends TestCase {
* @param bool $reachedEnd
* @param array groups
*/
- public function testSearchGroupsOnly($searchTerm, $contacts, $expected, $exactIdMatch, $reachedEnd, $userToGroupMapping, $validEmail) {
+ public function testSearchGroupsOnly($searchTerm, $contacts, $expected, $exactIdMatch, $reachedEnd, $userToGroupMapping, $validEmail): void {
$this->config->expects($this->any())
->method('getAppValue')
->willReturnCallback(
diff --git a/tests/lib/Collaboration/Collaborators/RemotePluginTest.php b/tests/lib/Collaboration/Collaborators/RemotePluginTest.php
index f1668dbcec2..14894aa2df6 100644
--- a/tests/lib/Collaboration/Collaborators/RemotePluginTest.php
+++ b/tests/lib/Collaboration/Collaborators/RemotePluginTest.php
@@ -79,7 +79,7 @@ class RemotePluginTest extends TestCase {
* @param bool $exactIdMatch
* @param bool $reachedEnd
*/
- public function testSearch($searchTerm, array $contacts, $shareeEnumeration, array $expected, $exactIdMatch, $reachedEnd) {
+ public function testSearch($searchTerm, array $contacts, $shareeEnumeration, array $expected, $exactIdMatch, $reachedEnd): void {
$this->config->expects($this->any())
->method('getAppValue')
->willReturnCallback(
@@ -117,7 +117,7 @@ class RemotePluginTest extends TestCase {
* @param string $expectedUser
* @param string $expectedUrl
*/
- public function testSplitUserRemote($remote, $expectedUser, $expectedUrl) {
+ public function testSplitUserRemote($remote, $expectedUser, $expectedUrl): void {
$this->instantiatePlugin();
$this->contactsManager->expects($this->any())
@@ -134,7 +134,7 @@ class RemotePluginTest extends TestCase {
*
* @param string $id
*/
- public function testSplitUserRemoteError($id) {
+ public function testSplitUserRemoteError($id): void {
$this->expectException(\Exception::class);
$this->instantiatePlugin();
diff --git a/tests/lib/Collaboration/Collaborators/SearchResultTest.php b/tests/lib/Collaboration/Collaborators/SearchResultTest.php
index b91e7f5a12d..6641a2caed1 100644
--- a/tests/lib/Collaboration/Collaborators/SearchResultTest.php
+++ b/tests/lib/Collaboration/Collaborators/SearchResultTest.php
@@ -41,7 +41,7 @@ class SearchResultTest extends TestCase {
* @param array $toAdd
* @param array $expected
*/
- public function testAddResultSet(array $toAdd, array $expected) {
+ public function testAddResultSet(array $toAdd, array $expected): void {
$result = new SearchResult();
foreach ($toAdd as $type => $results) {
@@ -72,7 +72,7 @@ class SearchResultTest extends TestCase {
* @param string $id
* @param bool $expected
*/
- public function testHasResult(array $toAdd, $type, $id, $expected) {
+ public function testHasResult(array $toAdd, $type, $id, $expected): void {
$result = new SearchResult();
foreach ($toAdd as $addType => $results) {
diff --git a/tests/lib/Collaboration/Collaborators/SearchTest.php b/tests/lib/Collaboration/Collaborators/SearchTest.php
index d23f584cb8a..88bdfa6047e 100644
--- a/tests/lib/Collaboration/Collaborators/SearchTest.php
+++ b/tests/lib/Collaboration/Collaborators/SearchTest.php
@@ -43,7 +43,7 @@ class SearchTest extends TestCase {
array $mockedMailResult,
array $expected,
bool $expectedMoreResults
- ) {
+ ): void {
$searchResult = new SearchResult();
$userPlugin = $this->createMock(ISearchPlugin::class);
diff --git a/tests/lib/Collaboration/Collaborators/UserPluginTest.php b/tests/lib/Collaboration/Collaborators/UserPluginTest.php
index 4ba03224533..c6a266b55d6 100644
--- a/tests/lib/Collaboration/Collaborators/UserPluginTest.php
+++ b/tests/lib/Collaboration/Collaborators/UserPluginTest.php
@@ -442,7 +442,7 @@ class UserPluginTest extends TestCase {
$singleUser,
array $users = [],
$shareeEnumerationPhone = false
- ) {
+ ): void {
$this->mockConfig(['core' => [
'shareapi_only_share_with_group_members' => $shareWithGroupOnly ? 'yes' : 'no',
'shareapi_allow_share_dialog_user_enumeration' => $shareeEnumeration? 'yes' : 'no',
@@ -539,7 +539,7 @@ class UserPluginTest extends TestCase {
* @param array $expectedUIDs
* @param $currentUserId
*/
- public function testTakeOutCurrentUser(array $users, array $expectedUIDs, $currentUserId) {
+ public function testTakeOutCurrentUser(array $users, array $expectedUIDs, $currentUserId): void {
$this->instantiatePlugin();
$this->session->expects($this->once())
@@ -719,7 +719,7 @@ class UserPluginTest extends TestCase {
/**
* @dataProvider dataSearchEnumeration
*/
- public function testSearchEnumerationLimit($search, $userGroups, $matchingUsers, $result, $mockedSettings) {
+ public function testSearchEnumerationLimit($search, $userGroups, $matchingUsers, $result, $mockedSettings): void {
$this->mockConfig($mockedSettings);
$userResults = [];
diff --git a/tests/lib/Command/AsyncBusTest.php b/tests/lib/Command/AsyncBusTest.php
index 12d6a3ddecc..7c515051609 100644
--- a/tests/lib/Command/AsyncBusTest.php
+++ b/tests/lib/Command/AsyncBusTest.php
@@ -1,180 +1,180 @@
-<?php
-
-/**
- * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
- * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
- * SPDX-License-Identifier: AGPL-3.0-or-later
- */
-
-namespace Test\Command;
-
-use OC\Command\FileAccess;
-use OCP\Command\IBus;
-use OCP\Command\ICommand;
-use Test\TestCase;
-
-class SimpleCommand implements ICommand {
- public function handle() {
- AsyncBusTest::$lastCommand = 'SimpleCommand';
- }
-}
-
-class StateFullCommand implements ICommand {
- private $state;
-
- public function __construct($state) {
- $this->state = $state;
- }
-
- public function handle() {
- AsyncBusTest::$lastCommand = $this->state;
- }
-}
-
-class FilesystemCommand implements ICommand {
- use FileAccess;
-
- public function handle() {
- AsyncBusTest::$lastCommand = 'FileAccess';
- }
-}
-
-function basicFunction() {
- AsyncBusTest::$lastCommand = 'function';
-}
-
-// clean class to prevent phpunit putting closure in $this
-class ThisClosureTest {
- private function privateMethod() {
- AsyncBusTest::$lastCommand = 'closure-this';
- }
-
- public function test(IBus $bus) {
- $bus->push(function () {
- $this->privateMethod();
- });
- }
-}
-
-abstract class AsyncBusTest extends TestCase {
- /**
- * Basic way to check output from a command
- *
- * @var string
- */
- public static $lastCommand;
-
- /**
- * @var \OCP\Command\IBus
- */
- private $bus;
-
- public static function DummyCommand() {
- self::$lastCommand = 'static';
- }
-
- /**
- * @return IBus
- */
- protected function getBus() {
- if (!$this->bus instanceof IBus) {
- $this->bus = $this->createBus();
- }
- return $this->bus;
- }
-
- /**
- * @return IBus
- */
- abstract protected function createBus();
-
- protected function setUp(): void {
- self::$lastCommand = '';
- }
-
- public function testSimpleCommand() {
- $command = new SimpleCommand();
- $this->getBus()->push($command);
- $this->runJobs();
- $this->assertEquals('SimpleCommand', self::$lastCommand);
- }
-
- public function testStateFullCommand() {
- $command = new StateFullCommand('foo');
- $this->getBus()->push($command);
- $this->runJobs();
- $this->assertEquals('foo', self::$lastCommand);
- }
-
- public function testStaticCallable() {
- $this->getBus()->push([\Test\Command\AsyncBusTest::class, 'DummyCommand']);
- $this->runJobs();
- $this->assertEquals('static', self::$lastCommand);
- }
-
- public function testMemberCallable() {
- $command = new StateFullCommand('bar');
- $this->getBus()->push([$command, 'handle']);
- $this->runJobs();
- $this->assertEquals('bar', self::$lastCommand);
- }
-
- public function testFunctionCallable() {
- $this->getBus()->push('\Test\Command\BasicFunction');
- $this->runJobs();
- $this->assertEquals('function', self::$lastCommand);
- }
-
- public function testClosure() {
- $this->getBus()->push(function () {
- AsyncBusTest::$lastCommand = 'closure';
- });
- $this->runJobs();
- $this->assertEquals('closure', self::$lastCommand);
- }
-
- public function testClosureSelf() {
- $this->getBus()->push(function () {
- AsyncBusTest::$lastCommand = 'closure-self';
- });
- $this->runJobs();
- $this->assertEquals('closure-self', self::$lastCommand);
- }
-
-
- public function testClosureThis() {
- // clean class to prevent phpunit putting closure in $this
- $test = new ThisClosureTest();
- $test->test($this->getBus());
- $this->runJobs();
- $this->assertEquals('closure-this', self::$lastCommand);
- }
-
- public function testClosureBind() {
- $state = 'bar';
- $this->getBus()->push(function () use ($state) {
- AsyncBusTest::$lastCommand = 'closure-' . $state;
- });
- $this->runJobs();
- $this->assertEquals('closure-bar', self::$lastCommand);
- }
-
- public function testFileFileAccessCommand() {
- $this->getBus()->push(new FilesystemCommand());
- $this->assertEquals('', self::$lastCommand);
- $this->runJobs();
- $this->assertEquals('FileAccess', self::$lastCommand);
- }
-
- public function testFileFileAccessCommandSync() {
- $this->getBus()->requireSync(\OC\Command\FileAccess::class);
- $this->getBus()->push(new FilesystemCommand());
- $this->assertEquals('FileAccess', self::$lastCommand);
- self::$lastCommand = '';
- $this->runJobs();
- $this->assertEquals('', self::$lastCommand);
- }
-
-
- abstract protected function runJobs();
-}
+<?php
+
+/**
+ * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+
+namespace Test\Command;
+
+use OC\Command\FileAccess;
+use OCP\Command\IBus;
+use OCP\Command\ICommand;
+use Test\TestCase;
+
+class SimpleCommand implements ICommand {
+ public function handle() {
+ AsyncBusTest::$lastCommand = 'SimpleCommand';
+ }
+}
+
+class StateFullCommand implements ICommand {
+ private $state;
+
+ public function __construct($state) {
+ $this->state = $state;
+ }
+
+ public function handle() {
+ AsyncBusTest::$lastCommand = $this->state;
+ }
+}
+
+class FilesystemCommand implements ICommand {
+ use FileAccess;
+
+ public function handle() {
+ AsyncBusTest::$lastCommand = 'FileAccess';
+ }
+}
+
+function basicFunction() {
+ AsyncBusTest::$lastCommand = 'function';
+}
+
+// clean class to prevent phpunit putting closure in $this
+class ThisClosureTest {
+ private function privateMethod() {
+ AsyncBusTest::$lastCommand = 'closure-this';
+ }
+
+ public function test(IBus $bus) {
+ $bus->push(function () {
+ $this->privateMethod();
+ });
+ }
+}
+
+abstract class AsyncBusTest extends TestCase {
+ /**
+ * Basic way to check output from a command
+ *
+ * @var string
+ */
+ public static $lastCommand;
+
+ /**
+ * @var \OCP\Command\IBus
+ */
+ private $bus;
+
+ public static function DummyCommand() {
+ self::$lastCommand = 'static';
+ }
+
+ /**
+ * @return IBus
+ */
+ protected function getBus() {
+ if (!$this->bus instanceof IBus) {
+ $this->bus = $this->createBus();
+ }
+ return $this->bus;
+ }
+
+ /**
+ * @return IBus
+ */
+ abstract protected function createBus();
+
+ protected function setUp(): void {
+ self::$lastCommand = '';
+ }
+
+ public function testSimpleCommand(): void {
+ $command = new SimpleCommand();
+ $this->getBus()->push($command);
+ $this->runJobs();
+ $this->assertEquals('SimpleCommand', self::$lastCommand);
+ }
+
+ public function testStateFullCommand(): void {
+ $command = new StateFullCommand('foo');
+ $this->getBus()->push($command);
+ $this->runJobs();
+ $this->assertEquals('foo', self::$lastCommand);
+ }
+
+ public function testStaticCallable(): void {
+ $this->getBus()->push([\Test\Command\AsyncBusTest::class, 'DummyCommand']);
+ $this->runJobs();
+ $this->assertEquals('static', self::$lastCommand);
+ }
+
+ public function testMemberCallable(): void {
+ $command = new StateFullCommand('bar');
+ $this->getBus()->push([$command, 'handle']);
+ $this->runJobs();
+ $this->assertEquals('bar', self::$lastCommand);
+ }
+
+ public function testFunctionCallable(): void {
+ $this->getBus()->push('\Test\Command\BasicFunction');
+ $this->runJobs();
+ $this->assertEquals('function', self::$lastCommand);
+ }
+
+ public function testClosure(): void {
+ $this->getBus()->push(function () {
+ AsyncBusTest::$lastCommand = 'closure';
+ });
+ $this->runJobs();
+ $this->assertEquals('closure', self::$lastCommand);
+ }
+
+ public function testClosureSelf(): void {
+ $this->getBus()->push(function () {
+ AsyncBusTest::$lastCommand = 'closure-self';
+ });
+ $this->runJobs();
+ $this->assertEquals('closure-self', self::$lastCommand);
+ }
+
+
+ public function testClosureThis(): void {
+ // clean class to prevent phpunit putting closure in $this
+ $test = new ThisClosureTest();
+ $test->test($this->getBus());
+ $this->runJobs();
+ $this->assertEquals('closure-this', self::$lastCommand);
+ }
+
+ public function testClosureBind(): void {
+ $state = 'bar';
+ $this->getBus()->push(function () use ($state) {
+ AsyncBusTest::$lastCommand = 'closure-' . $state;
+ });
+ $this->runJobs();
+ $this->assertEquals('closure-bar', self::$lastCommand);
+ }
+
+ public function testFileFileAccessCommand(): void {
+ $this->getBus()->push(new FilesystemCommand());
+ $this->assertEquals('', self::$lastCommand);
+ $this->runJobs();
+ $this->assertEquals('FileAccess', self::$lastCommand);
+ }
+
+ public function testFileFileAccessCommandSync(): void {
+ $this->getBus()->requireSync(\OC\Command\FileAccess::class);
+ $this->getBus()->push(new FilesystemCommand());
+ $this->assertEquals('FileAccess', self::$lastCommand);
+ self::$lastCommand = '';
+ $this->runJobs();
+ $this->assertEquals('', self::$lastCommand);
+ }
+
+
+ abstract protected function runJobs();
+}
diff --git a/tests/lib/Command/Integrity/SignAppTest.php b/tests/lib/Command/Integrity/SignAppTest.php
index 41333863ad4..d4921c79431 100644
--- a/tests/lib/Command/Integrity/SignAppTest.php
+++ b/tests/lib/Command/Integrity/SignAppTest.php
@@ -37,7 +37,7 @@ class SignAppTest extends TestCase {
);
}
- public function testExecuteWithMissingPath() {
+ public function testExecuteWithMissingPath(): void {
$inputInterface = $this->createMock(InputInterface::class);
$outputInterface = $this->createMock(OutputInterface::class);
@@ -64,7 +64,7 @@ class SignAppTest extends TestCase {
$this->assertSame(1, self::invokePrivate($this->signApp, 'execute', [$inputInterface, $outputInterface]));
}
- public function testExecuteWithMissingPrivateKey() {
+ public function testExecuteWithMissingPrivateKey(): void {
$inputInterface = $this->createMock(InputInterface::class);
$outputInterface = $this->createMock(OutputInterface::class);
@@ -91,7 +91,7 @@ class SignAppTest extends TestCase {
$this->assertSame(1, self::invokePrivate($this->signApp, 'execute', [$inputInterface, $outputInterface]));
}
- public function testExecuteWithMissingCertificate() {
+ public function testExecuteWithMissingCertificate(): void {
$inputInterface = $this->createMock(InputInterface::class);
$outputInterface = $this->createMock(OutputInterface::class);
@@ -118,7 +118,7 @@ class SignAppTest extends TestCase {
$this->assertSame(1, self::invokePrivate($this->signApp, 'execute', [$inputInterface, $outputInterface]));
}
- public function testExecuteWithNotExistingPrivateKey() {
+ public function testExecuteWithNotExistingPrivateKey(): void {
$inputInterface = $this->createMock(InputInterface::class);
$outputInterface = $this->createMock(OutputInterface::class);
@@ -152,7 +152,7 @@ class SignAppTest extends TestCase {
$this->assertSame(1, self::invokePrivate($this->signApp, 'execute', [$inputInterface, $outputInterface]));
}
- public function testExecuteWithNotExistingCertificate() {
+ public function testExecuteWithNotExistingCertificate(): void {
$inputInterface = $this->createMock(InputInterface::class);
$outputInterface = $this->createMock(OutputInterface::class);
@@ -191,7 +191,7 @@ class SignAppTest extends TestCase {
$this->assertSame(1, self::invokePrivate($this->signApp, 'execute', [$inputInterface, $outputInterface]));
}
- public function testExecuteWithException() {
+ public function testExecuteWithException(): void {
$inputInterface = $this->createMock(InputInterface::class);
$outputInterface = $this->createMock(OutputInterface::class);
@@ -235,7 +235,7 @@ class SignAppTest extends TestCase {
$this->assertSame(1, self::invokePrivate($this->signApp, 'execute', [$inputInterface, $outputInterface]));
}
- public function testExecute() {
+ public function testExecute(): void {
$inputInterface = $this->createMock(InputInterface::class);
$outputInterface = $this->createMock(OutputInterface::class);
diff --git a/tests/lib/Command/Integrity/SignCoreTest.php b/tests/lib/Command/Integrity/SignCoreTest.php
index 51bec55b774..bbb68e00a84 100644
--- a/tests/lib/Command/Integrity/SignCoreTest.php
+++ b/tests/lib/Command/Integrity/SignCoreTest.php
@@ -32,7 +32,7 @@ class SignCoreTest extends TestCase {
);
}
- public function testExecuteWithMissingPrivateKey() {
+ public function testExecuteWithMissingPrivateKey(): void {
$inputInterface = $this->createMock(InputInterface::class);
$outputInterface = $this->createMock(OutputInterface::class);
@@ -59,7 +59,7 @@ class SignCoreTest extends TestCase {
$this->assertSame(1, self::invokePrivate($this->signCore, 'execute', [$inputInterface, $outputInterface]));
}
- public function testExecuteWithMissingCertificate() {
+ public function testExecuteWithMissingCertificate(): void {
$inputInterface = $this->createMock(InputInterface::class);
$outputInterface = $this->createMock(OutputInterface::class);
@@ -86,7 +86,7 @@ class SignCoreTest extends TestCase {
$this->assertSame(1, self::invokePrivate($this->signCore, 'execute', [$inputInterface, $outputInterface]));
}
- public function testExecuteWithNotExistingPrivateKey() {
+ public function testExecuteWithNotExistingPrivateKey(): void {
$inputInterface = $this->createMock(InputInterface::class);
$outputInterface = $this->createMock(OutputInterface::class);
@@ -123,7 +123,7 @@ class SignCoreTest extends TestCase {
$this->assertSame(1, self::invokePrivate($this->signCore, 'execute', [$inputInterface, $outputInterface]));
}
- public function testExecuteWithNotExistingCertificate() {
+ public function testExecuteWithNotExistingCertificate(): void {
$inputInterface = $this->createMock(InputInterface::class);
$outputInterface = $this->createMock(OutputInterface::class);
@@ -162,7 +162,7 @@ class SignCoreTest extends TestCase {
$this->assertSame(1, self::invokePrivate($this->signCore, 'execute', [$inputInterface, $outputInterface]));
}
- public function testExecuteWithException() {
+ public function testExecuteWithException(): void {
$inputInterface = $this->createMock(InputInterface::class);
$outputInterface = $this->createMock(OutputInterface::class);
@@ -206,7 +206,7 @@ class SignCoreTest extends TestCase {
$this->assertEquals(1, self::invokePrivate($this->signCore, 'execute', [$inputInterface, $outputInterface]));
}
- public function testExecute() {
+ public function testExecute(): void {
$inputInterface = $this->createMock(InputInterface::class);
$outputInterface = $this->createMock(OutputInterface::class);
diff --git a/tests/lib/Comments/CommentTest.php b/tests/lib/Comments/CommentTest.php
index feaa268a09e..742ce33071f 100644
--- a/tests/lib/Comments/CommentTest.php
+++ b/tests/lib/Comments/CommentTest.php
@@ -14,7 +14,7 @@ class CommentTest extends TestCase {
/**
* @throws \OCP\Comments\IllegalIDChangeException
*/
- public function testSettersValidInput() {
+ public function testSettersValidInput(): void {
$comment = new Comment();
$id = 'comment23';
@@ -61,7 +61,7 @@ class CommentTest extends TestCase {
}
- public function testSetIdIllegalInput() {
+ public function testSetIdIllegalInput(): void {
$this->expectException(\OCP\Comments\IllegalIDChangeException::class);
$comment = new Comment();
@@ -73,7 +73,7 @@ class CommentTest extends TestCase {
/**
* @throws \OCP\Comments\IllegalIDChangeException
*/
- public function testResetId() {
+ public function testResetId(): void {
$comment = new Comment();
$comment->setId('c23');
$comment->setId('');
@@ -96,7 +96,7 @@ class CommentTest extends TestCase {
/**
* @dataProvider simpleSetterProvider
*/
- public function testSimpleSetterInvalidInput($field, $input) {
+ public function testSimpleSetterInvalidInput($field, $input): void {
$this->expectException(\InvalidArgumentException::class);
$comment = new Comment();
@@ -121,7 +121,7 @@ class CommentTest extends TestCase {
/**
* @dataProvider roleSetterProvider
*/
- public function testSetRoleInvalidInput($role, $type, $id) {
+ public function testSetRoleInvalidInput($role, $type, $id): void {
$this->expectException(\InvalidArgumentException::class);
$comment = new Comment();
@@ -130,7 +130,7 @@ class CommentTest extends TestCase {
}
- public function testSetUberlongMessage() {
+ public function testSetUberlongMessage(): void {
$this->expectException(\OCP\Comments\MessageTooLongException::class);
$comment = new Comment();
diff --git a/tests/lib/Comments/ManagerTest.php b/tests/lib/Comments/ManagerTest.php
index fda007c76a1..9a36182d393 100644
--- a/tests/lib/Comments/ManagerTest.php
+++ b/tests/lib/Comments/ManagerTest.php
@@ -97,7 +97,7 @@ class ManagerTest extends TestCase {
}
- public function testGetCommentNotFound() {
+ public function testGetCommentNotFound(): void {
$this->expectException(\OCP\Comments\NotFoundException::class);
$manager = $this->getManager();
@@ -105,14 +105,14 @@ class ManagerTest extends TestCase {
}
- public function testGetCommentNotFoundInvalidInput() {
+ public function testGetCommentNotFoundInvalidInput(): void {
$this->expectException(\InvalidArgumentException::class);
$manager = $this->getManager();
$manager->get('unexisting22');
}
- public function testGetComment() {
+ public function testGetComment(): void {
$manager = $this->getManager();
$creationDT = new \DateTime();
@@ -159,7 +159,7 @@ class ManagerTest extends TestCase {
}
- public function testGetTreeNotFound() {
+ public function testGetTreeNotFound(): void {
$this->expectException(\OCP\Comments\NotFoundException::class);
$manager = $this->getManager();
@@ -167,14 +167,14 @@ class ManagerTest extends TestCase {
}
- public function testGetTreeNotFoundInvalidIpnut() {
+ public function testGetTreeNotFoundInvalidIpnut(): void {
$this->expectException(\InvalidArgumentException::class);
$manager = $this->getManager();
$manager->getTree('unexisting22');
}
- public function testGetTree() {
+ public function testGetTree(): void {
$headId = $this->addDatabaseEntry(0, 0);
$this->addDatabaseEntry($headId, $headId, new \DateTime('-3 hours'));
@@ -200,7 +200,7 @@ class ManagerTest extends TestCase {
}
}
- public function testGetTreeNoReplies() {
+ public function testGetTreeNoReplies(): void {
$id = $this->addDatabaseEntry(0, 0);
$manager = $this->getManager();
@@ -219,7 +219,7 @@ class ManagerTest extends TestCase {
}
}
- public function testGetTreeWithLimitAndOffset() {
+ public function testGetTreeWithLimitAndOffset(): void {
$headId = $this->addDatabaseEntry(0, 0);
$this->addDatabaseEntry($headId, $headId, new \DateTime('-3 hours'));
@@ -249,7 +249,7 @@ class ManagerTest extends TestCase {
}
}
- public function testGetForObject() {
+ public function testGetForObject(): void {
$this->addDatabaseEntry(0, 0);
$manager = $this->getManager();
@@ -261,7 +261,7 @@ class ManagerTest extends TestCase {
$this->assertSame($comments[0]->getMessage(), 'nice one');
}
- public function testGetForObjectWithLimitAndOffset() {
+ public function testGetForObjectWithLimitAndOffset(): void {
$this->addDatabaseEntry(0, 0, new \DateTime('-6 hours'));
$this->addDatabaseEntry(0, 0, new \DateTime('-5 hours'));
$this->addDatabaseEntry(1, 1, new \DateTime('-4 hours'));
@@ -286,7 +286,7 @@ class ManagerTest extends TestCase {
} while (count($comments) > 0);
}
- public function testGetForObjectWithDateTimeConstraint() {
+ public function testGetForObjectWithDateTimeConstraint(): void {
$this->addDatabaseEntry(0, 0, new \DateTime('-6 hours'));
$this->addDatabaseEntry(0, 0, new \DateTime('-5 hours'));
$id1 = $this->addDatabaseEntry(0, 0, new \DateTime('-3 hours'));
@@ -300,7 +300,7 @@ class ManagerTest extends TestCase {
$this->assertSame($comments[1]->getId(), strval($id1));
}
- public function testGetForObjectWithLimitAndOffsetAndDateTimeConstraint() {
+ public function testGetForObjectWithLimitAndOffsetAndDateTimeConstraint(): void {
$this->addDatabaseEntry(0, 0, new \DateTime('-7 hours'));
$this->addDatabaseEntry(0, 0, new \DateTime('-6 hours'));
$this->addDatabaseEntry(1, 1, new \DateTime('-5 hours'));
@@ -326,7 +326,7 @@ class ManagerTest extends TestCase {
} while (count($comments) > 0);
}
- public function testGetNumberOfCommentsForObject() {
+ public function testGetNumberOfCommentsForObject(): void {
for ($i = 1; $i < 5; $i++) {
$this->addDatabaseEntry(0, 0);
}
@@ -340,7 +340,7 @@ class ManagerTest extends TestCase {
$this->assertSame($amount, 4);
}
- public function testGetNumberOfUnreadCommentsForFolder() {
+ public function testGetNumberOfUnreadCommentsForFolder(): void {
$folder = $this->createMock(Folder::class);
$fileIds = range(1111, 1114);
$children = array_map(function (int $id) {
@@ -391,7 +391,7 @@ class ManagerTest extends TestCase {
* @param $resultFrom
* @param $resultTo
*/
- public function testGetForObjectSince($lastKnown, $order, $limit, $resultFrom, $resultTo) {
+ public function testGetForObjectSince($lastKnown, $order, $limit, $resultFrom, $resultTo): void {
$ids = [];
$ids[] = $this->addDatabaseEntry(0, 0);
$ids[] = $this->addDatabaseEntry(0, 0);
@@ -445,14 +445,14 @@ class ManagerTest extends TestCase {
* @param string $oType
* @param string $oId
*/
- public function testCreateCommentInvalidArguments($aType, $aId, $oType, $oId) {
+ public function testCreateCommentInvalidArguments($aType, $aId, $oType, $oId): void {
$this->expectException(\InvalidArgumentException::class);
$manager = $this->getManager();
$manager->create($aType, $aId, $oType, $oId);
}
- public function testCreateComment() {
+ public function testCreateComment(): void {
$actorType = 'bot';
$actorId = 'bob';
$objectType = 'weather';
@@ -467,7 +467,7 @@ class ManagerTest extends TestCase {
}
- public function testDelete() {
+ public function testDelete(): void {
$this->expectException(\OCP\Comments\NotFoundException::class);
$manager = $this->getManager();
@@ -523,7 +523,7 @@ class ManagerTest extends TestCase {
];
}
- public function testSaveUpdate() {
+ public function testSaveUpdate(): void {
$manager = $this->getManager();
$comment = new Comment();
$comment
@@ -568,7 +568,7 @@ class ManagerTest extends TestCase {
}
- public function testSaveUpdateException() {
+ public function testSaveUpdateException(): void {
$this->expectException(\OCP\Comments\NotFoundException::class);
$manager = $this->getManager();
@@ -587,7 +587,7 @@ class ManagerTest extends TestCase {
}
- public function testSaveIncomplete() {
+ public function testSaveIncomplete(): void {
$this->expectException(\UnexpectedValueException::class);
$manager = $this->getManager();
@@ -596,7 +596,7 @@ class ManagerTest extends TestCase {
$manager->save($comment);
}
- public function testSaveAsChild() {
+ public function testSaveAsChild(): void {
$id = $this->addDatabaseEntry(0, 0);
$manager = $this->getManager();
@@ -635,14 +635,14 @@ class ManagerTest extends TestCase {
* @param string $type
* @param string $id
*/
- public function testDeleteReferencesOfActorInvalidInput($type, $id) {
+ public function testDeleteReferencesOfActorInvalidInput($type, $id): void {
$this->expectException(\InvalidArgumentException::class);
$manager = $this->getManager();
$manager->deleteReferencesOfActor($type, $id);
}
- public function testDeleteReferencesOfActor() {
+ public function testDeleteReferencesOfActor(): void {
$ids = [];
$ids[] = $this->addDatabaseEntry(0, 0);
$ids[] = $this->addDatabaseEntry(0, 0);
@@ -670,7 +670,7 @@ class ManagerTest extends TestCase {
$this->assertTrue($wasSuccessful);
}
- public function testDeleteReferencesOfActorWithUserManagement() {
+ public function testDeleteReferencesOfActorWithUserManagement(): void {
$user = \OC::$server->getUserManager()->createUser('xenia', 'NotAnEasyPassword123456+');
$this->assertTrue($user instanceof IUser);
@@ -704,14 +704,14 @@ class ManagerTest extends TestCase {
* @param string $type
* @param string $id
*/
- public function testDeleteCommentsAtObjectInvalidInput($type, $id) {
+ public function testDeleteCommentsAtObjectInvalidInput($type, $id): void {
$this->expectException(\InvalidArgumentException::class);
$manager = $this->getManager();
$manager->deleteCommentsAtObject($type, $id);
}
- public function testDeleteCommentsAtObject() {
+ public function testDeleteCommentsAtObject(): void {
$ids = [];
$ids[] = $this->addDatabaseEntry(0, 0);
$ids[] = $this->addDatabaseEntry(0, 0);
@@ -832,7 +832,7 @@ class ManagerTest extends TestCase {
$this->assertFalse($deleted);
}
- public function testSetMarkRead() {
+ public function testSetMarkRead(): void {
/** @var IUser|\PHPUnit\Framework\MockObject\MockObject $user */
$user = $this->createMock(IUser::class);
$user->expects($this->any())
@@ -849,7 +849,7 @@ class ManagerTest extends TestCase {
$this->assertEquals($dateTimeGet->getTimestamp(), $dateTimeSet->getTimestamp());
}
- public function testSetMarkReadUpdate() {
+ public function testSetMarkReadUpdate(): void {
/** @var IUser|\PHPUnit\Framework\MockObject\MockObject $user */
$user = $this->createMock(IUser::class);
$user->expects($this->any())
@@ -869,7 +869,7 @@ class ManagerTest extends TestCase {
$this->assertEquals($dateTimeGet, $dateTimeSet);
}
- public function testReadMarkDeleteUser() {
+ public function testReadMarkDeleteUser(): void {
/** @var IUser|\PHPUnit\Framework\MockObject\MockObject $user */
$user = $this->createMock(IUser::class);
$user->expects($this->any())
@@ -887,7 +887,7 @@ class ManagerTest extends TestCase {
$this->assertNull($dateTimeGet);
}
- public function testReadMarkDeleteObject() {
+ public function testReadMarkDeleteObject(): void {
/** @var IUser|\PHPUnit\Framework\MockObject\MockObject $user */
$user = $this->createMock(IUser::class);
$user->expects($this->any())
@@ -905,7 +905,7 @@ class ManagerTest extends TestCase {
$this->assertNull($dateTimeGet);
}
- public function testSendEvent() {
+ public function testSendEvent(): void {
$handler1 = $this->getMockBuilder(ICommentsEventHandler::class)->getMock();
$handler1->expects($this->exactly(4))
->method('handle');
@@ -940,7 +940,7 @@ class ManagerTest extends TestCase {
$manager->delete($comment->getId());
}
- public function testResolveDisplayName() {
+ public function testResolveDisplayName(): void {
$manager = $this->getManager();
$planetClosure = function ($name) {
@@ -959,7 +959,7 @@ class ManagerTest extends TestCase {
}
- public function testRegisterResolverDuplicate() {
+ public function testRegisterResolverDuplicate(): void {
$this->expectException(\OutOfBoundsException::class);
$manager = $this->getManager();
@@ -972,7 +972,7 @@ class ManagerTest extends TestCase {
}
- public function testRegisterResolverInvalidType() {
+ public function testRegisterResolverInvalidType(): void {
$this->expectException(\InvalidArgumentException::class);
$manager = $this->getManager();
@@ -984,7 +984,7 @@ class ManagerTest extends TestCase {
}
- public function testResolveDisplayNameUnregisteredType() {
+ public function testResolveDisplayNameUnregisteredType(): void {
$this->expectException(\OutOfBoundsException::class);
$manager = $this->getManager();
@@ -997,7 +997,7 @@ class ManagerTest extends TestCase {
$manager->resolveDisplayName('galaxy', 'sombrero');
}
- public function testResolveDisplayNameDirtyResolver() {
+ public function testResolveDisplayNameDirtyResolver(): void {
$manager = $this->getManager();
$planetClosure = function () {
@@ -1021,7 +1021,7 @@ class ManagerTest extends TestCase {
* @param array $reactionsExpected
* @return void
*/
- public function testReactionAddAndDelete(array $comments, array $reactionsExpected) {
+ public function testReactionAddAndDelete(array $comments, array $reactionsExpected): void {
$this->skipIfNotSupport4ByteUTF();
$manager = $this->getManager();
@@ -1080,7 +1080,7 @@ class ManagerTest extends TestCase {
];
}
- public function testResolveDisplayNameInvalidType() {
+ public function testResolveDisplayNameInvalidType(): void {
$this->expectException(\InvalidArgumentException::class);
$manager = $this->getManager();
@@ -1119,7 +1119,7 @@ class ManagerTest extends TestCase {
/**
* @dataProvider providerTestRetrieveAllReactions
*/
- public function testRetrieveAllReactions(array $comments, array $expected) {
+ public function testRetrieveAllReactions(array $comments, array $expected): void {
$this->skipIfNotSupport4ByteUTF();
$manager = $this->getManager();
@@ -2379,7 +2379,7 @@ class ManagerTest extends TestCase {
/**
* @dataProvider providerTestRetrieveAllReactionsWithSpecificReaction
*/
- public function testRetrieveAllReactionsWithSpecificReaction(array $comments, string $reaction, array $expected) {
+ public function testRetrieveAllReactionsWithSpecificReaction(array $comments, string $reaction, array $expected): void {
$this->skipIfNotSupport4ByteUTF();
$manager = $this->getManager();
@@ -2434,7 +2434,7 @@ class ManagerTest extends TestCase {
/**
* @dataProvider providerTestGetReactionComment
*/
- public function testGetReactionComment(array $comments, array $expected, bool $notFound) {
+ public function testGetReactionComment(array $comments, array $expected, bool $notFound): void {
$this->skipIfNotSupport4ByteUTF();
$manager = $this->getManager();
@@ -2503,7 +2503,7 @@ class ManagerTest extends TestCase {
/**
* @dataProvider providerTestReactionMessageSize
*/
- public function testReactionMessageSize($reactionString, $valid) {
+ public function testReactionMessageSize($reactionString, $valid): void {
$this->skipIfNotSupport4ByteUTF();
if (!$valid) {
$this->expectException(\UnexpectedValueException::class);
@@ -2534,7 +2534,7 @@ class ManagerTest extends TestCase {
/**
* @dataProvider providerTestReactionsSummarizeOrdered
*/
- public function testReactionsSummarizeOrdered(array $comments, array $expected, bool $isFullMatch) {
+ public function testReactionsSummarizeOrdered(array $comments, array $expected, bool $isFullMatch): void {
$this->skipIfNotSupport4ByteUTF();
$manager = $this->getManager();
diff --git a/tests/lib/ConfigTest.php b/tests/lib/ConfigTest.php
index e65cf7633e1..60006aa43de 100644
--- a/tests/lib/ConfigTest.php
+++ b/tests/lib/ConfigTest.php
@@ -36,12 +36,12 @@ class ConfigTest extends TestCase {
return new \OC\Config($this->randomTmpDir, 'testconfig.php');
}
- public function testGetKeys() {
+ public function testGetKeys(): void {
$expectedConfig = ['foo', 'beers', 'alcohol_free'];
$this->assertSame($expectedConfig, $this->getConfig()->getKeys());
}
- public function testGetValue() {
+ public function testGetValue(): void {
$config = $this->getConfig();
$this->assertSame('bar', $config->getValue('foo'));
$this->assertSame(null, $config->getValue('bar'));
@@ -51,7 +51,7 @@ class ConfigTest extends TestCase {
$this->assertSame(['Appenzeller', 'Guinness', 'Kölsch'], $config->getValue('beers'));
}
- public function testGetValueReturnsEnvironmentValueIfSet() {
+ public function testGetValueReturnsEnvironmentValueIfSet(): void {
$config = $this->getConfig();
$this->assertEquals('bar', $config->getValue('foo'));
@@ -61,7 +61,7 @@ class ConfigTest extends TestCase {
putenv('NC_foo'); // unset the env variable
}
- public function testGetValueReturnsEnvironmentValueIfSetToZero() {
+ public function testGetValueReturnsEnvironmentValueIfSetToZero(): void {
$config = $this->getConfig();
$this->assertEquals('bar', $config->getValue('foo'));
@@ -71,7 +71,7 @@ class ConfigTest extends TestCase {
putenv('NC_foo'); // unset the env variable
}
- public function testGetValueReturnsEnvironmentValueIfSetToFalse() {
+ public function testGetValueReturnsEnvironmentValueIfSetToFalse(): void {
$config = $this->getConfig();
$this->assertEquals('bar', $config->getValue('foo'));
@@ -81,7 +81,7 @@ class ConfigTest extends TestCase {
putenv('NC_foo'); // unset the env variable
}
- public function testSetValue() {
+ public function testSetValue(): void {
$config = $this->getConfig();
$config->setValue('foo', 'moo');
$this->assertSame('moo', $config->getValue('foo'));
@@ -104,7 +104,7 @@ class ConfigTest extends TestCase {
$this->assertEquals($expected, $content);
}
- public function testSetValues() {
+ public function testSetValues(): void {
$config = $this->getConfig();
$content = file_get_contents($this->configFile);
$this->assertEquals(self::TESTCONTENT, $content);
@@ -134,7 +134,7 @@ class ConfigTest extends TestCase {
$this->assertEquals($expected, $content);
}
- public function testDeleteKey() {
+ public function testDeleteKey(): void {
$config = $this->getConfig();
$config->deleteKey('foo');
$this->assertSame('this_was_clearly_not_set_before', $config->getValue('foo', 'this_was_clearly_not_set_before'));
@@ -145,7 +145,7 @@ class ConfigTest extends TestCase {
$this->assertEquals($expected, $content);
}
- public function testConfigMerge() {
+ public function testConfigMerge(): void {
// Create additional config
$additionalConfig = '<?php $CONFIG=array("php53"=>"totallyOutdated");';
$additionalConfigPath = $this->randomTmpDir.'additionalConfig.testconfig.php';
diff --git a/tests/lib/Contacts/ContactsMenu/ActionFactoryTest.php b/tests/lib/Contacts/ContactsMenu/ActionFactoryTest.php
index 55129f7753f..09e0e11bd5e 100644
--- a/tests/lib/Contacts/ContactsMenu/ActionFactoryTest.php
+++ b/tests/lib/Contacts/ContactsMenu/ActionFactoryTest.php
@@ -20,7 +20,7 @@ class ActionFactoryTest extends TestCase {
$this->actionFactory = new ActionFactory();
}
- public function testNewLinkAction() {
+ public function testNewLinkAction(): void {
$icon = 'icon-test';
$name = 'Test';
$href = 'some/url';
@@ -32,7 +32,7 @@ class ActionFactoryTest extends TestCase {
$this->assertEquals(10, $action->getPriority());
}
- public function testNewEMailAction() {
+ public function testNewEMailAction(): void {
$icon = 'icon-test';
$name = 'Test';
$href = 'user@example.com';
diff --git a/tests/lib/Contacts/ContactsMenu/ActionProviderStoreTest.php b/tests/lib/Contacts/ContactsMenu/ActionProviderStoreTest.php
index e9dcb2fba81..84de6ec88e2 100644
--- a/tests/lib/Contacts/ContactsMenu/ActionProviderStoreTest.php
+++ b/tests/lib/Contacts/ContactsMenu/ActionProviderStoreTest.php
@@ -40,7 +40,7 @@ class ActionProviderStoreTest extends TestCase {
$this->actionProviderStore = new ActionProviderStore($this->serverContainer, $this->appManager, $logger);
}
- public function testGetProviders() {
+ public function testGetProviders(): void {
$user = $this->createMock(IUser::class);
$provider1 = $this->createMock(ProfileProvider::class);
$provider2 = $this->createMock(LocalTimeProvider::class);
@@ -76,7 +76,7 @@ class ActionProviderStoreTest extends TestCase {
$this->assertInstanceOf(EMailProvider::class, $providers[2]);
}
- public function testGetProvidersOfAppWithIncompleInfo() {
+ public function testGetProvidersOfAppWithIncompleInfo(): void {
$user = $this->createMock(IUser::class);
$provider1 = $this->createMock(ProfileProvider::class);
$provider2 = $this->createMock(LocalTimeProvider::class);
@@ -107,7 +107,7 @@ class ActionProviderStoreTest extends TestCase {
}
- public function testGetProvidersWithQueryException() {
+ public function testGetProvidersWithQueryException(): void {
$this->expectException(\Exception::class);
$user = $this->createMock(IUser::class);
diff --git a/tests/lib/Contacts/ContactsMenu/Actions/LinkActionTest.php b/tests/lib/Contacts/ContactsMenu/Actions/LinkActionTest.php
index a5ac4543463..5e2b416a66b 100644
--- a/tests/lib/Contacts/ContactsMenu/Actions/LinkActionTest.php
+++ b/tests/lib/Contacts/ContactsMenu/Actions/LinkActionTest.php
@@ -19,7 +19,7 @@ class LinkActionTest extends TestCase {
$this->action = new LinkAction();
}
- public function testSetIcon() {
+ public function testSetIcon(): void {
$icon = 'icon-test';
$this->action->setIcon($icon);
@@ -29,7 +29,7 @@ class LinkActionTest extends TestCase {
$this->assertEquals($json['icon'], $icon);
}
- public function testGetSetName() {
+ public function testGetSetName(): void {
$name = 'Jane Doe';
$this->assertEmpty($this->action->getName());
@@ -37,7 +37,7 @@ class LinkActionTest extends TestCase {
$this->assertEquals($name, $this->action->getName());
}
- public function testGetSetPriority() {
+ public function testGetSetPriority(): void {
$prio = 50;
$this->assertEquals(10, $this->action->getPriority());
@@ -45,7 +45,7 @@ class LinkActionTest extends TestCase {
$this->assertEquals($prio, $this->action->getPriority());
}
- public function testSetHref() {
+ public function testSetHref(): void {
$this->action->setHref('/some/url');
$json = $this->action->jsonSerialize();
@@ -53,7 +53,7 @@ class LinkActionTest extends TestCase {
$this->assertEquals('/some/url', $json['hyperlink']);
}
- public function testJsonSerialize() {
+ public function testJsonSerialize(): void {
$this->action->setIcon('icon-contacts');
$this->action->setName('Nickie Works');
$this->action->setPriority(33);
@@ -71,7 +71,7 @@ class LinkActionTest extends TestCase {
$this->assertEquals($expected, $json);
}
- public function testJsonSerializeNoAppName() {
+ public function testJsonSerializeNoAppName(): void {
$this->action->setIcon('icon-contacts');
$this->action->setName('Nickie Works');
$this->action->setPriority(33);
diff --git a/tests/lib/Contacts/ContactsMenu/ContactsStoreTest.php b/tests/lib/Contacts/ContactsMenu/ContactsStoreTest.php
index d66af2925f4..a3151d0b040 100644
--- a/tests/lib/Contacts/ContactsMenu/ContactsStoreTest.php
+++ b/tests/lib/Contacts/ContactsMenu/ContactsStoreTest.php
@@ -69,7 +69,7 @@ class ContactsStoreTest extends TestCase {
);
}
- public function testGetContactsWithoutFilter() {
+ public function testGetContactsWithoutFilter(): void {
/** @var IUser|MockObject $user */
$user = $this->createMock(IUser::class);
$this->contactsManager->expects($this->once())
@@ -99,7 +99,7 @@ class ContactsStoreTest extends TestCase {
], $entries[1]->getEMailAddresses());
}
- public function testGetContactsHidesOwnEntry() {
+ public function testGetContactsHidesOwnEntry(): void {
/** @var IUser|MockObject $user */
$user = $this->createMock(IUser::class);
$this->contactsManager->expects($this->once())
@@ -126,7 +126,7 @@ class ContactsStoreTest extends TestCase {
$this->assertCount(1, $entries);
}
- public function testGetContactsWithoutBinaryImage() {
+ public function testGetContactsWithoutBinaryImage(): void {
/** @var IUser|MockObject $user */
$user = $this->createMock(IUser::class);
$this->urlGenerator->expects($this->any())
@@ -159,7 +159,7 @@ class ContactsStoreTest extends TestCase {
$this->assertSame('https://urlToNcAvatar.test', $entries[1]->getAvatar());
}
- public function testGetContactsWithoutAvatarURI() {
+ public function testGetContactsWithoutAvatarURI(): void {
/** @var IUser|MockObject $user */
$user = $this->createMock(IUser::class);
$this->contactsManager->expects($this->once())
@@ -188,7 +188,7 @@ class ContactsStoreTest extends TestCase {
$this->assertEquals('https://photo', $entries[1]->getAvatar());
}
- public function testGetContactsWhenUserIsInExcludeGroups() {
+ public function testGetContactsWhenUserIsInExcludeGroups(): void {
$this->config
->method('getAppValue')
->willReturnMap([
@@ -233,7 +233,7 @@ class ContactsStoreTest extends TestCase {
$this->assertCount(0, $entries);
}
- public function testGetContactsOnlyShareIfInTheSameGroup() {
+ public function testGetContactsOnlyShareIfInTheSameGroup(): void {
$this->config
->method('getAppValue')
->willReturnMap([
@@ -308,7 +308,7 @@ class ContactsStoreTest extends TestCase {
$this->assertEquals('contact', $entries[2]->getProperty('UID'));
}
- public function testGetContactsOnlyEnumerateIfInTheSameGroup() {
+ public function testGetContactsOnlyEnumerateIfInTheSameGroup(): void {
$this->config
->method('getAppValue')
->willReturnMap([
@@ -383,7 +383,7 @@ class ContactsStoreTest extends TestCase {
$this->assertEquals('contact', $entries[2]->getProperty('UID'));
}
- public function testGetContactsOnlyEnumerateIfPhoneBookMatch() {
+ public function testGetContactsOnlyEnumerateIfPhoneBookMatch(): void {
$this->config
->method('getAppValue')
->willReturnMap([
@@ -441,7 +441,7 @@ class ContactsStoreTest extends TestCase {
$this->assertEquals('contact', $entries[2]->getProperty('UID'));
}
- public function testGetContactsOnlyEnumerateIfPhoneBookMatchWithOwnGroupsOnly() {
+ public function testGetContactsOnlyEnumerateIfPhoneBookMatchWithOwnGroupsOnly(): void {
$this->config
->method('getAppValue')
->willReturnMap([
@@ -523,7 +523,7 @@ class ContactsStoreTest extends TestCase {
$this->assertEquals('contact', $entries[2]->getProperty('UID'));
}
- public function testGetContactsOnlyEnumerateIfPhoneBookOrSameGroup() {
+ public function testGetContactsOnlyEnumerateIfPhoneBookOrSameGroup(): void {
$this->config
->method('getAppValue')
->willReturnMap([
@@ -595,7 +595,7 @@ class ContactsStoreTest extends TestCase {
$this->assertEquals('contact', $entries[3]->getProperty('UID'));
}
- public function testGetContactsOnlyEnumerateIfPhoneBookOrSameGroupInOwnGroupsOnly() {
+ public function testGetContactsOnlyEnumerateIfPhoneBookOrSameGroupInOwnGroupsOnly(): void {
$this->config
->method('getAppValue')
->willReturnMap([
@@ -677,7 +677,7 @@ class ContactsStoreTest extends TestCase {
$this->assertEquals('contact', $entries[2]->getProperty('UID'));
}
- public function testGetContactsWithFilter() {
+ public function testGetContactsWithFilter(): void {
$this->config
->method('getAppValue')
->willReturnMap([
@@ -764,7 +764,7 @@ class ContactsStoreTest extends TestCase {
], $entry[0]->getEMailAddresses());
}
- public function testGetContactsWithFilterWithoutFullMatch() {
+ public function testGetContactsWithFilterWithoutFullMatch(): void {
$this->config
->method('getAppValue')
->willReturnMap([
@@ -848,7 +848,7 @@ class ContactsStoreTest extends TestCase {
], $entry[0]->getEMailAddresses());
}
- public function testFindOneUser() {
+ public function testFindOneUser(): void {
$this->config
->method('getAppValue')
->willReturnMap([
@@ -891,7 +891,7 @@ class ContactsStoreTest extends TestCase {
], $entry->getEMailAddresses());
}
- public function testFindOneEMail() {
+ public function testFindOneEMail(): void {
/** @var IUser|MockObject $user */
$user = $this->createMock(IUser::class);
$this->contactsManager->expects($this->once())
@@ -922,7 +922,7 @@ class ContactsStoreTest extends TestCase {
], $entry->getEMailAddresses());
}
- public function testFindOneNotSupportedType() {
+ public function testFindOneNotSupportedType(): void {
/** @var IUser|MockObject $user */
$user = $this->createMock(IUser::class);
@@ -931,7 +931,7 @@ class ContactsStoreTest extends TestCase {
$this->assertEquals(null, $entry);
}
- public function testFindOneNoMatches() {
+ public function testFindOneNoMatches(): void {
/** @var IUser|MockObject $user */
$user = $this->createMock(IUser::class);
$this->contactsManager->expects($this->once())
diff --git a/tests/lib/Contacts/ContactsMenu/EntryTest.php b/tests/lib/Contacts/ContactsMenu/EntryTest.php
index b06054ee77b..15f5b60b948 100644
--- a/tests/lib/Contacts/ContactsMenu/EntryTest.php
+++ b/tests/lib/Contacts/ContactsMenu/EntryTest.php
@@ -20,25 +20,25 @@ class EntryTest extends TestCase {
$this->entry = new Entry();
}
- public function testSetId() {
+ public function testSetId(): void {
$this->entry->setId(123);
$this->addToAssertionCount(1);
}
- public function testSetGetFullName() {
+ public function testSetGetFullName(): void {
$fn = 'Danette Chaille';
$this->assertEquals('', $this->entry->getFullName());
$this->entry->setFullName($fn);
$this->assertEquals($fn, $this->entry->getFullName());
}
- public function testAddGetEMailAddresses() {
+ public function testAddGetEMailAddresses(): void {
$this->assertEmpty($this->entry->getEMailAddresses());
$this->entry->addEMailAddress('user@example.com');
$this->assertEquals(['user@example.com'], $this->entry->getEMailAddresses());
}
- public function testAddAndSortAction() {
+ public function testAddAndSortAction(): void {
// Three actions, two with equal priority
$action1 = new LinkAction();
$action2 = new LinkAction();
@@ -62,7 +62,7 @@ class EntryTest extends TestCase {
$this->assertSame($action2, $sorted[2]);
}
- public function testSetGetProperties() {
+ public function testSetGetProperties(): void {
$props = [
'prop1' => 123,
'prop2' => 'string',
@@ -75,7 +75,7 @@ class EntryTest extends TestCase {
$this->assertEquals('string', $this->entry->getProperty('prop2'));
}
- public function testJsonSerialize() {
+ public function testJsonSerialize(): void {
$expectedJson = [
'id' => '123',
'fullName' => 'Guadalupe Frisbey',
diff --git a/tests/lib/Contacts/ContactsMenu/ManagerTest.php b/tests/lib/Contacts/ContactsMenu/ManagerTest.php
index 27ae9f5415c..c87bb3d5147 100644
--- a/tests/lib/Contacts/ContactsMenu/ManagerTest.php
+++ b/tests/lib/Contacts/ContactsMenu/ManagerTest.php
@@ -57,7 +57,7 @@ class ManagerTest extends TestCase {
return $entries;
}
- public function testGetFilteredEntries() {
+ public function testGetFilteredEntries(): void {
$filter = 'con';
$user = $this->createMock(IUser::class);
$entries = $this->generateTestEntries();
@@ -94,7 +94,7 @@ class ManagerTest extends TestCase {
$this->assertEquals($expected, $data);
}
- public function testGetFilteredEntriesLimit() {
+ public function testGetFilteredEntriesLimit(): void {
$filter = 'con';
$user = $this->createMock(IUser::class);
$entries = $this->generateTestEntries();
@@ -131,7 +131,7 @@ class ManagerTest extends TestCase {
$this->assertEquals($expected, $data);
}
- public function testGetFilteredEntriesMinSearchStringLength() {
+ public function testGetFilteredEntriesMinSearchStringLength(): void {
$filter = 'con';
$user = $this->createMock(IUser::class);
$provider = $this->createMock(IProvider::class);
@@ -157,7 +157,7 @@ class ManagerTest extends TestCase {
$this->assertEquals($expected, $data);
}
- public function testFindOne() {
+ public function testFindOne(): void {
$shareTypeFilter = 42;
$shareWithFilter = 'foobar';
@@ -180,7 +180,7 @@ class ManagerTest extends TestCase {
$this->assertEquals($entry, $data);
}
- public function testFindOne404() {
+ public function testFindOne404(): void {
$shareTypeFilter = 42;
$shareWithFilter = 'foobar';
diff --git a/tests/lib/Contacts/ContactsMenu/Providers/EMailproviderTest.php b/tests/lib/Contacts/ContactsMenu/Providers/EMailproviderTest.php
index 0c7c4922939..648351c2ca9 100644
--- a/tests/lib/Contacts/ContactsMenu/Providers/EMailproviderTest.php
+++ b/tests/lib/Contacts/ContactsMenu/Providers/EMailproviderTest.php
@@ -33,7 +33,7 @@ class EMailproviderTest extends TestCase {
$this->provider = new EMailProvider($this->actionFactory, $this->urlGenerator);
}
- public function testProcess() {
+ public function testProcess(): void {
$entry = $this->createMock(IEntry::class);
$action = $this->createMock(ILinkAction::class);
$iconUrl = 'https://example.com/img/actions/icon.svg';
@@ -60,7 +60,7 @@ class EMailproviderTest extends TestCase {
$this->provider->process($entry);
}
- public function testProcessEmptyAddress() {
+ public function testProcessEmptyAddress(): void {
$entry = $this->createMock(IEntry::class);
$iconUrl = 'https://example.com/img/actions/icon.svg';
$this->urlGenerator->expects($this->once())
diff --git a/tests/lib/ContactsManagerTest.php b/tests/lib/ContactsManagerTest.php
index 8219c5899d6..a726715c1bd 100644
--- a/tests/lib/ContactsManagerTest.php
+++ b/tests/lib/ContactsManagerTest.php
@@ -65,7 +65,7 @@ class ContactsManagerTest extends \Test\TestCase {
/**
* @dataProvider searchProvider
*/
- public function testSearch($search1, $search2, $expectedResult) {
+ public function testSearch($search1, $search2, $expectedResult): void {
/** @var \PHPUnit\Framework\MockObject\MockObject|IAddressBook $addressbook */
$addressbook1 = $this->getMockBuilder(\OCP\IAddressBook::class)
->disableOriginalConstructor()
@@ -99,7 +99,7 @@ class ContactsManagerTest extends \Test\TestCase {
}
- public function testDeleteHavePermission() {
+ public function testDeleteHavePermission(): void {
/** @var \PHPUnit\Framework\MockObject\MockObject|IAddressBook $addressbook */
$addressbook = $this->getMockBuilder(\OCP\IAddressBook::class)
->disableOriginalConstructor()
@@ -122,7 +122,7 @@ class ContactsManagerTest extends \Test\TestCase {
$this->assertEquals($result, 'returnMe');
}
- public function testDeleteNoPermission() {
+ public function testDeleteNoPermission(): void {
/** @var \PHPUnit\Framework\MockObject\MockObject|IAddressBook $addressbook */
$addressbook = $this->getMockBuilder(\OCP\IAddressBook::class)
->disableOriginalConstructor()
@@ -144,7 +144,7 @@ class ContactsManagerTest extends \Test\TestCase {
$this->assertEquals($result, null);
}
- public function testDeleteNoAddressbook() {
+ public function testDeleteNoAddressbook(): void {
/** @var \PHPUnit\Framework\MockObject\MockObject|IAddressBook $addressbook */
$addressbook = $this->getMockBuilder(\OCP\IAddressBook::class)
->disableOriginalConstructor()
@@ -162,7 +162,7 @@ class ContactsManagerTest extends \Test\TestCase {
$this->assertEquals($result, null);
}
- public function testCreateOrUpdateHavePermission() {
+ public function testCreateOrUpdateHavePermission(): void {
/** @var \PHPUnit\Framework\MockObject\MockObject|IAddressBook $addressbook */
$addressbook = $this->getMockBuilder(\OCP\IAddressBook::class)
->disableOriginalConstructor()
@@ -185,7 +185,7 @@ class ContactsManagerTest extends \Test\TestCase {
$this->assertEquals($result, 'returnMe');
}
- public function testCreateOrUpdateNoPermission() {
+ public function testCreateOrUpdateNoPermission(): void {
/** @var \PHPUnit\Framework\MockObject\MockObject|IAddressBook $addressbook */
$addressbook = $this->getMockBuilder(\OCP\IAddressBook::class)
->disableOriginalConstructor()
@@ -207,7 +207,7 @@ class ContactsManagerTest extends \Test\TestCase {
$this->assertEquals($result, null);
}
- public function testCreateOrUpdateNOAdressbook() {
+ public function testCreateOrUpdateNOAdressbook(): void {
/** @var \PHPUnit\Framework\MockObject\MockObject|IAddressBook $addressbook */
$addressbook = $this->getMockBuilder(\OCP\IAddressBook::class)
->disableOriginalConstructor()
@@ -225,12 +225,12 @@ class ContactsManagerTest extends \Test\TestCase {
$this->assertEquals($result, null);
}
- public function testIsEnabledIfNot() {
+ public function testIsEnabledIfNot(): void {
$result = $this->cm->isEnabled();
$this->assertFalse($result);
}
- public function testIsEnabledIfSo() {
+ public function testIsEnabledIfSo(): void {
/** @var \PHPUnit\Framework\MockObject\MockObject|IAddressBook $addressbook */
$addressbook = $this->getMockBuilder(\OCP\IAddressBook::class)
->disableOriginalConstructor()
@@ -245,7 +245,7 @@ class ContactsManagerTest extends \Test\TestCase {
$this->assertTrue($result);
}
- public function testAddressBookEnumeration() {
+ public function testAddressBookEnumeration(): void {
// create mock for the addressbook
/** @var \PHPUnit\Framework\MockObject\MockObject|IAddressBook $addressbook */
$addressbook = $this->getMockBuilder(\OCP\IAddressBook::class)
diff --git a/tests/lib/DB/ConnectionFactoryTest.php b/tests/lib/DB/ConnectionFactoryTest.php
index d889021f2b4..23bde34a8fb 100644
--- a/tests/lib/DB/ConnectionFactoryTest.php
+++ b/tests/lib/DB/ConnectionFactoryTest.php
@@ -31,7 +31,7 @@ class ConnectionFactoryTest extends TestCase {
* @param string $host
* @param array $expected
*/
- public function testSplitHostFromPortAndSocket($host, array $expected) {
+ public function testSplitHostFromPortAndSocket($host, array $expected): void {
/** @var SystemConfig $config */
$config = $this->createMock(SystemConfig::class);
$cacheFactory = $this->createMock(ICacheFactory::class);
diff --git a/tests/lib/DB/MigrationsTest.php b/tests/lib/DB/MigrationsTest.php
index eff7b764958..2be82a34ea8 100644
--- a/tests/lib/DB/MigrationsTest.php
+++ b/tests/lib/DB/MigrationsTest.php
@@ -55,14 +55,14 @@ class MigrationsTest extends \Test\TestCase {
$this->appManager = Server::get(IAppManager::class);
}
- public function testGetters() {
+ public function testGetters(): void {
$this->assertEquals('testing', $this->migrationService->getApp());
$this->assertEquals(\OC::$SERVERROOT . '/apps/testing/lib/Migration', $this->migrationService->getMigrationsDirectory());
$this->assertEquals('OCA\Testing\Migration', $this->migrationService->getMigrationsNamespace());
$this->assertEquals('test_oc_migrations', $this->migrationService->getMigrationsTableName());
}
- public function testCore() {
+ public function testCore(): void {
$this->migrationService = new MigrationService('core', $this->db);
$this->assertEquals('core', $this->migrationService->getApp());
@@ -72,7 +72,7 @@ class MigrationsTest extends \Test\TestCase {
}
- public function testExecuteUnknownStep() {
+ public function testExecuteUnknownStep(): void {
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Version 20170130180000 is unknown.');
@@ -80,7 +80,7 @@ class MigrationsTest extends \Test\TestCase {
}
- public function testUnknownApp() {
+ public function testUnknownApp(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('App not found');
@@ -88,7 +88,7 @@ class MigrationsTest extends \Test\TestCase {
}
- public function testExecuteStepWithUnknownClass() {
+ public function testExecuteStepWithUnknownClass(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Migration step \'X\' is unknown');
@@ -102,7 +102,7 @@ class MigrationsTest extends \Test\TestCase {
$this->migrationService->executeStep('20170130180000');
}
- public function testExecuteStepWithSchemaChange() {
+ public function testExecuteStepWithSchemaChange(): void {
$schema = $this->createMock(Schema::class);
$this->db->expects($this->any())
->method('createSchema')
@@ -145,7 +145,7 @@ class MigrationsTest extends \Test\TestCase {
$this->migrationService->executeStep('20170130180000');
}
- public function testExecuteStepWithoutSchemaChange() {
+ public function testExecuteStepWithoutSchemaChange(): void {
$schema = $this->createMock(Schema::class);
$this->db->expects($this->any())
->method('createSchema')
@@ -189,7 +189,7 @@ class MigrationsTest extends \Test\TestCase {
* @param string $alias
* @param string $expected
*/
- public function testGetMigration($alias, $expected) {
+ public function testGetMigration($alias, $expected): void {
$this->migrationService = $this->getMockBuilder(MigrationService::class)
->setMethods(['getMigratedVersions', 'findMigrations'])
->setConstructorArgs(['testing', $this->db])
@@ -209,7 +209,7 @@ class MigrationsTest extends \Test\TestCase {
$this->assertEquals($expected, $migration);
}
- public function testMigrate() {
+ public function testMigrate(): void {
$this->migrationService = $this->getMockBuilder(MigrationService::class)
->setMethods(['getMigratedVersions', 'findMigrations', 'executeStep'])
->setConstructorArgs(['testing', $this->db])
@@ -230,7 +230,7 @@ class MigrationsTest extends \Test\TestCase {
$this->migrationService->migrate();
}
- public function testEnsureOracleConstraintsValid() {
+ public function testEnsureOracleConstraintsValid(): void {
$column = $this->createMock(Column::class);
$column->expects($this->once())
->method('getName')
@@ -293,7 +293,7 @@ class MigrationsTest extends \Test\TestCase {
self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
}
- public function testEnsureOracleConstraintsValidWithPrimaryKey() {
+ public function testEnsureOracleConstraintsValidWithPrimaryKey(): void {
$index = $this->createMock(Index::class);
$index->expects($this->any())
->method('getName')
@@ -336,7 +336,7 @@ class MigrationsTest extends \Test\TestCase {
self::invokePrivate($this->migrationService, 'ensureOracleConstraints', [$sourceSchema, $schema, 3]);
}
- public function testEnsureOracleConstraintsValidWithPrimaryKeyDefault() {
+ public function testEnsureOracleConstraintsValidWithPrimaryKeyDefault(): void {
$defaultName = 'PRIMARY';
if ($this->db->getDatabaseProvider() === IDBConnection::PLATFORM_POSTGRES) {
$defaultName = \str_repeat('a', 26) . '_' . \str_repeat('b', 30) . '_seq';
@@ -390,7 +390,7 @@ class MigrationsTest extends \Test\TestCase {
}
- public function testEnsureOracleConstraintsTooLongTableName() {
+ public function testEnsureOracleConstraintsTooLongTableName(): void {
$this->expectException(\InvalidArgumentException::class);
$table = $this->createMock(Table::class);
@@ -415,7 +415,7 @@ class MigrationsTest extends \Test\TestCase {
}
- public function testEnsureOracleConstraintsTooLongPrimaryWithDefault() {
+ public function testEnsureOracleConstraintsTooLongPrimaryWithDefault(): void {
$this->expectException(\InvalidArgumentException::class);
$defaultName = 'PRIMARY';
@@ -468,7 +468,7 @@ class MigrationsTest extends \Test\TestCase {
}
- public function testEnsureOracleConstraintsTooLongPrimaryWithName() {
+ public function testEnsureOracleConstraintsTooLongPrimaryWithName(): void {
$this->expectException(\InvalidArgumentException::class);
$index = $this->createMock(Index::class);
@@ -511,7 +511,7 @@ class MigrationsTest extends \Test\TestCase {
}
- public function testEnsureOracleConstraintsTooLongColumnName() {
+ public function testEnsureOracleConstraintsTooLongColumnName(): void {
$this->expectException(\InvalidArgumentException::class);
$column = $this->createMock(Column::class);
@@ -545,7 +545,7 @@ class MigrationsTest extends \Test\TestCase {
}
- public function testEnsureOracleConstraintsTooLongIndexName() {
+ public function testEnsureOracleConstraintsTooLongIndexName(): void {
$this->expectException(\InvalidArgumentException::class);
$index = $this->createMock(Index::class);
@@ -582,7 +582,7 @@ class MigrationsTest extends \Test\TestCase {
}
- public function testEnsureOracleConstraintsTooLongForeignKeyName() {
+ public function testEnsureOracleConstraintsTooLongForeignKeyName(): void {
$this->expectException(\InvalidArgumentException::class);
$foreignKey = $this->createMock(ForeignKeyConstraint::class);
@@ -622,7 +622,7 @@ class MigrationsTest extends \Test\TestCase {
}
- public function testEnsureOracleConstraintsNoPrimaryKey() {
+ public function testEnsureOracleConstraintsNoPrimaryKey(): void {
$this->markTestSkipped('Test disabled for now due to multiple reasons, see https://github.com/nextcloud/server/pull/31580#issuecomment-1069182234 for details.');
$this->expectException(\InvalidArgumentException::class);
@@ -663,7 +663,7 @@ class MigrationsTest extends \Test\TestCase {
}
- public function testEnsureOracleConstraintsTooLongSequenceName() {
+ public function testEnsureOracleConstraintsTooLongSequenceName(): void {
$this->expectException(\InvalidArgumentException::class);
$sequence = $this->createMock(Sequence::class);
@@ -691,7 +691,7 @@ class MigrationsTest extends \Test\TestCase {
}
- public function testEnsureOracleConstraintsBooleanNotNull() {
+ public function testEnsureOracleConstraintsBooleanNotNull(): void {
$this->expectException(\InvalidArgumentException::class);
$column = $this->createMock(Column::class);
@@ -731,7 +731,7 @@ class MigrationsTest extends \Test\TestCase {
}
- public function testEnsureOracleConstraintsStringLength4000() {
+ public function testEnsureOracleConstraintsStringLength4000(): void {
$this->expectException(\InvalidArgumentException::class);
$column = $this->createMock(Column::class);
@@ -771,7 +771,7 @@ class MigrationsTest extends \Test\TestCase {
}
- public function testExtractMigrationAttributes() {
+ public function testExtractMigrationAttributes(): void {
$metadataManager = Server::get(MetadataManager::class);
$this->appManager->loadApp('testing');
@@ -780,7 +780,7 @@ class MigrationsTest extends \Test\TestCase {
$this->appManager->disableApp('testing');
}
- public function testDeserializeMigrationMetadata() {
+ public function testDeserializeMigrationMetadata(): void {
$metadataManager = Server::get(MetadataManager::class);
$this->assertEquals(
[
diff --git a/tests/lib/DB/MigratorTest.php b/tests/lib/DB/MigratorTest.php
index 929dc9aaf1b..c6afe5a053a 100644
--- a/tests/lib/DB/MigratorTest.php
+++ b/tests/lib/DB/MigratorTest.php
@@ -126,7 +126,7 @@ class MigratorTest extends \Test\TestCase {
return $config;
}
- public function testUpgrade() {
+ public function testUpgrade(): void {
[$startSchema, $endSchema] = $this->getDuplicateKeySchemas();
$migrator = $this->getMigrator();
$migrator->migrate($startSchema);
@@ -139,7 +139,7 @@ class MigratorTest extends \Test\TestCase {
$this->addToAssertionCount(1);
}
- public function testUpgradeDifferentPrefix() {
+ public function testUpgradeDifferentPrefix(): void {
$oldTablePrefix = $this->config->getSystemValueString('dbtableprefix', 'oc_');
$this->config->setSystemValue('dbtableprefix', 'ownc_');
@@ -159,7 +159,7 @@ class MigratorTest extends \Test\TestCase {
$this->config->setSystemValue('dbtableprefix', $oldTablePrefix);
}
- public function testInsertAfterUpgrade() {
+ public function testInsertAfterUpgrade(): void {
[$startSchema, $endSchema] = $this->getDuplicateKeySchemas();
$migrator = $this->getMigrator();
$migrator->migrate($startSchema);
@@ -176,7 +176,7 @@ class MigratorTest extends \Test\TestCase {
}
}
- public function testAddingPrimaryKeyWithAutoIncrement() {
+ public function testAddingPrimaryKeyWithAutoIncrement(): void {
$startSchema = new Schema([], [], $this->getSchemaConfig());
$table = $startSchema->createTable($this->tableName);
$table->addColumn('id', 'integer');
@@ -196,7 +196,7 @@ class MigratorTest extends \Test\TestCase {
$this->addToAssertionCount(1);
}
- public function testReservedKeywords() {
+ public function testReservedKeywords(): void {
$startSchema = new Schema([], [], $this->getSchemaConfig());
$table = $startSchema->createTable($this->tableName);
$table->addColumn('id', 'integer', ['autoincrement' => true]);
@@ -220,7 +220,7 @@ class MigratorTest extends \Test\TestCase {
/**
* Test for nextcloud/server#36803
*/
- public function testColumnCommentsInUpdate() {
+ public function testColumnCommentsInUpdate(): void {
$startSchema = new Schema([], [], $this->getSchemaConfig());
$table = $startSchema->createTable($this->tableName);
$table->addColumn('id', 'integer', ['autoincrement' => true, 'comment' => 'foo']);
@@ -241,7 +241,7 @@ class MigratorTest extends \Test\TestCase {
$this->addToAssertionCount(1);
}
- public function testAddingForeignKey() {
+ public function testAddingForeignKey(): void {
$startSchema = new Schema([], [], $this->getSchemaConfig());
$table = $startSchema->createTable($this->tableName);
$table->addColumn('id', 'integer', ['autoincrement' => true]);
diff --git a/tests/lib/DB/OCPostgreSqlPlatformTest.php b/tests/lib/DB/OCPostgreSqlPlatformTest.php
index 200fcbf36b3..bea3adf29a4 100644
--- a/tests/lib/DB/OCPostgreSqlPlatformTest.php
+++ b/tests/lib/DB/OCPostgreSqlPlatformTest.php
@@ -23,7 +23,7 @@ use Doctrine\DBAL\Types\Types;
* @package Test\DB
*/
class OCPostgreSqlPlatformTest extends \Test\TestCase {
- public function testAlterBigint() {
+ public function testAlterBigint(): void {
$platform = new PostgreSQLPlatform();
$sourceSchema = new Schema();
$targetSchema = new Schema();
diff --git a/tests/lib/DB/QueryBuilder/ExpressionBuilderDBTest.php b/tests/lib/DB/QueryBuilder/ExpressionBuilderDBTest.php
index 68dc4c1b712..ed6e328881b 100644
--- a/tests/lib/DB/QueryBuilder/ExpressionBuilderDBTest.php
+++ b/tests/lib/DB/QueryBuilder/ExpressionBuilderDBTest.php
@@ -52,7 +52,7 @@ class ExpressionBuilderDBTest extends TestCase {
* @param string $param2
* @param boolean $match
*/
- public function testLike($param1, $param2, $match) {
+ public function testLike($param1, $param2, $match): void {
$query = $this->connection->getQueryBuilder();
$query->select(new Literal('1'))
@@ -89,7 +89,7 @@ class ExpressionBuilderDBTest extends TestCase {
* @param string $param2
* @param boolean $match
*/
- public function testILike($param1, $param2, $match) {
+ public function testILike($param1, $param2, $match): void {
$query = $this->connection->getQueryBuilder();
$query->select(new Literal('1'))
@@ -141,7 +141,7 @@ class ExpressionBuilderDBTest extends TestCase {
self::assertEquals('myvalue', $entries[0]['configvalue']);
}
- public function testDateTimeEquals() {
+ public function testDateTimeEquals(): void {
$dateTime = new \DateTime('2023-01-01');
$insert = $this->connection->getQueryBuilder();
$insert->insert('testing')
@@ -158,7 +158,7 @@ class ExpressionBuilderDBTest extends TestCase {
self::assertCount(1, $entries);
}
- public function testDateTimeLess() {
+ public function testDateTimeLess(): void {
$dateTime = new \DateTime('2022-01-01');
$dateTimeCompare = new \DateTime('2022-01-02');
$insert = $this->connection->getQueryBuilder();
@@ -176,7 +176,7 @@ class ExpressionBuilderDBTest extends TestCase {
self::assertCount(1, $entries);
}
- public function testDateTimeGreater() {
+ public function testDateTimeGreater(): void {
$dateTime = new \DateTime('2023-01-02');
$dateTimeCompare = new \DateTime('2023-01-01');
$insert = $this->connection->getQueryBuilder();
diff --git a/tests/lib/DB/QueryBuilder/ExpressionBuilderTest.php b/tests/lib/DB/QueryBuilder/ExpressionBuilderTest.php
index 33a047e106b..48f88df14f2 100644
--- a/tests/lib/DB/QueryBuilder/ExpressionBuilderTest.php
+++ b/tests/lib/DB/QueryBuilder/ExpressionBuilderTest.php
@@ -72,7 +72,7 @@ class ExpressionBuilderTest extends TestCase {
* @param mixed $input2
* @param bool $isInput2Literal
*/
- public function testComparison($comparison, $input1, $isInput1Literal, $input2, $isInput2Literal) {
+ public function testComparison($comparison, $input1, $isInput1Literal, $input2, $isInput2Literal): void {
[$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal);
[$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal);
@@ -99,7 +99,7 @@ class ExpressionBuilderTest extends TestCase {
* @param mixed $input2
* @param bool $isInput2Literal
*/
- public function testEquals($input1, $isInput1Literal, $input2, $isInput2Literal) {
+ public function testEquals($input1, $isInput1Literal, $input2, $isInput2Literal): void {
[$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal);
[$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal);
@@ -117,7 +117,7 @@ class ExpressionBuilderTest extends TestCase {
* @param mixed $input2
* @param bool $isInput2Literal
*/
- public function testNotEquals($input1, $isInput1Literal, $input2, $isInput2Literal) {
+ public function testNotEquals($input1, $isInput1Literal, $input2, $isInput2Literal): void {
[$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal);
[$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal);
@@ -135,7 +135,7 @@ class ExpressionBuilderTest extends TestCase {
* @param mixed $input2
* @param bool $isInput2Literal
*/
- public function testLowerThan($input1, $isInput1Literal, $input2, $isInput2Literal) {
+ public function testLowerThan($input1, $isInput1Literal, $input2, $isInput2Literal): void {
[$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal);
[$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal);
@@ -153,7 +153,7 @@ class ExpressionBuilderTest extends TestCase {
* @param mixed $input2
* @param bool $isInput2Literal
*/
- public function testLowerThanEquals($input1, $isInput1Literal, $input2, $isInput2Literal) {
+ public function testLowerThanEquals($input1, $isInput1Literal, $input2, $isInput2Literal): void {
[$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal);
[$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal);
@@ -171,7 +171,7 @@ class ExpressionBuilderTest extends TestCase {
* @param mixed $input2
* @param bool $isInput2Literal
*/
- public function testGreaterThan($input1, $isInput1Literal, $input2, $isInput2Literal) {
+ public function testGreaterThan($input1, $isInput1Literal, $input2, $isInput2Literal): void {
[$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal);
[$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal);
@@ -189,7 +189,7 @@ class ExpressionBuilderTest extends TestCase {
* @param mixed $input2
* @param bool $isInput2Literal
*/
- public function testGreaterThanEquals($input1, $isInput1Literal, $input2, $isInput2Literal) {
+ public function testGreaterThanEquals($input1, $isInput1Literal, $input2, $isInput2Literal): void {
[$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal);
[$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal);
@@ -199,14 +199,14 @@ class ExpressionBuilderTest extends TestCase {
);
}
- public function testIsNull() {
+ public function testIsNull(): void {
$this->assertEquals(
$this->doctrineExpressionBuilder->isNull('`test`'),
$this->expressionBuilder->isNull('test')
);
}
- public function testIsNotNull() {
+ public function testIsNotNull(): void {
$this->assertEquals(
$this->doctrineExpressionBuilder->isNotNull('`test`'),
$this->expressionBuilder->isNotNull('test')
@@ -226,7 +226,7 @@ class ExpressionBuilderTest extends TestCase {
* @param mixed $input
* @param bool $isLiteral
*/
- public function testLike($input, $isLiteral) {
+ public function testLike($input, $isLiteral): void {
[$doctrineInput, $ocInput] = $this->helpWithLiteral($input, $isLiteral);
$this->assertEquals(
@@ -241,7 +241,7 @@ class ExpressionBuilderTest extends TestCase {
* @param mixed $input
* @param bool $isLiteral
*/
- public function testNotLike($input, $isLiteral) {
+ public function testNotLike($input, $isLiteral): void {
[$doctrineInput, $ocInput] = $this->helpWithLiteral($input, $isLiteral);
$this->assertEquals(
@@ -265,7 +265,7 @@ class ExpressionBuilderTest extends TestCase {
* @param mixed $input
* @param bool $isLiteral
*/
- public function testIn($input, $isLiteral) {
+ public function testIn($input, $isLiteral): void {
[$doctrineInput, $ocInput] = $this->helpWithLiteral($input, $isLiteral);
$this->assertEquals(
@@ -280,7 +280,7 @@ class ExpressionBuilderTest extends TestCase {
* @param mixed $input
* @param bool $isLiteral
*/
- public function testNotIn($input, $isLiteral) {
+ public function testNotIn($input, $isLiteral): void {
[$doctrineInput, $ocInput] = $this->helpWithLiteral($input, $isLiteral);
$this->assertEquals(
@@ -334,7 +334,7 @@ class ExpressionBuilderTest extends TestCase {
* @param mixed $input
* @param string|null $type
*/
- public function testLiteral($input, $type) {
+ public function testLiteral($input, $type): void {
/** @var \OC\DB\QueryBuilder\Literal $actual */
$actual = $this->expressionBuilder->literal($input, $type);
@@ -380,7 +380,7 @@ class ExpressionBuilderTest extends TestCase {
* @param bool $compareKeyToValue
* @param int $expected
*/
- public function testClobComparisons($function, $value, $type, $compareKeyToValue, $expected) {
+ public function testClobComparisons($function, $value, $type, $compareKeyToValue, $expected): void {
$appId = $this->getUniqueID('testing');
$this->createConfig($appId, 1, 4);
$this->createConfig($appId, 2, 5);
diff --git a/tests/lib/DB/QueryBuilder/FunctionBuilderTest.php b/tests/lib/DB/QueryBuilder/FunctionBuilderTest.php
index 4f7cc4dd39f..f3007ace85c 100644
--- a/tests/lib/DB/QueryBuilder/FunctionBuilderTest.php
+++ b/tests/lib/DB/QueryBuilder/FunctionBuilderTest.php
@@ -30,7 +30,7 @@ class FunctionBuilderTest extends TestCase {
/**
* @dataProvider providerTestConcatString
*/
- public function testConcatString($closure) {
+ public function testConcatString($closure): void {
$query = $this->connection->getQueryBuilder();
[$real, $arguments, $return] = $closure($query);
if ($real) {
@@ -232,7 +232,7 @@ class FunctionBuilderTest extends TestCase {
$this->assertEqualsCanonicalizing([1,2,3], $actual);
}
- public function testMd5() {
+ public function testMd5(): void {
$query = $this->connection->getQueryBuilder();
$query->select($query->func()->md5($query->createNamedParameter('foobar')));
@@ -245,7 +245,7 @@ class FunctionBuilderTest extends TestCase {
$this->assertEquals(md5('foobar'), $column);
}
- public function testSubstring() {
+ public function testSubstring(): void {
$query = $this->connection->getQueryBuilder();
$query->select($query->func()->substring($query->createNamedParameter('foobar'), new Literal(2), $query->createNamedParameter(2)));
@@ -258,7 +258,7 @@ class FunctionBuilderTest extends TestCase {
$this->assertEquals('oo', $column);
}
- public function testSubstringNoLength() {
+ public function testSubstringNoLength(): void {
$query = $this->connection->getQueryBuilder();
$query->select($query->func()->substring($query->createNamedParameter('foobar'), new Literal(2)));
@@ -271,7 +271,7 @@ class FunctionBuilderTest extends TestCase {
$this->assertEquals('oobar', $column);
}
- public function testLower() {
+ public function testLower(): void {
$query = $this->connection->getQueryBuilder();
$query->select($query->func()->lower($query->createNamedParameter('FooBar')));
@@ -284,7 +284,7 @@ class FunctionBuilderTest extends TestCase {
$this->assertEquals('foobar', $column);
}
- public function testAdd() {
+ public function testAdd(): void {
$query = $this->connection->getQueryBuilder();
$query->select($query->func()->add($query->createNamedParameter(2, IQueryBuilder::PARAM_INT), new Literal(1)));
@@ -297,7 +297,7 @@ class FunctionBuilderTest extends TestCase {
$this->assertEquals(3, $column);
}
- public function testSubtract() {
+ public function testSubtract(): void {
$query = $this->connection->getQueryBuilder();
$query->select($query->func()->subtract($query->createNamedParameter(2, IQueryBuilder::PARAM_INT), new Literal(1)));
@@ -310,7 +310,7 @@ class FunctionBuilderTest extends TestCase {
$this->assertEquals(1, $column);
}
- public function testCount() {
+ public function testCount(): void {
$query = $this->connection->getQueryBuilder();
$query->select($query->func()->count('appid'));
@@ -335,7 +335,7 @@ class FunctionBuilderTest extends TestCase {
/**
* @dataProvider octetLengthProvider
*/
- public function testOctetLength(string $str, int $bytes) {
+ public function testOctetLength(string $str, int $bytes): void {
$query = $this->connection->getQueryBuilder();
$query->select($query->func()->octetLength($query->createNamedParameter($str, IQueryBuilder::PARAM_STR)));
@@ -360,7 +360,7 @@ class FunctionBuilderTest extends TestCase {
/**
* @dataProvider charLengthProvider
*/
- public function testCharLength(string $str, int $bytes) {
+ public function testCharLength(string $str, int $bytes): void {
$query = $this->connection->getQueryBuilder();
$query->select($query->func()->charLength($query->createNamedParameter($str, IQueryBuilder::PARAM_STR)));
@@ -393,7 +393,7 @@ class FunctionBuilderTest extends TestCase {
$query->execute();
}
- public function testMaxEmpty() {
+ public function testMaxEmpty(): void {
$this->clearMinMax();
$query = $this->connection->getQueryBuilder();
@@ -409,7 +409,7 @@ class FunctionBuilderTest extends TestCase {
$this->assertEquals(null, $row);
}
- public function testMinEmpty() {
+ public function testMinEmpty(): void {
$this->clearMinMax();
$query = $this->connection->getQueryBuilder();
@@ -425,7 +425,7 @@ class FunctionBuilderTest extends TestCase {
$this->assertEquals(null, $row);
}
- public function testMax() {
+ public function testMax(): void {
$this->clearMinMax();
$this->setUpMinMax(10);
$this->setUpMinMax(11);
@@ -444,7 +444,7 @@ class FunctionBuilderTest extends TestCase {
$this->assertEquals(20, $row);
}
- public function testMin() {
+ public function testMin(): void {
$this->clearMinMax();
$this->setUpMinMax(10);
$this->setUpMinMax(11);
@@ -463,7 +463,7 @@ class FunctionBuilderTest extends TestCase {
$this->assertEquals(10, $row);
}
- public function testGreatest() {
+ public function testGreatest(): void {
$query = $this->connection->getQueryBuilder();
$query->select($query->func()->greatest($query->createNamedParameter(2, IQueryBuilder::PARAM_INT), new Literal(1)));
@@ -476,7 +476,7 @@ class FunctionBuilderTest extends TestCase {
$this->assertEquals(2, $row);
}
- public function testLeast() {
+ public function testLeast(): void {
$query = $this->connection->getQueryBuilder();
$query->select($query->func()->least($query->createNamedParameter(2, IQueryBuilder::PARAM_INT), new Literal(1)));
diff --git a/tests/lib/DB/QueryBuilder/Partitioned/PartitionedQueryBuilderTest.php b/tests/lib/DB/QueryBuilder/Partitioned/PartitionedQueryBuilderTest.php
index 12ba74fe89f..88a3c125044 100644
--- a/tests/lib/DB/QueryBuilder/Partitioned/PartitionedQueryBuilderTest.php
+++ b/tests/lib/DB/QueryBuilder/Partitioned/PartitionedQueryBuilderTest.php
@@ -115,7 +115,7 @@ class PartitionedQueryBuilderTest extends TestCase {
$query->executeStatement();
}
- public function testSimpleOnlyPartitionQuery() {
+ public function testSimpleOnlyPartitionQuery(): void {
$builder = $this->getQueryBuilder();
$builder->addPartition(new PartitionSplit('filecache', ['filecache']));
@@ -129,7 +129,7 @@ class PartitionedQueryBuilderTest extends TestCase {
$this->assertEquals($results[0]['path'], 'file1');
}
- public function testSimplePartitionedQuery() {
+ public function testSimplePartitionedQuery(): void {
$builder = $this->getQueryBuilder();
$builder->addPartition(new PartitionSplit('filecache', ['filecache']));
@@ -151,7 +151,7 @@ class PartitionedQueryBuilderTest extends TestCase {
$this->assertEquals($results[0]['path'], 'file1');
}
- public function testMultiTablePartitionedQuery() {
+ public function testMultiTablePartitionedQuery(): void {
$builder = $this->getQueryBuilder();
$builder->addPartition(new PartitionSplit('filecache', ['filecache', 'filecache_extended']));
@@ -174,7 +174,7 @@ class PartitionedQueryBuilderTest extends TestCase {
$this->assertEquals($results[0]['upload_time'], 1234);
}
- public function testPartitionedQueryFromSplit() {
+ public function testPartitionedQueryFromSplit(): void {
$builder = $this->getQueryBuilder();
$builder->addPartition(new PartitionSplit('filecache', ['filecache']));
@@ -195,7 +195,7 @@ class PartitionedQueryBuilderTest extends TestCase {
$this->assertEquals($results[0]['path'], 'file1');
}
- public function testMultiJoinPartitionedQuery() {
+ public function testMultiJoinPartitionedQuery(): void {
$builder = $this->getQueryBuilder();
$builder->addPartition(new PartitionSplit('filecache', ['filecache']));
diff --git a/tests/lib/DB/QueryBuilder/QueryBuilderTest.php b/tests/lib/DB/QueryBuilder/QueryBuilderTest.php
index 335666b54fd..508748f13b2 100644
--- a/tests/lib/DB/QueryBuilder/QueryBuilderTest.php
+++ b/tests/lib/DB/QueryBuilder/QueryBuilderTest.php
@@ -103,7 +103,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param int|null $firstResult
* @param array $expectedSet
*/
- public function testFirstResult($firstResult, $expectedSet) {
+ public function testFirstResult($firstResult, $expectedSet): void {
$this->deleteTestingRows();
$this->createTestingRows();
@@ -140,7 +140,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param int $maxResult
* @param array $expectedSet
*/
- public function testMaxResults($maxResult, $expectedSet) {
+ public function testMaxResults($maxResult, $expectedSet): void {
$this->deleteTestingRows();
$this->createTestingRows();
@@ -193,7 +193,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expected
* @param string $expectedLiteral
*/
- public function testSelect($selectArguments, $expected, $expectedLiteral = '') {
+ public function testSelect($selectArguments, $expected, $expectedLiteral = ''): void {
$this->deleteTestingRows();
$this->createTestingRows();
@@ -246,7 +246,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $alias
* @param array $expected
*/
- public function testSelectAlias($select, $alias, $expected) {
+ public function testSelectAlias($select, $alias, $expected): void {
$this->deleteTestingRows();
$this->createTestingRows();
@@ -272,7 +272,7 @@ class QueryBuilderTest extends \Test\TestCase {
$this->deleteTestingRows();
}
- public function testSelectDistinct() {
+ public function testSelectDistinct(): void {
$this->deleteTestingRows('testFirstResult1');
$this->deleteTestingRows('testFirstResult2');
$this->createTestingRows('testFirstResult1');
@@ -300,7 +300,7 @@ class QueryBuilderTest extends \Test\TestCase {
$this->deleteTestingRows('testFirstResult2');
}
- public function testSelectDistinctMultiple() {
+ public function testSelectDistinctMultiple(): void {
$this->deleteTestingRows('testFirstResult1');
$this->deleteTestingRows('testFirstResult2');
$this->createTestingRows('testFirstResult1');
@@ -370,7 +370,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expected
* @param string $expectedLiteral
*/
- public function testAddSelect($selectArguments, $expected, $expectedLiteral = '') {
+ public function testAddSelect($selectArguments, $expected, $expectedLiteral = ''): void {
$this->deleteTestingRows();
$this->createTestingRows();
@@ -423,7 +423,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
- public function testDelete($tableName, $tableAlias, $expectedQueryPart, $expectedQuery) {
+ public function testDelete($tableName, $tableAlias, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->delete($tableName, $tableAlias);
$this->assertSame(
@@ -452,7 +452,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
- public function testUpdate($tableName, $tableAlias, $expectedQueryPart, $expectedQuery) {
+ public function testUpdate($tableName, $tableAlias, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->update($tableName, $tableAlias);
$this->assertSame(
@@ -479,7 +479,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
- public function testInsert($tableName, $expectedQueryPart, $expectedQuery) {
+ public function testInsert($tableName, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->insert($tableName);
$this->assertSame(
@@ -524,7 +524,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
- public function testFrom($table1Name, $table1Alias, $table2Name, $table2Alias, $expectedQueryPart, $expectedQuery) {
+ public function testFrom($table1Name, $table1Alias, $table2Name, $table2Alias, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->from($table1Name, $table1Alias);
if ($table2Name !== null) {
$this->queryBuilder->from($table2Name, $table2Alias);
@@ -572,7 +572,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
- public function testJoin($fromAlias, $tableName, $tableAlias, $condition, $expectedQueryPart, $expectedQuery) {
+ public function testJoin($fromAlias, $tableName, $tableAlias, $condition, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->from('data1', 'd1');
$this->queryBuilder->join(
$fromAlias,
@@ -602,7 +602,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
- public function testInnerJoin($fromAlias, $tableName, $tableAlias, $condition, $expectedQueryPart, $expectedQuery) {
+ public function testInnerJoin($fromAlias, $tableName, $tableAlias, $condition, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->from('data1', 'd1');
$this->queryBuilder->innerJoin(
$fromAlias,
@@ -652,7 +652,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
- public function testLeftJoin($fromAlias, $tableName, $tableAlias, $condition, $expectedQueryPart, $expectedQuery) {
+ public function testLeftJoin($fromAlias, $tableName, $tableAlias, $condition, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->from('data1', 'd1');
$this->queryBuilder->leftJoin(
$fromAlias,
@@ -702,7 +702,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
- public function testRightJoin($fromAlias, $tableName, $tableAlias, $condition, $expectedQueryPart, $expectedQuery) {
+ public function testRightJoin($fromAlias, $tableName, $tableAlias, $condition, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->from('data1', 'd1');
$this->queryBuilder->rightJoin(
$fromAlias,
@@ -741,7 +741,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
- public function testSet($partOne1, $partOne2, $partTwo1, $partTwo2, $expectedQueryPart, $expectedQuery) {
+ public function testSet($partOne1, $partOne2, $partTwo1, $partTwo2, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->update('data');
$this->queryBuilder->set($partOne1, $partOne2);
if ($partTwo1 !== null) {
@@ -773,7 +773,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
- public function testWhere($whereArguments, $expectedQueryPart, $expectedQuery) {
+ public function testWhere($whereArguments, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->select('column');
call_user_func_array(
[$this->queryBuilder, 'where'],
@@ -798,7 +798,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
- public function testAndWhere($whereArguments, $expectedQueryPart, $expectedQuery) {
+ public function testAndWhere($whereArguments, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->select('column');
call_user_func_array(
[$this->queryBuilder, 'andWhere'],
@@ -830,7 +830,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
- public function testOrWhere($whereArguments, $expectedQueryPart, $expectedQuery) {
+ public function testOrWhere($whereArguments, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->select('column');
call_user_func_array(
[$this->queryBuilder, 'orWhere'],
@@ -862,7 +862,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
- public function testGroupBy($groupByArguments, $expectedQueryPart, $expectedQuery) {
+ public function testGroupBy($groupByArguments, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->select('column');
call_user_func_array(
[$this->queryBuilder, 'groupBy'],
@@ -894,7 +894,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
- public function testAddGroupBy($groupByArguments, $expectedQueryPart, $expectedQuery) {
+ public function testAddGroupBy($groupByArguments, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->select('column');
$this->queryBuilder->groupBy('column1');
call_user_func_array(
@@ -927,7 +927,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
- public function testSetValue($column, $value, $expectedQueryPart, $expectedQuery) {
+ public function testSetValue($column, $value, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->insert('data');
$this->queryBuilder->setValue($column, $value);
@@ -950,7 +950,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
- public function testValues($column, $value, $expectedQueryPart, $expectedQuery) {
+ public function testValues($column, $value, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->insert('data');
$this->queryBuilder->values([
$column => $value,
@@ -991,7 +991,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
- public function testHaving($havingArguments, $expectedQueryPart, $expectedQuery) {
+ public function testHaving($havingArguments, $expectedQueryPart, $expectedQuery): void {
call_user_func_array(
[$this->queryBuilder, 'having'],
$havingArguments
@@ -1032,7 +1032,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
- public function testAndHaving($havingArguments, $expectedQueryPart, $expectedQuery) {
+ public function testAndHaving($havingArguments, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->having('condition1');
call_user_func_array(
[$this->queryBuilder, 'andHaving'],
@@ -1074,7 +1074,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
- public function testOrHaving($havingArguments, $expectedQueryPart, $expectedQuery) {
+ public function testOrHaving($havingArguments, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->having('condition1');
call_user_func_array(
[$this->queryBuilder, 'orHaving'],
@@ -1108,7 +1108,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
- public function testOrderBy($sort, $order, $expectedQueryPart, $expectedQuery) {
+ public function testOrderBy($sort, $order, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->orderBy($sort, $order);
$this->assertEquals(
@@ -1145,7 +1145,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param array $expectedQueryPart
* @param string $expectedQuery
*/
- public function testAddOrderBy($sort2, $order2, $order1, $expectedQueryPart, $expectedQuery) {
+ public function testAddOrderBy($sort2, $order2, $order1, $expectedQueryPart, $expectedQuery): void {
$this->queryBuilder->orderBy('column1', $order1);
$this->queryBuilder->addOrderBy($sort2, $order2);
@@ -1160,7 +1160,7 @@ class QueryBuilderTest extends \Test\TestCase {
);
}
- public function testGetLastInsertId() {
+ public function testGetLastInsertId(): void {
$qB = $this->connection->getQueryBuilder();
try {
@@ -1223,7 +1223,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param bool $automatic
* @param string $expected
*/
- public function testGetTableName($tableName, $automatic, $expected) {
+ public function testGetTableName($tableName, $automatic, $expected): void {
if ($automatic !== null) {
$this->queryBuilder->automaticTablePrefix($automatic);
}
@@ -1247,7 +1247,7 @@ class QueryBuilderTest extends \Test\TestCase {
* @param string $prefix
* @param string $expected
*/
- public function testGetColumnName($column, $prefix, $expected) {
+ public function testGetColumnName($column, $prefix, $expected): void {
$this->assertSame(
$expected,
$this->queryBuilder->getColumnName($column, $prefix)
@@ -1263,7 +1263,7 @@ class QueryBuilderTest extends \Test\TestCase {
return $connection;
}
- public function testExecuteWithoutLogger() {
+ public function testExecuteWithoutLogger(): void {
$queryBuilder = $this->createMock(\Doctrine\DBAL\Query\QueryBuilder::class);
$queryBuilder
->method('getSQL')
@@ -1291,7 +1291,7 @@ class QueryBuilderTest extends \Test\TestCase {
$this->assertEquals(3, $this->queryBuilder->execute());
}
- public function testExecuteWithLoggerAndNamedArray() {
+ public function testExecuteWithLoggerAndNamedArray(): void {
$queryBuilder = $this->createMock(\Doctrine\DBAL\Query\QueryBuilder::class);
$queryBuilder
->expects($this->any())
@@ -1335,7 +1335,7 @@ class QueryBuilderTest extends \Test\TestCase {
$this->assertEquals(3, $this->queryBuilder->execute());
}
- public function testExecuteWithLoggerAndUnnamedArray() {
+ public function testExecuteWithLoggerAndUnnamedArray(): void {
$queryBuilder = $this->createMock(\Doctrine\DBAL\Query\QueryBuilder::class);
$queryBuilder
->expects($this->any())
@@ -1373,7 +1373,7 @@ class QueryBuilderTest extends \Test\TestCase {
$this->assertEquals(3, $this->queryBuilder->execute());
}
- public function testExecuteWithLoggerAndNoParams() {
+ public function testExecuteWithLoggerAndNoParams(): void {
$queryBuilder = $this->createMock(\Doctrine\DBAL\Query\QueryBuilder::class);
$queryBuilder
->expects($this->any())
@@ -1410,7 +1410,7 @@ class QueryBuilderTest extends \Test\TestCase {
$this->assertEquals(3, $this->queryBuilder->execute());
}
- public function testExecuteWithParameterTooLarge() {
+ public function testExecuteWithParameterTooLarge(): void {
$queryBuilder = $this->createMock(\Doctrine\DBAL\Query\QueryBuilder::class);
$p = array_fill(0, 1001, 'foo');
$queryBuilder
@@ -1445,7 +1445,7 @@ class QueryBuilderTest extends \Test\TestCase {
$this->queryBuilder->execute();
}
- public function testExecuteWithParametersTooMany() {
+ public function testExecuteWithParametersTooMany(): void {
$queryBuilder = $this->createMock(\Doctrine\DBAL\Query\QueryBuilder::class);
$p = array_fill(0, 999, 'foo');
$queryBuilder
diff --git a/tests/lib/DB/QueryBuilder/QuoteHelperTest.php b/tests/lib/DB/QueryBuilder/QuoteHelperTest.php
index 12984bac3e0..3c2e33c28ea 100644
--- a/tests/lib/DB/QueryBuilder/QuoteHelperTest.php
+++ b/tests/lib/DB/QueryBuilder/QuoteHelperTest.php
@@ -41,7 +41,7 @@ class QuoteHelperTest extends \Test\TestCase {
* @param mixed $input
* @param string $expected
*/
- public function testQuoteColumnName($input, $expected) {
+ public function testQuoteColumnName($input, $expected): void {
$this->assertSame(
$expected,
$this->helper->quoteColumnName($input)
@@ -76,7 +76,7 @@ class QuoteHelperTest extends \Test\TestCase {
* @param mixed $input
* @param string $expected
*/
- public function testQuoteColumnNames($input, $expected) {
+ public function testQuoteColumnNames($input, $expected): void {
$this->assertSame(
$expected,
$this->helper->quoteColumnNames($input)
diff --git a/tests/lib/DB/QueryBuilder/Sharded/SharedQueryBuilderTest.php b/tests/lib/DB/QueryBuilder/Sharded/SharedQueryBuilderTest.php
index 8f95c1b6263..a135b9159dd 100644
--- a/tests/lib/DB/QueryBuilder/Sharded/SharedQueryBuilderTest.php
+++ b/tests/lib/DB/QueryBuilder/Sharded/SharedQueryBuilderTest.php
@@ -46,7 +46,7 @@ class SharedQueryBuilderTest extends TestCase {
);
}
- public function testGetShardKeySingleParam() {
+ public function testGetShardKeySingleParam(): void {
$query = $this->getQueryBuilder('filecache', 'storage', 'fileid');
$query->select('fileid', 'path')
->from('filecache')
@@ -56,7 +56,7 @@ class SharedQueryBuilderTest extends TestCase {
$this->assertEquals([10], $query->getShardKeys());
}
- public function testGetPrimaryKeyParam() {
+ public function testGetPrimaryKeyParam(): void {
$query = $this->getQueryBuilder('filecache', 'storage', 'fileid');
$query->select('fileid', 'path')
->from('filecache')
@@ -66,7 +66,7 @@ class SharedQueryBuilderTest extends TestCase {
$this->assertEquals([], $query->getShardKeys());
}
- public function testValidateWithShardKey() {
+ public function testValidateWithShardKey(): void {
$query = $this->getQueryBuilder('filecache', 'storage', 'fileid');
$query->select('fileid', 'path')
->from('filecache')
@@ -76,7 +76,7 @@ class SharedQueryBuilderTest extends TestCase {
$this->assertTrue(true);
}
- public function testValidateWithPrimaryKey() {
+ public function testValidateWithPrimaryKey(): void {
$query = $this->getQueryBuilder('filecache', 'storage', 'fileid');
$query->select('fileid', 'path')
->from('filecache')
@@ -86,7 +86,7 @@ class SharedQueryBuilderTest extends TestCase {
$this->assertTrue(true);
}
- public function testValidateWithNoKey() {
+ public function testValidateWithNoKey(): void {
$query = $this->getQueryBuilder('filecache', 'storage', 'fileid');
$query->select('fileid', 'path')
->from('filecache')
@@ -97,7 +97,7 @@ class SharedQueryBuilderTest extends TestCase {
$this->fail('exception expected');
}
- public function testValidateNonSharedTable() {
+ public function testValidateNonSharedTable(): void {
$query = $this->getQueryBuilder('filecache', 'storage', 'fileid');
$query->select('configvalue')
->from('appconfig')
@@ -107,7 +107,7 @@ class SharedQueryBuilderTest extends TestCase {
$this->assertTrue(true);
}
- public function testGetShardKeyMultipleSingleParam() {
+ public function testGetShardKeyMultipleSingleParam(): void {
$query = $this->getQueryBuilder('filecache', 'storage', 'fileid');
$query->select('fileid', 'path')
->from('filecache')
diff --git a/tests/lib/DateTimeFormatterTest.php b/tests/lib/DateTimeFormatterTest.php
index 8f6dacd4678..924cac9d399 100644
--- a/tests/lib/DateTimeFormatterTest.php
+++ b/tests/lib/DateTimeFormatterTest.php
@@ -77,7 +77,7 @@ class DateTimeFormatterTest extends TestCase {
/**
* @dataProvider formatTimeSpanData
*/
- public function testFormatTimeSpan($expected, $timestamp, $compare, $locale = null) {
+ public function testFormatTimeSpan($expected, $timestamp, $compare, $locale = null): void {
$this->assertEquals((string)$expected, (string)$this->formatter->formatTimeSpan($timestamp, $compare, $locale));
}
@@ -143,7 +143,7 @@ class DateTimeFormatterTest extends TestCase {
/**
* @dataProvider formatDateSpanData
*/
- public function testFormatDateSpan($expected, $timestamp, $compare = null, $locale = null) {
+ public function testFormatDateSpan($expected, $timestamp, $compare = null, $locale = null): void {
$this->assertEquals((string)$expected, (string)$this->formatter->formatDateSpan($timestamp, $compare, $locale));
}
@@ -156,7 +156,7 @@ class DateTimeFormatterTest extends TestCase {
/**
* @dataProvider formatDateData
*/
- public function testFormatDate($timestamp, $expected) {
+ public function testFormatDate($timestamp, $expected): void {
$this->assertEquals($expected, (string)$this->formatter->formatDate($timestamp));
}
@@ -170,12 +170,12 @@ class DateTimeFormatterTest extends TestCase {
/**
* @dataProvider formatDateTimeData
*/
- public function testFormatDateTime($timestamp, $timeZone, $expected) {
+ public function testFormatDateTime($timestamp, $timeZone, $expected): void {
$this->assertEquals($expected, (string)$this->formatter->formatDateTime($timestamp, 'long', 'long', $timeZone));
}
- public function testFormatDateWithInvalidTZ() {
+ public function testFormatDateWithInvalidTZ(): void {
$this->expectException(\Exception::class);
$this->formatter->formatDate(1350129205, 'long', new \DateTimeZone('Mordor/Barad-dûr'));
diff --git a/tests/lib/Diagnostics/EventLoggerTest.php b/tests/lib/Diagnostics/EventLoggerTest.php
index 46a58e4275d..3ad13702679 100644
--- a/tests/lib/Diagnostics/EventLoggerTest.php
+++ b/tests/lib/Diagnostics/EventLoggerTest.php
@@ -27,7 +27,7 @@ class EventLoggerTest extends TestCase {
);
}
- public function testQueryLogger() {
+ public function testQueryLogger(): void {
// Module is not activated and this should not be logged
$this->logger->start('test1', 'testevent1');
$this->logger->end('test1');
diff --git a/tests/lib/Diagnostics/QueryLoggerTest.php b/tests/lib/Diagnostics/QueryLoggerTest.php
index 04b8d8570e7..6450c153b39 100644
--- a/tests/lib/Diagnostics/QueryLoggerTest.php
+++ b/tests/lib/Diagnostics/QueryLoggerTest.php
@@ -20,7 +20,7 @@ class QueryLoggerTest extends TestCase {
$this->logger = new QueryLogger();
}
- public function testQueryLogger() {
+ public function testQueryLogger(): void {
// Module is not activated and this should not be logged
$this->logger->startQuery('SELECT', ['testuser', 'count'], ['string', 'int']);
$this->logger->stopQuery();
diff --git a/tests/lib/DirectEditing/ManagerTest.php b/tests/lib/DirectEditing/ManagerTest.php
index 3dc2e464c37..d26817438cf 100644
--- a/tests/lib/DirectEditing/ManagerTest.php
+++ b/tests/lib/DirectEditing/ManagerTest.php
@@ -156,12 +156,12 @@ class ManagerTest extends TestCase {
$this->manager->registerDirectEditor($this->editor);
}
- public function testEditorRegistration() {
+ public function testEditorRegistration(): void {
$this->assertEquals($this->manager->getEditors(), ['testeditor' => $this->editor]);
}
- public function testCreateToken() {
+ public function testCreateToken(): void {
$expectedToken = 'TOKEN' . time();
$file = $this->createMock(File::class);
$file->expects($this->any())
@@ -186,7 +186,7 @@ class ManagerTest extends TestCase {
$this->assertEquals($token, $expectedToken);
}
- public function testCreateTokenAccess() {
+ public function testCreateTokenAccess(): void {
$expectedToken = 'TOKEN' . time();
$file = $this->createMock(File::class);
$file->expects($this->any())
@@ -214,7 +214,7 @@ class ManagerTest extends TestCase {
$this->assertInstanceOf(NotFoundResponse::class, $secondResult);
}
- public function testOpenByPath() {
+ public function testOpenByPath(): void {
$expectedToken = 'TOKEN' . time();
$file = $this->createMock(File::class);
$file->expects($this->any())
@@ -245,7 +245,7 @@ class ManagerTest extends TestCase {
$this->assertInstanceOf(NotFoundResponse::class, $secondResult);
}
- public function testOpenById() {
+ public function testOpenById(): void {
$expectedToken = 'TOKEN' . time();
$fileRead = $this->createMock(File::class);
$fileRead->method('getPermissions')
@@ -294,7 +294,7 @@ class ManagerTest extends TestCase {
$this->assertInstanceOf(NotFoundResponse::class, $secondResult);
}
- public function testCreateFileAlreadyExists() {
+ public function testCreateFileAlreadyExists(): void {
$this->expectException(\RuntimeException::class);
$this->userFolder
->method('nodeExists')
diff --git a/tests/lib/Encryption/DecryptAllTest.php b/tests/lib/Encryption/DecryptAllTest.php
index 52f120fde82..1138d8c2e80 100644
--- a/tests/lib/Encryption/DecryptAllTest.php
+++ b/tests/lib/Encryption/DecryptAllTest.php
@@ -98,7 +98,7 @@ class DecryptAllTest extends TestCase {
* @param string $user
* @param bool $userExistsChecked
*/
- public function testDecryptAll($prepareResult, $user, $userExistsChecked) {
+ public function testDecryptAll($prepareResult, $user, $userExistsChecked): void {
if ($userExistsChecked) {
$this->userManager->expects($this->once())->method('userExists')->willReturn(true);
} else {
@@ -135,7 +135,7 @@ class DecryptAllTest extends TestCase {
/**
* test decrypt all call with a user who doesn't exists
*/
- public function testDecryptAllWrongUser() {
+ public function testDecryptAllWrongUser(): void {
$this->userManager->expects($this->once())->method('userExists')->willReturn(false);
$this->outputInterface->expects($this->once())->method('writeln')
->with('User "user1" does not exist. Please check the username and try again');
@@ -156,7 +156,7 @@ class DecryptAllTest extends TestCase {
* @dataProvider dataTrueFalse
* @param bool $success
*/
- public function testPrepareEncryptionModules($success) {
+ public function testPrepareEncryptionModules($success): void {
$user = 'user1';
$dummyEncryptionModule = $this->getMockBuilder(\OCP\Encryption\IEncryptionModule::class)
@@ -188,7 +188,7 @@ class DecryptAllTest extends TestCase {
/**
* @dataProvider dataTestDecryptAllUsersFiles
*/
- public function testDecryptAllUsersFiles($user) {
+ public function testDecryptAllUsersFiles($user): void {
/** @var DecryptAll | \PHPUnit\Framework\MockObject\MockObject | $instance */
$instance = $this->getMockBuilder(\OC\Encryption\DecryptAll::class)
->setConstructorArgs(
@@ -233,7 +233,7 @@ class DecryptAllTest extends TestCase {
];
}
- public function testDecryptUsersFiles() {
+ public function testDecryptUsersFiles(): void {
/** @var DecryptAll | \PHPUnit\Framework\MockObject\MockObject $instance */
$instance = $this->getMockBuilder(\OC\Encryption\DecryptAll::class)
->setConstructorArgs(
@@ -308,7 +308,7 @@ class DecryptAllTest extends TestCase {
/**
* @dataProvider dataTrueFalse
*/
- public function testDecryptFile($isEncrypted) {
+ public function testDecryptFile($isEncrypted): void {
$path = 'test.txt';
/** @var DecryptAll | \PHPUnit\Framework\MockObject\MockObject $instance */
@@ -348,7 +348,7 @@ class DecryptAllTest extends TestCase {
);
}
- public function testDecryptFileFailure() {
+ public function testDecryptFileFailure(): void {
$path = 'test.txt';
/** @var DecryptAll | \PHPUnit\Framework\MockObject\MockObject $instance */
diff --git a/tests/lib/Encryption/EncryptionWrapperTest.php b/tests/lib/Encryption/EncryptionWrapperTest.php
index 00460e34ecb..01fbc0a3a12 100644
--- a/tests/lib/Encryption/EncryptionWrapperTest.php
+++ b/tests/lib/Encryption/EncryptionWrapperTest.php
@@ -41,7 +41,7 @@ class EncryptionWrapperTest extends TestCase {
/**
* @dataProvider provideWrapStorage
*/
- public function testWrapStorage($expectedWrapped, $wrappedStorages) {
+ public function testWrapStorage($expectedWrapped, $wrappedStorages): void {
$storage = $this->getMockBuilder(Storage::class)
->disableOriginalConstructor()
->getMock();
diff --git a/tests/lib/Encryption/Keys/StorageTest.php b/tests/lib/Encryption/Keys/StorageTest.php
index 2fcdd8abc16..7c8ff93486e 100644
--- a/tests/lib/Encryption/Keys/StorageTest.php
+++ b/tests/lib/Encryption/Keys/StorageTest.php
@@ -1,613 +1,613 @@
-<?php
-
-/**
- * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
- * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
- * SPDX-License-Identifier: AGPL-3.0-or-later
- */
-
-namespace Test\Encryption\Keys;
-
-use OC\Encryption\Keys\Storage;
-use OC\Files\View;
-use OCP\IConfig;
-use OCP\Security\ICrypto;
-use PHPUnit\Framework\MockObject\MockObject;
-use Test\TestCase;
-
-class StorageTest extends TestCase {
- /** @var Storage */
- protected $storage;
-
- /** @var MockObject|\OC\Encryption\Util */
- protected $util;
-
- /** @var MockObject|View */
- protected $view;
-
- /** @var MockObject|IConfig */
- protected $config;
-
- /** @var MockObject|ICrypto */
- protected $crypto;
-
- private array $mkdirStack = [];
-
- protected function setUp(): void {
- parent::setUp();
-
- $this->util = $this->getMockBuilder(\OC\Encryption\Util::class)
- ->disableOriginalConstructor()
- ->setMethodsExcept(['getFileKeyDir'])
- ->getMock();
-
- $this->view = $this->getMockBuilder(View::class)
- ->disableOriginalConstructor()
- ->getMock();
-
- $this->crypto = $this->createMock(ICrypto::class);
- $this->crypto->method('encrypt')
- ->willReturnCallback(function ($data, $pass) {
- return $data;
- });
- $this->crypto->method('decrypt')
- ->willReturnCallback(function ($data, $pass) {
- return $data;
- });
-
- $this->config = $this->getMockBuilder(IConfig::class)
- ->disableOriginalConstructor()
- ->getMock();
-
- $this->storage = new Storage($this->view, $this->util, $this->crypto, $this->config);
- }
-
- public function testSetFileKey() {
- $this->config->method('getSystemValueString')
- ->with('version')
- ->willReturn('20.0.0.2');
- $this->util->expects($this->any())
- ->method('getUidAndFilename')
- ->willReturn(['user1', '/files/foo.txt']);
- $this->util->expects($this->any())
- ->method('stripPartialFileExtension')
- ->willReturnArgument(0);
- $this->util->expects($this->any())
- ->method('isSystemWideMountPoint')
- ->willReturn(false);
-
- $data = json_encode(['key' => base64_encode('key')]);
- $this->view->expects($this->once())
- ->method('file_put_contents')
- ->with($this->equalTo('/user1/files_encryption/keys/files/foo.txt/encModule/fileKey'),
- $this->equalTo($data))
- ->willReturn(strlen($data));
-
- $this->assertTrue(
- $this->storage->setFileKey('user1/files/foo.txt', 'fileKey', 'key', 'encModule')
- );
- }
-
- public function testSetFileOld() {
- $this->config->method('getSystemValueString')
- ->with('version')
- ->willReturn('20.0.0.0');
- $this->util->expects($this->any())
- ->method('getUidAndFilename')
- ->willReturn(['user1', '/files/foo.txt']);
- $this->util->expects($this->any())
- ->method('stripPartialFileExtension')
- ->willReturnArgument(0);
- $this->util->expects($this->any())
- ->method('isSystemWideMountPoint')
- ->willReturn(false);
- $this->crypto->expects($this->never())
- ->method('encrypt');
- $this->view->expects($this->once())
- ->method('file_put_contents')
- ->with($this->equalTo('/user1/files_encryption/keys/files/foo.txt/encModule/fileKey'),
- $this->equalTo('key'))
- ->willReturn(strlen('key'));
-
- $this->assertTrue(
- $this->storage->setFileKey('user1/files/foo.txt', 'fileKey', 'key', 'encModule')
- );
- }
-
- public function dataTestGetFileKey() {
- return [
- ['/files/foo.txt', '/files/foo.txt', true, 'key'],
- ['/files/foo.txt.ocTransferId2111130212.part', '/files/foo.txt', true, 'key'],
- ['/files/foo.txt.ocTransferId2111130212.part', '/files/foo.txt', false, 'key2'],
- ];
- }
-
- /**
- * @dataProvider dataTestGetFileKey
- *
- * @param string $path
- * @param string $strippedPartialName
- * @param bool $originalKeyExists
- * @param string $expectedKeyContent
- */
- public function testGetFileKey($path, $strippedPartialName, $originalKeyExists, $expectedKeyContent) {
- $this->config->method('getSystemValueString')
- ->with('version')
- ->willReturn('20.0.0.2');
- $this->util->expects($this->any())
- ->method('getUidAndFilename')
- ->willReturnMap([
- ['user1/files/foo.txt', ['user1', '/files/foo.txt']],
- ['user1/files/foo.txt.ocTransferId2111130212.part', ['user1', '/files/foo.txt.ocTransferId2111130212.part']],
- ]);
- // we need to strip away the part file extension in order to reuse a
- // existing key if it exists, otherwise versions will break
- $this->util->expects($this->once())
- ->method('stripPartialFileExtension')
- ->willReturn('user1' . $strippedPartialName);
- $this->util->expects($this->any())
- ->method('isSystemWideMountPoint')
- ->willReturn(false);
-
- $this->crypto->method('decrypt')
- ->willReturnCallback(function ($data, $pass) {
- return $data;
- });
-
- if (!$originalKeyExists) {
- $this->view->expects($this->exactly(2))
- ->method('file_exists')
- ->withConsecutive(
- [$this->equalTo('/user1/files_encryption/keys' . $strippedPartialName . '/encModule/fileKey')],
- [$this->equalTo('/user1/files_encryption/keys' . $path . '/encModule/fileKey')],
- )->willReturnOnConsecutiveCalls(
- $originalKeyExists,
- true,
- );
-
- $this->view->expects($this->once())
- ->method('file_get_contents')
- ->with($this->equalTo('/user1/files_encryption/keys' . $path . '/encModule/fileKey'))
- ->willReturn(json_encode(['key' => base64_encode('key2')]));
- } else {
- $this->view->expects($this->once())
- ->method('file_exists')
- ->with($this->equalTo('/user1/files_encryption/keys' . $strippedPartialName . '/encModule/fileKey'))
- ->willReturn($originalKeyExists);
-
- $this->view->expects($this->once())
- ->method('file_get_contents')
- ->with($this->equalTo('/user1/files_encryption/keys' . $strippedPartialName . '/encModule/fileKey'))
- ->willReturn(json_encode(['key' => base64_encode('key')]));
- }
-
- $this->assertSame($expectedKeyContent,
- $this->storage->getFileKey('user1' . $path, 'fileKey', 'encModule')
- );
- }
-
- public function testSetFileKeySystemWide() {
- $this->config->method('getSystemValueString')
- ->with('version')
- ->willReturn('20.0.0.2');
-
- $this->util->expects($this->any())
- ->method('getUidAndFilename')
- ->willReturn(['user1', '/files/foo.txt']);
- $this->util->expects($this->any())
- ->method('isSystemWideMountPoint')
- ->willReturn(true);
- $this->util->expects($this->any())
- ->method('stripPartialFileExtension')
- ->willReturnArgument(0);
-
- $this->crypto->method('encrypt')
- ->willReturnCallback(function ($data, $pass) {
- return $data;
- });
-
- $data = json_encode(['key' => base64_encode('key')]);
- $this->view->expects($this->once())
- ->method('file_put_contents')
- ->with($this->equalTo('/files_encryption/keys/files/foo.txt/encModule/fileKey'),
- $this->equalTo($data))
- ->willReturn(strlen($data));
-
- $this->assertTrue(
- $this->storage->setFileKey('user1/files/foo.txt', 'fileKey', 'key', 'encModule')
- );
- }
-
- public function testGetFileKeySystemWide() {
- $this->config->method('getSystemValueString')
- ->with('version')
- ->willReturn('20.0.0.2');
-
- $this->util->expects($this->any())
- ->method('getUidAndFilename')
- ->willReturn(['user1', '/files/foo.txt']);
- $this->util->expects($this->any())
- ->method('stripPartialFileExtension')
- ->willReturnArgument(0);
- $this->util->expects($this->any())
- ->method('isSystemWideMountPoint')
- ->willReturn(true);
- $this->view->expects($this->once())
- ->method('file_get_contents')
- ->with($this->equalTo('/files_encryption/keys/files/foo.txt/encModule/fileKey'))
- ->willReturn(json_encode(['key' => base64_encode('key')]));
- $this->view->expects($this->once())
- ->method('file_exists')
- ->with($this->equalTo('/files_encryption/keys/files/foo.txt/encModule/fileKey'))
- ->willReturn(true);
-
- $this->assertSame('key',
- $this->storage->getFileKey('user1/files/foo.txt', 'fileKey', 'encModule')
- );
- }
-
- public function testSetSystemUserKey() {
- $this->config->method('getSystemValueString')
- ->with('version')
- ->willReturn('20.0.0.2');
-
- $data = json_encode([
- 'key' => base64_encode('key'),
- 'uid' => null]
- );
- $this->view->expects($this->once())
- ->method('file_put_contents')
- ->with($this->equalTo('/files_encryption/encModule/shareKey_56884'),
- $this->equalTo($data))
- ->willReturn(strlen($data));
-
- $this->assertTrue(
- $this->storage->setSystemUserKey('shareKey_56884', 'key', 'encModule')
- );
- }
-
- public function testSetUserKey() {
- $this->config->method('getSystemValueString')
- ->with('version')
- ->willReturn('20.0.0.2');
-
- $data = json_encode([
- 'key' => base64_encode('key'),
- 'uid' => 'user1']
- );
- $this->view->expects($this->once())
- ->method('file_put_contents')
- ->with($this->equalTo('/user1/files_encryption/encModule/user1.publicKey'),
- $this->equalTo($data))
- ->willReturn(strlen($data));
-
- $this->assertTrue(
- $this->storage->setUserKey('user1', 'publicKey', 'key', 'encModule')
- );
- }
-
- public function testGetSystemUserKey() {
- $this->config->method('getSystemValueString')
- ->with('version')
- ->willReturn('20.0.0.2');
-
- $data = json_encode([
- 'key' => base64_encode('key'),
- 'uid' => null]
- );
- $this->view->expects($this->once())
- ->method('file_get_contents')
- ->with($this->equalTo('/files_encryption/encModule/shareKey_56884'))
- ->willReturn($data);
- $this->view->expects($this->once())
- ->method('file_exists')
- ->with($this->equalTo('/files_encryption/encModule/shareKey_56884'))
- ->willReturn(true);
-
- $this->assertSame('key',
- $this->storage->getSystemUserKey('shareKey_56884', 'encModule')
- );
- }
-
- public function testGetUserKey() {
- $this->config->method('getSystemValueString')
- ->with('version')
- ->willReturn('20.0.0.2');
-
- $data = json_encode([
- 'key' => base64_encode('key'),
- 'uid' => 'user1']
- );
- $this->view->expects($this->once())
- ->method('file_get_contents')
- ->with($this->equalTo('/user1/files_encryption/encModule/user1.publicKey'))
- ->willReturn($data);
- $this->view->expects($this->once())
- ->method('file_exists')
- ->with($this->equalTo('/user1/files_encryption/encModule/user1.publicKey'))
- ->willReturn(true);
-
- $this->assertSame('key',
- $this->storage->getUserKey('user1', 'publicKey', 'encModule')
- );
- }
-
- public function testDeleteUserKey() {
- $this->view->expects($this->once())
- ->method('file_exists')
- ->with($this->equalTo('/user1/files_encryption/encModule/user1.publicKey'))
- ->willReturn(true);
- $this->view->expects($this->once())
- ->method('unlink')
- ->with($this->equalTo('/user1/files_encryption/encModule/user1.publicKey'))
- ->willReturn(true);
-
- $this->assertTrue(
- $this->storage->deleteUserKey('user1', 'publicKey', 'encModule')
- );
- }
-
- public function testDeleteSystemUserKey() {
- $this->view->expects($this->once())
- ->method('file_exists')
- ->with($this->equalTo('/files_encryption/encModule/shareKey_56884'))
- ->willReturn(true);
- $this->view->expects($this->once())
- ->method('unlink')
- ->with($this->equalTo('/files_encryption/encModule/shareKey_56884'))
- ->willReturn(true);
-
- $this->assertTrue(
- $this->storage->deleteSystemUserKey('shareKey_56884', 'encModule')
- );
- }
-
- public function testDeleteFileKeySystemWide() {
- $this->util->expects($this->any())
- ->method('getUidAndFilename')
- ->willReturn(['user1', '/files/foo.txt']);
- $this->util->expects($this->any())
- ->method('stripPartialFileExtension')
- ->willReturnArgument(0);
- $this->util->expects($this->any())
- ->method('isSystemWideMountPoint')
- ->willReturn(true);
- $this->view->expects($this->once())
- ->method('file_exists')
- ->with($this->equalTo('/files_encryption/keys/files/foo.txt/encModule/fileKey'))
- ->willReturn(true);
- $this->view->expects($this->once())
- ->method('unlink')
- ->with($this->equalTo('/files_encryption/keys/files/foo.txt/encModule/fileKey'))
- ->willReturn(true);
-
- $this->assertTrue(
- $this->storage->deleteFileKey('user1/files/foo.txt', 'fileKey', 'encModule')
- );
- }
-
- public function testDeleteFileKey() {
- $this->util->expects($this->any())
- ->method('getUidAndFilename')
- ->willReturn(['user1', '/files/foo.txt']);
- $this->util->expects($this->any())
- ->method('stripPartialFileExtension')
- ->willReturnArgument(0);
- $this->util->expects($this->any())
- ->method('isSystemWideMountPoint')
- ->willReturn(false);
- $this->view->expects($this->once())
- ->method('file_exists')
- ->with($this->equalTo('/user1/files_encryption/keys/files/foo.txt/encModule/fileKey'))
- ->willReturn(true);
- $this->view->expects($this->once())
- ->method('unlink')
- ->with($this->equalTo('/user1/files_encryption/keys/files/foo.txt/encModule/fileKey'))
- ->willReturn(true);
-
- $this->assertTrue(
- $this->storage->deleteFileKey('user1/files/foo.txt', 'fileKey', 'encModule')
- );
- }
-
- /**
- * @dataProvider dataProviderCopyRename
- */
- public function testRenameKeys($source, $target, $systemWideMountSource, $systemWideMountTarget, $expectedSource, $expectedTarget) {
- $this->view->expects($this->any())
- ->method('file_exists')
- ->willReturn(true);
- $this->view->expects($this->any())
- ->method('is_dir')
- ->willReturn(true);
- $this->view->expects($this->once())
- ->method('rename')
- ->with(
- $this->equalTo($expectedSource),
- $this->equalTo($expectedTarget))
- ->willReturn(true);
- $this->util->expects($this->any())
- ->method('getUidAndFilename')
- ->willReturnCallback([$this, 'getUidAndFilenameCallback']);
- $this->util->expects($this->any())
- ->method('isSystemWideMountPoint')
- ->willReturnCallback(function ($path, $owner) use ($systemWideMountSource, $systemWideMountTarget) {
- if (strpos($path, 'source.txt') !== false) {
- return $systemWideMountSource;
- }
- return $systemWideMountTarget;
- });
-
- $this->storage->renameKeys($source, $target);
- }
-
- /**
- * @dataProvider dataProviderCopyRename
- */
- public function testCopyKeys($source, $target, $systemWideMountSource, $systemWideMountTarget, $expectedSource, $expectedTarget) {
- $this->view->expects($this->any())
- ->method('file_exists')
- ->willReturn(true);
- $this->view->expects($this->any())
- ->method('is_dir')
- ->willReturn(true);
- $this->view->expects($this->once())
- ->method('copy')
- ->with(
- $this->equalTo($expectedSource),
- $this->equalTo($expectedTarget))
- ->willReturn(true);
- $this->util->expects($this->any())
- ->method('getUidAndFilename')
- ->willReturnCallback([$this, 'getUidAndFilenameCallback']);
- $this->util->expects($this->any())
- ->method('isSystemWideMountPoint')
- ->willReturnCallback(function ($path, $owner) use ($systemWideMountSource, $systemWideMountTarget) {
- if (strpos($path, 'source.txt') !== false) {
- return $systemWideMountSource;
- }
- return $systemWideMountTarget;
- });
-
- $this->storage->copyKeys($source, $target);
- }
-
- public function getUidAndFilenameCallback() {
- $args = func_get_args();
-
- $path = $args[0];
- $parts = explode('/', $path);
-
- return [$parts[1], '/' . implode('/', array_slice($parts, 2))];
- }
-
- public function dataProviderCopyRename() {
- return [
- ['/user1/files/source.txt', '/user1/files/target.txt', false, false,
- '/user1/files_encryption/keys/files/source.txt/', '/user1/files_encryption/keys/files/target.txt/'],
- ['/user1/files/foo/source.txt', '/user1/files/target.txt', false, false,
- '/user1/files_encryption/keys/files/foo/source.txt/', '/user1/files_encryption/keys/files/target.txt/'],
- ['/user1/files/source.txt', '/user1/files/foo/target.txt', false, false,
- '/user1/files_encryption/keys/files/source.txt/', '/user1/files_encryption/keys/files/foo/target.txt/'],
- ['/user1/files/source.txt', '/user1/files/foo/target.txt', true, true,
- '/files_encryption/keys/files/source.txt/', '/files_encryption/keys/files/foo/target.txt/'],
- ['/user1/files/source.txt', '/user1/files/target.txt', false, true,
- '/user1/files_encryption/keys/files/source.txt/', '/files_encryption/keys/files/target.txt/'],
- ['/user1/files/source.txt', '/user1/files/target.txt', true, false,
- '/files_encryption/keys/files/source.txt/', '/user1/files_encryption/keys/files/target.txt/'],
-
- ['/user2/files/source.txt', '/user1/files/target.txt', false, false,
- '/user2/files_encryption/keys/files/source.txt/', '/user1/files_encryption/keys/files/target.txt/'],
- ['/user2/files/foo/source.txt', '/user1/files/target.txt', false, false,
- '/user2/files_encryption/keys/files/foo/source.txt/', '/user1/files_encryption/keys/files/target.txt/'],
- ['/user2/files/source.txt', '/user1/files/foo/target.txt', false, false,
- '/user2/files_encryption/keys/files/source.txt/', '/user1/files_encryption/keys/files/foo/target.txt/'],
- ['/user2/files/source.txt', '/user1/files/foo/target.txt', true, true,
- '/files_encryption/keys/files/source.txt/', '/files_encryption/keys/files/foo/target.txt/'],
- ['/user2/files/source.txt', '/user1/files/target.txt', false, true,
- '/user2/files_encryption/keys/files/source.txt/', '/files_encryption/keys/files/target.txt/'],
- ['/user2/files/source.txt', '/user1/files/target.txt', true, false,
- '/files_encryption/keys/files/source.txt/', '/user1/files_encryption/keys/files/target.txt/'],
- ];
- }
-
- /**
- * @dataProvider dataTestGetPathToKeys
- *
- * @param string $path
- * @param boolean $systemWideMountPoint
- * @param string $storageRoot
- * @param string $expected
- */
- public function testGetPathToKeys($path, $systemWideMountPoint, $storageRoot, $expected) {
- $this->invokePrivate($this->storage, 'root_dir', [$storageRoot]);
-
- $this->util->expects($this->any())
- ->method('getUidAndFilename')
- ->willReturnCallback([$this, 'getUidAndFilenameCallback']);
- $this->util->expects($this->any())
- ->method('isSystemWideMountPoint')
- ->willReturn($systemWideMountPoint);
-
- $this->assertSame($expected,
- self::invokePrivate($this->storage, 'getPathToKeys', [$path])
- );
- }
-
- public function dataTestGetPathToKeys() {
- return [
- ['/user1/files/source.txt', false, '', '/user1/files_encryption/keys/files/source.txt/'],
- ['/user1/files/source.txt', true, '', '/files_encryption/keys/files/source.txt/'],
- ['/user1/files/source.txt', false, 'storageRoot', '/storageRoot/user1/files_encryption/keys/files/source.txt/'],
- ['/user1/files/source.txt', true, 'storageRoot', '/storageRoot/files_encryption/keys/files/source.txt/'],
- ];
- }
-
- public function testKeySetPreparation() {
- $this->view->expects($this->any())
- ->method('file_exists')
- ->willReturn(false);
- $this->view->expects($this->any())
- ->method('is_dir')
- ->willReturn(false);
- $this->view->expects($this->any())
- ->method('mkdir')
- ->willReturnCallback([$this, 'mkdirCallback']);
-
- $this->mkdirStack = [
- '/user1/files_encryption/keys/foo',
- '/user1/files_encryption/keys',
- '/user1/files_encryption',
- '/user1'];
-
- self::invokePrivate($this->storage, 'keySetPreparation', ['/user1/files_encryption/keys/foo']);
- }
-
- public function mkdirCallback() {
- $args = func_get_args();
- $expected = array_pop($this->mkdirStack);
- $this->assertSame($expected, $args[0]);
- }
-
-
- /**
- * @dataProvider dataTestBackupUserKeys
- * @param bool $createBackupDir
- */
- public function testBackupUserKeys($createBackupDir) {
- $storage = $this->getMockBuilder(\OC\Encryption\Keys\Storage::class)
- ->setConstructorArgs([$this->view, $this->util, $this->crypto, $this->config])
- ->setMethods(['getTimestamp'])
- ->getMock();
-
- $storage->expects($this->any())->method('getTimestamp')->willReturn('1234567');
-
- $this->view->expects($this->once())->method('file_exists')
- ->with('user1/files_encryption/backup')->willReturn(!$createBackupDir);
-
- if ($createBackupDir) {
- $this->view->expects($this->exactly(2))->method('mkdir')
- ->withConsecutive(
- ['user1/files_encryption/backup'],
- ['user1/files_encryption/backup/test.encryptionModule.1234567'],
- );
- } else {
- $this->view->expects($this->once())->method('mkdir')
- ->with('user1/files_encryption/backup/test.encryptionModule.1234567');
- }
-
- $this->view->expects($this->once())->method('copy')
- ->with(
- 'user1/files_encryption/encryptionModule',
- 'user1/files_encryption/backup/test.encryptionModule.1234567'
- )->willReturn(true);
-
- $this->assertTrue($storage->backupUserKeys('encryptionModule', 'test', 'user1'));
- }
-
- public function dataTestBackupUserKeys() {
- return [
- [true], [false]
- ];
- }
-}
+<?php
+
+/**
+ * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+
+namespace Test\Encryption\Keys;
+
+use OC\Encryption\Keys\Storage;
+use OC\Files\View;
+use OCP\IConfig;
+use OCP\Security\ICrypto;
+use PHPUnit\Framework\MockObject\MockObject;
+use Test\TestCase;
+
+class StorageTest extends TestCase {
+ /** @var Storage */
+ protected $storage;
+
+ /** @var MockObject|\OC\Encryption\Util */
+ protected $util;
+
+ /** @var MockObject|View */
+ protected $view;
+
+ /** @var MockObject|IConfig */
+ protected $config;
+
+ /** @var MockObject|ICrypto */
+ protected $crypto;
+
+ private array $mkdirStack = [];
+
+ protected function setUp(): void {
+ parent::setUp();
+
+ $this->util = $this->getMockBuilder(\OC\Encryption\Util::class)
+ ->disableOriginalConstructor()
+ ->setMethodsExcept(['getFileKeyDir'])
+ ->getMock();
+
+ $this->view = $this->getMockBuilder(View::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $this->crypto = $this->createMock(ICrypto::class);
+ $this->crypto->method('encrypt')
+ ->willReturnCallback(function ($data, $pass) {
+ return $data;
+ });
+ $this->crypto->method('decrypt')
+ ->willReturnCallback(function ($data, $pass) {
+ return $data;
+ });
+
+ $this->config = $this->getMockBuilder(IConfig::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $this->storage = new Storage($this->view, $this->util, $this->crypto, $this->config);
+ }
+
+ public function testSetFileKey(): void {
+ $this->config->method('getSystemValueString')
+ ->with('version')
+ ->willReturn('20.0.0.2');
+ $this->util->expects($this->any())
+ ->method('getUidAndFilename')
+ ->willReturn(['user1', '/files/foo.txt']);
+ $this->util->expects($this->any())
+ ->method('stripPartialFileExtension')
+ ->willReturnArgument(0);
+ $this->util->expects($this->any())
+ ->method('isSystemWideMountPoint')
+ ->willReturn(false);
+
+ $data = json_encode(['key' => base64_encode('key')]);
+ $this->view->expects($this->once())
+ ->method('file_put_contents')
+ ->with($this->equalTo('/user1/files_encryption/keys/files/foo.txt/encModule/fileKey'),
+ $this->equalTo($data))
+ ->willReturn(strlen($data));
+
+ $this->assertTrue(
+ $this->storage->setFileKey('user1/files/foo.txt', 'fileKey', 'key', 'encModule')
+ );
+ }
+
+ public function testSetFileOld(): void {
+ $this->config->method('getSystemValueString')
+ ->with('version')
+ ->willReturn('20.0.0.0');
+ $this->util->expects($this->any())
+ ->method('getUidAndFilename')
+ ->willReturn(['user1', '/files/foo.txt']);
+ $this->util->expects($this->any())
+ ->method('stripPartialFileExtension')
+ ->willReturnArgument(0);
+ $this->util->expects($this->any())
+ ->method('isSystemWideMountPoint')
+ ->willReturn(false);
+ $this->crypto->expects($this->never())
+ ->method('encrypt');
+ $this->view->expects($this->once())
+ ->method('file_put_contents')
+ ->with($this->equalTo('/user1/files_encryption/keys/files/foo.txt/encModule/fileKey'),
+ $this->equalTo('key'))
+ ->willReturn(strlen('key'));
+
+ $this->assertTrue(
+ $this->storage->setFileKey('user1/files/foo.txt', 'fileKey', 'key', 'encModule')
+ );
+ }
+
+ public function dataTestGetFileKey() {
+ return [
+ ['/files/foo.txt', '/files/foo.txt', true, 'key'],
+ ['/files/foo.txt.ocTransferId2111130212.part', '/files/foo.txt', true, 'key'],
+ ['/files/foo.txt.ocTransferId2111130212.part', '/files/foo.txt', false, 'key2'],
+ ];
+ }
+
+ /**
+ * @dataProvider dataTestGetFileKey
+ *
+ * @param string $path
+ * @param string $strippedPartialName
+ * @param bool $originalKeyExists
+ * @param string $expectedKeyContent
+ */
+ public function testGetFileKey($path, $strippedPartialName, $originalKeyExists, $expectedKeyContent): void {
+ $this->config->method('getSystemValueString')
+ ->with('version')
+ ->willReturn('20.0.0.2');
+ $this->util->expects($this->any())
+ ->method('getUidAndFilename')
+ ->willReturnMap([
+ ['user1/files/foo.txt', ['user1', '/files/foo.txt']],
+ ['user1/files/foo.txt.ocTransferId2111130212.part', ['user1', '/files/foo.txt.ocTransferId2111130212.part']],
+ ]);
+ // we need to strip away the part file extension in order to reuse a
+ // existing key if it exists, otherwise versions will break
+ $this->util->expects($this->once())
+ ->method('stripPartialFileExtension')
+ ->willReturn('user1' . $strippedPartialName);
+ $this->util->expects($this->any())
+ ->method('isSystemWideMountPoint')
+ ->willReturn(false);
+
+ $this->crypto->method('decrypt')
+ ->willReturnCallback(function ($data, $pass) {
+ return $data;
+ });
+
+ if (!$originalKeyExists) {
+ $this->view->expects($this->exactly(2))
+ ->method('file_exists')
+ ->withConsecutive(
+ [$this->equalTo('/user1/files_encryption/keys' . $strippedPartialName . '/encModule/fileKey')],
+ [$this->equalTo('/user1/files_encryption/keys' . $path . '/encModule/fileKey')],
+ )->willReturnOnConsecutiveCalls(
+ $originalKeyExists,
+ true,
+ );
+
+ $this->view->expects($this->once())
+ ->method('file_get_contents')
+ ->with($this->equalTo('/user1/files_encryption/keys' . $path . '/encModule/fileKey'))
+ ->willReturn(json_encode(['key' => base64_encode('key2')]));
+ } else {
+ $this->view->expects($this->once())
+ ->method('file_exists')
+ ->with($this->equalTo('/user1/files_encryption/keys' . $strippedPartialName . '/encModule/fileKey'))
+ ->willReturn($originalKeyExists);
+
+ $this->view->expects($this->once())
+ ->method('file_get_contents')
+ ->with($this->equalTo('/user1/files_encryption/keys' . $strippedPartialName . '/encModule/fileKey'))
+ ->willReturn(json_encode(['key' => base64_encode('key')]));
+ }
+
+ $this->assertSame($expectedKeyContent,
+ $this->storage->getFileKey('user1' . $path, 'fileKey', 'encModule')
+ );
+ }
+
+ public function testSetFileKeySystemWide(): void {
+ $this->config->method('getSystemValueString')
+ ->with('version')
+ ->willReturn('20.0.0.2');
+
+ $this->util->expects($this->any())
+ ->method('getUidAndFilename')
+ ->willReturn(['user1', '/files/foo.txt']);
+ $this->util->expects($this->any())
+ ->method('isSystemWideMountPoint')
+ ->willReturn(true);
+ $this->util->expects($this->any())
+ ->method('stripPartialFileExtension')
+ ->willReturnArgument(0);
+
+ $this->crypto->method('encrypt')
+ ->willReturnCallback(function ($data, $pass) {
+ return $data;
+ });
+
+ $data = json_encode(['key' => base64_encode('key')]);
+ $this->view->expects($this->once())
+ ->method('file_put_contents')
+ ->with($this->equalTo('/files_encryption/keys/files/foo.txt/encModule/fileKey'),
+ $this->equalTo($data))
+ ->willReturn(strlen($data));
+
+ $this->assertTrue(
+ $this->storage->setFileKey('user1/files/foo.txt', 'fileKey', 'key', 'encModule')
+ );
+ }
+
+ public function testGetFileKeySystemWide(): void {
+ $this->config->method('getSystemValueString')
+ ->with('version')
+ ->willReturn('20.0.0.2');
+
+ $this->util->expects($this->any())
+ ->method('getUidAndFilename')
+ ->willReturn(['user1', '/files/foo.txt']);
+ $this->util->expects($this->any())
+ ->method('stripPartialFileExtension')
+ ->willReturnArgument(0);
+ $this->util->expects($this->any())
+ ->method('isSystemWideMountPoint')
+ ->willReturn(true);
+ $this->view->expects($this->once())
+ ->method('file_get_contents')
+ ->with($this->equalTo('/files_encryption/keys/files/foo.txt/encModule/fileKey'))
+ ->willReturn(json_encode(['key' => base64_encode('key')]));
+ $this->view->expects($this->once())
+ ->method('file_exists')
+ ->with($this->equalTo('/files_encryption/keys/files/foo.txt/encModule/fileKey'))
+ ->willReturn(true);
+
+ $this->assertSame('key',
+ $this->storage->getFileKey('user1/files/foo.txt', 'fileKey', 'encModule')
+ );
+ }
+
+ public function testSetSystemUserKey(): void {
+ $this->config->method('getSystemValueString')
+ ->with('version')
+ ->willReturn('20.0.0.2');
+
+ $data = json_encode([
+ 'key' => base64_encode('key'),
+ 'uid' => null]
+ );
+ $this->view->expects($this->once())
+ ->method('file_put_contents')
+ ->with($this->equalTo('/files_encryption/encModule/shareKey_56884'),
+ $this->equalTo($data))
+ ->willReturn(strlen($data));
+
+ $this->assertTrue(
+ $this->storage->setSystemUserKey('shareKey_56884', 'key', 'encModule')
+ );
+ }
+
+ public function testSetUserKey(): void {
+ $this->config->method('getSystemValueString')
+ ->with('version')
+ ->willReturn('20.0.0.2');
+
+ $data = json_encode([
+ 'key' => base64_encode('key'),
+ 'uid' => 'user1']
+ );
+ $this->view->expects($this->once())
+ ->method('file_put_contents')
+ ->with($this->equalTo('/user1/files_encryption/encModule/user1.publicKey'),
+ $this->equalTo($data))
+ ->willReturn(strlen($data));
+
+ $this->assertTrue(
+ $this->storage->setUserKey('user1', 'publicKey', 'key', 'encModule')
+ );
+ }
+
+ public function testGetSystemUserKey(): void {
+ $this->config->method('getSystemValueString')
+ ->with('version')
+ ->willReturn('20.0.0.2');
+
+ $data = json_encode([
+ 'key' => base64_encode('key'),
+ 'uid' => null]
+ );
+ $this->view->expects($this->once())
+ ->method('file_get_contents')
+ ->with($this->equalTo('/files_encryption/encModule/shareKey_56884'))
+ ->willReturn($data);
+ $this->view->expects($this->once())
+ ->method('file_exists')
+ ->with($this->equalTo('/files_encryption/encModule/shareKey_56884'))
+ ->willReturn(true);
+
+ $this->assertSame('key',
+ $this->storage->getSystemUserKey('shareKey_56884', 'encModule')
+ );
+ }
+
+ public function testGetUserKey(): void {
+ $this->config->method('getSystemValueString')
+ ->with('version')
+ ->willReturn('20.0.0.2');
+
+ $data = json_encode([
+ 'key' => base64_encode('key'),
+ 'uid' => 'user1']
+ );
+ $this->view->expects($this->once())
+ ->method('file_get_contents')
+ ->with($this->equalTo('/user1/files_encryption/encModule/user1.publicKey'))
+ ->willReturn($data);
+ $this->view->expects($this->once())
+ ->method('file_exists')
+ ->with($this->equalTo('/user1/files_encryption/encModule/user1.publicKey'))
+ ->willReturn(true);
+
+ $this->assertSame('key',
+ $this->storage->getUserKey('user1', 'publicKey', 'encModule')
+ );
+ }
+
+ public function testDeleteUserKey(): void {
+ $this->view->expects($this->once())
+ ->method('file_exists')
+ ->with($this->equalTo('/user1/files_encryption/encModule/user1.publicKey'))
+ ->willReturn(true);
+ $this->view->expects($this->once())
+ ->method('unlink')
+ ->with($this->equalTo('/user1/files_encryption/encModule/user1.publicKey'))
+ ->willReturn(true);
+
+ $this->assertTrue(
+ $this->storage->deleteUserKey('user1', 'publicKey', 'encModule')
+ );
+ }
+
+ public function testDeleteSystemUserKey(): void {
+ $this->view->expects($this->once())
+ ->method('file_exists')
+ ->with($this->equalTo('/files_encryption/encModule/shareKey_56884'))
+ ->willReturn(true);
+ $this->view->expects($this->once())
+ ->method('unlink')
+ ->with($this->equalTo('/files_encryption/encModule/shareKey_56884'))
+ ->willReturn(true);
+
+ $this->assertTrue(
+ $this->storage->deleteSystemUserKey('shareKey_56884', 'encModule')
+ );
+ }
+
+ public function testDeleteFileKeySystemWide(): void {
+ $this->util->expects($this->any())
+ ->method('getUidAndFilename')
+ ->willReturn(['user1', '/files/foo.txt']);
+ $this->util->expects($this->any())
+ ->method('stripPartialFileExtension')
+ ->willReturnArgument(0);
+ $this->util->expects($this->any())
+ ->method('isSystemWideMountPoint')
+ ->willReturn(true);
+ $this->view->expects($this->once())
+ ->method('file_exists')
+ ->with($this->equalTo('/files_encryption/keys/files/foo.txt/encModule/fileKey'))
+ ->willReturn(true);
+ $this->view->expects($this->once())
+ ->method('unlink')
+ ->with($this->equalTo('/files_encryption/keys/files/foo.txt/encModule/fileKey'))
+ ->willReturn(true);
+
+ $this->assertTrue(
+ $this->storage->deleteFileKey('user1/files/foo.txt', 'fileKey', 'encModule')
+ );
+ }
+
+ public function testDeleteFileKey(): void {
+ $this->util->expects($this->any())
+ ->method('getUidAndFilename')
+ ->willReturn(['user1', '/files/foo.txt']);
+ $this->util->expects($this->any())
+ ->method('stripPartialFileExtension')
+ ->willReturnArgument(0);
+ $this->util->expects($this->any())
+ ->method('isSystemWideMountPoint')
+ ->willReturn(false);
+ $this->view->expects($this->once())
+ ->method('file_exists')
+ ->with($this->equalTo('/user1/files_encryption/keys/files/foo.txt/encModule/fileKey'))
+ ->willReturn(true);
+ $this->view->expects($this->once())
+ ->method('unlink')
+ ->with($this->equalTo('/user1/files_encryption/keys/files/foo.txt/encModule/fileKey'))
+ ->willReturn(true);
+
+ $this->assertTrue(
+ $this->storage->deleteFileKey('user1/files/foo.txt', 'fileKey', 'encModule')
+ );
+ }
+
+ /**
+ * @dataProvider dataProviderCopyRename
+ */
+ public function testRenameKeys($source, $target, $systemWideMountSource, $systemWideMountTarget, $expectedSource, $expectedTarget): void {
+ $this->view->expects($this->any())
+ ->method('file_exists')
+ ->willReturn(true);
+ $this->view->expects($this->any())
+ ->method('is_dir')
+ ->willReturn(true);
+ $this->view->expects($this->once())
+ ->method('rename')
+ ->with(
+ $this->equalTo($expectedSource),
+ $this->equalTo($expectedTarget))
+ ->willReturn(true);
+ $this->util->expects($this->any())
+ ->method('getUidAndFilename')
+ ->willReturnCallback([$this, 'getUidAndFilenameCallback']);
+ $this->util->expects($this->any())
+ ->method('isSystemWideMountPoint')
+ ->willReturnCallback(function ($path, $owner) use ($systemWideMountSource, $systemWideMountTarget) {
+ if (strpos($path, 'source.txt') !== false) {
+ return $systemWideMountSource;
+ }
+ return $systemWideMountTarget;
+ });
+
+ $this->storage->renameKeys($source, $target);
+ }
+
+ /**
+ * @dataProvider dataProviderCopyRename
+ */
+ public function testCopyKeys($source, $target, $systemWideMountSource, $systemWideMountTarget, $expectedSource, $expectedTarget): void {
+ $this->view->expects($this->any())
+ ->method('file_exists')
+ ->willReturn(true);
+ $this->view->expects($this->any())
+ ->method('is_dir')
+ ->willReturn(true);
+ $this->view->expects($this->once())
+ ->method('copy')
+ ->with(
+ $this->equalTo($expectedSource),
+ $this->equalTo($expectedTarget))
+ ->willReturn(true);
+ $this->util->expects($this->any())
+ ->method('getUidAndFilename')
+ ->willReturnCallback([$this, 'getUidAndFilenameCallback']);
+ $this->util->expects($this->any())
+ ->method('isSystemWideMountPoint')
+ ->willReturnCallback(function ($path, $owner) use ($systemWideMountSource, $systemWideMountTarget) {
+ if (strpos($path, 'source.txt') !== false) {
+ return $systemWideMountSource;
+ }
+ return $systemWideMountTarget;
+ });
+
+ $this->storage->copyKeys($source, $target);
+ }
+
+ public function getUidAndFilenameCallback() {
+ $args = func_get_args();
+
+ $path = $args[0];
+ $parts = explode('/', $path);
+
+ return [$parts[1], '/' . implode('/', array_slice($parts, 2))];
+ }
+
+ public function dataProviderCopyRename() {
+ return [
+ ['/user1/files/source.txt', '/user1/files/target.txt', false, false,
+ '/user1/files_encryption/keys/files/source.txt/', '/user1/files_encryption/keys/files/target.txt/'],
+ ['/user1/files/foo/source.txt', '/user1/files/target.txt', false, false,
+ '/user1/files_encryption/keys/files/foo/source.txt/', '/user1/files_encryption/keys/files/target.txt/'],
+ ['/user1/files/source.txt', '/user1/files/foo/target.txt', false, false,
+ '/user1/files_encryption/keys/files/source.txt/', '/user1/files_encryption/keys/files/foo/target.txt/'],
+ ['/user1/files/source.txt', '/user1/files/foo/target.txt', true, true,
+ '/files_encryption/keys/files/source.txt/', '/files_encryption/keys/files/foo/target.txt/'],
+ ['/user1/files/source.txt', '/user1/files/target.txt', false, true,
+ '/user1/files_encryption/keys/files/source.txt/', '/files_encryption/keys/files/target.txt/'],
+ ['/user1/files/source.txt', '/user1/files/target.txt', true, false,
+ '/files_encryption/keys/files/source.txt/', '/user1/files_encryption/keys/files/target.txt/'],
+
+ ['/user2/files/source.txt', '/user1/files/target.txt', false, false,
+ '/user2/files_encryption/keys/files/source.txt/', '/user1/files_encryption/keys/files/target.txt/'],
+ ['/user2/files/foo/source.txt', '/user1/files/target.txt', false, false,
+ '/user2/files_encryption/keys/files/foo/source.txt/', '/user1/files_encryption/keys/files/target.txt/'],
+ ['/user2/files/source.txt', '/user1/files/foo/target.txt', false, false,
+ '/user2/files_encryption/keys/files/source.txt/', '/user1/files_encryption/keys/files/foo/target.txt/'],
+ ['/user2/files/source.txt', '/user1/files/foo/target.txt', true, true,
+ '/files_encryption/keys/files/source.txt/', '/files_encryption/keys/files/foo/target.txt/'],
+ ['/user2/files/source.txt', '/user1/files/target.txt', false, true,
+ '/user2/files_encryption/keys/files/source.txt/', '/files_encryption/keys/files/target.txt/'],
+ ['/user2/files/source.txt', '/user1/files/target.txt', true, false,
+ '/files_encryption/keys/files/source.txt/', '/user1/files_encryption/keys/files/target.txt/'],
+ ];
+ }
+
+ /**
+ * @dataProvider dataTestGetPathToKeys
+ *
+ * @param string $path
+ * @param boolean $systemWideMountPoint
+ * @param string $storageRoot
+ * @param string $expected
+ */
+ public function testGetPathToKeys($path, $systemWideMountPoint, $storageRoot, $expected): void {
+ $this->invokePrivate($this->storage, 'root_dir', [$storageRoot]);
+
+ $this->util->expects($this->any())
+ ->method('getUidAndFilename')
+ ->willReturnCallback([$this, 'getUidAndFilenameCallback']);
+ $this->util->expects($this->any())
+ ->method('isSystemWideMountPoint')
+ ->willReturn($systemWideMountPoint);
+
+ $this->assertSame($expected,
+ self::invokePrivate($this->storage, 'getPathToKeys', [$path])
+ );
+ }
+
+ public function dataTestGetPathToKeys() {
+ return [
+ ['/user1/files/source.txt', false, '', '/user1/files_encryption/keys/files/source.txt/'],
+ ['/user1/files/source.txt', true, '', '/files_encryption/keys/files/source.txt/'],
+ ['/user1/files/source.txt', false, 'storageRoot', '/storageRoot/user1/files_encryption/keys/files/source.txt/'],
+ ['/user1/files/source.txt', true, 'storageRoot', '/storageRoot/files_encryption/keys/files/source.txt/'],
+ ];
+ }
+
+ public function testKeySetPreparation(): void {
+ $this->view->expects($this->any())
+ ->method('file_exists')
+ ->willReturn(false);
+ $this->view->expects($this->any())
+ ->method('is_dir')
+ ->willReturn(false);
+ $this->view->expects($this->any())
+ ->method('mkdir')
+ ->willReturnCallback([$this, 'mkdirCallback']);
+
+ $this->mkdirStack = [
+ '/user1/files_encryption/keys/foo',
+ '/user1/files_encryption/keys',
+ '/user1/files_encryption',
+ '/user1'];
+
+ self::invokePrivate($this->storage, 'keySetPreparation', ['/user1/files_encryption/keys/foo']);
+ }
+
+ public function mkdirCallback() {
+ $args = func_get_args();
+ $expected = array_pop($this->mkdirStack);
+ $this->assertSame($expected, $args[0]);
+ }
+
+
+ /**
+ * @dataProvider dataTestBackupUserKeys
+ * @param bool $createBackupDir
+ */
+ public function testBackupUserKeys($createBackupDir): void {
+ $storage = $this->getMockBuilder(\OC\Encryption\Keys\Storage::class)
+ ->setConstructorArgs([$this->view, $this->util, $this->crypto, $this->config])
+ ->setMethods(['getTimestamp'])
+ ->getMock();
+
+ $storage->expects($this->any())->method('getTimestamp')->willReturn('1234567');
+
+ $this->view->expects($this->once())->method('file_exists')
+ ->with('user1/files_encryption/backup')->willReturn(!$createBackupDir);
+
+ if ($createBackupDir) {
+ $this->view->expects($this->exactly(2))->method('mkdir')
+ ->withConsecutive(
+ ['user1/files_encryption/backup'],
+ ['user1/files_encryption/backup/test.encryptionModule.1234567'],
+ );
+ } else {
+ $this->view->expects($this->once())->method('mkdir')
+ ->with('user1/files_encryption/backup/test.encryptionModule.1234567');
+ }
+
+ $this->view->expects($this->once())->method('copy')
+ ->with(
+ 'user1/files_encryption/encryptionModule',
+ 'user1/files_encryption/backup/test.encryptionModule.1234567'
+ )->willReturn(true);
+
+ $this->assertTrue($storage->backupUserKeys('encryptionModule', 'test', 'user1'));
+ }
+
+ public function dataTestBackupUserKeys() {
+ return [
+ [true], [false]
+ ];
+ }
+}
diff --git a/tests/lib/Encryption/ManagerTest.php b/tests/lib/Encryption/ManagerTest.php
index d092068f6c6..8dd602349b6 100644
--- a/tests/lib/Encryption/ManagerTest.php
+++ b/tests/lib/Encryption/ManagerTest.php
@@ -49,16 +49,16 @@ class ManagerTest extends TestCase {
$this->manager = new Manager($this->config, $this->logger, $this->l10n, $this->view, $this->util, $this->arrayCache);
}
- public function testManagerIsDisabled() {
+ public function testManagerIsDisabled(): void {
$this->assertFalse($this->manager->isEnabled());
}
- public function testManagerIsDisabledIfEnabledButNoModules() {
+ public function testManagerIsDisabledIfEnabledButNoModules(): void {
$this->config->expects($this->any())->method('getAppValue')->willReturn(true);
$this->assertFalse($this->manager->isEnabled());
}
- public function testManagerIsDisabledIfDisabledButModules() {
+ public function testManagerIsDisabledIfDisabledButModules(): void {
$this->config->expects($this->any())->method('getAppValue')->willReturn(false);
$em = $this->createMock(IEncryptionModule::class);
$em->expects($this->any())->method('getId')->willReturn('id');
@@ -69,7 +69,7 @@ class ManagerTest extends TestCase {
$this->assertFalse($this->manager->isEnabled());
}
- public function testManagerIsEnabled() {
+ public function testManagerIsEnabled(): void {
$this->config->expects($this->any())->method('getSystemValueBool')->willReturn(true);
$this->config->expects($this->any())->method('getAppValue')->willReturn('yes');
$this->assertTrue($this->manager->isEnabled());
@@ -87,14 +87,14 @@ class ManagerTest extends TestCase {
/**
* @depends testModuleRegistration
*/
- public function testModuleReRegistration($manager) {
+ public function testModuleReRegistration($manager): void {
$this->expectException(\OC\Encryption\Exceptions\ModuleAlreadyExistsException::class);
$this->expectExceptionMessage('Id "ID0" already used by encryption module "TestDummyModule0"');
$this->addNewEncryptionModule($manager, 0);
}
- public function testModuleUnRegistration() {
+ public function testModuleUnRegistration(): void {
$this->config->expects($this->any())->method('getAppValue')->willReturn(true);
$this->addNewEncryptionModule($this->manager, 0);
$this->assertCount(1, $this->manager->getEncryptionModules());
@@ -104,7 +104,7 @@ class ManagerTest extends TestCase {
}
- public function testGetEncryptionModuleUnknown() {
+ public function testGetEncryptionModuleUnknown(): void {
$this->expectException(\OC\Encryption\Exceptions\ModuleDoesNotExistsException::class);
$this->expectExceptionMessage('Module with ID: unknown does not exist.');
@@ -114,7 +114,7 @@ class ManagerTest extends TestCase {
$this->manager->getEncryptionModule('unknown');
}
- public function testGetEncryptionModuleEmpty() {
+ public function testGetEncryptionModuleEmpty(): void {
global $defaultId;
$defaultId = null;
@@ -138,7 +138,7 @@ class ManagerTest extends TestCase {
$this->assertEquals('ID1', $this->manager->getEncryptionModule()->getId());
}
- public function testGetEncryptionModule() {
+ public function testGetEncryptionModule(): void {
global $defaultId;
$defaultId = null;
@@ -163,7 +163,7 @@ class ManagerTest extends TestCase {
$this->assertEquals('ID0', $this->manager->getDefaultEncryptionModuleId());
}
- public function testSetDefaultEncryptionModule() {
+ public function testSetDefaultEncryptionModule(): void {
global $defaultId;
$defaultId = null;
diff --git a/tests/lib/Encryption/UpdateTest.php b/tests/lib/Encryption/UpdateTest.php
index 1f20ac9ba51..012a6685a91 100644
--- a/tests/lib/Encryption/UpdateTest.php
+++ b/tests/lib/Encryption/UpdateTest.php
@@ -75,7 +75,7 @@ class UpdateTest extends TestCase {
* @param array $allFiles
* @param integer $numberOfFiles
*/
- public function testUpdate($path, $isDir, $allFiles, $numberOfFiles) {
+ public function testUpdate($path, $isDir, $allFiles, $numberOfFiles): void {
$this->encryptionManager->expects($this->once())
->method('getEncryptionModule')
->willReturn($this->encryptionModule);
@@ -120,7 +120,7 @@ class UpdateTest extends TestCase {
* @param string $target
* @param boolean $encryptionEnabled
*/
- public function testPostRename($source, $target, $encryptionEnabled) {
+ public function testPostRename($source, $target, $encryptionEnabled): void {
$updateMock = $this->getUpdateMock(['update', 'getOwnerPath']);
$this->encryptionManager->expects($this->once())
@@ -168,7 +168,7 @@ class UpdateTest extends TestCase {
*
* @param boolean $encryptionEnabled
*/
- public function testPostRestore($encryptionEnabled) {
+ public function testPostRestore($encryptionEnabled): void {
$updateMock = $this->getUpdateMock(['update']);
$this->encryptionManager->expects($this->once())
diff --git a/tests/lib/Encryption/UtilTest.php b/tests/lib/Encryption/UtilTest.php
index 813a288a470..62ef809a867 100644
--- a/tests/lib/Encryption/UtilTest.php
+++ b/tests/lib/Encryption/UtilTest.php
@@ -56,7 +56,7 @@ class UtilTest extends TestCase {
/**
* @dataProvider providesHeadersForEncryptionModule
*/
- public function testGetEncryptionModuleId($expected, $header) {
+ public function testGetEncryptionModuleId($expected, $header): void {
$id = $this->util->getEncryptionModuleId($header);
$this->assertEquals($expected, $id);
}
@@ -72,7 +72,7 @@ class UtilTest extends TestCase {
/**
* @dataProvider providesHeaders
*/
- public function testCreateHeader($expected, $header, $moduleId) {
+ public function testCreateHeader($expected, $header, $moduleId): void {
$em = $this->createMock(IEncryptionModule::class);
$em->expects($this->any())->method('getId')->willReturn($moduleId);
@@ -90,7 +90,7 @@ class UtilTest extends TestCase {
}
- public function testCreateHeaderFailed() {
+ public function testCreateHeaderFailed(): void {
$this->expectException(\OC\Encryption\Exceptions\EncryptionHeaderKeyExistsException::class);
@@ -105,7 +105,7 @@ class UtilTest extends TestCase {
/**
* @dataProvider providePathsForTestIsExcluded
*/
- public function testIsExcluded($path, $keyStorageRoot, $expected) {
+ public function testIsExcluded($path, $keyStorageRoot, $expected): void {
$this->config->expects($this->once())
->method('getAppValue')
->with('core', 'encryption_key_storage_root', '')
@@ -146,7 +146,7 @@ class UtilTest extends TestCase {
/**
* @dataProvider dataTestIsFile
*/
- public function testIsFile($path, $expected) {
+ public function testIsFile($path, $expected): void {
$this->assertSame($expected,
$this->util->isFile($path)
);
@@ -170,7 +170,7 @@ class UtilTest extends TestCase {
* @param string $path
* @param string $expected
*/
- public function testStripPartialFileExtension($path, $expected) {
+ public function testStripPartialFileExtension($path, $expected): void {
$this->assertSame($expected,
$this->util->stripPartialFileExtension($path));
}
@@ -187,7 +187,7 @@ class UtilTest extends TestCase {
/**
* @dataProvider dataTestParseRawHeader
*/
- public function testParseRawHeader($rawHeader, $expected) {
+ public function testParseRawHeader($rawHeader, $expected): void {
$result = $this->util->parseRawHeader($rawHeader);
$this->assertSameSize($expected, $result);
foreach ($result as $key => $value) {
@@ -218,7 +218,7 @@ class UtilTest extends TestCase {
* @param string $storageRoot
* @param string $expected
*/
- public function testGetFileKeyDir($isSystemWideMountPoint, $storageRoot, $expected) {
+ public function testGetFileKeyDir($isSystemWideMountPoint, $storageRoot, $expected): void {
$path = '/user1/files/foo/bar.txt';
$owner = 'user1';
$relativePath = '/foo/bar.txt';
diff --git a/tests/lib/ErrorHandlerTest.php b/tests/lib/ErrorHandlerTest.php
index 72974a14550..0846d09fd47 100644
--- a/tests/lib/ErrorHandlerTest.php
+++ b/tests/lib/ErrorHandlerTest.php
@@ -53,7 +53,7 @@ class ErrorHandlerTest extends TestCase {
* @param string $username
* @param string $password
*/
- public function testRemovePasswordFromError($username, $password) {
+ public function testRemovePasswordFromError($username, $password): void {
$url = 'http://'.$username.':'.$password.'@owncloud.org';
$expectedResult = 'http://xxx:xxx@owncloud.org';
$this->logger->expects(self::once())
diff --git a/tests/lib/Federation/CloudIdTest.php b/tests/lib/Federation/CloudIdTest.php
index 4ac9bd92d64..4087f45622d 100644
--- a/tests/lib/Federation/CloudIdTest.php
+++ b/tests/lib/Federation/CloudIdTest.php
@@ -24,7 +24,7 @@ class CloudIdTest extends TestCase {
* @param string $id
* @param string $display
*/
- public function testGetDisplayCloudId($id, $display) {
+ public function testGetDisplayCloudId($id, $display): void {
$cloudId = new CloudId($id, '', '');
$this->assertEquals($display, $cloudId->getDisplayId());
}
diff --git a/tests/lib/Files/AppData/AppDataTest.php b/tests/lib/Files/AppData/AppDataTest.php
index 241e49a026f..494096d1ac3 100644
--- a/tests/lib/Files/AppData/AppDataTest.php
+++ b/tests/lib/Files/AppData/AppDataTest.php
@@ -49,7 +49,7 @@ class AppDataTest extends \Test\TestCase {
return $appFolder;
}
- public function testGetFolder() {
+ public function testGetFolder(): void {
$folder = $this->createMock(Folder::class);
$this->rootFolder->expects($this->once())
@@ -61,7 +61,7 @@ class AppDataTest extends \Test\TestCase {
$this->assertInstanceOf(ISimpleFolder::class, $result);
}
- public function testNewFolder() {
+ public function testNewFolder(): void {
$appFolder = $this->setupAppFolder();
$folder = $this->createMock(Folder::class);
@@ -75,7 +75,7 @@ class AppDataTest extends \Test\TestCase {
$this->assertInstanceOf(ISimpleFolder::class, $result);
}
- public function testGetDirectoryListing() {
+ public function testGetDirectoryListing(): void {
$appFolder = $this->setupAppFolder();
$file = $this->createMock(File::class);
diff --git a/tests/lib/Files/AppData/FactoryTest.php b/tests/lib/Files/AppData/FactoryTest.php
index 1aad461e633..dff999d8b48 100644
--- a/tests/lib/Files/AppData/FactoryTest.php
+++ b/tests/lib/Files/AppData/FactoryTest.php
@@ -28,7 +28,7 @@ class FactoryTest extends \Test\TestCase {
$this->factory = new Factory($this->rootFolder, $this->systemConfig);
}
- public function testGet() {
+ public function testGet(): void {
$this->rootFolder->expects($this->never())
->method($this->anything());
$this->systemConfig->expects($this->never())
diff --git a/tests/lib/Files/Cache/CacheTest.php b/tests/lib/Files/Cache/CacheTest.php
index eca3531a7be..de6f4896aec 100644
--- a/tests/lib/Files/Cache/CacheTest.php
+++ b/tests/lib/Files/Cache/CacheTest.php
@@ -47,11 +47,11 @@ class CacheTest extends \Test\TestCase {
*/
protected $cache2;
- public function testGetNumericId() {
+ public function testGetNumericId(): void {
$this->assertNotNull($this->cache->getNumericStorageId());
}
- public function testSimple() {
+ public function testSimple(): void {
$file1 = 'foo';
$file2 = 'foo/bar';
$data1 = ['size' => 100, 'mtime' => 50, 'mimetype' => 'foo/folder'];
@@ -97,7 +97,7 @@ class CacheTest extends \Test\TestCase {
$this->assertEquals($cacheData1, $this->cache->get($id1));
}
- public function testCacheEntryGetters() {
+ public function testCacheEntryGetters(): void {
$file1 = 'foo';
$data1 = ['size' => 100, 'mtime' => 50, 'mimetype' => 'foo/file'];
@@ -122,7 +122,7 @@ class CacheTest extends \Test\TestCase {
$this->assertEquals($entry->getUnencryptedSize(), 100);
}
- public function testPartial() {
+ public function testPartial(): void {
$file1 = 'foo';
$this->cache->put($file1, ['size' => 10]);
@@ -138,7 +138,7 @@ class CacheTest extends \Test\TestCase {
/**
* @dataProvider folderDataProvider
*/
- public function testFolder($folder) {
+ 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();
@@ -187,7 +187,7 @@ class CacheTest extends \Test\TestCase {
$this->assertFalse($this->cache->inCache($folder . '/bar'));
}
- public function testRemoveRecursive() {
+ public function testRemoveRecursive(): void {
$folderData = ['size' => 100, 'mtime' => 50, 'mimetype' => 'httpd/unix-directory'];
$fileData = ['size' => 1000, 'mtime' => 20, 'mimetype' => 'text/plain'];
$folders = ['folder', 'folder/subfolder', 'folder/sub2', 'folder/sub2/sub3'];
@@ -220,7 +220,7 @@ class CacheTest extends \Test\TestCase {
];
}
- public function testEncryptedFolder() {
+ public function testEncryptedFolder(): void {
$file1 = 'folder';
$file2 = 'folder/bar';
$file3 = 'folder/foo';
@@ -263,7 +263,7 @@ class CacheTest extends \Test\TestCase {
$this->assertFalse($this->cache->inCache('folder/bar'));
}
- public function testRootFolderSizeForNonHomeStorage() {
+ public function testRootFolderSizeForNonHomeStorage(): void {
$dir1 = 'knownsize';
$dir2 = 'unknownsize';
$fileData = [];
@@ -290,7 +290,7 @@ class CacheTest extends \Test\TestCase {
$this->assertFalse($this->cache->inCache($dir2));
}
- public function testStatus() {
+ public function testStatus(): void {
$this->assertEquals(\OC\Files\Cache\Cache::NOT_FOUND, $this->cache->getStatus('foo'));
$this->cache->put('foo', ['size' => -1]);
$this->assertEquals(\OC\Files\Cache\Cache::PARTIAL, $this->cache->getStatus('foo'));
@@ -312,7 +312,7 @@ class CacheTest extends \Test\TestCase {
* @dataProvider putWithAllKindOfQuotesData
* @param $fileName
*/
- public function testPutWithAllKindOfQuotes($fileName) {
+ public function testPutWithAllKindOfQuotes($fileName): void {
$this->assertEquals(\OC\Files\Cache\Cache::NOT_FOUND, $this->cache->get($fileName));
$this->cache->put($fileName, ['size' => 20, 'mtime' => 25, 'mimetype' => 'foo/file', 'etag' => $fileName]);
@@ -321,7 +321,7 @@ class CacheTest extends \Test\TestCase {
$this->assertEquals($fileName, $cacheEntry['path']);
}
- public function testSearch() {
+ public function testSearch(): void {
$file1 = 'folder';
$file2 = 'folder/foobar';
$file3 = 'folder/foo';
@@ -350,7 +350,7 @@ class CacheTest extends \Test\TestCase {
$this->assertEquals(2, count($this->cache->searchByMime('foo/file')));
}
- public function testSearchQueryByTag() {
+ public function testSearchQueryByTag(): void {
$userId = static::getUniqueID('user');
\OC::$server->getUserManager()->createUser($userId, $userId);
static::loginAsUser($userId);
@@ -408,7 +408,7 @@ class CacheTest extends \Test\TestCase {
}
}
- public function testSearchByQuery() {
+ public function testSearchByQuery(): void {
$file1 = 'folder';
$file2 = 'folder/foobar';
$file3 = 'folder/foo';
@@ -448,7 +448,7 @@ class CacheTest extends \Test\TestCase {
/**
* @dataProvider movePathProvider
*/
- public function testMove($sourceFolder, $targetFolder, $children) {
+ public function testMove($sourceFolder, $targetFolder, $children): void {
$data = ['size' => 100, 'mtime' => 50, 'mimetype' => 'foo/bar'];
$folderData = ['size' => 100, 'mtime' => 50, 'mimetype' => 'httpd/unix-directory'];
@@ -483,7 +483,7 @@ class CacheTest extends \Test\TestCase {
}
}
- public function testMoveFromCache() {
+ public function testMoveFromCache(): void {
$data = ['size' => 100, 'mtime' => 50, 'mimetype' => 'foo/bar'];
$folderData = ['size' => 100, 'mtime' => 50, 'mimetype' => 'httpd/unix-directory'];
@@ -500,7 +500,7 @@ class CacheTest extends \Test\TestCase {
$this->assertTrue($this->cache->inCache('targetfolder/sub'));
}
- public function testGetIncomplete() {
+ public function testGetIncomplete(): void {
$file1 = 'folder1';
$file2 = 'folder2';
$file3 = 'folder3';
@@ -517,13 +517,13 @@ class CacheTest extends \Test\TestCase {
$this->assertEquals($file3, $this->cache->getIncomplete());
}
- public function testNonExisting() {
+ public function testNonExisting(): void {
$this->assertFalse($this->cache->get('foo.txt'));
$this->assertFalse($this->cache->get(-1));
$this->assertEquals([], $this->cache->getFolderContents('foo'));
}
- public function testGetById() {
+ public function testGetById(): void {
$storageId = $this->storage->getId();
$data = ['size' => 1000, 'mtime' => 20, 'mimetype' => 'foo/file'];
$id = $this->cache->put('foo', $data);
@@ -534,7 +534,7 @@ class CacheTest extends \Test\TestCase {
$this->assertEquals([$storageId, 'foo'], \OC\Files\Cache\Cache::getById($id));
}
- public function testStorageMTime() {
+ public function testStorageMTime(): void {
$data = ['size' => 1000, 'mtime' => 20, 'mimetype' => 'foo/file'];
$this->cache->put('foo', $data);
$cachedData = $this->cache->get('foo');
@@ -551,7 +551,7 @@ class CacheTest extends \Test\TestCase {
$this->assertEquals(25, $cachedData['mtime']);
}
- public function testLongId() {
+ public function testLongId(): void {
$storage = new LongId([]);
$cache = $storage->getCache();
$storageId = $storage->getId();
@@ -563,7 +563,7 @@ class CacheTest extends \Test\TestCase {
/**
* this test show the bug resulting if we have no normalizer installed
*/
- public function testWithoutNormalizer() {
+ public function testWithoutNormalizer(): void {
// folder name "Schön" with U+00F6 (normalized)
$folderWith00F6 = "\x53\x63\x68\xc3\xb6\x6e";
@@ -609,7 +609,7 @@ class CacheTest extends \Test\TestCase {
/**
* this test shows that there is no bug if we use the normalizer
*/
- public function testWithNormalizer() {
+ public function testWithNormalizer(): void {
if (!class_exists('Patchwork\PHP\Shim\Normalizer')) {
$this->markTestSkipped('The 3rdparty Normalizer extension is not available.');
return;
@@ -659,7 +659,7 @@ class CacheTest extends \Test\TestCase {
*
* @dataProvider bogusPathNamesProvider
*/
- public function testBogusPaths($bogusPath, $fixedBogusPath) {
+ public function testBogusPaths($bogusPath, $fixedBogusPath): void {
$data = ['size' => 100, 'mtime' => 50, 'mimetype' => 'httpd/unix-directory'];
// put root folder
@@ -681,7 +681,7 @@ class CacheTest extends \Test\TestCase {
$this->assertEquals($newData, $newDataFromBogus);
}
- public function testNoReuseOfFileId() {
+ public function testNoReuseOfFileId(): void {
$data1 = ['size' => 100, 'mtime' => 50, 'mimetype' => 'text/plain'];
$this->cache->put('somefile.txt', $data1);
$info = $this->cache->get('somefile.txt');
@@ -706,7 +706,7 @@ class CacheTest extends \Test\TestCase {
* @param string $name
* @dataProvider escapingProvider
*/
- public function testEscaping($name) {
+ public function testEscaping($name): void {
$data = ['size' => 100, 'mtime' => 50, 'mimetype' => 'text/plain'];
$this->cache->put($name, $data);
$this->assertTrue($this->cache->inCache($name));
@@ -742,7 +742,7 @@ class CacheTest extends \Test\TestCase {
}
}
- public function testExtended() {
+ public function testExtended(): void {
$folderData = ['size' => 100, 'mtime' => 50, 'mimetype' => 'httpd/unix-directory'];
$this->cache->put('', $folderData);
diff --git a/tests/lib/Files/Cache/HomeCacheTest.php b/tests/lib/Files/Cache/HomeCacheTest.php
index 986d6df4c17..ad069de1fef 100644
--- a/tests/lib/Files/Cache/HomeCacheTest.php
+++ b/tests/lib/Files/Cache/HomeCacheTest.php
@@ -78,7 +78,7 @@ class HomeCacheTest extends \Test\TestCase {
* that have an unknown size. This makes sure that quota calculation still
* works as it's based on the "files" folder size.
*/
- public function testRootFolderSizeIgnoresUnknownUpdate() {
+ public function testRootFolderSizeIgnoresUnknownUpdate(): void {
$dir1 = 'files/knownsize';
$dir2 = 'files/unknownsize';
$fileData = [];
@@ -110,7 +110,7 @@ class HomeCacheTest extends \Test\TestCase {
$this->assertFalse($this->cache->inCache($dir2));
}
- public function testRootFolderSizeIsFilesSize() {
+ public function testRootFolderSizeIsFilesSize(): void {
$dir1 = 'files';
$afile = 'test.txt';
$fileData = [];
diff --git a/tests/lib/Files/Cache/LocalRootScannerTest.php b/tests/lib/Files/Cache/LocalRootScannerTest.php
index 204621bbd03..e683283b7e1 100644
--- a/tests/lib/Files/Cache/LocalRootScannerTest.php
+++ b/tests/lib/Files/Cache/LocalRootScannerTest.php
@@ -25,7 +25,7 @@ class LocalRootScannerTest extends TestCase {
$this->storage = new LocalRootStorage(['datadir' => $folder]);
}
- public function testDontScanUsers() {
+ public function testDontScanUsers(): void {
$this->storage->mkdir('foo');
$this->storage->mkdir('foo/bar');
@@ -33,7 +33,7 @@ class LocalRootScannerTest extends TestCase {
$this->assertFalse($this->storage->getCache()->inCache('foo'));
}
- public function testDoScanAppData() {
+ public function testDoScanAppData(): void {
$this->storage->mkdir('appdata_foo');
$this->storage->mkdir('appdata_foo/bar');
diff --git a/tests/lib/Files/Cache/PropagatorTest.php b/tests/lib/Files/Cache/PropagatorTest.php
index dba1ae9c14e..e88816dfccc 100644
--- a/tests/lib/Files/Cache/PropagatorTest.php
+++ b/tests/lib/Files/Cache/PropagatorTest.php
@@ -38,7 +38,7 @@ class PropagatorTest extends TestCase {
return array_combine($paths, $values);
}
- public function testEtagPropagation() {
+ public function testEtagPropagation(): void {
$paths = ['', 'foo', 'foo/bar'];
$oldInfos = $this->getFileInfos($paths);
$this->storage->getPropagator()->propagateChange('foo/bar/file.txt', time());
@@ -49,7 +49,7 @@ class PropagatorTest extends TestCase {
}
}
- public function testTimePropagation() {
+ public function testTimePropagation(): void {
$paths = ['', 'foo', 'foo/bar'];
$oldTime = time() - 200;
$targetTime = time() - 100;
@@ -69,7 +69,7 @@ class PropagatorTest extends TestCase {
$this->assertEquals($now, $newInfos['']->getMTime());
}
- public function testSizePropagation() {
+ public function testSizePropagation(): void {
$paths = ['', 'foo', 'foo/bar'];
$oldInfos = $this->getFileInfos($paths);
$this->storage->getPropagator()->propagateChange('foo/bar/file.txt', time(), 10);
@@ -80,7 +80,7 @@ class PropagatorTest extends TestCase {
}
}
- public function testSizePropagationNoNegative() {
+ public function testSizePropagationNoNegative(): void {
$paths = ['', 'foo', 'foo/bar'];
$oldInfos = $this->getFileInfos($paths);
$this->storage->getPropagator()->propagateChange('foo/bar/file.txt', time(), -100);
@@ -91,7 +91,7 @@ class PropagatorTest extends TestCase {
}
}
- public function testBatchedPropagation() {
+ public function testBatchedPropagation(): void {
$this->storage->mkdir('foo/baz');
$this->storage->mkdir('asd');
$this->storage->file_put_contents('asd/file.txt', 'bar');
diff --git a/tests/lib/Files/Cache/ScannerTest.php b/tests/lib/Files/Cache/ScannerTest.php
index bc911baba0c..d78b7100d43 100644
--- a/tests/lib/Files/Cache/ScannerTest.php
+++ b/tests/lib/Files/Cache/ScannerTest.php
@@ -42,7 +42,7 @@ class ScannerTest extends TestCase {
parent::tearDown();
}
- public function testFile() {
+ public function testFile(): void {
$data = "dummy file data\n";
$this->storage->file_put_contents('foo.txt', $data);
$this->scanner->scanFile('foo.txt');
@@ -63,7 +63,7 @@ class ScannerTest extends TestCase {
$this->assertEquals($cachedData['mimetype'], 'image/png');
}
- public function testFile4Byte() {
+ public function testFile4Byte(): void {
$data = "dummy file data\n";
$this->storage->file_put_contents('foo🙈.txt', $data);
@@ -81,7 +81,7 @@ class ScannerTest extends TestCase {
}
}
- public function testFileInvalidChars() {
+ public function testFileInvalidChars(): void {
$data = "dummy file data\n";
$this->storage->file_put_contents("foo\nbar.txt", $data);
@@ -98,7 +98,7 @@ class ScannerTest extends TestCase {
$this->storage->file_put_contents('folder/bar.txt', $textData);
}
- public function testFolder() {
+ public function testFolder(): void {
$this->fillTestFolders();
$this->scanner->scan('');
@@ -120,7 +120,7 @@ class ScannerTest extends TestCase {
$this->assertEquals($cachedDataFolder2['size'], $cachedDataText2['size']);
}
- public function testShallow() {
+ public function testShallow(): void {
$this->fillTestFolders();
$this->scanner->scan('', IScanner::SCAN_SHALLOW);
@@ -148,7 +148,7 @@ class ScannerTest extends TestCase {
$this->assertNotEquals($cachedDataFolder['size'], -1);
}
- public function testBackgroundScan() {
+ public function testBackgroundScan(): void {
$this->fillTestFolders();
$this->storage->mkdir('folder2');
$this->storage->file_put_contents('folder2/bar.txt', 'foobar');
@@ -170,7 +170,7 @@ class ScannerTest extends TestCase {
$this->assertFalse($this->cache->getIncomplete());
}
- public function testBackgroundScanOnlyRecurseIncomplete() {
+ public function testBackgroundScanOnlyRecurseIncomplete(): void {
$this->fillTestFolders();
$this->storage->mkdir('folder2');
$this->storage->file_put_contents('folder2/bar.txt', 'foobar');
@@ -196,7 +196,7 @@ class ScannerTest extends TestCase {
$this->assertFalse($this->cache->getIncomplete());
}
- public function testBackgroundScanNestedIncompleteFolders() {
+ public function testBackgroundScanNestedIncompleteFolders(): void {
$this->storage->mkdir('folder');
$this->scanner->backgroundScan();
@@ -234,7 +234,7 @@ class ScannerTest extends TestCase {
$this->assertEquals(6, $this->cache->get('folder/subfolder2')['size']);
}
- public function testReuseExisting() {
+ public function testReuseExisting(): void {
$this->fillTestFolders();
$this->scanner->scan('');
@@ -273,7 +273,7 @@ class ScannerTest extends TestCase {
$this->assertEquals($oldData['size'], $newData['size']);
}
- public function testRemovedFile() {
+ public function testRemovedFile(): void {
$this->fillTestFolders();
$this->scanner->scan('');
@@ -283,7 +283,7 @@ class ScannerTest extends TestCase {
$this->assertFalse($this->cache->inCache('foo.txt'));
}
- public function testRemovedFolder() {
+ public function testRemovedFolder(): void {
$this->fillTestFolders();
$this->scanner->scan('');
@@ -294,7 +294,7 @@ class ScannerTest extends TestCase {
$this->assertFalse($this->cache->inCache('folder/bar.txt'));
}
- public function testScanRemovedFile() {
+ public function testScanRemovedFile(): void {
$this->fillTestFolders();
$this->scanner->scan('');
@@ -304,7 +304,7 @@ class ScannerTest extends TestCase {
$this->assertFalse($this->cache->inCache('folder/bar.txt'));
}
- public function testETagRecreation() {
+ public function testETagRecreation(): void {
$this->fillTestFolders();
$this->scanner->scan('folder/bar.txt');
@@ -330,7 +330,7 @@ class ScannerTest extends TestCase {
$this->assertNotEmpty($newData0['etag']);
}
- public function testRepairParent() {
+ public function testRepairParent(): void {
$this->fillTestFolders();
$this->scanner->scan('');
$this->assertTrue($this->cache->inCache('folder/bar.txt'));
@@ -356,7 +356,7 @@ class ScannerTest extends TestCase {
$this->assertEquals($newFolderId, $cachedData['parent']);
}
- public function testRepairParentShallow() {
+ public function testRepairParentShallow(): void {
$this->fillTestFolders();
$this->scanner->scan('');
$this->assertTrue($this->cache->inCache('folder/bar.txt'));
@@ -388,7 +388,7 @@ class ScannerTest extends TestCase {
* @param string $path
* @param bool $expected
*/
- public function testIsPartialFile($path, $expected) {
+ public function testIsPartialFile($path, $expected): void {
$this->assertSame($expected,
$this->scanner->isPartialFile($path)
);
@@ -404,7 +404,7 @@ class ScannerTest extends TestCase {
];
}
- public function testNoETagUnscannedFolder() {
+ public function testNoETagUnscannedFolder(): void {
$this->fillTestFolders();
$this->scanner->scan('');
@@ -423,7 +423,7 @@ class ScannerTest extends TestCase {
$this->assertNotEquals($newFolderEntry->getEtag(), $oldFolderEntry->getEtag());
}
- public function testNoETagUnscannedSubFolder() {
+ public function testNoETagUnscannedSubFolder(): void {
$this->fillTestFolders();
$this->storage->mkdir('folder/sub');
diff --git a/tests/lib/Files/Cache/SearchBuilderTest.php b/tests/lib/Files/Cache/SearchBuilderTest.php
index 57d890fcbcd..acb2e109144 100644
--- a/tests/lib/Files/Cache/SearchBuilderTest.php
+++ b/tests/lib/Files/Cache/SearchBuilderTest.php
@@ -175,7 +175,7 @@ class SearchBuilderTest extends TestCase {
* @param ISearchOperator $operator
* @param array $fileIds
*/
- public function testComparison(ISearchOperator $operator, array $fileIds) {
+ public function testComparison(ISearchOperator $operator, array $fileIds): void {
$fileId = [];
$fileId[] = $this->addCacheEntry([
'path' => 'foobar',
diff --git a/tests/lib/Files/Cache/UpdaterLegacyTest.php b/tests/lib/Files/Cache/UpdaterLegacyTest.php
index d95607eaeff..0f7e9d78d77 100644
--- a/tests/lib/Files/Cache/UpdaterLegacyTest.php
+++ b/tests/lib/Files/Cache/UpdaterLegacyTest.php
@@ -86,7 +86,7 @@ class UpdaterLegacyTest extends \Test\TestCase {
parent::tearDown();
}
- public function testWrite() {
+ public function testWrite(): void {
$textSize = strlen("dummy file data\n");
$imageSize = filesize(\OC::$SERVERROOT . '/core/img/logo/logo.png');
$this->cache->put('foo.txt', ['mtime' => 100, 'storage_mtime' => 150]);
@@ -121,7 +121,7 @@ class UpdaterLegacyTest extends \Test\TestCase {
$this->assertGreaterThanOrEqual($rootCachedData['mtime'], $mtime);
}
- public function testWriteWithMountPoints() {
+ public function testWriteWithMountPoints(): void {
$storage2 = new \OC\Files\Storage\Temporary([]);
$storage2->getScanner()->scan(''); //initialize etags
$cache2 = $storage2->getCache();
@@ -147,7 +147,7 @@ class UpdaterLegacyTest extends \Test\TestCase {
$this->assertNotSame($oldEtag, $cachedData['etag']);
}
- public function testDelete() {
+ public function testDelete(): void {
$textSize = strlen("dummy file data\n");
$imageSize = filesize(\OC::$SERVERROOT . '/core/img/logo/logo.png');
$rootCachedData = $this->cache->get('');
@@ -182,7 +182,7 @@ class UpdaterLegacyTest extends \Test\TestCase {
$this->assertGreaterThanOrEqual($rootCachedData['mtime'], $cachedData['mtime']);
}
- public function testDeleteWithMountPoints() {
+ public function testDeleteWithMountPoints(): void {
$storage2 = new \OC\Files\Storage\Temporary([]);
$cache2 = $storage2->getCache();
Filesystem::mount($storage2, [], '/' . self::$user . '/files/folder/substorage');
@@ -208,7 +208,7 @@ class UpdaterLegacyTest extends \Test\TestCase {
$this->assertGreaterThanOrEqual($folderCachedData['mtime'], $cachedData['mtime']);
}
- public function testRename() {
+ public function testRename(): void {
$textSize = strlen("dummy file data\n");
$imageSize = filesize(\OC::$SERVERROOT . '/core/img/logo/logo.png');
$rootCachedData = $this->cache->get('');
@@ -230,7 +230,7 @@ class UpdaterLegacyTest extends \Test\TestCase {
$this->assertNotSame($rootCachedData['etag'], $cachedData['etag']);
}
- public function testRenameExtension() {
+ public function testRenameExtension(): void {
$fooCachedData = $this->cache->get('foo.txt');
$this->assertEquals('text/plain', $fooCachedData['mimetype']);
Filesystem::rename('foo.txt', 'foo.abcd');
@@ -238,7 +238,7 @@ class UpdaterLegacyTest extends \Test\TestCase {
$this->assertEquals('application/octet-stream', $fooCachedData['mimetype']);
}
- public function testRenameWithMountPoints() {
+ public function testRenameWithMountPoints(): void {
$storage2 = new \OC\Files\Storage\Temporary([]);
$cache2 = $storage2->getCache();
Filesystem::mount($storage2, [], '/' . self::$user . '/files/folder/substorage');
@@ -271,7 +271,7 @@ class UpdaterLegacyTest extends \Test\TestCase {
// $this->assertEquals($mtime, $cachedData['mtime']);
}
- public function testTouch() {
+ public function testTouch(): void {
$rootCachedData = $this->cache->get('');
$fooCachedData = $this->cache->get('foo.txt');
Filesystem::touch('foo.txt');
diff --git a/tests/lib/Files/Cache/UpdaterTest.php b/tests/lib/Files/Cache/UpdaterTest.php
index bfc17e64467..8b8697fc139 100644
--- a/tests/lib/Files/Cache/UpdaterTest.php
+++ b/tests/lib/Files/Cache/UpdaterTest.php
@@ -53,7 +53,7 @@ class UpdaterTest extends \Test\TestCase {
parent::tearDown();
}
- public function testNewFile() {
+ public function testNewFile(): void {
$this->storage->file_put_contents('foo.txt', 'bar');
$this->assertFalse($this->cache->inCache('foo.txt'));
@@ -65,7 +65,7 @@ class UpdaterTest extends \Test\TestCase {
$this->assertEquals('text/plain', $cached['mimetype']);
}
- public function testUpdatedFile() {
+ public function testUpdatedFile(): void {
$this->storage->file_put_contents('foo.txt', 'bar');
$this->updater->update('foo.txt');
@@ -84,7 +84,7 @@ class UpdaterTest extends \Test\TestCase {
$this->assertEquals(6, $cached['size']);
}
- public function testParentSize() {
+ public function testParentSize(): void {
$this->storage->getScanner()->scan('');
$parentCached = $this->cache->get('');
@@ -121,7 +121,7 @@ class UpdaterTest extends \Test\TestCase {
$this->assertEquals(0, $parentCached['size']);
}
- public function testMove() {
+ public function testMove(): void {
$this->storage->file_put_contents('foo.txt', 'qwerty');
$this->updater->update('foo.txt');
@@ -146,7 +146,7 @@ class UpdaterTest extends \Test\TestCase {
$this->assertEquals($cached['fileid'], $cachedTarget['fileid']);
}
- public function testMoveNonExistingOverwrite() {
+ public function testMoveNonExistingOverwrite(): void {
$this->storage->file_put_contents('bar.txt', 'qwerty');
$this->updater->update('bar.txt');
@@ -164,7 +164,7 @@ class UpdaterTest extends \Test\TestCase {
$this->assertEquals($cached['fileid'], $cachedTarget['fileid']);
}
- public function testUpdateStorageMTime() {
+ public function testUpdateStorageMTime(): void {
$this->storage->mkdir('sub');
$this->storage->mkdir('sub2');
$this->storage->file_put_contents('sub/foo.txt', 'qwerty');
@@ -205,7 +205,7 @@ class UpdaterTest extends \Test\TestCase {
$this->assertNotEquals($testmtime, $cachedTargetParent['mtime'], 'target folder mtime changed, not from storage');
}
- public function testNewFileDisabled() {
+ public function testNewFileDisabled(): void {
$this->storage->file_put_contents('foo.txt', 'bar');
$this->assertFalse($this->cache->inCache('foo.txt'));
@@ -215,7 +215,7 @@ class UpdaterTest extends \Test\TestCase {
$this->assertFalse($this->cache->inCache('foo.txt'));
}
- public function testMoveCrossStorage() {
+ public function testMoveCrossStorage(): void {
$storage2 = new Temporary([]);
$cache2 = $storage2->getCache();
Filesystem::mount($storage2, [], '/bar');
@@ -246,7 +246,7 @@ class UpdaterTest extends \Test\TestCase {
$this->assertEquals($cached['fileid'], $cachedTarget['fileid']);
}
- public function testMoveFolderCrossStorage() {
+ public function testMoveFolderCrossStorage(): void {
$storage2 = new Temporary([]);
$cache2 = $storage2->getCache();
Filesystem::mount($storage2, [], '/bar');
diff --git a/tests/lib/Files/Cache/WatcherTest.php b/tests/lib/Files/Cache/WatcherTest.php
index d4a44ca6aa0..7319aa9b68d 100644
--- a/tests/lib/Files/Cache/WatcherTest.php
+++ b/tests/lib/Files/Cache/WatcherTest.php
@@ -40,7 +40,7 @@ class WatcherTest extends \Test\TestCase {
/**
* @medium
*/
- public function testWatcher() {
+ public function testWatcher(): void {
$storage = $this->getTestStorage();
$cache = $storage->getCache();
$updater = $storage->getWatcher();
@@ -81,7 +81,7 @@ class WatcherTest extends \Test\TestCase {
/**
* @medium
*/
- public function testFileToFolder() {
+ public function testFileToFolder(): void {
$storage = $this->getTestStorage();
$cache = $storage->getCache();
$updater = $storage->getWatcher();
@@ -116,7 +116,7 @@ class WatcherTest extends \Test\TestCase {
$this->assertTrue($cache->inCache('foo.txt/bar.txt'));
}
- public function testPolicyNever() {
+ public function testPolicyNever(): void {
$storage = $this->getTestStorage();
$cache = $storage->getCache();
$updater = $storage->getWatcher();
@@ -134,7 +134,7 @@ class WatcherTest extends \Test\TestCase {
$this->assertFalse($updater->checkUpdate('foo.txt'));
}
- public function testPolicyOnce() {
+ public function testPolicyOnce(): void {
$storage = $this->getTestStorage();
$cache = $storage->getCache();
$updater = $storage->getWatcher();
@@ -152,7 +152,7 @@ class WatcherTest extends \Test\TestCase {
$this->assertFalse($updater->checkUpdate('foo.txt'));
}
- public function testPolicyAlways() {
+ public function testPolicyAlways(): void {
$storage = $this->getTestStorage();
$cache = $storage->getCache();
$updater = $storage->getWatcher();
diff --git a/tests/lib/Files/Cache/Wrapper/CacheJailTest.php b/tests/lib/Files/Cache/Wrapper/CacheJailTest.php
index d0a6f99cb19..697a506971b 100644
--- a/tests/lib/Files/Cache/Wrapper/CacheJailTest.php
+++ b/tests/lib/Files/Cache/Wrapper/CacheJailTest.php
@@ -36,7 +36,7 @@ class CacheJailTest extends CacheTest {
$this->cache = new \OC\Files\Cache\Wrapper\CacheJail($this->sourceCache, 'foo');
}
- public function testSearchOutsideJail() {
+ public function testSearchOutsideJail(): void {
$this->storage->getScanner()->scan('');
$file1 = 'foo/foobar';
$file2 = 'folder/foobar';
@@ -60,7 +60,7 @@ class CacheJailTest extends CacheTest {
$this->assertEquals('foobar', $result[1]['path']);
}
- public function testSearchMimeOutsideJail() {
+ public function testSearchMimeOutsideJail(): void {
$this->storage->getScanner()->scan('');
$file1 = 'foo/foobar';
$file2 = 'folder/foobar';
@@ -76,7 +76,7 @@ class CacheJailTest extends CacheTest {
$this->assertEquals('foobar', $result[0]['path']);
}
- public function testSearchQueryOutsideJail() {
+ public function testSearchQueryOutsideJail(): void {
$this->storage->getScanner()->scan('');
$file1 = 'foo/foobar';
$file2 = 'folder/foobar';
@@ -98,7 +98,7 @@ class CacheJailTest extends CacheTest {
$this->assertEquals('', $result[0]['path']);
}
- public function testClearKeepEntriesOutsideJail() {
+ public function testClearKeepEntriesOutsideJail(): void {
$file1 = 'foo/foobar';
$file2 = 'foo/foobar/asd';
$file3 = 'folder/foobar';
@@ -115,7 +115,7 @@ class CacheJailTest extends CacheTest {
$this->assertTrue($this->sourceCache->inCache('folder/foobar'));
}
- public function testGetById() {
+ public function testGetById(): void {
$data1 = ['size' => 100, 'mtime' => 50, 'mimetype' => 'httpd/unix-directory'];
$id = $this->sourceCache->put('foo/bar', $data1);
@@ -129,12 +129,12 @@ class CacheJailTest extends CacheTest {
$this->assertEquals('foo/bar', $path);
}
- public function testGetIncomplete() {
+ public function testGetIncomplete(): void {
//not supported
$this->addToAssertionCount(1);
}
- public function testMoveFromJail() {
+ public function testMoveFromJail(): void {
$folderData = ['size' => 100, 'mtime' => 50, 'mimetype' => 'httpd/unix-directory'];
$this->sourceCache->put('source', $folderData);
@@ -150,7 +150,7 @@ class CacheJailTest extends CacheTest {
$this->assertTrue($this->sourceCache->inCache('target/foo/bar'));
}
- public function testMoveToJail() {
+ public function testMoveToJail(): void {
$folderData = ['size' => 100, 'mtime' => 50, 'mimetype' => 'httpd/unix-directory'];
$this->sourceCache->put('source', $folderData);
@@ -166,7 +166,7 @@ class CacheJailTest extends CacheTest {
$this->assertTrue($this->sourceCache->inCache('target/foo/bar'));
}
- public function testMoveBetweenJail() {
+ public function testMoveBetweenJail(): void {
$folderData = ['size' => 100, 'mtime' => 50, 'mimetype' => 'httpd/unix-directory'];
$this->sourceCache->put('source', $folderData);
@@ -183,7 +183,7 @@ class CacheJailTest extends CacheTest {
$this->assertTrue($this->sourceCache->inCache('target/foo/bar'));
}
- public function testSearchNested() {
+ public function testSearchNested(): void {
$this->storage->getScanner()->scan('');
$file1 = 'foo';
$file2 = 'foo/bar';
@@ -201,7 +201,7 @@ class CacheJailTest extends CacheTest {
$this->assertEquals('asd', $result[0]['path']);
}
- public function testRootJail() {
+ public function testRootJail(): void {
$this->storage->getScanner()->scan('');
$file1 = 'foo';
$file2 = 'foo/bar';
@@ -219,7 +219,7 @@ class CacheJailTest extends CacheTest {
$this->assertEquals('foo/bar/asd', $result[0]['path']);
}
- public function testWatcher() {
+ public function testWatcher(): void {
$storage = new Jail([
'storage' => $this->storage,
'root' => 'foo'
@@ -232,7 +232,7 @@ class CacheJailTest extends CacheTest {
$this->assertTrue($this->cache->inCache('bar'));
}
- public function testWatcherAfterInnerWatcher() {
+ public function testWatcherAfterInnerWatcher(): void {
$storage = new Jail([
'storage' => $this->storage,
'root' => 'foo'
diff --git a/tests/lib/Files/Cache/Wrapper/CachePermissionsMaskTest.php b/tests/lib/Files/Cache/Wrapper/CachePermissionsMaskTest.php
index d3eb8be7af9..afb5c6a5d4d 100644
--- a/tests/lib/Files/Cache/Wrapper/CachePermissionsMaskTest.php
+++ b/tests/lib/Files/Cache/Wrapper/CachePermissionsMaskTest.php
@@ -47,7 +47,7 @@ class CachePermissionsMaskTest extends CacheTest {
* @dataProvider maskProvider
* @param int $mask
*/
- public function testGetMasked($mask) {
+ public function testGetMasked($mask): void {
$cache = $this->getMaskedCached($mask);
$data = ['size' => 100, 'mtime' => 50, 'mimetype' => 'text/plain', 'permissions' => Constants::PERMISSION_ALL];
$this->sourceCache->put('foo', $data);
@@ -64,7 +64,7 @@ class CachePermissionsMaskTest extends CacheTest {
* @dataProvider maskProvider
* @param int $mask
*/
- public function testGetFolderContentMasked($mask) {
+ public function testGetFolderContentMasked($mask): void {
$this->storage->mkdir('foo');
$this->storage->file_put_contents('foo/bar', 'asd');
$this->storage->file_put_contents('foo/asd', 'bar');
@@ -83,7 +83,7 @@ class CachePermissionsMaskTest extends CacheTest {
* @dataProvider maskProvider
* @param int $mask
*/
- public function testSearchMasked($mask) {
+ public function testSearchMasked($mask): void {
$this->storage->mkdir('foo');
$this->storage->file_put_contents('foo/bar', 'asd');
$this->storage->file_put_contents('foo/foobar', 'bar');
diff --git a/tests/lib/Files/Config/UserMountCacheTest.php b/tests/lib/Files/Config/UserMountCacheTest.php
index 8da2f380955..77b2c80d053 100644
--- a/tests/lib/Files/Config/UserMountCacheTest.php
+++ b/tests/lib/Files/Config/UserMountCacheTest.php
@@ -123,7 +123,7 @@ class UserMountCacheTest extends TestCase {
return $mount->getStorageRootId().'::'.$mount->getMountPoint();
}
- public function testNewMounts() {
+ public function testNewMounts(): void {
$user = $this->userManager->get('u1');
[$storage] = $this->getStorage(10);
@@ -143,7 +143,7 @@ class UserMountCacheTest extends TestCase {
$this->assertEquals($storage->getStorageCache()->getNumericId(), $cachedMount->getStorageId());
}
- public function testSameMounts() {
+ public function testSameMounts(): void {
$user = $this->userManager->get('u1');
[$storage] = $this->getStorage(10);
@@ -167,7 +167,7 @@ class UserMountCacheTest extends TestCase {
$this->assertEquals($storage->getStorageCache()->getNumericId(), $cachedMount->getStorageId());
}
- public function testRemoveMounts() {
+ public function testRemoveMounts(): void {
$user = $this->userManager->get('u1');
[$storage] = $this->getStorage(10);
@@ -186,7 +186,7 @@ class UserMountCacheTest extends TestCase {
$this->assertCount(0, $cachedMounts);
}
- public function testChangeMounts() {
+ public function testChangeMounts(): void {
$user = $this->userManager->get('u1');
[$storage] = $this->getStorage(10);
@@ -209,7 +209,7 @@ class UserMountCacheTest extends TestCase {
$this->assertEquals('/foo/', $cachedMount->getMountPoint());
}
- public function testChangeMountId() {
+ public function testChangeMountId(): void {
$user = $this->userManager->get('u1');
[$storage] = $this->getStorage(10);
@@ -232,7 +232,7 @@ class UserMountCacheTest extends TestCase {
$this->assertEquals(1, $cachedMount->getMountId());
}
- public function testGetMountsForUser() {
+ public function testGetMountsForUser(): void {
$user1 = $this->userManager->get('u1');
$user2 = $this->userManager->get('u2');
$user3 = $this->userManager->get('u3');
@@ -269,7 +269,7 @@ class UserMountCacheTest extends TestCase {
$this->assertEmpty($cachedMounts);
}
- public function testGetMountsByStorageId() {
+ public function testGetMountsByStorageId(): void {
$user1 = $this->userManager->get('u1');
$user2 = $this->userManager->get('u2');
@@ -299,7 +299,7 @@ class UserMountCacheTest extends TestCase {
$this->assertEquals(2, $cachedMounts[1]->getStorageId());
}
- public function testGetMountsByRootId() {
+ public function testGetMountsByRootId(): void {
$user1 = $this->userManager->get('u1');
$user2 = $this->userManager->get('u2');
@@ -373,7 +373,7 @@ class UserMountCacheTest extends TestCase {
return $id;
}
- public function testGetMountsForFileIdRootId() {
+ public function testGetMountsForFileIdRootId(): void {
$user1 = $this->userManager->get('u1');
[$storage1, $rootId] = $this->getStorage(2);
@@ -393,7 +393,7 @@ class UserMountCacheTest extends TestCase {
$this->assertEquals(2, $cachedMounts[0]->getStorageId());
}
- public function testGetMountsForFileIdSubFolder() {
+ public function testGetMountsForFileIdSubFolder(): void {
$user1 = $this->userManager->get('u1');
$fileId = $this->createCacheEntry('/foo/bar', 2);
@@ -417,7 +417,7 @@ class UserMountCacheTest extends TestCase {
$this->assertEquals('/foo/foo/bar', $cachedMounts[0]->getPath());
}
- public function testGetMountsForFileIdSubFolderMount() {
+ public function testGetMountsForFileIdSubFolderMount(): void {
$user1 = $this->userManager->get('u1');
[$storage1, $rootId] = $this->getStorage(2);
@@ -451,7 +451,7 @@ class UserMountCacheTest extends TestCase {
$this->assertEquals('/bar', $cachedMounts[0]->getPath());
}
- public function testGetMountsForFileIdSubFolderMountOutside() {
+ public function testGetMountsForFileIdSubFolderMountOutside(): void {
$user1 = $this->userManager->get('u1');
[$storage1, $rootId] = $this->getStorage(2);
@@ -479,7 +479,7 @@ class UserMountCacheTest extends TestCase {
}
- public function testGetMountsForFileIdDeletedUser() {
+ public function testGetMountsForFileIdDeletedUser(): void {
$user1 = $this->userManager->get('u1');
[$storage1, $rootId] = $this->getStorage(2);
@@ -494,7 +494,7 @@ class UserMountCacheTest extends TestCase {
$this->assertEmpty($cachedMounts);
}
- public function testGetUsedSpaceForUsers() {
+ public function testGetUsedSpaceForUsers(): void {
$user1 = $this->userManager->get('u1');
$user2 = $this->userManager->get('u2');
@@ -525,7 +525,7 @@ class UserMountCacheTest extends TestCase {
}
- public function testMigrateMountProvider() {
+ public function testMigrateMountProvider(): void {
$user1 = $this->userManager->get('u1');
[$storage1, $rootId] = $this->getStorage(2);
diff --git a/tests/lib/Files/EtagTest.php b/tests/lib/Files/EtagTest.php
index b70785b192e..2c8888b2dea 100644
--- a/tests/lib/Files/EtagTest.php
+++ b/tests/lib/Files/EtagTest.php
@@ -55,7 +55,7 @@ class EtagTest extends \Test\TestCase {
parent::tearDown();
}
- public function testNewUser() {
+ public function testNewUser(): void {
$user1 = $this->getUniqueID('user_');
$this->userBackend->createUser($user1, '');
diff --git a/tests/lib/Files/FileInfoTest.php b/tests/lib/Files/FileInfoTest.php
index bc4a25ef622..2979252f78a 100644
--- a/tests/lib/Files/FileInfoTest.php
+++ b/tests/lib/Files/FileInfoTest.php
@@ -27,7 +27,7 @@ class FileInfoTest extends TestCase {
$this->config = $this->getMockBuilder(IConfig::class)->getMock();
}
- public function testIsMountedHomeStorage() {
+ public function testIsMountedHomeStorage(): void {
$user = $this->createMock(IUser::class);
$user->method('getUID')
->willReturn('foo');
@@ -45,7 +45,7 @@ class FileInfoTest extends TestCase {
$this->assertFalse($fileInfo->isMounted());
}
- public function testIsMountedNonHomeStorage() {
+ public function testIsMountedNonHomeStorage(): void {
$storage = new Temporary();
$fileInfo = new FileInfo(
'',
diff --git a/tests/lib/Files/FilesystemTest.php b/tests/lib/Files/FilesystemTest.php
index 1045c968417..c47d85994c6 100644
--- a/tests/lib/Files/FilesystemTest.php
+++ b/tests/lib/Files/FilesystemTest.php
@@ -1,476 +1,476 @@
-<?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\Files;
-
-use OC\Files\Mount\MountPoint;
-use OC\Files\Storage\Temporary;
-use OC\User\NoUserException;
-use OCP\Files\Config\IMountProvider;
-use OCP\Files\Storage\IStorageFactory;
-use OCP\IUser;
-
-class DummyMountProvider implements IMountProvider {
- private $mounts = [];
-
- /**
- * @param array $mounts
- */
- public function __construct(array $mounts) {
- $this->mounts = $mounts;
- }
-
- /**
- * Get the pre-registered mount points
- *
- * @param IUser $user
- * @param IStorageFactory $loader
- * @return \OCP\Files\Mount\IMountPoint[]
- */
- public function getMountsForUser(IUser $user, IStorageFactory $loader) {
- return isset($this->mounts[$user->getUID()]) ? $this->mounts[$user->getUID()] : [];
- }
-}
-
-/**
- * Class FilesystemTest
- *
- * @group DB
- *
- * @package Test\Files
- */
-class FilesystemTest extends \Test\TestCase {
- public const TEST_FILESYSTEM_USER1 = 'test-filesystem-user1';
- public const TEST_FILESYSTEM_USER2 = 'test-filesystem-user1';
-
- /**
- * @var array tmpDirs
- */
- private $tmpDirs = [];
-
- /**
- * @return array
- */
- private function getStorageData() {
- $dir = \OC::$server->getTempManager()->getTemporaryFolder();
- $this->tmpDirs[] = $dir;
- return ['datadir' => $dir];
- }
-
- protected function setUp(): void {
- parent::setUp();
- $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);
- $this->loginAsUser();
- }
-
- protected function tearDown(): void {
- foreach ($this->tmpDirs as $dir) {
- \OC_Helper::rmdirr($dir);
- }
-
- $this->logout();
- $this->invokePrivate(\OC\Files\Filesystem::class, 'normalizedPathCache', [null]);
- parent::tearDown();
- }
-
- public function testMount() {
- \OC\Files\Filesystem::mount(\OC\Files\Storage\Local::class, self::getStorageData(), '/');
- $this->assertEquals('/', \OC\Files\Filesystem::getMountPoint('/'));
- $this->assertEquals('/', \OC\Files\Filesystem::getMountPoint('/some/folder'));
- [, $internalPath] = \OC\Files\Filesystem::resolvePath('/');
- $this->assertEquals('', $internalPath);
- [, $internalPath] = \OC\Files\Filesystem::resolvePath('/some/folder');
- $this->assertEquals('some/folder', $internalPath);
-
- \OC\Files\Filesystem::mount(\OC\Files\Storage\Local::class, 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');
- $this->assertEquals('folder', $internalPath);
- }
-
- public function normalizePathData() {
- return [
- ['/', ''],
- ['/', '/'],
- ['/', '//'],
- ['/', '/', false],
- ['/', '//', false],
-
- ['/path', '/path/'],
- ['/path/', '/path/', false],
- ['/path', 'path'],
-
- ['/foo/bar', '/foo//bar/'],
- ['/foo/bar/', '/foo//bar/', false],
- ['/foo/bar', '/foo////bar'],
- ['/foo/bar', '/foo/////bar'],
- ['/foo/bar', '/foo/bar/.'],
- ['/foo/bar', '/foo/bar/./'],
- ['/foo/bar/', '/foo/bar/./', false],
- ['/foo/bar', '/foo/bar/./.'],
- ['/foo/bar', '/foo/bar/././'],
- ['/foo/bar/', '/foo/bar/././', false],
- ['/foo/bar', '/foo/./bar/'],
- ['/foo/bar/', '/foo/./bar/', false],
- ['/foo/.bar', '/foo/.bar/'],
- ['/foo/.bar/', '/foo/.bar/', false],
- ['/foo/.bar/tee', '/foo/.bar/tee'],
- ['/foo/bar.', '/foo/bar./'],
- ['/foo/bar./', '/foo/bar./', false],
- ['/foo/bar./tee', '/foo/bar./tee'],
- ['/foo/.bar.', '/foo/.bar./'],
- ['/foo/.bar./', '/foo/.bar./', false],
- ['/foo/.bar./tee', '/foo/.bar./tee'],
-
- ['/foo/bar', '/.////././//./foo/.///././//./bar/././/./.'],
- ['/foo/bar/', '/.////././//./foo/.///././//./bar/./././.', false],
- ['/foo/bar', '/.////././//./foo/.///././//./bar/././/././'],
- ['/foo/bar/', '/.////././//./foo/.///././//./bar/././/././', false],
- ['/foo/.bar', '/.////././//./foo/./././/./.bar/././/././'],
- ['/foo/.bar/', '/.////././//./foo/./././/./.bar/././/././', false],
- ['/foo/.bar/tee./', '/.////././//./foo/./././/./.bar/tee././/././', false],
- ['/foo/bar.', '/.////././//./foo/./././/./bar./././/././'],
- ['/foo/bar./', '/.////././//./foo/./././/./bar./././/././', false],
- ['/foo/bar./tee./', '/.////././//./foo/./././/./bar./tee././/././', false],
- ['/foo/.bar.', '/.////././//./foo/./././/./.bar./././/././'],
- ['/foo/.bar./', '/.////././//./foo/./././/./.bar./././././', false],
- ['/foo/.bar./tee./', '/.////././//./foo/./././/./.bar./tee././././', false],
-
- // Windows paths
- ['/', ''],
- ['/', '\\'],
- ['/', '\\', false],
- ['/', '\\\\'],
- ['/', '\\\\', false],
-
- ['/path', '\\path'],
- ['/path', '\\path', false],
- ['/path', '\\path\\'],
- ['/path/', '\\path\\', false],
-
- ['/foo/bar', '\\foo\\\\bar\\'],
- ['/foo/bar/', '\\foo\\\\bar\\', false],
- ['/foo/bar', '\\foo\\\\\\\\bar'],
- ['/foo/bar', '\\foo\\\\\\\\\\bar'],
- ['/foo/bar', '\\foo\\bar\\.'],
- ['/foo/bar', '\\foo\\bar\\.\\'],
- ['/foo/bar/', '\\foo\\bar\\.\\', false],
- ['/foo/bar', '\\foo\\bar\\.\\.'],
- ['/foo/bar', '\\foo\\bar\\.\\.\\'],
- ['/foo/bar/', '\\foo\\bar\\.\\.\\', false],
- ['/foo/bar', '\\foo\\.\\bar\\'],
- ['/foo/bar/', '\\foo\\.\\bar\\', false],
- ['/foo/.bar', '\\foo\\.bar\\'],
- ['/foo/.bar/', '\\foo\\.bar\\', false],
- ['/foo/.bar/tee', '\\foo\\.bar\\tee'],
-
- // Absolute windows paths NOT marked as absolute
- ['/C:', 'C:\\'],
- ['/C:/', 'C:\\', false],
- ['/C:/tests', 'C:\\tests'],
- ['/C:/tests', 'C:\\tests', false],
- ['/C:/tests', 'C:\\tests\\'],
- ['/C:/tests/', 'C:\\tests\\', false],
- ['/C:/tests/bar', 'C:\\tests\\.\\.\\bar'],
- ['/C:/tests/bar/', 'C:\\tests\\.\\.\\bar\\.\\', false],
-
- // normalize does not resolve '..' (by design)
- ['/foo/..', '/foo/../'],
- ['/foo/../bar', '/foo/../bar/.'],
- ['/foo/..', '\\foo\\..\\'],
- ['/foo/../bar', '\\foo\\..\\bar'],
- ];
- }
-
- /**
- * @dataProvider normalizePathData
- */
- public function testNormalizePath($expected, $path, $stripTrailingSlash = true) {
- $this->assertEquals($expected, \OC\Files\Filesystem::normalizePath($path, $stripTrailingSlash));
- }
-
- public function normalizePathKeepUnicodeData() {
- $nfdName = 'ümlaut';
- $nfcName = 'ümlaut';
- return [
- ['/' . $nfcName, $nfcName, true],
- ['/' . $nfcName, $nfcName, false],
- ['/' . $nfdName, $nfdName, true],
- ['/' . $nfcName, $nfdName, false],
- ];
- }
-
- /**
- * @dataProvider normalizePathKeepUnicodeData
- */
- public function testNormalizePathKeepUnicode($expected, $path, $keepUnicode = false) {
- $this->assertEquals($expected, \OC\Files\Filesystem::normalizePath($path, true, false, $keepUnicode));
- }
-
- public function testNormalizePathKeepUnicodeCache() {
- $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));
- }
-
- public function isValidPathData() {
- return [
- ['/', true],
- ['/path', true],
- ['/foo/bar', true],
- ['/foo//bar/', true],
- ['/foo////bar', true],
- ['/foo//\///bar', true],
- ['/foo/bar/.', true],
- ['/foo/bar/./', true],
- ['/foo/bar/./.', true],
- ['/foo/bar/././', true],
- ['/foo/bar/././..bar', true],
- ['/foo/bar/././..bar/a', true],
- ['/foo/bar/././..', false],
- ['/foo/bar/././../', false],
- ['/foo/bar/.././', false],
- ['/foo/bar/../../', false],
- ['/foo/bar/../..\\', false],
- ['..', false],
- ['../', false],
- ['../foo/bar', false],
- ['..\foo/bar', false],
- ];
- }
-
- /**
- * @dataProvider isValidPathData
- */
- public function testIsValidPath($path, $expected) {
- $this->assertSame($expected, \OC\Files\Filesystem::isValidPath($path));
- }
-
- public function isFileBlacklistedData() {
- return [
- ['/etc/foo/bar/foo.txt', false],
- ['\etc\foo/bar\foo.txt', false],
- ['.htaccess', true],
- ['.htaccess/', true],
- ['.htaccess\\', true],
- ['/etc/foo\bar/.htaccess\\', true],
- ['/etc/foo\bar/.htaccess/', true],
- ['/etc/foo\bar/.htaccess/foo', false],
- ['//foo//bar/\.htaccess/', true],
- ['\foo\bar\.HTAccess', true],
- ];
- }
-
- /**
- * @dataProvider isFileBlacklistedData
- */
- public function testIsFileBlacklisted($path, $expected) {
- $this->assertSame($expected, \OC\Files\Filesystem::isFileBlacklisted($path));
- }
-
- public function testNormalizePathUTF8() {
- if (!class_exists('Patchwork\PHP\Shim\Normalizer')) {
- $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"));
- }
-
- public function testHooks() {
- if (\OC\Files\Filesystem::getView()) {
- $user = \OC_User::getUser();
- } else {
- $user = self::TEST_FILESYSTEM_USER1;
- $backend = new \Test\Util\User\Dummy();
- \OC_User::useBackend($backend);
- $backend->createUser($user, $user);
- $userObj = \OC::$server->getUserManager()->get($user);
- \OC::$server->getUserSession()->setUser($userObj);
- \OC\Files\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::class, [], '/');
-
- $rootView = new \OC\Files\View('');
- $rootView->mkdir('/' . $user);
- $rootView->mkdir('/' . $user . '/files');
-
- // \OC\Files\Filesystem::file_put_contents('/foo', 'foo');
- \OC\Files\Filesystem::mkdir('/bar');
- // \OC\Files\Filesystem::file_put_contents('/bar//foo', 'foo');
-
- $tmpFile = \OC::$server->getTempManager()->getTemporaryFile();
- file_put_contents($tmpFile, 'foo');
- $fh = fopen($tmpFile, 'r');
- // \OC\Files\Filesystem::file_put_contents('/bar//foo', $fh);
- }
-
- /**
- * Tests that an exception is thrown when passed user does not exist.
- *
- */
- public function testLocalMountWhenUserDoesNotExist() {
- $this->expectException(\OC\User\NoUserException::class);
-
- $userId = $this->getUniqueID('user_');
-
- \OC\Files\Filesystem::initMountPoints($userId);
- }
-
-
- public function testNullUserThrows() {
- $this->expectException(\OC\User\NoUserException::class);
-
- \OC\Files\Filesystem::initMountPoints(null);
- }
-
- public function testNullUserThrowsTwice() {
- $thrown = 0;
- try {
- \OC\Files\Filesystem::initMountPoints(null);
- } catch (NoUserException $e) {
- $thrown++;
- }
- try {
- \OC\Files\Filesystem::initMountPoints(null);
- } catch (NoUserException $e) {
- $thrown++;
- }
- $this->assertEquals(2, $thrown);
- }
-
- /**
- * Tests that an exception is thrown when passed user does not exist.
- */
- public function testLocalMountWhenUserDoesNotExistTwice() {
- $thrown = 0;
- $userId = $this->getUniqueID('user_');
-
- try {
- \OC\Files\Filesystem::initMountPoints($userId);
- } catch (NoUserException $e) {
- $thrown++;
- }
-
- try {
- \OC\Files\Filesystem::initMountPoints($userId);
- } catch (NoUserException $e) {
- $thrown++;
- }
-
- $this->assertEquals(2, $thrown);
- }
-
- /**
- * Tests that the home storage is used for the user's mount point
- */
- public function testHomeMount() {
- $userId = $this->getUniqueID('user_');
-
- \OC::$server->getUserManager()->createUser($userId, $userId);
-
- \OC\Files\Filesystem::initMountPoints($userId);
-
- $homeMount = \OC\Files\Filesystem::getStorage('/' . $userId . '/');
-
- $this->assertTrue($homeMount->instanceOfStorage(\OCP\Files\IHomeStorage::class));
- if ($homeMount->instanceOfStorage(\OC\Files\ObjectStore\HomeObjectStoreStorage::class)) {
- $this->assertEquals('object::user:' . $userId, $homeMount->getId());
- } elseif ($homeMount->instanceOfStorage(\OC\Files\Storage\Home::class)) {
- $this->assertEquals('home::' . $userId, $homeMount->getId());
- }
-
- $user = \OC::$server->getUserManager()->get($userId);
- if ($user !== null) {
- $user->delete();
- }
- }
-
- 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
- }
-
- /**
- * Test that the default cache dir is part of the user's home
- */
- public function testMountDefaultCacheDir() {
- $userId = $this->getUniqueID('user_');
- $config = \OC::$server->getConfig();
- $oldCachePath = $config->getSystemValueString('cache_path', '');
- // no cache path configured
- $config->setSystemValue('cache_path', '');
-
- \OC::$server->getUserManager()->createUser($userId, $userId);
- \OC\Files\Filesystem::initMountPoints($userId);
-
- $this->assertEquals(
- '/' . $userId . '/',
- \OC\Files\Filesystem::getMountPoint('/' . $userId . '/cache')
- );
- [$storage, $internalPath] = \OC\Files\Filesystem::resolvePath('/' . $userId . '/cache');
- $this->assertTrue($storage->instanceOfStorage(\OCP\Files\IHomeStorage::class));
- $this->assertEquals('cache', $internalPath);
- $user = \OC::$server->getUserManager()->get($userId);
- if ($user !== null) {
- $user->delete();
- }
-
- $config->setSystemValue('cache_path', $oldCachePath);
- }
-
- /**
- * Test that an external cache is mounted into
- * the user's home
- */
- public function testMountExternalCacheDir() {
- $userId = $this->getUniqueID('user_');
-
- $config = \OC::$server->getConfig();
- $oldCachePath = $config->getSystemValueString('cache_path', '');
- // set cache path to temp dir
- $cachePath = \OC::$server->getTempManager()->getTemporaryFolder() . '/extcache';
- $config->setSystemValue('cache_path', $cachePath);
-
- \OC::$server->getUserManager()->createUser($userId, $userId);
- \OC\Files\Filesystem::initMountPoints($userId);
-
- $this->assertEquals(
- '/' . $userId . '/cache/',
- \OC\Files\Filesystem::getMountPoint('/' . $userId . '/cache')
- );
- [$storage, $internalPath] = \OC\Files\Filesystem::resolvePath('/' . $userId . '/cache');
- $this->assertTrue($storage->instanceOfStorage(\OC\Files\Storage\Local::class));
- $this->assertEquals('', $internalPath);
- $user = \OC::$server->getUserManager()->get($userId);
- if ($user !== null) {
- $user->delete();
- }
-
- $config->setSystemValue('cache_path', $oldCachePath);
- }
-
- public function testRegisterMountProviderAfterSetup() {
- \OC\Files\Filesystem::initMountPoints(self::TEST_FILESYSTEM_USER2);
- $this->assertEquals('/', \OC\Files\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'));
- }
-}
+<?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\Files;
+
+use OC\Files\Mount\MountPoint;
+use OC\Files\Storage\Temporary;
+use OC\User\NoUserException;
+use OCP\Files\Config\IMountProvider;
+use OCP\Files\Storage\IStorageFactory;
+use OCP\IUser;
+
+class DummyMountProvider implements IMountProvider {
+ private $mounts = [];
+
+ /**
+ * @param array $mounts
+ */
+ public function __construct(array $mounts) {
+ $this->mounts = $mounts;
+ }
+
+ /**
+ * Get the pre-registered mount points
+ *
+ * @param IUser $user
+ * @param IStorageFactory $loader
+ * @return \OCP\Files\Mount\IMountPoint[]
+ */
+ public function getMountsForUser(IUser $user, IStorageFactory $loader) {
+ return isset($this->mounts[$user->getUID()]) ? $this->mounts[$user->getUID()] : [];
+ }
+}
+
+/**
+ * Class FilesystemTest
+ *
+ * @group DB
+ *
+ * @package Test\Files
+ */
+class FilesystemTest extends \Test\TestCase {
+ public const TEST_FILESYSTEM_USER1 = 'test-filesystem-user1';
+ public const TEST_FILESYSTEM_USER2 = 'test-filesystem-user1';
+
+ /**
+ * @var array tmpDirs
+ */
+ private $tmpDirs = [];
+
+ /**
+ * @return array
+ */
+ private function getStorageData() {
+ $dir = \OC::$server->getTempManager()->getTemporaryFolder();
+ $this->tmpDirs[] = $dir;
+ return ['datadir' => $dir];
+ }
+
+ protected function setUp(): void {
+ parent::setUp();
+ $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);
+ $this->loginAsUser();
+ }
+
+ protected function tearDown(): void {
+ foreach ($this->tmpDirs as $dir) {
+ \OC_Helper::rmdirr($dir);
+ }
+
+ $this->logout();
+ $this->invokePrivate(\OC\Files\Filesystem::class, 'normalizedPathCache', [null]);
+ parent::tearDown();
+ }
+
+ public function testMount(): void {
+ \OC\Files\Filesystem::mount(\OC\Files\Storage\Local::class, self::getStorageData(), '/');
+ $this->assertEquals('/', \OC\Files\Filesystem::getMountPoint('/'));
+ $this->assertEquals('/', \OC\Files\Filesystem::getMountPoint('/some/folder'));
+ [, $internalPath] = \OC\Files\Filesystem::resolvePath('/');
+ $this->assertEquals('', $internalPath);
+ [, $internalPath] = \OC\Files\Filesystem::resolvePath('/some/folder');
+ $this->assertEquals('some/folder', $internalPath);
+
+ \OC\Files\Filesystem::mount(\OC\Files\Storage\Local::class, 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');
+ $this->assertEquals('folder', $internalPath);
+ }
+
+ public function normalizePathData() {
+ return [
+ ['/', ''],
+ ['/', '/'],
+ ['/', '//'],
+ ['/', '/', false],
+ ['/', '//', false],
+
+ ['/path', '/path/'],
+ ['/path/', '/path/', false],
+ ['/path', 'path'],
+
+ ['/foo/bar', '/foo//bar/'],
+ ['/foo/bar/', '/foo//bar/', false],
+ ['/foo/bar', '/foo////bar'],
+ ['/foo/bar', '/foo/////bar'],
+ ['/foo/bar', '/foo/bar/.'],
+ ['/foo/bar', '/foo/bar/./'],
+ ['/foo/bar/', '/foo/bar/./', false],
+ ['/foo/bar', '/foo/bar/./.'],
+ ['/foo/bar', '/foo/bar/././'],
+ ['/foo/bar/', '/foo/bar/././', false],
+ ['/foo/bar', '/foo/./bar/'],
+ ['/foo/bar/', '/foo/./bar/', false],
+ ['/foo/.bar', '/foo/.bar/'],
+ ['/foo/.bar/', '/foo/.bar/', false],
+ ['/foo/.bar/tee', '/foo/.bar/tee'],
+ ['/foo/bar.', '/foo/bar./'],
+ ['/foo/bar./', '/foo/bar./', false],
+ ['/foo/bar./tee', '/foo/bar./tee'],
+ ['/foo/.bar.', '/foo/.bar./'],
+ ['/foo/.bar./', '/foo/.bar./', false],
+ ['/foo/.bar./tee', '/foo/.bar./tee'],
+
+ ['/foo/bar', '/.////././//./foo/.///././//./bar/././/./.'],
+ ['/foo/bar/', '/.////././//./foo/.///././//./bar/./././.', false],
+ ['/foo/bar', '/.////././//./foo/.///././//./bar/././/././'],
+ ['/foo/bar/', '/.////././//./foo/.///././//./bar/././/././', false],
+ ['/foo/.bar', '/.////././//./foo/./././/./.bar/././/././'],
+ ['/foo/.bar/', '/.////././//./foo/./././/./.bar/././/././', false],
+ ['/foo/.bar/tee./', '/.////././//./foo/./././/./.bar/tee././/././', false],
+ ['/foo/bar.', '/.////././//./foo/./././/./bar./././/././'],
+ ['/foo/bar./', '/.////././//./foo/./././/./bar./././/././', false],
+ ['/foo/bar./tee./', '/.////././//./foo/./././/./bar./tee././/././', false],
+ ['/foo/.bar.', '/.////././//./foo/./././/./.bar./././/././'],
+ ['/foo/.bar./', '/.////././//./foo/./././/./.bar./././././', false],
+ ['/foo/.bar./tee./', '/.////././//./foo/./././/./.bar./tee././././', false],
+
+ // Windows paths
+ ['/', ''],
+ ['/', '\\'],
+ ['/', '\\', false],
+ ['/', '\\\\'],
+ ['/', '\\\\', false],
+
+ ['/path', '\\path'],
+ ['/path', '\\path', false],
+ ['/path', '\\path\\'],
+ ['/path/', '\\path\\', false],
+
+ ['/foo/bar', '\\foo\\\\bar\\'],
+ ['/foo/bar/', '\\foo\\\\bar\\', false],
+ ['/foo/bar', '\\foo\\\\\\\\bar'],
+ ['/foo/bar', '\\foo\\\\\\\\\\bar'],
+ ['/foo/bar', '\\foo\\bar\\.'],
+ ['/foo/bar', '\\foo\\bar\\.\\'],
+ ['/foo/bar/', '\\foo\\bar\\.\\', false],
+ ['/foo/bar', '\\foo\\bar\\.\\.'],
+ ['/foo/bar', '\\foo\\bar\\.\\.\\'],
+ ['/foo/bar/', '\\foo\\bar\\.\\.\\', false],
+ ['/foo/bar', '\\foo\\.\\bar\\'],
+ ['/foo/bar/', '\\foo\\.\\bar\\', false],
+ ['/foo/.bar', '\\foo\\.bar\\'],
+ ['/foo/.bar/', '\\foo\\.bar\\', false],
+ ['/foo/.bar/tee', '\\foo\\.bar\\tee'],
+
+ // Absolute windows paths NOT marked as absolute
+ ['/C:', 'C:\\'],
+ ['/C:/', 'C:\\', false],
+ ['/C:/tests', 'C:\\tests'],
+ ['/C:/tests', 'C:\\tests', false],
+ ['/C:/tests', 'C:\\tests\\'],
+ ['/C:/tests/', 'C:\\tests\\', false],
+ ['/C:/tests/bar', 'C:\\tests\\.\\.\\bar'],
+ ['/C:/tests/bar/', 'C:\\tests\\.\\.\\bar\\.\\', false],
+
+ // normalize does not resolve '..' (by design)
+ ['/foo/..', '/foo/../'],
+ ['/foo/../bar', '/foo/../bar/.'],
+ ['/foo/..', '\\foo\\..\\'],
+ ['/foo/../bar', '\\foo\\..\\bar'],
+ ];
+ }
+
+ /**
+ * @dataProvider normalizePathData
+ */
+ public function testNormalizePath($expected, $path, $stripTrailingSlash = true): void {
+ $this->assertEquals($expected, \OC\Files\Filesystem::normalizePath($path, $stripTrailingSlash));
+ }
+
+ public function normalizePathKeepUnicodeData() {
+ $nfdName = 'ümlaut';
+ $nfcName = 'ümlaut';
+ return [
+ ['/' . $nfcName, $nfcName, true],
+ ['/' . $nfcName, $nfcName, false],
+ ['/' . $nfdName, $nfdName, true],
+ ['/' . $nfcName, $nfdName, false],
+ ];
+ }
+
+ /**
+ * @dataProvider normalizePathKeepUnicodeData
+ */
+ public function testNormalizePathKeepUnicode($expected, $path, $keepUnicode = false): void {
+ $this->assertEquals($expected, \OC\Files\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));
+ }
+
+ public function isValidPathData() {
+ return [
+ ['/', true],
+ ['/path', true],
+ ['/foo/bar', true],
+ ['/foo//bar/', true],
+ ['/foo////bar', true],
+ ['/foo//\///bar', true],
+ ['/foo/bar/.', true],
+ ['/foo/bar/./', true],
+ ['/foo/bar/./.', true],
+ ['/foo/bar/././', true],
+ ['/foo/bar/././..bar', true],
+ ['/foo/bar/././..bar/a', true],
+ ['/foo/bar/././..', false],
+ ['/foo/bar/././../', false],
+ ['/foo/bar/.././', false],
+ ['/foo/bar/../../', false],
+ ['/foo/bar/../..\\', false],
+ ['..', false],
+ ['../', false],
+ ['../foo/bar', false],
+ ['..\foo/bar', false],
+ ];
+ }
+
+ /**
+ * @dataProvider isValidPathData
+ */
+ public function testIsValidPath($path, $expected): void {
+ $this->assertSame($expected, \OC\Files\Filesystem::isValidPath($path));
+ }
+
+ public function isFileBlacklistedData() {
+ return [
+ ['/etc/foo/bar/foo.txt', false],
+ ['\etc\foo/bar\foo.txt', false],
+ ['.htaccess', true],
+ ['.htaccess/', true],
+ ['.htaccess\\', true],
+ ['/etc/foo\bar/.htaccess\\', true],
+ ['/etc/foo\bar/.htaccess/', true],
+ ['/etc/foo\bar/.htaccess/foo', false],
+ ['//foo//bar/\.htaccess/', true],
+ ['\foo\bar\.HTAccess', true],
+ ];
+ }
+
+ /**
+ * @dataProvider isFileBlacklistedData
+ */
+ public function testIsFileBlacklisted($path, $expected): void {
+ $this->assertSame($expected, \OC\Files\Filesystem::isFileBlacklisted($path));
+ }
+
+ public function testNormalizePathUTF8(): void {
+ if (!class_exists('Patchwork\PHP\Shim\Normalizer')) {
+ $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"));
+ }
+
+ public function testHooks(): void {
+ if (\OC\Files\Filesystem::getView()) {
+ $user = \OC_User::getUser();
+ } else {
+ $user = self::TEST_FILESYSTEM_USER1;
+ $backend = new \Test\Util\User\Dummy();
+ \OC_User::useBackend($backend);
+ $backend->createUser($user, $user);
+ $userObj = \OC::$server->getUserManager()->get($user);
+ \OC::$server->getUserSession()->setUser($userObj);
+ \OC\Files\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::class, [], '/');
+
+ $rootView = new \OC\Files\View('');
+ $rootView->mkdir('/' . $user);
+ $rootView->mkdir('/' . $user . '/files');
+
+ // \OC\Files\Filesystem::file_put_contents('/foo', 'foo');
+ \OC\Files\Filesystem::mkdir('/bar');
+ // \OC\Files\Filesystem::file_put_contents('/bar//foo', 'foo');
+
+ $tmpFile = \OC::$server->getTempManager()->getTemporaryFile();
+ file_put_contents($tmpFile, 'foo');
+ $fh = fopen($tmpFile, 'r');
+ // \OC\Files\Filesystem::file_put_contents('/bar//foo', $fh);
+ }
+
+ /**
+ * Tests that an exception is thrown when passed user does not exist.
+ *
+ */
+ public function testLocalMountWhenUserDoesNotExist(): void {
+ $this->expectException(\OC\User\NoUserException::class);
+
+ $userId = $this->getUniqueID('user_');
+
+ \OC\Files\Filesystem::initMountPoints($userId);
+ }
+
+
+ public function testNullUserThrows(): void {
+ $this->expectException(\OC\User\NoUserException::class);
+
+ \OC\Files\Filesystem::initMountPoints(null);
+ }
+
+ public function testNullUserThrowsTwice(): void {
+ $thrown = 0;
+ try {
+ \OC\Files\Filesystem::initMountPoints(null);
+ } catch (NoUserException $e) {
+ $thrown++;
+ }
+ try {
+ \OC\Files\Filesystem::initMountPoints(null);
+ } catch (NoUserException $e) {
+ $thrown++;
+ }
+ $this->assertEquals(2, $thrown);
+ }
+
+ /**
+ * Tests that an exception is thrown when passed user does not exist.
+ */
+ public function testLocalMountWhenUserDoesNotExistTwice(): void {
+ $thrown = 0;
+ $userId = $this->getUniqueID('user_');
+
+ try {
+ \OC\Files\Filesystem::initMountPoints($userId);
+ } catch (NoUserException $e) {
+ $thrown++;
+ }
+
+ try {
+ \OC\Files\Filesystem::initMountPoints($userId);
+ } catch (NoUserException $e) {
+ $thrown++;
+ }
+
+ $this->assertEquals(2, $thrown);
+ }
+
+ /**
+ * Tests that the home storage is used for the user's mount point
+ */
+ public function testHomeMount(): void {
+ $userId = $this->getUniqueID('user_');
+
+ \OC::$server->getUserManager()->createUser($userId, $userId);
+
+ \OC\Files\Filesystem::initMountPoints($userId);
+
+ $homeMount = \OC\Files\Filesystem::getStorage('/' . $userId . '/');
+
+ $this->assertTrue($homeMount->instanceOfStorage(\OCP\Files\IHomeStorage::class));
+ if ($homeMount->instanceOfStorage(\OC\Files\ObjectStore\HomeObjectStoreStorage::class)) {
+ $this->assertEquals('object::user:' . $userId, $homeMount->getId());
+ } elseif ($homeMount->instanceOfStorage(\OC\Files\Storage\Home::class)) {
+ $this->assertEquals('home::' . $userId, $homeMount->getId());
+ }
+
+ $user = \OC::$server->getUserManager()->get($userId);
+ if ($user !== null) {
+ $user->delete();
+ }
+ }
+
+ 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
+ }
+
+ /**
+ * Test that the default cache dir is part of the user's home
+ */
+ public function testMountDefaultCacheDir(): void {
+ $userId = $this->getUniqueID('user_');
+ $config = \OC::$server->getConfig();
+ $oldCachePath = $config->getSystemValueString('cache_path', '');
+ // no cache path configured
+ $config->setSystemValue('cache_path', '');
+
+ \OC::$server->getUserManager()->createUser($userId, $userId);
+ \OC\Files\Filesystem::initMountPoints($userId);
+
+ $this->assertEquals(
+ '/' . $userId . '/',
+ \OC\Files\Filesystem::getMountPoint('/' . $userId . '/cache')
+ );
+ [$storage, $internalPath] = \OC\Files\Filesystem::resolvePath('/' . $userId . '/cache');
+ $this->assertTrue($storage->instanceOfStorage(\OCP\Files\IHomeStorage::class));
+ $this->assertEquals('cache', $internalPath);
+ $user = \OC::$server->getUserManager()->get($userId);
+ if ($user !== null) {
+ $user->delete();
+ }
+
+ $config->setSystemValue('cache_path', $oldCachePath);
+ }
+
+ /**
+ * Test that an external cache is mounted into
+ * the user's home
+ */
+ public function testMountExternalCacheDir(): void {
+ $userId = $this->getUniqueID('user_');
+
+ $config = \OC::$server->getConfig();
+ $oldCachePath = $config->getSystemValueString('cache_path', '');
+ // set cache path to temp dir
+ $cachePath = \OC::$server->getTempManager()->getTemporaryFolder() . '/extcache';
+ $config->setSystemValue('cache_path', $cachePath);
+
+ \OC::$server->getUserManager()->createUser($userId, $userId);
+ \OC\Files\Filesystem::initMountPoints($userId);
+
+ $this->assertEquals(
+ '/' . $userId . '/cache/',
+ \OC\Files\Filesystem::getMountPoint('/' . $userId . '/cache')
+ );
+ [$storage, $internalPath] = \OC\Files\Filesystem::resolvePath('/' . $userId . '/cache');
+ $this->assertTrue($storage->instanceOfStorage(\OC\Files\Storage\Local::class));
+ $this->assertEquals('', $internalPath);
+ $user = \OC::$server->getUserManager()->get($userId);
+ if ($user !== null) {
+ $user->delete();
+ }
+
+ $config->setSystemValue('cache_path', $oldCachePath);
+ }
+
+ public function testRegisterMountProviderAfterSetup(): void {
+ \OC\Files\Filesystem::initMountPoints(self::TEST_FILESYSTEM_USER2);
+ $this->assertEquals('/', \OC\Files\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'));
+ }
+}
diff --git a/tests/lib/Files/Mount/ManagerTest.php b/tests/lib/Files/Mount/ManagerTest.php
index f8adb2bf1cf..fe166988687 100644
--- a/tests/lib/Files/Mount/ManagerTest.php
+++ b/tests/lib/Files/Mount/ManagerTest.php
@@ -27,7 +27,7 @@ class ManagerTest extends \Test\TestCase {
$this->manager = new \OC\Files\Mount\Manager($this->createMock(SetupManagerFactory::class));
}
- public function testFind() {
+ public function testFind(): void {
$rootMount = new \OC\Files\Mount\MountPoint(new Temporary([]), '/');
$this->manager->addMount($rootMount);
$this->assertEquals($rootMount, $this->manager->find('/'));
@@ -52,7 +52,7 @@ class ManagerTest extends \Test\TestCase {
$this->assertEquals([$mount1, $mount3], $this->manager->findByStorageId($id));
}
- public function testLong() {
+ public function testLong(): void {
$storage = new LongId([]);
$mount = new \OC\Files\Mount\MountPoint($storage, '/foo');
$this->manager->addMount($mount);
diff --git a/tests/lib/Files/Mount/MountPointTest.php b/tests/lib/Files/Mount/MountPointTest.php
index b5ba7e01558..cd088979ef8 100644
--- a/tests/lib/Files/Mount/MountPointTest.php
+++ b/tests/lib/Files/Mount/MountPointTest.php
@@ -14,7 +14,7 @@ class DummyStorage {
}
class MountPointTest extends \Test\TestCase {
- public function testGetStorage() {
+ public function testGetStorage(): void {
$storage = $this->createMock(Storage::class);
$storage->expects($this->once())
->method('getId')
@@ -41,7 +41,7 @@ class MountPointTest extends \Test\TestCase {
$this->assertEquals('/another/', $mountPoint->getMountPoint());
}
- public function testInvalidStorage() {
+ public function testInvalidStorage(): void {
$loader = $this->createMock(StorageFactory::class);
$loader->expects($this->once())
->method('wrap')
diff --git a/tests/lib/Files/Mount/MountTest.php b/tests/lib/Files/Mount/MountTest.php
index e33fb9505a2..8b6cd25aaaa 100644
--- a/tests/lib/Files/Mount/MountTest.php
+++ b/tests/lib/Files/Mount/MountTest.php
@@ -1,44 +1,44 @@
-<?php
-/**
- * SPDX-FileCopyrightText: 2020-2024 Nextcloud GmbH and Nextcloud contributors
- * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
- * SPDX-License-Identifier: AGPL-3.0-or-later
- */
-
-namespace Test\Files\Mount;
-
-use OC\Files\Storage\StorageFactory;
-use OC\Files\Storage\Wrapper\Wrapper;
-
-class MountTest extends \Test\TestCase {
- public function testFromStorageObject() {
- $storage = $this->getMockBuilder(\OC\Files\Storage\Temporary::class)
- ->disableOriginalConstructor()
- ->getMock();
- $mount = new \OC\Files\Mount\MountPoint($storage, '/foo');
- $this->assertInstanceOf(\OC\Files\Storage\Temporary::class, $mount->getStorage());
- }
-
- public function testFromStorageClassname() {
- $mount = new \OC\Files\Mount\MountPoint(\OC\Files\Storage\Temporary::class, '/foo');
- $this->assertInstanceOf(\OC\Files\Storage\Temporary::class, $mount->getStorage());
- }
-
- public function testWrapper() {
- $test = $this;
- $wrapper = function ($mountPoint, $storage) use (&$test) {
- $test->assertEquals('/foo/', $mountPoint);
- $test->assertInstanceOf(\OC\Files\Storage\Storage::class, $storage);
- return new Wrapper(['storage' => $storage]);
- };
-
- $loader = new StorageFactory();
- $loader->addStorageWrapper('test_wrapper', $wrapper);
-
- $storage = $this->getMockBuilder(\OC\Files\Storage\Temporary::class)
- ->disableOriginalConstructor()
- ->getMock();
- $mount = new \OC\Files\Mount\MountPoint($storage, '/foo', [], $loader);
- $this->assertInstanceOf(\OC\Files\Storage\Wrapper\Wrapper::class, $mount->getStorage());
- }
-}
+<?php
+/**
+ * SPDX-FileCopyrightText: 2020-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+
+namespace Test\Files\Mount;
+
+use OC\Files\Storage\StorageFactory;
+use OC\Files\Storage\Wrapper\Wrapper;
+
+class MountTest extends \Test\TestCase {
+ public function testFromStorageObject(): void {
+ $storage = $this->getMockBuilder(\OC\Files\Storage\Temporary::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $mount = new \OC\Files\Mount\MountPoint($storage, '/foo');
+ $this->assertInstanceOf(\OC\Files\Storage\Temporary::class, $mount->getStorage());
+ }
+
+ public function testFromStorageClassname(): void {
+ $mount = new \OC\Files\Mount\MountPoint(\OC\Files\Storage\Temporary::class, '/foo');
+ $this->assertInstanceOf(\OC\Files\Storage\Temporary::class, $mount->getStorage());
+ }
+
+ public function testWrapper(): void {
+ $test = $this;
+ $wrapper = function ($mountPoint, $storage) use (&$test) {
+ $test->assertEquals('/foo/', $mountPoint);
+ $test->assertInstanceOf(\OC\Files\Storage\Storage::class, $storage);
+ return new Wrapper(['storage' => $storage]);
+ };
+
+ $loader = new StorageFactory();
+ $loader->addStorageWrapper('test_wrapper', $wrapper);
+
+ $storage = $this->getMockBuilder(\OC\Files\Storage\Temporary::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $mount = new \OC\Files\Mount\MountPoint($storage, '/foo', [], $loader);
+ $this->assertInstanceOf(\OC\Files\Storage\Wrapper\Wrapper::class, $mount->getStorage());
+ }
+}
diff --git a/tests/lib/Files/Mount/ObjectHomeMountProviderTest.php b/tests/lib/Files/Mount/ObjectHomeMountProviderTest.php
index d77809b53e4..de960ee4cbf 100644
--- a/tests/lib/Files/Mount/ObjectHomeMountProviderTest.php
+++ b/tests/lib/Files/Mount/ObjectHomeMountProviderTest.php
@@ -34,7 +34,7 @@ class ObjectHomeMountProviderTest extends \Test\TestCase {
$this->provider = new ObjectHomeMountProvider($this->config);
}
- public function testSingleBucket() {
+ public function testSingleBucket(): void {
$this->config->expects($this->once())
->method('getSystemValue')
->with($this->equalTo('objectstore'), '')
@@ -56,7 +56,7 @@ class ObjectHomeMountProviderTest extends \Test\TestCase {
$this->assertInstanceOf(\Test\Files\Mount\FakeObjectStore::class, $config['arguments']['objectstore']);
}
- public function testMultiBucket() {
+ public function testMultiBucket(): void {
$this->config->expects($this->exactly(2))
->method('getSystemValue')
->with($this->equalTo('objectstore_multibucket'), '')
@@ -100,7 +100,7 @@ class ObjectHomeMountProviderTest extends \Test\TestCase {
$this->assertEquals('49', $config['arguments']['bucket']);
}
- public function testMultiBucketWithPrefix() {
+ public function testMultiBucketWithPrefix(): void {
$this->config->expects($this->exactly(2))
->method('getSystemValue')
->with('objectstore_multibucket')
@@ -147,7 +147,7 @@ class ObjectHomeMountProviderTest extends \Test\TestCase {
$this->assertEquals('myBucketPrefix49', $config['arguments']['bucket']);
}
- public function testMultiBucketBucketAlreadySet() {
+ public function testMultiBucketBucketAlreadySet(): void {
$this->config->expects($this->once())
->method('getSystemValue')
->with('objectstore_multibucket')
@@ -187,7 +187,7 @@ class ObjectHomeMountProviderTest extends \Test\TestCase {
$this->assertEquals('awesomeBucket1', $config['arguments']['bucket']);
}
- public function testMultiBucketConfigFirst() {
+ public function testMultiBucketConfigFirst(): void {
$this->config->expects($this->exactly(2))
->method('getSystemValue')
->with('objectstore_multibucket')
@@ -203,7 +203,7 @@ class ObjectHomeMountProviderTest extends \Test\TestCase {
$this->assertInstanceOf(\OC\Files\Mount\MountPoint::class, $mount);
}
- public function testMultiBucketConfigFirstFallBackSingle() {
+ public function testMultiBucketConfigFirstFallBackSingle(): void {
$this->config->expects($this->exactly(2))
->method('getSystemValue')
->withConsecutive(
@@ -224,7 +224,7 @@ class ObjectHomeMountProviderTest extends \Test\TestCase {
$this->assertInstanceOf(\OC\Files\Mount\MountPoint::class, $mount);
}
- public function testNoObjectStore() {
+ public function testNoObjectStore(): void {
$this->config->expects($this->exactly(2))
->method('getSystemValue')
->willReturn('');
diff --git a/tests/lib/Files/Mount/ObjectStorePreviewCacheMountProviderTest.php b/tests/lib/Files/Mount/ObjectStorePreviewCacheMountProviderTest.php
index b22224aa7db..9060bf0d5f5 100644
--- a/tests/lib/Files/Mount/ObjectStorePreviewCacheMountProviderTest.php
+++ b/tests/lib/Files/Mount/ObjectStorePreviewCacheMountProviderTest.php
@@ -43,7 +43,7 @@ class ObjectStorePreviewCacheMountProviderTest extends \Test\TestCase {
$this->provider = new ObjectStorePreviewCacheMountProvider($this->logger, $this->config);
}
- public function testNoMultibucketObjectStorage() {
+ public function testNoMultibucketObjectStorage(): void {
$this->config->expects($this->once())
->method('getSystemValue')
->with('objectstore_multibucket')
@@ -52,7 +52,7 @@ class ObjectStorePreviewCacheMountProviderTest extends \Test\TestCase {
$this->assertEquals([], $this->provider->getRootMounts($this->loader));
}
- public function testMultibucketObjectStorage() {
+ public function testMultibucketObjectStorage(): void {
$objectstoreConfig = [
'class' => S3::class,
'arguments' => [
diff --git a/tests/lib/Files/Mount/RootMountProviderTest.php b/tests/lib/Files/Mount/RootMountProviderTest.php
index 5a33ddf479e..ebf1e56c622 100644
--- a/tests/lib/Files/Mount/RootMountProviderTest.php
+++ b/tests/lib/Files/Mount/RootMountProviderTest.php
@@ -44,7 +44,7 @@ class RootMountProviderTest extends TestCase {
return $provider;
}
- public function testLocal() {
+ public function testLocal(): void {
$provider = $this->getProvider([
'datadirectory' => '/data',
]);
@@ -58,7 +58,7 @@ class RootMountProviderTest extends TestCase {
$this->assertEquals('/data/', $storage->getSourcePath(''));
}
- public function testObjectStore() {
+ public function testObjectStore(): void {
$provider = $this->getProvider([
'objectstore' => [
'class' => \OC\Files\ObjectStore\S3::class,
@@ -91,7 +91,7 @@ class RootMountProviderTest extends TestCase {
$this->assertEquals('nextcloud', $objectStore->getBucket());
}
- public function testObjectStoreMultiBucket() {
+ public function testObjectStoreMultiBucket(): void {
$provider = $this->getProvider([
'objectstore_multibucket' => [
'class' => \OC\Files\ObjectStore\S3::class,
diff --git a/tests/lib/Files/Node/FileTest.php b/tests/lib/Files/Node/FileTest.php
index a5d455b33b7..4e0e147c062 100644
--- a/tests/lib/Files/Node/FileTest.php
+++ b/tests/lib/Files/Node/FileTest.php
@@ -35,7 +35,7 @@ class FileTest extends NodeTest {
return 'unlink';
}
- public function testGetContent() {
+ public function testGetContent(): void {
/** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject $root */
$root = $this->getMockBuilder(\OC\Files\Node\Root::class)
->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
@@ -63,7 +63,7 @@ class FileTest extends NodeTest {
}
- public function testGetContentNotPermitted() {
+ public function testGetContentNotPermitted(): void {
$this->expectException(\OCP\Files\NotPermittedException::class);
/** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject $root */
@@ -84,7 +84,7 @@ class FileTest extends NodeTest {
$node->getContent();
}
- public function testPutContent() {
+ public function testPutContent(): void {
/** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject $root */
$root = $this->getMockBuilder(\OC\Files\Node\Root::class)
->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
@@ -109,7 +109,7 @@ class FileTest extends NodeTest {
}
- public function testPutContentNotPermitted() {
+ public function testPutContentNotPermitted(): void {
$this->expectException(\OCP\Files\NotPermittedException::class);
/** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject $root */
@@ -126,7 +126,7 @@ class FileTest extends NodeTest {
$node->putContent('bar');
}
- public function testGetMimeType() {
+ public function testGetMimeType(): void {
/** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject $root */
$root = $this->getMockBuilder(\OC\Files\Node\Root::class)
->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
@@ -141,7 +141,7 @@ class FileTest extends NodeTest {
$this->assertEquals('text/plain', $node->getMimeType());
}
- public function testFOpenRead() {
+ public function testFOpenRead(): void {
$stream = fopen('php://memory', 'w+');
fwrite($stream, 'bar');
rewind($stream);
@@ -180,7 +180,7 @@ class FileTest extends NodeTest {
$this->assertEquals('bar', fread($fh, 3));
}
- public function testFOpenWrite() {
+ public function testFOpenWrite(): void {
$stream = fopen('php://memory', 'w+');
$root = new \OC\Files\Node\Root(
@@ -221,7 +221,7 @@ class FileTest extends NodeTest {
}
- public function testFOpenReadNotPermitted() {
+ public function testFOpenReadNotPermitted(): void {
$this->expectException(\OCP\Files\NotPermittedException::class);
$root = new \OC\Files\Node\Root(
@@ -248,7 +248,7 @@ class FileTest extends NodeTest {
}
- public function testFOpenReadWriteNoReadPermissions() {
+ public function testFOpenReadWriteNoReadPermissions(): void {
$this->expectException(\OCP\Files\NotPermittedException::class);
$root = new \OC\Files\Node\Root(
@@ -275,7 +275,7 @@ class FileTest extends NodeTest {
}
- public function testFOpenReadWriteNoWritePermissions() {
+ public function testFOpenReadWriteNoWritePermissions(): void {
$this->expectException(\OCP\Files\NotPermittedException::class);
$root = new \OC\Files\Node\Root(
diff --git a/tests/lib/Files/Node/FolderTest.php b/tests/lib/Files/Node/FolderTest.php
index 4b194746d4d..97b3c357cde 100644
--- a/tests/lib/Files/Node/FolderTest.php
+++ b/tests/lib/Files/Node/FolderTest.php
@@ -62,7 +62,7 @@ class FolderTest extends NodeTest {
return 'rmdir';
}
- public function testGetDirectoryContent() {
+ public function testGetDirectoryContent(): void {
$manager = $this->createMock(Manager::class);
/**
* @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view
@@ -97,7 +97,7 @@ class FolderTest extends NodeTest {
$this->assertEquals(3, $children[1]->getId());
}
- public function testGet() {
+ public function testGet(): void {
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
@@ -116,7 +116,7 @@ class FolderTest extends NodeTest {
self::assertEquals($node, $parentNode->get('asd'));
}
- public function testNodeExists() {
+ public function testNodeExists(): void {
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
@@ -136,7 +136,7 @@ class FolderTest extends NodeTest {
$this->assertTrue($node->nodeExists('asd'));
}
- public function testNodeExistsNotExists() {
+ public function testNodeExistsNotExists(): void {
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
@@ -154,7 +154,7 @@ class FolderTest extends NodeTest {
$this->assertFalse($node->nodeExists('asd'));
}
- public function testNewFolder() {
+ public function testNewFolder(): void {
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
@@ -178,7 +178,7 @@ class FolderTest extends NodeTest {
$this->assertEquals($child, $result);
}
- public function testNewFolderDeepParent() {
+ public function testNewFolderDeepParent(): void {
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
@@ -203,7 +203,7 @@ class FolderTest extends NodeTest {
}
- public function testNewFolderNotPermitted() {
+ public function testNewFolderNotPermitted(): void {
$this->expectException(\OCP\Files\NotPermittedException::class);
$manager = $this->createMock(Manager::class);
@@ -222,7 +222,7 @@ class FolderTest extends NodeTest {
$node->newFolder('asd');
}
- public function testNewFile() {
+ public function testNewFile(): void {
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
@@ -247,7 +247,7 @@ class FolderTest extends NodeTest {
}
- public function testNewFileNotPermitted() {
+ public function testNewFileNotPermitted(): void {
$this->expectException(\OCP\Files\NotPermittedException::class);
$manager = $this->createMock(Manager::class);
@@ -266,7 +266,7 @@ class FolderTest extends NodeTest {
$node->newFile('asd');
}
- public function testGetFreeSpace() {
+ public function testGetFreeSpace(): void {
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
@@ -283,7 +283,7 @@ class FolderTest extends NodeTest {
$this->assertEquals(100, $node->getFreeSpace());
}
- public function testSearch() {
+ public function testSearch(): void {
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
@@ -330,7 +330,7 @@ class FolderTest extends NodeTest {
$this->assertEquals('/bar/foo/qwerty', $result[0]->getPath());
}
- public function testSearchInRoot() {
+ public function testSearchInRoot(): void {
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
@@ -371,7 +371,7 @@ class FolderTest extends NodeTest {
$this->assertEquals('/foo', $result[0]->getPath());
}
- public function testSearchInStorageRoot() {
+ public function testSearchInStorageRoot(): void {
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
@@ -411,7 +411,7 @@ class FolderTest extends NodeTest {
$this->assertEquals('/bar/foo/qwerty', $result[0]->getPath());
}
- public function testSearchSubStorages() {
+ public function testSearchSubStorages(): void {
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
@@ -469,7 +469,7 @@ class FolderTest extends NodeTest {
$this->assertEquals(2, count($result));
}
- public function testIsSubNode() {
+ public function testIsSubNode(): void {
$rootFolderMock = $this->createMock(IRootFolder::class);
$file = new Node($rootFolderMock, $this->view, '/foo/bar');
$folder = new Folder($rootFolderMock, $this->view, '/foo');
@@ -480,7 +480,7 @@ class FolderTest extends NodeTest {
$this->assertFalse($folder->isSubNode($file));
}
- public function testGetById() {
+ public function testGetById(): void {
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
@@ -527,7 +527,7 @@ class FolderTest extends NodeTest {
$this->assertEquals('/bar/foo/qwerty', $result[0]->getPath());
}
- public function testGetByIdMountRoot() {
+ public function testGetByIdMountRoot(): void {
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
@@ -570,7 +570,7 @@ class FolderTest extends NodeTest {
$this->assertEquals('/bar', $result[0]->getPath());
}
- public function testGetByIdOutsideFolder() {
+ public function testGetByIdOutsideFolder(): void {
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
@@ -612,7 +612,7 @@ class FolderTest extends NodeTest {
$this->assertEquals(0, count($result));
}
- public function testGetByIdMultipleStorages() {
+ public function testGetByIdMultipleStorages(): void {
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
@@ -673,7 +673,7 @@ class FolderTest extends NodeTest {
/**
* @dataProvider uniqueNameProvider
*/
- public function testGetUniqueName($name, $existingFiles, $expected) {
+ public function testGetUniqueName($name, $existingFiles, $expected): void {
$manager = $this->createMock(Manager::class);
$folderPath = '/bar/foo';
$view = $this->getRootViewMock();
@@ -762,7 +762,7 @@ class FolderTest extends NodeTest {
$this->assertEquals([$id1, $id2, $id3], $ids);
}
- public function testRecentFolder() {
+ public function testRecentFolder(): void {
$manager = $this->createMock(Manager::class);
$folderPath = '/bar/foo';
$view = $this->getRootViewMock();
@@ -826,7 +826,7 @@ class FolderTest extends NodeTest {
$this->assertEquals($baseTime - 100, $nodes[1]->getMTime());
}
- public function testRecentJail() {
+ public function testRecentJail(): void {
$manager = $this->createMock(Manager::class);
$folderPath = '/bar/foo';
$view = $this->getRootViewMock();
@@ -909,7 +909,7 @@ class FolderTest extends NodeTest {
* @throws NotFoundException
* @throws \OCP\Files\InvalidPathException
*/
- public function testSearchSubStoragesLimitOffset(int $offset, int $limit, array $expectedPaths, array $ordering) {
+ 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 ac1672ca4be..1a3337b9ddc 100644
--- a/tests/lib/Files/Node/HookConnectorTest.php
+++ b/tests/lib/Files/Node/HookConnectorTest.php
@@ -152,7 +152,7 @@ class HookConnectorTest extends TestCase {
* @param string $expectedHook
* @dataProvider viewToNodeProvider
*/
- public function testViewToNode(callable $operation, $expectedHook, $expectedLegacyEvent, $expectedEvent) {
+ public function testViewToNode(callable $operation, $expectedHook, $expectedLegacyEvent, $expectedEvent): void {
$connector = new HookConnector($this->root, $this->view, $this->eventDispatcher, $this->logger);
$connector->viewToNode();
$hookCalled = false;
@@ -221,7 +221,7 @@ class HookConnectorTest extends TestCase {
* @param string $expectedHook
* @dataProvider viewToNodeProviderCopyRename
*/
- public function testViewToNodeCopyRename(callable $operation, $expectedHook, $expectedLegacyEvent, $expectedEvent) {
+ public function testViewToNodeCopyRename(callable $operation, $expectedHook, $expectedLegacyEvent, $expectedEvent): void {
$connector = new HookConnector($this->root, $this->view, $this->eventDispatcher, $this->logger);
$connector->viewToNode();
$hookCalled = false;
@@ -276,7 +276,7 @@ class HookConnectorTest extends TestCase {
$this->assertEquals('/' . $this->userId . '/files/target', $newDispatcherTargetNode->getPath());
}
- public function testPostDeleteMeta() {
+ public function testPostDeleteMeta(): void {
$connector = new HookConnector($this->root, $this->view, $this->eventDispatcher, $this->logger);
$connector->viewToNode();
$hookCalled = false;
diff --git a/tests/lib/Files/Node/IntegrationTest.php b/tests/lib/Files/Node/IntegrationTest.php
index 965cab32ac2..32d370c12fc 100644
--- a/tests/lib/Files/Node/IntegrationTest.php
+++ b/tests/lib/Files/Node/IntegrationTest.php
@@ -88,7 +88,7 @@ class IntegrationTest extends \Test\TestCase {
parent::tearDown();
}
- public function testBasicFile() {
+ public function testBasicFile(): void {
$file = $this->root->newFile('/foo.txt');
$this->assertCount(2, $this->root->getDirectoryListing());
$this->assertTrue($this->root->nodeExists('/foo.txt'));
@@ -111,7 +111,7 @@ class IntegrationTest extends \Test\TestCase {
$this->assertEquals('qwerty', $file->getContent());
}
- public function testBasicFolder() {
+ public function testBasicFolder(): void {
$folder = $this->root->newFolder('/foo');
$this->assertTrue($this->root->nodeExists('/foo'));
$file = $folder->newFile('/bar');
diff --git a/tests/lib/Files/Node/NodeTest.php b/tests/lib/Files/Node/NodeTest.php
index bbea14daf04..dd2ddbc2a53 100644
--- a/tests/lib/Files/Node/NodeTest.php
+++ b/tests/lib/Files/Node/NodeTest.php
@@ -127,7 +127,7 @@ abstract class NodeTest extends \Test\TestCase {
return new FileInfo('', $this->getMockStorage(), $internalPath, $data, $mount);
}
- public function testDelete() {
+ public function testDelete(): void {
$this->root->expects($this->exactly(2))
->method('emit')
->willReturn(true);
@@ -149,7 +149,7 @@ abstract class NodeTest extends \Test\TestCase {
$node->delete();
}
- public function testDeleteHooks() {
+ public function testDeleteHooks(): void {
$test = $this;
$hooksRun = 0;
/**
@@ -205,7 +205,7 @@ abstract class NodeTest extends \Test\TestCase {
}
- public function testDeleteNotPermitted() {
+ public function testDeleteNotPermitted(): void {
$this->expectException(\OCP\Files\NotPermittedException::class);
$this->root->expects($this->any())
@@ -222,7 +222,7 @@ abstract class NodeTest extends \Test\TestCase {
}
- public function testStat() {
+ public function testStat(): void {
$this->root->expects($this->any())
->method('getUser')
->willReturn($this->user);
@@ -244,7 +244,7 @@ abstract class NodeTest extends \Test\TestCase {
$this->assertEquals($stat, $node->stat());
}
- public function testGetId() {
+ public function testGetId(): void {
$this->root->expects($this->any())
->method('getUser')
->willReturn($this->user);
@@ -265,7 +265,7 @@ abstract class NodeTest extends \Test\TestCase {
$this->assertEquals(1, $node->getId());
}
- public function testGetSize() {
+ public function testGetSize(): void {
$this->root->expects($this->any())
->method('getUser')
->willReturn($this->user);
@@ -287,7 +287,7 @@ abstract class NodeTest extends \Test\TestCase {
$this->assertEquals(100, $node->getSize());
}
- public function testGetEtag() {
+ public function testGetEtag(): void {
$this->root->expects($this->any())
->method('getUser')
->willReturn($this->user);
@@ -308,7 +308,7 @@ abstract class NodeTest extends \Test\TestCase {
$this->assertEquals('qwerty', $node->getEtag());
}
- public function testGetMTime() {
+ public function testGetMTime(): void {
$this->root->expects($this->any())
->method('getUser')
->willReturn($this->user);
@@ -329,7 +329,7 @@ abstract class NodeTest extends \Test\TestCase {
$this->assertEquals(50, $node->getMTime());
}
- public function testGetStorage() {
+ public function testGetStorage(): void {
$this->root->expects($this->any())
->method('getUser')
->willReturn($this->user);
@@ -344,7 +344,7 @@ abstract class NodeTest extends \Test\TestCase {
$this->assertEquals($storage, $node->getStorage());
}
- public function testGetPath() {
+ public function testGetPath(): void {
$this->root->expects($this->any())
->method('getUser')
->willReturn($this->user);
@@ -353,7 +353,7 @@ abstract class NodeTest extends \Test\TestCase {
$this->assertEquals('/bar/foo', $node->getPath());
}
- public function testGetInternalPath() {
+ public function testGetInternalPath(): void {
$this->root->expects($this->any())
->method('getUser')
->willReturn($this->user);
@@ -374,7 +374,7 @@ abstract class NodeTest extends \Test\TestCase {
$this->assertEquals('foo', $node->getInternalPath());
}
- public function testGetName() {
+ public function testGetName(): void {
$this->root->expects($this->any())
->method('getUser')
->willReturn($this->user);
@@ -383,7 +383,7 @@ abstract class NodeTest extends \Test\TestCase {
$this->assertEquals('foo', $node->getName());
}
- public function testTouchSetMTime() {
+ public function testTouchSetMTime(): void {
$this->root->expects($this->any())
->method('getUser')
->willReturn($this->user);
@@ -403,7 +403,7 @@ abstract class NodeTest extends \Test\TestCase {
$this->assertEquals(100, $node->getMTime());
}
- public function testTouchHooks() {
+ public function testTouchHooks(): void {
$test = $this;
$hooksRun = 0;
/**
@@ -453,7 +453,7 @@ abstract class NodeTest extends \Test\TestCase {
}
- public function testTouchNotPermitted() {
+ public function testTouchNotPermitted(): void {
$this->expectException(\OCP\Files\NotPermittedException::class);
$this->root->expects($this->any())
@@ -470,14 +470,14 @@ abstract class NodeTest extends \Test\TestCase {
}
- public function testInvalidPath() {
+ public function testInvalidPath(): void {
$this->expectException(\OCP\Files\InvalidPathException::class);
$node = $this->createTestNode($this->root, $this->view, '/../foo');
$node->getFileInfo();
}
- public function testCopySameStorage() {
+ public function testCopySameStorage(): void {
$this->view->expects($this->any())
->method('copy')
->with('/bar/foo', '/bar/asd')
@@ -503,7 +503,7 @@ abstract class NodeTest extends \Test\TestCase {
}
- public function testCopyNotPermitted() {
+ public function testCopyNotPermitted(): void {
$this->expectException(\OCP\Files\NotPermittedException::class);
/**
@@ -534,7 +534,7 @@ abstract class NodeTest extends \Test\TestCase {
}
- public function testCopyNoParent() {
+ public function testCopyNoParent(): void {
$this->expectException(\OCP\Files\NotFoundException::class);
$this->view->expects($this->never())
@@ -551,7 +551,7 @@ abstract class NodeTest extends \Test\TestCase {
}
- public function testCopyParentIsFile() {
+ public function testCopyParentIsFile(): void {
$this->expectException(\OCP\Files\NotPermittedException::class);
$this->view->expects($this->never())
@@ -569,7 +569,7 @@ abstract class NodeTest extends \Test\TestCase {
$node->copy('/bar/asd');
}
- public function testMoveSameStorage() {
+ public function testMoveSameStorage(): void {
$this->view->expects($this->any())
->method('rename')
->with('/bar/foo', '/bar/asd')
@@ -606,7 +606,7 @@ abstract class NodeTest extends \Test\TestCase {
* @param string $preHookName
* @param string $postHookName
*/
- public function testMoveCopyHooks($operationMethod, $viewMethod, $preHookName, $postHookName) {
+ public function testMoveCopyHooks($operationMethod, $viewMethod, $preHookName, $postHookName): void {
/** @var IRootFolder|\PHPUnit\Framework\MockObject\MockObject $root */
$root = $this->getMockBuilder(\OC\Files\Node\Root::class)
->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
@@ -674,7 +674,7 @@ abstract class NodeTest extends \Test\TestCase {
}
- public function testMoveNotPermitted() {
+ public function testMoveNotPermitted(): void {
$this->expectException(\OCP\Files\NotPermittedException::class);
$this->view->expects($this->any())
@@ -696,7 +696,7 @@ abstract class NodeTest extends \Test\TestCase {
}
- public function testMoveNoParent() {
+ public function testMoveNoParent(): void {
$this->expectException(\OCP\Files\NotFoundException::class);
/**
@@ -718,7 +718,7 @@ abstract class NodeTest extends \Test\TestCase {
}
- public function testMoveParentIsFile() {
+ public function testMoveParentIsFile(): void {
$this->expectException(\OCP\Files\NotPermittedException::class);
$this->view->expects($this->never())
@@ -736,7 +736,7 @@ abstract class NodeTest extends \Test\TestCase {
}
- public function testMoveFailed() {
+ public function testMoveFailed(): void {
$this->expectException(\OCP\Files\NotPermittedException::class);
$this->view->expects($this->any())
@@ -759,7 +759,7 @@ abstract class NodeTest extends \Test\TestCase {
}
- public function testCopyFailed() {
+ public function testCopyFailed(): void {
$this->expectException(\OCP\Files\NotPermittedException::class);
$this->view->expects($this->any())
diff --git a/tests/lib/Files/Node/RootTest.php b/tests/lib/Files/Node/RootTest.php
index 00d6a328335..678e882e94e 100644
--- a/tests/lib/Files/Node/RootTest.php
+++ b/tests/lib/Files/Node/RootTest.php
@@ -75,7 +75,7 @@ class RootTest extends \Test\TestCase {
return new FileInfo('', null, '', $data, null);
}
- public function testGet() {
+ public function testGet(): void {
/**
* @var \OC\Files\Storage\Storage $storage
*/
@@ -106,7 +106,7 @@ class RootTest extends \Test\TestCase {
}
- public function testGetNotFound() {
+ public function testGetNotFound(): void {
$this->expectException(\OCP\Files\NotFoundException::class);
/**
@@ -137,7 +137,7 @@ class RootTest extends \Test\TestCase {
}
- public function testGetInvalidPath() {
+ public function testGetInvalidPath(): void {
$this->expectException(\OCP\Files\NotPermittedException::class);
$view = $this->getRootViewMock();
@@ -156,7 +156,7 @@ class RootTest extends \Test\TestCase {
}
- public function testGetNoStorages() {
+ public function testGetNoStorages(): void {
$this->expectException(\OCP\Files\NotFoundException::class);
$view = $this->getRootViewMock();
@@ -174,7 +174,7 @@ class RootTest extends \Test\TestCase {
$root->get('/bar/foo');
}
- public function testGetUserFolder() {
+ public function testGetUserFolder(): void {
$root = new \OC\Files\Node\Root(
$this->manager,
$this->getRootViewMock(),
@@ -213,7 +213,7 @@ class RootTest extends \Test\TestCase {
}
- public function testGetUserFolderWithNoUserObj() {
+ public function testGetUserFolderWithNoUserObj(): void {
$this->expectException(\OC\User\NoUserException::class);
$this->expectExceptionMessage('Backends provided no user object');
diff --git a/tests/lib/Files/ObjectStore/AzureTest.php b/tests/lib/Files/ObjectStore/AzureTest.php
index 9c7b48d7ca7..f56f7b589e0 100644
--- a/tests/lib/Files/ObjectStore/AzureTest.php
+++ b/tests/lib/Files/ObjectStore/AzureTest.php
@@ -21,7 +21,7 @@ class AzureTest extends ObjectStoreTest {
return new Azure($config['arguments']);
}
- public function testFseekSize() {
+ public function testFseekSize(): void {
$this->markTestSkipped('azure does not support seeking at the moment');
}
}
diff --git a/tests/lib/Files/ObjectStore/MapperTest.php b/tests/lib/Files/ObjectStore/MapperTest.php
index 19269f13355..15a2d497fc3 100644
--- a/tests/lib/Files/ObjectStore/MapperTest.php
+++ b/tests/lib/Files/ObjectStore/MapperTest.php
@@ -47,7 +47,7 @@ class MapperTest extends \Test\TestCase {
* @param int $numBuckets
* @param string $expectedBucket
*/
- public function testGetBucket($username, $numBuckets, $bucketShift, $expectedBucket) {
+ public function testGetBucket($username, $numBuckets, $bucketShift, $expectedBucket): void {
$this->user->expects($this->once())
->method('getUID')
->willReturn($username);
diff --git a/tests/lib/Files/ObjectStore/ObjectStoreScannerTest.php b/tests/lib/Files/ObjectStore/ObjectStoreScannerTest.php
index 425dc8c2581..4f6254cdb94 100644
--- a/tests/lib/Files/ObjectStore/ObjectStoreScannerTest.php
+++ b/tests/lib/Files/ObjectStore/ObjectStoreScannerTest.php
@@ -31,7 +31,7 @@ class ObjectStoreScannerTest extends TestCase {
$this->realScanner = new Scanner($this->storage);
}
- public function testFile() {
+ public function testFile(): void {
$data = "dummy file data\n";
$this->storage->file_put_contents('foo.txt', $data);
@@ -51,7 +51,7 @@ class ObjectStoreScannerTest extends TestCase {
$this->storage->file_put_contents('folder/bar.txt', $textData);
}
- public function testFolder() {
+ public function testFolder(): void {
$this->fillTestFolders();
$this->assertEquals(
@@ -61,7 +61,7 @@ class ObjectStoreScannerTest extends TestCase {
);
}
- public function testBackgroundScan() {
+ public function testBackgroundScan(): void {
$this->fillTestFolders();
$this->storage->mkdir('folder2');
$this->storage->file_put_contents('folder2/bar.txt', 'foobar');
diff --git a/tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php b/tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php
index 8ffd27f0069..09402d5706a 100644
--- a/tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php
+++ b/tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php
@@ -43,7 +43,7 @@ class ObjectStoreStorageTest extends Storage {
parent::tearDown();
}
- public function testStat() {
+ public function testStat(): void {
$textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
$ctimeStart = time();
$this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile));
@@ -67,14 +67,14 @@ class ObjectStoreStorageTest extends Storage {
}
}
- public function testCheckUpdate() {
+ public function testCheckUpdate(): void {
$this->markTestSkipped('Detecting external changes is not supported on object storages');
}
/**
* @dataProvider copyAndMoveProvider
*/
- public function testMove($source, $target) {
+ public function testMove($source, $target): void {
$this->initSourceAndTarget($source);
$sourceId = $this->instance->getCache()->getId(ltrim('/', $source));
$this->assertNotEquals(-1, $sourceId);
@@ -89,7 +89,7 @@ class ObjectStoreStorageTest extends Storage {
$this->assertSame($sourceId, $targetId, 'fileid must be stable on move or shares will break');
}
- public function testRenameDirectory() {
+ public function testRenameDirectory(): void {
$this->instance->mkdir('source');
$this->instance->file_put_contents('source/test1.txt', 'foo');
$this->instance->file_put_contents('source/test2.txt', 'qwerty');
@@ -118,7 +118,7 @@ class ObjectStoreStorageTest extends Storage {
$this->assertSame($sourceId, $targetId, 'fileid must be stable on move or shares will break');
}
- public function testRenameOverWriteDirectory() {
+ public function testRenameOverWriteDirectory(): void {
$this->instance->mkdir('source');
$this->instance->file_put_contents('source/test1.txt', 'foo');
$sourceId = $this->instance->getCache()->getId('source');
@@ -138,7 +138,7 @@ class ObjectStoreStorageTest extends Storage {
$this->assertSame($sourceId, $targetId, 'fileid must be stable on move or shares will break');
}
- public function testRenameOverWriteDirectoryOverFile() {
+ public function testRenameOverWriteDirectoryOverFile(): void {
$this->instance->mkdir('source');
$this->instance->file_put_contents('source/test1.txt', 'foo');
$sourceId = $this->instance->getCache()->getId('source');
@@ -155,7 +155,7 @@ class ObjectStoreStorageTest extends Storage {
$this->assertSame($sourceId, $targetId, 'fileid must be stable on move or shares will break');
}
- public function testWriteObjectSilentFailure() {
+ public function testWriteObjectSilentFailure(): void {
$objectStore = $this->instance->getObjectStore();
$this->instance->setObjectStore(new FailWriteObjectStore($objectStore));
@@ -168,7 +168,7 @@ class ObjectStoreStorageTest extends Storage {
$this->assertFalse($this->instance->file_exists('test.txt'));
}
- public function testWriteObjectSilentFailureNoCheck() {
+ public function testWriteObjectSilentFailureNoCheck(): void {
$objectStore = $this->instance->getObjectStore();
$this->instance->setObjectStore(new FailWriteObjectStore($objectStore));
$this->instance->setValidateWrites(false);
@@ -177,7 +177,7 @@ class ObjectStoreStorageTest extends Storage {
$this->assertTrue($this->instance->file_exists('test.txt'));
}
- public function testDeleteObjectFailureKeepCache() {
+ public function testDeleteObjectFailureKeepCache(): void {
$objectStore = $this->instance->getObjectStore();
$this->instance->setObjectStore(new FailDeleteObjectStore($objectStore));
$cache = $this->instance->getCache();
@@ -202,7 +202,7 @@ class ObjectStoreStorageTest extends Storage {
$this->assertTrue($cache->inCache('foo/test.txt'));
}
- public function testCopyBetweenJails() {
+ public function testCopyBetweenJails(): void {
$this->instance->mkdir('a');
$this->instance->mkdir('b');
$jailA = new Jail([
@@ -225,7 +225,7 @@ class ObjectStoreStorageTest extends Storage {
$this->assertEquals('3', $this->instance->file_get_contents('b/target/sub/3.txt'));
}
- public function testCopyPreservesPermissions() {
+ public function testCopyPreservesPermissions(): void {
$cache = $this->instance->getCache();
$this->instance->file_put_contents('test.txt', 'foo');
@@ -244,7 +244,7 @@ class ObjectStoreStorageTest extends Storage {
* Test that copying files will drop permissions like local storage does
* TODO: Drop this and fix local storage
*/
- public function testCopyGrantsPermissions() {
+ public function testCopyGrantsPermissions(): void {
$config['objectstore'] = $this->objectStorage;
$config['handleCopiesAsOwned'] = true;
$instance = new ObjectStoreStorageOverwrite($config);
diff --git a/tests/lib/Files/ObjectStore/ObjectStoreTest.php b/tests/lib/Files/ObjectStore/ObjectStoreTest.php
index 74f047a8663..4a4f85dfb91 100644
--- a/tests/lib/Files/ObjectStore/ObjectStoreTest.php
+++ b/tests/lib/Files/ObjectStore/ObjectStoreTest.php
@@ -38,7 +38,7 @@ abstract class ObjectStoreTest extends TestCase {
return $stream;
}
- public function testWriteRead() {
+ public function testWriteRead(): void {
$stream = $this->stringToStream('foobar');
$instance = $this->getInstance();
@@ -51,7 +51,7 @@ abstract class ObjectStoreTest extends TestCase {
$this->assertEquals('foobar', stream_get_contents($result));
}
- public function testDelete() {
+ public function testDelete(): void {
$stream = $this->stringToStream('foobar');
$instance = $this->getInstance();
@@ -70,7 +70,7 @@ abstract class ObjectStoreTest extends TestCase {
}
}
- public function testReadNonExisting() {
+ public function testReadNonExisting(): void {
$instance = $this->getInstance();
try {
@@ -82,7 +82,7 @@ abstract class ObjectStoreTest extends TestCase {
}
}
- public function testDeleteNonExisting() {
+ public function testDeleteNonExisting(): void {
$instance = $this->getInstance();
try {
@@ -94,7 +94,7 @@ abstract class ObjectStoreTest extends TestCase {
}
}
- public function testExists() {
+ public function testExists(): void {
$stream = $this->stringToStream('foobar');
$instance = $this->getInstance();
@@ -109,7 +109,7 @@ abstract class ObjectStoreTest extends TestCase {
$this->assertFalse($instance->objectExists('2'));
}
- public function testCopy() {
+ public function testCopy(): void {
$this->cleanupAfter('source');
$this->cleanupAfter('target');
@@ -128,7 +128,7 @@ abstract class ObjectStoreTest extends TestCase {
$this->assertEquals('foobar', stream_get_contents($instance->readObject('target')));
}
- public function testFseekSize() {
+ public function testFseekSize(): void {
$instance = $this->getInstance();
$textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
diff --git a/tests/lib/Files/ObjectStore/S3Test.php b/tests/lib/Files/ObjectStore/S3Test.php
index 6a8fad52476..1501f575f9a 100644
--- a/tests/lib/Files/ObjectStore/S3Test.php
+++ b/tests/lib/Files/ObjectStore/S3Test.php
@@ -60,7 +60,7 @@ class S3Test extends ObjectStoreTest {
return new S3($config['arguments']);
}
- public function testUploadNonSeekable() {
+ public function testUploadNonSeekable(): void {
$this->cleanupAfter('multiparttest');
$s3 = $this->getInstance();
@@ -72,7 +72,7 @@ class S3Test extends ObjectStoreTest {
$this->assertEquals(file_get_contents(__FILE__), stream_get_contents($result));
}
- public function testSeek() {
+ public function testSeek(): void {
$this->cleanupAfter('seek');
$data = file_get_contents(__FILE__);
@@ -101,7 +101,7 @@ class S3Test extends ObjectStoreTest {
$this->assertArrayNotHasKey('Uploads', $uploads, 'Assert is not uploaded');
}
- public function testEmptyUpload() {
+ public function testEmptyUpload(): void {
$s3 = $this->getInstance();
$emptyStream = fopen('php://memory', 'r');
@@ -133,7 +133,7 @@ class S3Test extends ObjectStoreTest {
}
/** @dataProvider dataFileSizes */
- public function testFileSizes($size) {
+ 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 735bebc44a0..01de4da140a 100644
--- a/tests/lib/Files/ObjectStore/SwiftTest.php
+++ b/tests/lib/Files/ObjectStore/SwiftTest.php
@@ -25,7 +25,7 @@ class SwiftTest extends ObjectStoreTest {
return new Swift($config['arguments']);
}
- public function testFseekSize() {
+ public function testFseekSize(): void {
$this->markTestSkipped('Swift does not support seeking at the moment');
}
}
diff --git a/tests/lib/Files/PathVerificationTest.php b/tests/lib/Files/PathVerificationTest.php
index f256a954f9f..fcbe0a6957f 100644
--- a/tests/lib/Files/PathVerificationTest.php
+++ b/tests/lib/Files/PathVerificationTest.php
@@ -30,7 +30,7 @@ class PathVerificationTest extends \Test\TestCase {
}
- public function testPathVerificationFileNameTooLong() {
+ public function testPathVerificationFileNameTooLong(): void {
$this->expectException(\OCP\Files\InvalidPathException::class);
$this->expectExceptionMessage('Filename is too long');
@@ -42,7 +42,7 @@ class PathVerificationTest extends \Test\TestCase {
/**
* @dataProvider providesEmptyFiles
*/
- public function testPathVerificationEmptyFileName($fileName) {
+ public function testPathVerificationEmptyFileName($fileName): void {
$this->expectException(\OCP\Files\InvalidPathException::class);
$this->expectExceptionMessage('Empty filename is not allowed');
@@ -59,7 +59,7 @@ class PathVerificationTest extends \Test\TestCase {
/**
* @dataProvider providesDotFiles
*/
- public function testPathVerificationDotFiles($fileName) {
+ public function testPathVerificationDotFiles($fileName): void {
$this->expectException(\OCP\Files\InvalidPathException::class);
$this->expectExceptionMessage('Dot files are not allowed');
@@ -82,7 +82,7 @@ class PathVerificationTest extends \Test\TestCase {
/**
* @dataProvider providesAstralPlane
*/
- public function testPathVerificationAstralPlane($fileName) {
+ public function testPathVerificationAstralPlane($fileName): void {
$connection = \OC::$server->getDatabaseConnection();
if (!$connection->supports4ByteText()) {
@@ -109,7 +109,7 @@ class PathVerificationTest extends \Test\TestCase {
/**
* @dataProvider providesValidPosixPaths
*/
- public function testPathVerificationValidPaths($fileName) {
+ public function testPathVerificationValidPaths($fileName): void {
$storage = new Local(['datadir' => '']);
self::invokePrivate($storage, 'verifyPosixPath', [$fileName]);
diff --git a/tests/lib/Files/Search/QueryOptimizer/CombinedTests.php b/tests/lib/Files/Search/QueryOptimizer/CombinedTests.php
index 4e7f13cd33e..e6cb11a7eba 100644
--- a/tests/lib/Files/Search/QueryOptimizer/CombinedTests.php
+++ b/tests/lib/Files/Search/QueryOptimizer/CombinedTests.php
@@ -21,7 +21,7 @@ class CombinedTests extends TestCase {
$this->optimizer = new QueryOptimizer();
}
- public function testBasicOrOfAnds() {
+ public function testBasicOrOfAnds(): void {
$operator = new SearchBinaryOperator(
ISearchBinaryOperator::OPERATOR_OR,
[
@@ -46,7 +46,7 @@ class CombinedTests extends TestCase {
$this->assertEquals('(storage eq 1 and path in ["foo","bar","asd"])', $operator->__toString());
}
- public function testComplexSearchPattern1() {
+ public function testComplexSearchPattern1(): void {
$operator = new SearchBinaryOperator(
ISearchBinaryOperator::OPERATOR_OR,
[
@@ -85,7 +85,7 @@ class CombinedTests extends TestCase {
$this->assertEquals('(storage eq 1 or (storage eq 2 and (path eq "201" or path like "201\/%")) or (storage eq 3 and path in ["301","302"]) or (storage eq 4 and path in ["401","402"]))', $operator->__toString());
}
- public function testComplexSearchPattern2() {
+ public function testComplexSearchPattern2(): void {
$operator = new SearchBinaryOperator(
ISearchBinaryOperator::OPERATOR_OR,
[
@@ -122,7 +122,7 @@ class CombinedTests extends TestCase {
$this->assertEquals('(storage eq 1 or (storage eq 2 and (path eq "201" or path like "201\/%")) or (storage eq 3 and path in ["301","302"]) or (storage eq 4 and path in ["401","402"]))', $operator->__toString());
}
- public function testApplySearchConstraints1() {
+ public function testApplySearchConstraints1(): void {
$operator = new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_AND, [
new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_AND, [
new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_OR, [
@@ -156,7 +156,7 @@ class CombinedTests extends TestCase {
$this->assertEquals('(mimetype in ["image\/png","image\/jpeg"] and ((storage eq 1 and (path eq "files" or path like "files\/%")) or storage eq 2 or (storage eq 3 and path in ["files\/301","files\/302"])))', $operator->__toString());
}
- public function testApplySearchConstraints2() {
+ public function testApplySearchConstraints2(): void {
$operator = new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_AND, [
new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_AND, [
new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_OR, [
diff --git a/tests/lib/Files/Search/QueryOptimizer/FlattenNestedBoolTest.php b/tests/lib/Files/Search/QueryOptimizer/FlattenNestedBoolTest.php
index 778b20541a5..6777047d68b 100644
--- a/tests/lib/Files/Search/QueryOptimizer/FlattenNestedBoolTest.php
+++ b/tests/lib/Files/Search/QueryOptimizer/FlattenNestedBoolTest.php
@@ -24,7 +24,7 @@ class FlattenNestedBoolTest extends TestCase {
$this->simplifier = new FlattenSingleArgumentBinaryOperation();
}
- public function testOrs() {
+ public function testOrs(): void {
$operator = new SearchBinaryOperator(
ISearchBinaryOperator::OPERATOR_OR,
[
diff --git a/tests/lib/Files/Search/QueryOptimizer/MergeDistributiveOperationsTest.php b/tests/lib/Files/Search/QueryOptimizer/MergeDistributiveOperationsTest.php
index a7e6dc63b15..4f933d0c371 100644
--- a/tests/lib/Files/Search/QueryOptimizer/MergeDistributiveOperationsTest.php
+++ b/tests/lib/Files/Search/QueryOptimizer/MergeDistributiveOperationsTest.php
@@ -24,7 +24,7 @@ class MergeDistributiveOperationsTest extends TestCase {
$this->simplifier = new FlattenSingleArgumentBinaryOperation();
}
- public function testBasicOrOfAnds() {
+ public function testBasicOrOfAnds(): void {
$operator = new SearchBinaryOperator(
ISearchBinaryOperator::OPERATOR_OR,
[
@@ -50,7 +50,7 @@ class MergeDistributiveOperationsTest extends TestCase {
$this->assertEquals('(storage eq 1 and (path eq "foo" or path eq "bar" or path eq "asd"))', $operator->__toString());
}
- public function testDontTouchIfNotSame() {
+ public function testDontTouchIfNotSame(): void {
$operator = new SearchBinaryOperator(
ISearchBinaryOperator::OPERATOR_OR,
[
@@ -76,7 +76,7 @@ class MergeDistributiveOperationsTest extends TestCase {
$this->assertEquals('((storage eq 1 and path eq "foo") or (storage eq 2 and path eq "bar") or (storage eq 3 and path eq "asd"))', $operator->__toString());
}
- public function testMergePartial() {
+ public function testMergePartial(): void {
$operator = new SearchBinaryOperator(
ISearchBinaryOperator::OPERATOR_OR,
[
@@ -102,7 +102,7 @@ class MergeDistributiveOperationsTest extends TestCase {
$this->assertEquals('((storage eq 1 and (path eq "foo" or path eq "bar")) or (storage eq 2 and path eq "asd"))', $operator->__toString());
}
- public function testOptimizeInside() {
+ public function testOptimizeInside(): void {
$operator = new SearchBinaryOperator(
ISearchBinaryOperator::OPERATOR_AND,
[
@@ -134,7 +134,7 @@ class MergeDistributiveOperationsTest extends TestCase {
$this->assertEquals('((storage eq 1 and (path eq "foo" or path eq "bar" or path eq "asd")) and mimetype eq "text")', $operator->__toString());
}
- public function testMoveInnerOperations() {
+ public function testMoveInnerOperations(): void {
$operator = new SearchBinaryOperator(
ISearchBinaryOperator::OPERATOR_OR,
[
diff --git a/tests/lib/Files/Search/QueryOptimizer/OrEqualsToInTest.php b/tests/lib/Files/Search/QueryOptimizer/OrEqualsToInTest.php
index d0ab70323ba..8b1c3b992b2 100644
--- a/tests/lib/Files/Search/QueryOptimizer/OrEqualsToInTest.php
+++ b/tests/lib/Files/Search/QueryOptimizer/OrEqualsToInTest.php
@@ -24,7 +24,7 @@ class OrEqualsToInTest extends TestCase {
$this->simplifier = new FlattenSingleArgumentBinaryOperation();
}
- public function testOrs() {
+ public function testOrs(): void {
$operator = new SearchBinaryOperator(
ISearchBinaryOperator::OPERATOR_OR,
[
@@ -41,7 +41,7 @@ class OrEqualsToInTest extends TestCase {
$this->assertEquals('path in ["foo","bar","asd"]', $operator->__toString());
}
- public function testOrsMultipleFields() {
+ public function testOrsMultipleFields(): void {
$operator = new SearchBinaryOperator(
ISearchBinaryOperator::OPERATOR_OR,
[
@@ -60,7 +60,7 @@ class OrEqualsToInTest extends TestCase {
$this->assertEquals('(path in ["foo","bar"] or fileid in [1,2] or mimetype eq "asd")', $operator->__toString());
}
- public function testPreserveHints() {
+ public function testPreserveHints(): void {
$operator = new SearchBinaryOperator(
ISearchBinaryOperator::OPERATOR_OR,
[
@@ -81,7 +81,7 @@ class OrEqualsToInTest extends TestCase {
$this->assertEquals(false, $operator->getQueryHint(ISearchComparison::HINT_PATH_EQ_HASH, true));
}
- public function testOrSomeEq() {
+ public function testOrSomeEq(): void {
$operator = new SearchBinaryOperator(
ISearchBinaryOperator::OPERATOR_OR,
[
@@ -98,7 +98,7 @@ class OrEqualsToInTest extends TestCase {
$this->assertEquals('(path in ["foo","bar"] or path like "foo%")', $operator->__toString());
}
- public function testOrsInside() {
+ public function testOrsInside(): void {
$operator = new SearchBinaryOperator(
ISearchBinaryOperator::OPERATOR_AND,
[
diff --git a/tests/lib/Files/Search/SearchIntegrationTest.php b/tests/lib/Files/Search/SearchIntegrationTest.php
index c1017537a0c..0ca67285fd5 100644
--- a/tests/lib/Files/Search/SearchIntegrationTest.php
+++ b/tests/lib/Files/Search/SearchIntegrationTest.php
@@ -29,7 +29,7 @@ class SearchIntegrationTest extends TestCase {
}
- public function testThousandAndOneFilters() {
+ public function testThousandAndOneFilters(): void {
$id = $this->cache->put('file10', ['size' => 1, 'mtime' => 50, 'mimetype' => 'foo/folder']);
$comparisons = [];
diff --git a/tests/lib/Files/SimpleFS/InMemoryFileTest.php b/tests/lib/Files/SimpleFS/InMemoryFileTest.php
index dfd6c44ac7e..43587acdce9 100644
--- a/tests/lib/Files/SimpleFS/InMemoryFileTest.php
+++ b/tests/lib/Files/SimpleFS/InMemoryFileTest.php
@@ -44,7 +44,7 @@ class InMemoryFileTest extends TestCase {
*
* @return void
*/
- public function testPutContent() {
+ public function testPutContent(): void {
$this->testPdf->putContent('test');
self::assertEquals('test', $this->testPdf->getContent());
}
@@ -54,7 +54,7 @@ class InMemoryFileTest extends TestCase {
*
* @return void
*/
- public function testDelete() {
+ public function testDelete(): void {
$this->testPdf->delete();
// assert true, otherwise phpunit complains about not doing any assert
self::assertTrue(true);
@@ -65,7 +65,7 @@ class InMemoryFileTest extends TestCase {
*
* @return void
*/
- public function testGetName() {
+ public function testGetName(): void {
self::assertEquals('test.pdf', $this->testPdf->getName());
}
@@ -74,7 +74,7 @@ class InMemoryFileTest extends TestCase {
*
* @return void
*/
- public function testGetSize() {
+ public function testGetSize(): void {
self::assertEquals(7083, $this->testPdf->getSize());
}
@@ -83,7 +83,7 @@ class InMemoryFileTest extends TestCase {
*
* @return void
*/
- public function testGetContent() {
+ public function testGetContent(): void {
self::assertEquals(
file_get_contents(__DIR__ . '/../../../data/test.pdf'),
$this->testPdf->getContent()
@@ -95,7 +95,7 @@ class InMemoryFileTest extends TestCase {
*
* @return void
*/
- public function testGetMTime() {
+ public function testGetMTime(): void {
self::assertTrue(is_int($this->testPdf->getMTime()));
}
@@ -104,7 +104,7 @@ class InMemoryFileTest extends TestCase {
*
* @return void
*/
- public function testGetMimeType() {
+ public function testGetMimeType(): void {
self::assertEquals('application/pdf', $this->testPdf->getMimeType());
}
@@ -114,7 +114,7 @@ class InMemoryFileTest extends TestCase {
*
* @return void
*/
- public function testRead() {
+ public function testRead(): void {
self::expectException(NotPermittedException::class);
$this->testPdf->read();
}
@@ -124,7 +124,7 @@ class InMemoryFileTest extends TestCase {
*
* @return void
*/
- public function testWrite() {
+ public function testWrite(): void {
self::expectException(NotPermittedException::class);
$this->testPdf->write();
}
diff --git a/tests/lib/Files/SimpleFS/SimpleFileTest.php b/tests/lib/Files/SimpleFS/SimpleFileTest.php
index 6dbd663068e..d0676eae70f 100644
--- a/tests/lib/Files/SimpleFS/SimpleFileTest.php
+++ b/tests/lib/Files/SimpleFS/SimpleFileTest.php
@@ -25,7 +25,7 @@ class SimpleFileTest extends \Test\TestCase {
$this->simpleFile = new SimpleFile($this->file);
}
- public function testGetName() {
+ public function testGetName(): void {
$this->file->expects($this->once())
->method('getName')
->willReturn('myname');
@@ -33,7 +33,7 @@ class SimpleFileTest extends \Test\TestCase {
$this->assertEquals('myname', $this->simpleFile->getName());
}
- public function testGetSize() {
+ public function testGetSize(): void {
$this->file->expects($this->once())
->method('getSize')
->willReturn(42);
@@ -41,7 +41,7 @@ class SimpleFileTest extends \Test\TestCase {
$this->assertEquals(42, $this->simpleFile->getSize());
}
- public function testGetETag() {
+ public function testGetETag(): void {
$this->file->expects($this->once())
->method('getETag')
->willReturn('etag');
@@ -49,7 +49,7 @@ class SimpleFileTest extends \Test\TestCase {
$this->assertEquals('etag', $this->simpleFile->getETag());
}
- public function testGetMTime() {
+ public function testGetMTime(): void {
$this->file->expects($this->once())
->method('getMTime')
->willReturn(101);
@@ -57,7 +57,7 @@ class SimpleFileTest extends \Test\TestCase {
$this->assertEquals(101, $this->simpleFile->getMTime());
}
- public function testGetContent() {
+ public function testGetContent(): void {
$this->file->expects($this->once())
->method('getContent')
->willReturn('foo');
@@ -65,7 +65,7 @@ class SimpleFileTest extends \Test\TestCase {
$this->assertEquals('foo', $this->simpleFile->getContent());
}
- public function testPutContent() {
+ public function testPutContent(): void {
$this->file->expects($this->once())
->method('putContent')
->with($this->equalTo('bar'));
@@ -73,14 +73,14 @@ class SimpleFileTest extends \Test\TestCase {
$this->simpleFile->putContent('bar');
}
- public function testDelete() {
+ public function testDelete(): void {
$this->file->expects($this->once())
->method('delete');
$this->simpleFile->delete();
}
- public function testGetMimeType() {
+ public function testGetMimeType(): void {
$this->file->expects($this->once())
->method('getMimeType')
->willReturn('app/awesome');
@@ -88,7 +88,7 @@ class SimpleFileTest extends \Test\TestCase {
$this->assertEquals('app/awesome', $this->simpleFile->getMimeType());
}
- public function testGetContentInvalidAppData() {
+ public function testGetContentInvalidAppData(): void {
$this->file->method('getContent')
->willReturn(false);
$this->file->method('stat')->willReturn(false);
@@ -107,7 +107,7 @@ class SimpleFileTest extends \Test\TestCase {
$this->simpleFile->getContent();
}
- public function testRead() {
+ public function testRead(): void {
$this->file->expects($this->once())
->method('fopen')
->with('r');
@@ -115,7 +115,7 @@ class SimpleFileTest extends \Test\TestCase {
$this->simpleFile->read();
}
- public function testWrite() {
+ public function testWrite(): void {
$this->file->expects($this->once())
->method('fopen')
->with('w');
diff --git a/tests/lib/Files/SimpleFS/SimpleFolderTest.php b/tests/lib/Files/SimpleFS/SimpleFolderTest.php
index 139a6cb703c..6897aab1f02 100644
--- a/tests/lib/Files/SimpleFS/SimpleFolderTest.php
+++ b/tests/lib/Files/SimpleFS/SimpleFolderTest.php
@@ -47,24 +47,24 @@ class SimpleFolderTest extends \Test\TestCase {
$this->simpleFolder = new SimpleFolder($this->folder);
}
- public function testGetName() {
+ public function testGetName(): void {
$this->assertEquals('test', $this->simpleFolder->getName());
}
- public function testDelete() {
+ public function testDelete(): void {
$this->assertTrue($this->parentFolder->nodeExists('test'));
$this->simpleFolder->delete();
$this->assertFalse($this->parentFolder->nodeExists('test'));
}
- public function testFileExists() {
+ public function testFileExists(): void {
$this->folder->newFile('exists');
$this->assertFalse($this->simpleFolder->fileExists('not-exists'));
$this->assertTrue($this->simpleFolder->fileExists('exists'));
}
- public function testGetFile() {
+ public function testGetFile(): void {
$this->folder->newFile('exists');
$result = $this->simpleFolder->getFile('exists');
@@ -74,7 +74,7 @@ class SimpleFolderTest extends \Test\TestCase {
$this->simpleFolder->getFile('not-exists');
}
- public function testNewFile() {
+ public function testNewFile(): void {
$result = $this->simpleFolder->newFile('file');
$this->assertInstanceOf(ISimpleFile::class, $result);
$this->assertFalse($this->folder->nodeExists('file'));
@@ -84,7 +84,7 @@ class SimpleFolderTest extends \Test\TestCase {
$this->assertEquals('bar', $result->getContent());
}
- public function testGetDirectoryListing() {
+ public function testGetDirectoryListing(): void {
$this->folder->newFile('file1');
$this->folder->newFile('file2');
@@ -94,7 +94,7 @@ class SimpleFolderTest extends \Test\TestCase {
$this->assertInstanceOf(ISimpleFile::class, $result[1]);
}
- public function testGetFolder() {
+ public function testGetFolder(): void {
$this->folder->newFolder('exists');
$result = $this->simpleFolder->getFolder('exists');
@@ -104,7 +104,7 @@ class SimpleFolderTest extends \Test\TestCase {
$this->simpleFolder->getFolder('not-exists');
}
- public function testNewFolder() {
+ public function testNewFolder(): void {
$result = $this->simpleFolder->newFolder('folder');
$this->assertInstanceOf(ISimpleFolder::class, $result);
$result->newFile('file');
diff --git a/tests/lib/Files/Storage/CommonTest.php b/tests/lib/Files/Storage/CommonTest.php
index 321894cc23b..b51b35be8f9 100644
--- a/tests/lib/Files/Storage/CommonTest.php
+++ b/tests/lib/Files/Storage/CommonTest.php
@@ -42,7 +42,7 @@ class CommonTest extends Storage {
parent::tearDown();
}
- public function testVerifyPath() {
+ public function testVerifyPath(): void {
$this->filenameValidator
->expects($this->once())
->method('validateFilename')
@@ -53,7 +53,7 @@ class CommonTest extends Storage {
$this->instance->verifyPath('/', 'invalid:char.txt');
}
- public function testVerifyPathSucceed() {
+ public function testVerifyPathSucceed(): void {
$this->filenameValidator
->expects($this->once())
->method('validateFilename')
@@ -62,7 +62,7 @@ class CommonTest extends Storage {
$this->instance->verifyPath('/', 'valid-char.txt');
}
- public function testMoveFromStorageWrapped() {
+ public function testMoveFromStorageWrapped(): void {
/** @var \OC\Files\Storage\CommonTest|MockObject $instance */
$instance = $this->getMockBuilder(\OC\Files\Storage\CommonTest::class)
->onlyMethods(['copyFromStorage', 'rmdir', 'unlink'])
@@ -80,7 +80,7 @@ class CommonTest extends Storage {
$this->assertTrue($instance->file_exists('bar.txt'));
}
- public function testMoveFromStorageJailed() {
+ public function testMoveFromStorageJailed(): void {
/** @var \OC\Files\Storage\CommonTest|MockObject $instance */
$instance = $this->getMockBuilder(\OC\Files\Storage\CommonTest::class)
->onlyMethods(['copyFromStorage', 'rmdir', 'unlink'])
@@ -103,7 +103,7 @@ class CommonTest extends Storage {
$this->assertTrue($instance->file_exists('bar.txt'));
}
- public function testMoveFromStorageNestedJail() {
+ public function testMoveFromStorageNestedJail(): void {
/** @var \OC\Files\Storage\CommonTest|MockObject $instance */
$instance = $this->getMockBuilder(\OC\Files\Storage\CommonTest::class)
->onlyMethods(['copyFromStorage', 'rmdir', 'unlink'])
diff --git a/tests/lib/Files/Storage/HomeTest.php b/tests/lib/Files/Storage/HomeTest.php
index ca2c1a797af..5026b3087bb 100644
--- a/tests/lib/Files/Storage/HomeTest.php
+++ b/tests/lib/Files/Storage/HomeTest.php
@@ -1,86 +1,86 @@
-<?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\Files\Storage;
-
-use OC\User\User;
-
-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 getHome() {
- return $this->home;
- }
-
- public function getUID() {
- return $this->uid;
- }
-}
-
-/**
- * Class Home
- *
- * @group DB
- *
- * @package Test\Files\Storage
- */
-class HomeTest extends Storage {
- /**
- * @var string tmpDir
- */
- private $tmpDir;
-
- private $userId;
-
- /**
- * @var \OC\User\User $user
- */
- private $user;
-
- protected function setUp(): void {
- parent::setUp();
-
- $this->tmpDir = \OC::$server->getTempManager()->getTemporaryFolder();
- $this->userId = $this->getUniqueID('user_');
- $this->user = new DummyUser($this->userId, $this->tmpDir);
- $this->instance = new \OC\Files\Storage\Home(['user' => $this->user]);
- }
-
- protected function tearDown(): void {
- \OC_Helper::rmdirr($this->tmpDir);
- parent::tearDown();
- }
-
- /**
- * Tests that the home id is in the format home::user1
- */
- public function testId() {
- $this->assertEquals('home::' . $this->userId, $this->instance->getId());
- }
-
- /**
- * Tests that getCache() returns an instance of HomeCache
- */
- public function testGetCacheReturnsHomeCache() {
- $this->assertInstanceOf(\OC\Files\Cache\HomeCache::class, $this->instance->getCache());
- }
-
- public function testGetOwner() {
- $this->assertEquals($this->userId, $this->instance->getOwner(''));
- }
-}
+<?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\Files\Storage;
+
+use OC\User\User;
+
+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 getHome() {
+ return $this->home;
+ }
+
+ public function getUID() {
+ return $this->uid;
+ }
+}
+
+/**
+ * Class Home
+ *
+ * @group DB
+ *
+ * @package Test\Files\Storage
+ */
+class HomeTest extends Storage {
+ /**
+ * @var string tmpDir
+ */
+ private $tmpDir;
+
+ private $userId;
+
+ /**
+ * @var \OC\User\User $user
+ */
+ private $user;
+
+ protected function setUp(): void {
+ parent::setUp();
+
+ $this->tmpDir = \OC::$server->getTempManager()->getTemporaryFolder();
+ $this->userId = $this->getUniqueID('user_');
+ $this->user = new DummyUser($this->userId, $this->tmpDir);
+ $this->instance = new \OC\Files\Storage\Home(['user' => $this->user]);
+ }
+
+ protected function tearDown(): void {
+ \OC_Helper::rmdirr($this->tmpDir);
+ parent::tearDown();
+ }
+
+ /**
+ * Tests that the home id is in the format home::user1
+ */
+ public function testId(): void {
+ $this->assertEquals('home::' . $this->userId, $this->instance->getId());
+ }
+
+ /**
+ * Tests that getCache() returns an instance of HomeCache
+ */
+ public function testGetCacheReturnsHomeCache(): void {
+ $this->assertInstanceOf(\OC\Files\Cache\HomeCache::class, $this->instance->getCache());
+ }
+
+ public function testGetOwner(): void {
+ $this->assertEquals($this->userId, $this->instance->getOwner(''));
+ }
+}
diff --git a/tests/lib/Files/Storage/LocalTest.php b/tests/lib/Files/Storage/LocalTest.php
index efe5dd04e47..4a98970f233 100644
--- a/tests/lib/Files/Storage/LocalTest.php
+++ b/tests/lib/Files/Storage/LocalTest.php
@@ -32,14 +32,14 @@ class LocalTest extends Storage {
parent::tearDown();
}
- public function testStableEtag() {
+ public function testStableEtag(): void {
$this->instance->file_put_contents('test.txt', 'foobar');
$etag1 = $this->instance->getETag('test.txt');
$etag2 = $this->instance->getETag('test.txt');
$this->assertEquals($etag1, $etag2);
}
- public function testEtagChange() {
+ public function testEtagChange(): void {
$this->instance->file_put_contents('test.txt', 'foo');
$this->instance->touch('test.txt', time() - 2);
$etag1 = $this->instance->getETag('test.txt');
@@ -49,21 +49,21 @@ class LocalTest extends Storage {
}
- public function testInvalidArgumentsEmptyArray() {
+ public function testInvalidArgumentsEmptyArray(): void {
$this->expectException(\InvalidArgumentException::class);
new \OC\Files\Storage\Local([]);
}
- public function testInvalidArgumentsNoArray() {
+ public function testInvalidArgumentsNoArray(): void {
$this->expectException(\InvalidArgumentException::class);
new \OC\Files\Storage\Local(null);
}
- public function testDisallowSymlinksOutsideDatadir() {
+ public function testDisallowSymlinksOutsideDatadir(): void {
$this->expectException(\OCP\Files\ForbiddenException::class);
$subDir1 = $this->tmpDir . 'sub1';
@@ -79,7 +79,7 @@ class LocalTest extends Storage {
$storage->file_put_contents('sym/foo', 'bar');
}
- public function testDisallowSymlinksInsideDatadir() {
+ public function testDisallowSymlinksInsideDatadir(): void {
$subDir1 = $this->tmpDir . 'sub1';
$subDir2 = $this->tmpDir . 'sub1/sub2';
$sym = $this->tmpDir . 'sub1/sym';
@@ -94,21 +94,21 @@ class LocalTest extends Storage {
$this->addToAssertionCount(1);
}
- public function testWriteUmaskFilePutContents() {
+ public function testWriteUmaskFilePutContents(): void {
$oldMask = umask(0333);
$this->instance->file_put_contents('test.txt', 'sad');
umask($oldMask);
$this->assertTrue($this->instance->isUpdatable('test.txt'));
}
- public function testWriteUmaskMkdir() {
+ public function testWriteUmaskMkdir(): void {
$oldMask = umask(0333);
$this->instance->mkdir('test.txt');
umask($oldMask);
$this->assertTrue($this->instance->isUpdatable('test.txt'));
}
- public function testWriteUmaskFopen() {
+ public function testWriteUmaskFopen(): void {
$oldMask = umask(0333);
$handle = $this->instance->fopen('test.txt', 'w');
fwrite($handle, 'foo');
@@ -117,7 +117,7 @@ class LocalTest extends Storage {
$this->assertTrue($this->instance->isUpdatable('test.txt'));
}
- public function testWriteUmaskCopy() {
+ public function testWriteUmaskCopy(): void {
$this->instance->file_put_contents('source.txt', 'sad');
$oldMask = umask(0333);
$this->instance->copy('source.txt', 'test.txt');
@@ -125,12 +125,12 @@ class LocalTest extends Storage {
$this->assertTrue($this->instance->isUpdatable('test.txt'));
}
- public function testUnavailableExternal() {
+ public function testUnavailableExternal(): void {
$this->expectException(\OCP\Files\StorageNotAvailableException::class);
$this->instance = new \OC\Files\Storage\Local(['datadir' => $this->tmpDir . '/unexist', 'isExternal' => true]);
}
- public function testUnavailableNonExternal() {
+ public function testUnavailableNonExternal(): void {
$this->instance = new \OC\Files\Storage\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 584be1d4e96..18cd34a78cf 100644
--- a/tests/lib/Files/Storage/Storage.php
+++ b/tests/lib/Files/Storage/Storage.php
@@ -1,667 +1,667 @@
-<?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\Files\Storage;
-
-use OC\Files\Cache\Watcher;
-use OCP\Files\Storage\IWriteStreamStorage;
-
-abstract class Storage extends \Test\TestCase {
- /**
- * @var \OC\Files\Storage\Storage instance
- */
- protected $instance;
- protected $waitDelay = 0;
-
- /**
- * Sleep for the number of seconds specified in the
- * $waitDelay attribute
- */
- protected function wait() {
- if ($this->waitDelay > 0) {
- sleep($this->waitDelay);
- }
- }
-
- /**
- * the root folder of the storage should always exist, be readable and be recognized as a directory
- */
- public function testRoot() {
- $this->assertTrue($this->instance->file_exists('/'), 'Root folder does not exist');
- $this->assertTrue($this->instance->isReadable('/'), 'Root folder is not readable');
- $this->assertTrue($this->instance->is_dir('/'), 'Root folder is not a directory');
- $this->assertFalse($this->instance->is_file('/'), 'Root folder is a file');
- $this->assertEquals('dir', $this->instance->filetype('/'));
-
- //without this, any further testing would be useless, not an actual requirement for filestorage though
- $this->assertTrue($this->instance->isUpdatable('/'), 'Root folder is not writable');
- }
-
- /**
- * Check that the test() function works
- */
- public function testTestFunction() {
- $this->assertTrue($this->instance->test());
- }
-
- /**
- * @dataProvider directoryProvider
- */
- public function testDirectories($directory) {
- $this->assertFalse($this->instance->file_exists('/' . $directory));
-
- $this->assertTrue($this->instance->mkdir('/' . $directory));
-
- $this->assertTrue($this->instance->file_exists('/' . $directory));
- $this->assertTrue($this->instance->is_dir('/' . $directory));
- $this->assertFalse($this->instance->is_file('/' . $directory));
- $this->assertEquals('dir', $this->instance->filetype('/' . $directory));
- $this->assertEquals(0, $this->instance->filesize('/' . $directory));
- $this->assertTrue($this->instance->isReadable('/' . $directory));
- $this->assertTrue($this->instance->isUpdatable('/' . $directory));
-
- $dh = $this->instance->opendir('/');
- $content = [];
- while (($file = readdir($dh)) !== false) {
- if ($file != '.' and $file != '..') {
- $content[] = $file;
- }
- }
- $this->assertEquals([$directory], $content);
-
- $content = iterator_to_array($this->instance->getDirectoryContent('/'));
-
- $this->assertCount(1, $content);
- $dirEntry = $content[0];
- unset($dirEntry['scan_permissions']);
- unset($dirEntry['etag']);
- $this->assertLessThanOrEqual(1, abs($dirEntry['mtime'] - $this->instance->filemtime($directory)));
- unset($dirEntry['mtime']);
- unset($dirEntry['storage_mtime']);
- $this->assertEquals([
- 'name' => $directory,
- 'mimetype' => $this->instance->getMimeType($directory),
- 'size' => -1,
- 'permissions' => $this->instance->getPermissions($directory),
- ], $dirEntry);
-
- $this->assertFalse($this->instance->mkdir('/' . $directory)); //can't create existing folders
- $this->assertTrue($this->instance->rmdir('/' . $directory));
-
- $this->wait();
- $this->assertFalse($this->instance->file_exists('/' . $directory));
-
- $this->assertFalse($this->instance->rmdir('/' . $directory)); //can't remove non existing folders
-
- $dh = $this->instance->opendir('/');
- $content = [];
- while (($file = readdir($dh)) !== false) {
- if ($file != '.' and $file != '..') {
- $content[] = $file;
- }
- }
- $this->assertEquals([], $content);
- }
-
- public function fileNameProvider() {
- return [
- ['file.txt'],
- [' file.txt'],
- ['folder .txt'],
- ['file with space.txt'],
- ['spéciäl fäile'],
- ['test single\'quote.txt'],
- ];
- }
-
- public function directoryProvider() {
- return [
- ['folder'],
- [' folder'],
- ['folder '],
- ['folder with space'],
- ['spéciäl földer'],
- ['test single\'quote'],
- ];
- }
-
- public function loremFileProvider() {
- $root = \OC::$SERVERROOT . '/tests/data/';
- return [
- // small file
- [$root . 'lorem.txt'],
- // bigger file (> 8 KB which is the standard PHP block size)
- [$root . 'lorem-big.txt']
- ];
- }
-
- /**
- * test the various uses of file_get_contents and file_put_contents
- *
- * @dataProvider loremFileProvider
- */
- public function testGetPutContents($sourceFile) {
- $sourceText = file_get_contents($sourceFile);
-
- //fill a file with string data
- $this->instance->file_put_contents('/lorem.txt', $sourceText);
- $this->assertFalse($this->instance->is_dir('/lorem.txt'));
- $this->assertEquals($sourceText, $this->instance->file_get_contents('/lorem.txt'), 'data returned from file_get_contents is not equal to the source data');
-
- //empty the file
- $this->instance->file_put_contents('/lorem.txt', '');
- $this->assertEquals('', $this->instance->file_get_contents('/lorem.txt'), 'file not emptied');
- }
-
- /**
- * test various known mimetypes
- */
- public function testMimeType() {
- $this->assertEquals('httpd/unix-directory', $this->instance->getMimeType('/'));
- $this->assertEquals(false, $this->instance->getMimeType('/non/existing/file'));
-
- $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
- $this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile, 'r'));
- $this->assertEquals('text/plain', $this->instance->getMimeType('/lorem.txt'));
-
- $pngFile = \OC::$SERVERROOT . '/tests/data/desktopapp.png';
- $this->instance->file_put_contents('/desktopapp.png', file_get_contents($pngFile, 'r'));
- $this->assertEquals('image/png', $this->instance->getMimeType('/desktopapp.png'));
-
- $svgFile = \OC::$SERVERROOT . '/tests/data/desktopapp.svg';
- $this->instance->file_put_contents('/desktopapp.svg', file_get_contents($svgFile, 'r'));
- $this->assertEquals('image/svg+xml', $this->instance->getMimeType('/desktopapp.svg'));
- }
-
-
- public function copyAndMoveProvider() {
- return [
- ['/source.txt', '/target.txt'],
- ['/source.txt', '/target with space.txt'],
- ['/source with space.txt', '/target.txt'],
- ['/source with space.txt', '/target with space.txt'],
- ['/source.txt', '/tärgét.txt'],
- ['/sòurcē.txt', '/target.txt'],
- ['/sòurcē.txt', '/tärgét.txt'],
- ['/single \' quote.txt', '/tar\'get.txt'],
- ];
- }
-
- public function initSourceAndTarget($source, $target = null) {
- $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
- $this->instance->file_put_contents($source, file_get_contents($textFile));
- if ($target) {
- $testContents = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
- $this->instance->file_put_contents($target, $testContents);
- }
- }
-
- public function assertSameAsLorem($file) {
- $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
- $this->assertEquals(
- file_get_contents($textFile),
- $this->instance->file_get_contents($file),
- 'Expected ' . $file . ' to be a copy of ' . $textFile
- );
- }
-
- /**
- * @dataProvider copyAndMoveProvider
- */
- public function testCopy($source, $target) {
- $this->initSourceAndTarget($source);
-
- $this->instance->copy($source, $target);
-
- $this->assertTrue($this->instance->file_exists($target), $target . ' was not created');
- $this->assertSameAsLorem($target);
- $this->assertTrue($this->instance->file_exists($source), $source . ' was deleted');
- }
-
- /**
- * @dataProvider copyAndMoveProvider
- */
- public function testMove($source, $target) {
- $this->initSourceAndTarget($source);
-
- $this->instance->rename($source, $target);
-
- $this->wait();
- $this->assertTrue($this->instance->file_exists($target), $target . ' was not created');
- $this->assertFalse($this->instance->file_exists($source), $source . ' still exists');
- $this->assertSameAsLorem($target);
- }
-
- /**
- * @dataProvider copyAndMoveProvider
- */
- public function testCopyOverwrite($source, $target) {
- $this->initSourceAndTarget($source, $target);
-
- $this->instance->copy($source, $target);
-
- $this->assertTrue($this->instance->file_exists($target), $target . ' was not created');
- $this->assertTrue($this->instance->file_exists($source), $source . ' was deleted');
- $this->assertSameAsLorem($target);
- $this->assertSameAsLorem($source);
- }
-
- /**
- * @dataProvider copyAndMoveProvider
- */
- public function testMoveOverwrite($source, $target) {
- $this->initSourceAndTarget($source, $target);
-
- $this->instance->rename($source, $target);
-
- $this->assertTrue($this->instance->file_exists($target), $target . ' was not created');
- $this->assertFalse($this->instance->file_exists($source), $source . ' still exists');
- $this->assertSameAsLorem($target);
- }
-
- public function testLocal() {
- $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
- $this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile));
- $localFile = $this->instance->getLocalFile('/lorem.txt');
- $this->assertTrue(file_exists($localFile));
- $this->assertEquals(file_get_contents($textFile), file_get_contents($localFile));
-
- $this->instance->mkdir('/folder');
- $this->instance->file_put_contents('/folder/lorem.txt', file_get_contents($textFile));
- $this->instance->file_put_contents('/folder/bar.txt', 'asd');
- $this->instance->mkdir('/folder/recursive');
- $this->instance->file_put_contents('/folder/recursive/file.txt', 'foo');
-
- // test below require to use instance->getLocalFile because the physical storage might be different
- $localFile = $this->instance->getLocalFile('/folder/lorem.txt');
- $this->assertTrue(file_exists($localFile));
- $this->assertEquals(file_get_contents($localFile), file_get_contents($textFile));
-
- $localFile = $this->instance->getLocalFile('/folder/bar.txt');
- $this->assertTrue(file_exists($localFile));
- $this->assertEquals(file_get_contents($localFile), 'asd');
-
- $localFile = $this->instance->getLocalFile('/folder/recursive/file.txt');
- $this->assertTrue(file_exists($localFile));
- $this->assertEquals(file_get_contents($localFile), 'foo');
- }
-
- public function testStat() {
- $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
- $ctimeStart = time();
- $this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile));
- $this->assertTrue($this->instance->isReadable('/lorem.txt'));
- $ctimeEnd = time();
- $mTime = $this->instance->filemtime('/lorem.txt');
- $this->assertTrue($this->instance->hasUpdated('/lorem.txt', $ctimeStart - 5));
- $this->assertTrue($this->instance->hasUpdated('/', $ctimeStart - 5));
-
- // check that ($ctimeStart - 5) <= $mTime <= ($ctimeEnd + 1)
- $this->assertGreaterThanOrEqual(($ctimeStart - 5), $mTime);
- $this->assertLessThanOrEqual(($ctimeEnd + 1), $mTime);
- $this->assertEquals(filesize($textFile), $this->instance->filesize('/lorem.txt'));
-
- $stat = $this->instance->stat('/lorem.txt');
- //only size and mtime are required in the result
- $this->assertEquals($stat['size'], $this->instance->filesize('/lorem.txt'));
- $this->assertEquals($stat['mtime'], $mTime);
-
- if ($this->instance->touch('/lorem.txt', 100) !== false) {
- $mTime = $this->instance->filemtime('/lorem.txt');
- $this->assertEquals($mTime, 100);
- }
-
- $mtimeStart = time();
-
- $this->instance->unlink('/lorem.txt');
- $this->assertTrue($this->instance->hasUpdated('/', $mtimeStart - 5));
- }
-
- /**
- * Test whether checkUpdate properly returns false when there was
- * no change.
- */
- public function testCheckUpdate() {
- if ($this->instance instanceof \OC\Files\Storage\Wrapper\Wrapper) {
- $this->markTestSkipped('Cannot test update check on wrappers');
- }
- $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
- $watcher = $this->instance->getWatcher();
- $watcher->setPolicy(Watcher::CHECK_ALWAYS);
- $this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile));
- $this->assertTrue($watcher->checkUpdate('/lorem.txt'), 'Update detected');
- $this->assertFalse($watcher->checkUpdate('/lorem.txt'), 'No update');
- }
-
- public function testUnlink() {
- $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
- $this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile));
-
- $this->assertTrue($this->instance->file_exists('/lorem.txt'));
-
- $this->assertTrue($this->instance->unlink('/lorem.txt'));
- $this->wait();
-
- $this->assertFalse($this->instance->file_exists('/lorem.txt'));
- }
-
- /**
- * @dataProvider fileNameProvider
- */
- public function testFOpen($fileName) {
- $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
-
- $fh = @$this->instance->fopen($fileName, 'r');
- if ($fh) {
- fclose($fh);
- }
- $this->assertFalse($fh);
- $this->assertFalse($this->instance->file_exists($fileName));
-
- $fh = $this->instance->fopen($fileName, 'w');
- fwrite($fh, file_get_contents($textFile));
- fclose($fh);
- $this->assertTrue($this->instance->file_exists($fileName));
-
- $fh = $this->instance->fopen($fileName, 'r');
- $content = stream_get_contents($fh);
- $this->assertEquals(file_get_contents($textFile), $content);
- }
-
- public function testTouchCreateFile() {
- $this->assertFalse($this->instance->file_exists('touch'));
- // returns true on success
- $this->assertTrue($this->instance->touch('touch'));
- $this->assertTrue($this->instance->file_exists('touch'));
- }
-
- public function testRecursiveRmdir() {
- $this->instance->mkdir('folder');
- $this->instance->mkdir('folder/bar');
- $this->wait();
- $this->instance->file_put_contents('folder/asd.txt', 'foobar');
- $this->instance->file_put_contents('folder/bar/foo.txt', 'asd');
- $this->assertTrue($this->instance->rmdir('folder'));
- $this->wait();
- $this->assertFalse($this->instance->file_exists('folder/asd.txt'));
- $this->assertFalse($this->instance->file_exists('folder/bar/foo.txt'));
- $this->assertFalse($this->instance->file_exists('folder/bar'));
- $this->assertFalse($this->instance->file_exists('folder'));
- }
-
- public function testRmdirEmptyFolder() {
- $this->assertTrue($this->instance->mkdir('empty'));
- $this->wait();
- $this->assertTrue($this->instance->rmdir('empty'));
- $this->assertFalse($this->instance->file_exists('empty'));
- }
-
- public function testRecursiveUnlink() {
- $this->instance->mkdir('folder');
- $this->instance->mkdir('folder/bar');
- $this->instance->file_put_contents('folder/asd.txt', 'foobar');
- $this->instance->file_put_contents('folder/bar/foo.txt', 'asd');
- $this->assertTrue($this->instance->unlink('folder'));
- $this->wait();
- $this->assertFalse($this->instance->file_exists('folder/asd.txt'));
- $this->assertFalse($this->instance->file_exists('folder/bar/foo.txt'));
- $this->assertFalse($this->instance->file_exists('folder/bar'));
- $this->assertFalse($this->instance->file_exists('folder'));
- }
-
- public function hashProvider() {
- return [
- ['Foobar', 'md5'],
- ['Foobar', 'sha1'],
- ['Foobar', 'sha256'],
- ];
- }
-
- /**
- * @dataProvider hashProvider
- */
- public function testHash($data, $type) {
- $this->instance->file_put_contents('hash.txt', $data);
- $this->assertEquals(hash($type, $data), $this->instance->hash($type, 'hash.txt'));
- $this->assertEquals(hash($type, $data, true), $this->instance->hash($type, 'hash.txt', true));
- }
-
- public function testHashInFileName() {
- $this->instance->file_put_contents('#test.txt', 'data');
- $this->assertEquals('data', $this->instance->file_get_contents('#test.txt'));
-
- $this->instance->mkdir('#foo');
- $this->instance->file_put_contents('#foo/test.txt', 'data');
- $this->assertEquals('data', $this->instance->file_get_contents('#foo/test.txt'));
-
- $dh = $this->instance->opendir('#foo');
- $content = [];
- while ($file = readdir($dh)) {
- if ($file != '.' and $file != '..') {
- $content[] = $file;
- }
- }
-
- $this->assertEquals(['test.txt'], $content);
- }
-
- public function testCopyOverWriteFile() {
- $this->instance->file_put_contents('target.txt', 'foo');
- $this->instance->file_put_contents('source.txt', 'bar');
- $this->instance->copy('source.txt', 'target.txt');
- $this->assertEquals('bar', $this->instance->file_get_contents('target.txt'));
- }
-
- public function testRenameOverWriteFile() {
- $this->instance->file_put_contents('target.txt', 'foo');
- $this->instance->file_put_contents('source.txt', 'bar');
- $this->instance->rename('source.txt', 'target.txt');
- $this->assertEquals('bar', $this->instance->file_get_contents('target.txt'));
- $this->assertFalse($this->instance->file_exists('source.txt'));
- }
-
- public function testRenameDirectory() {
- $this->instance->mkdir('source');
- $this->instance->file_put_contents('source/test1.txt', 'foo');
- $this->instance->file_put_contents('source/test2.txt', 'qwerty');
- $this->instance->mkdir('source/subfolder');
- $this->instance->file_put_contents('source/subfolder/test.txt', 'bar');
- $this->instance->rename('source', 'target');
-
- $this->assertFalse($this->instance->file_exists('source'));
- $this->assertFalse($this->instance->file_exists('source/test1.txt'));
- $this->assertFalse($this->instance->file_exists('source/test2.txt'));
- $this->assertFalse($this->instance->file_exists('source/subfolder'));
- $this->assertFalse($this->instance->file_exists('source/subfolder/test.txt'));
-
- $this->assertTrue($this->instance->file_exists('target'));
- $this->assertTrue($this->instance->file_exists('target/test1.txt'));
- $this->assertTrue($this->instance->file_exists('target/test2.txt'));
- $this->assertTrue($this->instance->file_exists('target/subfolder'));
- $this->assertTrue($this->instance->file_exists('target/subfolder/test.txt'));
-
- $contents = iterator_to_array($this->instance->getDirectoryContent(''));
- $this->assertCount(1, $contents);
-
- $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt'));
- $this->assertEquals('qwerty', $this->instance->file_get_contents('target/test2.txt'));
- $this->assertEquals('bar', $this->instance->file_get_contents('target/subfolder/test.txt'));
- }
-
- public function testRenameOverWriteDirectory() {
- $this->instance->mkdir('source');
- $this->instance->file_put_contents('source/test1.txt', 'foo');
-
- $this->instance->mkdir('target');
- $this->instance->file_put_contents('target/test1.txt', 'bar');
- $this->instance->file_put_contents('target/test2.txt', 'bar');
-
- $this->assertTrue($this->instance->rename('source', 'target'), 'rename must return true on success');
-
- $this->assertFalse($this->instance->file_exists('source'), 'source has not been removed');
- $this->assertFalse($this->instance->file_exists('source/test1.txt'), 'source/test1.txt has not been removed');
- $this->assertFalse($this->instance->file_exists('target/test2.txt'), 'target/test2.txt has not been removed');
- $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt'), 'target/test1.txt has not been overwritten');
- }
-
- public function testRenameOverWriteDirectoryOverFile() {
- $this->instance->mkdir('source');
- $this->instance->file_put_contents('source/test1.txt', 'foo');
-
- $this->instance->file_put_contents('target', 'bar');
-
- $this->assertTrue($this->instance->rename('source', 'target'), 'rename must return true on success');
-
- $this->assertFalse($this->instance->file_exists('source'));
- $this->assertFalse($this->instance->file_exists('source/test1.txt'));
- $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt'));
- }
-
- public function testCopyDirectory() {
- $this->instance->mkdir('source');
- $this->instance->file_put_contents('source/test1.txt', 'foo');
- $this->instance->file_put_contents('source/test2.txt', 'qwerty');
- $this->instance->mkdir('source/subfolder');
- $this->instance->file_put_contents('source/subfolder/test.txt', 'bar');
- $this->instance->copy('source', 'target');
-
- $this->assertTrue($this->instance->file_exists('source'));
- $this->assertTrue($this->instance->file_exists('source/test1.txt'));
- $this->assertTrue($this->instance->file_exists('source/test2.txt'));
- $this->assertTrue($this->instance->file_exists('source/subfolder'));
- $this->assertTrue($this->instance->file_exists('source/subfolder/test.txt'));
-
- $this->assertTrue($this->instance->file_exists('target'));
- $this->assertTrue($this->instance->file_exists('target/test1.txt'));
- $this->assertTrue($this->instance->file_exists('target/test2.txt'));
- $this->assertTrue($this->instance->file_exists('target/subfolder'));
- $this->assertTrue($this->instance->file_exists('target/subfolder/test.txt'));
-
- $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt'));
- $this->assertEquals('qwerty', $this->instance->file_get_contents('target/test2.txt'));
- $this->assertEquals('bar', $this->instance->file_get_contents('target/subfolder/test.txt'));
- }
-
- public function testCopyOverWriteDirectory() {
- $this->instance->mkdir('source');
- $this->instance->file_put_contents('source/test1.txt', 'foo');
-
- $this->instance->mkdir('target');
- $this->instance->file_put_contents('target/test1.txt', 'bar');
- $this->instance->file_put_contents('target/test2.txt', 'bar');
-
- $this->instance->copy('source', 'target');
-
- $this->assertFalse($this->instance->file_exists('target/test2.txt'));
- $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt'));
- }
-
- public function testCopyOverWriteDirectoryOverFile() {
- $this->instance->mkdir('source');
- $this->instance->file_put_contents('source/test1.txt', 'foo');
-
- $this->instance->file_put_contents('target', 'bar');
-
- $this->instance->copy('source', 'target');
-
- $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt'));
- }
-
- public function testInstanceOfStorage() {
- $this->assertTrue($this->instance->instanceOfStorage(\OCP\Files\Storage::class));
- $this->assertTrue($this->instance->instanceOfStorage(get_class($this->instance)));
- $this->assertFalse($this->instance->instanceOfStorage('\OC'));
- }
-
- /**
- * @dataProvider copyAndMoveProvider
- */
- public function testCopyFromSameStorage($source, $target) {
- $this->initSourceAndTarget($source);
-
- $this->instance->copyFromStorage($this->instance, $source, $target);
-
- $this->assertTrue($this->instance->file_exists($target), $target . ' was not created');
- $this->assertSameAsLorem($target);
- $this->assertTrue($this->instance->file_exists($source), $source . ' was deleted');
- }
-
- public function testIsCreatable() {
- $this->instance->mkdir('source');
- $this->assertTrue($this->instance->isCreatable('source'));
- }
-
- public function testIsReadable() {
- $this->instance->mkdir('source');
- $this->assertTrue($this->instance->isReadable('source'));
- }
-
- public function testIsUpdatable() {
- $this->instance->mkdir('source');
- $this->assertTrue($this->instance->isUpdatable('source'));
- }
-
- public function testIsDeletable() {
- $this->instance->mkdir('source');
- $this->assertTrue($this->instance->isDeletable('source'));
- }
-
- public function testIsShareable() {
- $this->instance->mkdir('source');
- $this->assertTrue($this->instance->isSharable('source'));
- }
-
- public function testStatAfterWrite() {
- $this->instance->file_put_contents('foo.txt', 'bar');
- $stat = $this->instance->stat('foo.txt');
- $this->assertEquals(3, $stat['size']);
-
- $fh = $this->instance->fopen('foo.txt', 'w');
- fwrite($fh, 'qwerty');
- fclose($fh);
-
- $stat = $this->instance->stat('foo.txt');
- $this->assertEquals(6, $stat['size']);
- }
-
- public function testPartFile() {
- $this->instance->file_put_contents('bar.txt.part', 'bar');
- $this->instance->rename('bar.txt.part', 'bar.txt');
- $this->assertEquals('bar', $this->instance->file_get_contents('bar.txt'));
- }
-
- public function testWriteStream() {
- $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
-
- if (!$this->instance->instanceOfStorage(IWriteStreamStorage::class)) {
- $this->markTestSkipped('Not a WriteSteamStorage');
- }
- /** @var IWriteStreamStorage $storage */
- $storage = $this->instance;
-
- $source = fopen($textFile, 'r');
-
- $storage->writeStream('test.txt', $source);
- $this->assertTrue($storage->file_exists('test.txt'));
- $this->assertStringEqualsFile($textFile, $storage->file_get_contents('test.txt'));
- $this->assertEquals('resource (closed)', gettype($source));
- }
-
- public function testFseekSize() {
- $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
- $this->instance->file_put_contents('bar.txt', file_get_contents($textFile));
-
- $size = $this->instance->filesize('bar.txt');
- $this->assertEquals(filesize($textFile), $size);
- $fh = $this->instance->fopen('bar.txt', 'r');
-
- fseek($fh, 0, SEEK_END);
- $pos = ftell($fh);
-
- $this->assertEquals($size, $pos);
- }
-}
+<?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\Files\Storage;
+
+use OC\Files\Cache\Watcher;
+use OCP\Files\Storage\IWriteStreamStorage;
+
+abstract class Storage extends \Test\TestCase {
+ /**
+ * @var \OC\Files\Storage\Storage instance
+ */
+ protected $instance;
+ protected $waitDelay = 0;
+
+ /**
+ * Sleep for the number of seconds specified in the
+ * $waitDelay attribute
+ */
+ protected function wait() {
+ if ($this->waitDelay > 0) {
+ sleep($this->waitDelay);
+ }
+ }
+
+ /**
+ * the root folder of the storage should always exist, be readable and be recognized as a directory
+ */
+ public function testRoot(): void {
+ $this->assertTrue($this->instance->file_exists('/'), 'Root folder does not exist');
+ $this->assertTrue($this->instance->isReadable('/'), 'Root folder is not readable');
+ $this->assertTrue($this->instance->is_dir('/'), 'Root folder is not a directory');
+ $this->assertFalse($this->instance->is_file('/'), 'Root folder is a file');
+ $this->assertEquals('dir', $this->instance->filetype('/'));
+
+ //without this, any further testing would be useless, not an actual requirement for filestorage though
+ $this->assertTrue($this->instance->isUpdatable('/'), 'Root folder is not writable');
+ }
+
+ /**
+ * Check that the test() function works
+ */
+ public function testTestFunction(): void {
+ $this->assertTrue($this->instance->test());
+ }
+
+ /**
+ * @dataProvider directoryProvider
+ */
+ public function testDirectories($directory): void {
+ $this->assertFalse($this->instance->file_exists('/' . $directory));
+
+ $this->assertTrue($this->instance->mkdir('/' . $directory));
+
+ $this->assertTrue($this->instance->file_exists('/' . $directory));
+ $this->assertTrue($this->instance->is_dir('/' . $directory));
+ $this->assertFalse($this->instance->is_file('/' . $directory));
+ $this->assertEquals('dir', $this->instance->filetype('/' . $directory));
+ $this->assertEquals(0, $this->instance->filesize('/' . $directory));
+ $this->assertTrue($this->instance->isReadable('/' . $directory));
+ $this->assertTrue($this->instance->isUpdatable('/' . $directory));
+
+ $dh = $this->instance->opendir('/');
+ $content = [];
+ while (($file = readdir($dh)) !== false) {
+ if ($file != '.' and $file != '..') {
+ $content[] = $file;
+ }
+ }
+ $this->assertEquals([$directory], $content);
+
+ $content = iterator_to_array($this->instance->getDirectoryContent('/'));
+
+ $this->assertCount(1, $content);
+ $dirEntry = $content[0];
+ unset($dirEntry['scan_permissions']);
+ unset($dirEntry['etag']);
+ $this->assertLessThanOrEqual(1, abs($dirEntry['mtime'] - $this->instance->filemtime($directory)));
+ unset($dirEntry['mtime']);
+ unset($dirEntry['storage_mtime']);
+ $this->assertEquals([
+ 'name' => $directory,
+ 'mimetype' => $this->instance->getMimeType($directory),
+ 'size' => -1,
+ 'permissions' => $this->instance->getPermissions($directory),
+ ], $dirEntry);
+
+ $this->assertFalse($this->instance->mkdir('/' . $directory)); //can't create existing folders
+ $this->assertTrue($this->instance->rmdir('/' . $directory));
+
+ $this->wait();
+ $this->assertFalse($this->instance->file_exists('/' . $directory));
+
+ $this->assertFalse($this->instance->rmdir('/' . $directory)); //can't remove non existing folders
+
+ $dh = $this->instance->opendir('/');
+ $content = [];
+ while (($file = readdir($dh)) !== false) {
+ if ($file != '.' and $file != '..') {
+ $content[] = $file;
+ }
+ }
+ $this->assertEquals([], $content);
+ }
+
+ public function fileNameProvider() {
+ return [
+ ['file.txt'],
+ [' file.txt'],
+ ['folder .txt'],
+ ['file with space.txt'],
+ ['spéciäl fäile'],
+ ['test single\'quote.txt'],
+ ];
+ }
+
+ public function directoryProvider() {
+ return [
+ ['folder'],
+ [' folder'],
+ ['folder '],
+ ['folder with space'],
+ ['spéciäl földer'],
+ ['test single\'quote'],
+ ];
+ }
+
+ public function loremFileProvider() {
+ $root = \OC::$SERVERROOT . '/tests/data/';
+ return [
+ // small file
+ [$root . 'lorem.txt'],
+ // bigger file (> 8 KB which is the standard PHP block size)
+ [$root . 'lorem-big.txt']
+ ];
+ }
+
+ /**
+ * test the various uses of file_get_contents and file_put_contents
+ *
+ * @dataProvider loremFileProvider
+ */
+ public function testGetPutContents($sourceFile): void {
+ $sourceText = file_get_contents($sourceFile);
+
+ //fill a file with string data
+ $this->instance->file_put_contents('/lorem.txt', $sourceText);
+ $this->assertFalse($this->instance->is_dir('/lorem.txt'));
+ $this->assertEquals($sourceText, $this->instance->file_get_contents('/lorem.txt'), 'data returned from file_get_contents is not equal to the source data');
+
+ //empty the file
+ $this->instance->file_put_contents('/lorem.txt', '');
+ $this->assertEquals('', $this->instance->file_get_contents('/lorem.txt'), 'file not emptied');
+ }
+
+ /**
+ * test various known mimetypes
+ */
+ public function testMimeType(): void {
+ $this->assertEquals('httpd/unix-directory', $this->instance->getMimeType('/'));
+ $this->assertEquals(false, $this->instance->getMimeType('/non/existing/file'));
+
+ $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
+ $this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile, 'r'));
+ $this->assertEquals('text/plain', $this->instance->getMimeType('/lorem.txt'));
+
+ $pngFile = \OC::$SERVERROOT . '/tests/data/desktopapp.png';
+ $this->instance->file_put_contents('/desktopapp.png', file_get_contents($pngFile, 'r'));
+ $this->assertEquals('image/png', $this->instance->getMimeType('/desktopapp.png'));
+
+ $svgFile = \OC::$SERVERROOT . '/tests/data/desktopapp.svg';
+ $this->instance->file_put_contents('/desktopapp.svg', file_get_contents($svgFile, 'r'));
+ $this->assertEquals('image/svg+xml', $this->instance->getMimeType('/desktopapp.svg'));
+ }
+
+
+ public function copyAndMoveProvider() {
+ return [
+ ['/source.txt', '/target.txt'],
+ ['/source.txt', '/target with space.txt'],
+ ['/source with space.txt', '/target.txt'],
+ ['/source with space.txt', '/target with space.txt'],
+ ['/source.txt', '/tärgét.txt'],
+ ['/sòurcē.txt', '/target.txt'],
+ ['/sòurcē.txt', '/tärgét.txt'],
+ ['/single \' quote.txt', '/tar\'get.txt'],
+ ];
+ }
+
+ public function initSourceAndTarget($source, $target = null) {
+ $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
+ $this->instance->file_put_contents($source, file_get_contents($textFile));
+ if ($target) {
+ $testContents = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
+ $this->instance->file_put_contents($target, $testContents);
+ }
+ }
+
+ public function assertSameAsLorem($file) {
+ $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
+ $this->assertEquals(
+ file_get_contents($textFile),
+ $this->instance->file_get_contents($file),
+ 'Expected ' . $file . ' to be a copy of ' . $textFile
+ );
+ }
+
+ /**
+ * @dataProvider copyAndMoveProvider
+ */
+ public function testCopy($source, $target): void {
+ $this->initSourceAndTarget($source);
+
+ $this->instance->copy($source, $target);
+
+ $this->assertTrue($this->instance->file_exists($target), $target . ' was not created');
+ $this->assertSameAsLorem($target);
+ $this->assertTrue($this->instance->file_exists($source), $source . ' was deleted');
+ }
+
+ /**
+ * @dataProvider copyAndMoveProvider
+ */
+ public function testMove($source, $target): void {
+ $this->initSourceAndTarget($source);
+
+ $this->instance->rename($source, $target);
+
+ $this->wait();
+ $this->assertTrue($this->instance->file_exists($target), $target . ' was not created');
+ $this->assertFalse($this->instance->file_exists($source), $source . ' still exists');
+ $this->assertSameAsLorem($target);
+ }
+
+ /**
+ * @dataProvider copyAndMoveProvider
+ */
+ public function testCopyOverwrite($source, $target): void {
+ $this->initSourceAndTarget($source, $target);
+
+ $this->instance->copy($source, $target);
+
+ $this->assertTrue($this->instance->file_exists($target), $target . ' was not created');
+ $this->assertTrue($this->instance->file_exists($source), $source . ' was deleted');
+ $this->assertSameAsLorem($target);
+ $this->assertSameAsLorem($source);
+ }
+
+ /**
+ * @dataProvider copyAndMoveProvider
+ */
+ public function testMoveOverwrite($source, $target): void {
+ $this->initSourceAndTarget($source, $target);
+
+ $this->instance->rename($source, $target);
+
+ $this->assertTrue($this->instance->file_exists($target), $target . ' was not created');
+ $this->assertFalse($this->instance->file_exists($source), $source . ' still exists');
+ $this->assertSameAsLorem($target);
+ }
+
+ public function testLocal(): void {
+ $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
+ $this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile));
+ $localFile = $this->instance->getLocalFile('/lorem.txt');
+ $this->assertTrue(file_exists($localFile));
+ $this->assertEquals(file_get_contents($textFile), file_get_contents($localFile));
+
+ $this->instance->mkdir('/folder');
+ $this->instance->file_put_contents('/folder/lorem.txt', file_get_contents($textFile));
+ $this->instance->file_put_contents('/folder/bar.txt', 'asd');
+ $this->instance->mkdir('/folder/recursive');
+ $this->instance->file_put_contents('/folder/recursive/file.txt', 'foo');
+
+ // test below require to use instance->getLocalFile because the physical storage might be different
+ $localFile = $this->instance->getLocalFile('/folder/lorem.txt');
+ $this->assertTrue(file_exists($localFile));
+ $this->assertEquals(file_get_contents($localFile), file_get_contents($textFile));
+
+ $localFile = $this->instance->getLocalFile('/folder/bar.txt');
+ $this->assertTrue(file_exists($localFile));
+ $this->assertEquals(file_get_contents($localFile), 'asd');
+
+ $localFile = $this->instance->getLocalFile('/folder/recursive/file.txt');
+ $this->assertTrue(file_exists($localFile));
+ $this->assertEquals(file_get_contents($localFile), 'foo');
+ }
+
+ public function testStat(): void {
+ $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
+ $ctimeStart = time();
+ $this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile));
+ $this->assertTrue($this->instance->isReadable('/lorem.txt'));
+ $ctimeEnd = time();
+ $mTime = $this->instance->filemtime('/lorem.txt');
+ $this->assertTrue($this->instance->hasUpdated('/lorem.txt', $ctimeStart - 5));
+ $this->assertTrue($this->instance->hasUpdated('/', $ctimeStart - 5));
+
+ // check that ($ctimeStart - 5) <= $mTime <= ($ctimeEnd + 1)
+ $this->assertGreaterThanOrEqual(($ctimeStart - 5), $mTime);
+ $this->assertLessThanOrEqual(($ctimeEnd + 1), $mTime);
+ $this->assertEquals(filesize($textFile), $this->instance->filesize('/lorem.txt'));
+
+ $stat = $this->instance->stat('/lorem.txt');
+ //only size and mtime are required in the result
+ $this->assertEquals($stat['size'], $this->instance->filesize('/lorem.txt'));
+ $this->assertEquals($stat['mtime'], $mTime);
+
+ if ($this->instance->touch('/lorem.txt', 100) !== false) {
+ $mTime = $this->instance->filemtime('/lorem.txt');
+ $this->assertEquals($mTime, 100);
+ }
+
+ $mtimeStart = time();
+
+ $this->instance->unlink('/lorem.txt');
+ $this->assertTrue($this->instance->hasUpdated('/', $mtimeStart - 5));
+ }
+
+ /**
+ * Test whether checkUpdate properly returns false when there was
+ * no change.
+ */
+ public function testCheckUpdate(): void {
+ if ($this->instance instanceof \OC\Files\Storage\Wrapper\Wrapper) {
+ $this->markTestSkipped('Cannot test update check on wrappers');
+ }
+ $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
+ $watcher = $this->instance->getWatcher();
+ $watcher->setPolicy(Watcher::CHECK_ALWAYS);
+ $this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile));
+ $this->assertTrue($watcher->checkUpdate('/lorem.txt'), 'Update detected');
+ $this->assertFalse($watcher->checkUpdate('/lorem.txt'), 'No update');
+ }
+
+ public function testUnlink(): void {
+ $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
+ $this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile));
+
+ $this->assertTrue($this->instance->file_exists('/lorem.txt'));
+
+ $this->assertTrue($this->instance->unlink('/lorem.txt'));
+ $this->wait();
+
+ $this->assertFalse($this->instance->file_exists('/lorem.txt'));
+ }
+
+ /**
+ * @dataProvider fileNameProvider
+ */
+ public function testFOpen($fileName): void {
+ $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
+
+ $fh = @$this->instance->fopen($fileName, 'r');
+ if ($fh) {
+ fclose($fh);
+ }
+ $this->assertFalse($fh);
+ $this->assertFalse($this->instance->file_exists($fileName));
+
+ $fh = $this->instance->fopen($fileName, 'w');
+ fwrite($fh, file_get_contents($textFile));
+ fclose($fh);
+ $this->assertTrue($this->instance->file_exists($fileName));
+
+ $fh = $this->instance->fopen($fileName, 'r');
+ $content = stream_get_contents($fh);
+ $this->assertEquals(file_get_contents($textFile), $content);
+ }
+
+ public function testTouchCreateFile(): void {
+ $this->assertFalse($this->instance->file_exists('touch'));
+ // returns true on success
+ $this->assertTrue($this->instance->touch('touch'));
+ $this->assertTrue($this->instance->file_exists('touch'));
+ }
+
+ public function testRecursiveRmdir(): void {
+ $this->instance->mkdir('folder');
+ $this->instance->mkdir('folder/bar');
+ $this->wait();
+ $this->instance->file_put_contents('folder/asd.txt', 'foobar');
+ $this->instance->file_put_contents('folder/bar/foo.txt', 'asd');
+ $this->assertTrue($this->instance->rmdir('folder'));
+ $this->wait();
+ $this->assertFalse($this->instance->file_exists('folder/asd.txt'));
+ $this->assertFalse($this->instance->file_exists('folder/bar/foo.txt'));
+ $this->assertFalse($this->instance->file_exists('folder/bar'));
+ $this->assertFalse($this->instance->file_exists('folder'));
+ }
+
+ public function testRmdirEmptyFolder(): void {
+ $this->assertTrue($this->instance->mkdir('empty'));
+ $this->wait();
+ $this->assertTrue($this->instance->rmdir('empty'));
+ $this->assertFalse($this->instance->file_exists('empty'));
+ }
+
+ public function testRecursiveUnlink(): void {
+ $this->instance->mkdir('folder');
+ $this->instance->mkdir('folder/bar');
+ $this->instance->file_put_contents('folder/asd.txt', 'foobar');
+ $this->instance->file_put_contents('folder/bar/foo.txt', 'asd');
+ $this->assertTrue($this->instance->unlink('folder'));
+ $this->wait();
+ $this->assertFalse($this->instance->file_exists('folder/asd.txt'));
+ $this->assertFalse($this->instance->file_exists('folder/bar/foo.txt'));
+ $this->assertFalse($this->instance->file_exists('folder/bar'));
+ $this->assertFalse($this->instance->file_exists('folder'));
+ }
+
+ public function hashProvider() {
+ return [
+ ['Foobar', 'md5'],
+ ['Foobar', 'sha1'],
+ ['Foobar', 'sha256'],
+ ];
+ }
+
+ /**
+ * @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'));
+ $this->assertEquals(hash($type, $data, true), $this->instance->hash($type, 'hash.txt', true));
+ }
+
+ public function testHashInFileName(): void {
+ $this->instance->file_put_contents('#test.txt', 'data');
+ $this->assertEquals('data', $this->instance->file_get_contents('#test.txt'));
+
+ $this->instance->mkdir('#foo');
+ $this->instance->file_put_contents('#foo/test.txt', 'data');
+ $this->assertEquals('data', $this->instance->file_get_contents('#foo/test.txt'));
+
+ $dh = $this->instance->opendir('#foo');
+ $content = [];
+ while ($file = readdir($dh)) {
+ if ($file != '.' and $file != '..') {
+ $content[] = $file;
+ }
+ }
+
+ $this->assertEquals(['test.txt'], $content);
+ }
+
+ public function testCopyOverWriteFile(): void {
+ $this->instance->file_put_contents('target.txt', 'foo');
+ $this->instance->file_put_contents('source.txt', 'bar');
+ $this->instance->copy('source.txt', 'target.txt');
+ $this->assertEquals('bar', $this->instance->file_get_contents('target.txt'));
+ }
+
+ public function testRenameOverWriteFile(): void {
+ $this->instance->file_put_contents('target.txt', 'foo');
+ $this->instance->file_put_contents('source.txt', 'bar');
+ $this->instance->rename('source.txt', 'target.txt');
+ $this->assertEquals('bar', $this->instance->file_get_contents('target.txt'));
+ $this->assertFalse($this->instance->file_exists('source.txt'));
+ }
+
+ public function testRenameDirectory(): void {
+ $this->instance->mkdir('source');
+ $this->instance->file_put_contents('source/test1.txt', 'foo');
+ $this->instance->file_put_contents('source/test2.txt', 'qwerty');
+ $this->instance->mkdir('source/subfolder');
+ $this->instance->file_put_contents('source/subfolder/test.txt', 'bar');
+ $this->instance->rename('source', 'target');
+
+ $this->assertFalse($this->instance->file_exists('source'));
+ $this->assertFalse($this->instance->file_exists('source/test1.txt'));
+ $this->assertFalse($this->instance->file_exists('source/test2.txt'));
+ $this->assertFalse($this->instance->file_exists('source/subfolder'));
+ $this->assertFalse($this->instance->file_exists('source/subfolder/test.txt'));
+
+ $this->assertTrue($this->instance->file_exists('target'));
+ $this->assertTrue($this->instance->file_exists('target/test1.txt'));
+ $this->assertTrue($this->instance->file_exists('target/test2.txt'));
+ $this->assertTrue($this->instance->file_exists('target/subfolder'));
+ $this->assertTrue($this->instance->file_exists('target/subfolder/test.txt'));
+
+ $contents = iterator_to_array($this->instance->getDirectoryContent(''));
+ $this->assertCount(1, $contents);
+
+ $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt'));
+ $this->assertEquals('qwerty', $this->instance->file_get_contents('target/test2.txt'));
+ $this->assertEquals('bar', $this->instance->file_get_contents('target/subfolder/test.txt'));
+ }
+
+ public function testRenameOverWriteDirectory(): void {
+ $this->instance->mkdir('source');
+ $this->instance->file_put_contents('source/test1.txt', 'foo');
+
+ $this->instance->mkdir('target');
+ $this->instance->file_put_contents('target/test1.txt', 'bar');
+ $this->instance->file_put_contents('target/test2.txt', 'bar');
+
+ $this->assertTrue($this->instance->rename('source', 'target'), 'rename must return true on success');
+
+ $this->assertFalse($this->instance->file_exists('source'), 'source has not been removed');
+ $this->assertFalse($this->instance->file_exists('source/test1.txt'), 'source/test1.txt has not been removed');
+ $this->assertFalse($this->instance->file_exists('target/test2.txt'), 'target/test2.txt has not been removed');
+ $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt'), 'target/test1.txt has not been overwritten');
+ }
+
+ public function testRenameOverWriteDirectoryOverFile(): void {
+ $this->instance->mkdir('source');
+ $this->instance->file_put_contents('source/test1.txt', 'foo');
+
+ $this->instance->file_put_contents('target', 'bar');
+
+ $this->assertTrue($this->instance->rename('source', 'target'), 'rename must return true on success');
+
+ $this->assertFalse($this->instance->file_exists('source'));
+ $this->assertFalse($this->instance->file_exists('source/test1.txt'));
+ $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt'));
+ }
+
+ public function testCopyDirectory(): void {
+ $this->instance->mkdir('source');
+ $this->instance->file_put_contents('source/test1.txt', 'foo');
+ $this->instance->file_put_contents('source/test2.txt', 'qwerty');
+ $this->instance->mkdir('source/subfolder');
+ $this->instance->file_put_contents('source/subfolder/test.txt', 'bar');
+ $this->instance->copy('source', 'target');
+
+ $this->assertTrue($this->instance->file_exists('source'));
+ $this->assertTrue($this->instance->file_exists('source/test1.txt'));
+ $this->assertTrue($this->instance->file_exists('source/test2.txt'));
+ $this->assertTrue($this->instance->file_exists('source/subfolder'));
+ $this->assertTrue($this->instance->file_exists('source/subfolder/test.txt'));
+
+ $this->assertTrue($this->instance->file_exists('target'));
+ $this->assertTrue($this->instance->file_exists('target/test1.txt'));
+ $this->assertTrue($this->instance->file_exists('target/test2.txt'));
+ $this->assertTrue($this->instance->file_exists('target/subfolder'));
+ $this->assertTrue($this->instance->file_exists('target/subfolder/test.txt'));
+
+ $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt'));
+ $this->assertEquals('qwerty', $this->instance->file_get_contents('target/test2.txt'));
+ $this->assertEquals('bar', $this->instance->file_get_contents('target/subfolder/test.txt'));
+ }
+
+ public function testCopyOverWriteDirectory(): void {
+ $this->instance->mkdir('source');
+ $this->instance->file_put_contents('source/test1.txt', 'foo');
+
+ $this->instance->mkdir('target');
+ $this->instance->file_put_contents('target/test1.txt', 'bar');
+ $this->instance->file_put_contents('target/test2.txt', 'bar');
+
+ $this->instance->copy('source', 'target');
+
+ $this->assertFalse($this->instance->file_exists('target/test2.txt'));
+ $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt'));
+ }
+
+ public function testCopyOverWriteDirectoryOverFile(): void {
+ $this->instance->mkdir('source');
+ $this->instance->file_put_contents('source/test1.txt', 'foo');
+
+ $this->instance->file_put_contents('target', 'bar');
+
+ $this->instance->copy('source', 'target');
+
+ $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt'));
+ }
+
+ public function testInstanceOfStorage(): void {
+ $this->assertTrue($this->instance->instanceOfStorage(\OCP\Files\Storage::class));
+ $this->assertTrue($this->instance->instanceOfStorage(get_class($this->instance)));
+ $this->assertFalse($this->instance->instanceOfStorage('\OC'));
+ }
+
+ /**
+ * @dataProvider copyAndMoveProvider
+ */
+ public function testCopyFromSameStorage($source, $target): void {
+ $this->initSourceAndTarget($source);
+
+ $this->instance->copyFromStorage($this->instance, $source, $target);
+
+ $this->assertTrue($this->instance->file_exists($target), $target . ' was not created');
+ $this->assertSameAsLorem($target);
+ $this->assertTrue($this->instance->file_exists($source), $source . ' was deleted');
+ }
+
+ public function testIsCreatable(): void {
+ $this->instance->mkdir('source');
+ $this->assertTrue($this->instance->isCreatable('source'));
+ }
+
+ public function testIsReadable(): void {
+ $this->instance->mkdir('source');
+ $this->assertTrue($this->instance->isReadable('source'));
+ }
+
+ public function testIsUpdatable(): void {
+ $this->instance->mkdir('source');
+ $this->assertTrue($this->instance->isUpdatable('source'));
+ }
+
+ public function testIsDeletable(): void {
+ $this->instance->mkdir('source');
+ $this->assertTrue($this->instance->isDeletable('source'));
+ }
+
+ public function testIsShareable(): void {
+ $this->instance->mkdir('source');
+ $this->assertTrue($this->instance->isSharable('source'));
+ }
+
+ public function testStatAfterWrite(): void {
+ $this->instance->file_put_contents('foo.txt', 'bar');
+ $stat = $this->instance->stat('foo.txt');
+ $this->assertEquals(3, $stat['size']);
+
+ $fh = $this->instance->fopen('foo.txt', 'w');
+ fwrite($fh, 'qwerty');
+ fclose($fh);
+
+ $stat = $this->instance->stat('foo.txt');
+ $this->assertEquals(6, $stat['size']);
+ }
+
+ public function testPartFile(): void {
+ $this->instance->file_put_contents('bar.txt.part', 'bar');
+ $this->instance->rename('bar.txt.part', 'bar.txt');
+ $this->assertEquals('bar', $this->instance->file_get_contents('bar.txt'));
+ }
+
+ public function testWriteStream(): void {
+ $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
+
+ if (!$this->instance->instanceOfStorage(IWriteStreamStorage::class)) {
+ $this->markTestSkipped('Not a WriteSteamStorage');
+ }
+ /** @var IWriteStreamStorage $storage */
+ $storage = $this->instance;
+
+ $source = fopen($textFile, 'r');
+
+ $storage->writeStream('test.txt', $source);
+ $this->assertTrue($storage->file_exists('test.txt'));
+ $this->assertStringEqualsFile($textFile, $storage->file_get_contents('test.txt'));
+ $this->assertEquals('resource (closed)', gettype($source));
+ }
+
+ public function testFseekSize(): void {
+ $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
+ $this->instance->file_put_contents('bar.txt', file_get_contents($textFile));
+
+ $size = $this->instance->filesize('bar.txt');
+ $this->assertEquals(filesize($textFile), $size);
+ $fh = $this->instance->fopen('bar.txt', 'r');
+
+ fseek($fh, 0, SEEK_END);
+ $pos = ftell($fh);
+
+ $this->assertEquals($size, $pos);
+ }
+}
diff --git a/tests/lib/Files/Storage/StorageFactoryTest.php b/tests/lib/Files/Storage/StorageFactoryTest.php
index 1114a48b80f..2d9e45dfdfc 100644
--- a/tests/lib/Files/Storage/StorageFactoryTest.php
+++ b/tests/lib/Files/Storage/StorageFactoryTest.php
@@ -25,7 +25,7 @@ class DummyWrapper extends Wrapper {
}
class StorageFactoryTest extends TestCase {
- public function testSimpleWrapper() {
+ public function testSimpleWrapper(): void {
$instance = new \OC\Files\Storage\StorageFactory();
$mount = new MountPoint(\OC\Files\Storage\Temporary::class, '/foo', [[]], $instance);
$instance->addStorageWrapper('dummy', function ($mountPoint, IStorage $storage, IMountPoint $mount) {
@@ -38,7 +38,7 @@ class StorageFactoryTest extends TestCase {
$this->assertInstanceOf(\Test\Files\Storage\DummyWrapper::class, $wrapped);
}
- public function testRemoveWrapper() {
+ public function testRemoveWrapper(): void {
$instance = new \OC\Files\Storage\StorageFactory();
$mount = new MountPoint(\OC\Files\Storage\Temporary::class, '/foo', [[]], $instance);
$instance->addStorageWrapper('dummy', function ($mountPoint, IStorage $storage) {
@@ -49,7 +49,7 @@ class StorageFactoryTest extends TestCase {
$this->assertInstanceOf(\OC\Files\Storage\Temporary::class, $wrapped);
}
- public function testWrapperPriority() {
+ public function testWrapperPriority(): void {
$instance = new \OC\Files\Storage\StorageFactory();
$mount = new MountPoint(\OC\Files\Storage\Temporary::class, '/foo', [[]], $instance);
$instance->addStorageWrapper('dummy1', function ($mountPoint, IStorage $storage) {
diff --git a/tests/lib/Files/Storage/Wrapper/AvailabilityTest.php b/tests/lib/Files/Storage/Wrapper/AvailabilityTest.php
index 8e64269a2f4..616fd023414 100644
--- a/tests/lib/Files/Storage/Wrapper/AvailabilityTest.php
+++ b/tests/lib/Files/Storage/Wrapper/AvailabilityTest.php
@@ -36,7 +36,7 @@ class AvailabilityTest extends \Test\TestCase {
/**
* Storage is available
*/
- public function testAvailable() {
+ public function testAvailable(): void {
$this->storage->expects($this->once())
->method('getAvailability')
->willReturn(['available' => true, 'last_checked' => 0]);
@@ -52,7 +52,7 @@ class AvailabilityTest extends \Test\TestCase {
* Storage marked unavailable, TTL not expired
*
*/
- public function testUnavailable() {
+ public function testUnavailable(): void {
$this->expectException(\OCP\Files\StorageNotAvailableException::class);
$this->storage->expects($this->once())
@@ -69,7 +69,7 @@ class AvailabilityTest extends \Test\TestCase {
/**
* Storage marked unavailable, TTL expired
*/
- public function testUnavailableRecheck() {
+ public function testUnavailableRecheck(): void {
$this->storage->expects($this->once())
->method('getAvailability')
->willReturn(['available' => false, 'last_checked' => 0]);
@@ -92,7 +92,7 @@ class AvailabilityTest extends \Test\TestCase {
* Storage marked available, but throws StorageNotAvailableException
*
*/
- public function testAvailableThrowStorageNotAvailable() {
+ public function testAvailableThrowStorageNotAvailable(): void {
$this->expectException(\OCP\Files\StorageNotAvailableException::class);
$this->storage->expects($this->once())
@@ -114,7 +114,7 @@ class AvailabilityTest extends \Test\TestCase {
* Storage available, but call fails
* Method failure does not indicate storage unavailability
*/
- public function testAvailableFailure() {
+ public function testAvailableFailure(): void {
$this->storage->expects($this->once())
->method('getAvailability')
->willReturn(['available' => true, 'last_checked' => 0]);
@@ -134,7 +134,7 @@ class AvailabilityTest extends \Test\TestCase {
* Standard exception does not indicate storage unavailability
*
*/
- public function testAvailableThrow() {
+ public function testAvailableThrow(): void {
$this->expectException(\Exception::class);
$this->storage->expects($this->once())
diff --git a/tests/lib/Files/Storage/Wrapper/EncodingTest.php b/tests/lib/Files/Storage/Wrapper/EncodingTest.php
index ae6a6ece742..4256337f08e 100644
--- a/tests/lib/Files/Storage/Wrapper/EncodingTest.php
+++ b/tests/lib/Files/Storage/Wrapper/EncodingTest.php
@@ -57,7 +57,7 @@ class EncodingTest extends \Test\Files\Storage\Storage {
/**
* @dataProvider accessNameProvider
*/
- public function testFputEncoding($accessName) {
+ public function testFputEncoding($accessName): void {
$this->sourceStorage->file_put_contents(self::NFD_NAME, 'bar');
$this->assertEquals('bar', $this->instance->file_get_contents($accessName));
}
@@ -65,7 +65,7 @@ class EncodingTest extends \Test\Files\Storage\Storage {
/**
* @dataProvider accessNameProvider
*/
- public function testFopenReadEncoding($accessName) {
+ public function testFopenReadEncoding($accessName): void {
$this->sourceStorage->file_put_contents(self::NFD_NAME, 'bar');
$fh = $this->instance->fopen($accessName, 'r');
$data = fgets($fh);
@@ -76,7 +76,7 @@ class EncodingTest extends \Test\Files\Storage\Storage {
/**
* @dataProvider accessNameProvider
*/
- public function testFopenOverwriteEncoding($accessName) {
+ public function testFopenOverwriteEncoding($accessName): void {
$this->sourceStorage->file_put_contents(self::NFD_NAME, 'bar');
$fh = $this->instance->fopen($accessName, 'w');
$data = fputs($fh, 'test');
@@ -89,7 +89,7 @@ class EncodingTest extends \Test\Files\Storage\Storage {
/**
* @dataProvider accessNameProvider
*/
- public function testFileExistsEncoding($accessName) {
+ public function testFileExistsEncoding($accessName): void {
$this->sourceStorage->file_put_contents(self::NFD_NAME, 'bar');
$this->assertTrue($this->instance->file_exists($accessName));
}
@@ -97,14 +97,14 @@ class EncodingTest extends \Test\Files\Storage\Storage {
/**
* @dataProvider accessNameProvider
*/
- public function testUnlinkEncoding($accessName) {
+ public function testUnlinkEncoding($accessName): void {
$this->sourceStorage->file_put_contents(self::NFD_NAME, 'bar');
$this->assertTrue($this->instance->unlink($accessName));
$this->assertFalse($this->sourceStorage->file_exists(self::NFC_NAME));
$this->assertFalse($this->sourceStorage->file_exists(self::NFD_NAME));
}
- public function testNfcHigherPriority() {
+ public function testNfcHigherPriority(): void {
$this->sourceStorage->file_put_contents(self::NFC_NAME, 'nfc');
$this->sourceStorage->file_put_contents(self::NFD_NAME, 'nfd');
$this->assertEquals('nfc', $this->instance->file_get_contents(self::NFC_NAME));
@@ -121,7 +121,7 @@ class EncodingTest extends \Test\Files\Storage\Storage {
/**
* @dataProvider encodedDirectoriesProvider
*/
- public function testOperationInsideDirectory($sourceDir, $accessDir) {
+ public function testOperationInsideDirectory($sourceDir, $accessDir): void {
$this->sourceStorage->mkdir($sourceDir);
$this->instance->file_put_contents($accessDir . '/test.txt', 'bar');
$this->assertTrue($this->instance->file_exists($accessDir . '/test.txt'));
@@ -138,7 +138,7 @@ class EncodingTest extends \Test\Files\Storage\Storage {
$this->assertTrue($this->instance->file_exists($accessDir . '/' . self::NFC_NAME));
}
- public function testCacheExtraSlash() {
+ public function testCacheExtraSlash(): void {
$this->sourceStorage->file_put_contents(self::NFD_NAME, 'foo');
$this->assertEquals(3, $this->instance->file_put_contents(self::NFC_NAME, 'bar'));
$this->assertEquals('bar', $this->instance->file_get_contents(self::NFC_NAME));
@@ -162,7 +162,7 @@ class EncodingTest extends \Test\Files\Storage\Storage {
/**
* @dataProvider sourceAndTargetDirectoryProvider
*/
- public function testCopyAndMoveEncodedFolder($sourceDir, $targetDir) {
+ public function testCopyAndMoveEncodedFolder($sourceDir, $targetDir): void {
$this->sourceStorage->mkdir($sourceDir);
$this->sourceStorage->mkdir($targetDir);
$this->sourceStorage->file_put_contents($sourceDir . '/test.txt', 'bar');
@@ -182,7 +182,7 @@ class EncodingTest extends \Test\Files\Storage\Storage {
/**
* @dataProvider sourceAndTargetDirectoryProvider
*/
- public function testCopyAndMoveFromStorageEncodedFolder($sourceDir, $targetDir) {
+ public function testCopyAndMoveFromStorageEncodedFolder($sourceDir, $targetDir): void {
$this->sourceStorage->mkdir($sourceDir);
$this->sourceStorage->mkdir($targetDir);
$this->sourceStorage->file_put_contents($sourceDir . '/test.txt', 'bar');
@@ -199,7 +199,7 @@ class EncodingTest extends \Test\Files\Storage\Storage {
$this->assertEquals('bar', $this->instance->file_get_contents(self::NFC_NAME . '2/test2.txt'));
}
- public function testNormalizedDirectoryEntriesOpenDir() {
+ public function testNormalizedDirectoryEntriesOpenDir(): void {
$this->sourceStorage->mkdir('/test');
$this->sourceStorage->mkdir('/test/' . self::NFD_NAME);
@@ -218,7 +218,7 @@ class EncodingTest extends \Test\Files\Storage\Storage {
$this->assertEquals(self::NFC_NAME, $content[0]);
}
- public function testNormalizedDirectoryEntriesGetDirectoryContent() {
+ public function testNormalizedDirectoryEntriesGetDirectoryContent(): void {
$this->sourceStorage->mkdir('/test');
$this->sourceStorage->mkdir('/test/' . self::NFD_NAME);
@@ -230,7 +230,7 @@ class EncodingTest extends \Test\Files\Storage\Storage {
$this->assertEquals(self::NFC_NAME, $content[0]['name']);
}
- public function testNormalizedGetMetaData() {
+ public function testNormalizedGetMetaData(): void {
$this->sourceStorage->mkdir('/test');
$this->sourceStorage->mkdir('/test/' . self::NFD_NAME);
diff --git a/tests/lib/Files/Storage/Wrapper/EncryptionTest.php b/tests/lib/Files/Storage/Wrapper/EncryptionTest.php
index 8bc8196fea3..3159ded5075 100644
--- a/tests/lib/Files/Storage/Wrapper/EncryptionTest.php
+++ b/tests/lib/Files/Storage/Wrapper/EncryptionTest.php
@@ -1,1032 +1,1032 @@
-<?php
-/**
- * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
- * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
- * SPDX-License-Identifier: AGPL-3.0-only
- */
-namespace Test\Files\Storage\Wrapper;
-
-use OC\Encryption\Exceptions\ModuleDoesNotExistsException;
-use OC\Encryption\Update;
-use OC\Encryption\Util;
-use OC\Files\Cache\CacheEntry;
-use OC\Files\Storage\Temporary;
-use OC\Files\Storage\Wrapper\Encryption;
-use OC\Files\View;
-use OC\Memcache\ArrayCache;
-use OC\User\Manager;
-use OCP\Encryption\IEncryptionModule;
-use OCP\Encryption\IFile;
-use OCP\Encryption\Keys\IStorage;
-use OCP\EventDispatcher\IEventDispatcher;
-use OCP\Files\Cache\ICache;
-use OCP\Files\Mount\IMountPoint;
-use OCP\ICacheFactory;
-use OCP\IConfig;
-use Psr\Log\LoggerInterface;
-use Test\Files\Storage\Storage;
-
-class EncryptionTest extends Storage {
- /**
- * block size will always be 8192 for a PHP stream
- * @see https://bugs.php.net/bug.php?id=21641
- * @var integer
- */
- protected $headerSize = 8192;
-
- /**
- * @var Temporary
- */
- private $sourceStorage;
-
- /**
- * @var \OC\Files\Storage\Wrapper\Encryption | \PHPUnit\Framework\MockObject\MockObject
- */
- protected $instance;
-
- /**
- * @var \OC\Encryption\Keys\Storage | \PHPUnit\Framework\MockObject\MockObject
- */
- private $keyStore;
-
- /**
- * @var \OC\Encryption\Util | \PHPUnit\Framework\MockObject\MockObject
- */
- private $util;
-
- /**
- * @var \OC\Encryption\Manager | \PHPUnit\Framework\MockObject\MockObject
- */
- private $encryptionManager;
-
- /**
- * @var \OCP\Encryption\IEncryptionModule | \PHPUnit\Framework\MockObject\MockObject
- */
- private $encryptionModule;
-
- /**
- * @var \OC\Encryption\Update | \PHPUnit\Framework\MockObject\MockObject
- */
- private $update;
-
- /**
- * @var \OC\Files\Cache\Cache | \PHPUnit\Framework\MockObject\MockObject
- */
- private $cache;
-
- /**
- * @var \OC\Log | \PHPUnit\Framework\MockObject\MockObject
- */
- private $logger;
-
- /**
- * @var \OC\Encryption\File | \PHPUnit\Framework\MockObject\MockObject
- */
- private $file;
-
-
- /**
- * @var \OC\Files\Mount\MountPoint | \PHPUnit\Framework\MockObject\MockObject
- */
- private $mount;
-
- /**
- * @var \OC\Files\Mount\Manager | \PHPUnit\Framework\MockObject\MockObject
- */
- private $mountManager;
-
- /**
- * @var \OC\Group\Manager | \PHPUnit\Framework\MockObject\MockObject
- */
- private $groupManager;
-
- /**
- * @var \OCP\IConfig | \PHPUnit\Framework\MockObject\MockObject
- */
- private $config;
-
- /** @var \OC\Memcache\ArrayCache | \PHPUnit\Framework\MockObject\MockObject */
- private $arrayCache;
-
-
- /** @var integer dummy unencrypted size */
- private $dummySize = -1;
-
- protected function setUp(): void {
- parent::setUp();
-
- $mockModule = $this->buildMockModule();
- $this->encryptionManager = $this->getMockBuilder(\OC\Encryption\Manager::class)
- ->disableOriginalConstructor()
- ->setMethods(['getEncryptionModule', 'isEnabled'])
- ->getMock();
- $this->encryptionManager->expects($this->any())
- ->method('getEncryptionModule')
- ->willReturn($mockModule);
-
- $this->arrayCache = $this->createMock(ArrayCache::class);
- $this->config = $this->getMockBuilder(IConfig::class)
- ->disableOriginalConstructor()
- ->getMock();
- $this->groupManager = $this->getMockBuilder(\OC\Group\Manager::class)
- ->disableOriginalConstructor()
- ->getMock();
-
- $this->util = $this->getMockBuilder(\OC\Encryption\Util::class)
- ->setMethods(['getUidAndFilename', 'isFile', 'isExcluded'])
- ->setConstructorArgs([new View(), new Manager(
- $this->config,
- $this->createMock(ICacheFactory::class),
- $this->createMock(IEventDispatcher::class)
- ), $this->groupManager, $this->config, $this->arrayCache])
- ->getMock();
- $this->util->expects($this->any())
- ->method('getUidAndFilename')
- ->willReturnCallback(function ($path) {
- return ['user1', $path];
- });
-
- $this->file = $this->getMockBuilder(\OC\Encryption\File::class)
- ->disableOriginalConstructor()
- ->setMethods(['getAccessList'])
- ->getMock();
- $this->file->expects($this->any())->method('getAccessList')->willReturn([]);
-
- $this->logger = $this->createMock(LoggerInterface::class);
-
- $this->sourceStorage = new Temporary([]);
-
- $this->keyStore = $this->getMockBuilder(\OC\Encryption\Keys\Storage::class)
- ->disableOriginalConstructor()->getMock();
-
- $this->update = $this->getMockBuilder(\OC\Encryption\Update::class)
- ->disableOriginalConstructor()->getMock();
-
- $this->mount = $this->getMockBuilder(\OC\Files\Mount\MountPoint::class)
- ->disableOriginalConstructor()
- ->setMethods(['getOption'])
- ->getMock();
- $this->mount->expects($this->any())->method('getOption')->willReturnCallback(function ($option, $default) {
- if ($option === 'encrypt' && $default === true) {
- global $mockedMountPointEncryptionEnabled;
- if ($mockedMountPointEncryptionEnabled !== null) {
- return $mockedMountPointEncryptionEnabled;
- }
- }
- return true;
- });
-
- $this->cache = $this->getMockBuilder(\OC\Files\Cache\Cache::class)
- ->disableOriginalConstructor()->getMock();
- $this->cache->expects($this->any())
- ->method('get')
- ->willReturnCallback(function ($path) {
- return ['encrypted' => false, 'path' => $path];
- });
-
- $this->mountManager = $this->createMock(\OC\Files\Mount\Manager::class);
- $this->mountManager->method('findByStorageId')
- ->willReturn([]);
-
- $this->instance = $this->getMockBuilder(\OC\Files\Storage\Wrapper\Encryption::class)
- ->setConstructorArgs(
- [
- [
- 'storage' => $this->sourceStorage,
- 'root' => 'foo',
- 'mountPoint' => '/',
- 'mount' => $this->mount
- ],
- $this->encryptionManager, $this->util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager, $this->arrayCache
- ]
- )
- ->setMethods(['getMetaData', 'getCache', 'getEncryptionModule'])
- ->getMock();
-
- $this->instance->expects($this->any())
- ->method('getMetaData')
- ->willReturnCallback(function ($path) {
- return ['encrypted' => true, 'size' => $this->dummySize, 'path' => $path];
- });
-
- $this->instance->expects($this->any())
- ->method('getCache')
- ->willReturn($this->cache);
-
- $this->instance->expects($this->any())
- ->method('getEncryptionModule')
- ->willReturn($mockModule);
- }
-
- /**
- * @return \PHPUnit\Framework\MockObject\MockObject
- */
- protected function buildMockModule() {
- $this->encryptionModule = $this->getMockBuilder(\OCP\Encryption\IEncryptionModule::class)
- ->disableOriginalConstructor()
- ->setMethods(['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');
- $this->encryptionModule->expects($this->any())->method('getDisplayName')->willReturn('Unit test module');
- $this->encryptionModule->expects($this->any())->method('begin')->willReturn([]);
- $this->encryptionModule->expects($this->any())->method('end')->willReturn('');
- $this->encryptionModule->expects($this->any())->method('encrypt')->willReturnArgument(0);
- $this->encryptionModule->expects($this->any())->method('decrypt')->willReturnArgument(0);
- $this->encryptionModule->expects($this->any())->method('update')->willReturn(true);
- $this->encryptionModule->expects($this->any())->method('shouldEncrypt')->willReturn(true);
- $this->encryptionModule->expects($this->any())->method('getUnencryptedBlockSize')->willReturn(8192);
- $this->encryptionModule->expects($this->any())->method('isReadable')->willReturn(true);
- $this->encryptionModule->expects($this->any())->method('needDetailedAccessList')->willReturn(false);
- return $this->encryptionModule;
- }
-
- /**
- * @dataProvider dataTestGetMetaData
- *
- * @param string $path
- * @param array $metaData
- * @param bool $encrypted
- * @param bool $unencryptedSizeSet
- * @param int $storedUnencryptedSize
- * @param array $expected
- */
- public function testGetMetaData($path, $metaData, $encrypted, $unencryptedSizeSet, $storedUnencryptedSize, $expected) {
- $sourceStorage = $this->getMockBuilder(\OC\Files\Storage\Storage::class)
- ->disableOriginalConstructor()->getMock();
-
- $cache = $this->getMockBuilder(\OC\Files\Cache\Cache::class)
- ->disableOriginalConstructor()->getMock();
- $cache->expects($this->any())
- ->method('get')
- ->willReturnCallback(
- function ($path) use ($encrypted) {
- return new CacheEntry(['encrypted' => $encrypted, 'path' => $path, 'size' => 0, 'fileid' => 1]);
- }
- );
-
- $this->instance = $this->getMockBuilder(\OC\Files\Storage\Wrapper\Encryption::class)
- ->setConstructorArgs(
- [
- [
- 'storage' => $sourceStorage,
- 'root' => 'foo',
- 'mountPoint' => '/',
- 'mount' => $this->mount
- ],
- $this->encryptionManager, $this->util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager, $this->arrayCache
- ]
- )
- ->setMethods(['getCache', 'verifyUnencryptedSize'])
- ->getMock();
-
- if ($unencryptedSizeSet) {
- $this->invokePrivate($this->instance, 'unencryptedSize', [[$path => $storedUnencryptedSize]]);
- }
-
- $fileEntry = $this->getMockBuilder(\OC\Files\Cache\Cache::class)
- ->disableOriginalConstructor()->getMock();
- $sourceStorage->expects($this->once())->method('getMetaData')->with($path)
- ->willReturn($metaData);
- $sourceStorage->expects($this->any())
- ->method('getCache')
- ->with($path)
- ->willReturn($fileEntry);
- if ($metaData !== null) {
- $fileEntry->expects($this->any())
- ->method('get')
- ->with($metaData['fileid']);
- }
-
- $this->instance->expects($this->any())->method('getCache')->willReturn($cache);
- if ($expected !== null) {
- $this->instance->expects($this->any())->method('verifyUnencryptedSize')
- ->with($path, 0)->willReturn($expected['size']);
- }
-
- $result = $this->instance->getMetaData($path);
- if (isset($expected['encrypted'])) {
- $this->assertSame($expected['encrypted'], (bool)$result['encrypted']);
-
- if (isset($expected['encryptedVersion'])) {
- $this->assertSame($expected['encryptedVersion'], $result['encryptedVersion']);
- }
- }
-
- if ($expected !== null) {
- $this->assertSame($expected['size'], $result['size']);
- } else {
- $this->assertSame(null, $result);
- }
- }
-
- public function dataTestGetMetaData() {
- 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],
- ['/test.txt', ['size' => 42, 'encrypted' => 0, 'fileid' => 1], false, false, 12, ['size' => 42, 'encrypted' => false]],
- ['/test.txt', ['size' => 42, 'encrypted' => false, 'fileid' => 1], true, false, 12, ['size' => 12, 'encrypted' => true]]
- ];
- }
-
- public function testFilesize() {
- $cache = $this->getMockBuilder(\OC\Files\Cache\Cache::class)
- ->disableOriginalConstructor()->getMock();
- $cache->expects($this->any())
- ->method('get')
- ->willReturn(new CacheEntry(['encrypted' => true, 'path' => '/test.txt', 'size' => 0, 'fileid' => 1]));
-
- $this->instance = $this->getMockBuilder(\OC\Files\Storage\Wrapper\Encryption::class)
- ->setConstructorArgs(
- [
- [
- 'storage' => $this->sourceStorage,
- 'root' => 'foo',
- 'mountPoint' => '/',
- 'mount' => $this->mount
- ],
- $this->encryptionManager, $this->util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager, $this->arrayCache
- ]
- )
- ->setMethods(['getCache', 'verifyUnencryptedSize'])
- ->getMock();
-
- $this->instance->expects($this->any())->method('getCache')->willReturn($cache);
- $this->instance->expects($this->any())->method('verifyUnencryptedSize')
- ->willReturn(42);
-
-
- $this->assertSame(42,
- $this->instance->filesize('/test.txt')
- );
- }
-
- /**
- * @dataProvider dataTestVerifyUnencryptedSize
- *
- * @param int $encryptedSize
- * @param int $unencryptedSize
- * @param bool $failure
- * @param int $expected
- */
- public function testVerifyUnencryptedSize($encryptedSize, $unencryptedSize, $failure, $expected) {
- $sourceStorage = $this->getMockBuilder(\OC\Files\Storage\Storage::class)
- ->disableOriginalConstructor()->getMock();
-
- $this->instance = $this->getMockBuilder(\OC\Files\Storage\Wrapper\Encryption::class)
- ->setConstructorArgs(
- [
- [
- 'storage' => $sourceStorage,
- 'root' => 'foo',
- 'mountPoint' => '/',
- 'mount' => $this->mount
- ],
- $this->encryptionManager, $this->util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager, $this->arrayCache
- ]
- )
- ->setMethods(['fixUnencryptedSize'])
- ->getMock();
-
- $sourceStorage->expects($this->once())->method('filesize')->willReturn($encryptedSize);
-
- $this->instance->expects($this->any())->method('fixUnencryptedSize')
- ->with('/test.txt', $encryptedSize, $unencryptedSize)
- ->willReturnCallback(
- function () use ($failure, $expected) {
- if ($failure) {
- throw new \Exception();
- } else {
- return $expected;
- }
- }
- );
-
- $this->assertSame(
- $expected,
- $this->invokePrivate($this->instance, 'verifyUnencryptedSize', ['/test.txt', $unencryptedSize])
- );
- }
-
- public function dataTestVerifyUnencryptedSize() {
- return [
- [120, 80, false, 80],
- [120, 120, false, 80],
- [120, -1, false, 80],
- [120, -1, true, -1]
- ];
- }
-
- /**
- * @dataProvider dataTestCopyAndRename
- *
- * @param string $source
- * @param string $target
- * @param $encryptionEnabled
- * @param boolean $renameKeysReturn
- */
- public function testRename($source,
- $target,
- $encryptionEnabled,
- $renameKeysReturn) {
- if ($encryptionEnabled) {
- $this->keyStore
- ->expects($this->once())
- ->method('renameKeys')
- ->willReturn($renameKeysReturn);
- } else {
- $this->keyStore
- ->expects($this->never())->method('renameKeys');
- }
- $this->util->expects($this->any())
- ->method('isFile')->willReturn(true);
- $this->encryptionManager->expects($this->once())
- ->method('isEnabled')->willReturn($encryptionEnabled);
-
- $this->instance->mkdir($source);
- $this->instance->mkdir(dirname($target));
- $this->instance->rename($source, $target);
- }
-
- public function testCopyEncryption() {
- $this->instance->file_put_contents('source.txt', 'bar');
- $this->instance->copy('source.txt', 'target.txt');
- $this->assertSame('bar', $this->instance->file_get_contents('target.txt'));
- $targetMeta = $this->instance->getMetaData('target.txt');
- $sourceMeta = $this->instance->getMetaData('source.txt');
- $this->assertSame($sourceMeta['encrypted'], $targetMeta['encrypted']);
- $this->assertSame($sourceMeta['size'], $targetMeta['size']);
- }
-
- /**
- * data provider for testCopyTesting() and dataTestCopyAndRename()
- *
- * @return array
- */
- public function dataTestCopyAndRename() {
- return [
- ['source', 'target', true, false, false],
- ['source', 'target', true, true, false],
- ['source', '/subFolder/target', true, false, false],
- ['source', '/subFolder/target', true, true, true],
- ['source', '/subFolder/target', false, true, false],
- ];
- }
-
- public function testIsLocal() {
- $this->encryptionManager->expects($this->once())
- ->method('isEnabled')->willReturn(true);
- $this->assertFalse($this->instance->isLocal());
- }
-
- /**
- * @dataProvider dataTestRmdir
- *
- * @param string $path
- * @param boolean $rmdirResult
- * @param boolean $isExcluded
- * @param boolean $encryptionEnabled
- */
- public function testRmdir($path, $rmdirResult, $isExcluded, $encryptionEnabled) {
- $sourceStorage = $this->getMockBuilder(\OC\Files\Storage\Storage::class)
- ->disableOriginalConstructor()->getMock();
-
- $util = $this->getMockBuilder(\OC\Encryption\Util::class)->disableOriginalConstructor()->getMock();
-
- $sourceStorage->expects($this->once())->method('rmdir')->willReturn($rmdirResult);
- $util->expects($this->any())->method('isExcluded')-> willReturn($isExcluded);
- $this->encryptionManager->expects($this->any())->method('isEnabled')->willReturn($encryptionEnabled);
-
- $encryptionStorage = new \OC\Files\Storage\Wrapper\Encryption(
- [
- 'storage' => $sourceStorage,
- 'root' => 'foo',
- 'mountPoint' => '/mountPoint',
- 'mount' => $this->mount
- ],
- $this->encryptionManager, $util, $this->logger, $this->file, null, $this->keyStore, $this->update
- );
-
-
- if ($rmdirResult === true && $isExcluded === false && $encryptionEnabled === true) {
- $this->keyStore->expects($this->once())->method('deleteAllFileKeys')->with('/mountPoint' . $path);
- } else {
- $this->keyStore->expects($this->never())->method('deleteAllFileKeys');
- }
-
- $encryptionStorage->rmdir($path);
- }
-
- public function dataTestRmdir() {
- return [
- ['/file.txt', true, true, true],
- ['/file.txt', false, true, true],
- ['/file.txt', true, false, true],
- ['/file.txt', false, false, true],
- ['/file.txt', true, true, false],
- ['/file.txt', false, true, false],
- ['/file.txt', true, false, false],
- ['/file.txt', false, false, false],
- ];
- }
-
- /**
- * @dataProvider dataTestCopyKeys
- *
- * @param boolean $excluded
- * @param boolean $expected
- */
- public function testCopyKeys($excluded, $expected) {
- $this->util->expects($this->once())
- ->method('isExcluded')
- ->willReturn($excluded);
-
- if ($excluded) {
- $this->keyStore->expects($this->never())->method('copyKeys');
- } else {
- $this->keyStore->expects($this->once())->method('copyKeys')->willReturn(true);
- }
-
- $this->assertSame($expected,
- self::invokePrivate($this->instance, 'copyKeys', ['/source', '/target'])
- );
- }
-
- public function dataTestCopyKeys() {
- return [
- [true, false],
- [false, true],
- ];
- }
-
- /**
- * @dataProvider dataTestGetHeader
- *
- * @param string $path
- * @param bool $strippedPathExists
- * @param string $strippedPath
- */
- public function testGetHeader($path, $strippedPathExists, $strippedPath) {
- $sourceStorage = $this->getMockBuilder(\OC\Files\Storage\Storage::class)
- ->disableOriginalConstructor()->getMock();
-
- $util = $this->getMockBuilder(\OC\Encryption\Util::class)
- ->setConstructorArgs(
- [
- new View(),
- new Manager(
- $this->config,
- $this->createMock(ICacheFactory::class),
- $this->createMock(IEventDispatcher::class)
- ),
- $this->groupManager,
- $this->config,
- $this->arrayCache
- ]
- )->getMock();
-
- $cache = $this->getMockBuilder(\OC\Files\Cache\Cache::class)
- ->disableOriginalConstructor()->getMock();
- $cache->expects($this->any())
- ->method('get')
- ->willReturnCallback(function ($path) {
- return ['encrypted' => true, 'path' => $path];
- });
-
- $instance = $this->getMockBuilder(\OC\Files\Storage\Wrapper\Encryption::class)
- ->setConstructorArgs(
- [
- [
- 'storage' => $sourceStorage,
- 'root' => 'foo',
- 'mountPoint' => '/',
- 'mount' => $this->mount
- ],
- $this->encryptionManager, $util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager, $this->arrayCache
- ]
- )
- ->setMethods(['getCache', 'readFirstBlock'])
- ->getMock();
-
- $instance->method('getCache')->willReturn($cache);
-
- $util->method('parseRawHeader')
- ->willReturn([Util::HEADER_ENCRYPTION_MODULE_KEY => 'OC_DEFAULT_MODULE']);
-
- if ($strippedPathExists) {
- $instance->method('readFirstBlock')
- ->with($strippedPath)->willReturn('');
- } else {
- $instance->method('readFirstBlock')
- ->with($path)->willReturn('');
- }
-
- $util->expects($this->once())->method('stripPartialFileExtension')
- ->with($path)->willReturn($strippedPath);
- $sourceStorage->expects($this->once())
- ->method('is_file')
- ->with($strippedPath)
- ->willReturn($strippedPathExists);
-
- $this->invokePrivate($instance, 'getHeader', [$path]);
- }
-
- public function dataTestGetHeader() {
- return [
- ['/foo/bar.txt', false, '/foo/bar.txt'],
- ['/foo/bar.txt.part', false, '/foo/bar.txt'],
- ['/foo/bar.txt.ocTransferId7437493.part', false, '/foo/bar.txt'],
- ['/foo/bar.txt.part', true, '/foo/bar.txt'],
- ['/foo/bar.txt.ocTransferId7437493.part', true, '/foo/bar.txt'],
- ];
- }
-
- /**
- * test if getHeader adds the default module correctly to the header for
- * legacy files
- *
- * @dataProvider dataTestGetHeaderAddLegacyModule
- */
- public function testGetHeaderAddLegacyModule($header, $isEncrypted, $exists, $expected) {
- $sourceStorage = $this->getMockBuilder(\OC\Files\Storage\Storage::class)
- ->disableOriginalConstructor()->getMock();
-
- $sourceStorage->expects($this->once())
- ->method('is_file')
- ->willReturn($exists);
-
- $util = $this->getMockBuilder(\OC\Encryption\Util::class)
- ->setConstructorArgs([new View(), new Manager(
- $this->config,
- $this->createMock(ICacheFactory::class),
- $this->createMock(IEventDispatcher::class)
- ), $this->groupManager, $this->config, $this->arrayCache])
- ->getMock();
-
- $cache = $this->getMockBuilder(\OC\Files\Cache\Cache::class)
- ->disableOriginalConstructor()->getMock();
- $cache->expects($this->any())
- ->method('get')
- ->willReturnCallback(function ($path) use ($isEncrypted) {
- return ['encrypted' => $isEncrypted, 'path' => $path];
- });
-
- $instance = $this->getMockBuilder(\OC\Files\Storage\Wrapper\Encryption::class)
- ->setConstructorArgs(
- [
- [
- 'storage' => $sourceStorage,
- 'root' => 'foo',
- 'mountPoint' => '/',
- 'mount' => $this->mount
- ],
- $this->encryptionManager, $util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager, $this->arrayCache
- ]
- )
- ->setMethods(['readFirstBlock', 'getCache'])
- ->getMock();
-
- $instance->method('readFirstBlock')->willReturn('');
-
- $util->method(('parseRawHeader'))->willReturn($header);
- $instance->method('getCache')->willReturn($cache);
-
- $result = $this->invokePrivate($instance, 'getHeader', ['test.txt']);
- $this->assertSameSize($expected, $result);
- foreach ($result as $key => $value) {
- $this->assertArrayHasKey($key, $expected);
- $this->assertSame($expected[$key], $value);
- }
- }
-
- public function dataTestGetHeaderAddLegacyModule() {
- return [
- [['cipher' => 'AES-128'], true, true, ['cipher' => 'AES-128', Util::HEADER_ENCRYPTION_MODULE_KEY => 'OC_DEFAULT_MODULE']],
- [[], true, false, []],
- [[], true, true, [Util::HEADER_ENCRYPTION_MODULE_KEY => 'OC_DEFAULT_MODULE']],
- [[], false, true, []],
- ];
- }
-
- public function dataCopyBetweenStorage() {
- return [
- [true, true, true],
- [true, false, false],
- [false, true, false],
- [false, false, false],
- ];
- }
-
- public function testCopyBetweenStorageMinimumEncryptedVersion() {
- $storage2 = $this->createMock(\OC\Files\Storage\Storage::class);
-
- $sourceInternalPath = $targetInternalPath = 'file.txt';
- $preserveMtime = $isRename = false;
-
- $storage2->expects($this->any())
- ->method('fopen')
- ->willReturnCallback(function ($path, $mode) {
- $temp = \OC::$server->getTempManager();
- return fopen($temp->getTemporaryFile(), $mode);
- });
- $storage2->method('getId')
- ->willReturn('stroage2');
- $cache = $this->createMock(ICache::class);
- $cache->expects($this->once())
- ->method('get')
- ->with($sourceInternalPath)
- ->willReturn(['encryptedVersion' => 0]);
- $storage2->expects($this->once())
- ->method('getCache')
- ->willReturn($cache);
- $this->encryptionManager->expects($this->any())
- ->method('isEnabled')
- ->willReturn(true);
- global $mockedMountPointEncryptionEnabled;
- $mockedMountPointEncryptionEnabled = true;
-
- $expectedCachePut = [
- 'encrypted' => true,
- ];
- $expectedCachePut['encryptedVersion'] = 1;
-
- $this->cache->expects($this->once())
- ->method('put')
- ->with($sourceInternalPath, $expectedCachePut);
-
- $this->invokePrivate($this->instance, 'copyBetweenStorage', [$storage2, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename]);
-
- $this->assertFalse(false);
- }
-
- /**
- * @dataProvider dataCopyBetweenStorage
- *
- * @param bool $encryptionEnabled
- * @param bool $mountPointEncryptionEnabled
- * @param bool $expectedEncrypted
- */
- public function testCopyBetweenStorage($encryptionEnabled, $mountPointEncryptionEnabled, $expectedEncrypted) {
- $storage2 = $this->createMock(\OC\Files\Storage\Storage::class);
-
- $sourceInternalPath = $targetInternalPath = 'file.txt';
- $preserveMtime = $isRename = false;
-
- $storage2->expects($this->any())
- ->method('fopen')
- ->willReturnCallback(function ($path, $mode) {
- $temp = \OC::$server->getTempManager();
- return fopen($temp->getTemporaryFile(), $mode);
- });
- $storage2->method('getId')
- ->willReturn('stroage2');
- if ($expectedEncrypted) {
- $cache = $this->createMock(ICache::class);
- $cache->expects($this->once())
- ->method('get')
- ->with($sourceInternalPath)
- ->willReturn(['encryptedVersion' => 12345]);
- $storage2->expects($this->once())
- ->method('getCache')
- ->willReturn($cache);
- }
- $this->encryptionManager->expects($this->any())
- ->method('isEnabled')
- ->willReturn($encryptionEnabled);
- // FIXME can not overwrite the return after definition
- // $this->mount->expects($this->at(0))
- // ->method('getOption')
- // ->with('encrypt', true)
- // ->willReturn($mountPointEncryptionEnabled);
- global $mockedMountPointEncryptionEnabled;
- $mockedMountPointEncryptionEnabled = $mountPointEncryptionEnabled;
-
- $expectedCachePut = [
- 'encrypted' => $expectedEncrypted,
- ];
- if ($expectedEncrypted === true) {
- $expectedCachePut['encryptedVersion'] = 1;
- }
-
- $this->arrayCache->expects($this->never())->method('set');
-
- $this->cache->expects($this->once())
- ->method('put')
- ->with($sourceInternalPath, $expectedCachePut);
-
- $this->invokePrivate($this->instance, 'copyBetweenStorage', [$storage2, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename]);
-
- $this->assertFalse(false);
- }
-
- /**
- * @dataProvider dataTestCopyBetweenStorageVersions
- *
- * @param string $sourceInternalPath
- * @param string $targetInternalPath
- * @param bool $copyResult
- * @param bool $encrypted
- */
- public function testCopyBetweenStorageVersions($sourceInternalPath, $targetInternalPath, $copyResult, $encrypted) {
- $sourceStorage = $this->createMock(\OC\Files\Storage\Storage::class);
-
- $targetStorage = $this->createMock(\OC\Files\Storage\Storage::class);
-
- $cache = $this->getMockBuilder(\OC\Files\Cache\Cache::class)
- ->disableOriginalConstructor()->getMock();
-
- $mountPoint = '/mountPoint';
-
- /** @var \OC\Files\Storage\Wrapper\Encryption |\PHPUnit\Framework\MockObject\MockObject $instance */
- $instance = $this->getMockBuilder(\OC\Files\Storage\Wrapper\Encryption::class)
- ->setConstructorArgs(
- [
- [
- 'storage' => $targetStorage,
- 'root' => 'foo',
- 'mountPoint' => $mountPoint,
- 'mount' => $this->mount
- ],
- $this->encryptionManager,
- $this->util,
- $this->logger,
- $this->file,
- null,
- $this->keyStore,
- $this->update,
- $this->mountManager,
- $this->arrayCache
- ]
- )
- ->setMethods(['updateUnencryptedSize', 'getCache'])
- ->getMock();
-
- $targetStorage->expects($this->once())->method('copyFromStorage')
- ->with($sourceStorage, $sourceInternalPath, $targetInternalPath)
- ->willReturn($copyResult);
-
- $instance->expects($this->any())->method('getCache')
- ->willReturn($cache);
-
- $this->arrayCache->expects($this->once())->method('set')
- ->with('encryption_copy_version_' . $sourceInternalPath, true);
-
- if ($copyResult) {
- $cache->expects($this->once())->method('get')
- ->with($sourceInternalPath)
- ->willReturn(new CacheEntry(['encrypted' => $encrypted, 'size' => 42]));
- if ($encrypted) {
- $instance->expects($this->once())->method('updateUnencryptedSize')
- ->with($mountPoint . $targetInternalPath, 42);
- } else {
- $instance->expects($this->never())->method('updateUnencryptedSize');
- }
- } else {
- $instance->expects($this->never())->method('updateUnencryptedSize');
- }
-
- $result = $this->invokePrivate(
- $instance,
- 'copyBetweenStorage',
- [
- $sourceStorage,
- $sourceInternalPath,
- $targetInternalPath,
- false,
- false
- ]
- );
-
- $this->assertSame($copyResult, $result);
- }
-
- public function dataTestCopyBetweenStorageVersions() {
- return [
- ['/files/foo.txt', '/files_versions/foo.txt.768743', true, true],
- ['/files/foo.txt', '/files_versions/foo.txt.768743', true, false],
- ['/files/foo.txt', '/files_versions/foo.txt.768743', false, true],
- ['/files/foo.txt', '/files_versions/foo.txt.768743', false, false],
- ['/files_versions/foo.txt.6487634', '/files/foo.txt', true, true],
- ['/files_versions/foo.txt.6487634', '/files/foo.txt', true, false],
- ['/files_versions/foo.txt.6487634', '/files/foo.txt', false, true],
- ['/files_versions/foo.txt.6487634', '/files/foo.txt', false, false],
-
- ];
- }
-
- /**
- * @dataProvider dataTestIsVersion
- * @param string $path
- * @param bool $expected
- */
- public function testIsVersion($path, $expected) {
- $this->assertSame($expected,
- $this->invokePrivate($this->instance, 'isVersion', [$path])
- );
- }
-
- public function dataTestIsVersion() {
- return [
- ['files_versions/foo', true],
- ['/files_versions/foo', true],
- ['//files_versions/foo', true],
- ['files/versions/foo', false],
- ['files/files_versions/foo', false],
- ['files_versions_test/foo', false],
- ];
- }
-
- /**
- * @dataProvider dataTestShouldEncrypt
- *
- * @param bool $encryptMountPoint
- * @param mixed $encryptionModule
- * @param bool $encryptionModuleShouldEncrypt
- * @param bool $expected
- */
- public function testShouldEncrypt(
- $encryptMountPoint,
- $encryptionModule,
- $encryptionModuleShouldEncrypt,
- $expected
- ) {
- $encryptionManager = $this->createMock(\OC\Encryption\Manager::class);
- $util = $this->createMock(Util::class);
- $fileHelper = $this->createMock(IFile::class);
- $uid = null;
- $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);
- $path = '/welcome.txt';
- $fullPath = 'admin/files/welcome.txt';
- $defaultEncryptionModule = $this->createMock(IEncryptionModule::class);
-
- $wrapper = $this->getMockBuilder(Encryption::class)
- ->setConstructorArgs(
- [
- ['mountPoint' => '', 'mount' => $mount, 'storage' => ''],
- $encryptionManager,
- $util,
- $this->logger,
- $fileHelper,
- $uid,
- $keyStorage,
- $update,
- $mountManager,
- $arrayCache
- ]
- )
- ->setMethods(['getFullPath', 'getEncryptionModule'])
- ->getMock();
-
- if ($encryptionModule === true) {
- /** @var IEncryptionModule|\PHPUnit\Framework\MockObject\MockObject $encryptionModule */
- $encryptionModule = $this->createMock(IEncryptionModule::class);
- }
-
- $wrapper->method('getFullPath')->with($path)->willReturn($fullPath);
- $wrapper->expects($encryptMountPoint ? $this->once() : $this->never())
- ->method('getEncryptionModule')
- ->with($fullPath)
- ->willReturnCallback(
- function () use ($encryptionModule) {
- if ($encryptionModule === false) {
- throw new ModuleDoesNotExistsException();
- }
- return $encryptionModule;
- }
- );
- $mount->expects($this->once())->method('getOption')->with('encrypt', true)
- ->willReturn($encryptMountPoint);
-
- if ($encryptionModule !== null && $encryptionModule !== false) {
- $encryptionModule
- ->method('shouldEncrypt')
- ->with($fullPath)
- ->willReturn($encryptionModuleShouldEncrypt);
- }
-
- if ($encryptionModule === null) {
- $encryptionManager->expects($this->once())
- ->method('getEncryptionModule')
- ->willReturn($defaultEncryptionModule);
- }
- $defaultEncryptionModule->method('shouldEncrypt')->willReturn(true);
-
- $result = $this->invokePrivate($wrapper, 'shouldEncrypt', [$path]);
-
- $this->assertSame($expected, $result);
- }
-
- public function dataTestShouldEncrypt() {
- return [
- [false, false, false, false],
- [true, false, false, false],
- [true, true, false, false],
- [true, true, true, true],
- [true, null, false, true],
- ];
- }
-}
+<?php
+/**
+ * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
+ */
+namespace Test\Files\Storage\Wrapper;
+
+use OC\Encryption\Exceptions\ModuleDoesNotExistsException;
+use OC\Encryption\Update;
+use OC\Encryption\Util;
+use OC\Files\Cache\CacheEntry;
+use OC\Files\Storage\Temporary;
+use OC\Files\Storage\Wrapper\Encryption;
+use OC\Files\View;
+use OC\Memcache\ArrayCache;
+use OC\User\Manager;
+use OCP\Encryption\IEncryptionModule;
+use OCP\Encryption\IFile;
+use OCP\Encryption\Keys\IStorage;
+use OCP\EventDispatcher\IEventDispatcher;
+use OCP\Files\Cache\ICache;
+use OCP\Files\Mount\IMountPoint;
+use OCP\ICacheFactory;
+use OCP\IConfig;
+use Psr\Log\LoggerInterface;
+use Test\Files\Storage\Storage;
+
+class EncryptionTest extends Storage {
+ /**
+ * block size will always be 8192 for a PHP stream
+ * @see https://bugs.php.net/bug.php?id=21641
+ * @var integer
+ */
+ protected $headerSize = 8192;
+
+ /**
+ * @var Temporary
+ */
+ private $sourceStorage;
+
+ /**
+ * @var \OC\Files\Storage\Wrapper\Encryption | \PHPUnit\Framework\MockObject\MockObject
+ */
+ protected $instance;
+
+ /**
+ * @var \OC\Encryption\Keys\Storage | \PHPUnit\Framework\MockObject\MockObject
+ */
+ private $keyStore;
+
+ /**
+ * @var \OC\Encryption\Util | \PHPUnit\Framework\MockObject\MockObject
+ */
+ private $util;
+
+ /**
+ * @var \OC\Encryption\Manager | \PHPUnit\Framework\MockObject\MockObject
+ */
+ private $encryptionManager;
+
+ /**
+ * @var \OCP\Encryption\IEncryptionModule | \PHPUnit\Framework\MockObject\MockObject
+ */
+ private $encryptionModule;
+
+ /**
+ * @var \OC\Encryption\Update | \PHPUnit\Framework\MockObject\MockObject
+ */
+ private $update;
+
+ /**
+ * @var \OC\Files\Cache\Cache | \PHPUnit\Framework\MockObject\MockObject
+ */
+ private $cache;
+
+ /**
+ * @var \OC\Log | \PHPUnit\Framework\MockObject\MockObject
+ */
+ private $logger;
+
+ /**
+ * @var \OC\Encryption\File | \PHPUnit\Framework\MockObject\MockObject
+ */
+ private $file;
+
+
+ /**
+ * @var \OC\Files\Mount\MountPoint | \PHPUnit\Framework\MockObject\MockObject
+ */
+ private $mount;
+
+ /**
+ * @var \OC\Files\Mount\Manager | \PHPUnit\Framework\MockObject\MockObject
+ */
+ private $mountManager;
+
+ /**
+ * @var \OC\Group\Manager | \PHPUnit\Framework\MockObject\MockObject
+ */
+ private $groupManager;
+
+ /**
+ * @var \OCP\IConfig | \PHPUnit\Framework\MockObject\MockObject
+ */
+ private $config;
+
+ /** @var \OC\Memcache\ArrayCache | \PHPUnit\Framework\MockObject\MockObject */
+ private $arrayCache;
+
+
+ /** @var integer dummy unencrypted size */
+ private $dummySize = -1;
+
+ protected function setUp(): void {
+ parent::setUp();
+
+ $mockModule = $this->buildMockModule();
+ $this->encryptionManager = $this->getMockBuilder(\OC\Encryption\Manager::class)
+ ->disableOriginalConstructor()
+ ->setMethods(['getEncryptionModule', 'isEnabled'])
+ ->getMock();
+ $this->encryptionManager->expects($this->any())
+ ->method('getEncryptionModule')
+ ->willReturn($mockModule);
+
+ $this->arrayCache = $this->createMock(ArrayCache::class);
+ $this->config = $this->getMockBuilder(IConfig::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $this->groupManager = $this->getMockBuilder(\OC\Group\Manager::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $this->util = $this->getMockBuilder(\OC\Encryption\Util::class)
+ ->setMethods(['getUidAndFilename', 'isFile', 'isExcluded'])
+ ->setConstructorArgs([new View(), new Manager(
+ $this->config,
+ $this->createMock(ICacheFactory::class),
+ $this->createMock(IEventDispatcher::class)
+ ), $this->groupManager, $this->config, $this->arrayCache])
+ ->getMock();
+ $this->util->expects($this->any())
+ ->method('getUidAndFilename')
+ ->willReturnCallback(function ($path) {
+ return ['user1', $path];
+ });
+
+ $this->file = $this->getMockBuilder(\OC\Encryption\File::class)
+ ->disableOriginalConstructor()
+ ->setMethods(['getAccessList'])
+ ->getMock();
+ $this->file->expects($this->any())->method('getAccessList')->willReturn([]);
+
+ $this->logger = $this->createMock(LoggerInterface::class);
+
+ $this->sourceStorage = new Temporary([]);
+
+ $this->keyStore = $this->getMockBuilder(\OC\Encryption\Keys\Storage::class)
+ ->disableOriginalConstructor()->getMock();
+
+ $this->update = $this->getMockBuilder(\OC\Encryption\Update::class)
+ ->disableOriginalConstructor()->getMock();
+
+ $this->mount = $this->getMockBuilder(\OC\Files\Mount\MountPoint::class)
+ ->disableOriginalConstructor()
+ ->setMethods(['getOption'])
+ ->getMock();
+ $this->mount->expects($this->any())->method('getOption')->willReturnCallback(function ($option, $default) {
+ if ($option === 'encrypt' && $default === true) {
+ global $mockedMountPointEncryptionEnabled;
+ if ($mockedMountPointEncryptionEnabled !== null) {
+ return $mockedMountPointEncryptionEnabled;
+ }
+ }
+ return true;
+ });
+
+ $this->cache = $this->getMockBuilder(\OC\Files\Cache\Cache::class)
+ ->disableOriginalConstructor()->getMock();
+ $this->cache->expects($this->any())
+ ->method('get')
+ ->willReturnCallback(function ($path) {
+ return ['encrypted' => false, 'path' => $path];
+ });
+
+ $this->mountManager = $this->createMock(\OC\Files\Mount\Manager::class);
+ $this->mountManager->method('findByStorageId')
+ ->willReturn([]);
+
+ $this->instance = $this->getMockBuilder(\OC\Files\Storage\Wrapper\Encryption::class)
+ ->setConstructorArgs(
+ [
+ [
+ 'storage' => $this->sourceStorage,
+ 'root' => 'foo',
+ 'mountPoint' => '/',
+ 'mount' => $this->mount
+ ],
+ $this->encryptionManager, $this->util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager, $this->arrayCache
+ ]
+ )
+ ->setMethods(['getMetaData', 'getCache', 'getEncryptionModule'])
+ ->getMock();
+
+ $this->instance->expects($this->any())
+ ->method('getMetaData')
+ ->willReturnCallback(function ($path) {
+ return ['encrypted' => true, 'size' => $this->dummySize, 'path' => $path];
+ });
+
+ $this->instance->expects($this->any())
+ ->method('getCache')
+ ->willReturn($this->cache);
+
+ $this->instance->expects($this->any())
+ ->method('getEncryptionModule')
+ ->willReturn($mockModule);
+ }
+
+ /**
+ * @return \PHPUnit\Framework\MockObject\MockObject
+ */
+ protected function buildMockModule() {
+ $this->encryptionModule = $this->getMockBuilder(\OCP\Encryption\IEncryptionModule::class)
+ ->disableOriginalConstructor()
+ ->setMethods(['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');
+ $this->encryptionModule->expects($this->any())->method('getDisplayName')->willReturn('Unit test module');
+ $this->encryptionModule->expects($this->any())->method('begin')->willReturn([]);
+ $this->encryptionModule->expects($this->any())->method('end')->willReturn('');
+ $this->encryptionModule->expects($this->any())->method('encrypt')->willReturnArgument(0);
+ $this->encryptionModule->expects($this->any())->method('decrypt')->willReturnArgument(0);
+ $this->encryptionModule->expects($this->any())->method('update')->willReturn(true);
+ $this->encryptionModule->expects($this->any())->method('shouldEncrypt')->willReturn(true);
+ $this->encryptionModule->expects($this->any())->method('getUnencryptedBlockSize')->willReturn(8192);
+ $this->encryptionModule->expects($this->any())->method('isReadable')->willReturn(true);
+ $this->encryptionModule->expects($this->any())->method('needDetailedAccessList')->willReturn(false);
+ return $this->encryptionModule;
+ }
+
+ /**
+ * @dataProvider dataTestGetMetaData
+ *
+ * @param string $path
+ * @param array $metaData
+ * @param bool $encrypted
+ * @param bool $unencryptedSizeSet
+ * @param int $storedUnencryptedSize
+ * @param array $expected
+ */
+ public function testGetMetaData($path, $metaData, $encrypted, $unencryptedSizeSet, $storedUnencryptedSize, $expected): void {
+ $sourceStorage = $this->getMockBuilder(\OC\Files\Storage\Storage::class)
+ ->disableOriginalConstructor()->getMock();
+
+ $cache = $this->getMockBuilder(\OC\Files\Cache\Cache::class)
+ ->disableOriginalConstructor()->getMock();
+ $cache->expects($this->any())
+ ->method('get')
+ ->willReturnCallback(
+ function ($path) use ($encrypted) {
+ return new CacheEntry(['encrypted' => $encrypted, 'path' => $path, 'size' => 0, 'fileid' => 1]);
+ }
+ );
+
+ $this->instance = $this->getMockBuilder(\OC\Files\Storage\Wrapper\Encryption::class)
+ ->setConstructorArgs(
+ [
+ [
+ 'storage' => $sourceStorage,
+ 'root' => 'foo',
+ 'mountPoint' => '/',
+ 'mount' => $this->mount
+ ],
+ $this->encryptionManager, $this->util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager, $this->arrayCache
+ ]
+ )
+ ->setMethods(['getCache', 'verifyUnencryptedSize'])
+ ->getMock();
+
+ if ($unencryptedSizeSet) {
+ $this->invokePrivate($this->instance, 'unencryptedSize', [[$path => $storedUnencryptedSize]]);
+ }
+
+ $fileEntry = $this->getMockBuilder(\OC\Files\Cache\Cache::class)
+ ->disableOriginalConstructor()->getMock();
+ $sourceStorage->expects($this->once())->method('getMetaData')->with($path)
+ ->willReturn($metaData);
+ $sourceStorage->expects($this->any())
+ ->method('getCache')
+ ->with($path)
+ ->willReturn($fileEntry);
+ if ($metaData !== null) {
+ $fileEntry->expects($this->any())
+ ->method('get')
+ ->with($metaData['fileid']);
+ }
+
+ $this->instance->expects($this->any())->method('getCache')->willReturn($cache);
+ if ($expected !== null) {
+ $this->instance->expects($this->any())->method('verifyUnencryptedSize')
+ ->with($path, 0)->willReturn($expected['size']);
+ }
+
+ $result = $this->instance->getMetaData($path);
+ if (isset($expected['encrypted'])) {
+ $this->assertSame($expected['encrypted'], (bool)$result['encrypted']);
+
+ if (isset($expected['encryptedVersion'])) {
+ $this->assertSame($expected['encryptedVersion'], $result['encryptedVersion']);
+ }
+ }
+
+ if ($expected !== null) {
+ $this->assertSame($expected['size'], $result['size']);
+ } else {
+ $this->assertSame(null, $result);
+ }
+ }
+
+ public function dataTestGetMetaData() {
+ 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],
+ ['/test.txt', ['size' => 42, 'encrypted' => 0, 'fileid' => 1], false, false, 12, ['size' => 42, 'encrypted' => false]],
+ ['/test.txt', ['size' => 42, 'encrypted' => false, 'fileid' => 1], true, false, 12, ['size' => 12, 'encrypted' => true]]
+ ];
+ }
+
+ public function testFilesize(): void {
+ $cache = $this->getMockBuilder(\OC\Files\Cache\Cache::class)
+ ->disableOriginalConstructor()->getMock();
+ $cache->expects($this->any())
+ ->method('get')
+ ->willReturn(new CacheEntry(['encrypted' => true, 'path' => '/test.txt', 'size' => 0, 'fileid' => 1]));
+
+ $this->instance = $this->getMockBuilder(\OC\Files\Storage\Wrapper\Encryption::class)
+ ->setConstructorArgs(
+ [
+ [
+ 'storage' => $this->sourceStorage,
+ 'root' => 'foo',
+ 'mountPoint' => '/',
+ 'mount' => $this->mount
+ ],
+ $this->encryptionManager, $this->util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager, $this->arrayCache
+ ]
+ )
+ ->setMethods(['getCache', 'verifyUnencryptedSize'])
+ ->getMock();
+
+ $this->instance->expects($this->any())->method('getCache')->willReturn($cache);
+ $this->instance->expects($this->any())->method('verifyUnencryptedSize')
+ ->willReturn(42);
+
+
+ $this->assertSame(42,
+ $this->instance->filesize('/test.txt')
+ );
+ }
+
+ /**
+ * @dataProvider dataTestVerifyUnencryptedSize
+ *
+ * @param int $encryptedSize
+ * @param int $unencryptedSize
+ * @param bool $failure
+ * @param int $expected
+ */
+ public function testVerifyUnencryptedSize($encryptedSize, $unencryptedSize, $failure, $expected): void {
+ $sourceStorage = $this->getMockBuilder(\OC\Files\Storage\Storage::class)
+ ->disableOriginalConstructor()->getMock();
+
+ $this->instance = $this->getMockBuilder(\OC\Files\Storage\Wrapper\Encryption::class)
+ ->setConstructorArgs(
+ [
+ [
+ 'storage' => $sourceStorage,
+ 'root' => 'foo',
+ 'mountPoint' => '/',
+ 'mount' => $this->mount
+ ],
+ $this->encryptionManager, $this->util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager, $this->arrayCache
+ ]
+ )
+ ->setMethods(['fixUnencryptedSize'])
+ ->getMock();
+
+ $sourceStorage->expects($this->once())->method('filesize')->willReturn($encryptedSize);
+
+ $this->instance->expects($this->any())->method('fixUnencryptedSize')
+ ->with('/test.txt', $encryptedSize, $unencryptedSize)
+ ->willReturnCallback(
+ function () use ($failure, $expected) {
+ if ($failure) {
+ throw new \Exception();
+ } else {
+ return $expected;
+ }
+ }
+ );
+
+ $this->assertSame(
+ $expected,
+ $this->invokePrivate($this->instance, 'verifyUnencryptedSize', ['/test.txt', $unencryptedSize])
+ );
+ }
+
+ public function dataTestVerifyUnencryptedSize() {
+ return [
+ [120, 80, false, 80],
+ [120, 120, false, 80],
+ [120, -1, false, 80],
+ [120, -1, true, -1]
+ ];
+ }
+
+ /**
+ * @dataProvider dataTestCopyAndRename
+ *
+ * @param string $source
+ * @param string $target
+ * @param $encryptionEnabled
+ * @param boolean $renameKeysReturn
+ */
+ public function testRename($source,
+ $target,
+ $encryptionEnabled,
+ $renameKeysReturn): void {
+ if ($encryptionEnabled) {
+ $this->keyStore
+ ->expects($this->once())
+ ->method('renameKeys')
+ ->willReturn($renameKeysReturn);
+ } else {
+ $this->keyStore
+ ->expects($this->never())->method('renameKeys');
+ }
+ $this->util->expects($this->any())
+ ->method('isFile')->willReturn(true);
+ $this->encryptionManager->expects($this->once())
+ ->method('isEnabled')->willReturn($encryptionEnabled);
+
+ $this->instance->mkdir($source);
+ $this->instance->mkdir(dirname($target));
+ $this->instance->rename($source, $target);
+ }
+
+ public function testCopyEncryption(): void {
+ $this->instance->file_put_contents('source.txt', 'bar');
+ $this->instance->copy('source.txt', 'target.txt');
+ $this->assertSame('bar', $this->instance->file_get_contents('target.txt'));
+ $targetMeta = $this->instance->getMetaData('target.txt');
+ $sourceMeta = $this->instance->getMetaData('source.txt');
+ $this->assertSame($sourceMeta['encrypted'], $targetMeta['encrypted']);
+ $this->assertSame($sourceMeta['size'], $targetMeta['size']);
+ }
+
+ /**
+ * data provider for testCopyTesting() and dataTestCopyAndRename()
+ *
+ * @return array
+ */
+ public function dataTestCopyAndRename() {
+ return [
+ ['source', 'target', true, false, false],
+ ['source', 'target', true, true, false],
+ ['source', '/subFolder/target', true, false, false],
+ ['source', '/subFolder/target', true, true, true],
+ ['source', '/subFolder/target', false, true, false],
+ ];
+ }
+
+ public function testIsLocal(): void {
+ $this->encryptionManager->expects($this->once())
+ ->method('isEnabled')->willReturn(true);
+ $this->assertFalse($this->instance->isLocal());
+ }
+
+ /**
+ * @dataProvider dataTestRmdir
+ *
+ * @param string $path
+ * @param boolean $rmdirResult
+ * @param boolean $isExcluded
+ * @param boolean $encryptionEnabled
+ */
+ public function testRmdir($path, $rmdirResult, $isExcluded, $encryptionEnabled): void {
+ $sourceStorage = $this->getMockBuilder(\OC\Files\Storage\Storage::class)
+ ->disableOriginalConstructor()->getMock();
+
+ $util = $this->getMockBuilder(\OC\Encryption\Util::class)->disableOriginalConstructor()->getMock();
+
+ $sourceStorage->expects($this->once())->method('rmdir')->willReturn($rmdirResult);
+ $util->expects($this->any())->method('isExcluded')-> willReturn($isExcluded);
+ $this->encryptionManager->expects($this->any())->method('isEnabled')->willReturn($encryptionEnabled);
+
+ $encryptionStorage = new \OC\Files\Storage\Wrapper\Encryption(
+ [
+ 'storage' => $sourceStorage,
+ 'root' => 'foo',
+ 'mountPoint' => '/mountPoint',
+ 'mount' => $this->mount
+ ],
+ $this->encryptionManager, $util, $this->logger, $this->file, null, $this->keyStore, $this->update
+ );
+
+
+ if ($rmdirResult === true && $isExcluded === false && $encryptionEnabled === true) {
+ $this->keyStore->expects($this->once())->method('deleteAllFileKeys')->with('/mountPoint' . $path);
+ } else {
+ $this->keyStore->expects($this->never())->method('deleteAllFileKeys');
+ }
+
+ $encryptionStorage->rmdir($path);
+ }
+
+ public function dataTestRmdir() {
+ return [
+ ['/file.txt', true, true, true],
+ ['/file.txt', false, true, true],
+ ['/file.txt', true, false, true],
+ ['/file.txt', false, false, true],
+ ['/file.txt', true, true, false],
+ ['/file.txt', false, true, false],
+ ['/file.txt', true, false, false],
+ ['/file.txt', false, false, false],
+ ];
+ }
+
+ /**
+ * @dataProvider dataTestCopyKeys
+ *
+ * @param boolean $excluded
+ * @param boolean $expected
+ */
+ public function testCopyKeys($excluded, $expected): void {
+ $this->util->expects($this->once())
+ ->method('isExcluded')
+ ->willReturn($excluded);
+
+ if ($excluded) {
+ $this->keyStore->expects($this->never())->method('copyKeys');
+ } else {
+ $this->keyStore->expects($this->once())->method('copyKeys')->willReturn(true);
+ }
+
+ $this->assertSame($expected,
+ self::invokePrivate($this->instance, 'copyKeys', ['/source', '/target'])
+ );
+ }
+
+ public function dataTestCopyKeys() {
+ return [
+ [true, false],
+ [false, true],
+ ];
+ }
+
+ /**
+ * @dataProvider dataTestGetHeader
+ *
+ * @param string $path
+ * @param bool $strippedPathExists
+ * @param string $strippedPath
+ */
+ public function testGetHeader($path, $strippedPathExists, $strippedPath): void {
+ $sourceStorage = $this->getMockBuilder(\OC\Files\Storage\Storage::class)
+ ->disableOriginalConstructor()->getMock();
+
+ $util = $this->getMockBuilder(\OC\Encryption\Util::class)
+ ->setConstructorArgs(
+ [
+ new View(),
+ new Manager(
+ $this->config,
+ $this->createMock(ICacheFactory::class),
+ $this->createMock(IEventDispatcher::class)
+ ),
+ $this->groupManager,
+ $this->config,
+ $this->arrayCache
+ ]
+ )->getMock();
+
+ $cache = $this->getMockBuilder(\OC\Files\Cache\Cache::class)
+ ->disableOriginalConstructor()->getMock();
+ $cache->expects($this->any())
+ ->method('get')
+ ->willReturnCallback(function ($path) {
+ return ['encrypted' => true, 'path' => $path];
+ });
+
+ $instance = $this->getMockBuilder(\OC\Files\Storage\Wrapper\Encryption::class)
+ ->setConstructorArgs(
+ [
+ [
+ 'storage' => $sourceStorage,
+ 'root' => 'foo',
+ 'mountPoint' => '/',
+ 'mount' => $this->mount
+ ],
+ $this->encryptionManager, $util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager, $this->arrayCache
+ ]
+ )
+ ->setMethods(['getCache', 'readFirstBlock'])
+ ->getMock();
+
+ $instance->method('getCache')->willReturn($cache);
+
+ $util->method('parseRawHeader')
+ ->willReturn([Util::HEADER_ENCRYPTION_MODULE_KEY => 'OC_DEFAULT_MODULE']);
+
+ if ($strippedPathExists) {
+ $instance->method('readFirstBlock')
+ ->with($strippedPath)->willReturn('');
+ } else {
+ $instance->method('readFirstBlock')
+ ->with($path)->willReturn('');
+ }
+
+ $util->expects($this->once())->method('stripPartialFileExtension')
+ ->with($path)->willReturn($strippedPath);
+ $sourceStorage->expects($this->once())
+ ->method('is_file')
+ ->with($strippedPath)
+ ->willReturn($strippedPathExists);
+
+ $this->invokePrivate($instance, 'getHeader', [$path]);
+ }
+
+ public function dataTestGetHeader() {
+ return [
+ ['/foo/bar.txt', false, '/foo/bar.txt'],
+ ['/foo/bar.txt.part', false, '/foo/bar.txt'],
+ ['/foo/bar.txt.ocTransferId7437493.part', false, '/foo/bar.txt'],
+ ['/foo/bar.txt.part', true, '/foo/bar.txt'],
+ ['/foo/bar.txt.ocTransferId7437493.part', true, '/foo/bar.txt'],
+ ];
+ }
+
+ /**
+ * test if getHeader adds the default module correctly to the header for
+ * legacy files
+ *
+ * @dataProvider dataTestGetHeaderAddLegacyModule
+ */
+ public function testGetHeaderAddLegacyModule($header, $isEncrypted, $exists, $expected): void {
+ $sourceStorage = $this->getMockBuilder(\OC\Files\Storage\Storage::class)
+ ->disableOriginalConstructor()->getMock();
+
+ $sourceStorage->expects($this->once())
+ ->method('is_file')
+ ->willReturn($exists);
+
+ $util = $this->getMockBuilder(\OC\Encryption\Util::class)
+ ->setConstructorArgs([new View(), new Manager(
+ $this->config,
+ $this->createMock(ICacheFactory::class),
+ $this->createMock(IEventDispatcher::class)
+ ), $this->groupManager, $this->config, $this->arrayCache])
+ ->getMock();
+
+ $cache = $this->getMockBuilder(\OC\Files\Cache\Cache::class)
+ ->disableOriginalConstructor()->getMock();
+ $cache->expects($this->any())
+ ->method('get')
+ ->willReturnCallback(function ($path) use ($isEncrypted) {
+ return ['encrypted' => $isEncrypted, 'path' => $path];
+ });
+
+ $instance = $this->getMockBuilder(\OC\Files\Storage\Wrapper\Encryption::class)
+ ->setConstructorArgs(
+ [
+ [
+ 'storage' => $sourceStorage,
+ 'root' => 'foo',
+ 'mountPoint' => '/',
+ 'mount' => $this->mount
+ ],
+ $this->encryptionManager, $util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager, $this->arrayCache
+ ]
+ )
+ ->setMethods(['readFirstBlock', 'getCache'])
+ ->getMock();
+
+ $instance->method('readFirstBlock')->willReturn('');
+
+ $util->method(('parseRawHeader'))->willReturn($header);
+ $instance->method('getCache')->willReturn($cache);
+
+ $result = $this->invokePrivate($instance, 'getHeader', ['test.txt']);
+ $this->assertSameSize($expected, $result);
+ foreach ($result as $key => $value) {
+ $this->assertArrayHasKey($key, $expected);
+ $this->assertSame($expected[$key], $value);
+ }
+ }
+
+ public function dataTestGetHeaderAddLegacyModule() {
+ return [
+ [['cipher' => 'AES-128'], true, true, ['cipher' => 'AES-128', Util::HEADER_ENCRYPTION_MODULE_KEY => 'OC_DEFAULT_MODULE']],
+ [[], true, false, []],
+ [[], true, true, [Util::HEADER_ENCRYPTION_MODULE_KEY => 'OC_DEFAULT_MODULE']],
+ [[], false, true, []],
+ ];
+ }
+
+ public function dataCopyBetweenStorage() {
+ return [
+ [true, true, true],
+ [true, false, false],
+ [false, true, false],
+ [false, false, false],
+ ];
+ }
+
+ public function testCopyBetweenStorageMinimumEncryptedVersion(): void {
+ $storage2 = $this->createMock(\OC\Files\Storage\Storage::class);
+
+ $sourceInternalPath = $targetInternalPath = 'file.txt';
+ $preserveMtime = $isRename = false;
+
+ $storage2->expects($this->any())
+ ->method('fopen')
+ ->willReturnCallback(function ($path, $mode) {
+ $temp = \OC::$server->getTempManager();
+ return fopen($temp->getTemporaryFile(), $mode);
+ });
+ $storage2->method('getId')
+ ->willReturn('stroage2');
+ $cache = $this->createMock(ICache::class);
+ $cache->expects($this->once())
+ ->method('get')
+ ->with($sourceInternalPath)
+ ->willReturn(['encryptedVersion' => 0]);
+ $storage2->expects($this->once())
+ ->method('getCache')
+ ->willReturn($cache);
+ $this->encryptionManager->expects($this->any())
+ ->method('isEnabled')
+ ->willReturn(true);
+ global $mockedMountPointEncryptionEnabled;
+ $mockedMountPointEncryptionEnabled = true;
+
+ $expectedCachePut = [
+ 'encrypted' => true,
+ ];
+ $expectedCachePut['encryptedVersion'] = 1;
+
+ $this->cache->expects($this->once())
+ ->method('put')
+ ->with($sourceInternalPath, $expectedCachePut);
+
+ $this->invokePrivate($this->instance, 'copyBetweenStorage', [$storage2, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename]);
+
+ $this->assertFalse(false);
+ }
+
+ /**
+ * @dataProvider dataCopyBetweenStorage
+ *
+ * @param bool $encryptionEnabled
+ * @param bool $mountPointEncryptionEnabled
+ * @param bool $expectedEncrypted
+ */
+ public function testCopyBetweenStorage($encryptionEnabled, $mountPointEncryptionEnabled, $expectedEncrypted): void {
+ $storage2 = $this->createMock(\OC\Files\Storage\Storage::class);
+
+ $sourceInternalPath = $targetInternalPath = 'file.txt';
+ $preserveMtime = $isRename = false;
+
+ $storage2->expects($this->any())
+ ->method('fopen')
+ ->willReturnCallback(function ($path, $mode) {
+ $temp = \OC::$server->getTempManager();
+ return fopen($temp->getTemporaryFile(), $mode);
+ });
+ $storage2->method('getId')
+ ->willReturn('stroage2');
+ if ($expectedEncrypted) {
+ $cache = $this->createMock(ICache::class);
+ $cache->expects($this->once())
+ ->method('get')
+ ->with($sourceInternalPath)
+ ->willReturn(['encryptedVersion' => 12345]);
+ $storage2->expects($this->once())
+ ->method('getCache')
+ ->willReturn($cache);
+ }
+ $this->encryptionManager->expects($this->any())
+ ->method('isEnabled')
+ ->willReturn($encryptionEnabled);
+ // FIXME can not overwrite the return after definition
+ // $this->mount->expects($this->at(0))
+ // ->method('getOption')
+ // ->with('encrypt', true)
+ // ->willReturn($mountPointEncryptionEnabled);
+ global $mockedMountPointEncryptionEnabled;
+ $mockedMountPointEncryptionEnabled = $mountPointEncryptionEnabled;
+
+ $expectedCachePut = [
+ 'encrypted' => $expectedEncrypted,
+ ];
+ if ($expectedEncrypted === true) {
+ $expectedCachePut['encryptedVersion'] = 1;
+ }
+
+ $this->arrayCache->expects($this->never())->method('set');
+
+ $this->cache->expects($this->once())
+ ->method('put')
+ ->with($sourceInternalPath, $expectedCachePut);
+
+ $this->invokePrivate($this->instance, 'copyBetweenStorage', [$storage2, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename]);
+
+ $this->assertFalse(false);
+ }
+
+ /**
+ * @dataProvider dataTestCopyBetweenStorageVersions
+ *
+ * @param string $sourceInternalPath
+ * @param string $targetInternalPath
+ * @param bool $copyResult
+ * @param bool $encrypted
+ */
+ public function testCopyBetweenStorageVersions($sourceInternalPath, $targetInternalPath, $copyResult, $encrypted): void {
+ $sourceStorage = $this->createMock(\OC\Files\Storage\Storage::class);
+
+ $targetStorage = $this->createMock(\OC\Files\Storage\Storage::class);
+
+ $cache = $this->getMockBuilder(\OC\Files\Cache\Cache::class)
+ ->disableOriginalConstructor()->getMock();
+
+ $mountPoint = '/mountPoint';
+
+ /** @var \OC\Files\Storage\Wrapper\Encryption |\PHPUnit\Framework\MockObject\MockObject $instance */
+ $instance = $this->getMockBuilder(\OC\Files\Storage\Wrapper\Encryption::class)
+ ->setConstructorArgs(
+ [
+ [
+ 'storage' => $targetStorage,
+ 'root' => 'foo',
+ 'mountPoint' => $mountPoint,
+ 'mount' => $this->mount
+ ],
+ $this->encryptionManager,
+ $this->util,
+ $this->logger,
+ $this->file,
+ null,
+ $this->keyStore,
+ $this->update,
+ $this->mountManager,
+ $this->arrayCache
+ ]
+ )
+ ->setMethods(['updateUnencryptedSize', 'getCache'])
+ ->getMock();
+
+ $targetStorage->expects($this->once())->method('copyFromStorage')
+ ->with($sourceStorage, $sourceInternalPath, $targetInternalPath)
+ ->willReturn($copyResult);
+
+ $instance->expects($this->any())->method('getCache')
+ ->willReturn($cache);
+
+ $this->arrayCache->expects($this->once())->method('set')
+ ->with('encryption_copy_version_' . $sourceInternalPath, true);
+
+ if ($copyResult) {
+ $cache->expects($this->once())->method('get')
+ ->with($sourceInternalPath)
+ ->willReturn(new CacheEntry(['encrypted' => $encrypted, 'size' => 42]));
+ if ($encrypted) {
+ $instance->expects($this->once())->method('updateUnencryptedSize')
+ ->with($mountPoint . $targetInternalPath, 42);
+ } else {
+ $instance->expects($this->never())->method('updateUnencryptedSize');
+ }
+ } else {
+ $instance->expects($this->never())->method('updateUnencryptedSize');
+ }
+
+ $result = $this->invokePrivate(
+ $instance,
+ 'copyBetweenStorage',
+ [
+ $sourceStorage,
+ $sourceInternalPath,
+ $targetInternalPath,
+ false,
+ false
+ ]
+ );
+
+ $this->assertSame($copyResult, $result);
+ }
+
+ public function dataTestCopyBetweenStorageVersions() {
+ return [
+ ['/files/foo.txt', '/files_versions/foo.txt.768743', true, true],
+ ['/files/foo.txt', '/files_versions/foo.txt.768743', true, false],
+ ['/files/foo.txt', '/files_versions/foo.txt.768743', false, true],
+ ['/files/foo.txt', '/files_versions/foo.txt.768743', false, false],
+ ['/files_versions/foo.txt.6487634', '/files/foo.txt', true, true],
+ ['/files_versions/foo.txt.6487634', '/files/foo.txt', true, false],
+ ['/files_versions/foo.txt.6487634', '/files/foo.txt', false, true],
+ ['/files_versions/foo.txt.6487634', '/files/foo.txt', false, false],
+
+ ];
+ }
+
+ /**
+ * @dataProvider dataTestIsVersion
+ * @param string $path
+ * @param bool $expected
+ */
+ public function testIsVersion($path, $expected): void {
+ $this->assertSame($expected,
+ $this->invokePrivate($this->instance, 'isVersion', [$path])
+ );
+ }
+
+ public function dataTestIsVersion() {
+ return [
+ ['files_versions/foo', true],
+ ['/files_versions/foo', true],
+ ['//files_versions/foo', true],
+ ['files/versions/foo', false],
+ ['files/files_versions/foo', false],
+ ['files_versions_test/foo', false],
+ ];
+ }
+
+ /**
+ * @dataProvider dataTestShouldEncrypt
+ *
+ * @param bool $encryptMountPoint
+ * @param mixed $encryptionModule
+ * @param bool $encryptionModuleShouldEncrypt
+ * @param bool $expected
+ */
+ public function testShouldEncrypt(
+ $encryptMountPoint,
+ $encryptionModule,
+ $encryptionModuleShouldEncrypt,
+ $expected
+ ): void {
+ $encryptionManager = $this->createMock(\OC\Encryption\Manager::class);
+ $util = $this->createMock(Util::class);
+ $fileHelper = $this->createMock(IFile::class);
+ $uid = null;
+ $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);
+ $path = '/welcome.txt';
+ $fullPath = 'admin/files/welcome.txt';
+ $defaultEncryptionModule = $this->createMock(IEncryptionModule::class);
+
+ $wrapper = $this->getMockBuilder(Encryption::class)
+ ->setConstructorArgs(
+ [
+ ['mountPoint' => '', 'mount' => $mount, 'storage' => ''],
+ $encryptionManager,
+ $util,
+ $this->logger,
+ $fileHelper,
+ $uid,
+ $keyStorage,
+ $update,
+ $mountManager,
+ $arrayCache
+ ]
+ )
+ ->setMethods(['getFullPath', 'getEncryptionModule'])
+ ->getMock();
+
+ if ($encryptionModule === true) {
+ /** @var IEncryptionModule|\PHPUnit\Framework\MockObject\MockObject $encryptionModule */
+ $encryptionModule = $this->createMock(IEncryptionModule::class);
+ }
+
+ $wrapper->method('getFullPath')->with($path)->willReturn($fullPath);
+ $wrapper->expects($encryptMountPoint ? $this->once() : $this->never())
+ ->method('getEncryptionModule')
+ ->with($fullPath)
+ ->willReturnCallback(
+ function () use ($encryptionModule) {
+ if ($encryptionModule === false) {
+ throw new ModuleDoesNotExistsException();
+ }
+ return $encryptionModule;
+ }
+ );
+ $mount->expects($this->once())->method('getOption')->with('encrypt', true)
+ ->willReturn($encryptMountPoint);
+
+ if ($encryptionModule !== null && $encryptionModule !== false) {
+ $encryptionModule
+ ->method('shouldEncrypt')
+ ->with($fullPath)
+ ->willReturn($encryptionModuleShouldEncrypt);
+ }
+
+ if ($encryptionModule === null) {
+ $encryptionManager->expects($this->once())
+ ->method('getEncryptionModule')
+ ->willReturn($defaultEncryptionModule);
+ }
+ $defaultEncryptionModule->method('shouldEncrypt')->willReturn(true);
+
+ $result = $this->invokePrivate($wrapper, 'shouldEncrypt', [$path]);
+
+ $this->assertSame($expected, $result);
+ }
+
+ public function dataTestShouldEncrypt() {
+ return [
+ [false, false, false, false],
+ [true, false, false, false],
+ [true, true, false, false],
+ [true, true, true, true],
+ [true, null, false, true],
+ ];
+ }
+}
diff --git a/tests/lib/Files/Storage/Wrapper/JailTest.php b/tests/lib/Files/Storage/Wrapper/JailTest.php
index fb2d05d0691..fbc4e1d09ee 100644
--- a/tests/lib/Files/Storage/Wrapper/JailTest.php
+++ b/tests/lib/Files/Storage/Wrapper/JailTest.php
@@ -37,12 +37,12 @@ class JailTest extends \Test\Files\Storage\Storage {
parent::tearDown();
}
- public function testMkDirRooted() {
+ public function testMkDirRooted(): void {
$this->instance->mkdir('bar');
$this->assertTrue($this->sourceStorage->is_dir('foo/bar'));
}
- public function testFilePutContentsRooted() {
+ public function testFilePutContentsRooted(): void {
$this->instance->file_put_contents('bar', 'asd');
$this->assertEquals('asd', $this->sourceStorage->file_get_contents('foo/bar'));
}
diff --git a/tests/lib/Files/Storage/Wrapper/KnownMtimeTest.php b/tests/lib/Files/Storage/Wrapper/KnownMtimeTest.php
index ccc95de1002..bbeb48c5cef 100644
--- a/tests/lib/Files/Storage/Wrapper/KnownMtimeTest.php
+++ b/tests/lib/Files/Storage/Wrapper/KnownMtimeTest.php
@@ -50,7 +50,7 @@ class KnownMtimeTest extends Storage {
]);
}
- public function testNewerKnownMtime() {
+ public function testNewerKnownMtime(): void {
$future = time() + 1000;
$this->fakeTime = $future;
diff --git a/tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php b/tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php
index 4e5324651a0..e082e9ef06e 100644
--- a/tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php
+++ b/tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php
@@ -38,13 +38,13 @@ class PermissionsMaskTest extends \Test\Files\Storage\Storage {
]);
}
- public function testMkdirNoCreate() {
+ public function testMkdirNoCreate(): void {
$storage = $this->getMaskedStorage(Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE);
$this->assertFalse($storage->mkdir('foo'));
$this->assertFalse($storage->file_exists('foo'));
}
- public function testRmdirNoDelete() {
+ public function testRmdirNoDelete(): void {
$storage = $this->getMaskedStorage(Constants::PERMISSION_ALL - Constants::PERMISSION_DELETE);
$this->assertTrue($storage->mkdir('foo'));
$this->assertTrue($storage->file_exists('foo'));
@@ -52,25 +52,25 @@ class PermissionsMaskTest extends \Test\Files\Storage\Storage {
$this->assertTrue($storage->file_exists('foo'));
}
- public function testTouchNewFileNoCreate() {
+ public function testTouchNewFileNoCreate(): void {
$storage = $this->getMaskedStorage(Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE);
$this->assertFalse($storage->touch('foo'));
$this->assertFalse($storage->file_exists('foo'));
}
- public function testTouchNewFileNoUpdate() {
+ public function testTouchNewFileNoUpdate(): void {
$storage = $this->getMaskedStorage(Constants::PERMISSION_ALL - Constants::PERMISSION_UPDATE);
$this->assertTrue($storage->touch('foo'));
$this->assertTrue($storage->file_exists('foo'));
}
- public function testTouchExistingFileNoUpdate() {
+ public function testTouchExistingFileNoUpdate(): void {
$this->sourceStorage->touch('foo');
$storage = $this->getMaskedStorage(Constants::PERMISSION_ALL - Constants::PERMISSION_UPDATE);
$this->assertFalse($storage->touch('foo'));
}
- public function testUnlinkNoDelete() {
+ public function testUnlinkNoDelete(): void {
$storage = $this->getMaskedStorage(Constants::PERMISSION_ALL - Constants::PERMISSION_DELETE);
$this->assertTrue($storage->touch('foo'));
$this->assertTrue($storage->file_exists('foo'));
@@ -78,35 +78,35 @@ class PermissionsMaskTest extends \Test\Files\Storage\Storage {
$this->assertTrue($storage->file_exists('foo'));
}
- public function testPutContentsNewFileNoUpdate() {
+ public function testPutContentsNewFileNoUpdate(): void {
$storage = $this->getMaskedStorage(Constants::PERMISSION_ALL - Constants::PERMISSION_UPDATE);
$this->assertEquals(3, $storage->file_put_contents('foo', 'bar'));
$this->assertEquals('bar', $storage->file_get_contents('foo'));
}
- public function testPutContentsNewFileNoCreate() {
+ public function testPutContentsNewFileNoCreate(): void {
$storage = $this->getMaskedStorage(Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE);
$this->assertFalse($storage->file_put_contents('foo', 'bar'));
}
- public function testPutContentsExistingFileNoUpdate() {
+ public function testPutContentsExistingFileNoUpdate(): void {
$this->sourceStorage->touch('foo');
$storage = $this->getMaskedStorage(Constants::PERMISSION_ALL - Constants::PERMISSION_UPDATE);
$this->assertFalse($storage->file_put_contents('foo', 'bar'));
}
- public function testFopenExistingFileNoUpdate() {
+ public function testFopenExistingFileNoUpdate(): void {
$this->sourceStorage->touch('foo');
$storage = $this->getMaskedStorage(Constants::PERMISSION_ALL - Constants::PERMISSION_UPDATE);
$this->assertFalse($storage->fopen('foo', 'w'));
}
- public function testFopenNewFileNoCreate() {
+ public function testFopenNewFileNoCreate(): void {
$storage = $this->getMaskedStorage(Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE);
$this->assertFalse($storage->fopen('foo', 'w'));
}
- public function testScanNewFiles() {
+ public function testScanNewFiles(): void {
$storage = $this->getMaskedStorage(Constants::PERMISSION_READ + Constants::PERMISSION_CREATE);
$storage->file_put_contents('foo', 'bar');
$storage->getScanner()->scan('');
@@ -115,7 +115,7 @@ class PermissionsMaskTest extends \Test\Files\Storage\Storage {
$this->assertEquals(Constants::PERMISSION_READ, $storage->getCache()->get('foo')->getPermissions());
}
- public function testScanNewWrappedFiles() {
+ public function testScanNewWrappedFiles(): void {
$storage = $this->getMaskedStorage(Constants::PERMISSION_READ + Constants::PERMISSION_CREATE);
$wrappedStorage = new Wrapper(['storage' => $storage]);
$wrappedStorage->file_put_contents('foo', 'bar');
@@ -125,7 +125,7 @@ class PermissionsMaskTest extends \Test\Files\Storage\Storage {
$this->assertEquals(Constants::PERMISSION_READ, $storage->getCache()->get('foo')->getPermissions());
}
- public function testScanNewFilesNested() {
+ public function testScanNewFilesNested(): void {
$storage = $this->getMaskedStorage(Constants::PERMISSION_READ + Constants::PERMISSION_CREATE + Constants::PERMISSION_UPDATE);
$nestedStorage = new \OC\Files\Storage\Wrapper\PermissionsMask([
'storage' => $storage,
@@ -140,7 +140,7 @@ class PermissionsMaskTest extends \Test\Files\Storage\Storage {
$this->assertEquals(Constants::PERMISSION_READ, $wrappedStorage->getCache()->get('foo')->getPermissions());
}
- public function testScanUnchanged() {
+ public function testScanUnchanged(): void {
$this->sourceStorage->mkdir('foo');
$this->sourceStorage->file_put_contents('foo/bar.txt', 'bar');
@@ -157,7 +157,7 @@ class PermissionsMaskTest extends \Test\Files\Storage\Storage {
$this->assertFalse($called);
}
- public function testScanUnchangedWrapped() {
+ public function testScanUnchangedWrapped(): void {
$this->sourceStorage->mkdir('foo');
$this->sourceStorage->file_put_contents('foo/bar.txt', 'bar');
diff --git a/tests/lib/Files/Storage/Wrapper/QuotaTest.php b/tests/lib/Files/Storage/Wrapper/QuotaTest.php
index ff606855510..8ad3c36d5c1 100644
--- a/tests/lib/Files/Storage/Wrapper/QuotaTest.php
+++ b/tests/lib/Files/Storage/Wrapper/QuotaTest.php
@@ -1,229 +1,229 @@
-<?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\Files\Storage\Wrapper;
-
-//ensure the constants are loaded
-use OC\Files\Cache\CacheEntry;
-use OC\Files\Storage\Local;
-
-\OC::$loader->load(\OC\Files\Filesystem::class);
-
-/**
- * Class QuotaTest
- *
- * @group DB
- *
- * @package Test\Files\Storage\Wrapper
- */
-class QuotaTest extends \Test\Files\Storage\Storage {
- /**
- * @var string tmpDir
- */
- private $tmpDir;
-
- 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]);
- }
-
- protected function tearDown(): void {
- \OC_Helper::rmdirr($this->tmpDir);
- parent::tearDown();
- }
-
- /**
- * @param integer $limit
- */
- protected function getLimitedStorage($limit) {
- $storage = new \OC\Files\Storage\Local(['datadir' => $this->tmpDir]);
- $storage->mkdir('files');
- $storage->getScanner()->scan('');
- return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $limit]);
- }
-
- public function testFilePutContentsNotEnoughSpace() {
- $instance = $this->getLimitedStorage(3);
- $this->assertFalse($instance->file_put_contents('files/foo', 'foobar'));
- }
-
- public function testCopyNotEnoughSpace() {
- $instance = $this->getLimitedStorage(9);
- $this->assertEquals(6, $instance->file_put_contents('files/foo', 'foobar'));
- $instance->getScanner()->scan('');
- $this->assertFalse($instance->copy('files/foo', 'files/bar'));
- }
-
- public function testFreeSpace() {
- $instance = $this->getLimitedStorage(9);
- $this->assertEquals(9, $instance->free_space(''));
- }
-
- public function testFreeSpaceWithUsedSpace() {
- $instance = $this->getLimitedStorage(9);
- $instance->getCache()->put(
- '', ['size' => 3]
- );
- $this->assertEquals(6, $instance->free_space(''));
- }
-
- public function testFreeSpaceWithUnknownDiskSpace() {
- $storage = $this->getMockBuilder(Local::class)
- ->setMethods(['free_space'])
- ->setConstructorArgs([['datadir' => $this->tmpDir]])
- ->getMock();
- $storage->expects($this->any())
- ->method('free_space')
- ->willReturn(-2);
- $storage->getScanner()->scan('');
-
- $instance = new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => 9]);
- $instance->getCache()->put(
- '', ['size' => 3]
- );
- $this->assertEquals(6, $instance->free_space(''));
- }
-
- public function testFreeSpaceWithUsedSpaceAndEncryption() {
- $instance = $this->getLimitedStorage(9);
- $instance->getCache()->put(
- '', ['size' => 7]
- );
- $this->assertEquals(2, $instance->free_space(''));
- }
-
- public function testFWriteNotEnoughSpace() {
- $instance = $this->getLimitedStorage(9);
- $stream = $instance->fopen('files/foo', 'w+');
- $this->assertEquals(6, fwrite($stream, 'foobar'));
- $this->assertEquals(3, fwrite($stream, 'qwerty'));
- fclose($stream);
- $this->assertEquals('foobarqwe', $instance->file_get_contents('files/foo'));
- }
-
- public function testStreamCopyWithEnoughSpace() {
- $instance = $this->getLimitedStorage(16);
- $inputStream = fopen('data://text/plain,foobarqwerty', 'r');
- $outputStream = $instance->fopen('files/foo', 'w+');
- [$count, $result] = \OC_Helper::streamCopy($inputStream, $outputStream);
- $this->assertEquals(12, $count);
- $this->assertTrue($result);
- fclose($inputStream);
- fclose($outputStream);
- }
-
- public function testStreamCopyNotEnoughSpace() {
- $instance = $this->getLimitedStorage(9);
- $inputStream = fopen('data://text/plain,foobarqwerty', 'r');
- $outputStream = $instance->fopen('files/foo', 'w+');
- [$count, $result] = \OC_Helper::streamCopy($inputStream, $outputStream);
- $this->assertEquals(9, $count);
- $this->assertFalse($result);
- fclose($inputStream);
- fclose($outputStream);
- }
-
- public function testReturnFalseWhenFopenFailed() {
- $failStorage = $this->getMockBuilder(Local::class)
- ->setMethods(['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]);
-
- $this->assertFalse($instance->fopen('failedfopen', 'r'));
- }
-
- public function testReturnRegularStreamOnRead() {
- $instance = $this->getLimitedStorage(9);
-
- // create test file first
- $stream = $instance->fopen('files/foo', 'w+');
- fwrite($stream, 'blablacontent');
- fclose($stream);
-
- $stream = $instance->fopen('files/foo', 'r');
- $meta = stream_get_meta_data($stream);
- $this->assertEquals('plainfile', $meta['wrapper_type']);
- fclose($stream);
-
- $stream = $instance->fopen('files/foo', 'rb');
- $meta = stream_get_meta_data($stream);
- $this->assertEquals('plainfile', $meta['wrapper_type']);
- fclose($stream);
- }
-
- public function testReturnRegularStreamWhenOutsideFiles() {
- $instance = $this->getLimitedStorage(9);
- $instance->mkdir('files_other');
-
- // create test file first
- $stream = $instance->fopen('files_other/foo', 'w+');
- $meta = stream_get_meta_data($stream);
- $this->assertEquals('plainfile', $meta['wrapper_type']);
- fclose($stream);
- }
-
- public function testReturnQuotaStreamOnWrite() {
- $instance = $this->getLimitedStorage(9);
- $stream = $instance->fopen('files/foo', 'w+');
- $meta = stream_get_meta_data($stream);
- $expected_type = 'user-space';
- $this->assertEquals($expected_type, $meta['wrapper_type']);
- fclose($stream);
- }
-
- public function testSpaceRoot() {
- $storage = $this->getMockBuilder(Local::class)->disableOriginalConstructor()->getMock();
- $cache = $this->getMockBuilder(\OC\Files\Cache\Cache::class)->disableOriginalConstructor()->getMock();
- $storage->expects($this->once())
- ->method('getCache')
- ->willReturn($cache);
- $storage->expects($this->once())
- ->method('free_space')
- ->willReturn(2048);
- $cache->expects($this->once())
- ->method('get')
- ->with('files')
- ->willReturn(new CacheEntry(['size' => 50]));
-
- $instance = new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => 1024, 'root' => 'files']);
-
- $this->assertEquals(1024 - 50, $instance->free_space(''));
- }
-
- public function testInstanceOfStorageWrapper() {
- $this->assertTrue($this->instance->instanceOfStorage(\OC\Files\Storage\Local::class));
- $this->assertTrue($this->instance->instanceOfStorage(\OC\Files\Storage\Wrapper\Wrapper::class));
- $this->assertTrue($this->instance->instanceOfStorage(\OC\Files\Storage\Wrapper\Quota::class));
- }
-
- public function testNoMkdirQuotaZero() {
- $instance = $this->getLimitedStorage(0.0);
- $this->assertFalse($instance->mkdir('files'));
- $this->assertFalse($instance->mkdir('files/foobar'));
- }
-
- public function testMkdirQuotaZeroTrashbin() {
- $instance = $this->getLimitedStorage(0.0);
- $this->assertTrue($instance->mkdir('files_trashbin'));
- $this->assertTrue($instance->mkdir('files_trashbin/files'));
- $this->assertTrue($instance->mkdir('files_versions'));
- $this->assertTrue($instance->mkdir('cache'));
- }
-
- public function testNoTouchQuotaZero() {
- $instance = $this->getLimitedStorage(0.0);
- $this->assertFalse($instance->touch('foobar'));
- }
-}
+<?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\Files\Storage\Wrapper;
+
+//ensure the constants are loaded
+use OC\Files\Cache\CacheEntry;
+use OC\Files\Storage\Local;
+
+\OC::$loader->load(\OC\Files\Filesystem::class);
+
+/**
+ * Class QuotaTest
+ *
+ * @group DB
+ *
+ * @package Test\Files\Storage\Wrapper
+ */
+class QuotaTest extends \Test\Files\Storage\Storage {
+ /**
+ * @var string tmpDir
+ */
+ private $tmpDir;
+
+ 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]);
+ }
+
+ protected function tearDown(): void {
+ \OC_Helper::rmdirr($this->tmpDir);
+ parent::tearDown();
+ }
+
+ /**
+ * @param integer $limit
+ */
+ protected function getLimitedStorage($limit) {
+ $storage = new \OC\Files\Storage\Local(['datadir' => $this->tmpDir]);
+ $storage->mkdir('files');
+ $storage->getScanner()->scan('');
+ return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $limit]);
+ }
+
+ public function testFilePutContentsNotEnoughSpace(): void {
+ $instance = $this->getLimitedStorage(3);
+ $this->assertFalse($instance->file_put_contents('files/foo', 'foobar'));
+ }
+
+ public function testCopyNotEnoughSpace(): void {
+ $instance = $this->getLimitedStorage(9);
+ $this->assertEquals(6, $instance->file_put_contents('files/foo', 'foobar'));
+ $instance->getScanner()->scan('');
+ $this->assertFalse($instance->copy('files/foo', 'files/bar'));
+ }
+
+ public function testFreeSpace(): void {
+ $instance = $this->getLimitedStorage(9);
+ $this->assertEquals(9, $instance->free_space(''));
+ }
+
+ public function testFreeSpaceWithUsedSpace(): void {
+ $instance = $this->getLimitedStorage(9);
+ $instance->getCache()->put(
+ '', ['size' => 3]
+ );
+ $this->assertEquals(6, $instance->free_space(''));
+ }
+
+ public function testFreeSpaceWithUnknownDiskSpace(): void {
+ $storage = $this->getMockBuilder(Local::class)
+ ->setMethods(['free_space'])
+ ->setConstructorArgs([['datadir' => $this->tmpDir]])
+ ->getMock();
+ $storage->expects($this->any())
+ ->method('free_space')
+ ->willReturn(-2);
+ $storage->getScanner()->scan('');
+
+ $instance = new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => 9]);
+ $instance->getCache()->put(
+ '', ['size' => 3]
+ );
+ $this->assertEquals(6, $instance->free_space(''));
+ }
+
+ public function testFreeSpaceWithUsedSpaceAndEncryption(): void {
+ $instance = $this->getLimitedStorage(9);
+ $instance->getCache()->put(
+ '', ['size' => 7]
+ );
+ $this->assertEquals(2, $instance->free_space(''));
+ }
+
+ public function testFWriteNotEnoughSpace(): void {
+ $instance = $this->getLimitedStorage(9);
+ $stream = $instance->fopen('files/foo', 'w+');
+ $this->assertEquals(6, fwrite($stream, 'foobar'));
+ $this->assertEquals(3, fwrite($stream, 'qwerty'));
+ fclose($stream);
+ $this->assertEquals('foobarqwe', $instance->file_get_contents('files/foo'));
+ }
+
+ public function testStreamCopyWithEnoughSpace(): void {
+ $instance = $this->getLimitedStorage(16);
+ $inputStream = fopen('data://text/plain,foobarqwerty', 'r');
+ $outputStream = $instance->fopen('files/foo', 'w+');
+ [$count, $result] = \OC_Helper::streamCopy($inputStream, $outputStream);
+ $this->assertEquals(12, $count);
+ $this->assertTrue($result);
+ fclose($inputStream);
+ fclose($outputStream);
+ }
+
+ public function testStreamCopyNotEnoughSpace(): void {
+ $instance = $this->getLimitedStorage(9);
+ $inputStream = fopen('data://text/plain,foobarqwerty', 'r');
+ $outputStream = $instance->fopen('files/foo', 'w+');
+ [$count, $result] = \OC_Helper::streamCopy($inputStream, $outputStream);
+ $this->assertEquals(9, $count);
+ $this->assertFalse($result);
+ fclose($inputStream);
+ fclose($outputStream);
+ }
+
+ public function testReturnFalseWhenFopenFailed(): void {
+ $failStorage = $this->getMockBuilder(Local::class)
+ ->setMethods(['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]);
+
+ $this->assertFalse($instance->fopen('failedfopen', 'r'));
+ }
+
+ public function testReturnRegularStreamOnRead(): void {
+ $instance = $this->getLimitedStorage(9);
+
+ // create test file first
+ $stream = $instance->fopen('files/foo', 'w+');
+ fwrite($stream, 'blablacontent');
+ fclose($stream);
+
+ $stream = $instance->fopen('files/foo', 'r');
+ $meta = stream_get_meta_data($stream);
+ $this->assertEquals('plainfile', $meta['wrapper_type']);
+ fclose($stream);
+
+ $stream = $instance->fopen('files/foo', 'rb');
+ $meta = stream_get_meta_data($stream);
+ $this->assertEquals('plainfile', $meta['wrapper_type']);
+ fclose($stream);
+ }
+
+ public function testReturnRegularStreamWhenOutsideFiles(): void {
+ $instance = $this->getLimitedStorage(9);
+ $instance->mkdir('files_other');
+
+ // create test file first
+ $stream = $instance->fopen('files_other/foo', 'w+');
+ $meta = stream_get_meta_data($stream);
+ $this->assertEquals('plainfile', $meta['wrapper_type']);
+ fclose($stream);
+ }
+
+ public function testReturnQuotaStreamOnWrite(): void {
+ $instance = $this->getLimitedStorage(9);
+ $stream = $instance->fopen('files/foo', 'w+');
+ $meta = stream_get_meta_data($stream);
+ $expected_type = 'user-space';
+ $this->assertEquals($expected_type, $meta['wrapper_type']);
+ fclose($stream);
+ }
+
+ public function testSpaceRoot(): void {
+ $storage = $this->getMockBuilder(Local::class)->disableOriginalConstructor()->getMock();
+ $cache = $this->getMockBuilder(\OC\Files\Cache\Cache::class)->disableOriginalConstructor()->getMock();
+ $storage->expects($this->once())
+ ->method('getCache')
+ ->willReturn($cache);
+ $storage->expects($this->once())
+ ->method('free_space')
+ ->willReturn(2048);
+ $cache->expects($this->once())
+ ->method('get')
+ ->with('files')
+ ->willReturn(new CacheEntry(['size' => 50]));
+
+ $instance = new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => 1024, 'root' => 'files']);
+
+ $this->assertEquals(1024 - 50, $instance->free_space(''));
+ }
+
+ public function testInstanceOfStorageWrapper(): void {
+ $this->assertTrue($this->instance->instanceOfStorage(\OC\Files\Storage\Local::class));
+ $this->assertTrue($this->instance->instanceOfStorage(\OC\Files\Storage\Wrapper\Wrapper::class));
+ $this->assertTrue($this->instance->instanceOfStorage(\OC\Files\Storage\Wrapper\Quota::class));
+ }
+
+ public function testNoMkdirQuotaZero(): void {
+ $instance = $this->getLimitedStorage(0.0);
+ $this->assertFalse($instance->mkdir('files'));
+ $this->assertFalse($instance->mkdir('files/foobar'));
+ }
+
+ public function testMkdirQuotaZeroTrashbin(): void {
+ $instance = $this->getLimitedStorage(0.0);
+ $this->assertTrue($instance->mkdir('files_trashbin'));
+ $this->assertTrue($instance->mkdir('files_trashbin/files'));
+ $this->assertTrue($instance->mkdir('files_versions'));
+ $this->assertTrue($instance->mkdir('cache'));
+ }
+
+ public function testNoTouchQuotaZero(): void {
+ $instance = $this->getLimitedStorage(0.0);
+ $this->assertFalse($instance->touch('foobar'));
+ }
+}
diff --git a/tests/lib/Files/Storage/Wrapper/WrapperTest.php b/tests/lib/Files/Storage/Wrapper/WrapperTest.php
index ef84c35abc0..9584af0db8f 100644
--- a/tests/lib/Files/Storage/Wrapper/WrapperTest.php
+++ b/tests/lib/Files/Storage/Wrapper/WrapperTest.php
@@ -1,33 +1,33 @@
-<?php
-/**
- * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
- * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
- * SPDX-License-Identifier: AGPL-3.0-or-later
- */
-
-namespace Test\Files\Storage\Wrapper;
-
-class WrapperTest extends \Test\Files\Storage\Storage {
- /**
- * @var string tmpDir
- */
- private $tmpDir;
-
- 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]);
- }
-
- protected function tearDown(): void {
- \OC_Helper::rmdirr($this->tmpDir);
- parent::tearDown();
- }
-
- public function testInstanceOfStorageWrapper() {
- $this->assertTrue($this->instance->instanceOfStorage(\OC\Files\Storage\Local::class));
- $this->assertTrue($this->instance->instanceOfStorage(\OC\Files\Storage\Wrapper\Wrapper::class));
- }
-}
+<?php
+/**
+ * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+
+namespace Test\Files\Storage\Wrapper;
+
+class WrapperTest extends \Test\Files\Storage\Storage {
+ /**
+ * @var string tmpDir
+ */
+ private $tmpDir;
+
+ 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]);
+ }
+
+ protected function tearDown(): void {
+ \OC_Helper::rmdirr($this->tmpDir);
+ parent::tearDown();
+ }
+
+ public function testInstanceOfStorageWrapper(): void {
+ $this->assertTrue($this->instance->instanceOfStorage(\OC\Files\Storage\Local::class));
+ $this->assertTrue($this->instance->instanceOfStorage(\OC\Files\Storage\Wrapper\Wrapper::class));
+ }
+}
diff --git a/tests/lib/Files/Stream/EncryptionTest.php b/tests/lib/Files/Stream/EncryptionTest.php
index 5482f365358..0a758337539 100644
--- a/tests/lib/Files/Stream/EncryptionTest.php
+++ b/tests/lib/Files/Stream/EncryptionTest.php
@@ -1,371 +1,371 @@
-<?php
-/**
- * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
- * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
- * SPDX-License-Identifier: AGPL-3.0-only
- */
-namespace Test\Files\Stream;
-
-use OC\Files\Cache\CacheEntry;
-use OC\Files\View;
-use OC\Memcache\ArrayCache;
-use OCP\EventDispatcher\IEventDispatcher;
-use OCP\Files\Cache\ICache;
-use OCP\ICacheFactory;
-use OCP\IConfig;
-
-class EncryptionTest extends \Test\TestCase {
- public const DEFAULT_WRAPPER = '\OC\Files\Stream\Encryption';
-
- /** @var \OCP\Encryption\IEncryptionModule | \PHPUnit\Framework\MockObject\MockObject */
- private $encryptionModule;
-
- /**
- * @param string $fileName
- * @param string $mode
- * @param integer $unencryptedSize
- * @return resource
- */
- protected function getStream($fileName, $mode, $unencryptedSize, $wrapper = self::DEFAULT_WRAPPER, $unencryptedSizeOnClose = 0) {
- clearstatcache();
- $size = filesize($fileName);
- $source = fopen($fileName, $mode);
- $internalPath = $fileName;
- $fullPath = $fileName;
- $header = [];
- $uid = '';
- $this->encryptionModule = $this->buildMockModule();
- $cache = $this->createMock(ICache::class);
- $storage = $this->getMockBuilder(\OC\Files\Storage\Storage::class)
- ->disableOriginalConstructor()->getMock();
- $encStorage = $this->getMockBuilder(\OC\Files\Storage\Wrapper\Encryption::class)
- ->disableOriginalConstructor()->getMock();
- $config = $this->getMockBuilder(IConfig::class)
- ->disableOriginalConstructor()
- ->getMock();
- $arrayCache = $this->createMock(ArrayCache::class);
- $groupManager = $this->getMockBuilder(\OC\Group\Manager::class)
- ->disableOriginalConstructor()
- ->getMock();
- $file = $this->getMockBuilder(\OC\Encryption\File::class)
- ->disableOriginalConstructor()
- ->setMethods(['getAccessList'])
- ->getMock();
- $file->expects($this->any())->method('getAccessList')->willReturn([]);
- $util = $this->getMockBuilder(\OC\Encryption\Util::class)
- ->setMethods(['getUidAndFilename'])
- ->setConstructorArgs([new View(), new \OC\User\Manager(
- $config,
- $this->createMock(ICacheFactory::class),
- $this->createMock(IEventDispatcher::class)
- ), $groupManager, $config, $arrayCache])
- ->getMock();
- $util->expects($this->any())
- ->method('getUidAndFilename')
- ->willReturn(['user1', $internalPath]);
- $storage->expects($this->any())->method('getCache')->willReturn($cache);
- $entry = new CacheEntry([
- 'fileid' => 5,
- 'encryptedVersion' => 2,
- 'unencrypted_size' => $unencryptedSizeOnClose,
- ]);
- $cache->expects($this->any())->method('get')->willReturn($entry);
- $cache->expects($this->any())->method('update')->with(5, ['encrypted' => 3, 'encryptedVersion' => 3, 'unencrypted_size' => $unencryptedSizeOnClose]);
-
-
- return $wrapper::wrap($source, $internalPath,
- $fullPath, $header, $uid, $this->encryptionModule, $storage, $encStorage,
- $util, $file, $mode, $size, $unencryptedSize, 8192, $wrapper);
- }
-
- /**
- * @dataProvider dataProviderStreamOpen()
- */
- public function testStreamOpen($isMasterKeyUsed,
- $mode,
- $fullPath,
- $fileExists,
- $expectedSharePath,
- $expectedSize,
- $expectedUnencryptedSize,
- $expectedReadOnly) {
- // build mocks
- $encryptionModuleMock = $this->getMockBuilder(\OCP\Encryption\IEncryptionModule::class)
- ->disableOriginalConstructor()->getMock();
- $encryptionModuleMock->expects($this->any())->method('needDetailedAccessList')->willReturn(!$isMasterKeyUsed);
- $encryptionModuleMock->expects($this->once())
- ->method('getUnencryptedBlockSize')->willReturn(99);
- $encryptionModuleMock->expects($this->once())
- ->method('begin')->willReturn(true);
-
- $storageMock = $this->getMockBuilder(\OC\Files\Storage\Storage::class)
- ->disableOriginalConstructor()->getMock();
- $storageMock->expects($this->once())->method('file_exists')->willReturn($fileExists);
-
- $fileMock = $this->getMockBuilder(\OC\Encryption\File::class)
- ->disableOriginalConstructor()->getMock();
- if ($isMasterKeyUsed) {
- $fileMock->expects($this->never())->method('getAccessList');
- } else {
- $fileMock->expects($this->once())->method('getAccessList')
- ->willReturnCallback(function ($sharePath) use ($expectedSharePath) {
- $this->assertSame($expectedSharePath, $sharePath);
- return [];
- });
- }
- $utilMock = $this->getMockBuilder(\OC\Encryption\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::class)
- ->setMethods(['loadContext', 'writeHeader', 'skipHeader'])->disableOriginalConstructor()->getMock();
-
- // set internal properties of the stream wrapper
- $stream = new \ReflectionClass(\OC\Files\Stream\Encryption::class);
- $encryptionModule = $stream->getProperty('encryptionModule');
- $encryptionModule->setAccessible(true);
- $encryptionModule->setValue($streamWrapper, $encryptionModuleMock);
- $encryptionModule->setAccessible(false);
- $storage = $stream->getProperty('storage');
- $storage->setAccessible(true);
- $storage->setValue($streamWrapper, $storageMock);
- $storage->setAccessible(false);
- $file = $stream->getProperty('file');
- $file->setAccessible(true);
- $file->setValue($streamWrapper, $fileMock);
- $file->setAccessible(false);
- $util = $stream->getProperty('util');
- $util->setAccessible(true);
- $util->setValue($streamWrapper, $utilMock);
- $util->setAccessible(false);
- $fullPathP = $stream->getProperty('fullPath');
- $fullPathP->setAccessible(true);
- $fullPathP->setValue($streamWrapper, $fullPath);
- $fullPathP->setAccessible(false);
- $header = $stream->getProperty('header');
- $header->setAccessible(true);
- $header->setValue($streamWrapper, []);
- $header->setAccessible(false);
- $this->invokePrivate($streamWrapper, 'signed', [true]);
-
- // call stream_open, that's the method we want to test
- $dummyVar = 'foo';
- $streamWrapper->stream_open('', $mode, '', $dummyVar);
-
- // check internal properties
- $size = $stream->getProperty('size');
- $size->setAccessible(true);
- $this->assertSame($expectedSize,
- $size->getValue($streamWrapper)
- );
- $size->setAccessible(false);
-
- $unencryptedSize = $stream->getProperty('unencryptedSize');
- $unencryptedSize->setAccessible(true);
- $this->assertSame($expectedUnencryptedSize,
- $unencryptedSize->getValue($streamWrapper)
- );
- $unencryptedSize->setAccessible(false);
-
- $readOnly = $stream->getProperty('readOnly');
- $readOnly->setAccessible(true);
- $this->assertSame($expectedReadOnly,
- $readOnly->getValue($streamWrapper)
- );
- $readOnly->setAccessible(false);
- }
-
- public function dataProviderStreamOpen() {
- 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],
- [false, 'w', '/foo/bar/test.txt', true, '/foo/bar/test.txt', 8192, 0, false],
- [true, 'r', '/foo/bar/test.txt', true, '/foo/bar/test.txt', null, null, true],
- [true, 'r', '/foo/bar/test.txt', false, '/foo/bar', null, null, true],
- [true, 'w', '/foo/bar/test.txt', true, '/foo/bar/test.txt', 8192, 0, false],
- ];
- }
-
- public function testWriteRead() {
- $fileName = tempnam('/tmp', 'FOO');
- $stream = $this->getStream($fileName, 'w+', 0, self::DEFAULT_WRAPPER, 6);
- $this->assertEquals(6, fwrite($stream, 'foobar'));
- fclose($stream);
-
- $stream = $this->getStream($fileName, 'r', 6);
- $this->assertEquals('foobar', fread($stream, 100));
- fclose($stream);
-
- $stream = $this->getStream($fileName, 'r+', 6, self::DEFAULT_WRAPPER, 6);
- $this->assertEquals(3, fwrite($stream, 'bar'));
- fclose($stream);
-
- $stream = $this->getStream($fileName, 'r', 6);
- $this->assertEquals('barbar', fread($stream, 100));
- fclose($stream);
-
- unlink($fileName);
- }
-
- public function testRewind() {
- $fileName = tempnam('/tmp', 'FOO');
- $stream = $this->getStream($fileName, 'w+', 0, self::DEFAULT_WRAPPER, 6);
- $this->assertEquals(6, fwrite($stream, 'foobar'));
- $this->assertEquals(true, rewind($stream));
- $this->assertEquals('foobar', fread($stream, 100));
- $this->assertEquals(true, rewind($stream));
- $this->assertEquals(3, fwrite($stream, 'bar'));
- fclose($stream);
-
- $stream = $this->getStream($fileName, 'r', 6);
- $this->assertEquals('barbar', fread($stream, 100));
- fclose($stream);
-
- unlink($fileName);
- }
-
- public function testSeek() {
- $fileName = tempnam('/tmp', 'FOO');
-
- $stream = $this->getStream($fileName, 'w+', 0, self::DEFAULT_WRAPPER, 9);
- $this->assertEquals(6, fwrite($stream, 'foobar'));
- $this->assertEquals(0, fseek($stream, 3));
- $this->assertEquals(6, fwrite($stream, 'foobar'));
- fclose($stream);
-
- $stream = $this->getStream($fileName, 'r', 9);
- $this->assertEquals('foofoobar', fread($stream, 100));
- $this->assertEquals(-1, fseek($stream, 10));
- $this->assertEquals(0, fseek($stream, 9));
- $this->assertEquals(-1, fseek($stream, -10, SEEK_CUR));
- $this->assertEquals(0, fseek($stream, -9, SEEK_CUR));
- $this->assertEquals(-1, fseek($stream, -10, SEEK_END));
- $this->assertEquals(0, fseek($stream, -9, SEEK_END));
- fclose($stream);
-
- unlink($fileName);
- }
-
- public function dataFilesProvider() {
- return [
- ['lorem-big.txt'],
- ['block-aligned.txt'],
- ['block-aligned-plus-one.txt'],
- ];
- }
-
- /**
- * @dataProvider dataFilesProvider
- */
- public function testWriteReadBigFile($testFile) {
- $expectedData = file_get_contents(\OC::$SERVERROOT . '/tests/data/' . $testFile);
- // write it
- $fileName = tempnam('/tmp', 'FOO');
- $stream = $this->getStream($fileName, 'w+', 0, self::DEFAULT_WRAPPER, strlen($expectedData));
- // while writing the file from the beginning to the end we should never try
- // to read parts of the file. This should only happen for write operations
- // in the middle of a file
- $this->encryptionModule->expects($this->never())->method('decrypt');
- fwrite($stream, $expectedData);
- fclose($stream);
-
- // read it all
- $stream = $this->getStream($fileName, 'r', strlen($expectedData));
- $data = stream_get_contents($stream);
- fclose($stream);
-
- $this->assertEquals($expectedData, $data);
-
- // another read test with a loop like we do in several places:
- $stream = $this->getStream($fileName, 'r', strlen($expectedData));
- $data = '';
- while (!feof($stream)) {
- $data .= fread($stream, 8192);
- }
- fclose($stream);
-
- $this->assertEquals($expectedData, $data);
-
- unlink($fileName);
- }
-
- /**
- * simulate a non-seekable storage
- *
- * @dataProvider dataFilesProvider
- */
- public function testWriteToNonSeekableStorage($testFile) {
- $wrapper = $this->getMockBuilder(\OC\Files\Stream\Encryption::class)
- ->setMethods(['parentSeekStream'])->getMock();
- $wrapper->expects($this->any())->method('parentSeekStream')->willReturn(false);
-
- $expectedData = file_get_contents(\OC::$SERVERROOT . '/tests/data/' . $testFile);
- // write it
- $fileName = tempnam('/tmp', 'FOO');
- $stream = $this->getStream($fileName, 'w+', 0, \Test\Files\Stream\DummyEncryptionWrapper::class, strlen($expectedData));
- // while writing the file from the beginning to the end we should never try
- // to read parts of the file. This should only happen for write operations
- // in the middle of a file
- $this->encryptionModule->expects($this->never())->method('decrypt');
- fwrite($stream, $expectedData);
- fclose($stream);
-
- // read it all
- $stream = $this->getStream($fileName, 'r', strlen($expectedData), \Test\Files\Stream\DummyEncryptionWrapper::class, strlen($expectedData));
- $data = stream_get_contents($stream);
- fclose($stream);
-
- $this->assertEquals($expectedData, $data);
-
- // another read test with a loop like we do in several places:
- $stream = $this->getStream($fileName, 'r', strlen($expectedData));
- $data = '';
- while (!feof($stream)) {
- $data .= fread($stream, 8192);
- }
- fclose($stream);
-
- $this->assertEquals($expectedData, $data);
-
- unlink($fileName);
- }
-
- /**
- * @return \PHPUnit\Framework\MockObject\MockObject
- */
- protected function buildMockModule() {
- $encryptionModule = $this->getMockBuilder(\OCP\Encryption\IEncryptionModule::class)
- ->disableOriginalConstructor()
- ->setMethods(['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');
- $encryptionModule->expects($this->any())->method('getDisplayName')->willReturn('Unit test module');
- $encryptionModule->expects($this->any())->method('begin')->willReturn([]);
- $encryptionModule->expects($this->any())->method('end')->willReturn('');
- $encryptionModule->expects($this->any())->method('isReadable')->willReturn(true);
- $encryptionModule->expects($this->any())->method('needDetailedAccessList')->willReturn(false);
- $encryptionModule->expects($this->any())->method('encrypt')->willReturnCallback(function ($data) {
- // simulate different block size by adding some padding to the data
- if (isset($data[6125])) {
- return str_pad($data, 8192, 'X');
- }
- // last block
- return $data;
- });
- $encryptionModule->expects($this->any())->method('decrypt')->willReturnCallback(function ($data) {
- if (isset($data[8191])) {
- return substr($data, 0, 6126);
- }
- // last block
- return $data;
- });
- $encryptionModule->expects($this->any())->method('update')->willReturn(true);
- $encryptionModule->expects($this->any())->method('shouldEncrypt')->willReturn(true);
- $encryptionModule->expects($this->any())->method('getUnencryptedBlockSize')->willReturn(6126);
- return $encryptionModule;
- }
-}
+<?php
+/**
+ * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
+ */
+namespace Test\Files\Stream;
+
+use OC\Files\Cache\CacheEntry;
+use OC\Files\View;
+use OC\Memcache\ArrayCache;
+use OCP\EventDispatcher\IEventDispatcher;
+use OCP\Files\Cache\ICache;
+use OCP\ICacheFactory;
+use OCP\IConfig;
+
+class EncryptionTest extends \Test\TestCase {
+ public const DEFAULT_WRAPPER = '\OC\Files\Stream\Encryption';
+
+ /** @var \OCP\Encryption\IEncryptionModule | \PHPUnit\Framework\MockObject\MockObject */
+ private $encryptionModule;
+
+ /**
+ * @param string $fileName
+ * @param string $mode
+ * @param integer $unencryptedSize
+ * @return resource
+ */
+ protected function getStream($fileName, $mode, $unencryptedSize, $wrapper = self::DEFAULT_WRAPPER, $unencryptedSizeOnClose = 0) {
+ clearstatcache();
+ $size = filesize($fileName);
+ $source = fopen($fileName, $mode);
+ $internalPath = $fileName;
+ $fullPath = $fileName;
+ $header = [];
+ $uid = '';
+ $this->encryptionModule = $this->buildMockModule();
+ $cache = $this->createMock(ICache::class);
+ $storage = $this->getMockBuilder(\OC\Files\Storage\Storage::class)
+ ->disableOriginalConstructor()->getMock();
+ $encStorage = $this->getMockBuilder(\OC\Files\Storage\Wrapper\Encryption::class)
+ ->disableOriginalConstructor()->getMock();
+ $config = $this->getMockBuilder(IConfig::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $arrayCache = $this->createMock(ArrayCache::class);
+ $groupManager = $this->getMockBuilder(\OC\Group\Manager::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $file = $this->getMockBuilder(\OC\Encryption\File::class)
+ ->disableOriginalConstructor()
+ ->setMethods(['getAccessList'])
+ ->getMock();
+ $file->expects($this->any())->method('getAccessList')->willReturn([]);
+ $util = $this->getMockBuilder(\OC\Encryption\Util::class)
+ ->setMethods(['getUidAndFilename'])
+ ->setConstructorArgs([new View(), new \OC\User\Manager(
+ $config,
+ $this->createMock(ICacheFactory::class),
+ $this->createMock(IEventDispatcher::class)
+ ), $groupManager, $config, $arrayCache])
+ ->getMock();
+ $util->expects($this->any())
+ ->method('getUidAndFilename')
+ ->willReturn(['user1', $internalPath]);
+ $storage->expects($this->any())->method('getCache')->willReturn($cache);
+ $entry = new CacheEntry([
+ 'fileid' => 5,
+ 'encryptedVersion' => 2,
+ 'unencrypted_size' => $unencryptedSizeOnClose,
+ ]);
+ $cache->expects($this->any())->method('get')->willReturn($entry);
+ $cache->expects($this->any())->method('update')->with(5, ['encrypted' => 3, 'encryptedVersion' => 3, 'unencrypted_size' => $unencryptedSizeOnClose]);
+
+
+ return $wrapper::wrap($source, $internalPath,
+ $fullPath, $header, $uid, $this->encryptionModule, $storage, $encStorage,
+ $util, $file, $mode, $size, $unencryptedSize, 8192, $wrapper);
+ }
+
+ /**
+ * @dataProvider dataProviderStreamOpen()
+ */
+ public function testStreamOpen($isMasterKeyUsed,
+ $mode,
+ $fullPath,
+ $fileExists,
+ $expectedSharePath,
+ $expectedSize,
+ $expectedUnencryptedSize,
+ $expectedReadOnly): void {
+ // build mocks
+ $encryptionModuleMock = $this->getMockBuilder(\OCP\Encryption\IEncryptionModule::class)
+ ->disableOriginalConstructor()->getMock();
+ $encryptionModuleMock->expects($this->any())->method('needDetailedAccessList')->willReturn(!$isMasterKeyUsed);
+ $encryptionModuleMock->expects($this->once())
+ ->method('getUnencryptedBlockSize')->willReturn(99);
+ $encryptionModuleMock->expects($this->once())
+ ->method('begin')->willReturn(true);
+
+ $storageMock = $this->getMockBuilder(\OC\Files\Storage\Storage::class)
+ ->disableOriginalConstructor()->getMock();
+ $storageMock->expects($this->once())->method('file_exists')->willReturn($fileExists);
+
+ $fileMock = $this->getMockBuilder(\OC\Encryption\File::class)
+ ->disableOriginalConstructor()->getMock();
+ if ($isMasterKeyUsed) {
+ $fileMock->expects($this->never())->method('getAccessList');
+ } else {
+ $fileMock->expects($this->once())->method('getAccessList')
+ ->willReturnCallback(function ($sharePath) use ($expectedSharePath) {
+ $this->assertSame($expectedSharePath, $sharePath);
+ return [];
+ });
+ }
+ $utilMock = $this->getMockBuilder(\OC\Encryption\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::class)
+ ->setMethods(['loadContext', 'writeHeader', 'skipHeader'])->disableOriginalConstructor()->getMock();
+
+ // set internal properties of the stream wrapper
+ $stream = new \ReflectionClass(\OC\Files\Stream\Encryption::class);
+ $encryptionModule = $stream->getProperty('encryptionModule');
+ $encryptionModule->setAccessible(true);
+ $encryptionModule->setValue($streamWrapper, $encryptionModuleMock);
+ $encryptionModule->setAccessible(false);
+ $storage = $stream->getProperty('storage');
+ $storage->setAccessible(true);
+ $storage->setValue($streamWrapper, $storageMock);
+ $storage->setAccessible(false);
+ $file = $stream->getProperty('file');
+ $file->setAccessible(true);
+ $file->setValue($streamWrapper, $fileMock);
+ $file->setAccessible(false);
+ $util = $stream->getProperty('util');
+ $util->setAccessible(true);
+ $util->setValue($streamWrapper, $utilMock);
+ $util->setAccessible(false);
+ $fullPathP = $stream->getProperty('fullPath');
+ $fullPathP->setAccessible(true);
+ $fullPathP->setValue($streamWrapper, $fullPath);
+ $fullPathP->setAccessible(false);
+ $header = $stream->getProperty('header');
+ $header->setAccessible(true);
+ $header->setValue($streamWrapper, []);
+ $header->setAccessible(false);
+ $this->invokePrivate($streamWrapper, 'signed', [true]);
+
+ // call stream_open, that's the method we want to test
+ $dummyVar = 'foo';
+ $streamWrapper->stream_open('', $mode, '', $dummyVar);
+
+ // check internal properties
+ $size = $stream->getProperty('size');
+ $size->setAccessible(true);
+ $this->assertSame($expectedSize,
+ $size->getValue($streamWrapper)
+ );
+ $size->setAccessible(false);
+
+ $unencryptedSize = $stream->getProperty('unencryptedSize');
+ $unencryptedSize->setAccessible(true);
+ $this->assertSame($expectedUnencryptedSize,
+ $unencryptedSize->getValue($streamWrapper)
+ );
+ $unencryptedSize->setAccessible(false);
+
+ $readOnly = $stream->getProperty('readOnly');
+ $readOnly->setAccessible(true);
+ $this->assertSame($expectedReadOnly,
+ $readOnly->getValue($streamWrapper)
+ );
+ $readOnly->setAccessible(false);
+ }
+
+ public function dataProviderStreamOpen() {
+ 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],
+ [false, 'w', '/foo/bar/test.txt', true, '/foo/bar/test.txt', 8192, 0, false],
+ [true, 'r', '/foo/bar/test.txt', true, '/foo/bar/test.txt', null, null, true],
+ [true, 'r', '/foo/bar/test.txt', false, '/foo/bar', null, null, true],
+ [true, 'w', '/foo/bar/test.txt', true, '/foo/bar/test.txt', 8192, 0, false],
+ ];
+ }
+
+ public function testWriteRead(): void {
+ $fileName = tempnam('/tmp', 'FOO');
+ $stream = $this->getStream($fileName, 'w+', 0, self::DEFAULT_WRAPPER, 6);
+ $this->assertEquals(6, fwrite($stream, 'foobar'));
+ fclose($stream);
+
+ $stream = $this->getStream($fileName, 'r', 6);
+ $this->assertEquals('foobar', fread($stream, 100));
+ fclose($stream);
+
+ $stream = $this->getStream($fileName, 'r+', 6, self::DEFAULT_WRAPPER, 6);
+ $this->assertEquals(3, fwrite($stream, 'bar'));
+ fclose($stream);
+
+ $stream = $this->getStream($fileName, 'r', 6);
+ $this->assertEquals('barbar', fread($stream, 100));
+ fclose($stream);
+
+ unlink($fileName);
+ }
+
+ public function testRewind(): void {
+ $fileName = tempnam('/tmp', 'FOO');
+ $stream = $this->getStream($fileName, 'w+', 0, self::DEFAULT_WRAPPER, 6);
+ $this->assertEquals(6, fwrite($stream, 'foobar'));
+ $this->assertEquals(true, rewind($stream));
+ $this->assertEquals('foobar', fread($stream, 100));
+ $this->assertEquals(true, rewind($stream));
+ $this->assertEquals(3, fwrite($stream, 'bar'));
+ fclose($stream);
+
+ $stream = $this->getStream($fileName, 'r', 6);
+ $this->assertEquals('barbar', fread($stream, 100));
+ fclose($stream);
+
+ unlink($fileName);
+ }
+
+ public function testSeek(): void {
+ $fileName = tempnam('/tmp', 'FOO');
+
+ $stream = $this->getStream($fileName, 'w+', 0, self::DEFAULT_WRAPPER, 9);
+ $this->assertEquals(6, fwrite($stream, 'foobar'));
+ $this->assertEquals(0, fseek($stream, 3));
+ $this->assertEquals(6, fwrite($stream, 'foobar'));
+ fclose($stream);
+
+ $stream = $this->getStream($fileName, 'r', 9);
+ $this->assertEquals('foofoobar', fread($stream, 100));
+ $this->assertEquals(-1, fseek($stream, 10));
+ $this->assertEquals(0, fseek($stream, 9));
+ $this->assertEquals(-1, fseek($stream, -10, SEEK_CUR));
+ $this->assertEquals(0, fseek($stream, -9, SEEK_CUR));
+ $this->assertEquals(-1, fseek($stream, -10, SEEK_END));
+ $this->assertEquals(0, fseek($stream, -9, SEEK_END));
+ fclose($stream);
+
+ unlink($fileName);
+ }
+
+ public function dataFilesProvider() {
+ return [
+ ['lorem-big.txt'],
+ ['block-aligned.txt'],
+ ['block-aligned-plus-one.txt'],
+ ];
+ }
+
+ /**
+ * @dataProvider dataFilesProvider
+ */
+ public function testWriteReadBigFile($testFile): void {
+ $expectedData = file_get_contents(\OC::$SERVERROOT . '/tests/data/' . $testFile);
+ // write it
+ $fileName = tempnam('/tmp', 'FOO');
+ $stream = $this->getStream($fileName, 'w+', 0, self::DEFAULT_WRAPPER, strlen($expectedData));
+ // while writing the file from the beginning to the end we should never try
+ // to read parts of the file. This should only happen for write operations
+ // in the middle of a file
+ $this->encryptionModule->expects($this->never())->method('decrypt');
+ fwrite($stream, $expectedData);
+ fclose($stream);
+
+ // read it all
+ $stream = $this->getStream($fileName, 'r', strlen($expectedData));
+ $data = stream_get_contents($stream);
+ fclose($stream);
+
+ $this->assertEquals($expectedData, $data);
+
+ // another read test with a loop like we do in several places:
+ $stream = $this->getStream($fileName, 'r', strlen($expectedData));
+ $data = '';
+ while (!feof($stream)) {
+ $data .= fread($stream, 8192);
+ }
+ fclose($stream);
+
+ $this->assertEquals($expectedData, $data);
+
+ unlink($fileName);
+ }
+
+ /**
+ * simulate a non-seekable storage
+ *
+ * @dataProvider dataFilesProvider
+ */
+ public function testWriteToNonSeekableStorage($testFile): void {
+ $wrapper = $this->getMockBuilder(\OC\Files\Stream\Encryption::class)
+ ->setMethods(['parentSeekStream'])->getMock();
+ $wrapper->expects($this->any())->method('parentSeekStream')->willReturn(false);
+
+ $expectedData = file_get_contents(\OC::$SERVERROOT . '/tests/data/' . $testFile);
+ // write it
+ $fileName = tempnam('/tmp', 'FOO');
+ $stream = $this->getStream($fileName, 'w+', 0, \Test\Files\Stream\DummyEncryptionWrapper::class, strlen($expectedData));
+ // while writing the file from the beginning to the end we should never try
+ // to read parts of the file. This should only happen for write operations
+ // in the middle of a file
+ $this->encryptionModule->expects($this->never())->method('decrypt');
+ fwrite($stream, $expectedData);
+ fclose($stream);
+
+ // read it all
+ $stream = $this->getStream($fileName, 'r', strlen($expectedData), \Test\Files\Stream\DummyEncryptionWrapper::class, strlen($expectedData));
+ $data = stream_get_contents($stream);
+ fclose($stream);
+
+ $this->assertEquals($expectedData, $data);
+
+ // another read test with a loop like we do in several places:
+ $stream = $this->getStream($fileName, 'r', strlen($expectedData));
+ $data = '';
+ while (!feof($stream)) {
+ $data .= fread($stream, 8192);
+ }
+ fclose($stream);
+
+ $this->assertEquals($expectedData, $data);
+
+ unlink($fileName);
+ }
+
+ /**
+ * @return \PHPUnit\Framework\MockObject\MockObject
+ */
+ protected function buildMockModule() {
+ $encryptionModule = $this->getMockBuilder(\OCP\Encryption\IEncryptionModule::class)
+ ->disableOriginalConstructor()
+ ->setMethods(['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');
+ $encryptionModule->expects($this->any())->method('getDisplayName')->willReturn('Unit test module');
+ $encryptionModule->expects($this->any())->method('begin')->willReturn([]);
+ $encryptionModule->expects($this->any())->method('end')->willReturn('');
+ $encryptionModule->expects($this->any())->method('isReadable')->willReturn(true);
+ $encryptionModule->expects($this->any())->method('needDetailedAccessList')->willReturn(false);
+ $encryptionModule->expects($this->any())->method('encrypt')->willReturnCallback(function ($data) {
+ // simulate different block size by adding some padding to the data
+ if (isset($data[6125])) {
+ return str_pad($data, 8192, 'X');
+ }
+ // last block
+ return $data;
+ });
+ $encryptionModule->expects($this->any())->method('decrypt')->willReturnCallback(function ($data) {
+ if (isset($data[8191])) {
+ return substr($data, 0, 6126);
+ }
+ // last block
+ return $data;
+ });
+ $encryptionModule->expects($this->any())->method('update')->willReturn(true);
+ $encryptionModule->expects($this->any())->method('shouldEncrypt')->willReturn(true);
+ $encryptionModule->expects($this->any())->method('getUnencryptedBlockSize')->willReturn(6126);
+ return $encryptionModule;
+ }
+}
diff --git a/tests/lib/Files/Stream/HashWrapperTest.php b/tests/lib/Files/Stream/HashWrapperTest.php
index 686fcbec82a..ee50fe3b13a 100644
--- a/tests/lib/Files/Stream/HashWrapperTest.php
+++ b/tests/lib/Files/Stream/HashWrapperTest.php
@@ -15,7 +15,7 @@ class HashWrapperTest extends TestCase {
/**
* @dataProvider hashProvider
*/
- public function testHashStream($data, string $algo, string $hash) {
+ public function testHashStream($data, string $algo, string $hash): void {
if (!is_resource($data)) {
$tmpData = fopen('php://temp', 'r+');
if ($data !== null) {
diff --git a/tests/lib/Files/Stream/QuotaTest.php b/tests/lib/Files/Stream/QuotaTest.php
index 17ad14b7e44..2df767d6c60 100644
--- a/tests/lib/Files/Stream/QuotaTest.php
+++ b/tests/lib/Files/Stream/QuotaTest.php
@@ -18,21 +18,21 @@ class QuotaTest extends \Test\TestCase {
return \OC\Files\Stream\Quota::wrap($source, $limit);
}
- public function testWriteEnoughSpace() {
+ public function testWriteEnoughSpace(): void {
$stream = $this->getStream('w+', 100);
$this->assertEquals(6, fwrite($stream, 'foobar'));
rewind($stream);
$this->assertEquals('foobar', fread($stream, 100));
}
- public function testWriteNotEnoughSpace() {
+ public function testWriteNotEnoughSpace(): void {
$stream = $this->getStream('w+', 3);
$this->assertEquals(3, fwrite($stream, 'foobar'));
rewind($stream);
$this->assertEquals('foo', fread($stream, 100));
}
- public function testWriteNotEnoughSpaceSecondTime() {
+ public function testWriteNotEnoughSpaceSecondTime(): void {
$stream = $this->getStream('w+', 9);
$this->assertEquals(6, fwrite($stream, 'foobar'));
$this->assertEquals(3, fwrite($stream, 'qwerty'));
@@ -40,7 +40,7 @@ class QuotaTest extends \Test\TestCase {
$this->assertEquals('foobarqwe', fread($stream, 100));
}
- public function testWriteEnoughSpaceRewind() {
+ public function testWriteEnoughSpaceRewind(): void {
$stream = $this->getStream('w+', 6);
$this->assertEquals(6, fwrite($stream, 'foobar'));
rewind($stream);
@@ -49,7 +49,7 @@ class QuotaTest extends \Test\TestCase {
$this->assertEquals('qwebar', fread($stream, 100));
}
- public function testWriteNotEnoughSpaceRead() {
+ public function testWriteNotEnoughSpaceRead(): void {
$stream = $this->getStream('w+', 6);
$this->assertEquals(6, fwrite($stream, 'foobar'));
rewind($stream);
@@ -57,7 +57,7 @@ class QuotaTest extends \Test\TestCase {
$this->assertEquals(0, fwrite($stream, 'qwe'));
}
- public function testWriteNotEnoughSpaceExistingStream() {
+ public function testWriteNotEnoughSpaceExistingStream(): void {
$source = fopen('php://temp', 'w+');
fwrite($source, 'foobar');
$stream = \OC\Files\Stream\Quota::wrap($source, 3);
@@ -66,7 +66,7 @@ class QuotaTest extends \Test\TestCase {
$this->assertEquals('foobarfoo', fread($stream, 100));
}
- public function testWriteNotEnoughSpaceExistingStreamRewind() {
+ public function testWriteNotEnoughSpaceExistingStreamRewind(): void {
$source = fopen('php://temp', 'w+');
fwrite($source, 'foobar');
$stream = \OC\Files\Stream\Quota::wrap($source, 3);
@@ -76,7 +76,7 @@ class QuotaTest extends \Test\TestCase {
$this->assertEquals('qwerty', fread($stream, 100));
}
- public function testFseekReturnsSuccess() {
+ public function testFseekReturnsSuccess(): void {
$stream = $this->getStream('w+', 100);
fwrite($stream, '0123456789');
$this->assertEquals(0, fseek($stream, 3, SEEK_SET));
@@ -84,7 +84,7 @@ class QuotaTest extends \Test\TestCase {
$this->assertEquals(0, fseek($stream, -4, SEEK_END));
}
- public function testWriteAfterSeekEndWithEnoughSpace() {
+ public function testWriteAfterSeekEndWithEnoughSpace(): void {
$stream = $this->getStream('w+', 100);
fwrite($stream, '0123456789');
fseek($stream, -3, SEEK_END);
@@ -93,7 +93,7 @@ class QuotaTest extends \Test\TestCase {
$this->assertEquals('0123456abcdefghijk', fread($stream, 100));
}
- public function testWriteAfterSeekEndWithNotEnoughSpace() {
+ public function testWriteAfterSeekEndWithNotEnoughSpace(): void {
$stream = $this->getStream('w+', 13);
fwrite($stream, '0123456789');
// seek forward first to potentially week out
@@ -106,7 +106,7 @@ class QuotaTest extends \Test\TestCase {
$this->assertEquals('0123456abcdef', fread($stream, 100));
}
- public function testWriteAfterSeekSetWithEnoughSpace() {
+ public function testWriteAfterSeekSetWithEnoughSpace(): void {
$stream = $this->getStream('w+', 100);
fwrite($stream, '0123456789');
fseek($stream, 7, SEEK_SET);
@@ -115,7 +115,7 @@ class QuotaTest extends \Test\TestCase {
$this->assertEquals('0123456abcdefghijk', fread($stream, 100));
}
- public function testWriteAfterSeekSetWithNotEnoughSpace() {
+ public function testWriteAfterSeekSetWithNotEnoughSpace(): void {
$stream = $this->getStream('w+', 13);
fwrite($stream, '0123456789');
fseek($stream, 7, SEEK_SET);
@@ -124,7 +124,7 @@ class QuotaTest extends \Test\TestCase {
$this->assertEquals('0123456abcdef', fread($stream, 100));
}
- public function testWriteAfterSeekCurWithEnoughSpace() {
+ public function testWriteAfterSeekCurWithEnoughSpace(): void {
$stream = $this->getStream('w+', 100);
fwrite($stream, '0123456789');
rewind($stream);
@@ -136,7 +136,7 @@ class QuotaTest extends \Test\TestCase {
$this->assertEquals('0123456abcdefghijk', fread($stream, 100));
}
- public function testWriteAfterSeekCurWithNotEnoughSpace() {
+ public function testWriteAfterSeekCurWithNotEnoughSpace(): void {
$stream = $this->getStream('w+', 13);
fwrite($stream, '0123456789');
rewind($stream);
diff --git a/tests/lib/Files/Type/DetectionTest.php b/tests/lib/Files/Type/DetectionTest.php
index e647fa064d4..dcbb455efc9 100644
--- a/tests/lib/Files/Type/DetectionTest.php
+++ b/tests/lib/Files/Type/DetectionTest.php
@@ -117,7 +117,7 @@ class DetectionTest extends \Test\TestCase {
$this->assertEquals($expected, $this->detection->getSecureMimeType($mimeType));
}
- public function testMimeTypeIcon() {
+ public function testMimeTypeIcon(): void {
if (!class_exists('org\\bovigo\\vfs\\vfsStream')) {
$this->markTestSkipped('Package vfsStream not installed');
}
diff --git a/tests/lib/Files/Type/LoaderTest.php b/tests/lib/Files/Type/LoaderTest.php
index cd2788bd208..6eaf6ac2013 100644
--- a/tests/lib/Files/Type/LoaderTest.php
+++ b/tests/lib/Files/Type/LoaderTest.php
@@ -30,7 +30,7 @@ class LoaderTest extends TestCase {
}
- public function testGetMimetype() {
+ public function testGetMimetype(): void {
$qb = $this->db->getQueryBuilder();
$qb->insert('mimetypes')
->values([
@@ -46,13 +46,13 @@ class LoaderTest extends TestCase {
$this->assertEquals('testing/mymimetype', $mimetype);
}
- public function testGetNonexistentMimetype() {
+ public function testGetNonexistentMimetype(): void {
$this->assertFalse($this->loader->exists('testing/nonexistent'));
// hopefully this ID doesn't exist
$this->assertNull($this->loader->getMimetypeById(12345));
}
- public function testStore() {
+ public function testStore(): void {
$this->assertFalse($this->loader->exists('testing/mymimetype'));
$mimetypeId = $this->loader->getId('testing/mymimetype');
@@ -70,7 +70,7 @@ class LoaderTest extends TestCase {
$this->assertEquals($mimetypeId, $this->loader->getId('testing/mymimetype'));
}
- public function testStoreExists() {
+ public function testStoreExists(): void {
$mimetypeId = $this->loader->getId('testing/mymimetype');
$mimetypeId2 = $this->loader->getId('testing/mymimetype');
diff --git a/tests/lib/Files/Utils/ScannerTest.php b/tests/lib/Files/Utils/ScannerTest.php
index c3ba696ac5c..f66bb72e865 100644
--- a/tests/lib/Files/Utils/ScannerTest.php
+++ b/tests/lib/Files/Utils/ScannerTest.php
@@ -61,7 +61,7 @@ class ScannerTest extends \Test\TestCase {
parent::tearDown();
}
- public function testReuseExistingRoot() {
+ public function testReuseExistingRoot(): void {
$storage = new Temporary([]);
$mount = new MountPoint($storage, '');
Filesystem::getMountManager()->addMount($mount);
@@ -83,7 +83,7 @@ class ScannerTest extends \Test\TestCase {
$this->assertEquals($oldRoot, $newRoot);
}
- public function testReuseExistingFile() {
+ public function testReuseExistingFile(): void {
$storage = new Temporary([]);
$mount = new MountPoint($storage, '');
Filesystem::getMountManager()->addMount($mount);
@@ -105,7 +105,7 @@ class ScannerTest extends \Test\TestCase {
$this->assertEquals($old, $new);
}
- public function testScanSubMount() {
+ public function testScanSubMount(): void {
$uid = $this->getUniqueID();
$this->userBackend->createUser($uid, 'test');
@@ -159,7 +159,7 @@ class ScannerTest extends \Test\TestCase {
* @dataProvider invalidPathProvider
* @param string $invalidPath
*/
- public function testInvalidPathScanning($invalidPath) {
+ public function testInvalidPathScanning($invalidPath): void {
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid path to scan');
@@ -167,7 +167,7 @@ class ScannerTest extends \Test\TestCase {
$scanner->scan($invalidPath);
}
- public function testPropagateEtag() {
+ public function testPropagateEtag(): void {
$storage = new Temporary([]);
$mount = new MountPoint($storage, '');
Filesystem::getMountManager()->addMount($mount);
@@ -191,7 +191,7 @@ class ScannerTest extends \Test\TestCase {
$this->assertNotEquals($oldRoot->getEtag(), $newRoot->getEtag());
}
- public function testShallow() {
+ public function testShallow(): void {
$storage = new Temporary([]);
$mount = new MountPoint($storage, '');
Filesystem::getMountManager()->addMount($mount);
diff --git a/tests/lib/Files/ViewTest.php b/tests/lib/Files/ViewTest.php
index 7a70266d5d5..1081d5857df 100644
--- a/tests/lib/Files/ViewTest.php
+++ b/tests/lib/Files/ViewTest.php
@@ -147,7 +147,7 @@ class ViewTest extends \Test\TestCase {
/**
* @medium
*/
- public function testCacheAPI() {
+ public function testCacheAPI(): void {
$storage1 = $this->getTestStorage();
$storage2 = $this->getTestStorage();
$storage3 = $this->getTestStorage();
@@ -230,7 +230,7 @@ class ViewTest extends \Test\TestCase {
/**
* @medium
*/
- public function testGetPath() {
+ public function testGetPath(): void {
$storage1 = $this->getTestStorage();
$storage2 = $this->getTestStorage();
$storage3 = $this->getTestStorage();
@@ -257,7 +257,7 @@ class ViewTest extends \Test\TestCase {
}
- public function testGetPathNotExisting() {
+ public function testGetPathNotExisting(): void {
$this->expectException(\OCP\Files\NotFoundException::class);
$storage1 = $this->getTestStorage();
@@ -274,7 +274,7 @@ class ViewTest extends \Test\TestCase {
/**
* @medium
*/
- public function testMountPointOverwrite() {
+ public function testMountPointOverwrite(): void {
$storage1 = $this->getTestStorage(false);
$storage2 = $this->getTestStorage();
$storage1->mkdir('substorage');
@@ -296,7 +296,7 @@ class ViewTest extends \Test\TestCase {
/**
* @dataProvider sharingDisabledPermissionProvider
*/
- public function testRemoveSharePermissionWhenSharingDisabledForUser($excludeGroups, $excludeGroupsList, $expectedShareable) {
+ public function testRemoveSharePermissionWhenSharingDisabledForUser($excludeGroups, $excludeGroupsList, $expectedShareable): void {
// Reset sharing disabled for users cache
self::invokePrivate(\OC::$server->get(ShareDisableChecker::class), 'sharingDisabledForUsersCache', [new CappedMemoryCache()]);
@@ -326,7 +326,7 @@ class ViewTest extends \Test\TestCase {
self::invokePrivate(\OC::$server->get(ShareDisableChecker::class), 'sharingDisabledForUsersCache', [new CappedMemoryCache()]);
}
- public function testCacheIncompleteFolder() {
+ public function testCacheIncompleteFolder(): void {
$storage1 = $this->getTestStorage(false);
Filesystem::mount($storage1, [], '/incomplete');
$rootView = new View('/incomplete');
@@ -339,7 +339,7 @@ class ViewTest extends \Test\TestCase {
$this->assertCount(1, $entries);
}
- public function testAutoScan() {
+ public function testAutoScan(): void {
$storage1 = $this->getTestStorage(false);
$storage2 = $this->getTestStorage(false);
Filesystem::mount($storage1, [], '/');
@@ -360,7 +360,7 @@ class ViewTest extends \Test\TestCase {
/**
* @medium
*/
- public function testSearch() {
+ public function testSearch(): void {
$storage1 = $this->getTestStorage();
$storage2 = $this->getTestStorage();
$storage3 = $this->getTestStorage();
@@ -410,7 +410,7 @@ class ViewTest extends \Test\TestCase {
/**
* @medium
*/
- public function testWatcher() {
+ public function testWatcher(): void {
$storage1 = $this->getTestStorage();
Filesystem::mount($storage1, [], '/');
$storage1->getWatcher()->setPolicy(Watcher::CHECK_ALWAYS);
@@ -431,7 +431,7 @@ class ViewTest extends \Test\TestCase {
/**
* @medium
*/
- public function testCopyBetweenStorageNoCross() {
+ public function testCopyBetweenStorageNoCross(): void {
$storage1 = $this->getTestStorage(true, TemporaryNoCross::class);
$storage2 = $this->getTestStorage(true, TemporaryNoCross::class);
$this->copyBetweenStorages($storage1, $storage2);
@@ -440,7 +440,7 @@ class ViewTest extends \Test\TestCase {
/**
* @medium
*/
- public function testCopyBetweenStorageCross() {
+ public function testCopyBetweenStorageCross(): void {
$storage1 = $this->getTestStorage();
$storage2 = $this->getTestStorage();
$this->copyBetweenStorages($storage1, $storage2);
@@ -449,7 +449,7 @@ class ViewTest extends \Test\TestCase {
/**
* @medium
*/
- public function testCopyBetweenStorageCrossNonLocal() {
+ public function testCopyBetweenStorageCrossNonLocal(): void {
$storage1 = $this->getTestStorage(true, TemporaryNoLocal::class);
$storage2 = $this->getTestStorage(true, TemporaryNoLocal::class);
$this->copyBetweenStorages($storage1, $storage2);
@@ -477,7 +477,7 @@ class ViewTest extends \Test\TestCase {
/**
* @medium
*/
- public function testMoveBetweenStorageNoCross() {
+ public function testMoveBetweenStorageNoCross(): void {
$storage1 = $this->getTestStorage(true, TemporaryNoCross::class);
$storage2 = $this->getTestStorage(true, TemporaryNoCross::class);
$this->moveBetweenStorages($storage1, $storage2);
@@ -486,7 +486,7 @@ class ViewTest extends \Test\TestCase {
/**
* @medium
*/
- public function testMoveBetweenStorageCross() {
+ public function testMoveBetweenStorageCross(): void {
$storage1 = $this->getTestStorage();
$storage2 = $this->getTestStorage();
$this->moveBetweenStorages($storage1, $storage2);
@@ -495,7 +495,7 @@ class ViewTest extends \Test\TestCase {
/**
* @medium
*/
- public function testMoveBetweenStorageCrossNonLocal() {
+ public function testMoveBetweenStorageCrossNonLocal(): void {
$storage1 = $this->getTestStorage(true, TemporaryNoLocal::class);
$storage2 = $this->getTestStorage(true, TemporaryNoLocal::class);
$this->moveBetweenStorages($storage1, $storage2);
@@ -518,7 +518,7 @@ class ViewTest extends \Test\TestCase {
/**
* @medium
*/
- public function testUnlink() {
+ public function testUnlink(): void {
$storage1 = $this->getTestStorage();
$storage2 = $this->getTestStorage();
Filesystem::mount($storage1, [], '/');
@@ -545,7 +545,7 @@ class ViewTest extends \Test\TestCase {
/**
* @dataProvider rmdirOrUnlinkDataProvider
*/
- public function testRmdir($method) {
+ public function testRmdir($method): void {
$storage1 = $this->getTestStorage();
Filesystem::mount($storage1, [], '/');
@@ -564,7 +564,7 @@ class ViewTest extends \Test\TestCase {
/**
* @medium
*/
- public function testUnlinkRootMustFail() {
+ public function testUnlinkRootMustFail(): void {
$storage1 = $this->getTestStorage();
$storage2 = $this->getTestStorage();
Filesystem::mount($storage1, [], '/');
@@ -583,7 +583,7 @@ class ViewTest extends \Test\TestCase {
/**
* @medium
*/
- public function testTouch() {
+ public function testTouch(): void {
$storage = $this->getTestStorage(true, TemporaryNoTouch::class);
Filesystem::mount($storage, [], '/');
@@ -607,7 +607,7 @@ class ViewTest extends \Test\TestCase {
/**
* @medium
*/
- public function testTouchFloat() {
+ public function testTouchFloat(): void {
$storage = $this->getTestStorage(true, TemporaryNoTouch::class);
Filesystem::mount($storage, [], '/');
@@ -624,7 +624,7 @@ class ViewTest extends \Test\TestCase {
/**
* @medium
*/
- public function testViewHooks() {
+ public function testViewHooks(): void {
$storage1 = $this->getTestStorage();
$storage2 = $this->getTestStorage();
$defaultRoot = Filesystem::getRoot();
@@ -649,7 +649,7 @@ class ViewTest extends \Test\TestCase {
$this->hookPath = $params['path'];
}
- public function testSearchNotOutsideView() {
+ public function testSearchNotOutsideView(): void {
$storage1 = $this->getTestStorage();
Filesystem::mount($storage1, [], '/');
$storage1->rename('folder', 'foo');
@@ -690,7 +690,7 @@ class ViewTest extends \Test\TestCase {
/**
* @medium
*/
- public function testViewHooksIfRootStartsTheSame() {
+ public function testViewHooksIfRootStartsTheSame(): void {
$storage1 = $this->getTestStorage();
$storage2 = $this->getTestStorage();
$defaultRoot = Filesystem::getRoot();
@@ -721,7 +721,7 @@ class ViewTest extends \Test\TestCase {
$this->hookCreatePath = $params['path'];
}
- public function testEditNoCreateHook() {
+ public function testEditNoCreateHook(): void {
$storage1 = $this->getTestStorage();
$storage2 = $this->getTestStorage();
$defaultRoot = Filesystem::getRoot();
@@ -754,7 +754,7 @@ class ViewTest extends \Test\TestCase {
/**
* @dataProvider resolvePathTestProvider
*/
- public function testResolvePath($expected, $pathToTest) {
+ public function testResolvePath($expected, $pathToTest): void {
$storage1 = $this->getTestStorage();
Filesystem::mount($storage1, [], '/');
@@ -785,7 +785,7 @@ class ViewTest extends \Test\TestCase {
];
}
- public function testUTF8Names() {
+ public function testUTF8Names(): void {
$names = ['虚', '和知しゃ和で', 'regular ascii', 'sɨˈrɪlɪk', 'ѨѬ', 'أنا أحب القراءة كثيرا'];
$storage = new Temporary([]);
@@ -864,7 +864,7 @@ class ViewTest extends \Test\TestCase {
}
}
- public function testTouchNotSupported() {
+ public function testTouchNotSupported(): void {
$storage = new TemporaryNoTouch([]);
$scanner = $storage->getScanner();
Filesystem::mount($storage, [], '/test/');
@@ -881,7 +881,7 @@ class ViewTest extends \Test\TestCase {
$this->assertSame($info['etag'], $info2['etag']);
}
- public function testWatcherEtagCrossStorage() {
+ public function testWatcherEtagCrossStorage(): void {
$storage1 = new Temporary([]);
$storage2 = new Temporary([]);
$scanner1 = $storage1->getScanner();
@@ -916,12 +916,12 @@ class ViewTest extends \Test\TestCase {
/**
* @dataProvider absolutePathProvider
*/
- public function testGetAbsolutePath($expectedPath, $relativePath) {
+ public function testGetAbsolutePath($expectedPath, $relativePath): void {
$view = new View('/files');
$this->assertEquals($expectedPath, $view->getAbsolutePath($relativePath));
}
- public function testPartFileInfo() {
+ public function testPartFileInfo(): void {
$storage = new Temporary([]);
$scanner = $storage->getScanner();
Filesystem::mount($storage, [], '/test/');
@@ -950,7 +950,7 @@ class ViewTest extends \Test\TestCase {
/**
* @dataProvider chrootRelativePathProvider
*/
- public function testChrootGetRelativePath($root, $absolutePath, $expectedPath) {
+ public function testChrootGetRelativePath($root, $absolutePath, $expectedPath): void {
$view = new View('/files');
$view->chroot($root);
$this->assertEquals($expectedPath, $view->getRelativePath($absolutePath));
@@ -963,7 +963,7 @@ class ViewTest extends \Test\TestCase {
/**
* @dataProvider initRelativePathProvider
*/
- public function testInitGetRelativePath($root, $absolutePath, $expectedPath) {
+ public function testInitGetRelativePath($root, $absolutePath, $expectedPath): void {
$view = new View($root);
$this->assertEquals($expectedPath, $view->getRelativePath($absolutePath));
}
@@ -1043,7 +1043,7 @@ class ViewTest extends \Test\TestCase {
];
}
- public function testFileView() {
+ public function testFileView(): void {
$storage = new Temporary([]);
$scanner = $storage->getScanner();
$storage->file_put_contents('foo.txt', 'bar');
@@ -1062,7 +1062,7 @@ class ViewTest extends \Test\TestCase {
/**
* @dataProvider tooLongPathDataProvider
*/
- public function testTooLongPath($operation, $param0 = null) {
+ public function testTooLongPath($operation, $param0 = null): void {
$this->expectException(\OCP\Files\InvalidPathException::class);
@@ -1137,7 +1137,7 @@ class ViewTest extends \Test\TestCase {
];
}
- public function testRenameCrossStoragePreserveMtime() {
+ public function testRenameCrossStoragePreserveMtime(): void {
$storage1 = new Temporary([]);
$storage2 = new Temporary([]);
$storage1->mkdir('sub');
@@ -1162,11 +1162,11 @@ class ViewTest extends \Test\TestCase {
$this->assertEquals($time, $view->filemtime('/test/sub/storage/foo/bar.txt'));
}
- public function testRenameFailDeleteTargetKeepSource() {
+ public function testRenameFailDeleteTargetKeepSource(): void {
$this->doTestCopyRenameFail('rename');
}
- public function testCopyFailDeleteTargetKeepSource() {
+ public function testCopyFailDeleteTargetKeepSource(): void {
$this->doTestCopyRenameFail('copy');
}
@@ -1217,7 +1217,7 @@ class ViewTest extends \Test\TestCase {
$this->assertFalse($storage2->getCache()->get('dirtomove/indir2.txt'));
}
- public function testDeleteFailKeepCache() {
+ public function testDeleteFailKeepCache(): void {
/** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
$storage = $this->getMockBuilder(Temporary::class)
->setConstructorArgs([[]])
@@ -1250,13 +1250,13 @@ class ViewTest extends \Test\TestCase {
* @dataProvider directoryTraversalProvider
* @param string $root
*/
- public function testConstructDirectoryTraversalException($root) {
+ public function testConstructDirectoryTraversalException($root): void {
$this->expectException(\Exception::class);
new View($root);
}
- public function testRenameOverWrite() {
+ public function testRenameOverWrite(): void {
$storage = new Temporary([]);
$scanner = $storage->getScanner();
$storage->mkdir('sub');
@@ -1269,7 +1269,7 @@ class ViewTest extends \Test\TestCase {
$this->assertTrue($view->rename('/test/foo.txt', '/test/foo/bar.txt'));
}
- public function testSetMountOptionsInStorage() {
+ public function testSetMountOptionsInStorage(): void {
$mount = new MountPoint(Temporary::class, '/asd/', [[]], Filesystem::getLoader(), ['foo' => 'bar']);
Filesystem::getMountManager()->addMount($mount);
/** @var \OC\Files\Storage\Common $storage */
@@ -1277,7 +1277,7 @@ class ViewTest extends \Test\TestCase {
$this->assertEquals($storage->getMountOption('foo'), 'bar');
}
- public function testSetMountOptionsWatcherPolicy() {
+ 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 */
@@ -1286,18 +1286,18 @@ class ViewTest extends \Test\TestCase {
$this->assertEquals(Watcher::CHECK_NEVER, $watcher->getPolicy());
}
- public function testGetAbsolutePathOnNull() {
+ public function testGetAbsolutePathOnNull(): void {
$view = new View();
$this->assertNull($view->getAbsolutePath(null));
}
- public function testGetRelativePathOnNull() {
+ public function testGetRelativePathOnNull(): void {
$view = new View();
$this->assertNull($view->getRelativePath(null));
}
- public function testNullAsRoot() {
+ public function testNullAsRoot(): void {
$this->expectException(\TypeError::class);
new View(null);
@@ -1312,7 +1312,7 @@ class ViewTest extends \Test\TestCase {
* @param string $rootPath
* @param string $pathPrefix
*/
- public function testReadFromWriteLockedPath($rootPath, $pathPrefix) {
+ public function testReadFromWriteLockedPath($rootPath, $pathPrefix): void {
$this->expectException(\OCP\Lock\LockedException::class);
$rootPath = str_replace('{folder}', 'files', $rootPath);
@@ -1333,7 +1333,7 @@ class ViewTest extends \Test\TestCase {
* @param string $rootPath
* @param string $pathPrefix
*/
- public function testReadFromWriteUnlockablePath($rootPath, $pathPrefix) {
+ public function testReadFromWriteUnlockablePath($rootPath, $pathPrefix): void {
$rootPath = str_replace('{folder}', 'files_encryption', $rootPath);
$pathPrefix = str_replace('{folder}', 'files_encryption', $pathPrefix);
@@ -1353,7 +1353,7 @@ class ViewTest extends \Test\TestCase {
* @param string $rootPath
* @param string $pathPrefix
*/
- public function testWriteToReadLockedFile($rootPath, $pathPrefix) {
+ public function testWriteToReadLockedFile($rootPath, $pathPrefix): void {
$this->expectException(\OCP\Lock\LockedException::class);
$rootPath = str_replace('{folder}', 'files', $rootPath);
@@ -1374,7 +1374,7 @@ class ViewTest extends \Test\TestCase {
* @param string $rootPath
* @param string $pathPrefix
*/
- public function testWriteToReadUnlockableFile($rootPath, $pathPrefix) {
+ public function testWriteToReadUnlockableFile($rootPath, $pathPrefix): void {
$rootPath = str_replace('{folder}', 'files_encryption', $rootPath);
$pathPrefix = str_replace('{folder}', 'files_encryption', $pathPrefix);
@@ -1388,7 +1388,7 @@ class ViewTest extends \Test\TestCase {
/**
* Test that locks are on mount point paths instead of mount root
*/
- public function testLockLocalMountPointPathInsteadOfStorageRoot() {
+ public function testLockLocalMountPointPathInsteadOfStorageRoot(): void {
$lockingProvider = \OC::$server->get(ILockingProvider::class);
$view = new View('/testuser/files/');
$storage = new Temporary([]);
@@ -1418,7 +1418,7 @@ class ViewTest extends \Test\TestCase {
/**
* Test that locks are on mount point paths and also mount root when requested
*/
- public function testLockStorageRootButNotLocalMountPoint() {
+ public function testLockStorageRootButNotLocalMountPoint(): void {
$lockingProvider = \OC::$server->get(ILockingProvider::class);
$view = new View('/testuser/files/');
$storage = new Temporary([]);
@@ -1448,7 +1448,7 @@ class ViewTest extends \Test\TestCase {
/**
* Test that locks are on mount point paths and also mount root when requested
*/
- public function testLockMountPointPathFailReleasesBoth() {
+ public function testLockMountPointPathFailReleasesBoth(): void {
$lockingProvider = \OC::$server->get(ILockingProvider::class);
$view = new View('/testuser/files/');
$storage = new Temporary([]);
@@ -1499,7 +1499,7 @@ class ViewTest extends \Test\TestCase {
/**
* @dataProvider pathRelativeToFilesProvider
*/
- public function testGetPathRelativeToFiles($path, $expectedPath) {
+ public function testGetPathRelativeToFiles($path, $expectedPath): void {
$view = new View();
$this->assertEquals($expectedPath, $view->getPathRelativeToFiles($path));
}
@@ -1518,7 +1518,7 @@ class ViewTest extends \Test\TestCase {
* @dataProvider pathRelativeToFilesProviderExceptionCases
* @param string $path
*/
- public function testGetPathRelativeToFilesWithInvalidArgument($path) {
+ public function testGetPathRelativeToFilesWithInvalidArgument($path): void {
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('$absolutePath must be relative to "files"');
@@ -1526,7 +1526,7 @@ class ViewTest extends \Test\TestCase {
$view->getPathRelativeToFiles($path);
}
- public function testChangeLock() {
+ public function testChangeLock(): void {
$view = new View('/testuser/files/');
$storage = new Temporary([]);
Filesystem::mount($storage, [], '/');
@@ -1565,7 +1565,7 @@ class ViewTest extends \Test\TestCase {
* @param $path
* @param $shouldEmit
*/
- public function testHookPaths($root, $path, $shouldEmit) {
+ public function testHookPaths($root, $path, $shouldEmit): void {
$filesystemReflection = new \ReflectionClass(Filesystem::class);
$defaultRootValue = $filesystemReflection->getProperty('defaultInstance');
$defaultRootValue->setAccessible(true);
@@ -1617,7 +1617,7 @@ class ViewTest extends \Test\TestCase {
/**
* Test mount point move
*/
- public function testMountPointMove() {
+ public function testMountPointMove(): void {
self::loginAsUser($this->user);
[$mount1, $mount2] = $this->createTestMovableMountPoints([
@@ -1642,7 +1642,7 @@ class ViewTest extends \Test\TestCase {
/**
* Test that moving a mount point into another is forbidden
*/
- public function testMoveMountPointIntoAnother() {
+ public function testMoveMountPointIntoAnother(): void {
self::loginAsUser($this->user);
[$mount1, $mount2] = $this->createTestMovableMountPoints([
@@ -1665,7 +1665,7 @@ class ViewTest extends \Test\TestCase {
/**
* Test that moving a mount point into a shared folder is forbidden
*/
- public function testMoveMountPointIntoSharedFolder() {
+ public function testMoveMountPointIntoSharedFolder(): void {
self::loginAsUser($this->user);
[$mount1, $mount2] = $this->createTestMovableMountPoints([
@@ -1856,7 +1856,7 @@ class ViewTest extends \Test\TestCase {
$expectedLockAfter = ILockingProvider::LOCK_SHARED,
$expectedStrayLock = null,
$returnValue = true,
- ) {
+ ): void {
$view = new View('/' . $this->user . '/files/');
/** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
@@ -1905,7 +1905,7 @@ class ViewTest extends \Test\TestCase {
* Test locks for file_put_content with stream.
* This code path uses $storage->fopen instead
*/
- public function testLockFilePutContentWithStream() {
+ public function testLockFilePutContentWithStream(): void {
$view = new View('/' . $this->user . '/files/');
$path = 'test_file_put_contents.txt';
@@ -1944,7 +1944,7 @@ class ViewTest extends \Test\TestCase {
/**
* Test locks for fopen with fclose at the end
*/
- public function testLockFopen() {
+ public function testLockFopen(): void {
$view = new View('/' . $this->user . '/files/');
$path = 'test_file_put_contents.txt';
@@ -1997,7 +1997,7 @@ class ViewTest extends \Test\TestCase {
$operation,
$operationArgs,
$path
- ) {
+ ): void {
if ($operation === 'touch') {
$this->markTestSkipped('touch handles storage exceptions internally');
}
@@ -2036,7 +2036,7 @@ class ViewTest extends \Test\TestCase {
$this->assertNull($this->getFileLockType($view, $path), 'File got unlocked after exception');
}
- public function testLockBasicOperationUnlocksAfterLockException() {
+ public function testLockBasicOperationUnlocksAfterLockException(): void {
$view = new View('/' . $this->user . '/files/');
$storage = new Temporary([]);
@@ -2082,7 +2082,7 @@ class ViewTest extends \Test\TestCase {
$operationArgs,
$path,
$hookType
- ) {
+ ): void {
$view = new View('/' . $this->user . '/files/');
/** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
@@ -2121,7 +2121,7 @@ class ViewTest extends \Test\TestCase {
* @param int $expectedLockTypeSourceDuring expected lock type on source file during
* the operation
*/
- public function testLockFileRename($operation, $expectedLockTypeSourceDuring) {
+ public function testLockFileRename($operation, $expectedLockTypeSourceDuring): void {
$view = new View('/' . $this->user . '/files/');
/** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
@@ -2185,7 +2185,7 @@ class ViewTest extends \Test\TestCase {
* We expect that we catch the exception, free the lock and re-throw it.
*
*/
- public function testLockFileCopyException() {
+ public function testLockFileCopyException(): void {
$this->expectException(\Exception::class);
$view = new View('/' . $this->user . '/files/');
@@ -2228,7 +2228,7 @@ class ViewTest extends \Test\TestCase {
/**
* Test rename operation: unlock first path when second path was locked
*/
- public function testLockFileRenameUnlockOnException() {
+ public function testLockFileRenameUnlockOnException(): void {
self::loginAsUser('test');
$view = new View('/' . $this->user . '/files/');
@@ -2261,7 +2261,7 @@ class ViewTest extends \Test\TestCase {
/**
* Test rename operation: unlock first path when second path was locked
*/
- public function testGetOwner() {
+ public function testGetOwner(): void {
self::loginAsUser('test');
$view = new View('/test/files/');
@@ -2306,7 +2306,7 @@ class ViewTest extends \Test\TestCase {
* @param int $expectedLockTypeSourceDuring expected lock type on source file during
* the operation
*/
- public function testLockFileRenameCrossStorage($viewOperation, $storageOperation, $expectedLockTypeSourceDuring) {
+ public function testLockFileRenameCrossStorage($viewOperation, $storageOperation, $expectedLockTypeSourceDuring): void {
$view = new View('/' . $this->user . '/files/');
/** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
@@ -2375,7 +2375,7 @@ class ViewTest extends \Test\TestCase {
/**
* Test locks when moving a mount point
*/
- public function testLockMoveMountPoint() {
+ public function testLockMoveMountPoint(): void {
self::loginAsUser('test');
[$mount] = $this->createTestMovableMountPoints([
@@ -2504,7 +2504,7 @@ class ViewTest extends \Test\TestCase {
}
- public function testRemoveMoveableMountPoint() {
+ public function testRemoveMoveableMountPoint(): void {
$mountPoint = '/' . $this->user . '/files/mount/';
// Mock the mount point
@@ -2565,7 +2565,7 @@ class ViewTest extends \Test\TestCase {
* @param string[] $expected
* @dataProvider mimeFilterProvider
*/
- public function testGetDirectoryContentMimeFilter($filter, $expected) {
+ public function testGetDirectoryContentMimeFilter($filter, $expected): void {
$storage1 = new Temporary();
$root = self::getUniqueID('/');
Filesystem::mount($storage1, [], $root . '/');
@@ -2586,7 +2586,7 @@ class ViewTest extends \Test\TestCase {
$this->assertEquals($expected, $files);
}
- public function testFilePutContentsClearsChecksum() {
+ public function testFilePutContentsClearsChecksum(): void {
$storage = new Temporary([]);
$scanner = $storage->getScanner();
$storage->file_put_contents('foo.txt', 'bar');
@@ -2607,7 +2607,7 @@ class ViewTest extends \Test\TestCase {
$this->assertEquals('', $data->getChecksum());
}
- public function testDeleteGhostFile() {
+ public function testDeleteGhostFile(): void {
$storage = new Temporary([]);
$scanner = $storage->getScanner();
$cache = $storage->getCache();
@@ -2630,7 +2630,7 @@ class ViewTest extends \Test\TestCase {
$this->assertEquals(0, $newInfo->getSize());
}
- public function testDeleteGhostFolder() {
+ public function testDeleteGhostFolder(): void {
$storage = new Temporary([]);
$scanner = $storage->getScanner();
$cache = $storage->getCache();
@@ -2656,7 +2656,7 @@ class ViewTest extends \Test\TestCase {
$this->assertEquals(0, $newInfo->getSize());
}
- public function testCreateParentDirectories() {
+ public function testCreateParentDirectories(): void {
$view = $this->getMockBuilder(View::class)
->disableOriginalConstructor()
->setMethods([
@@ -2695,7 +2695,7 @@ class ViewTest extends \Test\TestCase {
$this->assertTrue(self::invokePrivate($view, 'createParentDirectories', ['/new/folder/structure']));
}
- public function testCreateParentDirectoriesWithExistingFile() {
+ public function testCreateParentDirectoriesWithExistingFile(): void {
$view = $this->getMockBuilder(View::class)
->disableOriginalConstructor()
->setMethods([
@@ -2713,7 +2713,7 @@ class ViewTest extends \Test\TestCase {
$this->assertFalse(self::invokePrivate($view, 'createParentDirectories', ['/file.txt/folder/structure']));
}
- public function testCacheExtension() {
+ public function testCacheExtension(): void {
$storage = new Temporary([]);
$scanner = $storage->getScanner();
$storage->file_put_contents('foo.txt', 'bar');
@@ -2733,7 +2733,7 @@ class ViewTest extends \Test\TestCase {
$this->assertEquals(0, $info->getCreationTime());
}
- public function testFopenGone() {
+ public function testFopenGone(): void {
$storage = new Temporary([]);
$scanner = $storage->getScanner();
$storage->file_put_contents('foo.txt', 'bar');
@@ -2752,7 +2752,7 @@ class ViewTest extends \Test\TestCase {
$this->assertFalse($cache->inCache('foo.txt'));
}
- public function testMountpointParentsCreated() {
+ public function testMountpointParentsCreated(): void {
$storage1 = $this->getTestStorage();
Filesystem::mount($storage1, [], '/');
diff --git a/tests/lib/GlobalScale/ConfigTest.php b/tests/lib/GlobalScale/ConfigTest.php
index ca02332d02b..aa001268ecd 100644
--- a/tests/lib/GlobalScale/ConfigTest.php
+++ b/tests/lib/GlobalScale/ConfigTest.php
@@ -35,7 +35,7 @@ class ConfigTest extends TestCase {
return new Config($this->config);
}
- public function testIsGlobalScaleEnabled() {
+ public function testIsGlobalScaleEnabled(): void {
$gsConfig = $this->getInstance();
$this->config->expects($this->once())->method('getSystemValueBool')
->with('gs.enabled', false)->willReturn(true);
@@ -53,7 +53,7 @@ class ConfigTest extends TestCase {
* @param string $gsFederation
* @param bool $expected
*/
- public function testOnlyInternalFederation($gsEnabled, $gsFederation, $expected) {
+ public function testOnlyInternalFederation($gsEnabled, $gsFederation, $expected): void {
$gsConfig = $this->getInstance(['isGlobalScaleEnabled']);
$gsConfig->expects($this->any())->method('isGlobalScaleEnabled')->willReturn($gsEnabled);
diff --git a/tests/lib/Group/Backend.php b/tests/lib/Group/Backend.php
index 7eb71d0f22c..1b6bfe840f8 100644
--- a/tests/lib/Group/Backend.php
+++ b/tests/lib/Group/Backend.php
@@ -42,7 +42,7 @@ abstract class Backend extends \Test\TestCase {
return $this->getUniqueID('test_');
}
- public function testAddRemove() {
+ public function testAddRemove(): void {
//get the number of groups we start with, in case there are exising groups
$startCount = count($this->backend->getGroups());
@@ -66,7 +66,7 @@ abstract class Backend extends \Test\TestCase {
$this->assertFalse((array_search($name2, $this->backend->getGroups()) !== false));
}
- public function testUser() {
+ public function testUser(): void {
$group1 = $this->getGroupName();
$group2 = $this->getGroupName();
$this->backend->createGroup($group1);
@@ -101,7 +101,7 @@ abstract class Backend extends \Test\TestCase {
$this->assertFalse($this->backend->inGroup($user1, $group1));
}
- public function testSearchGroups() {
+ public function testSearchGroups(): void {
$name1 = $this->getGroupName('foobarbaz');
$name2 = $this->getGroupName('bazbarfoo');
$name3 = $this->getGroupName('notme');
@@ -114,7 +114,7 @@ abstract class Backend extends \Test\TestCase {
$this->assertSame(2, count($result));
}
- public function testSearchUsers() {
+ public function testSearchUsers(): void {
$group = $this->getGroupName();
$this->backend->createGroup($group);
@@ -133,7 +133,7 @@ abstract class Backend extends \Test\TestCase {
$this->assertSame(2, $result);
}
- public function testAddDouble() {
+ public function testAddDouble(): void {
$group = $this->getGroupName();
$this->backend->createGroup($group);
diff --git a/tests/lib/Group/GroupTest.php b/tests/lib/Group/GroupTest.php
index 14cdaf1f2cb..a15a6e39a24 100644
--- a/tests/lib/Group/GroupTest.php
+++ b/tests/lib/Group/GroupTest.php
@@ -1,475 +1,475 @@
-<?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\Group;
-
-use OC\User\User;
-use OCP\EventDispatcher\IEventDispatcher;
-use OCP\IUser;
-use PHPUnit\Framework\MockObject\MockObject;
-
-class GroupTest extends \Test\TestCase {
- /** @var IEventDispatcher|MockObject */
- protected $dispatcher;
-
- protected function setUp(): void {
- parent::setUp();
- $this->dispatcher = $this->createMock(IEventDispatcher::class);
- }
-
- /**
- * @param string $uid
- * @param \OC\User\Backend $backend
- * @return User
- */
- private function newUser($uid, \OC\User\Backend $backend) {
- $user = $this->createMock(IUser::class);
- $user->method('getUID')
- ->willReturn($uid);
- $user->method('getBackend')
- ->willReturn($backend);
-
- return $user;
- }
-
- /**
- * @return \OC\User\Manager
- */
- protected function getUserManager() {
- $userManager = $this->getMockBuilder(\OC\User\Manager::class)
- ->disableOriginalConstructor()
- ->getMock();
- $backend = $this->getMockBuilder(\OC\User\Backend::class)
- ->disableOriginalConstructor()
- ->getMock();
- $user1 = $this->newUser('user1', $backend);
- $user2 = $this->newUser('user2', $backend);
- $user3 = $this->newUser('user3', $backend);
- $userManager->expects($this->any())
- ->method('get')
- ->willReturnMap([
- ['user1', $user1],
- ['user2', $user2],
- ['user3', $user3]
- ]);
- return $userManager;
- }
-
- public function testGetUsersSingleBackend() {
- $backend = $this->getMockBuilder(\OC\Group\Database::class)
- ->disableOriginalConstructor()
- ->getMock();
- $userManager = $this->getUserManager();
- $group = new \OC\Group\Group('group1', [$backend], $this->dispatcher, $userManager);
-
- $backend->expects($this->once())
- ->method('usersInGroup')
- ->with('group1')
- ->willReturn(['user1', 'user2']);
-
- $users = $group->getUsers();
-
- $this->assertEquals(2, count($users));
- $user1 = $users['user1'];
- $user2 = $users['user2'];
- $this->assertEquals('user1', $user1->getUID());
- $this->assertEquals('user2', $user2->getUID());
- }
-
- public function testGetUsersMultipleBackends() {
- $backend1 = $this->getMockBuilder(\OC\Group\Database::class)
- ->disableOriginalConstructor()
- ->getMock();
- $backend2 = $this->getMockBuilder(\OC\Group\Database::class)
- ->disableOriginalConstructor()
- ->getMock();
- $userManager = $this->getUserManager();
- $group = new \OC\Group\Group('group1', [$backend1, $backend2], $this->dispatcher, $userManager);
-
- $backend1->expects($this->once())
- ->method('usersInGroup')
- ->with('group1')
- ->willReturn(['user1', 'user2']);
-
- $backend2->expects($this->once())
- ->method('usersInGroup')
- ->with('group1')
- ->willReturn(['user2', 'user3']);
-
- $users = $group->getUsers();
-
- $this->assertEquals(3, count($users));
- $user1 = $users['user1'];
- $user2 = $users['user2'];
- $user3 = $users['user3'];
- $this->assertEquals('user1', $user1->getUID());
- $this->assertEquals('user2', $user2->getUID());
- $this->assertEquals('user3', $user3->getUID());
- }
-
- public function testInGroupSingleBackend() {
- $backend = $this->getMockBuilder(\OC\Group\Database::class)
- ->disableOriginalConstructor()
- ->getMock();
- $userManager = $this->getUserManager();
- $userBackend = $this->getMockBuilder(\OC\User\Backend::class)
- ->disableOriginalConstructor()
- ->getMock();
- $group = new \OC\Group\Group('group1', [$backend], $this->dispatcher, $userManager);
-
- $backend->expects($this->once())
- ->method('inGroup')
- ->with('user1', 'group1')
- ->willReturn(true);
-
- $this->assertTrue($group->inGroup($this->newUser('user1', $userBackend)));
- }
-
- public function testInGroupMultipleBackends() {
- $backend1 = $this->getMockBuilder(\OC\Group\Database::class)
- ->disableOriginalConstructor()
- ->getMock();
- $backend2 = $this->getMockBuilder(\OC\Group\Database::class)
- ->disableOriginalConstructor()
- ->getMock();
- $userManager = $this->getUserManager();
- $userBackend = $this->getMockBuilder(\OC\User\Backend::class)
- ->disableOriginalConstructor()
- ->getMock();
- $group = new \OC\Group\Group('group1', [$backend1, $backend2], $this->dispatcher, $userManager);
-
- $backend1->expects($this->once())
- ->method('inGroup')
- ->with('user1', 'group1')
- ->willReturn(false);
-
- $backend2->expects($this->once())
- ->method('inGroup')
- ->with('user1', 'group1')
- ->willReturn(true);
-
- $this->assertTrue($group->inGroup($this->newUser('user1', $userBackend)));
- }
-
- public function testAddUser() {
- $backend = $this->getMockBuilder(\OC\Group\Database::class)
- ->disableOriginalConstructor()
- ->getMock();
- $userManager = $this->getUserManager();
- $userBackend = $this->getMockBuilder(\OC\User\Backend::class)
- ->disableOriginalConstructor()
- ->getMock();
- $group = new \OC\Group\Group('group1', [$backend], $this->dispatcher, $userManager);
-
- $backend->expects($this->once())
- ->method('inGroup')
- ->with('user1', 'group1')
- ->willReturn(false);
- $backend->expects($this->any())
- ->method('implementsActions')
- ->willReturn(true);
-
- $backend->expects($this->once())
- ->method('addToGroup')
- ->with('user1', 'group1');
-
- $group->addUser($this->newUser('user1', $userBackend));
- }
-
- public function testAddUserAlreadyInGroup() {
- $backend = $this->getMockBuilder(\OC\Group\Database::class)
- ->disableOriginalConstructor()
- ->getMock();
- $userManager = $this->getUserManager();
- $userBackend = $this->getMockBuilder(\OC\User\Backend::class)
- ->disableOriginalConstructor()
- ->getMock();
- $group = new \OC\Group\Group('group1', [$backend], $this->dispatcher, $userManager);
-
- $backend->expects($this->once())
- ->method('inGroup')
- ->with('user1', 'group1')
- ->willReturn(true);
- $backend->expects($this->any())
- ->method('implementsActions')
- ->willReturn(true);
-
- $backend->expects($this->never())
- ->method('addToGroup');
-
- $group->addUser($this->newUser('user1', $userBackend));
- }
-
- public function testRemoveUser() {
- $backend = $this->getMockBuilder(\OC\Group\Database::class)
- ->disableOriginalConstructor()
- ->getMock();
- $userManager = $this->getUserManager();
- $userBackend = $this->getMockBuilder(\OC\User\Backend::class)
- ->disableOriginalConstructor()
- ->getMock();
- $group = new \OC\Group\Group('group1', [$backend], $this->dispatcher, $userManager);
-
- $backend->expects($this->once())
- ->method('inGroup')
- ->with('user1', 'group1')
- ->willReturn(true);
- $backend->expects($this->any())
- ->method('implementsActions')
- ->willReturn(true);
-
- $backend->expects($this->once())
- ->method('removeFromGroup')
- ->with('user1', 'group1');
-
- $group->removeUser($this->newUser('user1', $userBackend));
- }
-
- public function testRemoveUserNotInGroup() {
- $backend = $this->getMockBuilder(\OC\Group\Database::class)
- ->disableOriginalConstructor()
- ->getMock();
- $userManager = $this->getUserManager();
- $userBackend = $this->getMockBuilder(\OC\User\Backend::class)
- ->disableOriginalConstructor()
- ->getMock();
- $group = new \OC\Group\Group('group1', [$backend], $this->dispatcher, $userManager);
-
- $backend->expects($this->once())
- ->method('inGroup')
- ->with('user1', 'group1')
- ->willReturn(false);
- $backend->expects($this->any())
- ->method('implementsActions')
- ->willReturn(true);
-
- $backend->expects($this->never())
- ->method('removeFromGroup');
-
- $group->removeUser($this->newUser('user1', $userBackend));
- }
-
- public function testRemoveUserMultipleBackends() {
- $backend1 = $this->getMockBuilder(\OC\Group\Database::class)
- ->disableOriginalConstructor()
- ->getMock();
- $backend2 = $this->getMockBuilder(\OC\Group\Database::class)
- ->disableOriginalConstructor()
- ->getMock();
- $userManager = $this->getUserManager();
- $userBackend = $this->getMockBuilder(\OC\User\Backend::class)
- ->disableOriginalConstructor()
- ->getMock();
- $group = new \OC\Group\Group('group1', [$backend1, $backend2], $this->dispatcher, $userManager);
-
- $backend1->expects($this->once())
- ->method('inGroup')
- ->with('user1', 'group1')
- ->willReturn(true);
- $backend1->expects($this->any())
- ->method('implementsActions')
- ->willReturn(true);
-
- $backend1->expects($this->once())
- ->method('removeFromGroup')
- ->with('user1', 'group1');
-
- $backend2->expects($this->once())
- ->method('inGroup')
- ->with('user1', 'group1')
- ->willReturn(true);
- $backend2->expects($this->any())
- ->method('implementsActions')
- ->willReturn(true);
-
- $backend2->expects($this->once())
- ->method('removeFromGroup')
- ->with('user1', 'group1');
-
- $group->removeUser($this->newUser('user1', $userBackend));
- }
-
- public function testSearchUsers() {
- $backend = $this->getMockBuilder(\OC\Group\Database::class)
- ->disableOriginalConstructor()
- ->getMock();
- $userManager = $this->getUserManager();
- $group = new \OC\Group\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)]);
-
- $users = $group->searchUsers('2');
-
- $this->assertEquals(1, count($users));
- $user2 = reset($users);
- $this->assertEquals('user2', $user2->getUID());
- }
-
- public function testSearchUsersMultipleBackends() {
- $backend1 = $this->getMockBuilder(\OC\Group\Database::class)
- ->disableOriginalConstructor()
- ->getMock();
- $backend2 = $this->getMockBuilder(\OC\Group\Database::class)
- ->disableOriginalConstructor()
- ->getMock();
- $userManager = $this->getUserManager();
- $group = new \OC\Group\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)]);
- $backend2->expects($this->once())
- ->method('searchInGroup')
- ->with('group1', '2')
- ->willReturn(['user2' => new \OC\User\User('user2', null, $this->dispatcher)]);
-
- $users = $group->searchUsers('2');
-
- $this->assertEquals(1, count($users));
- $user2 = reset($users);
- $this->assertEquals('user2', $user2->getUID());
- }
-
- public function testSearchUsersLimitAndOffset() {
- $backend = $this->getMockBuilder(\OC\Group\Database::class)
- ->disableOriginalConstructor()
- ->getMock();
- $userManager = $this->getUserManager();
- $group = new \OC\Group\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)]);
-
- $users = $group->searchUsers('user', 1, 1);
-
- $this->assertEquals(1, count($users));
- $user2 = reset($users);
- $this->assertEquals('user2', $user2->getUID());
- }
-
- public function testSearchUsersMultipleBackendsLimitAndOffset() {
- $backend1 = $this->getMockBuilder(\OC\Group\Database::class)
- ->disableOriginalConstructor()
- ->getMock();
- $backend2 = $this->getMockBuilder(\OC\Group\Database::class)
- ->disableOriginalConstructor()
- ->getMock();
- $userManager = $this->getUserManager();
- $group = new \OC\Group\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)]);
- $backend2->expects($this->once())
- ->method('searchInGroup')
- ->with('group1', 'user', 2, 1)
- ->willReturn(['user1' => new \OC\User\User('user1', null, $this->dispatcher)]);
-
- $users = $group->searchUsers('user', 2, 1);
-
- $this->assertEquals(2, count($users));
- $user2 = reset($users);
- $user1 = next($users);
- $this->assertEquals('user2', $user2->getUID());
- $this->assertEquals('user1', $user1->getUID());
- }
-
- public function testCountUsers() {
- $backend1 = $this->getMockBuilder(\OC\Group\Database::class)
- ->disableOriginalConstructor()
- ->getMock();
- $userManager = $this->getUserManager();
- $group = new \OC\Group\Group('group1', [$backend1], $this->dispatcher, $userManager);
-
- $backend1->expects($this->once())
- ->method('countUsersInGroup')
- ->with('group1', '2')
- ->willReturn(3);
-
- $backend1->expects($this->any())
- ->method('implementsActions')
- ->willReturn(true);
-
- $users = $group->count('2');
-
- $this->assertSame(3, $users);
- }
-
- public function testCountUsersMultipleBackends() {
- $backend1 = $this->getMockBuilder(\OC\Group\Database::class)
- ->disableOriginalConstructor()
- ->getMock();
- $backend2 = $this->getMockBuilder(\OC\Group\Database::class)
- ->disableOriginalConstructor()
- ->getMock();
- $userManager = $this->getUserManager();
- $group = new \OC\Group\Group('group1', [$backend1, $backend2], $this->dispatcher, $userManager);
-
- $backend1->expects($this->once())
- ->method('countUsersInGroup')
- ->with('group1', '2')
- ->willReturn(3);
- $backend1->expects($this->any())
- ->method('implementsActions')
- ->willReturn(true);
-
- $backend2->expects($this->once())
- ->method('countUsersInGroup')
- ->with('group1', '2')
- ->willReturn(4);
- $backend2->expects($this->any())
- ->method('implementsActions')
- ->willReturn(true);
-
- $users = $group->count('2');
-
- $this->assertSame(7, $users);
- }
-
- public function testCountUsersNoMethod() {
- $backend1 = $this->getMockBuilder(\OC\Group\Database::class)
- ->disableOriginalConstructor()
- ->getMock();
- $userManager = $this->getUserManager();
- $group = new \OC\Group\Group('group1', [$backend1], $this->dispatcher, $userManager);
-
- $backend1->expects($this->never())
- ->method('countUsersInGroup');
- $backend1->expects($this->any())
- ->method('implementsActions')
- ->willReturn(false);
-
- $users = $group->count('2');
-
- $this->assertSame(false, $users);
- }
-
- public function testDelete() {
- $backend = $this->getMockBuilder(\OC\Group\Database::class)
- ->disableOriginalConstructor()
- ->getMock();
- $userManager = $this->getUserManager();
- $group = new \OC\Group\Group('group1', [$backend], $this->dispatcher, $userManager);
-
- $backend->expects($this->once())
- ->method('deleteGroup')
- ->with('group1');
- $backend->expects($this->any())
- ->method('implementsActions')
- ->willReturn(true);
-
- $group->delete();
- }
-}
+<?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\Group;
+
+use OC\User\User;
+use OCP\EventDispatcher\IEventDispatcher;
+use OCP\IUser;
+use PHPUnit\Framework\MockObject\MockObject;
+
+class GroupTest extends \Test\TestCase {
+ /** @var IEventDispatcher|MockObject */
+ protected $dispatcher;
+
+ protected function setUp(): void {
+ parent::setUp();
+ $this->dispatcher = $this->createMock(IEventDispatcher::class);
+ }
+
+ /**
+ * @param string $uid
+ * @param \OC\User\Backend $backend
+ * @return User
+ */
+ private function newUser($uid, \OC\User\Backend $backend) {
+ $user = $this->createMock(IUser::class);
+ $user->method('getUID')
+ ->willReturn($uid);
+ $user->method('getBackend')
+ ->willReturn($backend);
+
+ return $user;
+ }
+
+ /**
+ * @return \OC\User\Manager
+ */
+ protected function getUserManager() {
+ $userManager = $this->getMockBuilder(\OC\User\Manager::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $backend = $this->getMockBuilder(\OC\User\Backend::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $user1 = $this->newUser('user1', $backend);
+ $user2 = $this->newUser('user2', $backend);
+ $user3 = $this->newUser('user3', $backend);
+ $userManager->expects($this->any())
+ ->method('get')
+ ->willReturnMap([
+ ['user1', $user1],
+ ['user2', $user2],
+ ['user3', $user3]
+ ]);
+ return $userManager;
+ }
+
+ public function testGetUsersSingleBackend(): void {
+ $backend = $this->getMockBuilder(\OC\Group\Database::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userManager = $this->getUserManager();
+ $group = new \OC\Group\Group('group1', [$backend], $this->dispatcher, $userManager);
+
+ $backend->expects($this->once())
+ ->method('usersInGroup')
+ ->with('group1')
+ ->willReturn(['user1', 'user2']);
+
+ $users = $group->getUsers();
+
+ $this->assertEquals(2, count($users));
+ $user1 = $users['user1'];
+ $user2 = $users['user2'];
+ $this->assertEquals('user1', $user1->getUID());
+ $this->assertEquals('user2', $user2->getUID());
+ }
+
+ public function testGetUsersMultipleBackends(): void {
+ $backend1 = $this->getMockBuilder(\OC\Group\Database::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $backend2 = $this->getMockBuilder(\OC\Group\Database::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userManager = $this->getUserManager();
+ $group = new \OC\Group\Group('group1', [$backend1, $backend2], $this->dispatcher, $userManager);
+
+ $backend1->expects($this->once())
+ ->method('usersInGroup')
+ ->with('group1')
+ ->willReturn(['user1', 'user2']);
+
+ $backend2->expects($this->once())
+ ->method('usersInGroup')
+ ->with('group1')
+ ->willReturn(['user2', 'user3']);
+
+ $users = $group->getUsers();
+
+ $this->assertEquals(3, count($users));
+ $user1 = $users['user1'];
+ $user2 = $users['user2'];
+ $user3 = $users['user3'];
+ $this->assertEquals('user1', $user1->getUID());
+ $this->assertEquals('user2', $user2->getUID());
+ $this->assertEquals('user3', $user3->getUID());
+ }
+
+ public function testInGroupSingleBackend(): void {
+ $backend = $this->getMockBuilder(\OC\Group\Database::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userManager = $this->getUserManager();
+ $userBackend = $this->getMockBuilder(\OC\User\Backend::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $group = new \OC\Group\Group('group1', [$backend], $this->dispatcher, $userManager);
+
+ $backend->expects($this->once())
+ ->method('inGroup')
+ ->with('user1', 'group1')
+ ->willReturn(true);
+
+ $this->assertTrue($group->inGroup($this->newUser('user1', $userBackend)));
+ }
+
+ public function testInGroupMultipleBackends(): void {
+ $backend1 = $this->getMockBuilder(\OC\Group\Database::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $backend2 = $this->getMockBuilder(\OC\Group\Database::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userManager = $this->getUserManager();
+ $userBackend = $this->getMockBuilder(\OC\User\Backend::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $group = new \OC\Group\Group('group1', [$backend1, $backend2], $this->dispatcher, $userManager);
+
+ $backend1->expects($this->once())
+ ->method('inGroup')
+ ->with('user1', 'group1')
+ ->willReturn(false);
+
+ $backend2->expects($this->once())
+ ->method('inGroup')
+ ->with('user1', 'group1')
+ ->willReturn(true);
+
+ $this->assertTrue($group->inGroup($this->newUser('user1', $userBackend)));
+ }
+
+ public function testAddUser(): void {
+ $backend = $this->getMockBuilder(\OC\Group\Database::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userManager = $this->getUserManager();
+ $userBackend = $this->getMockBuilder(\OC\User\Backend::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $group = new \OC\Group\Group('group1', [$backend], $this->dispatcher, $userManager);
+
+ $backend->expects($this->once())
+ ->method('inGroup')
+ ->with('user1', 'group1')
+ ->willReturn(false);
+ $backend->expects($this->any())
+ ->method('implementsActions')
+ ->willReturn(true);
+
+ $backend->expects($this->once())
+ ->method('addToGroup')
+ ->with('user1', 'group1');
+
+ $group->addUser($this->newUser('user1', $userBackend));
+ }
+
+ public function testAddUserAlreadyInGroup(): void {
+ $backend = $this->getMockBuilder(\OC\Group\Database::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userManager = $this->getUserManager();
+ $userBackend = $this->getMockBuilder(\OC\User\Backend::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $group = new \OC\Group\Group('group1', [$backend], $this->dispatcher, $userManager);
+
+ $backend->expects($this->once())
+ ->method('inGroup')
+ ->with('user1', 'group1')
+ ->willReturn(true);
+ $backend->expects($this->any())
+ ->method('implementsActions')
+ ->willReturn(true);
+
+ $backend->expects($this->never())
+ ->method('addToGroup');
+
+ $group->addUser($this->newUser('user1', $userBackend));
+ }
+
+ public function testRemoveUser(): void {
+ $backend = $this->getMockBuilder(\OC\Group\Database::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userManager = $this->getUserManager();
+ $userBackend = $this->getMockBuilder(\OC\User\Backend::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $group = new \OC\Group\Group('group1', [$backend], $this->dispatcher, $userManager);
+
+ $backend->expects($this->once())
+ ->method('inGroup')
+ ->with('user1', 'group1')
+ ->willReturn(true);
+ $backend->expects($this->any())
+ ->method('implementsActions')
+ ->willReturn(true);
+
+ $backend->expects($this->once())
+ ->method('removeFromGroup')
+ ->with('user1', 'group1');
+
+ $group->removeUser($this->newUser('user1', $userBackend));
+ }
+
+ public function testRemoveUserNotInGroup(): void {
+ $backend = $this->getMockBuilder(\OC\Group\Database::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userManager = $this->getUserManager();
+ $userBackend = $this->getMockBuilder(\OC\User\Backend::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $group = new \OC\Group\Group('group1', [$backend], $this->dispatcher, $userManager);
+
+ $backend->expects($this->once())
+ ->method('inGroup')
+ ->with('user1', 'group1')
+ ->willReturn(false);
+ $backend->expects($this->any())
+ ->method('implementsActions')
+ ->willReturn(true);
+
+ $backend->expects($this->never())
+ ->method('removeFromGroup');
+
+ $group->removeUser($this->newUser('user1', $userBackend));
+ }
+
+ public function testRemoveUserMultipleBackends(): void {
+ $backend1 = $this->getMockBuilder(\OC\Group\Database::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $backend2 = $this->getMockBuilder(\OC\Group\Database::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userManager = $this->getUserManager();
+ $userBackend = $this->getMockBuilder(\OC\User\Backend::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $group = new \OC\Group\Group('group1', [$backend1, $backend2], $this->dispatcher, $userManager);
+
+ $backend1->expects($this->once())
+ ->method('inGroup')
+ ->with('user1', 'group1')
+ ->willReturn(true);
+ $backend1->expects($this->any())
+ ->method('implementsActions')
+ ->willReturn(true);
+
+ $backend1->expects($this->once())
+ ->method('removeFromGroup')
+ ->with('user1', 'group1');
+
+ $backend2->expects($this->once())
+ ->method('inGroup')
+ ->with('user1', 'group1')
+ ->willReturn(true);
+ $backend2->expects($this->any())
+ ->method('implementsActions')
+ ->willReturn(true);
+
+ $backend2->expects($this->once())
+ ->method('removeFromGroup')
+ ->with('user1', 'group1');
+
+ $group->removeUser($this->newUser('user1', $userBackend));
+ }
+
+ public function testSearchUsers(): void {
+ $backend = $this->getMockBuilder(\OC\Group\Database::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userManager = $this->getUserManager();
+ $group = new \OC\Group\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)]);
+
+ $users = $group->searchUsers('2');
+
+ $this->assertEquals(1, count($users));
+ $user2 = reset($users);
+ $this->assertEquals('user2', $user2->getUID());
+ }
+
+ public function testSearchUsersMultipleBackends(): void {
+ $backend1 = $this->getMockBuilder(\OC\Group\Database::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $backend2 = $this->getMockBuilder(\OC\Group\Database::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userManager = $this->getUserManager();
+ $group = new \OC\Group\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)]);
+ $backend2->expects($this->once())
+ ->method('searchInGroup')
+ ->with('group1', '2')
+ ->willReturn(['user2' => new \OC\User\User('user2', null, $this->dispatcher)]);
+
+ $users = $group->searchUsers('2');
+
+ $this->assertEquals(1, count($users));
+ $user2 = reset($users);
+ $this->assertEquals('user2', $user2->getUID());
+ }
+
+ public function testSearchUsersLimitAndOffset(): void {
+ $backend = $this->getMockBuilder(\OC\Group\Database::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userManager = $this->getUserManager();
+ $group = new \OC\Group\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)]);
+
+ $users = $group->searchUsers('user', 1, 1);
+
+ $this->assertEquals(1, count($users));
+ $user2 = reset($users);
+ $this->assertEquals('user2', $user2->getUID());
+ }
+
+ public function testSearchUsersMultipleBackendsLimitAndOffset(): void {
+ $backend1 = $this->getMockBuilder(\OC\Group\Database::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $backend2 = $this->getMockBuilder(\OC\Group\Database::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userManager = $this->getUserManager();
+ $group = new \OC\Group\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)]);
+ $backend2->expects($this->once())
+ ->method('searchInGroup')
+ ->with('group1', 'user', 2, 1)
+ ->willReturn(['user1' => new \OC\User\User('user1', null, $this->dispatcher)]);
+
+ $users = $group->searchUsers('user', 2, 1);
+
+ $this->assertEquals(2, count($users));
+ $user2 = reset($users);
+ $user1 = next($users);
+ $this->assertEquals('user2', $user2->getUID());
+ $this->assertEquals('user1', $user1->getUID());
+ }
+
+ public function testCountUsers(): void {
+ $backend1 = $this->getMockBuilder(\OC\Group\Database::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userManager = $this->getUserManager();
+ $group = new \OC\Group\Group('group1', [$backend1], $this->dispatcher, $userManager);
+
+ $backend1->expects($this->once())
+ ->method('countUsersInGroup')
+ ->with('group1', '2')
+ ->willReturn(3);
+
+ $backend1->expects($this->any())
+ ->method('implementsActions')
+ ->willReturn(true);
+
+ $users = $group->count('2');
+
+ $this->assertSame(3, $users);
+ }
+
+ public function testCountUsersMultipleBackends(): void {
+ $backend1 = $this->getMockBuilder(\OC\Group\Database::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $backend2 = $this->getMockBuilder(\OC\Group\Database::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userManager = $this->getUserManager();
+ $group = new \OC\Group\Group('group1', [$backend1, $backend2], $this->dispatcher, $userManager);
+
+ $backend1->expects($this->once())
+ ->method('countUsersInGroup')
+ ->with('group1', '2')
+ ->willReturn(3);
+ $backend1->expects($this->any())
+ ->method('implementsActions')
+ ->willReturn(true);
+
+ $backend2->expects($this->once())
+ ->method('countUsersInGroup')
+ ->with('group1', '2')
+ ->willReturn(4);
+ $backend2->expects($this->any())
+ ->method('implementsActions')
+ ->willReturn(true);
+
+ $users = $group->count('2');
+
+ $this->assertSame(7, $users);
+ }
+
+ public function testCountUsersNoMethod(): void {
+ $backend1 = $this->getMockBuilder(\OC\Group\Database::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userManager = $this->getUserManager();
+ $group = new \OC\Group\Group('group1', [$backend1], $this->dispatcher, $userManager);
+
+ $backend1->expects($this->never())
+ ->method('countUsersInGroup');
+ $backend1->expects($this->any())
+ ->method('implementsActions')
+ ->willReturn(false);
+
+ $users = $group->count('2');
+
+ $this->assertSame(false, $users);
+ }
+
+ public function testDelete(): void {
+ $backend = $this->getMockBuilder(\OC\Group\Database::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userManager = $this->getUserManager();
+ $group = new \OC\Group\Group('group1', [$backend], $this->dispatcher, $userManager);
+
+ $backend->expects($this->once())
+ ->method('deleteGroup')
+ ->with('group1');
+ $backend->expects($this->any())
+ ->method('implementsActions')
+ ->willReturn(true);
+
+ $group->delete();
+ }
+}
diff --git a/tests/lib/Group/ManagerTest.php b/tests/lib/Group/ManagerTest.php
index d652d5ec96c..0f8d7a5ecc3 100644
--- a/tests/lib/Group/ManagerTest.php
+++ b/tests/lib/Group/ManagerTest.php
@@ -99,7 +99,7 @@ class ManagerTest extends TestCase {
return $backend;
}
- public function testGet() {
+ public function testGet(): void {
/**
* @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend
*/
@@ -117,13 +117,13 @@ class ManagerTest extends TestCase {
$this->assertEquals('group1', $group->getGID());
}
- public function testGetNoBackend() {
+ public function testGetNoBackend(): void {
$manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache, $this->remoteIpAddress);
$this->assertNull($manager->get('group1'));
}
- public function testGetNotExists() {
+ public function testGetNotExists(): void {
/**
* @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend
*/
@@ -139,7 +139,7 @@ class ManagerTest extends TestCase {
$this->assertNull($manager->get('group1'));
}
- public function testGetDeleted() {
+ public function testGetDeleted(): void {
$backend = new \Test\Util\Group\Dummy();
$backend->createGroup('group1');
@@ -151,7 +151,7 @@ class ManagerTest extends TestCase {
$this->assertNull($manager->get('group1'));
}
- public function testGetMultipleBackends() {
+ public function testGetMultipleBackends(): void {
/**
* @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend1
*/
@@ -179,7 +179,7 @@ class ManagerTest extends TestCase {
$this->assertEquals('group1', $group->getGID());
}
- public function testCreate() {
+ public function testCreate(): void {
/** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Group\Backend $backend */
$backendGroupCreated = false;
$backend = $this->getTestBackend();
@@ -203,7 +203,7 @@ class ManagerTest extends TestCase {
$this->assertEquals('group1', $group->getGID());
}
- public function testCreateFailure() {
+ public function testCreateFailure(): void {
/** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Group\Backend $backend */
$backendGroupCreated = false;
$backend = $this->getTestBackend(
@@ -232,7 +232,7 @@ class ManagerTest extends TestCase {
$this->assertEquals(null, $group);
}
- public function testCreateTooLong() {
+ public function testCreateTooLong(): void {
/** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Group\Backend $backend */
$backendGroupCreated = false;
$backend = $this->getTestBackend(
@@ -256,7 +256,7 @@ class ManagerTest extends TestCase {
$group = $manager->createGroup($groupName);
}
- public function testCreateExists() {
+ public function testCreateExists(): void {
/** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Group\Backend $backend */
$backend = $this->getTestBackend();
$backend->expects($this->any())
@@ -273,7 +273,7 @@ class ManagerTest extends TestCase {
$this->assertEquals('group1', $group->getGID());
}
- public function testSearch() {
+ public function testSearch(): void {
/**
* @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend
*/
@@ -296,7 +296,7 @@ class ManagerTest extends TestCase {
$this->assertEquals('group1', $group1->getGID());
}
- public function testSearchMultipleBackends() {
+ public function testSearchMultipleBackends(): void {
/**
* @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend1
*/
@@ -333,7 +333,7 @@ class ManagerTest extends TestCase {
$this->assertEquals('group12', $group12->getGID());
}
- public function testSearchMultipleBackendsLimitAndOffset() {
+ public function testSearchMultipleBackendsLimitAndOffset(): void {
/**
* @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend1
*/
@@ -370,7 +370,7 @@ class ManagerTest extends TestCase {
$this->assertEquals('group12', $group12->getGID());
}
- public function testSearchResultExistsButGroupDoesNot() {
+ public function testSearchResultExistsButGroupDoesNot(): void {
/** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Group\Backend $backend */
$backend = $this->createMock(Database::class);
$backend->expects($this->once())
@@ -394,7 +394,7 @@ class ManagerTest extends TestCase {
$this->assertEmpty($groups);
}
- public function testGetUserGroups() {
+ public function testGetUserGroups(): void {
/**
* @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend
*/
@@ -417,7 +417,7 @@ class ManagerTest extends TestCase {
$this->assertEquals('group1', $group1->getGID());
}
- public function testGetUserGroupIds() {
+ public function testGetUserGroupIds(): void {
/**
* @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend
*/
@@ -442,7 +442,7 @@ class ManagerTest extends TestCase {
}
}
- public function testGetUserGroupsWithDeletedGroup() {
+ public function testGetUserGroupsWithDeletedGroup(): void {
/**
* @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend
*/
@@ -469,7 +469,7 @@ class ManagerTest extends TestCase {
$this->assertEmpty($groups);
}
- public function testInGroup() {
+ public function testInGroup(): void {
/**
* @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend
*/
@@ -488,7 +488,7 @@ class ManagerTest extends TestCase {
$this->assertTrue($manager->isInGroup('user1', 'group1'));
}
- public function testIsAdmin() {
+ public function testIsAdmin(): void {
/**
* @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend
*/
@@ -507,7 +507,7 @@ class ManagerTest extends TestCase {
$this->assertTrue($manager->isAdmin('user1'));
}
- public function testNotAdmin() {
+ public function testNotAdmin(): void {
/**
* @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend
*/
@@ -526,7 +526,7 @@ class ManagerTest extends TestCase {
$this->assertFalse($manager->isAdmin('user1'));
}
- public function testGetUserGroupsMultipleBackends() {
+ public function testGetUserGroupsMultipleBackends(): void {
/**
* @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend1
*/
@@ -563,7 +563,7 @@ class ManagerTest extends TestCase {
$this->assertEquals('group2', $group2->getGID());
}
- public function testDisplayNamesInGroupWithOneUserBackend() {
+ public function testDisplayNamesInGroupWithOneUserBackend(): void {
/**
* @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend
*/
@@ -621,7 +621,7 @@ class ManagerTest extends TestCase {
$this->assertTrue(isset($users['user33']));
}
- public function testDisplayNamesInGroupWithOneUserBackendWithLimitSpecified() {
+ public function testDisplayNamesInGroupWithOneUserBackendWithLimitSpecified(): void {
/**
* @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend
*/
@@ -682,7 +682,7 @@ class ManagerTest extends TestCase {
$this->assertFalse(isset($users['user333']));
}
- public function testDisplayNamesInGroupWithOneUserBackendWithLimitAndOffsetSpecified() {
+ public function testDisplayNamesInGroupWithOneUserBackendWithLimitAndOffsetSpecified(): void {
/**
* @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend
*/
@@ -746,7 +746,7 @@ class ManagerTest extends TestCase {
$this->assertTrue(isset($users['user333']));
}
- public function testDisplayNamesInGroupWithOneUserBackendAndSearchEmpty() {
+ public function testDisplayNamesInGroupWithOneUserBackendAndSearchEmpty(): void {
/**
* @var \PHPUnit\Framework\MockObject\MockObject|\OC\Group\Backend $backend
*/
@@ -774,7 +774,7 @@ class ManagerTest extends TestCase {
$this->assertTrue(isset($users['user33']));
}
- public function testDisplayNamesInGroupWithOneUserBackendAndSearchEmptyAndLimitSpecified() {
+ public function testDisplayNamesInGroupWithOneUserBackendAndSearchEmptyAndLimitSpecified(): void {
/**
* @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend
*/
@@ -802,7 +802,7 @@ class ManagerTest extends TestCase {
$this->assertFalse(isset($users['user33']));
}
- public function testDisplayNamesInGroupWithOneUserBackendAndSearchEmptyAndLimitAndOffsetSpecified() {
+ public function testDisplayNamesInGroupWithOneUserBackendAndSearchEmptyAndLimitAndOffsetSpecified(): void {
/**
* @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend
*/
@@ -830,7 +830,7 @@ class ManagerTest extends TestCase {
$this->assertTrue(isset($users['user33']));
}
- public function testGetUserGroupsWithAddUser() {
+ public function testGetUserGroupsWithAddUser(): void {
/**
* @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend
*/
@@ -867,7 +867,7 @@ class ManagerTest extends TestCase {
$this->assertEquals('group1', $group1->getGID());
}
- public function testGetUserGroupsWithRemoveUser() {
+ public function testGetUserGroupsWithRemoveUser(): void {
/**
* @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend
*/
@@ -910,7 +910,7 @@ class ManagerTest extends TestCase {
$this->assertEquals($expectedGroups, $groups);
}
- public function testGetUserIdGroups() {
+ public function testGetUserIdGroups(): void {
/**
* @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend
*/
@@ -927,7 +927,7 @@ class ManagerTest extends TestCase {
$this->assertEquals([], $groups);
}
- public function testGroupDisplayName() {
+ public function testGroupDisplayName(): void {
/**
* @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend
*/
diff --git a/tests/lib/Group/MetaDataTest.php b/tests/lib/Group/MetaDataTest.php
index bd91203a808..e42954a529d 100644
--- a/tests/lib/Group/MetaDataTest.php
+++ b/tests/lib/Group/MetaDataTest.php
@@ -59,7 +59,7 @@ class MetaDataTest extends \Test\TestCase {
}
- public function testGet() {
+ public function testGet(): void {
$group = $this->getGroupMock();
$groups = array_fill(0, 3, $group);
@@ -78,7 +78,7 @@ class MetaDataTest extends \Test\TestCase {
$this->assertSame(0, $ordinaryGroups[0]['usercount']);
}
- public function testGetWithSorting() {
+ public function testGetWithSorting(): void {
$this->groupMetadata->setSorting(1);
$group = $this->getGroupMock(3);
$groups = array_fill(0, 3, $group);
@@ -97,7 +97,7 @@ class MetaDataTest extends \Test\TestCase {
$this->assertSame(5, $ordinaryGroups[0]['usercount']);
}
- public function testGetWithCache() {
+ public function testGetWithCache(): void {
$group = $this->getGroupMock();
$groups = array_fill(0, 3, $group);
@@ -115,7 +115,7 @@ class MetaDataTest extends \Test\TestCase {
//get() does not need to be tested with search parameters, because they are
//solely and only passed to GroupManager and Group.
- public function testGetGroupsAsAdmin() {
+ public function testGetGroupsAsAdmin(): void {
$this->groupManager
->expects($this->once())
->method('search')
diff --git a/tests/lib/HelperStorageTest.php b/tests/lib/HelperStorageTest.php
index ddf32d94724..4d5002de3ab 100644
--- a/tests/lib/HelperStorageTest.php
+++ b/tests/lib/HelperStorageTest.php
@@ -84,7 +84,7 @@ class HelperStorageTest extends \Test\TestCase {
/**
* Test getting the storage info
*/
- public function testGetStorageInfo() {
+ public function testGetStorageInfo(): void {
$homeStorage = $this->getStorageMock(12);
\OC\Files\Filesystem::mount($homeStorage, [], '/' . $this->user . '/files');
$homeStorage->file_put_contents('test.txt', '01234');
@@ -111,7 +111,7 @@ class HelperStorageTest extends \Test\TestCase {
/**
* Test getting the storage info, ignoring extra mount points
*/
- public function testGetStorageInfoExcludingExtStorage() {
+ public function testGetStorageInfoExcludingExtStorage(): void {
$homeStorage = $this->getStorageMock(12);
\OC\Files\Filesystem::mount($homeStorage, [], '/' . $this->user . '/files');
$homeStorage->file_put_contents('test.txt', '01234');
@@ -133,7 +133,7 @@ class HelperStorageTest extends \Test\TestCase {
/**
* Test getting the storage info, including extra mount points
*/
- public function testGetStorageInfoIncludingExtStorage() {
+ public function testGetStorageInfoIncludingExtStorage(): void {
$homeStorage = new \OC\Files\Storage\Temporary([]);
\OC\Files\Filesystem::mount($homeStorage, [], '/' . $this->user . '/files');
$homeStorage->file_put_contents('test.txt', '01234');
@@ -162,7 +162,7 @@ class HelperStorageTest extends \Test\TestCase {
* when user has no quota set, even when quota ext storage option
* was set
*/
- public function testGetStorageInfoIncludingExtStorageWithNoUserQuota() {
+ public function testGetStorageInfoIncludingExtStorageWithNoUserQuota(): void {
$homeStorage = $this->getStorageMock(12);
\OC\Files\Filesystem::mount($homeStorage, [], '/' . $this->user . '/files');
$homeStorage->file_put_contents('test.txt', '01234');
@@ -186,7 +186,7 @@ class HelperStorageTest extends \Test\TestCase {
/**
* Test getting the storage info with quota enabled
*/
- public function testGetStorageInfoWithQuota() {
+ public function testGetStorageInfoWithQuota(): void {
$homeStorage = $this->getStorageMock(12);
$homeStorage->file_put_contents('test.txt', '01234');
$homeStorage = new \OC\Files\Storage\Wrapper\Quota(
@@ -206,7 +206,7 @@ class HelperStorageTest extends \Test\TestCase {
/**
* Test getting the storage info when data exceeds quota
*/
- public function testGetStorageInfoWhenSizeExceedsQuota() {
+ public function testGetStorageInfoWhenSizeExceedsQuota(): void {
$homeStorage = $this->getStorageMock(12);
$homeStorage->file_put_contents('test.txt', '0123456789');
$homeStorage = new \OC\Files\Storage\Wrapper\Quota(
@@ -228,7 +228,7 @@ class HelperStorageTest extends \Test\TestCase {
* Test getting the storage info when the remaining
* free storage space is less than the quota
*/
- public function testGetStorageInfoWhenFreeSpaceLessThanQuota() {
+ public function testGetStorageInfoWhenFreeSpaceLessThanQuota(): void {
$homeStorage = $this->getStorageMock(12);
$homeStorage->file_put_contents('test.txt', '01234');
$homeStorage = new \OC\Files\Storage\Wrapper\Quota(
diff --git a/tests/lib/Hooks/BasicEmitterTest.php b/tests/lib/Hooks/BasicEmitterTest.php
index 262d9bfb0fd..b9f86865cea 100644
--- a/tests/lib/Hooks/BasicEmitterTest.php
+++ b/tests/lib/Hooks/BasicEmitterTest.php
@@ -50,7 +50,7 @@ class BasicEmitterTest extends \Test\TestCase {
}
- public function testAnonymousFunction() {
+ public function testAnonymousFunction(): void {
$this->expectException(\Test\Hooks\EmittedException::class);
$this->emitter->listen('Test', 'test', function () {
@@ -60,7 +60,7 @@ class BasicEmitterTest extends \Test\TestCase {
}
- public function testStaticCallback() {
+ public function testStaticCallback(): void {
$this->expectException(\Test\Hooks\EmittedException::class);
$this->emitter->listen('Test', 'test', [\Test\Hooks\BasicEmitterTest::class, 'staticCallBack']);
@@ -68,14 +68,14 @@ class BasicEmitterTest extends \Test\TestCase {
}
- public function testNonStaticCallback() {
+ public function testNonStaticCallback(): void {
$this->expectException(\Test\Hooks\EmittedException::class);
$this->emitter->listen('Test', 'test', [$this, 'nonStaticCallBack']);
$this->emitter->emitEvent('Test', 'test');
}
- public function testOnlyCallOnce() {
+ public function testOnlyCallOnce(): void {
$count = 0;
$listener = function () use (&$count) {
$count++;
@@ -86,7 +86,7 @@ class BasicEmitterTest extends \Test\TestCase {
$this->assertEquals(1, $count, 'Listener called an invalid number of times (' . $count . ') expected 1');
}
- public function testDifferentMethods() {
+ public function testDifferentMethods(): void {
$count = 0;
$listener = function () use (&$count) {
$count++;
@@ -98,7 +98,7 @@ class BasicEmitterTest extends \Test\TestCase {
$this->assertEquals(2, $count, 'Listener called an invalid number of times (' . $count . ') expected 2');
}
- public function testDifferentScopes() {
+ public function testDifferentScopes(): void {
$count = 0;
$listener = function () use (&$count) {
$count++;
@@ -110,7 +110,7 @@ class BasicEmitterTest extends \Test\TestCase {
$this->assertEquals(2, $count, 'Listener called an invalid number of times (' . $count . ') expected 2');
}
- public function testDifferentCallbacks() {
+ public function testDifferentCallbacks(): void {
$count = 0;
$listener1 = function () use (&$count) {
$count++;
@@ -125,7 +125,7 @@ class BasicEmitterTest extends \Test\TestCase {
}
- public function testArguments() {
+ public function testArguments(): void {
$this->expectException(\Test\Hooks\EmittedException::class);
$this->emitter->listen('Test', 'test', function ($foo, $bar) {
@@ -137,7 +137,7 @@ class BasicEmitterTest extends \Test\TestCase {
}
- public function testNamedArguments() {
+ public function testNamedArguments(): void {
$this->expectException(\Test\Hooks\EmittedException::class);
$this->emitter->listen('Test', 'test', function ($foo, $bar) {
@@ -148,7 +148,7 @@ class BasicEmitterTest extends \Test\TestCase {
$this->emitter->emitEvent('Test', 'test', ['foo' => 'foo', 'bar' => 'bar']);
}
- public function testRemoveAllSpecified() {
+ public function testRemoveAllSpecified(): void {
$listener = function () {
throw new EmittedException;
};
@@ -159,7 +159,7 @@ class BasicEmitterTest extends \Test\TestCase {
$this->addToAssertionCount(1);
}
- public function testRemoveWildcardListener() {
+ public function testRemoveWildcardListener(): void {
$listener1 = function () {
throw new EmittedException;
};
@@ -174,7 +174,7 @@ class BasicEmitterTest extends \Test\TestCase {
$this->addToAssertionCount(1);
}
- public function testRemoveWildcardMethod() {
+ public function testRemoveWildcardMethod(): void {
$listener = function () {
throw new EmittedException;
};
@@ -187,7 +187,7 @@ class BasicEmitterTest extends \Test\TestCase {
$this->addToAssertionCount(1);
}
- public function testRemoveWildcardScope() {
+ public function testRemoveWildcardScope(): void {
$listener = function () {
throw new EmittedException;
};
@@ -200,7 +200,7 @@ class BasicEmitterTest extends \Test\TestCase {
$this->addToAssertionCount(1);
}
- public function testRemoveWildcardScopeAndMethod() {
+ public function testRemoveWildcardScopeAndMethod(): void {
$listener = function () {
throw new EmittedException;
};
@@ -216,7 +216,7 @@ class BasicEmitterTest extends \Test\TestCase {
}
- public function testRemoveKeepOtherCallback() {
+ public function testRemoveKeepOtherCallback(): void {
$this->expectException(\Test\Hooks\EmittedException::class);
$listener1 = function () {
@@ -234,7 +234,7 @@ class BasicEmitterTest extends \Test\TestCase {
}
- public function testRemoveKeepOtherMethod() {
+ public function testRemoveKeepOtherMethod(): void {
$this->expectException(\Test\Hooks\EmittedException::class);
$listener = function () {
@@ -249,7 +249,7 @@ class BasicEmitterTest extends \Test\TestCase {
}
- public function testRemoveKeepOtherScope() {
+ public function testRemoveKeepOtherScope(): void {
$this->expectException(\Test\Hooks\EmittedException::class);
$listener = function () {
@@ -264,7 +264,7 @@ class BasicEmitterTest extends \Test\TestCase {
}
- public function testRemoveNonExistingName() {
+ public function testRemoveNonExistingName(): void {
$this->expectException(\Test\Hooks\EmittedException::class);
$listener = function () {
diff --git a/tests/lib/Http/Client/DnsPinMiddlewareTest.php b/tests/lib/Http/Client/DnsPinMiddlewareTest.php
index d265ce3e71c..9d71af15c5d 100644
--- a/tests/lib/Http/Client/DnsPinMiddlewareTest.php
+++ b/tests/lib/Http/Client/DnsPinMiddlewareTest.php
@@ -42,7 +42,7 @@ class DnsPinMiddlewareTest extends TestCase {
->getMock();
}
- public function testPopulateDnsCacheIPv4() {
+ public function testPopulateDnsCacheIPv4(): void {
$mockHandler = new MockHandler([
static function (RequestInterface $request, array $options) {
self::arrayHasKey('curl', $options);
@@ -135,7 +135,7 @@ class DnsPinMiddlewareTest extends TestCase {
);
}
- public function testPopulateDnsCacheIPv6() {
+ public function testPopulateDnsCacheIPv6(): void {
$mockHandler = new MockHandler([
static function (RequestInterface $request, array $options) {
self::arrayHasKey('curl', $options);
@@ -250,7 +250,7 @@ class DnsPinMiddlewareTest extends TestCase {
);
}
- public function testAllowLocalAddress() {
+ public function testAllowLocalAddress(): void {
$mockHandler = new MockHandler([
static function (RequestInterface $request, array $options) {
self::assertArrayNotHasKey('curl', $options);
@@ -268,7 +268,7 @@ class DnsPinMiddlewareTest extends TestCase {
);
}
- public function testRejectIPv4() {
+ public function testRejectIPv4(): void {
$this->expectException(LocalServerException::class);
$this->expectExceptionMessage('violates local access rules');
@@ -315,7 +315,7 @@ class DnsPinMiddlewareTest extends TestCase {
);
}
- public function testRejectIPv6() {
+ public function testRejectIPv6(): void {
$this->expectException(LocalServerException::class);
$this->expectExceptionMessage('violates local access rules');
@@ -362,7 +362,7 @@ class DnsPinMiddlewareTest extends TestCase {
);
}
- public function testRejectCanonicalName() {
+ public function testRejectCanonicalName(): void {
$this->expectException(LocalServerException::class);
$this->expectExceptionMessage('violates local access rules');
@@ -452,7 +452,7 @@ class DnsPinMiddlewareTest extends TestCase {
);
}
- public function testRejectFaultyResponse() {
+ public function testRejectFaultyResponse(): void {
$this->expectException(LocalServerException::class);
$this->expectExceptionMessage('No DNS record found for www.example.com');
@@ -478,7 +478,7 @@ class DnsPinMiddlewareTest extends TestCase {
);
}
- public function testIgnoreSubdomainForSoaQuery() {
+ public function testIgnoreSubdomainForSoaQuery(): void {
$mockHandler = new MockHandler([
static function (RequestInterface $request, array $options) {
// The handler should not be called
diff --git a/tests/lib/Http/Client/NegativeDnsCacheTest.php b/tests/lib/Http/Client/NegativeDnsCacheTest.php
index bcde25ddf85..ba91e95a906 100644
--- a/tests/lib/Http/Client/NegativeDnsCacheTest.php
+++ b/tests/lib/Http/Client/NegativeDnsCacheTest.php
@@ -43,7 +43,7 @@ class NegativeDnsCacheTest extends \Test\TestCase {
$this->negativeDnsCache->setNegativeCacheForDnsType('www.example.com', DNS_A, 3600);
}
- public function testIsNegativeCached() {
+ public function testIsNegativeCached(): void {
$this->cache
->expects($this->once())
->method('hasKey')
diff --git a/tests/lib/Http/Client/ResponseTest.php b/tests/lib/Http/Client/ResponseTest.php
index c0d9770e2fb..291dc287148 100644
--- a/tests/lib/Http/Client/ResponseTest.php
+++ b/tests/lib/Http/Client/ResponseTest.php
@@ -23,22 +23,22 @@ class ResponseTest extends \Test\TestCase {
$this->guzzleResponse = new GuzzleResponse(418);
}
- public function testGetBody() {
+ public function testGetBody(): void {
$response = new Response($this->guzzleResponse->withBody(Utils::streamFor('MyResponse')));
$this->assertSame('MyResponse', $response->getBody());
}
- public function testGetStatusCode() {
+ public function testGetStatusCode(): void {
$response = new Response($this->guzzleResponse);
$this->assertSame(418, $response->getStatusCode());
}
- public function testGetHeader() {
+ public function testGetHeader(): void {
$response = new Response($this->guzzleResponse->withHeader('bar', 'foo'));
$this->assertSame('foo', $response->getHeader('bar'));
}
- public function testGetHeaders() {
+ public function testGetHeaders(): void {
$response = new Response($this->guzzleResponse
->withHeader('bar', 'foo')
->withHeader('x-awesome', 'yes')
diff --git a/tests/lib/ImageTest.php b/tests/lib/ImageTest.php
index 5cdfbdb36cf..4c56623cbf8 100644
--- a/tests/lib/ImageTest.php
+++ b/tests/lib/ImageTest.php
@@ -20,7 +20,7 @@ class ImageTest extends \Test\TestCase {
parent::tearDownAfterClass();
}
- public function testConstructDestruct() {
+ public function testConstructDestruct(): void {
$img = new Image();
$img->loadFromFile(OC::$SERVERROOT.'/tests/data/testimage.png');
$this->assertInstanceOf(\OC\Image::class, $img);
@@ -47,7 +47,7 @@ class ImageTest extends \Test\TestCase {
unset($img);
}
- public function testValid() {
+ public function testValid(): void {
$img = new Image();
$img->loadFromFile(OC::$SERVERROOT.'/tests/data/testimage.png');
$this->assertTrue($img->valid());
@@ -61,7 +61,7 @@ class ImageTest extends \Test\TestCase {
$this->assertFalse($img->valid());
}
- public function testMimeType() {
+ public function testMimeType(): void {
$img = new Image();
$img->loadFromFile(OC::$SERVERROOT.'/tests/data/testimage.png');
$this->assertEquals('image/png', $img->mimeType());
@@ -78,7 +78,7 @@ class ImageTest extends \Test\TestCase {
$this->assertEquals('image/gif', $img->mimeType());
}
- public function testWidth() {
+ public function testWidth(): void {
$img = new Image();
$img->loadFromFile(OC::$SERVERROOT.'/tests/data/testimage.png');
$this->assertEquals(128, $img->width());
@@ -95,7 +95,7 @@ class ImageTest extends \Test\TestCase {
$this->assertEquals(-1, $img->width());
}
- public function testHeight() {
+ public function testHeight(): void {
$img = new Image();
$img->loadFromFile(OC::$SERVERROOT.'/tests/data/testimage.png');
$this->assertEquals(128, $img->height());
@@ -112,7 +112,7 @@ class ImageTest extends \Test\TestCase {
$this->assertEquals(-1, $img->height());
}
- public function testSave() {
+ public function testSave(): void {
$img = new Image();
$img->loadFromFile(OC::$SERVERROOT.'/tests/data/testimage.png');
$img->resize(16);
@@ -126,7 +126,7 @@ class ImageTest extends \Test\TestCase {
$this->assertEquals(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage2.jpg'), $img->data());
}
- public function testData() {
+ public function testData(): void {
$img = new Image();
$img->loadFromFile(OC::$SERVERROOT.'/tests/data/testimage.png');
$raw = imagecreatefromstring(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.png'));
@@ -166,7 +166,7 @@ class ImageTest extends \Test\TestCase {
$this->assertEquals($expected, $img->data());
}
- public function testDataNoResource() {
+ public function testDataNoResource(): void {
$img = new Image();
$this->assertNull($img->data());
}
@@ -174,7 +174,7 @@ class ImageTest extends \Test\TestCase {
/**
* @depends testData
*/
- public function testToString() {
+ public function testToString(): void {
$img = new Image();
$img->loadFromFile(OC::$SERVERROOT.'/tests/data/testimage.png');
$expected = base64_encode($img->data());
@@ -191,7 +191,7 @@ class ImageTest extends \Test\TestCase {
$this->assertEquals($expected, (string)$img);
}
- public function testResize() {
+ public function testResize(): void {
$img = new Image();
$img->loadFromFile(OC::$SERVERROOT.'/tests/data/testimage.png');
$this->assertTrue($img->resize(32));
@@ -211,7 +211,7 @@ class ImageTest extends \Test\TestCase {
$this->assertEquals(100, $img->height());
}
- public function testPreciseResize() {
+ public function testPreciseResize(): void {
$img = new Image();
$img->loadFromFile(OC::$SERVERROOT.'/tests/data/testimage.png');
$this->assertTrue($img->preciseResize(128, 512));
@@ -231,7 +231,7 @@ class ImageTest extends \Test\TestCase {
$this->assertEquals(1337, $img->height());
}
- public function testCenterCrop() {
+ public function testCenterCrop(): void {
$img = new Image();
$img->loadFromFile(OC::$SERVERROOT.'/tests/data/testimage.png');
$img->centerCrop();
@@ -251,7 +251,7 @@ class ImageTest extends \Test\TestCase {
$this->assertEquals(512, $img->height());
}
- public function testCrop() {
+ public function testCrop(): void {
$img = new Image();
$img->loadFromFile(OC::$SERVERROOT.'/tests/data/testimage.png');
$this->assertTrue($img->crop(0, 0, 50, 20));
@@ -286,7 +286,7 @@ class ImageTest extends \Test\TestCase {
* @param int[] $asked
* @param int[] $expected
*/
- public function testFitIn($filename, $asked, $expected) {
+ public function testFitIn($filename, $asked, $expected): void {
$img = new Image();
$img->loadFromFile(OC::$SERVERROOT . '/tests/data/' . $filename);
$this->assertTrue($img->fitIn($asked[0], $asked[1]));
@@ -309,7 +309,7 @@ class ImageTest extends \Test\TestCase {
*
* @param string $filename
*/
- public function testScaleDownToFitWhenSmallerAlready($filename) {
+ public function testScaleDownToFitWhenSmallerAlready($filename): void {
$img = new Image();
$img->loadFromFile(OC::$SERVERROOT.'/tests/data/' . $filename);
$currentWidth = $img->width();
@@ -342,7 +342,7 @@ class ImageTest extends \Test\TestCase {
* @param int[] $asked
* @param int[] $expected
*/
- public function testScaleDownWhenBigger($filename, $asked, $expected) {
+ public function testScaleDownWhenBigger($filename, $asked, $expected): void {
$img = new Image();
$img->loadFromFile(OC::$SERVERROOT.'/tests/data/' . $filename);
//$this->assertTrue($img->scaleDownToFit($asked[0], $asked[1]));
@@ -362,7 +362,7 @@ class ImageTest extends \Test\TestCase {
/**
* @dataProvider convertDataProvider
*/
- public function testConvert($mimeType) {
+ public function testConvert($mimeType): void {
$img = new Image();
$img->loadFromFile(OC::$SERVERROOT.'/tests/data/testimage.png');
$tempFile = tempnam(sys_get_temp_dir(), 'img-test');
@@ -371,13 +371,13 @@ class ImageTest extends \Test\TestCase {
$this->assertEquals($mimeType, image_type_to_mime_type(exif_imagetype($tempFile)));
}
- public function testMemoryLimitFromFile() {
+ public function testMemoryLimitFromFile(): void {
$img = new Image();
$img->loadFromFile(OC::$SERVERROOT.'/tests/data/testimage-badheader.jpg');
$this->assertFalse($img->valid());
}
- public function testMemoryLimitFromData() {
+ public function testMemoryLimitFromData(): void {
$data = file_get_contents(OC::$SERVERROOT.'/tests/data/testimage-badheader.jpg');
$img = new Image();
$img->loadFromData($data);
diff --git a/tests/lib/InfoXmlTest.php b/tests/lib/InfoXmlTest.php
index 1527e363bd7..461a2ecafa8 100644
--- a/tests/lib/InfoXmlTest.php
+++ b/tests/lib/InfoXmlTest.php
@@ -52,7 +52,7 @@ class InfoXmlTest extends TestCase {
*
* @param string $app
*/
- public function testClasses($app) {
+ public function testClasses($app): void {
$appInfo = $this->appManager->getAppInfo($app);
$appPath = $this->appManager->getAppPath($app);
\OC_App::registerAutoloading($app, $appPath);
diff --git a/tests/lib/InstallerTest.php b/tests/lib/InstallerTest.php
index 1fd48ea4fc9..d27ca6e2159 100644
--- a/tests/lib/InstallerTest.php
+++ b/tests/lib/InstallerTest.php
@@ -86,7 +86,7 @@ class InstallerTest extends TestCase {
parent::tearDown();
}
- public function testInstallApp() {
+ public function testInstallApp(): void {
// Read the current version of the app to check for bug #2572
\OCP\Server::get(IAppManager::class)->getAppVersion('testapp', true);
@@ -149,7 +149,7 @@ class InstallerTest extends TestCase {
* @param array $appArray
* @param string|bool $updateAvailable
*/
- public function testIsUpdateAvailable(array $appArray, $updateAvailable) {
+ public function testIsUpdateAvailable(array $appArray, $updateAvailable): void {
$this->appFetcher
->expects($this->once())
->method('get')
@@ -161,7 +161,7 @@ class InstallerTest extends TestCase {
}
- public function testDownloadAppWithRevokedCertificate() {
+ public function testDownloadAppWithRevokedCertificate(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Certificate "4112" has been revoked');
@@ -205,7 +205,7 @@ gLgK8d8sKL60JMmKHN3boHrsThKBVA==
}
- public function testDownloadAppWithNotNextcloudCertificate() {
+ public function testDownloadAppWithNotNextcloudCertificate(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('App with id news has a certificate not issued by a trusted Code Signing Authority');
@@ -248,7 +248,7 @@ YSu356M=
}
- public function testDownloadAppWithDifferentCN() {
+ public function testDownloadAppWithDifferentCN(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('App with id news has a cert issued to passman');
@@ -291,7 +291,7 @@ u/spPSSVhaun5BA1FlphB2TkgnzlCmxJa63nFY045e/Jq+IKMcqqZl/092gbI2EQ
}
- public function testDownloadAppWithInvalidSignature() {
+ public function testDownloadAppWithInvalidSignature(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('App with id passman has invalid signature');
@@ -359,7 +359,7 @@ u/spPSSVhaun5BA1FlphB2TkgnzlCmxJa63nFY045e/Jq+IKMcqqZl/092gbI2EQ
}
- public function testDownloadAppWithMoreThanOneFolderDownloaded() {
+ public function testDownloadAppWithMoreThanOneFolderDownloaded(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Extracted app testapp has more than 1 folder');
@@ -443,7 +443,7 @@ YwDVP+QmNRzx72jtqAN/Kc3CvQ9nkgYhU65B95aX0xA=',
}
- public function testDownloadAppWithMismatchingIdentifier() {
+ public function testDownloadAppWithMismatchingIdentifier(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('App for id testapp has a wrong app ID in info.xml: testapp1');
@@ -525,7 +525,7 @@ YwDVP+QmNRzx72jtqAN/Kc3CvQ9nkgYhU65B95aX0xA=',
$installer->downloadApp('testapp');
}
- public function testDownloadAppSuccessful() {
+ public function testDownloadAppSuccessful(): void {
$appArray = [
[
'id' => 'testapp',
@@ -608,7 +608,7 @@ MPLX6f5V9tCJtlH6ztmEcDROfvuVc0U3rEhqx2hphoyo+MZrPFpdcJL8KkIdMKbY
}
- public function testDownloadAppWithDowngrade() {
+ public function testDownloadAppWithDowngrade(): void {
// Use previous test to download the application in version 0.9
$this->testDownloadAppSuccessful();
diff --git a/tests/lib/IntegrityCheck/CheckerTest.php b/tests/lib/IntegrityCheck/CheckerTest.php
index a9e99a4c81d..be952765077 100644
--- a/tests/lib/IntegrityCheck/CheckerTest.php
+++ b/tests/lib/IntegrityCheck/CheckerTest.php
@@ -1,1153 +1,1153 @@
-<?php
-/**
- * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
- * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
- * SPDX-License-Identifier: AGPL-3.0-only
- */
-
-namespace Test\IntegrityCheck;
-
-use OC\Core\Command\Maintenance\Mimetype\GenerateMimetypeFileBuilder;
-use OC\IntegrityCheck\Checker;
-use OC\IntegrityCheck\Helpers\AppLocator;
-use OC\IntegrityCheck\Helpers\EnvironmentHelper;
-use OC\IntegrityCheck\Helpers\FileAccessHelper;
-use OC\Memcache\NullCache;
-use OCP\App\IAppManager;
-use OCP\IAppConfig;
-use OCP\ICacheFactory;
-use OCP\IConfig;
-use phpseclib\Crypt\RSA;
-use phpseclib\File\X509;
-use Test\TestCase;
-
-class CheckerTest extends TestCase {
- /** @var EnvironmentHelper|\PHPUnit\Framework\MockObject\MockObject */
- private $environmentHelper;
- /** @var AppLocator|\PHPUnit\Framework\MockObject\MockObject */
- private $appLocator;
- /** @var Checker */
- private $checker;
- /** @var FileAccessHelper|\PHPUnit\Framework\MockObject\MockObject */
- private $fileAccessHelper;
- /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */
- private $config;
- /** @var IAppConfig|\PHPUnit\Framework\MockObject\MockObject */
- private $appConfig;
- /** @var ICacheFactory|\PHPUnit\Framework\MockObject\MockObject */
- private $cacheFactory;
- /** @var IAppManager|\PHPUnit\Framework\MockObject\MockObject */
- private $appManager;
- /** @var \OC\Files\Type\Detection|\PHPUnit\Framework\MockObject\MockObject */
- private $mimeTypeDetector;
-
- protected function setUp(): void {
- parent::setUp();
- $this->environmentHelper = $this->createMock(EnvironmentHelper::class);
- $this->fileAccessHelper = $this->createMock(FileAccessHelper::class);
- $this->appLocator = $this->createMock(AppLocator::class);
- $this->config = $this->createMock(IConfig::class);
- $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->config->method('getAppValue')
- ->willReturnArgument(2);
-
- $this->cacheFactory
- ->expects($this->any())
- ->method('createDistributed')
- ->with('oc.integritycheck.checker')
- ->willReturn(new NullCache());
-
- $this->checker = new Checker(
- $this->environmentHelper,
- $this->fileAccessHelper,
- $this->appLocator,
- $this->config,
- $this->appConfig,
- $this->cacheFactory,
- $this->appManager,
- $this->mimeTypeDetector
- );
- }
-
-
- public function testWriteAppSignatureOfNotExistingApp() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('Exception message');
-
- $this->fileAccessHelper
- ->expects($this->once())
- ->method('assertDirectoryExists')
- ->with('NotExistingApp/appinfo')
- ->willThrowException(new \Exception('Exception message'));
- $this->fileAccessHelper
- ->expects($this->once())
- ->method('is_writable')
- ->with('NotExistingApp/appinfo')
- ->willReturn(true);
-
- $keyBundle = file_get_contents(__DIR__ .'/../../data/integritycheck/SomeApp.crt');
- $rsaPrivateKey = file_get_contents(__DIR__ .'/../../data/integritycheck/SomeApp.key');
- $rsa = new RSA();
- $rsa->loadKey($rsaPrivateKey);
- $x509 = new X509();
- $x509->loadX509($keyBundle);
- $this->checker->writeAppSignature('NotExistingApp', $x509, $rsa);
- }
-
-
- public function testWriteAppSignatureWrongPermissions() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessageMatches('/[a-zA-Z\\/_-]+ is not writable/');
-
- $this->fileAccessHelper
- ->expects($this->once())
- ->method('file_put_contents')
- ->will($this->throwException(new \Exception('Exception message')));
-
- $keyBundle = file_get_contents(__DIR__ .'/../../data/integritycheck/SomeApp.crt');
- $rsaPrivateKey = file_get_contents(__DIR__ .'/../../data/integritycheck/SomeApp.key');
- $rsa = new RSA();
- $rsa->loadKey($rsaPrivateKey);
- $x509 = new X509();
- $x509->loadX509($keyBundle);
- $this->checker->writeAppSignature(\OC::$SERVERROOT . '/tests/data/integritycheck/app/', $x509, $rsa);
- }
-
- public function testWriteAppSignature() {
- $expectedSignatureFileData = '{
- "hashes": {
- "AnotherFile.txt": "1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112",
- "subfolder\/file.txt": "410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b"
- },
- "signature": "Y5yvXvcGHVPuRRatKVDUONWq1FpLXugZd6Km\/+aEHsQj7coVl9FeMj9OsWamBf7yRIw3dtNLguTLlAA9QAv\/b0uHN3JnbNZN+dwFOve4NMtqXfSDlWftqKN00VS+RJXpG1S2IIx9Poyp2NoghL\/5AuTv4GHiNb7zU\/DT\/kt71pUGPgPR6IIFaE+zHOD96vjYkrH+GfWZzKR0FCdLib9yyNvk+EGrcjKM6qjs2GKfS\/XFjj\/\/neDnh\/0kcPuKE3ZbofnI4TIDTv0CGqvOp7PtqVNc3Vy\/UKa7uF1PT0MAUKMww6EiMUSFZdUVP4WWF0Y72W53Qdtf1hrAZa2kfKyoK5kd7sQmCSKUPSU8978AUVZlBtTRlyT803IKwMV0iHMkw+xYB1sN2FlHup\/DESADqxhdgYuK35bCPvgkb4SBe4B8Voz\/izTvcP7VT5UvkYdAO+05\/jzdaHEmzmsD92CFfvX0q8O\/Y\/29ubftUJsqcHeMDKgcR4eZOE8+\/QVc\/89QO6WnKNuNuV+5bybO6g6PAdC9ZPsCvnihS61O2mwRXHLR3jv2UleFWm+lZEquPKtkhi6SLtDiijA4GV6dmS+dzujSLb7hGeD5o1plZcZ94uhWljl+QIp82+zU\/lYB1Zfr4Mb4e+V7r2gv7Fbv7y6YtjE2GIQwRhC5jq56bD0ZB+I=",
- "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEwTCCAqmgAwIBAgIUWv0iujufs5lUr0svCf\/qTQvoyKAwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIyNDk1M1oXDTE2MTEwMzIyNDk1M1owEjEQMA4GA1UEAwwHU29tZUFwcDCCAiIw\r\nDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK8q0x62agGSRBqeWsaeEwFfepMk\r\nF8cAobMMi50qHCv9IrOn\/ZH9l52xBrbIkErVmRjmly0d4JhD8Ymhidsh9ONKYl\/j\r\n+ishsZDM8eNNdp3Ew+fEYVvY1W7mR1qU24NWj0bzVsClI7hvPVIuw7AjfBDq1C5+\r\nA+ZSLSXYvOK2cEWjdxQfuNZwEZSjmA63DUllBIrm35IaTvfuyhU6BW9yHZxmb8+M\r\nw0xDv30D5UkE\/2N7Pa\/HQJLxCR+3zKibRK3nUyRDLSXxMkU9PnFNaPNX59VPgyj4\r\nGB1CFSToldJVPF4pzh7p36uGXZVxs8m3LFD4Ol8mhi7jkxDZjqFN46gzR0r23Py6\r\ndol9vfawGIoUwp9LvL0S7MvdRY0oazLXwClLP4OQ17zpSMAiCj7fgNT661JamPGj\r\nt5O7Zn2wA7I4ddDS\/HDTWCu98Zwc9fHIpsJPgCZ9awoqxi4Mnf7Pk9g5nnXhszGC\r\ncxxIASQKM+GhdzoRxKknax2RzUCwCzcPRtCj8AQT\/x\/mqN3PfRmlnFBNACUw9bpZ\r\nSOoNq2pCF9igftDWpSIXQ38pVpKLWowjjg3DVRmVKBgivHnUnVLyzYBahHPj0vaz\r\ntFtUFRaqXDnt+4qyUGyrT5h5pjZaTcHIcSB4PiarYwdVvgslgwnQzOUcGAzRWBD4\r\n6jV2brP5vFY3g6iPAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBACTY3CCHC+Z28gCf\r\nFWGKQ3wAKs+k4+0yoti0qm2EKX7rSGQ0PHSas6uW79WstC4Rj+DYkDtIhGMSg8FS\r\nHVGZHGBCc0HwdX+BOAt3zi4p7Sf3oQef70\/4imPoKxbAVCpd\/cveVcFyDC19j1yB\r\nBapwu87oh+muoeaZxOlqQI4UxjBlR\/uRSMhOn2UGauIr3dWJgAF4pGt7TtIzt+1v\r\n0uA6FtN1Y4R5O8AaJPh1bIG0CVvFBE58esGzjEYLhOydgKFnEP94kVPgJD5ds9C3\r\npPhEpo1dRpiXaF7WGIV1X6DI\/ipWvfrF7CEy6I\/kP1InY\/vMDjQjeDnJ\/VrXIWXO\r\nyZvHXVaN\/m+1RlETsH7YO\/QmxRue9ZHN3gvvWtmpCeA95sfpepOk7UcHxHZYyQbF\r\n49\/au8j+5tsr4A83xzsT1JbcKRxkAaQ7WDJpOnE5O1+H0fB+BaLakTg6XX9d4Fo7\r\n7Gin7hVWX7pL+JIyxMzME3LhfI61+CRcqZQIrpyaafUziPQbWIPfEs7h8tCOWyvW\r\nUO8ZLervYCB3j44ivkrxPlcBklDCqqKKBzDP9dYOtS\/P4RB1NkHA9+NTvmBpTonS\r\nSFXdg9fFMD7VfjDE3Vnk+8DWkVH5wBYowTAD7w9Wuzr7DumiAULexnP\/Y7xwxLv7\r\n4B+pXTAcRK0zECDEaX3npS8xWzrB\r\n-----END CERTIFICATE-----"
-}';
- $this->fileAccessHelper
- ->expects($this->once())
- ->method('file_put_contents')
- ->with(
- $this->equalTo(\OC::$SERVERROOT . '/tests/data/integritycheck/app//appinfo/signature.json'),
- $this->callback(function ($signature) use ($expectedSignatureFileData) {
- $expectedArray = json_decode($expectedSignatureFileData, true);
- $actualArray = json_decode($signature, true);
- $this->assertEquals($expectedArray, $actualArray);
- return true;
- })
- );
-
- $keyBundle = file_get_contents(__DIR__ .'/../../data/integritycheck/SomeApp.crt');
- $rsaPrivateKey = file_get_contents(__DIR__ .'/../../data/integritycheck/SomeApp.key');
- $rsa = new RSA();
- $rsa->loadKey($rsaPrivateKey);
- $x509 = new X509();
- $x509->loadX509($keyBundle);
- $this->checker->writeAppSignature(\OC::$SERVERROOT . '/tests/data/integritycheck/app/', $x509, $rsa);
- }
-
- public function testVerifyAppSignatureWithoutSignatureData() {
- $this->environmentHelper
- ->expects($this->once())
- ->method('getChannel')
- ->willReturn('stable');
- $this->config
- ->expects($this->any())
- ->method('getSystemValueBool')
- ->with('integrity.check.disabled', false)
- ->willReturn(false);
-
- $expected = [
- 'EXCEPTION' => [
- 'class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class,
- 'message' => 'Signature data not found.',
- ],
- ];
- $this->assertSame($expected, $this->checker->verifyAppSignature('SomeApp'));
- }
-
- public function testVerifyAppSignatureWithValidSignatureData() {
- $this->environmentHelper
- ->expects($this->once())
- ->method('getChannel')
- ->willReturn('stable');
- $this->config
- ->expects($this->any())
- ->method('getSystemValueBool')
- ->with('integrity.check.disabled', false)
- ->willReturn(false);
-
- $this->appLocator
- ->expects($this->once())
- ->method('getAppPath')
- ->with('SomeApp')
- ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/app/');
- $signatureDataFile = '{
- "hashes": {
- "AnotherFile.txt": "1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112",
- "subfolder\/file.txt": "410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b"
- },
- "signature": "dYoohBaWIFR\/To1FXEbMQB5apUhVYlEauBGSPo12nq84wxWkBx2EM3KDRgkB5Sub2tr0CgmAc2EVjPhKIEzAam26cyUb48bJziz1V6wvW7z4GZAfaJpzLkyHdSfV5117VSf5w1rDcAeZDXfGUaaNEJPWytaF4ZIxVge7f3NGshHy4odFVPADy\/u6c43BWvaOtJ4m3aJQbP6sxCO9dxwcm5yJJJR3n36jfh229sdWBxyl8BhwhH1e1DEv78\/aiL6ckKFPVNzx01R6yDFt3TgEMR97YZ\/R6lWiXG+dsJ305jNFlusLu518zBUvl7g5yjzGN778H29b2C8VLZKmi\/h1CH9jGdD72fCqCYdenD2uZKzb6dsUtXtvBmVcVT6BUGz41W1pkkEEB+YJpMrHILIxAiHRGv1+aZa9\/Oz8LWFd+BEUQjC2LJgojPnpzaG\/msw1nBkX16NNVDWWtJ25Bc\/r\/mG46rwjWB\/cmV6Lwt6KODiqlxgrC4lm9ALOCEWw+23OcYhLwNfQTYevXqHqsFfXOkhUnM8z5vDUb\/HBraB1DjFXN8iLK+1YewD4P495e+SRzrR79Oi3F8SEqRIzRLfN2rnW1BTms\/wYsz0p67cup1Slk1XlNmHwbWX25NVd2PPlLOvZRGoqcKFpIjC5few8THiZfyjiNFwt3RM0AFdZcXY=",
- "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----"
-}';
- $this->fileAccessHelper
- ->expects($this->exactly(2))
- ->method('file_get_contents')
- ->withConsecutive(
- [\OC::$SERVERROOT . '/tests/data/integritycheck/app//appinfo/signature.json'],
- ['/resources/codesigning/root.crt'],
- )
- ->willReturnOnConsecutiveCalls(
- $signatureDataFile,
- file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')
- );
-
- $this->assertSame([], $this->checker->verifyAppSignature('SomeApp'));
- }
-
- public function testVerifyAppSignatureWithTamperedSignatureData() {
- $this->environmentHelper
- ->expects($this->once())
- ->method('getChannel')
- ->willReturn('stable');
- $this->config
- ->expects($this->any())
- ->method('getSystemValueBool')
- ->with('integrity.check.disabled', false)
- ->willReturn(false);
-
- $this->appLocator
- ->expects($this->once())
- ->method('getAppPath')
- ->with('SomeApp')
- ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/app/');
- $signatureDataFile = '{
- "hashes": {
- "AnotherFile.txt": "tampered",
- "subfolder\/file.txt": "tampered"
- },
- "signature": "EL49UaSeyMAqyMtqId+tgOhhwgOevPZsRLX4j2blnybAB6fN07z0936JqZV7+eMPiE30Idx+UCY6rCFN531Kqe9vAOCdgtHUSOjjKyKc+lvULESlMb6YQcrZrvDlEMMjzjH49ewG7Ai8sNN6HrRUd9U8ws+ewSkW2DOOBItj\/21RBnkrSt+2AtGXGigEvuTm57HrCYDj8\/lSkumC2GVkjLUHeLOKYo4PRNOr6yP5mED5v7zo66AWvXl2fKv54InZcdxsAk35lyK9DGZbk\/027ZRd0AOHT3LImRLvQ+8EAg3XLlRUy0hOFGgPC+jYonMzgYvsAXAXi2j8LnLJlsLwpFwu1k1B+kZVPMumKZvP9OvJb70EirecXmz62V+Jiyuaq7ne4y7Kp5gKZT\/T8SeZ0lFtCmPfYyzBB0y8s5ldmTTmdVYHs54t\/OCCW82HzQZxnFNPzDTRa8HglsaMKrqPtW59+R4UvRKSWhB8M\/Ah57qgzycvPV4KMz\/FbD4l\/\/9chRKSlCfc2k3b8ZSHNmi+EzCKgJjWIoKdgN1yax94puU8jfn8UW+G7H9Y1Jsf\/jox6QLyYEgtV1vOHY2xLT7fVs2vhyvkN2MNjJnmQ70gFG5Qz2lBz5wi6ZpB+tOfCcpbLxWAkoWoIrmC\/Ilqh7mfmRZ43g5upjkepHNd93ONuY8=",
- "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEwTCCAqmgAwIBAgIUWv0iujufs5lUr0svCf\/qTQvoyKAwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIyNDk1M1oXDTE2MTEwMzIyNDk1M1owEjEQMA4GA1UEAwwHU29tZUFwcDCCAiIw\r\nDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK8q0x62agGSRBqeWsaeEwFfepMk\r\nF8cAobMMi50qHCv9IrOn\/ZH9l52xBrbIkErVmRjmly0d4JhD8Ymhidsh9ONKYl\/j\r\n+ishsZDM8eNNdp3Ew+fEYVvY1W7mR1qU24NWj0bzVsClI7hvPVIuw7AjfBDq1C5+\r\nA+ZSLSXYvOK2cEWjdxQfuNZwEZSjmA63DUllBIrm35IaTvfuyhU6BW9yHZxmb8+M\r\nw0xDv30D5UkE\/2N7Pa\/HQJLxCR+3zKibRK3nUyRDLSXxMkU9PnFNaPNX59VPgyj4\r\nGB1CFSToldJVPF4pzh7p36uGXZVxs8m3LFD4Ol8mhi7jkxDZjqFN46gzR0r23Py6\r\ndol9vfawGIoUwp9LvL0S7MvdRY0oazLXwClLP4OQ17zpSMAiCj7fgNT661JamPGj\r\nt5O7Zn2wA7I4ddDS\/HDTWCu98Zwc9fHIpsJPgCZ9awoqxi4Mnf7Pk9g5nnXhszGC\r\ncxxIASQKM+GhdzoRxKknax2RzUCwCzcPRtCj8AQT\/x\/mqN3PfRmlnFBNACUw9bpZ\r\nSOoNq2pCF9igftDWpSIXQ38pVpKLWowjjg3DVRmVKBgivHnUnVLyzYBahHPj0vaz\r\ntFtUFRaqXDnt+4qyUGyrT5h5pjZaTcHIcSB4PiarYwdVvgslgwnQzOUcGAzRWBD4\r\n6jV2brP5vFY3g6iPAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBACTY3CCHC+Z28gCf\r\nFWGKQ3wAKs+k4+0yoti0qm2EKX7rSGQ0PHSas6uW79WstC4Rj+DYkDtIhGMSg8FS\r\nHVGZHGBCc0HwdX+BOAt3zi4p7Sf3oQef70\/4imPoKxbAVCpd\/cveVcFyDC19j1yB\r\nBapwu87oh+muoeaZxOlqQI4UxjBlR\/uRSMhOn2UGauIr3dWJgAF4pGt7TtIzt+1v\r\n0uA6FtN1Y4R5O8AaJPh1bIG0CVvFBE58esGzjEYLhOydgKFnEP94kVPgJD5ds9C3\r\npPhEpo1dRpiXaF7WGIV1X6DI\/ipWvfrF7CEy6I\/kP1InY\/vMDjQjeDnJ\/VrXIWXO\r\nyZvHXVaN\/m+1RlETsH7YO\/QmxRue9ZHN3gvvWtmpCeA95sfpepOk7UcHxHZYyQbF\r\n49\/au8j+5tsr4A83xzsT1JbcKRxkAaQ7WDJpOnE5O1+H0fB+BaLakTg6XX9d4Fo7\r\n7Gin7hVWX7pL+JIyxMzME3LhfI61+CRcqZQIrpyaafUziPQbWIPfEs7h8tCOWyvW\r\nUO8ZLervYCB3j44ivkrxPlcBklDCqqKKBzDP9dYOtS\/P4RB1NkHA9+NTvmBpTonS\r\nSFXdg9fFMD7VfjDE3Vnk+8DWkVH5wBYowTAD7w9Wuzr7DumiAULexnP\/Y7xwxLv7\r\n4B+pXTAcRK0zECDEaX3npS8xWzrB\r\n-----END CERTIFICATE-----"
-}';
- $this->fileAccessHelper
- ->expects($this->exactly(2))
- ->method('file_get_contents')
- ->withConsecutive(
- [\OC::$SERVERROOT . '/tests/data/integritycheck/app//appinfo/signature.json'],
- ['/resources/codesigning/root.crt'],
- )
- ->willReturnOnConsecutiveCalls(
- $signatureDataFile,
- file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')
- );
-
- $expected = [
- 'EXCEPTION' => [
- 'class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class,
- 'message' => 'Signature could not get verified.',
- ],
- ];
- $this->assertEquals($expected, $this->checker->verifyAppSignature('SomeApp'));
- }
-
- public function testVerifyAppSignatureWithTamperedFiles() {
- $this->environmentHelper
- ->expects($this->once())
- ->method('getChannel')
- ->willReturn('stable');
- $this->config
- ->expects($this->any())
- ->method('getSystemValueBool')
- ->with('integrity.check.disabled', false)
- ->willReturn(false);
-
- $this->appLocator
- ->expects($this->once())
- ->method('getAppPath')
- ->with('SomeApp')
- ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/appWithInvalidData/');
- $signatureDataFile = '{
- "hashes": {
- "AnotherFile.txt": "1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112",
- "subfolder\/file.txt": "410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b"
- },
- "signature": "dYoohBaWIFR\/To1FXEbMQB5apUhVYlEauBGSPo12nq84wxWkBx2EM3KDRgkB5Sub2tr0CgmAc2EVjPhKIEzAam26cyUb48bJziz1V6wvW7z4GZAfaJpzLkyHdSfV5117VSf5w1rDcAeZDXfGUaaNEJPWytaF4ZIxVge7f3NGshHy4odFVPADy\/u6c43BWvaOtJ4m3aJQbP6sxCO9dxwcm5yJJJR3n36jfh229sdWBxyl8BhwhH1e1DEv78\/aiL6ckKFPVNzx01R6yDFt3TgEMR97YZ\/R6lWiXG+dsJ305jNFlusLu518zBUvl7g5yjzGN778H29b2C8VLZKmi\/h1CH9jGdD72fCqCYdenD2uZKzb6dsUtXtvBmVcVT6BUGz41W1pkkEEB+YJpMrHILIxAiHRGv1+aZa9\/Oz8LWFd+BEUQjC2LJgojPnpzaG\/msw1nBkX16NNVDWWtJ25Bc\/r\/mG46rwjWB\/cmV6Lwt6KODiqlxgrC4lm9ALOCEWw+23OcYhLwNfQTYevXqHqsFfXOkhUnM8z5vDUb\/HBraB1DjFXN8iLK+1YewD4P495e+SRzrR79Oi3F8SEqRIzRLfN2rnW1BTms\/wYsz0p67cup1Slk1XlNmHwbWX25NVd2PPlLOvZRGoqcKFpIjC5few8THiZfyjiNFwt3RM0AFdZcXY=",
- "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----"
-}';
- $this->fileAccessHelper
- ->expects($this->exactly(2))
- ->method('file_get_contents')
- ->withConsecutive(
- [\OC::$SERVERROOT . '/tests/data/integritycheck/appWithInvalidData//appinfo/signature.json'],
- ['/resources/codesigning/root.crt'],
- )
- ->willReturnOnConsecutiveCalls(
- $signatureDataFile,
- file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')
- );
-
-
- $expected = [
- 'INVALID_HASH' => [
- 'AnotherFile.txt' => [
- 'expected' => '1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112',
- 'current' => '7322348ba269c6d5522efe02f424fa3a0da319a7cd9c33142a5afe32a2d9af2da3a411f086fcfc96ff4301ea566f481dba0960c2abeef3594c4d930462f6584c',
- ],
- ],
- 'FILE_MISSING' => [
- 'subfolder/file.txt' => [
- 'expected' => '410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b',
- 'current' => '',
- ],
- ],
- 'EXTRA_FILE' => [
- 'UnecessaryFile' => [
- 'expected' => '',
- 'current' => 'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e',
- ],
- ],
-
- ];
- $this->assertSame($expected, $this->checker->verifyAppSignature('SomeApp'));
- }
-
- public function testVerifyAppSignatureWithTamperedFilesAndAlternatePath() {
- $this->environmentHelper
- ->expects($this->once())
- ->method('getChannel')
- ->willReturn('stable');
- $this->config
- ->expects($this->any())
- ->method('getSystemValueBool')
- ->with('integrity.check.disabled', false)
- ->willReturn(false);
-
- $this->appLocator
- ->expects($this->never())
- ->method('getAppPath')
- ->with('SomeApp');
- $signatureDataFile = '{
- "hashes": {
- "AnotherFile.txt": "1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112",
- "subfolder\/file.txt": "410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b"
- },
- "signature": "dYoohBaWIFR\/To1FXEbMQB5apUhVYlEauBGSPo12nq84wxWkBx2EM3KDRgkB5Sub2tr0CgmAc2EVjPhKIEzAam26cyUb48bJziz1V6wvW7z4GZAfaJpzLkyHdSfV5117VSf5w1rDcAeZDXfGUaaNEJPWytaF4ZIxVge7f3NGshHy4odFVPADy\/u6c43BWvaOtJ4m3aJQbP6sxCO9dxwcm5yJJJR3n36jfh229sdWBxyl8BhwhH1e1DEv78\/aiL6ckKFPVNzx01R6yDFt3TgEMR97YZ\/R6lWiXG+dsJ305jNFlusLu518zBUvl7g5yjzGN778H29b2C8VLZKmi\/h1CH9jGdD72fCqCYdenD2uZKzb6dsUtXtvBmVcVT6BUGz41W1pkkEEB+YJpMrHILIxAiHRGv1+aZa9\/Oz8LWFd+BEUQjC2LJgojPnpzaG\/msw1nBkX16NNVDWWtJ25Bc\/r\/mG46rwjWB\/cmV6Lwt6KODiqlxgrC4lm9ALOCEWw+23OcYhLwNfQTYevXqHqsFfXOkhUnM8z5vDUb\/HBraB1DjFXN8iLK+1YewD4P495e+SRzrR79Oi3F8SEqRIzRLfN2rnW1BTms\/wYsz0p67cup1Slk1XlNmHwbWX25NVd2PPlLOvZRGoqcKFpIjC5few8THiZfyjiNFwt3RM0AFdZcXY=",
- "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----"
-}';
- $this->fileAccessHelper
- ->expects($this->exactly(2))
- ->method('file_get_contents')
- ->withConsecutive(
- [\OC::$SERVERROOT . '/tests/data/integritycheck/appWithInvalidData//appinfo/signature.json'],
- ['/resources/codesigning/root.crt'],
- )
- ->willReturnOnConsecutiveCalls(
- $signatureDataFile,
- file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')
- );
-
-
- $expected = [
- 'INVALID_HASH' => [
- 'AnotherFile.txt' => [
- 'expected' => '1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112',
- 'current' => '7322348ba269c6d5522efe02f424fa3a0da319a7cd9c33142a5afe32a2d9af2da3a411f086fcfc96ff4301ea566f481dba0960c2abeef3594c4d930462f6584c',
- ],
- ],
- 'FILE_MISSING' => [
- 'subfolder/file.txt' => [
- 'expected' => '410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b',
- 'current' => '',
- ],
- ],
- 'EXTRA_FILE' => [
- 'UnecessaryFile' => [
- 'expected' => '',
- 'current' => 'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e',
- ],
- ],
-
- ];
- $this->assertSame($expected, $this->checker->verifyAppSignature('SomeApp', \OC::$SERVERROOT . '/tests/data/integritycheck/appWithInvalidData/'));
- }
-
- public function testVerifyAppWithDifferentScope() {
- $this->environmentHelper
- ->expects($this->once())
- ->method('getChannel')
- ->willReturn('stable');
- $this->config
- ->expects($this->any())
- ->method('getSystemValueBool')
- ->with('integrity.check.disabled', false)
- ->willReturn(false);
-
- $this->appLocator
- ->expects($this->once())
- ->method('getAppPath')
- ->with('SomeApp')
- ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/appWithInvalidData/');
- $signatureDataFile = '{
- "hashes": {
- "AnotherFile.txt": "1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112",
- "subfolder\/file.txt": "410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b"
- },
- "signature": "eXesvDm3pkek12xSwMG10y9suRES79Nye3jYNe5KYq1tTUPqRRNgxmMGAfcUro0zpLeAr2YgHeSMWtglblGOW7pmwGVPZ0O1Y4r1fE6jnep0kW+35PLIaqCorIOnCAtSzDNKBhwd1ow3zW2wC0DFouuEkIO8u5Fw28g8E8dp8zEk1xMblNPy+xtWkmYHrVJ\/dQgun1bYOF2ZFtAzatwndTI\/bGsy1i3Wsl+x6HyWKQdq8y8VObtOqKDH7uERBEpB9DHVyKflj1v1gQuEH6BhaRdATc7ee0MiQdGblraIySwYRdfo2d8i82OVKrenMB3SLwyCvDPyQ9iKpTOnSF52ZBqaqSXKM2N\/RAkweeBFQQCwcHhqxvB0cfbyHcbkOLeCZe\/tsh68IxwTiYgzvLfl7sOZ5arnZbzrPpZmB+hfV2omkoJ1tDwOWz9hEmLLNtfo2OxyUH1m0+XFaC+Gbn4WkVDgf7YZkwUcG+Qoa3oKDNMss8MEyZxewl2iDGZcf402dlidHRprlfmXbAYuVQ08\/a0HxIKYPGh\/nsMGmwnO15CWtFpAbhUA\/D5oRjsIxnvXaMDg0iAFpdu\/5Ffsj7g3EPdBkiQHNYK7YU1RRx609eH0bZyiIYHdUPw7ikLupvrebZmELqi3mqDFO99u4eISlxFJlUbUND3L4BtmWTWrKwI=",
- "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIExjCCAq6gAwIBAgIUHSJjhJqMwr+3TkoiQFg4SVVYQ1gwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIzMjc1NVoXDTE2MTEwMzIzMjc1NVowFzEVMBMGA1UEAwwMQW5vdGhlclNjb3Bl\r\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA33npb5RmUkXrDT+TbwMf\r\n0zQ33SlzsjoGxCrbSwJOn6leGGInJ6ZrdzLL0WTi\/dTpg+Y\/JS+72XWm5NSjaTxo\r\n7OHc3cQBwXQj4tN6j\/y5qqY0GDLYufEkx2rpazqt9lBSJ72u1bGl2yoOXzYCz5i0\r\n60KsJXC9K44LKzGsarzbwAgskSVNkjAsPgjnCWZmcl6icpLi5Fz9rs2UMOWbdvdI\r\nAROsn0eC9E\/akmXTy5YMu6bAIGpvjZFHzyA83FQRbvv5o1V5Gsye\/VQLEgh7rqfz\r\nT\/jgWifP+JgoeB6otzuRZ3fFsmbBiyCIRtIOzQQflozhUlWtmiEGwg4GySuMUjEH\r\nA1LF86LO+ZzDQgd2oYNKmrQ8O+EcLqx9BpV4AFhEvqdk7uycJYPHs6yl+yfbzTeJ\r\n2Xd0yVAfd9r\/iDr36clLj2bzEObdl9xzKjcCIXE4Q0G4Pur41\/BJUDK9PI390ccQ\r\nnFjjVYBMsC859OwW64tMP0zkM9Vv72LCaEzaR8jqH0j11catqxunr+StfMcmxLTN\r\nbqBJbSEq4ER3mJxCTI2UrIVmdQ7+wRxgv3QTDNOZyqrz2L8A1Rpb3h0APxtQv+oA\r\n8KIZYID5\/qsS2V2jITkMQ8Nd1W3b0cZhZ600z+znh3jLJ0TYLvwN6\/qBQTUDaM2o\r\ng1+icMqXIXIeKuoPCVVsG7cCAwEAATANBgkqhkiG9w0BAQUFAAOCAgEAHc4F\/kOV\r\nHc8In5MmGg2YtjwZzjdeoC5TIPZczRqz0B+wRbJzN6aYryKZKLmP+wKpgRnJWDzp\r\nrgKGyyEQIAfK63DEv4B9p4N1B+B3aeMKsSpVcw7wbFTD57V5A7pURGoo31d0mw5L\r\nUIXZ2u+TUfGbzucMxLdFhTwjGpz9M6Kkm\/POxmV0tvLija5LdbdKnYR9BFmyu4IX\r\nqyoIAtComATNLl+3URu3SZxhE3NxhzMz+eAeNfh1KuIf2gWIIeDCXalVSJLym+OQ\r\nHFDpqRhJqfTMprrRlmmU7Zntgbj8\/RRZuXnBvH9cQ2KykLOb4UoCPlGUqOqKyP9m\r\nDJSFRiMJfpgMQUaJk1TLhKF+IR6FnmwURLEtkONJumtDQju9KaWPlhueONdyGi0p\r\nqxLVUo1Vb52XnPhk2GEEduxpDc9V5ePJ+pdcEdMifY\/uPNBRuBj2c87yq1DLH+U4\r\n3XzP1MlwjnBWZYuoFo0j6Jq0r\/MG6HjGdmkGIsRoheRi8Z8Scz5AW5QRkNz8pKop\r\nTELFqQy9g6TyQzzC8t6HZcpNe842ZUk4raEAbCZe\/XqxWMw5svPgNceBqM3fh7sZ\r\nBSykOHLaL8kiRO\/IS3y1yZEAuiWBvtxcTNLzBb+hdRpm2y8\/qH\/pKo+CMj1VzjNT\r\nD8YRQg0cjmDytJzHDrtV\/aTc9W1aPHun0vw=\r\n-----END CERTIFICATE-----"
-}';
- $this->fileAccessHelper
- ->expects($this->exactly(2))
- ->method('file_get_contents')
- ->withConsecutive(
- [\OC::$SERVERROOT . '/tests/data/integritycheck/appWithInvalidData//appinfo/signature.json'],
- ['/resources/codesigning/root.crt'],
- )->willReturnOnConsecutiveCalls(
- $signatureDataFile,
- file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')
- );
-
- $expected = [
- 'EXCEPTION' => [
- 'class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class,
- 'message' => 'Certificate is not valid for required scope. (Requested: SomeApp, current: CN=AnotherScope)',
- ],
- ];
- $this->assertSame($expected, $this->checker->verifyAppSignature('SomeApp'));
- }
-
- public function testVerifyAppWithDifferentScopeAndAlwaysTrustedCore() {
- $this->environmentHelper
- ->expects($this->once())
- ->method('getChannel')
- ->willReturn('stable');
- $this->config
- ->expects($this->any())
- ->method('getSystemValueBool')
- ->with('integrity.check.disabled', false)
- ->willReturn(false);
-
- $this->appLocator
- ->expects($this->once())
- ->method('getAppPath')
- ->with('SomeApp')
- ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/app/');
- $signatureDataFile = '{
- "hashes": {
- "AnotherFile.txt": "1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112",
- "subfolder\/file.txt": "410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b"
- },
- "signature": "dYoohBaWIFR\/To1FXEbMQB5apUhVYlEauBGSPo12nq84wxWkBx2EM3KDRgkB5Sub2tr0CgmAc2EVjPhKIEzAam26cyUb48bJziz1V6wvW7z4GZAfaJpzLkyHdSfV5117VSf5w1rDcAeZDXfGUaaNEJPWytaF4ZIxVge7f3NGshHy4odFVPADy\/u6c43BWvaOtJ4m3aJQbP6sxCO9dxwcm5yJJJR3n36jfh229sdWBxyl8BhwhH1e1DEv78\/aiL6ckKFPVNzx01R6yDFt3TgEMR97YZ\/R6lWiXG+dsJ305jNFlusLu518zBUvl7g5yjzGN778H29b2C8VLZKmi\/h1CH9jGdD72fCqCYdenD2uZKzb6dsUtXtvBmVcVT6BUGz41W1pkkEEB+YJpMrHILIxAiHRGv1+aZa9\/Oz8LWFd+BEUQjC2LJgojPnpzaG\/msw1nBkX16NNVDWWtJ25Bc\/r\/mG46rwjWB\/cmV6Lwt6KODiqlxgrC4lm9ALOCEWw+23OcYhLwNfQTYevXqHqsFfXOkhUnM8z5vDUb\/HBraB1DjFXN8iLK+1YewD4P495e+SRzrR79Oi3F8SEqRIzRLfN2rnW1BTms\/wYsz0p67cup1Slk1XlNmHwbWX25NVd2PPlLOvZRGoqcKFpIjC5few8THiZfyjiNFwt3RM0AFdZcXY=",
- "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----"
-}';
- $this->fileAccessHelper
- ->expects($this->exactly(2))
- ->method('file_get_contents')
- ->withConsecutive(
- [\OC::$SERVERROOT . '/tests/data/integritycheck/app//appinfo/signature.json'],
- ['/resources/codesigning/root.crt'],
- )->willReturnOnConsecutiveCalls(
- $signatureDataFile,
- file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')
- );
-
- $this->assertSame([], $this->checker->verifyAppSignature('SomeApp'));
- }
-
-
- public function testWriteCoreSignatureWithException() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('Exception message');
-
- $this->fileAccessHelper
- ->expects($this->once())
- ->method('assertDirectoryExists')
- ->will($this->throwException(new \Exception('Exception message')));
- $this->fileAccessHelper
- ->expects($this->once())
- ->method('is_writable')
- ->with(__DIR__ . '/core')
- ->willReturn(true);
-
- $keyBundle = file_get_contents(__DIR__ .'/../../data/integritycheck/SomeApp.crt');
- $rsaPrivateKey = file_get_contents(__DIR__ .'/../../data/integritycheck/SomeApp.key');
- $rsa = new RSA();
- $rsa->loadKey($rsaPrivateKey);
- $x509 = new X509();
- $x509->loadX509($keyBundle);
- $this->checker->writeCoreSignature($x509, $rsa, __DIR__);
- }
-
-
- public function testWriteCoreSignatureWrongPermissions() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessageMatches('/[a-zA-Z\\/_-]+ is not writable/');
-
- $this->fileAccessHelper
- ->expects($this->once())
- ->method('assertDirectoryExists')
- ->will($this->throwException(new \Exception('Exception message')));
- $this->fileAccessHelper
- ->expects($this->once())
- ->method('is_writable')
- ->with(__DIR__ . '/core')
- ->willReturn(false);
-
- $keyBundle = file_get_contents(__DIR__ .'/../../data/integritycheck/SomeApp.crt');
- $rsaPrivateKey = file_get_contents(__DIR__ .'/../../data/integritycheck/SomeApp.key');
- $rsa = new RSA();
- $rsa->loadKey($rsaPrivateKey);
- $x509 = new X509();
- $x509->loadX509($keyBundle);
- $this->checker->writeCoreSignature($x509, $rsa, __DIR__);
- }
-
- public function testWriteCoreSignature() {
- $expectedSignatureFileData = '{
- "hashes": {
- "AnotherFile.txt": "1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112",
- "subfolder\/file.txt": "410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b"
- },
- "signature": "dYoohBaWIFR\/To1FXEbMQB5apUhVYlEauBGSPo12nq84wxWkBx2EM3KDRgkB5Sub2tr0CgmAc2EVjPhKIEzAam26cyUb48bJziz1V6wvW7z4GZAfaJpzLkyHdSfV5117VSf5w1rDcAeZDXfGUaaNEJPWytaF4ZIxVge7f3NGshHy4odFVPADy\/u6c43BWvaOtJ4m3aJQbP6sxCO9dxwcm5yJJJR3n36jfh229sdWBxyl8BhwhH1e1DEv78\/aiL6ckKFPVNzx01R6yDFt3TgEMR97YZ\/R6lWiXG+dsJ305jNFlusLu518zBUvl7g5yjzGN778H29b2C8VLZKmi\/h1CH9jGdD72fCqCYdenD2uZKzb6dsUtXtvBmVcVT6BUGz41W1pkkEEB+YJpMrHILIxAiHRGv1+aZa9\/Oz8LWFd+BEUQjC2LJgojPnpzaG\/msw1nBkX16NNVDWWtJ25Bc\/r\/mG46rwjWB\/cmV6Lwt6KODiqlxgrC4lm9ALOCEWw+23OcYhLwNfQTYevXqHqsFfXOkhUnM8z5vDUb\/HBraB1DjFXN8iLK+1YewD4P495e+SRzrR79Oi3F8SEqRIzRLfN2rnW1BTms\/wYsz0p67cup1Slk1XlNmHwbWX25NVd2PPlLOvZRGoqcKFpIjC5few8THiZfyjiNFwt3RM0AFdZcXY=",
- "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----"
-}';
- $this->environmentHelper
- ->expects($this->any())
- ->method('getServerRoot')
- ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/app/');
- $this->fileAccessHelper
- ->expects($this->once())
- ->method('file_put_contents')
- ->with(
- \OC::$SERVERROOT . '/tests/data/integritycheck/app//core/signature.json',
- $this->callback(function ($signature) use ($expectedSignatureFileData) {
- $expectedArray = json_decode($expectedSignatureFileData, true);
- $actualArray = json_decode($signature, true);
- $this->assertEquals($expectedArray, $actualArray);
- return true;
- })
- );
-
- $keyBundle = file_get_contents(__DIR__ .'/../../data/integritycheck/core.crt');
- $rsaPrivateKey = file_get_contents(__DIR__ .'/../../data/integritycheck/core.key');
- $rsa = new RSA();
- $rsa->loadKey($rsaPrivateKey);
- $x509 = new X509();
- $x509->loadX509($keyBundle);
- $this->checker->writeCoreSignature($x509, $rsa, \OC::$SERVERROOT . '/tests/data/integritycheck/app/');
- }
-
- public function testWriteCoreSignatureWithUnmodifiedHtaccess() {
- $expectedSignatureFileData = '{
- "hashes": {
- ".htaccess": "dc479770a6232061e04a768ee1f9133fdb3aea7b3a99f7105b0e0b6197474733e8d14b5b2bbad054e6b62a410fe5d0b3d790242dee1e0f11274af2100f5289e2",
- "subfolder\/.htaccess": "2c57b1e25050e11dc3ae975832f378c452159f7b69f818e47eeeafadd6ba568517461dcb4d843b90b906cd7c89d161bc1b89dff8e3ae0eb6f5088508c47befd1"
- },
- "signature": "nRtR377DB\/I\/4hmh9q3elMQYfSHnQFlNtjchNgrdfmUQqVmgkU\/4qgGyxDqYkV8mSMbH2gYysfP42nx\/3zSo7n0dBYDfU87Q6f96Cv597vEV27do8CaBkEk8Xjn2SxhHw8hVxracvE2OBAPxk0H3sRp\/cQBgjoXpju4kQin0N5E+DEJMh7Sp+u8aKoFpb+2FaAZJFn\/hnqxLTlVi2nyDxGL3U0eobWY+jWH9XPt52v3Hyh8TDhcAnQ1cN30B8Jn2+jkrm8ib+buchaCXHk0cPX72xuPECdwOEKLCBNrJa3FGSvO1zWiecnCgxCXgt+R8hUgsVPTsbrdFY2YRJGIhHndYZL98XzgG7cw85SnnMMe2SulzeL7xANGF8qiEVyiC7x83bbj5xOkeM\/CUTajrLBO3vyZ23KKOxvskjgI0t+Zw1zFsl+sYW0\/O\/V5WzPOwMwV8+iApQ8k9gEMiYQg98QLEMYnSohncmp0Z9qx2qFcQuHLcKJVa1J6wGtE\/EHR\/4d0aYPd6IRjg+qshCJmdzud\/12xjpGTl+BT0Hi0VsU5o7ZMi7WhmukZmmv8u0uZsvKREQNATm4cO4WCkYySt5O9gZEJOF+jjgeynDoAh09lyrNXIgMpM9ufm\/XEG\/I\/f2zIwbAUc6J6qks5OuYlJzW5vscTiOKhwcGZU9WBLgh0=",
- "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----"
-}';
- $this->environmentHelper
- ->expects($this->any())
- ->method('getServerRoot')
- ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/htaccessUnmodified/');
- $this->fileAccessHelper
- ->expects($this->once())
- ->method('file_put_contents')
- ->with(
- \OC::$SERVERROOT . '/tests/data/integritycheck/htaccessUnmodified//core/signature.json',
- $this->callback(function ($signature) use ($expectedSignatureFileData) {
- $expectedArray = json_decode($expectedSignatureFileData, true);
- $actualArray = json_decode($signature, true);
- $this->assertEquals($expectedArray, $actualArray);
- return true;
- })
- );
-
- $keyBundle = file_get_contents(__DIR__ .'/../../data/integritycheck/core.crt');
- $rsaPrivateKey = file_get_contents(__DIR__ .'/../../data/integritycheck/core.key');
- $rsa = new RSA();
- $rsa->loadKey($rsaPrivateKey);
- $x509 = new X509();
- $x509->loadX509($keyBundle);
- $this->checker->writeCoreSignature($x509, $rsa, \OC::$SERVERROOT . '/tests/data/integritycheck/htaccessUnmodified/');
- }
-
- public function testWriteCoreSignatureWithInvalidModifiedHtaccess() {
- $expectedSignatureFileData = '{
- "hashes": {
- ".htaccess": "4a54273dc8d697b2ca615acf2ae2c1ee3c1c643492cb04f42b10984fa9aacff1420dc829fd82f93ad3476fbd0cdab0251142c887dc8f872d03e39a3a3eb6d381"
- },
- "signature": "qpDddYGgAKNR3TszOgjPXRphUl2P9Ym5OQaetltocgZASGDkOun5D64+1D0QJRKb4SG2+48muxGOHyL2Ngos4NUrrSR+SIkywZacay82YQBCEdr7\/4MjW1WHRPjvboLwEJwViw0EdAjsWRpD68aPnzUGrGsy2BsCo06P5iwjk9cXcHxdjC9R39npvoC3QNvQ2jmNIbh1Lc4U97dbb+CsXEQCLU1OSa9p3q6cEFV98Easwt7uF\/DzHK+CbeZlxVZ0DwLh2\/ylT1PyGou8QC1b3vKAnPjLWMO+UsCPpCKhk3C5pV+5etQ8puGd+0x2t5tEU+qXxLzek91zWNC+rqgC\/WlqLKbwPb\/BCHs4zLGV55Q2fEQmT21x0KCUELdPs4dBnYP4Ox5tEDugtJujWFzOHzoY6gGa\/BY\/78pSZXmq9o8dWkBEtioWWvaNZ1rM0ddE83GBlBTgjigi9Ay1D++bUW\/FCBB7CMk6qyNlV81H+cBuIEODw2aymmkM9LLDD2Qbmvo8gHEPRjiQxPC5OpDlcdSNiL+zcxVxeuX4FpT+9xzz\/\/DRONhufxRpsbuCOMxd96RW7y9U2N2Uxb3Bzn\/BIqEayUUsdgZjfaGcXXYKR+chu\/LOwNYN6RlnLsgqL\/dhGKwlRVKXw1RA2\/af\/CpqyR7uVP6al1YJo\/YJ+5XJ6zE=",
- "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----"
-}';
- $this->fileAccessHelper
- ->expects($this->once())
- ->method('file_put_contents')
- ->with(
- \OC::$SERVERROOT . '/tests/data/integritycheck/htaccessWithInvalidModifiedContent//core/signature.json',
- $this->callback(function ($signature) use ($expectedSignatureFileData) {
- $expectedArray = json_decode($expectedSignatureFileData, true);
- $actualArray = json_decode($signature, true);
- $this->assertEquals($expectedArray, $actualArray);
- return true;
- })
- );
-
- $keyBundle = file_get_contents(__DIR__ .'/../../data/integritycheck/core.crt');
- $rsaPrivateKey = file_get_contents(__DIR__ .'/../../data/integritycheck/core.key');
- $rsa = new RSA();
- $rsa->loadKey($rsaPrivateKey);
- $x509 = new X509();
- $x509->loadX509($keyBundle);
- $this->checker->writeCoreSignature($x509, $rsa, \OC::$SERVERROOT . '/tests/data/integritycheck/htaccessWithInvalidModifiedContent/');
- }
-
- public function testWriteCoreSignatureWithValidModifiedHtaccess() {
- $expectedSignatureFileData = '{
- "hashes": {
- ".htaccess": "7e6a7a4d8ee4f3fbc45dd579407c643471575a9d127d1c75f6d0a49e80766c3c587104b2139ef76d2a4bffce3f45777900605aaa49519c9532909b71e5030227",
- "subfolder\/.htaccess": "2c57b1e25050e11dc3ae975832f378c452159f7b69f818e47eeeafadd6ba568517461dcb4d843b90b906cd7c89d161bc1b89dff8e3ae0eb6f5088508c47befd1"
- },
- "signature": "YVwQvl9Dh8UebCumfgzFxfz3NiZJLmYG8oJVTfEBhulI4KXBnTG1jZTprf4XxG2XIriEYAZXsoXpu9xWsUFe9QfdncwoEpqJtGq7l6aVDTofX5Be5b03MQFJr4cflgllqW77QZ84D9O9qWF\/vNDAofXcwrzT04CxLDhyQgTCgYUnRjG9pnuP\/gtbDKbTjRvxhTyfg3T0Phv1+XAvpTPnH2q5A+1+LmiqziUJ1sMipsKo+jQP614eCi9qjmqhHIgLRgcuOBvsi4g5WUcdcAIZ6qLt5gm2Y3r6rKNVchosU9ZydMUTfjuejDbVwE2fNH5UUnV57fQBxwg9CfX7iFHqKv1bfv5Zviu12paShgWCB12uR3iH\/3lmTJn8K5Xqit3G4eymFaJ5IChdUThBp\/jhQSI2r8sPcZDYSJ\/UZKuFnezFdKhEBd5hMXe8aKAd6ijGDjLARksFuqpi1sS8llC5K1Q+DzktSL\/o64TY4Vuvykiwe\/BAk2SkL9voOtrvU7vfDBcuCPbDJnSBBC0ESpcXeClTBIn6xZ9WaxqoS7sinE\/kUwtWsRd04I7d79\/ouotyNb+mBhTuRsZT12p\/gn4JHXXNUAIpTwchYzGxbfNJ4kxnYBFZWVmvsSqOLFZu1yi5BP3ktA9yhFyWIa5659azRFEKRdXpVHtQVa4IgdhxEqA=",
- "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----"
-}';
- $this->environmentHelper
- ->expects($this->any())
- ->method('getServerRoot')
- ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/htaccessWithValidModifiedContent');
- $this->fileAccessHelper
- ->expects($this->once())
- ->method('file_put_contents')
- ->with(
- \OC::$SERVERROOT . '/tests/data/integritycheck/htaccessWithValidModifiedContent/core/signature.json',
- $this->callback(function ($signature) use ($expectedSignatureFileData) {
- $expectedArray = json_decode($expectedSignatureFileData, true);
- $actualArray = json_decode($signature, true);
- $this->assertEquals($expectedArray, $actualArray);
- return true;
- })
- );
-
- $keyBundle = file_get_contents(__DIR__ .'/../../data/integritycheck/core.crt');
- $rsaPrivateKey = file_get_contents(__DIR__ .'/../../data/integritycheck/core.key');
- $rsa = new RSA();
- $rsa->loadKey($rsaPrivateKey);
- $x509 = new X509();
- $x509->loadX509($keyBundle);
- $this->checker->writeCoreSignature($x509, $rsa, \OC::$SERVERROOT . '/tests/data/integritycheck/htaccessWithValidModifiedContent');
- }
-
- public function testVerifyCoreSignatureWithoutSignatureData() {
- $this->environmentHelper
- ->expects($this->once())
- ->method('getChannel')
- ->willReturn('stable');
- $this->config
- ->expects($this->any())
- ->method('getSystemValueBool')
- ->with('integrity.check.disabled', false)
- ->willReturn(false);
-
- $expected = [
- 'EXCEPTION' => [
- 'class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class,
- 'message' => 'Signature data not found.',
- ],
- ];
- $this->assertSame($expected, $this->checker->verifyCoreSignature());
- }
-
- public function testVerifyCoreSignatureWithValidSignatureData() {
- $this->environmentHelper
- ->expects($this->once())
- ->method('getChannel')
- ->willReturn('stable');
- $this->config
- ->expects($this->any())
- ->method('getSystemValueBool')
- ->with('integrity.check.disabled', false)
- ->willReturn(false);
-
- $this->environmentHelper
- ->expects($this->any())
- ->method('getServerRoot')
- ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/app/');
- $signatureDataFile = '{
- "hashes": {
- "AnotherFile.txt": "1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112",
- "subfolder\/file.txt": "410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b"
- },
- "signature": "dYoohBaWIFR\/To1FXEbMQB5apUhVYlEauBGSPo12nq84wxWkBx2EM3KDRgkB5Sub2tr0CgmAc2EVjPhKIEzAam26cyUb48bJziz1V6wvW7z4GZAfaJpzLkyHdSfV5117VSf5w1rDcAeZDXfGUaaNEJPWytaF4ZIxVge7f3NGshHy4odFVPADy\/u6c43BWvaOtJ4m3aJQbP6sxCO9dxwcm5yJJJR3n36jfh229sdWBxyl8BhwhH1e1DEv78\/aiL6ckKFPVNzx01R6yDFt3TgEMR97YZ\/R6lWiXG+dsJ305jNFlusLu518zBUvl7g5yjzGN778H29b2C8VLZKmi\/h1CH9jGdD72fCqCYdenD2uZKzb6dsUtXtvBmVcVT6BUGz41W1pkkEEB+YJpMrHILIxAiHRGv1+aZa9\/Oz8LWFd+BEUQjC2LJgojPnpzaG\/msw1nBkX16NNVDWWtJ25Bc\/r\/mG46rwjWB\/cmV6Lwt6KODiqlxgrC4lm9ALOCEWw+23OcYhLwNfQTYevXqHqsFfXOkhUnM8z5vDUb\/HBraB1DjFXN8iLK+1YewD4P495e+SRzrR79Oi3F8SEqRIzRLfN2rnW1BTms\/wYsz0p67cup1Slk1XlNmHwbWX25NVd2PPlLOvZRGoqcKFpIjC5few8THiZfyjiNFwt3RM0AFdZcXY=",
- "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----"
-}';
- $this->fileAccessHelper
- ->expects($this->exactly(2))
- ->method('file_get_contents')
- ->withConsecutive(
- [\OC::$SERVERROOT . '/tests/data/integritycheck/app//core/signature.json'],
- [\OC::$SERVERROOT . '/tests/data/integritycheck/app//resources/codesigning/root.crt'],
- )->willReturnOnConsecutiveCalls(
- $signatureDataFile,
- file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')
- );
-
- $this->assertSame([], $this->checker->verifyCoreSignature());
- }
-
- public function testVerifyCoreSignatureWithValidModifiedHtaccessSignatureData() {
- $this->environmentHelper
- ->expects($this->once())
- ->method('getChannel')
- ->willReturn('stable');
- $this->config
- ->expects($this->any())
- ->method('getSystemValueBool')
- ->with('integrity.check.disabled', false)
- ->willReturn(false);
-
- $this->environmentHelper
- ->expects($this->any())
- ->method('getServerRoot')
- ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/htaccessWithValidModifiedContent');
- $signatureDataFile = '{
- "hashes": {
- ".htaccess": "7e6a7a4d8ee4f3fbc45dd579407c643471575a9d127d1c75f6d0a49e80766c3c587104b2139ef76d2a4bffce3f45777900605aaa49519c9532909b71e5030227",
- "subfolder\/.htaccess": "2c57b1e25050e11dc3ae975832f378c452159f7b69f818e47eeeafadd6ba568517461dcb4d843b90b906cd7c89d161bc1b89dff8e3ae0eb6f5088508c47befd1"
- },
- "signature": "YVwQvl9Dh8UebCumfgzFxfz3NiZJLmYG8oJVTfEBhulI4KXBnTG1jZTprf4XxG2XIriEYAZXsoXpu9xWsUFe9QfdncwoEpqJtGq7l6aVDTofX5Be5b03MQFJr4cflgllqW77QZ84D9O9qWF\/vNDAofXcwrzT04CxLDhyQgTCgYUnRjG9pnuP\/gtbDKbTjRvxhTyfg3T0Phv1+XAvpTPnH2q5A+1+LmiqziUJ1sMipsKo+jQP614eCi9qjmqhHIgLRgcuOBvsi4g5WUcdcAIZ6qLt5gm2Y3r6rKNVchosU9ZydMUTfjuejDbVwE2fNH5UUnV57fQBxwg9CfX7iFHqKv1bfv5Zviu12paShgWCB12uR3iH\/3lmTJn8K5Xqit3G4eymFaJ5IChdUThBp\/jhQSI2r8sPcZDYSJ\/UZKuFnezFdKhEBd5hMXe8aKAd6ijGDjLARksFuqpi1sS8llC5K1Q+DzktSL\/o64TY4Vuvykiwe\/BAk2SkL9voOtrvU7vfDBcuCPbDJnSBBC0ESpcXeClTBIn6xZ9WaxqoS7sinE\/kUwtWsRd04I7d79\/ouotyNb+mBhTuRsZT12p\/gn4JHXXNUAIpTwchYzGxbfNJ4kxnYBFZWVmvsSqOLFZu1yi5BP3ktA9yhFyWIa5659azRFEKRdXpVHtQVa4IgdhxEqA=",
- "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----"
-}';
- $this->fileAccessHelper
- ->expects($this->exactly(2))
- ->method('file_get_contents')
- ->withConsecutive(
- [\OC::$SERVERROOT . '/tests/data/integritycheck/htaccessWithValidModifiedContent/core/signature.json'],
- [\OC::$SERVERROOT . '/tests/data/integritycheck/htaccessWithValidModifiedContent/resources/codesigning/root.crt'],
- )
- ->willReturnOnConsecutiveCalls(
- $signatureDataFile,
- file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')
- );
-
- $this->assertSame([], $this->checker->verifyCoreSignature());
- }
-
- /**
- * See inline instruction on how to update the test assets when changing mimetypealiases.dist.json
- */
- public function testVerifyCoreSignatureWithModifiedMimetypelistSignatureData() {
- $shippedMimetypeAliases = (array)json_decode(file_get_contents(\OC::$SERVERROOT . '/resources/config/mimetypealiases.dist.json'));
- $allAliases = array_merge($shippedMimetypeAliases, ['my-custom/mimetype' => 'custom']);
-
- $this->mimeTypeDetector
- ->method('getOnlyDefaultAliases')
- ->willReturn($shippedMimetypeAliases);
-
- $this->mimeTypeDetector
- ->method('getAllAliases')
- ->willReturn($allAliases);
-
- $oldMimetypeList = new GenerateMimetypeFileBuilder();
- $all = $this->mimeTypeDetector->getAllAliases();
- $newFile = $oldMimetypeList->generateFile($all);
-
- // 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:
- // file_put_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/mimetypeListModified/core/js/mimetypelist.js', $newFile);
- // 2. Update signature.json using the following occ command:
- // occ integrity:sign-core --privateKey=./tests/data/integritycheck/core.key --certificate=./tests/data/integritycheck/core.crt --path=./tests/data/integritycheck/mimetypeListModified
- self::assertEquals($newFile, file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/mimetypeListModified/core/js/mimetypelist.js'));
-
- $this->environmentHelper
- ->expects($this->once())
- ->method('getChannel')
- ->willReturn('stable');
- $this->config
- ->expects($this->any())
- ->method('getSystemValueBool')
- ->with('integrity.check.disabled', false)
- ->willReturn(false);
-
- $this->environmentHelper
- ->expects($this->any())
- ->method('getServerRoot')
- ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/mimetypeListModified');
-
- $signatureDataFile = file_get_contents(__DIR__ .'/../../data/integritycheck/mimetypeListModified/core/signature.json');
- $this->fileAccessHelper
- ->method('file_get_contents')
- ->willReturnMap([
- [\OC::$SERVERROOT . '/tests/data/integritycheck/mimetypeListModified/core/signature.json', $signatureDataFile],
- [\OC::$SERVERROOT . '/tests/data/integritycheck/mimetypeListModified/resources/codesigning/root.crt', file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')],
- ]);
-
- $this->assertSame([], $this->checker->verifyCoreSignature());
- }
-
- public function testVerifyCoreSignatureWithValidSignatureDataAndNotAlphabeticOrder() {
- $this->environmentHelper
- ->expects($this->once())
- ->method('getChannel')
- ->willReturn('stable');
- $this->config
- ->expects($this->any())
- ->method('getSystemValueBool')
- ->with('integrity.check.disabled', false)
- ->willReturn(false);
-
- $this->environmentHelper
- ->expects($this->any())
- ->method('getServerRoot')
- ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/app/');
- $signatureDataFile = '{
- "hashes": {
- "AnotherFile.txt": "1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112",
- "subfolder\/file.txt": "410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b"
- },
- "signature": "dYoohBaWIFR\/To1FXEbMQB5apUhVYlEauBGSPo12nq84wxWkBx2EM3KDRgkB5Sub2tr0CgmAc2EVjPhKIEzAam26cyUb48bJziz1V6wvW7z4GZAfaJpzLkyHdSfV5117VSf5w1rDcAeZDXfGUaaNEJPWytaF4ZIxVge7f3NGshHy4odFVPADy\/u6c43BWvaOtJ4m3aJQbP6sxCO9dxwcm5yJJJR3n36jfh229sdWBxyl8BhwhH1e1DEv78\/aiL6ckKFPVNzx01R6yDFt3TgEMR97YZ\/R6lWiXG+dsJ305jNFlusLu518zBUvl7g5yjzGN778H29b2C8VLZKmi\/h1CH9jGdD72fCqCYdenD2uZKzb6dsUtXtvBmVcVT6BUGz41W1pkkEEB+YJpMrHILIxAiHRGv1+aZa9\/Oz8LWFd+BEUQjC2LJgojPnpzaG\/msw1nBkX16NNVDWWtJ25Bc\/r\/mG46rwjWB\/cmV6Lwt6KODiqlxgrC4lm9ALOCEWw+23OcYhLwNfQTYevXqHqsFfXOkhUnM8z5vDUb\/HBraB1DjFXN8iLK+1YewD4P495e+SRzrR79Oi3F8SEqRIzRLfN2rnW1BTms\/wYsz0p67cup1Slk1XlNmHwbWX25NVd2PPlLOvZRGoqcKFpIjC5few8THiZfyjiNFwt3RM0AFdZcXY=",
- "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----"
-}';
- $this->fileAccessHelper
- ->expects($this->exactly(2))
- ->method('file_get_contents')
- ->withConsecutive(
- [\OC::$SERVERROOT . '/tests/data/integritycheck/app//core/signature.json'],
- [\OC::$SERVERROOT . '/tests/data/integritycheck/app//resources/codesigning/root.crt'],
- )->willReturnOnConsecutiveCalls(
- $signatureDataFile,
- file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')
- );
-
- $this->assertSame([], $this->checker->verifyCoreSignature());
- }
-
- public function testVerifyCoreSignatureWithTamperedSignatureData() {
- $this->environmentHelper
- ->expects($this->once())
- ->method('getChannel')
- ->willReturn('stable');
- $this->config
- ->expects($this->any())
- ->method('getSystemValueBool')
- ->with('integrity.check.disabled', false)
- ->willReturn(false);
-
- $this->environmentHelper
- ->expects($this->any())
- ->method('getServerRoot')
- ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/appWithInvalidData/');
- $signatureDataFile = '{
- "hashes": {
- "AnotherFile.txt": "tampered",
- "subfolder\/file.txt": "tampered"
- },
- "signature": "eXesvDm3pkek12xSwMG10y9suRES79Nye3jYNe5KYq1tTUPqRRNgxmMGAfcUro0zpLeAr2YgHeSMWtglblGOW7pmwGVPZ0O1Y4r1fE6jnep0kW+35PLIaqCorIOnCAtSzDNKBhwd1ow3zW2wC0DFouuEkIO8u5Fw28g8E8dp8zEk1xMblNPy+xtWkmYHrVJ\/dQgun1bYOF2ZFtAzatwndTI\/bGsy1i3Wsl+x6HyWKQdq8y8VObtOqKDH7uERBEpB9DHVyKflj1v1gQuEH6BhaRdATc7ee0MiQdGblraIySwYRdfo2d8i82OVKrenMB3SLwyCvDPyQ9iKpTOnSF52ZBqaqSXKM2N\/RAkweeBFQQCwcHhqxvB0cfbyHcbkOLeCZe\/tsh68IxwTiYgzvLfl7sOZ5arnZbzrPpZmB+hfV2omkoJ1tDwOWz9hEmLLNtfo2OxyUH1m0+XFaC+Gbn4WkVDgf7YZkwUcG+Qoa3oKDNMss8MEyZxewl2iDGZcf402dlidHRprlfmXbAYuVQ08\/a0HxIKYPGh\/nsMGmwnO15CWtFpAbhUA\/D5oRjsIxnvXaMDg0iAFpdu\/5Ffsj7g3EPdBkiQHNYK7YU1RRx609eH0bZyiIYHdUPw7ikLupvrebZmELqi3mqDFO99u4eISlxFJlUbUND3L4BtmWTWrKwI=",
- "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----"
-}';
- $this->fileAccessHelper
- ->expects($this->exactly(2))
- ->method('file_get_contents')
- ->withConsecutive(
- [\OC::$SERVERROOT . '/tests/data/integritycheck/appWithInvalidData//core/signature.json'],
- [\OC::$SERVERROOT . '/tests/data/integritycheck/appWithInvalidData//resources/codesigning/root.crt'],
- )->willReturnOnConsecutiveCalls(
- $signatureDataFile,
- file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')
- );
-
- $expected = [
- 'EXCEPTION' => [
- 'class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class,
- 'message' => 'Signature could not get verified.',
- ]
- ];
- $this->assertSame($expected, $this->checker->verifyCoreSignature());
- }
-
- public function testVerifyCoreSignatureWithTamperedFiles() {
- $this->environmentHelper
- ->expects($this->once())
- ->method('getChannel')
- ->willReturn('stable');
- $this->config
- ->expects($this->any())
- ->method('getSystemValueBool')
- ->with('integrity.check.disabled', false)
- ->willReturn(false);
-
- $this->environmentHelper
- ->expects($this->any())
- ->method('getServerRoot')
- ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/appWithInvalidData/');
- $signatureDataFile = '{
- "hashes": {
- "AnotherFile.txt": "1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112",
- "subfolder\/file.txt": "410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b"
- },
- "signature": "dYoohBaWIFR\/To1FXEbMQB5apUhVYlEauBGSPo12nq84wxWkBx2EM3KDRgkB5Sub2tr0CgmAc2EVjPhKIEzAam26cyUb48bJziz1V6wvW7z4GZAfaJpzLkyHdSfV5117VSf5w1rDcAeZDXfGUaaNEJPWytaF4ZIxVge7f3NGshHy4odFVPADy\/u6c43BWvaOtJ4m3aJQbP6sxCO9dxwcm5yJJJR3n36jfh229sdWBxyl8BhwhH1e1DEv78\/aiL6ckKFPVNzx01R6yDFt3TgEMR97YZ\/R6lWiXG+dsJ305jNFlusLu518zBUvl7g5yjzGN778H29b2C8VLZKmi\/h1CH9jGdD72fCqCYdenD2uZKzb6dsUtXtvBmVcVT6BUGz41W1pkkEEB+YJpMrHILIxAiHRGv1+aZa9\/Oz8LWFd+BEUQjC2LJgojPnpzaG\/msw1nBkX16NNVDWWtJ25Bc\/r\/mG46rwjWB\/cmV6Lwt6KODiqlxgrC4lm9ALOCEWw+23OcYhLwNfQTYevXqHqsFfXOkhUnM8z5vDUb\/HBraB1DjFXN8iLK+1YewD4P495e+SRzrR79Oi3F8SEqRIzRLfN2rnW1BTms\/wYsz0p67cup1Slk1XlNmHwbWX25NVd2PPlLOvZRGoqcKFpIjC5few8THiZfyjiNFwt3RM0AFdZcXY=",
- "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----"
-}';
- $this->fileAccessHelper
- ->expects($this->exactly(2))
- ->method('file_get_contents')
- ->withConsecutive(
- [\OC::$SERVERROOT . '/tests/data/integritycheck/appWithInvalidData//core/signature.json'],
- [\OC::$SERVERROOT . '/tests/data/integritycheck/appWithInvalidData//resources/codesigning/root.crt'],
- )->willReturnOnConsecutiveCalls(
- $signatureDataFile,
- file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')
- );
-
- $expected = [
- 'INVALID_HASH' => [
- 'AnotherFile.txt' => [
- 'expected' => '1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112',
- 'current' => '7322348ba269c6d5522efe02f424fa3a0da319a7cd9c33142a5afe32a2d9af2da3a411f086fcfc96ff4301ea566f481dba0960c2abeef3594c4d930462f6584c',
- ],
- ],
- 'FILE_MISSING' => [
- 'subfolder/file.txt' => [
- 'expected' => '410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b',
- 'current' => '',
- ],
- ],
- 'EXTRA_FILE' => [
- 'UnecessaryFile' => [
- 'expected' => '',
- 'current' => 'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e',
- ],
- ],
-
- ];
- $this->assertSame($expected, $this->checker->verifyCoreSignature());
- }
-
- public function testVerifyCoreWithInvalidCertificate() {
- $this->environmentHelper
- ->expects($this->once())
- ->method('getChannel')
- ->willReturn('stable');
- $this->config
- ->expects($this->any())
- ->method('getSystemValueBool')
- ->with('integrity.check.disabled', false)
- ->willReturn(false);
-
- $this->environmentHelper
- ->expects($this->any())
- ->method('getServerRoot')
- ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/app/');
- $signatureDataFile = '{
- "hashes": {
- "AnotherFile.txt": "1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112",
- "subfolder\/file.txt": "410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b"
- },
- "signature": "eXesvDm3pkek12xSwMG10y9suRES79Nye3jYNe5KYq1tTUPqRRNgxmMGAfcUro0zpLeAr2YgHeSMWtglblGOW7pmwGVPZ0O1Y4r1fE6jnep0kW+35PLIaqCorIOnCAtSzDNKBhwd1ow3zW2wC0DFouuEkIO8u5Fw28g8E8dp8zEk1xMblNPy+xtWkmYHrVJ\/dQgun1bYOF2ZFtAzatwndTI\/bGsy1i3Wsl+x6HyWKQdq8y8VObtOqKDH7uERBEpB9DHVyKflj1v1gQuEH6BhaRdATc7ee0MiQdGblraIySwYRdfo2d8i82OVKrenMB3SLwyCvDPyQ9iKpTOnSF52ZBqaqSXKM2N\/RAkweeBFQQCwcHhqxvB0cfbyHcbkOLeCZe\/tsh68IxwTiYgzvLfl7sOZ5arnZbzrPpZmB+hfV2omkoJ1tDwOWz9hEmLLNtfo2OxyUH1m0+XFaC+Gbn4WkVDgf7YZkwUcG+Qoa3oKDNMss8MEyZxewl2iDGZcf402dlidHRprlfmXbAYuVQ08\/a0HxIKYPGh\/nsMGmwnO15CWtFpAbhUA\/D5oRjsIxnvXaMDg0iAFpdu\/5Ffsj7g3EPdBkiQHNYK7YU1RRx609eH0bZyiIYHdUPw7ikLupvrebZmELqi3mqDFO99u4eISlxFJlUbUND3L4BtmWTWrKwI=",
- "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUPYoweUxCPqbDW4ntuh7QvgyqSrgwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIyNDIwNloXDTE2MTEwMzIyNDIwNlowDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBAJui3nDbjOIjxNnthdBZplphujsN6u8K\r\nQ\/62zAuSwzXVp0+3IMgM\/2sepklVE8YfCyVJ5+SUJqnqHoUWVRVfs8jL0wW6nrHM\r\n\/lsscAguWCee4iAdNOqI9kq4+DUau8J45e62XA9mrAo\/8\/NKzFE2y2WduDoQZcm+\r\n8+dwcUUHXw2jl8dfrmvEMYSqTNDdb4rGmQpeV+dr9BLqr+x03U1Q08qCG9j7mSOz\r\ncvJENjOvC5uzAh5LCuCgxqG4o+mPzB0FtNnwoRRu6IsF3Y3KacRqPc30fB\/iXDn5\r\nBPr14uNxTTYWoZJ1F0tZrLzRbXdjJJOC+dnQurTtXWZ8WjPB1BWQYK7fW6t82mkN\r\n2Qe2xen99gs9nX5yY\/sHM3TKSJdM7AVCEv\/emW3gNjkvWTtRlN\/Nc7X2ckNwXcvo\r\n0yi3fSPjzXpDgLbhp1FzrMlHDn1VzmRT3r8wLByWa\/hsxrJDsBzwunMJYhXhmeKb\r\n3wX0tN\/EUJTWBntpwVOIGnRPD51oBoQUOMaEAq\/kz8PgN181bWZkJbRuf+FWkijQ\r\no+HR2lVF1jWXXst5Uc+s9HN81Uly7X4O9MMg0QxT4+wymtGDs6AOkwMi9rgBTrRB\r\n3tLU3XL2UIwRXgmd8cPtTu\/I6Bm7LdyaYtZ3yJTxRewq3nZdWypqBhD8uhpIYVkf\r\no4bxmGkVAQVTAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAKKAX5EHgU1grODnJ0of\r\nspFpgB1K67YvclNUyuU6NQ6zBJx1\/w1RnM7uxLcxiiWj1BbUhwZQ0ojmEHeUyi6O\r\nGrDVajwhTccDMmja3u5adhEncx65\/H+lD85IPRRkS2qBDssMDdJHhZ0uI+40nI7M\r\nMq1kFjl+6wiuqZXqps66DuLbk45g\/ZlrFIrIo3Ix5vj0OVqwT+gO4LYirJK6KgVS\r\nUttbcEsc\/yKU9ThnM8\/n4m2jstZXfzKPgOsJrQcZrFOtpj+CWmBzVElBSPlDT3Nh\r\nHSgOeTFJ8bQBxj2iG5dLA+JZJQKxyJ1gy2ZtxIJ2GyvLtSe8NUSqvfPWOaAKEUV2\r\ngniytnEFLr+PcD+9EGux6jZNuj6HmtWVThTfD5VGFmtlVU2z71ZRYY0kn6J3mmFc\r\nS2ecEcCUwqG5YNLncEUCyZhC2klWql2SHyGctCEyWWY7ikIDjVzYt2EbcFvLNBnP\r\ntybN1TYHRRZxlug00CCoOE9EZfk46FkZpDvU6KmqJRofkNZ5sj+SffyGcwYwNrDH\r\nKqe8m+9lHf3CRTIDeMu8r2xl1I6M6ZZfjabbmVP9Jd6WN4s6f1FlXDWzhlT1N0Qw\r\nGzJj6xB+SPtS3UV05tBlvbfA4e06D5G9uD7Q8ONcINtMS0xsSJ2oo82AqlpvlF\/q\r\noj7YKHsaTVGA+FxBktZHfoxD\r\n-----END CERTIFICATE-----"
-}';
- $this->fileAccessHelper
- ->expects($this->exactly(2))
- ->method('file_get_contents')
- ->withConsecutive(
- [\OC::$SERVERROOT . '/tests/data/integritycheck/app//core/signature.json'],
- [\OC::$SERVERROOT . '/tests/data/integritycheck/app//resources/codesigning/root.crt'],
- )->willReturnOnConsecutiveCalls(
- $signatureDataFile,
- file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')
- );
-
- $expected = [
- 'EXCEPTION' => [
- 'class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class,
- 'message' => 'Certificate is not valid.',
- ]
- ];
- $this->assertSame($expected, $this->checker->verifyCoreSignature());
- }
-
- public function testVerifyCoreWithDifferentScope() {
- $this->environmentHelper
- ->expects($this->once())
- ->method('getChannel')
- ->willReturn('stable');
- $this->config
- ->expects($this->any())
- ->method('getSystemValueBool')
- ->with('integrity.check.disabled', false)
- ->willReturn(false);
-
- $this->environmentHelper
- ->expects($this->any())
- ->method('getServerRoot')
- ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/app/');
- $signatureDataFile = '{
- "hashes": {
- "AnotherFile.txt": "1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112",
- "subfolder\/file.txt": "410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b"
- },
- "signature": "EL49UaSeyMAqyMtqId+tgOhhwgOevPZsRLX4j2blnybAB6fN07z0936JqZV7+eMPiE30Idx+UCY6rCFN531Kqe9vAOCdgtHUSOjjKyKc+lvULESlMb6YQcrZrvDlEMMjzjH49ewG7Ai8sNN6HrRUd9U8ws+ewSkW2DOOBItj\/21RBnkrSt+2AtGXGigEvuTm57HrCYDj8\/lSkumC2GVkjLUHeLOKYo4PRNOr6yP5mED5v7zo66AWvXl2fKv54InZcdxsAk35lyK9DGZbk\/027ZRd0AOHT3LImRLvQ+8EAg3XLlRUy0hOFGgPC+jYonMzgYvsAXAXi2j8LnLJlsLwpFwu1k1B+kZVPMumKZvP9OvJb70EirecXmz62V+Jiyuaq7ne4y7Kp5gKZT\/T8SeZ0lFtCmPfYyzBB0y8s5ldmTTmdVYHs54t\/OCCW82HzQZxnFNPzDTRa8HglsaMKrqPtW59+R4UvRKSWhB8M\/Ah57qgzycvPV4KMz\/FbD4l\/\/9chRKSlCfc2k3b8ZSHNmi+EzCKgJjWIoKdgN1yax94puU8jfn8UW+G7H9Y1Jsf\/jox6QLyYEgtV1vOHY2xLT7fVs2vhyvkN2MNjJnmQ70gFG5Qz2lBz5wi6ZpB+tOfCcpbLxWAkoWoIrmC\/Ilqh7mfmRZ43g5upjkepHNd93ONuY8=",
- "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEwTCCAqmgAwIBAgIUWv0iujufs5lUr0svCf\/qTQvoyKAwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIyNDk1M1oXDTE2MTEwMzIyNDk1M1owEjEQMA4GA1UEAwwHU29tZUFwcDCCAiIw\r\nDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK8q0x62agGSRBqeWsaeEwFfepMk\r\nF8cAobMMi50qHCv9IrOn\/ZH9l52xBrbIkErVmRjmly0d4JhD8Ymhidsh9ONKYl\/j\r\n+ishsZDM8eNNdp3Ew+fEYVvY1W7mR1qU24NWj0bzVsClI7hvPVIuw7AjfBDq1C5+\r\nA+ZSLSXYvOK2cEWjdxQfuNZwEZSjmA63DUllBIrm35IaTvfuyhU6BW9yHZxmb8+M\r\nw0xDv30D5UkE\/2N7Pa\/HQJLxCR+3zKibRK3nUyRDLSXxMkU9PnFNaPNX59VPgyj4\r\nGB1CFSToldJVPF4pzh7p36uGXZVxs8m3LFD4Ol8mhi7jkxDZjqFN46gzR0r23Py6\r\ndol9vfawGIoUwp9LvL0S7MvdRY0oazLXwClLP4OQ17zpSMAiCj7fgNT661JamPGj\r\nt5O7Zn2wA7I4ddDS\/HDTWCu98Zwc9fHIpsJPgCZ9awoqxi4Mnf7Pk9g5nnXhszGC\r\ncxxIASQKM+GhdzoRxKknax2RzUCwCzcPRtCj8AQT\/x\/mqN3PfRmlnFBNACUw9bpZ\r\nSOoNq2pCF9igftDWpSIXQ38pVpKLWowjjg3DVRmVKBgivHnUnVLyzYBahHPj0vaz\r\ntFtUFRaqXDnt+4qyUGyrT5h5pjZaTcHIcSB4PiarYwdVvgslgwnQzOUcGAzRWBD4\r\n6jV2brP5vFY3g6iPAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBACTY3CCHC+Z28gCf\r\nFWGKQ3wAKs+k4+0yoti0qm2EKX7rSGQ0PHSas6uW79WstC4Rj+DYkDtIhGMSg8FS\r\nHVGZHGBCc0HwdX+BOAt3zi4p7Sf3oQef70\/4imPoKxbAVCpd\/cveVcFyDC19j1yB\r\nBapwu87oh+muoeaZxOlqQI4UxjBlR\/uRSMhOn2UGauIr3dWJgAF4pGt7TtIzt+1v\r\n0uA6FtN1Y4R5O8AaJPh1bIG0CVvFBE58esGzjEYLhOydgKFnEP94kVPgJD5ds9C3\r\npPhEpo1dRpiXaF7WGIV1X6DI\/ipWvfrF7CEy6I\/kP1InY\/vMDjQjeDnJ\/VrXIWXO\r\nyZvHXVaN\/m+1RlETsH7YO\/QmxRue9ZHN3gvvWtmpCeA95sfpepOk7UcHxHZYyQbF\r\n49\/au8j+5tsr4A83xzsT1JbcKRxkAaQ7WDJpOnE5O1+H0fB+BaLakTg6XX9d4Fo7\r\n7Gin7hVWX7pL+JIyxMzME3LhfI61+CRcqZQIrpyaafUziPQbWIPfEs7h8tCOWyvW\r\nUO8ZLervYCB3j44ivkrxPlcBklDCqqKKBzDP9dYOtS\/P4RB1NkHA9+NTvmBpTonS\r\nSFXdg9fFMD7VfjDE3Vnk+8DWkVH5wBYowTAD7w9Wuzr7DumiAULexnP\/Y7xwxLv7\r\n4B+pXTAcRK0zECDEaX3npS8xWzrB\r\n-----END CERTIFICATE-----"
-}';
- $this->fileAccessHelper
- ->expects($this->exactly(2))
- ->method('file_get_contents')
- ->withConsecutive(
- [\OC::$SERVERROOT . '/tests/data/integritycheck/app//core/signature.json'],
- [\OC::$SERVERROOT . '/tests/data/integritycheck/app//resources/codesigning/root.crt'],
- )->willReturnOnConsecutiveCalls(
- $signatureDataFile,
- file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')
- );
-
- $expected = [
- 'EXCEPTION' => [
- 'class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class,
- 'message' => 'Certificate is not valid for required scope. (Requested: core, current: CN=SomeApp)',
- ]
- ];
- $this->assertSame($expected, $this->checker->verifyCoreSignature());
- }
-
- public function testRunInstanceVerification() {
- $this->checker = $this->getMockBuilder(\OC\IntegrityCheck\Checker::class)
- ->setConstructorArgs([
- $this->environmentHelper,
- $this->fileAccessHelper,
- $this->appLocator,
- $this->config,
- $this->appConfig,
- $this->cacheFactory,
- $this->appManager,
- $this->mimeTypeDetector,
- ])
- ->setMethods([
- 'verifyCoreSignature',
- 'verifyAppSignature',
- ])
- ->getMock();
-
- $this->checker
- ->expects($this->once())
- ->method('verifyCoreSignature');
- $this->appManager
- ->expects($this->once())
- ->method('getAllAppsInAppsFolders')
- ->willReturn([
- 'files',
- 'calendar',
- 'contacts',
- 'dav',
- ]);
- $this->appManager
- ->expects($this->exactly(4))
- ->method('isShipped')
- ->withConsecutive(
- ['files'],
- ['calendar'],
- ['contacts'],
- ['dav'],
- )->willReturnOnConsecutiveCalls(
- true,
- false,
- false,
- true,
- );
- $this->checker
- ->expects($this->exactly(3))
- ->method('verifyAppSignature')
- ->withConsecutive(
- ['files'],
- ['calendar'],
- ['dav'],
- );
- $this->appLocator
- ->expects($this->exactly(2))
- ->method('getAppPath')
- ->withConsecutive(
- ['calendar'],
- ['contacts'],
- )->willReturnOnConsecutiveCalls(
- '/apps/calendar',
- '/apps/contacts',
- );
- $this->fileAccessHelper
- ->expects($this->exactly(2))
- ->method('file_exists')
- ->withConsecutive(
- ['/apps/calendar/appinfo/signature.json'],
- ['/apps/contacts/appinfo/signature.json'],
- )->willReturnOnConsecutiveCalls(
- true,
- false,
- );
- $this->appConfig
- ->expects($this->once())
- ->method('deleteKey')
- ->with('core', 'oc.integritycheck.checker');
-
- $this->checker->runInstanceVerification();
- }
-
- public function testVerifyAppSignatureWithoutSignatureDataAndCodeCheckerDisabled() {
- $this->environmentHelper
- ->expects($this->once())
- ->method('getChannel')
- ->willReturn('stable');
- $this->config
- ->expects($this->any())
- ->method('getSystemValueBool')
- ->with('integrity.check.disabled', false)
- ->willReturn(true);
-
- $expected = [];
- $this->assertSame($expected, $this->checker->verifyAppSignature('SomeApp'));
- }
-
- /**
- * @return array
- */
- public function channelDataProvider() {
- return [
- ['stable', true],
- ['git', false],
- ];
- }
-
- /**
- * @param string $channel
- * @param bool $isCodeSigningEnforced
- * @dataProvider channelDataProvider
- */
- public function testIsCodeCheckEnforced($channel, $isCodeSigningEnforced) {
- $this->environmentHelper
- ->expects($this->once())
- ->method('getChannel')
- ->willReturn($channel);
- $this->config
- ->expects($this->any())
- ->method('getSystemValueBool')
- ->with('integrity.check.disabled', false)
- ->willReturn(false);
-
- $this->assertSame($isCodeSigningEnforced, $this->checker->isCodeCheckEnforced());
- }
-
- /**
- * @param string $channel
- * @dataProvider channelDataProvider
- */
- public function testIsCodeCheckEnforcedWithDisabledConfigSwitch($channel) {
- $this->environmentHelper
- ->expects($this->once())
- ->method('getChannel')
- ->willReturn($channel);
- $this->config
- ->expects($this->any())
- ->method('getSystemValueBool')
- ->with('integrity.check.disabled', false)
- ->willReturn(true);
-
- $this->assertFalse(self::invokePrivate($this->checker, 'isCodeCheckEnforced'));
- }
-}
+<?php
+/**
+ * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
+ */
+
+namespace Test\IntegrityCheck;
+
+use OC\Core\Command\Maintenance\Mimetype\GenerateMimetypeFileBuilder;
+use OC\IntegrityCheck\Checker;
+use OC\IntegrityCheck\Helpers\AppLocator;
+use OC\IntegrityCheck\Helpers\EnvironmentHelper;
+use OC\IntegrityCheck\Helpers\FileAccessHelper;
+use OC\Memcache\NullCache;
+use OCP\App\IAppManager;
+use OCP\IAppConfig;
+use OCP\ICacheFactory;
+use OCP\IConfig;
+use phpseclib\Crypt\RSA;
+use phpseclib\File\X509;
+use Test\TestCase;
+
+class CheckerTest extends TestCase {
+ /** @var EnvironmentHelper|\PHPUnit\Framework\MockObject\MockObject */
+ private $environmentHelper;
+ /** @var AppLocator|\PHPUnit\Framework\MockObject\MockObject */
+ private $appLocator;
+ /** @var Checker */
+ private $checker;
+ /** @var FileAccessHelper|\PHPUnit\Framework\MockObject\MockObject */
+ private $fileAccessHelper;
+ /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */
+ private $config;
+ /** @var IAppConfig|\PHPUnit\Framework\MockObject\MockObject */
+ private $appConfig;
+ /** @var ICacheFactory|\PHPUnit\Framework\MockObject\MockObject */
+ private $cacheFactory;
+ /** @var IAppManager|\PHPUnit\Framework\MockObject\MockObject */
+ private $appManager;
+ /** @var \OC\Files\Type\Detection|\PHPUnit\Framework\MockObject\MockObject */
+ private $mimeTypeDetector;
+
+ protected function setUp(): void {
+ parent::setUp();
+ $this->environmentHelper = $this->createMock(EnvironmentHelper::class);
+ $this->fileAccessHelper = $this->createMock(FileAccessHelper::class);
+ $this->appLocator = $this->createMock(AppLocator::class);
+ $this->config = $this->createMock(IConfig::class);
+ $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->config->method('getAppValue')
+ ->willReturnArgument(2);
+
+ $this->cacheFactory
+ ->expects($this->any())
+ ->method('createDistributed')
+ ->with('oc.integritycheck.checker')
+ ->willReturn(new NullCache());
+
+ $this->checker = new Checker(
+ $this->environmentHelper,
+ $this->fileAccessHelper,
+ $this->appLocator,
+ $this->config,
+ $this->appConfig,
+ $this->cacheFactory,
+ $this->appManager,
+ $this->mimeTypeDetector
+ );
+ }
+
+
+ public function testWriteAppSignatureOfNotExistingApp(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('Exception message');
+
+ $this->fileAccessHelper
+ ->expects($this->once())
+ ->method('assertDirectoryExists')
+ ->with('NotExistingApp/appinfo')
+ ->willThrowException(new \Exception('Exception message'));
+ $this->fileAccessHelper
+ ->expects($this->once())
+ ->method('is_writable')
+ ->with('NotExistingApp/appinfo')
+ ->willReturn(true);
+
+ $keyBundle = file_get_contents(__DIR__ .'/../../data/integritycheck/SomeApp.crt');
+ $rsaPrivateKey = file_get_contents(__DIR__ .'/../../data/integritycheck/SomeApp.key');
+ $rsa = new RSA();
+ $rsa->loadKey($rsaPrivateKey);
+ $x509 = new X509();
+ $x509->loadX509($keyBundle);
+ $this->checker->writeAppSignature('NotExistingApp', $x509, $rsa);
+ }
+
+
+ public function testWriteAppSignatureWrongPermissions(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessageMatches('/[a-zA-Z\\/_-]+ is not writable/');
+
+ $this->fileAccessHelper
+ ->expects($this->once())
+ ->method('file_put_contents')
+ ->will($this->throwException(new \Exception('Exception message')));
+
+ $keyBundle = file_get_contents(__DIR__ .'/../../data/integritycheck/SomeApp.crt');
+ $rsaPrivateKey = file_get_contents(__DIR__ .'/../../data/integritycheck/SomeApp.key');
+ $rsa = new RSA();
+ $rsa->loadKey($rsaPrivateKey);
+ $x509 = new X509();
+ $x509->loadX509($keyBundle);
+ $this->checker->writeAppSignature(\OC::$SERVERROOT . '/tests/data/integritycheck/app/', $x509, $rsa);
+ }
+
+ public function testWriteAppSignature(): void {
+ $expectedSignatureFileData = '{
+ "hashes": {
+ "AnotherFile.txt": "1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112",
+ "subfolder\/file.txt": "410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b"
+ },
+ "signature": "Y5yvXvcGHVPuRRatKVDUONWq1FpLXugZd6Km\/+aEHsQj7coVl9FeMj9OsWamBf7yRIw3dtNLguTLlAA9QAv\/b0uHN3JnbNZN+dwFOve4NMtqXfSDlWftqKN00VS+RJXpG1S2IIx9Poyp2NoghL\/5AuTv4GHiNb7zU\/DT\/kt71pUGPgPR6IIFaE+zHOD96vjYkrH+GfWZzKR0FCdLib9yyNvk+EGrcjKM6qjs2GKfS\/XFjj\/\/neDnh\/0kcPuKE3ZbofnI4TIDTv0CGqvOp7PtqVNc3Vy\/UKa7uF1PT0MAUKMww6EiMUSFZdUVP4WWF0Y72W53Qdtf1hrAZa2kfKyoK5kd7sQmCSKUPSU8978AUVZlBtTRlyT803IKwMV0iHMkw+xYB1sN2FlHup\/DESADqxhdgYuK35bCPvgkb4SBe4B8Voz\/izTvcP7VT5UvkYdAO+05\/jzdaHEmzmsD92CFfvX0q8O\/Y\/29ubftUJsqcHeMDKgcR4eZOE8+\/QVc\/89QO6WnKNuNuV+5bybO6g6PAdC9ZPsCvnihS61O2mwRXHLR3jv2UleFWm+lZEquPKtkhi6SLtDiijA4GV6dmS+dzujSLb7hGeD5o1plZcZ94uhWljl+QIp82+zU\/lYB1Zfr4Mb4e+V7r2gv7Fbv7y6YtjE2GIQwRhC5jq56bD0ZB+I=",
+ "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEwTCCAqmgAwIBAgIUWv0iujufs5lUr0svCf\/qTQvoyKAwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIyNDk1M1oXDTE2MTEwMzIyNDk1M1owEjEQMA4GA1UEAwwHU29tZUFwcDCCAiIw\r\nDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK8q0x62agGSRBqeWsaeEwFfepMk\r\nF8cAobMMi50qHCv9IrOn\/ZH9l52xBrbIkErVmRjmly0d4JhD8Ymhidsh9ONKYl\/j\r\n+ishsZDM8eNNdp3Ew+fEYVvY1W7mR1qU24NWj0bzVsClI7hvPVIuw7AjfBDq1C5+\r\nA+ZSLSXYvOK2cEWjdxQfuNZwEZSjmA63DUllBIrm35IaTvfuyhU6BW9yHZxmb8+M\r\nw0xDv30D5UkE\/2N7Pa\/HQJLxCR+3zKibRK3nUyRDLSXxMkU9PnFNaPNX59VPgyj4\r\nGB1CFSToldJVPF4pzh7p36uGXZVxs8m3LFD4Ol8mhi7jkxDZjqFN46gzR0r23Py6\r\ndol9vfawGIoUwp9LvL0S7MvdRY0oazLXwClLP4OQ17zpSMAiCj7fgNT661JamPGj\r\nt5O7Zn2wA7I4ddDS\/HDTWCu98Zwc9fHIpsJPgCZ9awoqxi4Mnf7Pk9g5nnXhszGC\r\ncxxIASQKM+GhdzoRxKknax2RzUCwCzcPRtCj8AQT\/x\/mqN3PfRmlnFBNACUw9bpZ\r\nSOoNq2pCF9igftDWpSIXQ38pVpKLWowjjg3DVRmVKBgivHnUnVLyzYBahHPj0vaz\r\ntFtUFRaqXDnt+4qyUGyrT5h5pjZaTcHIcSB4PiarYwdVvgslgwnQzOUcGAzRWBD4\r\n6jV2brP5vFY3g6iPAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBACTY3CCHC+Z28gCf\r\nFWGKQ3wAKs+k4+0yoti0qm2EKX7rSGQ0PHSas6uW79WstC4Rj+DYkDtIhGMSg8FS\r\nHVGZHGBCc0HwdX+BOAt3zi4p7Sf3oQef70\/4imPoKxbAVCpd\/cveVcFyDC19j1yB\r\nBapwu87oh+muoeaZxOlqQI4UxjBlR\/uRSMhOn2UGauIr3dWJgAF4pGt7TtIzt+1v\r\n0uA6FtN1Y4R5O8AaJPh1bIG0CVvFBE58esGzjEYLhOydgKFnEP94kVPgJD5ds9C3\r\npPhEpo1dRpiXaF7WGIV1X6DI\/ipWvfrF7CEy6I\/kP1InY\/vMDjQjeDnJ\/VrXIWXO\r\nyZvHXVaN\/m+1RlETsH7YO\/QmxRue9ZHN3gvvWtmpCeA95sfpepOk7UcHxHZYyQbF\r\n49\/au8j+5tsr4A83xzsT1JbcKRxkAaQ7WDJpOnE5O1+H0fB+BaLakTg6XX9d4Fo7\r\n7Gin7hVWX7pL+JIyxMzME3LhfI61+CRcqZQIrpyaafUziPQbWIPfEs7h8tCOWyvW\r\nUO8ZLervYCB3j44ivkrxPlcBklDCqqKKBzDP9dYOtS\/P4RB1NkHA9+NTvmBpTonS\r\nSFXdg9fFMD7VfjDE3Vnk+8DWkVH5wBYowTAD7w9Wuzr7DumiAULexnP\/Y7xwxLv7\r\n4B+pXTAcRK0zECDEaX3npS8xWzrB\r\n-----END CERTIFICATE-----"
+}';
+ $this->fileAccessHelper
+ ->expects($this->once())
+ ->method('file_put_contents')
+ ->with(
+ $this->equalTo(\OC::$SERVERROOT . '/tests/data/integritycheck/app//appinfo/signature.json'),
+ $this->callback(function ($signature) use ($expectedSignatureFileData) {
+ $expectedArray = json_decode($expectedSignatureFileData, true);
+ $actualArray = json_decode($signature, true);
+ $this->assertEquals($expectedArray, $actualArray);
+ return true;
+ })
+ );
+
+ $keyBundle = file_get_contents(__DIR__ .'/../../data/integritycheck/SomeApp.crt');
+ $rsaPrivateKey = file_get_contents(__DIR__ .'/../../data/integritycheck/SomeApp.key');
+ $rsa = new RSA();
+ $rsa->loadKey($rsaPrivateKey);
+ $x509 = new X509();
+ $x509->loadX509($keyBundle);
+ $this->checker->writeAppSignature(\OC::$SERVERROOT . '/tests/data/integritycheck/app/', $x509, $rsa);
+ }
+
+ public function testVerifyAppSignatureWithoutSignatureData(): void {
+ $this->environmentHelper
+ ->expects($this->once())
+ ->method('getChannel')
+ ->willReturn('stable');
+ $this->config
+ ->expects($this->any())
+ ->method('getSystemValueBool')
+ ->with('integrity.check.disabled', false)
+ ->willReturn(false);
+
+ $expected = [
+ 'EXCEPTION' => [
+ 'class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class,
+ 'message' => 'Signature data not found.',
+ ],
+ ];
+ $this->assertSame($expected, $this->checker->verifyAppSignature('SomeApp'));
+ }
+
+ public function testVerifyAppSignatureWithValidSignatureData(): void {
+ $this->environmentHelper
+ ->expects($this->once())
+ ->method('getChannel')
+ ->willReturn('stable');
+ $this->config
+ ->expects($this->any())
+ ->method('getSystemValueBool')
+ ->with('integrity.check.disabled', false)
+ ->willReturn(false);
+
+ $this->appLocator
+ ->expects($this->once())
+ ->method('getAppPath')
+ ->with('SomeApp')
+ ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/app/');
+ $signatureDataFile = '{
+ "hashes": {
+ "AnotherFile.txt": "1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112",
+ "subfolder\/file.txt": "410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b"
+ },
+ "signature": "dYoohBaWIFR\/To1FXEbMQB5apUhVYlEauBGSPo12nq84wxWkBx2EM3KDRgkB5Sub2tr0CgmAc2EVjPhKIEzAam26cyUb48bJziz1V6wvW7z4GZAfaJpzLkyHdSfV5117VSf5w1rDcAeZDXfGUaaNEJPWytaF4ZIxVge7f3NGshHy4odFVPADy\/u6c43BWvaOtJ4m3aJQbP6sxCO9dxwcm5yJJJR3n36jfh229sdWBxyl8BhwhH1e1DEv78\/aiL6ckKFPVNzx01R6yDFt3TgEMR97YZ\/R6lWiXG+dsJ305jNFlusLu518zBUvl7g5yjzGN778H29b2C8VLZKmi\/h1CH9jGdD72fCqCYdenD2uZKzb6dsUtXtvBmVcVT6BUGz41W1pkkEEB+YJpMrHILIxAiHRGv1+aZa9\/Oz8LWFd+BEUQjC2LJgojPnpzaG\/msw1nBkX16NNVDWWtJ25Bc\/r\/mG46rwjWB\/cmV6Lwt6KODiqlxgrC4lm9ALOCEWw+23OcYhLwNfQTYevXqHqsFfXOkhUnM8z5vDUb\/HBraB1DjFXN8iLK+1YewD4P495e+SRzrR79Oi3F8SEqRIzRLfN2rnW1BTms\/wYsz0p67cup1Slk1XlNmHwbWX25NVd2PPlLOvZRGoqcKFpIjC5few8THiZfyjiNFwt3RM0AFdZcXY=",
+ "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----"
+}';
+ $this->fileAccessHelper
+ ->expects($this->exactly(2))
+ ->method('file_get_contents')
+ ->withConsecutive(
+ [\OC::$SERVERROOT . '/tests/data/integritycheck/app//appinfo/signature.json'],
+ ['/resources/codesigning/root.crt'],
+ )
+ ->willReturnOnConsecutiveCalls(
+ $signatureDataFile,
+ file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')
+ );
+
+ $this->assertSame([], $this->checker->verifyAppSignature('SomeApp'));
+ }
+
+ public function testVerifyAppSignatureWithTamperedSignatureData(): void {
+ $this->environmentHelper
+ ->expects($this->once())
+ ->method('getChannel')
+ ->willReturn('stable');
+ $this->config
+ ->expects($this->any())
+ ->method('getSystemValueBool')
+ ->with('integrity.check.disabled', false)
+ ->willReturn(false);
+
+ $this->appLocator
+ ->expects($this->once())
+ ->method('getAppPath')
+ ->with('SomeApp')
+ ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/app/');
+ $signatureDataFile = '{
+ "hashes": {
+ "AnotherFile.txt": "tampered",
+ "subfolder\/file.txt": "tampered"
+ },
+ "signature": "EL49UaSeyMAqyMtqId+tgOhhwgOevPZsRLX4j2blnybAB6fN07z0936JqZV7+eMPiE30Idx+UCY6rCFN531Kqe9vAOCdgtHUSOjjKyKc+lvULESlMb6YQcrZrvDlEMMjzjH49ewG7Ai8sNN6HrRUd9U8ws+ewSkW2DOOBItj\/21RBnkrSt+2AtGXGigEvuTm57HrCYDj8\/lSkumC2GVkjLUHeLOKYo4PRNOr6yP5mED5v7zo66AWvXl2fKv54InZcdxsAk35lyK9DGZbk\/027ZRd0AOHT3LImRLvQ+8EAg3XLlRUy0hOFGgPC+jYonMzgYvsAXAXi2j8LnLJlsLwpFwu1k1B+kZVPMumKZvP9OvJb70EirecXmz62V+Jiyuaq7ne4y7Kp5gKZT\/T8SeZ0lFtCmPfYyzBB0y8s5ldmTTmdVYHs54t\/OCCW82HzQZxnFNPzDTRa8HglsaMKrqPtW59+R4UvRKSWhB8M\/Ah57qgzycvPV4KMz\/FbD4l\/\/9chRKSlCfc2k3b8ZSHNmi+EzCKgJjWIoKdgN1yax94puU8jfn8UW+G7H9Y1Jsf\/jox6QLyYEgtV1vOHY2xLT7fVs2vhyvkN2MNjJnmQ70gFG5Qz2lBz5wi6ZpB+tOfCcpbLxWAkoWoIrmC\/Ilqh7mfmRZ43g5upjkepHNd93ONuY8=",
+ "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEwTCCAqmgAwIBAgIUWv0iujufs5lUr0svCf\/qTQvoyKAwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIyNDk1M1oXDTE2MTEwMzIyNDk1M1owEjEQMA4GA1UEAwwHU29tZUFwcDCCAiIw\r\nDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK8q0x62agGSRBqeWsaeEwFfepMk\r\nF8cAobMMi50qHCv9IrOn\/ZH9l52xBrbIkErVmRjmly0d4JhD8Ymhidsh9ONKYl\/j\r\n+ishsZDM8eNNdp3Ew+fEYVvY1W7mR1qU24NWj0bzVsClI7hvPVIuw7AjfBDq1C5+\r\nA+ZSLSXYvOK2cEWjdxQfuNZwEZSjmA63DUllBIrm35IaTvfuyhU6BW9yHZxmb8+M\r\nw0xDv30D5UkE\/2N7Pa\/HQJLxCR+3zKibRK3nUyRDLSXxMkU9PnFNaPNX59VPgyj4\r\nGB1CFSToldJVPF4pzh7p36uGXZVxs8m3LFD4Ol8mhi7jkxDZjqFN46gzR0r23Py6\r\ndol9vfawGIoUwp9LvL0S7MvdRY0oazLXwClLP4OQ17zpSMAiCj7fgNT661JamPGj\r\nt5O7Zn2wA7I4ddDS\/HDTWCu98Zwc9fHIpsJPgCZ9awoqxi4Mnf7Pk9g5nnXhszGC\r\ncxxIASQKM+GhdzoRxKknax2RzUCwCzcPRtCj8AQT\/x\/mqN3PfRmlnFBNACUw9bpZ\r\nSOoNq2pCF9igftDWpSIXQ38pVpKLWowjjg3DVRmVKBgivHnUnVLyzYBahHPj0vaz\r\ntFtUFRaqXDnt+4qyUGyrT5h5pjZaTcHIcSB4PiarYwdVvgslgwnQzOUcGAzRWBD4\r\n6jV2brP5vFY3g6iPAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBACTY3CCHC+Z28gCf\r\nFWGKQ3wAKs+k4+0yoti0qm2EKX7rSGQ0PHSas6uW79WstC4Rj+DYkDtIhGMSg8FS\r\nHVGZHGBCc0HwdX+BOAt3zi4p7Sf3oQef70\/4imPoKxbAVCpd\/cveVcFyDC19j1yB\r\nBapwu87oh+muoeaZxOlqQI4UxjBlR\/uRSMhOn2UGauIr3dWJgAF4pGt7TtIzt+1v\r\n0uA6FtN1Y4R5O8AaJPh1bIG0CVvFBE58esGzjEYLhOydgKFnEP94kVPgJD5ds9C3\r\npPhEpo1dRpiXaF7WGIV1X6DI\/ipWvfrF7CEy6I\/kP1InY\/vMDjQjeDnJ\/VrXIWXO\r\nyZvHXVaN\/m+1RlETsH7YO\/QmxRue9ZHN3gvvWtmpCeA95sfpepOk7UcHxHZYyQbF\r\n49\/au8j+5tsr4A83xzsT1JbcKRxkAaQ7WDJpOnE5O1+H0fB+BaLakTg6XX9d4Fo7\r\n7Gin7hVWX7pL+JIyxMzME3LhfI61+CRcqZQIrpyaafUziPQbWIPfEs7h8tCOWyvW\r\nUO8ZLervYCB3j44ivkrxPlcBklDCqqKKBzDP9dYOtS\/P4RB1NkHA9+NTvmBpTonS\r\nSFXdg9fFMD7VfjDE3Vnk+8DWkVH5wBYowTAD7w9Wuzr7DumiAULexnP\/Y7xwxLv7\r\n4B+pXTAcRK0zECDEaX3npS8xWzrB\r\n-----END CERTIFICATE-----"
+}';
+ $this->fileAccessHelper
+ ->expects($this->exactly(2))
+ ->method('file_get_contents')
+ ->withConsecutive(
+ [\OC::$SERVERROOT . '/tests/data/integritycheck/app//appinfo/signature.json'],
+ ['/resources/codesigning/root.crt'],
+ )
+ ->willReturnOnConsecutiveCalls(
+ $signatureDataFile,
+ file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')
+ );
+
+ $expected = [
+ 'EXCEPTION' => [
+ 'class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class,
+ 'message' => 'Signature could not get verified.',
+ ],
+ ];
+ $this->assertEquals($expected, $this->checker->verifyAppSignature('SomeApp'));
+ }
+
+ public function testVerifyAppSignatureWithTamperedFiles(): void {
+ $this->environmentHelper
+ ->expects($this->once())
+ ->method('getChannel')
+ ->willReturn('stable');
+ $this->config
+ ->expects($this->any())
+ ->method('getSystemValueBool')
+ ->with('integrity.check.disabled', false)
+ ->willReturn(false);
+
+ $this->appLocator
+ ->expects($this->once())
+ ->method('getAppPath')
+ ->with('SomeApp')
+ ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/appWithInvalidData/');
+ $signatureDataFile = '{
+ "hashes": {
+ "AnotherFile.txt": "1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112",
+ "subfolder\/file.txt": "410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b"
+ },
+ "signature": "dYoohBaWIFR\/To1FXEbMQB5apUhVYlEauBGSPo12nq84wxWkBx2EM3KDRgkB5Sub2tr0CgmAc2EVjPhKIEzAam26cyUb48bJziz1V6wvW7z4GZAfaJpzLkyHdSfV5117VSf5w1rDcAeZDXfGUaaNEJPWytaF4ZIxVge7f3NGshHy4odFVPADy\/u6c43BWvaOtJ4m3aJQbP6sxCO9dxwcm5yJJJR3n36jfh229sdWBxyl8BhwhH1e1DEv78\/aiL6ckKFPVNzx01R6yDFt3TgEMR97YZ\/R6lWiXG+dsJ305jNFlusLu518zBUvl7g5yjzGN778H29b2C8VLZKmi\/h1CH9jGdD72fCqCYdenD2uZKzb6dsUtXtvBmVcVT6BUGz41W1pkkEEB+YJpMrHILIxAiHRGv1+aZa9\/Oz8LWFd+BEUQjC2LJgojPnpzaG\/msw1nBkX16NNVDWWtJ25Bc\/r\/mG46rwjWB\/cmV6Lwt6KODiqlxgrC4lm9ALOCEWw+23OcYhLwNfQTYevXqHqsFfXOkhUnM8z5vDUb\/HBraB1DjFXN8iLK+1YewD4P495e+SRzrR79Oi3F8SEqRIzRLfN2rnW1BTms\/wYsz0p67cup1Slk1XlNmHwbWX25NVd2PPlLOvZRGoqcKFpIjC5few8THiZfyjiNFwt3RM0AFdZcXY=",
+ "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----"
+}';
+ $this->fileAccessHelper
+ ->expects($this->exactly(2))
+ ->method('file_get_contents')
+ ->withConsecutive(
+ [\OC::$SERVERROOT . '/tests/data/integritycheck/appWithInvalidData//appinfo/signature.json'],
+ ['/resources/codesigning/root.crt'],
+ )
+ ->willReturnOnConsecutiveCalls(
+ $signatureDataFile,
+ file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')
+ );
+
+
+ $expected = [
+ 'INVALID_HASH' => [
+ 'AnotherFile.txt' => [
+ 'expected' => '1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112',
+ 'current' => '7322348ba269c6d5522efe02f424fa3a0da319a7cd9c33142a5afe32a2d9af2da3a411f086fcfc96ff4301ea566f481dba0960c2abeef3594c4d930462f6584c',
+ ],
+ ],
+ 'FILE_MISSING' => [
+ 'subfolder/file.txt' => [
+ 'expected' => '410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b',
+ 'current' => '',
+ ],
+ ],
+ 'EXTRA_FILE' => [
+ 'UnecessaryFile' => [
+ 'expected' => '',
+ 'current' => 'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e',
+ ],
+ ],
+
+ ];
+ $this->assertSame($expected, $this->checker->verifyAppSignature('SomeApp'));
+ }
+
+ public function testVerifyAppSignatureWithTamperedFilesAndAlternatePath(): void {
+ $this->environmentHelper
+ ->expects($this->once())
+ ->method('getChannel')
+ ->willReturn('stable');
+ $this->config
+ ->expects($this->any())
+ ->method('getSystemValueBool')
+ ->with('integrity.check.disabled', false)
+ ->willReturn(false);
+
+ $this->appLocator
+ ->expects($this->never())
+ ->method('getAppPath')
+ ->with('SomeApp');
+ $signatureDataFile = '{
+ "hashes": {
+ "AnotherFile.txt": "1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112",
+ "subfolder\/file.txt": "410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b"
+ },
+ "signature": "dYoohBaWIFR\/To1FXEbMQB5apUhVYlEauBGSPo12nq84wxWkBx2EM3KDRgkB5Sub2tr0CgmAc2EVjPhKIEzAam26cyUb48bJziz1V6wvW7z4GZAfaJpzLkyHdSfV5117VSf5w1rDcAeZDXfGUaaNEJPWytaF4ZIxVge7f3NGshHy4odFVPADy\/u6c43BWvaOtJ4m3aJQbP6sxCO9dxwcm5yJJJR3n36jfh229sdWBxyl8BhwhH1e1DEv78\/aiL6ckKFPVNzx01R6yDFt3TgEMR97YZ\/R6lWiXG+dsJ305jNFlusLu518zBUvl7g5yjzGN778H29b2C8VLZKmi\/h1CH9jGdD72fCqCYdenD2uZKzb6dsUtXtvBmVcVT6BUGz41W1pkkEEB+YJpMrHILIxAiHRGv1+aZa9\/Oz8LWFd+BEUQjC2LJgojPnpzaG\/msw1nBkX16NNVDWWtJ25Bc\/r\/mG46rwjWB\/cmV6Lwt6KODiqlxgrC4lm9ALOCEWw+23OcYhLwNfQTYevXqHqsFfXOkhUnM8z5vDUb\/HBraB1DjFXN8iLK+1YewD4P495e+SRzrR79Oi3F8SEqRIzRLfN2rnW1BTms\/wYsz0p67cup1Slk1XlNmHwbWX25NVd2PPlLOvZRGoqcKFpIjC5few8THiZfyjiNFwt3RM0AFdZcXY=",
+ "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----"
+}';
+ $this->fileAccessHelper
+ ->expects($this->exactly(2))
+ ->method('file_get_contents')
+ ->withConsecutive(
+ [\OC::$SERVERROOT . '/tests/data/integritycheck/appWithInvalidData//appinfo/signature.json'],
+ ['/resources/codesigning/root.crt'],
+ )
+ ->willReturnOnConsecutiveCalls(
+ $signatureDataFile,
+ file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')
+ );
+
+
+ $expected = [
+ 'INVALID_HASH' => [
+ 'AnotherFile.txt' => [
+ 'expected' => '1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112',
+ 'current' => '7322348ba269c6d5522efe02f424fa3a0da319a7cd9c33142a5afe32a2d9af2da3a411f086fcfc96ff4301ea566f481dba0960c2abeef3594c4d930462f6584c',
+ ],
+ ],
+ 'FILE_MISSING' => [
+ 'subfolder/file.txt' => [
+ 'expected' => '410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b',
+ 'current' => '',
+ ],
+ ],
+ 'EXTRA_FILE' => [
+ 'UnecessaryFile' => [
+ 'expected' => '',
+ 'current' => 'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e',
+ ],
+ ],
+
+ ];
+ $this->assertSame($expected, $this->checker->verifyAppSignature('SomeApp', \OC::$SERVERROOT . '/tests/data/integritycheck/appWithInvalidData/'));
+ }
+
+ public function testVerifyAppWithDifferentScope(): void {
+ $this->environmentHelper
+ ->expects($this->once())
+ ->method('getChannel')
+ ->willReturn('stable');
+ $this->config
+ ->expects($this->any())
+ ->method('getSystemValueBool')
+ ->with('integrity.check.disabled', false)
+ ->willReturn(false);
+
+ $this->appLocator
+ ->expects($this->once())
+ ->method('getAppPath')
+ ->with('SomeApp')
+ ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/appWithInvalidData/');
+ $signatureDataFile = '{
+ "hashes": {
+ "AnotherFile.txt": "1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112",
+ "subfolder\/file.txt": "410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b"
+ },
+ "signature": "eXesvDm3pkek12xSwMG10y9suRES79Nye3jYNe5KYq1tTUPqRRNgxmMGAfcUro0zpLeAr2YgHeSMWtglblGOW7pmwGVPZ0O1Y4r1fE6jnep0kW+35PLIaqCorIOnCAtSzDNKBhwd1ow3zW2wC0DFouuEkIO8u5Fw28g8E8dp8zEk1xMblNPy+xtWkmYHrVJ\/dQgun1bYOF2ZFtAzatwndTI\/bGsy1i3Wsl+x6HyWKQdq8y8VObtOqKDH7uERBEpB9DHVyKflj1v1gQuEH6BhaRdATc7ee0MiQdGblraIySwYRdfo2d8i82OVKrenMB3SLwyCvDPyQ9iKpTOnSF52ZBqaqSXKM2N\/RAkweeBFQQCwcHhqxvB0cfbyHcbkOLeCZe\/tsh68IxwTiYgzvLfl7sOZ5arnZbzrPpZmB+hfV2omkoJ1tDwOWz9hEmLLNtfo2OxyUH1m0+XFaC+Gbn4WkVDgf7YZkwUcG+Qoa3oKDNMss8MEyZxewl2iDGZcf402dlidHRprlfmXbAYuVQ08\/a0HxIKYPGh\/nsMGmwnO15CWtFpAbhUA\/D5oRjsIxnvXaMDg0iAFpdu\/5Ffsj7g3EPdBkiQHNYK7YU1RRx609eH0bZyiIYHdUPw7ikLupvrebZmELqi3mqDFO99u4eISlxFJlUbUND3L4BtmWTWrKwI=",
+ "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIExjCCAq6gAwIBAgIUHSJjhJqMwr+3TkoiQFg4SVVYQ1gwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIzMjc1NVoXDTE2MTEwMzIzMjc1NVowFzEVMBMGA1UEAwwMQW5vdGhlclNjb3Bl\r\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA33npb5RmUkXrDT+TbwMf\r\n0zQ33SlzsjoGxCrbSwJOn6leGGInJ6ZrdzLL0WTi\/dTpg+Y\/JS+72XWm5NSjaTxo\r\n7OHc3cQBwXQj4tN6j\/y5qqY0GDLYufEkx2rpazqt9lBSJ72u1bGl2yoOXzYCz5i0\r\n60KsJXC9K44LKzGsarzbwAgskSVNkjAsPgjnCWZmcl6icpLi5Fz9rs2UMOWbdvdI\r\nAROsn0eC9E\/akmXTy5YMu6bAIGpvjZFHzyA83FQRbvv5o1V5Gsye\/VQLEgh7rqfz\r\nT\/jgWifP+JgoeB6otzuRZ3fFsmbBiyCIRtIOzQQflozhUlWtmiEGwg4GySuMUjEH\r\nA1LF86LO+ZzDQgd2oYNKmrQ8O+EcLqx9BpV4AFhEvqdk7uycJYPHs6yl+yfbzTeJ\r\n2Xd0yVAfd9r\/iDr36clLj2bzEObdl9xzKjcCIXE4Q0G4Pur41\/BJUDK9PI390ccQ\r\nnFjjVYBMsC859OwW64tMP0zkM9Vv72LCaEzaR8jqH0j11catqxunr+StfMcmxLTN\r\nbqBJbSEq4ER3mJxCTI2UrIVmdQ7+wRxgv3QTDNOZyqrz2L8A1Rpb3h0APxtQv+oA\r\n8KIZYID5\/qsS2V2jITkMQ8Nd1W3b0cZhZ600z+znh3jLJ0TYLvwN6\/qBQTUDaM2o\r\ng1+icMqXIXIeKuoPCVVsG7cCAwEAATANBgkqhkiG9w0BAQUFAAOCAgEAHc4F\/kOV\r\nHc8In5MmGg2YtjwZzjdeoC5TIPZczRqz0B+wRbJzN6aYryKZKLmP+wKpgRnJWDzp\r\nrgKGyyEQIAfK63DEv4B9p4N1B+B3aeMKsSpVcw7wbFTD57V5A7pURGoo31d0mw5L\r\nUIXZ2u+TUfGbzucMxLdFhTwjGpz9M6Kkm\/POxmV0tvLija5LdbdKnYR9BFmyu4IX\r\nqyoIAtComATNLl+3URu3SZxhE3NxhzMz+eAeNfh1KuIf2gWIIeDCXalVSJLym+OQ\r\nHFDpqRhJqfTMprrRlmmU7Zntgbj8\/RRZuXnBvH9cQ2KykLOb4UoCPlGUqOqKyP9m\r\nDJSFRiMJfpgMQUaJk1TLhKF+IR6FnmwURLEtkONJumtDQju9KaWPlhueONdyGi0p\r\nqxLVUo1Vb52XnPhk2GEEduxpDc9V5ePJ+pdcEdMifY\/uPNBRuBj2c87yq1DLH+U4\r\n3XzP1MlwjnBWZYuoFo0j6Jq0r\/MG6HjGdmkGIsRoheRi8Z8Scz5AW5QRkNz8pKop\r\nTELFqQy9g6TyQzzC8t6HZcpNe842ZUk4raEAbCZe\/XqxWMw5svPgNceBqM3fh7sZ\r\nBSykOHLaL8kiRO\/IS3y1yZEAuiWBvtxcTNLzBb+hdRpm2y8\/qH\/pKo+CMj1VzjNT\r\nD8YRQg0cjmDytJzHDrtV\/aTc9W1aPHun0vw=\r\n-----END CERTIFICATE-----"
+}';
+ $this->fileAccessHelper
+ ->expects($this->exactly(2))
+ ->method('file_get_contents')
+ ->withConsecutive(
+ [\OC::$SERVERROOT . '/tests/data/integritycheck/appWithInvalidData//appinfo/signature.json'],
+ ['/resources/codesigning/root.crt'],
+ )->willReturnOnConsecutiveCalls(
+ $signatureDataFile,
+ file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')
+ );
+
+ $expected = [
+ 'EXCEPTION' => [
+ 'class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class,
+ 'message' => 'Certificate is not valid for required scope. (Requested: SomeApp, current: CN=AnotherScope)',
+ ],
+ ];
+ $this->assertSame($expected, $this->checker->verifyAppSignature('SomeApp'));
+ }
+
+ public function testVerifyAppWithDifferentScopeAndAlwaysTrustedCore(): void {
+ $this->environmentHelper
+ ->expects($this->once())
+ ->method('getChannel')
+ ->willReturn('stable');
+ $this->config
+ ->expects($this->any())
+ ->method('getSystemValueBool')
+ ->with('integrity.check.disabled', false)
+ ->willReturn(false);
+
+ $this->appLocator
+ ->expects($this->once())
+ ->method('getAppPath')
+ ->with('SomeApp')
+ ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/app/');
+ $signatureDataFile = '{
+ "hashes": {
+ "AnotherFile.txt": "1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112",
+ "subfolder\/file.txt": "410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b"
+ },
+ "signature": "dYoohBaWIFR\/To1FXEbMQB5apUhVYlEauBGSPo12nq84wxWkBx2EM3KDRgkB5Sub2tr0CgmAc2EVjPhKIEzAam26cyUb48bJziz1V6wvW7z4GZAfaJpzLkyHdSfV5117VSf5w1rDcAeZDXfGUaaNEJPWytaF4ZIxVge7f3NGshHy4odFVPADy\/u6c43BWvaOtJ4m3aJQbP6sxCO9dxwcm5yJJJR3n36jfh229sdWBxyl8BhwhH1e1DEv78\/aiL6ckKFPVNzx01R6yDFt3TgEMR97YZ\/R6lWiXG+dsJ305jNFlusLu518zBUvl7g5yjzGN778H29b2C8VLZKmi\/h1CH9jGdD72fCqCYdenD2uZKzb6dsUtXtvBmVcVT6BUGz41W1pkkEEB+YJpMrHILIxAiHRGv1+aZa9\/Oz8LWFd+BEUQjC2LJgojPnpzaG\/msw1nBkX16NNVDWWtJ25Bc\/r\/mG46rwjWB\/cmV6Lwt6KODiqlxgrC4lm9ALOCEWw+23OcYhLwNfQTYevXqHqsFfXOkhUnM8z5vDUb\/HBraB1DjFXN8iLK+1YewD4P495e+SRzrR79Oi3F8SEqRIzRLfN2rnW1BTms\/wYsz0p67cup1Slk1XlNmHwbWX25NVd2PPlLOvZRGoqcKFpIjC5few8THiZfyjiNFwt3RM0AFdZcXY=",
+ "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----"
+}';
+ $this->fileAccessHelper
+ ->expects($this->exactly(2))
+ ->method('file_get_contents')
+ ->withConsecutive(
+ [\OC::$SERVERROOT . '/tests/data/integritycheck/app//appinfo/signature.json'],
+ ['/resources/codesigning/root.crt'],
+ )->willReturnOnConsecutiveCalls(
+ $signatureDataFile,
+ file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')
+ );
+
+ $this->assertSame([], $this->checker->verifyAppSignature('SomeApp'));
+ }
+
+
+ public function testWriteCoreSignatureWithException(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('Exception message');
+
+ $this->fileAccessHelper
+ ->expects($this->once())
+ ->method('assertDirectoryExists')
+ ->will($this->throwException(new \Exception('Exception message')));
+ $this->fileAccessHelper
+ ->expects($this->once())
+ ->method('is_writable')
+ ->with(__DIR__ . '/core')
+ ->willReturn(true);
+
+ $keyBundle = file_get_contents(__DIR__ .'/../../data/integritycheck/SomeApp.crt');
+ $rsaPrivateKey = file_get_contents(__DIR__ .'/../../data/integritycheck/SomeApp.key');
+ $rsa = new RSA();
+ $rsa->loadKey($rsaPrivateKey);
+ $x509 = new X509();
+ $x509->loadX509($keyBundle);
+ $this->checker->writeCoreSignature($x509, $rsa, __DIR__);
+ }
+
+
+ public function testWriteCoreSignatureWrongPermissions(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessageMatches('/[a-zA-Z\\/_-]+ is not writable/');
+
+ $this->fileAccessHelper
+ ->expects($this->once())
+ ->method('assertDirectoryExists')
+ ->will($this->throwException(new \Exception('Exception message')));
+ $this->fileAccessHelper
+ ->expects($this->once())
+ ->method('is_writable')
+ ->with(__DIR__ . '/core')
+ ->willReturn(false);
+
+ $keyBundle = file_get_contents(__DIR__ .'/../../data/integritycheck/SomeApp.crt');
+ $rsaPrivateKey = file_get_contents(__DIR__ .'/../../data/integritycheck/SomeApp.key');
+ $rsa = new RSA();
+ $rsa->loadKey($rsaPrivateKey);
+ $x509 = new X509();
+ $x509->loadX509($keyBundle);
+ $this->checker->writeCoreSignature($x509, $rsa, __DIR__);
+ }
+
+ public function testWriteCoreSignature(): void {
+ $expectedSignatureFileData = '{
+ "hashes": {
+ "AnotherFile.txt": "1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112",
+ "subfolder\/file.txt": "410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b"
+ },
+ "signature": "dYoohBaWIFR\/To1FXEbMQB5apUhVYlEauBGSPo12nq84wxWkBx2EM3KDRgkB5Sub2tr0CgmAc2EVjPhKIEzAam26cyUb48bJziz1V6wvW7z4GZAfaJpzLkyHdSfV5117VSf5w1rDcAeZDXfGUaaNEJPWytaF4ZIxVge7f3NGshHy4odFVPADy\/u6c43BWvaOtJ4m3aJQbP6sxCO9dxwcm5yJJJR3n36jfh229sdWBxyl8BhwhH1e1DEv78\/aiL6ckKFPVNzx01R6yDFt3TgEMR97YZ\/R6lWiXG+dsJ305jNFlusLu518zBUvl7g5yjzGN778H29b2C8VLZKmi\/h1CH9jGdD72fCqCYdenD2uZKzb6dsUtXtvBmVcVT6BUGz41W1pkkEEB+YJpMrHILIxAiHRGv1+aZa9\/Oz8LWFd+BEUQjC2LJgojPnpzaG\/msw1nBkX16NNVDWWtJ25Bc\/r\/mG46rwjWB\/cmV6Lwt6KODiqlxgrC4lm9ALOCEWw+23OcYhLwNfQTYevXqHqsFfXOkhUnM8z5vDUb\/HBraB1DjFXN8iLK+1YewD4P495e+SRzrR79Oi3F8SEqRIzRLfN2rnW1BTms\/wYsz0p67cup1Slk1XlNmHwbWX25NVd2PPlLOvZRGoqcKFpIjC5few8THiZfyjiNFwt3RM0AFdZcXY=",
+ "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----"
+}';
+ $this->environmentHelper
+ ->expects($this->any())
+ ->method('getServerRoot')
+ ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/app/');
+ $this->fileAccessHelper
+ ->expects($this->once())
+ ->method('file_put_contents')
+ ->with(
+ \OC::$SERVERROOT . '/tests/data/integritycheck/app//core/signature.json',
+ $this->callback(function ($signature) use ($expectedSignatureFileData) {
+ $expectedArray = json_decode($expectedSignatureFileData, true);
+ $actualArray = json_decode($signature, true);
+ $this->assertEquals($expectedArray, $actualArray);
+ return true;
+ })
+ );
+
+ $keyBundle = file_get_contents(__DIR__ .'/../../data/integritycheck/core.crt');
+ $rsaPrivateKey = file_get_contents(__DIR__ .'/../../data/integritycheck/core.key');
+ $rsa = new RSA();
+ $rsa->loadKey($rsaPrivateKey);
+ $x509 = new X509();
+ $x509->loadX509($keyBundle);
+ $this->checker->writeCoreSignature($x509, $rsa, \OC::$SERVERROOT . '/tests/data/integritycheck/app/');
+ }
+
+ public function testWriteCoreSignatureWithUnmodifiedHtaccess(): void {
+ $expectedSignatureFileData = '{
+ "hashes": {
+ ".htaccess": "dc479770a6232061e04a768ee1f9133fdb3aea7b3a99f7105b0e0b6197474733e8d14b5b2bbad054e6b62a410fe5d0b3d790242dee1e0f11274af2100f5289e2",
+ "subfolder\/.htaccess": "2c57b1e25050e11dc3ae975832f378c452159f7b69f818e47eeeafadd6ba568517461dcb4d843b90b906cd7c89d161bc1b89dff8e3ae0eb6f5088508c47befd1"
+ },
+ "signature": "nRtR377DB\/I\/4hmh9q3elMQYfSHnQFlNtjchNgrdfmUQqVmgkU\/4qgGyxDqYkV8mSMbH2gYysfP42nx\/3zSo7n0dBYDfU87Q6f96Cv597vEV27do8CaBkEk8Xjn2SxhHw8hVxracvE2OBAPxk0H3sRp\/cQBgjoXpju4kQin0N5E+DEJMh7Sp+u8aKoFpb+2FaAZJFn\/hnqxLTlVi2nyDxGL3U0eobWY+jWH9XPt52v3Hyh8TDhcAnQ1cN30B8Jn2+jkrm8ib+buchaCXHk0cPX72xuPECdwOEKLCBNrJa3FGSvO1zWiecnCgxCXgt+R8hUgsVPTsbrdFY2YRJGIhHndYZL98XzgG7cw85SnnMMe2SulzeL7xANGF8qiEVyiC7x83bbj5xOkeM\/CUTajrLBO3vyZ23KKOxvskjgI0t+Zw1zFsl+sYW0\/O\/V5WzPOwMwV8+iApQ8k9gEMiYQg98QLEMYnSohncmp0Z9qx2qFcQuHLcKJVa1J6wGtE\/EHR\/4d0aYPd6IRjg+qshCJmdzud\/12xjpGTl+BT0Hi0VsU5o7ZMi7WhmukZmmv8u0uZsvKREQNATm4cO4WCkYySt5O9gZEJOF+jjgeynDoAh09lyrNXIgMpM9ufm\/XEG\/I\/f2zIwbAUc6J6qks5OuYlJzW5vscTiOKhwcGZU9WBLgh0=",
+ "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----"
+}';
+ $this->environmentHelper
+ ->expects($this->any())
+ ->method('getServerRoot')
+ ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/htaccessUnmodified/');
+ $this->fileAccessHelper
+ ->expects($this->once())
+ ->method('file_put_contents')
+ ->with(
+ \OC::$SERVERROOT . '/tests/data/integritycheck/htaccessUnmodified//core/signature.json',
+ $this->callback(function ($signature) use ($expectedSignatureFileData) {
+ $expectedArray = json_decode($expectedSignatureFileData, true);
+ $actualArray = json_decode($signature, true);
+ $this->assertEquals($expectedArray, $actualArray);
+ return true;
+ })
+ );
+
+ $keyBundle = file_get_contents(__DIR__ .'/../../data/integritycheck/core.crt');
+ $rsaPrivateKey = file_get_contents(__DIR__ .'/../../data/integritycheck/core.key');
+ $rsa = new RSA();
+ $rsa->loadKey($rsaPrivateKey);
+ $x509 = new X509();
+ $x509->loadX509($keyBundle);
+ $this->checker->writeCoreSignature($x509, $rsa, \OC::$SERVERROOT . '/tests/data/integritycheck/htaccessUnmodified/');
+ }
+
+ public function testWriteCoreSignatureWithInvalidModifiedHtaccess(): void {
+ $expectedSignatureFileData = '{
+ "hashes": {
+ ".htaccess": "4a54273dc8d697b2ca615acf2ae2c1ee3c1c643492cb04f42b10984fa9aacff1420dc829fd82f93ad3476fbd0cdab0251142c887dc8f872d03e39a3a3eb6d381"
+ },
+ "signature": "qpDddYGgAKNR3TszOgjPXRphUl2P9Ym5OQaetltocgZASGDkOun5D64+1D0QJRKb4SG2+48muxGOHyL2Ngos4NUrrSR+SIkywZacay82YQBCEdr7\/4MjW1WHRPjvboLwEJwViw0EdAjsWRpD68aPnzUGrGsy2BsCo06P5iwjk9cXcHxdjC9R39npvoC3QNvQ2jmNIbh1Lc4U97dbb+CsXEQCLU1OSa9p3q6cEFV98Easwt7uF\/DzHK+CbeZlxVZ0DwLh2\/ylT1PyGou8QC1b3vKAnPjLWMO+UsCPpCKhk3C5pV+5etQ8puGd+0x2t5tEU+qXxLzek91zWNC+rqgC\/WlqLKbwPb\/BCHs4zLGV55Q2fEQmT21x0KCUELdPs4dBnYP4Ox5tEDugtJujWFzOHzoY6gGa\/BY\/78pSZXmq9o8dWkBEtioWWvaNZ1rM0ddE83GBlBTgjigi9Ay1D++bUW\/FCBB7CMk6qyNlV81H+cBuIEODw2aymmkM9LLDD2Qbmvo8gHEPRjiQxPC5OpDlcdSNiL+zcxVxeuX4FpT+9xzz\/\/DRONhufxRpsbuCOMxd96RW7y9U2N2Uxb3Bzn\/BIqEayUUsdgZjfaGcXXYKR+chu\/LOwNYN6RlnLsgqL\/dhGKwlRVKXw1RA2\/af\/CpqyR7uVP6al1YJo\/YJ+5XJ6zE=",
+ "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----"
+}';
+ $this->fileAccessHelper
+ ->expects($this->once())
+ ->method('file_put_contents')
+ ->with(
+ \OC::$SERVERROOT . '/tests/data/integritycheck/htaccessWithInvalidModifiedContent//core/signature.json',
+ $this->callback(function ($signature) use ($expectedSignatureFileData) {
+ $expectedArray = json_decode($expectedSignatureFileData, true);
+ $actualArray = json_decode($signature, true);
+ $this->assertEquals($expectedArray, $actualArray);
+ return true;
+ })
+ );
+
+ $keyBundle = file_get_contents(__DIR__ .'/../../data/integritycheck/core.crt');
+ $rsaPrivateKey = file_get_contents(__DIR__ .'/../../data/integritycheck/core.key');
+ $rsa = new RSA();
+ $rsa->loadKey($rsaPrivateKey);
+ $x509 = new X509();
+ $x509->loadX509($keyBundle);
+ $this->checker->writeCoreSignature($x509, $rsa, \OC::$SERVERROOT . '/tests/data/integritycheck/htaccessWithInvalidModifiedContent/');
+ }
+
+ public function testWriteCoreSignatureWithValidModifiedHtaccess(): void {
+ $expectedSignatureFileData = '{
+ "hashes": {
+ ".htaccess": "7e6a7a4d8ee4f3fbc45dd579407c643471575a9d127d1c75f6d0a49e80766c3c587104b2139ef76d2a4bffce3f45777900605aaa49519c9532909b71e5030227",
+ "subfolder\/.htaccess": "2c57b1e25050e11dc3ae975832f378c452159f7b69f818e47eeeafadd6ba568517461dcb4d843b90b906cd7c89d161bc1b89dff8e3ae0eb6f5088508c47befd1"
+ },
+ "signature": "YVwQvl9Dh8UebCumfgzFxfz3NiZJLmYG8oJVTfEBhulI4KXBnTG1jZTprf4XxG2XIriEYAZXsoXpu9xWsUFe9QfdncwoEpqJtGq7l6aVDTofX5Be5b03MQFJr4cflgllqW77QZ84D9O9qWF\/vNDAofXcwrzT04CxLDhyQgTCgYUnRjG9pnuP\/gtbDKbTjRvxhTyfg3T0Phv1+XAvpTPnH2q5A+1+LmiqziUJ1sMipsKo+jQP614eCi9qjmqhHIgLRgcuOBvsi4g5WUcdcAIZ6qLt5gm2Y3r6rKNVchosU9ZydMUTfjuejDbVwE2fNH5UUnV57fQBxwg9CfX7iFHqKv1bfv5Zviu12paShgWCB12uR3iH\/3lmTJn8K5Xqit3G4eymFaJ5IChdUThBp\/jhQSI2r8sPcZDYSJ\/UZKuFnezFdKhEBd5hMXe8aKAd6ijGDjLARksFuqpi1sS8llC5K1Q+DzktSL\/o64TY4Vuvykiwe\/BAk2SkL9voOtrvU7vfDBcuCPbDJnSBBC0ESpcXeClTBIn6xZ9WaxqoS7sinE\/kUwtWsRd04I7d79\/ouotyNb+mBhTuRsZT12p\/gn4JHXXNUAIpTwchYzGxbfNJ4kxnYBFZWVmvsSqOLFZu1yi5BP3ktA9yhFyWIa5659azRFEKRdXpVHtQVa4IgdhxEqA=",
+ "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----"
+}';
+ $this->environmentHelper
+ ->expects($this->any())
+ ->method('getServerRoot')
+ ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/htaccessWithValidModifiedContent');
+ $this->fileAccessHelper
+ ->expects($this->once())
+ ->method('file_put_contents')
+ ->with(
+ \OC::$SERVERROOT . '/tests/data/integritycheck/htaccessWithValidModifiedContent/core/signature.json',
+ $this->callback(function ($signature) use ($expectedSignatureFileData) {
+ $expectedArray = json_decode($expectedSignatureFileData, true);
+ $actualArray = json_decode($signature, true);
+ $this->assertEquals($expectedArray, $actualArray);
+ return true;
+ })
+ );
+
+ $keyBundle = file_get_contents(__DIR__ .'/../../data/integritycheck/core.crt');
+ $rsaPrivateKey = file_get_contents(__DIR__ .'/../../data/integritycheck/core.key');
+ $rsa = new RSA();
+ $rsa->loadKey($rsaPrivateKey);
+ $x509 = new X509();
+ $x509->loadX509($keyBundle);
+ $this->checker->writeCoreSignature($x509, $rsa, \OC::$SERVERROOT . '/tests/data/integritycheck/htaccessWithValidModifiedContent');
+ }
+
+ public function testVerifyCoreSignatureWithoutSignatureData(): void {
+ $this->environmentHelper
+ ->expects($this->once())
+ ->method('getChannel')
+ ->willReturn('stable');
+ $this->config
+ ->expects($this->any())
+ ->method('getSystemValueBool')
+ ->with('integrity.check.disabled', false)
+ ->willReturn(false);
+
+ $expected = [
+ 'EXCEPTION' => [
+ 'class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class,
+ 'message' => 'Signature data not found.',
+ ],
+ ];
+ $this->assertSame($expected, $this->checker->verifyCoreSignature());
+ }
+
+ public function testVerifyCoreSignatureWithValidSignatureData(): void {
+ $this->environmentHelper
+ ->expects($this->once())
+ ->method('getChannel')
+ ->willReturn('stable');
+ $this->config
+ ->expects($this->any())
+ ->method('getSystemValueBool')
+ ->with('integrity.check.disabled', false)
+ ->willReturn(false);
+
+ $this->environmentHelper
+ ->expects($this->any())
+ ->method('getServerRoot')
+ ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/app/');
+ $signatureDataFile = '{
+ "hashes": {
+ "AnotherFile.txt": "1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112",
+ "subfolder\/file.txt": "410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b"
+ },
+ "signature": "dYoohBaWIFR\/To1FXEbMQB5apUhVYlEauBGSPo12nq84wxWkBx2EM3KDRgkB5Sub2tr0CgmAc2EVjPhKIEzAam26cyUb48bJziz1V6wvW7z4GZAfaJpzLkyHdSfV5117VSf5w1rDcAeZDXfGUaaNEJPWytaF4ZIxVge7f3NGshHy4odFVPADy\/u6c43BWvaOtJ4m3aJQbP6sxCO9dxwcm5yJJJR3n36jfh229sdWBxyl8BhwhH1e1DEv78\/aiL6ckKFPVNzx01R6yDFt3TgEMR97YZ\/R6lWiXG+dsJ305jNFlusLu518zBUvl7g5yjzGN778H29b2C8VLZKmi\/h1CH9jGdD72fCqCYdenD2uZKzb6dsUtXtvBmVcVT6BUGz41W1pkkEEB+YJpMrHILIxAiHRGv1+aZa9\/Oz8LWFd+BEUQjC2LJgojPnpzaG\/msw1nBkX16NNVDWWtJ25Bc\/r\/mG46rwjWB\/cmV6Lwt6KODiqlxgrC4lm9ALOCEWw+23OcYhLwNfQTYevXqHqsFfXOkhUnM8z5vDUb\/HBraB1DjFXN8iLK+1YewD4P495e+SRzrR79Oi3F8SEqRIzRLfN2rnW1BTms\/wYsz0p67cup1Slk1XlNmHwbWX25NVd2PPlLOvZRGoqcKFpIjC5few8THiZfyjiNFwt3RM0AFdZcXY=",
+ "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----"
+}';
+ $this->fileAccessHelper
+ ->expects($this->exactly(2))
+ ->method('file_get_contents')
+ ->withConsecutive(
+ [\OC::$SERVERROOT . '/tests/data/integritycheck/app//core/signature.json'],
+ [\OC::$SERVERROOT . '/tests/data/integritycheck/app//resources/codesigning/root.crt'],
+ )->willReturnOnConsecutiveCalls(
+ $signatureDataFile,
+ file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')
+ );
+
+ $this->assertSame([], $this->checker->verifyCoreSignature());
+ }
+
+ public function testVerifyCoreSignatureWithValidModifiedHtaccessSignatureData(): void {
+ $this->environmentHelper
+ ->expects($this->once())
+ ->method('getChannel')
+ ->willReturn('stable');
+ $this->config
+ ->expects($this->any())
+ ->method('getSystemValueBool')
+ ->with('integrity.check.disabled', false)
+ ->willReturn(false);
+
+ $this->environmentHelper
+ ->expects($this->any())
+ ->method('getServerRoot')
+ ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/htaccessWithValidModifiedContent');
+ $signatureDataFile = '{
+ "hashes": {
+ ".htaccess": "7e6a7a4d8ee4f3fbc45dd579407c643471575a9d127d1c75f6d0a49e80766c3c587104b2139ef76d2a4bffce3f45777900605aaa49519c9532909b71e5030227",
+ "subfolder\/.htaccess": "2c57b1e25050e11dc3ae975832f378c452159f7b69f818e47eeeafadd6ba568517461dcb4d843b90b906cd7c89d161bc1b89dff8e3ae0eb6f5088508c47befd1"
+ },
+ "signature": "YVwQvl9Dh8UebCumfgzFxfz3NiZJLmYG8oJVTfEBhulI4KXBnTG1jZTprf4XxG2XIriEYAZXsoXpu9xWsUFe9QfdncwoEpqJtGq7l6aVDTofX5Be5b03MQFJr4cflgllqW77QZ84D9O9qWF\/vNDAofXcwrzT04CxLDhyQgTCgYUnRjG9pnuP\/gtbDKbTjRvxhTyfg3T0Phv1+XAvpTPnH2q5A+1+LmiqziUJ1sMipsKo+jQP614eCi9qjmqhHIgLRgcuOBvsi4g5WUcdcAIZ6qLt5gm2Y3r6rKNVchosU9ZydMUTfjuejDbVwE2fNH5UUnV57fQBxwg9CfX7iFHqKv1bfv5Zviu12paShgWCB12uR3iH\/3lmTJn8K5Xqit3G4eymFaJ5IChdUThBp\/jhQSI2r8sPcZDYSJ\/UZKuFnezFdKhEBd5hMXe8aKAd6ijGDjLARksFuqpi1sS8llC5K1Q+DzktSL\/o64TY4Vuvykiwe\/BAk2SkL9voOtrvU7vfDBcuCPbDJnSBBC0ESpcXeClTBIn6xZ9WaxqoS7sinE\/kUwtWsRd04I7d79\/ouotyNb+mBhTuRsZT12p\/gn4JHXXNUAIpTwchYzGxbfNJ4kxnYBFZWVmvsSqOLFZu1yi5BP3ktA9yhFyWIa5659azRFEKRdXpVHtQVa4IgdhxEqA=",
+ "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----"
+}';
+ $this->fileAccessHelper
+ ->expects($this->exactly(2))
+ ->method('file_get_contents')
+ ->withConsecutive(
+ [\OC::$SERVERROOT . '/tests/data/integritycheck/htaccessWithValidModifiedContent/core/signature.json'],
+ [\OC::$SERVERROOT . '/tests/data/integritycheck/htaccessWithValidModifiedContent/resources/codesigning/root.crt'],
+ )
+ ->willReturnOnConsecutiveCalls(
+ $signatureDataFile,
+ file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')
+ );
+
+ $this->assertSame([], $this->checker->verifyCoreSignature());
+ }
+
+ /**
+ * See inline instruction on how to update the test assets when changing mimetypealiases.dist.json
+ */
+ public function testVerifyCoreSignatureWithModifiedMimetypelistSignatureData(): void {
+ $shippedMimetypeAliases = (array)json_decode(file_get_contents(\OC::$SERVERROOT . '/resources/config/mimetypealiases.dist.json'));
+ $allAliases = array_merge($shippedMimetypeAliases, ['my-custom/mimetype' => 'custom']);
+
+ $this->mimeTypeDetector
+ ->method('getOnlyDefaultAliases')
+ ->willReturn($shippedMimetypeAliases);
+
+ $this->mimeTypeDetector
+ ->method('getAllAliases')
+ ->willReturn($allAliases);
+
+ $oldMimetypeList = new GenerateMimetypeFileBuilder();
+ $all = $this->mimeTypeDetector->getAllAliases();
+ $newFile = $oldMimetypeList->generateFile($all);
+
+ // 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:
+ // file_put_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/mimetypeListModified/core/js/mimetypelist.js', $newFile);
+ // 2. Update signature.json using the following occ command:
+ // occ integrity:sign-core --privateKey=./tests/data/integritycheck/core.key --certificate=./tests/data/integritycheck/core.crt --path=./tests/data/integritycheck/mimetypeListModified
+ self::assertEquals($newFile, file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/mimetypeListModified/core/js/mimetypelist.js'));
+
+ $this->environmentHelper
+ ->expects($this->once())
+ ->method('getChannel')
+ ->willReturn('stable');
+ $this->config
+ ->expects($this->any())
+ ->method('getSystemValueBool')
+ ->with('integrity.check.disabled', false)
+ ->willReturn(false);
+
+ $this->environmentHelper
+ ->expects($this->any())
+ ->method('getServerRoot')
+ ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/mimetypeListModified');
+
+ $signatureDataFile = file_get_contents(__DIR__ .'/../../data/integritycheck/mimetypeListModified/core/signature.json');
+ $this->fileAccessHelper
+ ->method('file_get_contents')
+ ->willReturnMap([
+ [\OC::$SERVERROOT . '/tests/data/integritycheck/mimetypeListModified/core/signature.json', $signatureDataFile],
+ [\OC::$SERVERROOT . '/tests/data/integritycheck/mimetypeListModified/resources/codesigning/root.crt', file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')],
+ ]);
+
+ $this->assertSame([], $this->checker->verifyCoreSignature());
+ }
+
+ public function testVerifyCoreSignatureWithValidSignatureDataAndNotAlphabeticOrder(): void {
+ $this->environmentHelper
+ ->expects($this->once())
+ ->method('getChannel')
+ ->willReturn('stable');
+ $this->config
+ ->expects($this->any())
+ ->method('getSystemValueBool')
+ ->with('integrity.check.disabled', false)
+ ->willReturn(false);
+
+ $this->environmentHelper
+ ->expects($this->any())
+ ->method('getServerRoot')
+ ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/app/');
+ $signatureDataFile = '{
+ "hashes": {
+ "AnotherFile.txt": "1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112",
+ "subfolder\/file.txt": "410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b"
+ },
+ "signature": "dYoohBaWIFR\/To1FXEbMQB5apUhVYlEauBGSPo12nq84wxWkBx2EM3KDRgkB5Sub2tr0CgmAc2EVjPhKIEzAam26cyUb48bJziz1V6wvW7z4GZAfaJpzLkyHdSfV5117VSf5w1rDcAeZDXfGUaaNEJPWytaF4ZIxVge7f3NGshHy4odFVPADy\/u6c43BWvaOtJ4m3aJQbP6sxCO9dxwcm5yJJJR3n36jfh229sdWBxyl8BhwhH1e1DEv78\/aiL6ckKFPVNzx01R6yDFt3TgEMR97YZ\/R6lWiXG+dsJ305jNFlusLu518zBUvl7g5yjzGN778H29b2C8VLZKmi\/h1CH9jGdD72fCqCYdenD2uZKzb6dsUtXtvBmVcVT6BUGz41W1pkkEEB+YJpMrHILIxAiHRGv1+aZa9\/Oz8LWFd+BEUQjC2LJgojPnpzaG\/msw1nBkX16NNVDWWtJ25Bc\/r\/mG46rwjWB\/cmV6Lwt6KODiqlxgrC4lm9ALOCEWw+23OcYhLwNfQTYevXqHqsFfXOkhUnM8z5vDUb\/HBraB1DjFXN8iLK+1YewD4P495e+SRzrR79Oi3F8SEqRIzRLfN2rnW1BTms\/wYsz0p67cup1Slk1XlNmHwbWX25NVd2PPlLOvZRGoqcKFpIjC5few8THiZfyjiNFwt3RM0AFdZcXY=",
+ "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----"
+}';
+ $this->fileAccessHelper
+ ->expects($this->exactly(2))
+ ->method('file_get_contents')
+ ->withConsecutive(
+ [\OC::$SERVERROOT . '/tests/data/integritycheck/app//core/signature.json'],
+ [\OC::$SERVERROOT . '/tests/data/integritycheck/app//resources/codesigning/root.crt'],
+ )->willReturnOnConsecutiveCalls(
+ $signatureDataFile,
+ file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')
+ );
+
+ $this->assertSame([], $this->checker->verifyCoreSignature());
+ }
+
+ public function testVerifyCoreSignatureWithTamperedSignatureData(): void {
+ $this->environmentHelper
+ ->expects($this->once())
+ ->method('getChannel')
+ ->willReturn('stable');
+ $this->config
+ ->expects($this->any())
+ ->method('getSystemValueBool')
+ ->with('integrity.check.disabled', false)
+ ->willReturn(false);
+
+ $this->environmentHelper
+ ->expects($this->any())
+ ->method('getServerRoot')
+ ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/appWithInvalidData/');
+ $signatureDataFile = '{
+ "hashes": {
+ "AnotherFile.txt": "tampered",
+ "subfolder\/file.txt": "tampered"
+ },
+ "signature": "eXesvDm3pkek12xSwMG10y9suRES79Nye3jYNe5KYq1tTUPqRRNgxmMGAfcUro0zpLeAr2YgHeSMWtglblGOW7pmwGVPZ0O1Y4r1fE6jnep0kW+35PLIaqCorIOnCAtSzDNKBhwd1ow3zW2wC0DFouuEkIO8u5Fw28g8E8dp8zEk1xMblNPy+xtWkmYHrVJ\/dQgun1bYOF2ZFtAzatwndTI\/bGsy1i3Wsl+x6HyWKQdq8y8VObtOqKDH7uERBEpB9DHVyKflj1v1gQuEH6BhaRdATc7ee0MiQdGblraIySwYRdfo2d8i82OVKrenMB3SLwyCvDPyQ9iKpTOnSF52ZBqaqSXKM2N\/RAkweeBFQQCwcHhqxvB0cfbyHcbkOLeCZe\/tsh68IxwTiYgzvLfl7sOZ5arnZbzrPpZmB+hfV2omkoJ1tDwOWz9hEmLLNtfo2OxyUH1m0+XFaC+Gbn4WkVDgf7YZkwUcG+Qoa3oKDNMss8MEyZxewl2iDGZcf402dlidHRprlfmXbAYuVQ08\/a0HxIKYPGh\/nsMGmwnO15CWtFpAbhUA\/D5oRjsIxnvXaMDg0iAFpdu\/5Ffsj7g3EPdBkiQHNYK7YU1RRx609eH0bZyiIYHdUPw7ikLupvrebZmELqi3mqDFO99u4eISlxFJlUbUND3L4BtmWTWrKwI=",
+ "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----"
+}';
+ $this->fileAccessHelper
+ ->expects($this->exactly(2))
+ ->method('file_get_contents')
+ ->withConsecutive(
+ [\OC::$SERVERROOT . '/tests/data/integritycheck/appWithInvalidData//core/signature.json'],
+ [\OC::$SERVERROOT . '/tests/data/integritycheck/appWithInvalidData//resources/codesigning/root.crt'],
+ )->willReturnOnConsecutiveCalls(
+ $signatureDataFile,
+ file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')
+ );
+
+ $expected = [
+ 'EXCEPTION' => [
+ 'class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class,
+ 'message' => 'Signature could not get verified.',
+ ]
+ ];
+ $this->assertSame($expected, $this->checker->verifyCoreSignature());
+ }
+
+ public function testVerifyCoreSignatureWithTamperedFiles(): void {
+ $this->environmentHelper
+ ->expects($this->once())
+ ->method('getChannel')
+ ->willReturn('stable');
+ $this->config
+ ->expects($this->any())
+ ->method('getSystemValueBool')
+ ->with('integrity.check.disabled', false)
+ ->willReturn(false);
+
+ $this->environmentHelper
+ ->expects($this->any())
+ ->method('getServerRoot')
+ ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/appWithInvalidData/');
+ $signatureDataFile = '{
+ "hashes": {
+ "AnotherFile.txt": "1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112",
+ "subfolder\/file.txt": "410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b"
+ },
+ "signature": "dYoohBaWIFR\/To1FXEbMQB5apUhVYlEauBGSPo12nq84wxWkBx2EM3KDRgkB5Sub2tr0CgmAc2EVjPhKIEzAam26cyUb48bJziz1V6wvW7z4GZAfaJpzLkyHdSfV5117VSf5w1rDcAeZDXfGUaaNEJPWytaF4ZIxVge7f3NGshHy4odFVPADy\/u6c43BWvaOtJ4m3aJQbP6sxCO9dxwcm5yJJJR3n36jfh229sdWBxyl8BhwhH1e1DEv78\/aiL6ckKFPVNzx01R6yDFt3TgEMR97YZ\/R6lWiXG+dsJ305jNFlusLu518zBUvl7g5yjzGN778H29b2C8VLZKmi\/h1CH9jGdD72fCqCYdenD2uZKzb6dsUtXtvBmVcVT6BUGz41W1pkkEEB+YJpMrHILIxAiHRGv1+aZa9\/Oz8LWFd+BEUQjC2LJgojPnpzaG\/msw1nBkX16NNVDWWtJ25Bc\/r\/mG46rwjWB\/cmV6Lwt6KODiqlxgrC4lm9ALOCEWw+23OcYhLwNfQTYevXqHqsFfXOkhUnM8z5vDUb\/HBraB1DjFXN8iLK+1YewD4P495e+SRzrR79Oi3F8SEqRIzRLfN2rnW1BTms\/wYsz0p67cup1Slk1XlNmHwbWX25NVd2PPlLOvZRGoqcKFpIjC5few8THiZfyjiNFwt3RM0AFdZcXY=",
+ "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----"
+}';
+ $this->fileAccessHelper
+ ->expects($this->exactly(2))
+ ->method('file_get_contents')
+ ->withConsecutive(
+ [\OC::$SERVERROOT . '/tests/data/integritycheck/appWithInvalidData//core/signature.json'],
+ [\OC::$SERVERROOT . '/tests/data/integritycheck/appWithInvalidData//resources/codesigning/root.crt'],
+ )->willReturnOnConsecutiveCalls(
+ $signatureDataFile,
+ file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')
+ );
+
+ $expected = [
+ 'INVALID_HASH' => [
+ 'AnotherFile.txt' => [
+ 'expected' => '1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112',
+ 'current' => '7322348ba269c6d5522efe02f424fa3a0da319a7cd9c33142a5afe32a2d9af2da3a411f086fcfc96ff4301ea566f481dba0960c2abeef3594c4d930462f6584c',
+ ],
+ ],
+ 'FILE_MISSING' => [
+ 'subfolder/file.txt' => [
+ 'expected' => '410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b',
+ 'current' => '',
+ ],
+ ],
+ 'EXTRA_FILE' => [
+ 'UnecessaryFile' => [
+ 'expected' => '',
+ 'current' => 'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e',
+ ],
+ ],
+
+ ];
+ $this->assertSame($expected, $this->checker->verifyCoreSignature());
+ }
+
+ public function testVerifyCoreWithInvalidCertificate(): void {
+ $this->environmentHelper
+ ->expects($this->once())
+ ->method('getChannel')
+ ->willReturn('stable');
+ $this->config
+ ->expects($this->any())
+ ->method('getSystemValueBool')
+ ->with('integrity.check.disabled', false)
+ ->willReturn(false);
+
+ $this->environmentHelper
+ ->expects($this->any())
+ ->method('getServerRoot')
+ ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/app/');
+ $signatureDataFile = '{
+ "hashes": {
+ "AnotherFile.txt": "1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112",
+ "subfolder\/file.txt": "410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b"
+ },
+ "signature": "eXesvDm3pkek12xSwMG10y9suRES79Nye3jYNe5KYq1tTUPqRRNgxmMGAfcUro0zpLeAr2YgHeSMWtglblGOW7pmwGVPZ0O1Y4r1fE6jnep0kW+35PLIaqCorIOnCAtSzDNKBhwd1ow3zW2wC0DFouuEkIO8u5Fw28g8E8dp8zEk1xMblNPy+xtWkmYHrVJ\/dQgun1bYOF2ZFtAzatwndTI\/bGsy1i3Wsl+x6HyWKQdq8y8VObtOqKDH7uERBEpB9DHVyKflj1v1gQuEH6BhaRdATc7ee0MiQdGblraIySwYRdfo2d8i82OVKrenMB3SLwyCvDPyQ9iKpTOnSF52ZBqaqSXKM2N\/RAkweeBFQQCwcHhqxvB0cfbyHcbkOLeCZe\/tsh68IxwTiYgzvLfl7sOZ5arnZbzrPpZmB+hfV2omkoJ1tDwOWz9hEmLLNtfo2OxyUH1m0+XFaC+Gbn4WkVDgf7YZkwUcG+Qoa3oKDNMss8MEyZxewl2iDGZcf402dlidHRprlfmXbAYuVQ08\/a0HxIKYPGh\/nsMGmwnO15CWtFpAbhUA\/D5oRjsIxnvXaMDg0iAFpdu\/5Ffsj7g3EPdBkiQHNYK7YU1RRx609eH0bZyiIYHdUPw7ikLupvrebZmELqi3mqDFO99u4eISlxFJlUbUND3L4BtmWTWrKwI=",
+ "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUPYoweUxCPqbDW4ntuh7QvgyqSrgwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIyNDIwNloXDTE2MTEwMzIyNDIwNlowDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBAJui3nDbjOIjxNnthdBZplphujsN6u8K\r\nQ\/62zAuSwzXVp0+3IMgM\/2sepklVE8YfCyVJ5+SUJqnqHoUWVRVfs8jL0wW6nrHM\r\n\/lsscAguWCee4iAdNOqI9kq4+DUau8J45e62XA9mrAo\/8\/NKzFE2y2WduDoQZcm+\r\n8+dwcUUHXw2jl8dfrmvEMYSqTNDdb4rGmQpeV+dr9BLqr+x03U1Q08qCG9j7mSOz\r\ncvJENjOvC5uzAh5LCuCgxqG4o+mPzB0FtNnwoRRu6IsF3Y3KacRqPc30fB\/iXDn5\r\nBPr14uNxTTYWoZJ1F0tZrLzRbXdjJJOC+dnQurTtXWZ8WjPB1BWQYK7fW6t82mkN\r\n2Qe2xen99gs9nX5yY\/sHM3TKSJdM7AVCEv\/emW3gNjkvWTtRlN\/Nc7X2ckNwXcvo\r\n0yi3fSPjzXpDgLbhp1FzrMlHDn1VzmRT3r8wLByWa\/hsxrJDsBzwunMJYhXhmeKb\r\n3wX0tN\/EUJTWBntpwVOIGnRPD51oBoQUOMaEAq\/kz8PgN181bWZkJbRuf+FWkijQ\r\no+HR2lVF1jWXXst5Uc+s9HN81Uly7X4O9MMg0QxT4+wymtGDs6AOkwMi9rgBTrRB\r\n3tLU3XL2UIwRXgmd8cPtTu\/I6Bm7LdyaYtZ3yJTxRewq3nZdWypqBhD8uhpIYVkf\r\no4bxmGkVAQVTAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAKKAX5EHgU1grODnJ0of\r\nspFpgB1K67YvclNUyuU6NQ6zBJx1\/w1RnM7uxLcxiiWj1BbUhwZQ0ojmEHeUyi6O\r\nGrDVajwhTccDMmja3u5adhEncx65\/H+lD85IPRRkS2qBDssMDdJHhZ0uI+40nI7M\r\nMq1kFjl+6wiuqZXqps66DuLbk45g\/ZlrFIrIo3Ix5vj0OVqwT+gO4LYirJK6KgVS\r\nUttbcEsc\/yKU9ThnM8\/n4m2jstZXfzKPgOsJrQcZrFOtpj+CWmBzVElBSPlDT3Nh\r\nHSgOeTFJ8bQBxj2iG5dLA+JZJQKxyJ1gy2ZtxIJ2GyvLtSe8NUSqvfPWOaAKEUV2\r\ngniytnEFLr+PcD+9EGux6jZNuj6HmtWVThTfD5VGFmtlVU2z71ZRYY0kn6J3mmFc\r\nS2ecEcCUwqG5YNLncEUCyZhC2klWql2SHyGctCEyWWY7ikIDjVzYt2EbcFvLNBnP\r\ntybN1TYHRRZxlug00CCoOE9EZfk46FkZpDvU6KmqJRofkNZ5sj+SffyGcwYwNrDH\r\nKqe8m+9lHf3CRTIDeMu8r2xl1I6M6ZZfjabbmVP9Jd6WN4s6f1FlXDWzhlT1N0Qw\r\nGzJj6xB+SPtS3UV05tBlvbfA4e06D5G9uD7Q8ONcINtMS0xsSJ2oo82AqlpvlF\/q\r\noj7YKHsaTVGA+FxBktZHfoxD\r\n-----END CERTIFICATE-----"
+}';
+ $this->fileAccessHelper
+ ->expects($this->exactly(2))
+ ->method('file_get_contents')
+ ->withConsecutive(
+ [\OC::$SERVERROOT . '/tests/data/integritycheck/app//core/signature.json'],
+ [\OC::$SERVERROOT . '/tests/data/integritycheck/app//resources/codesigning/root.crt'],
+ )->willReturnOnConsecutiveCalls(
+ $signatureDataFile,
+ file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')
+ );
+
+ $expected = [
+ 'EXCEPTION' => [
+ 'class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class,
+ 'message' => 'Certificate is not valid.',
+ ]
+ ];
+ $this->assertSame($expected, $this->checker->verifyCoreSignature());
+ }
+
+ public function testVerifyCoreWithDifferentScope(): void {
+ $this->environmentHelper
+ ->expects($this->once())
+ ->method('getChannel')
+ ->willReturn('stable');
+ $this->config
+ ->expects($this->any())
+ ->method('getSystemValueBool')
+ ->with('integrity.check.disabled', false)
+ ->willReturn(false);
+
+ $this->environmentHelper
+ ->expects($this->any())
+ ->method('getServerRoot')
+ ->willReturn(\OC::$SERVERROOT . '/tests/data/integritycheck/app/');
+ $signatureDataFile = '{
+ "hashes": {
+ "AnotherFile.txt": "1570ca9420e37629de4328f48c51da29840ddeaa03ae733da4bf1d854b8364f594aac560601270f9e1797ed4cd57c1aea87bf44cf4245295c94f2e935a2f0112",
+ "subfolder\/file.txt": "410738545fb623c0a5c8a71f561e48ea69e3ada0981a455e920a5ae9bf17c6831ae654df324f9328ff8453de179276ae51931cca0fa71fe8ccde6c083ca0574b"
+ },
+ "signature": "EL49UaSeyMAqyMtqId+tgOhhwgOevPZsRLX4j2blnybAB6fN07z0936JqZV7+eMPiE30Idx+UCY6rCFN531Kqe9vAOCdgtHUSOjjKyKc+lvULESlMb6YQcrZrvDlEMMjzjH49ewG7Ai8sNN6HrRUd9U8ws+ewSkW2DOOBItj\/21RBnkrSt+2AtGXGigEvuTm57HrCYDj8\/lSkumC2GVkjLUHeLOKYo4PRNOr6yP5mED5v7zo66AWvXl2fKv54InZcdxsAk35lyK9DGZbk\/027ZRd0AOHT3LImRLvQ+8EAg3XLlRUy0hOFGgPC+jYonMzgYvsAXAXi2j8LnLJlsLwpFwu1k1B+kZVPMumKZvP9OvJb70EirecXmz62V+Jiyuaq7ne4y7Kp5gKZT\/T8SeZ0lFtCmPfYyzBB0y8s5ldmTTmdVYHs54t\/OCCW82HzQZxnFNPzDTRa8HglsaMKrqPtW59+R4UvRKSWhB8M\/Ah57qgzycvPV4KMz\/FbD4l\/\/9chRKSlCfc2k3b8ZSHNmi+EzCKgJjWIoKdgN1yax94puU8jfn8UW+G7H9Y1Jsf\/jox6QLyYEgtV1vOHY2xLT7fVs2vhyvkN2MNjJnmQ70gFG5Qz2lBz5wi6ZpB+tOfCcpbLxWAkoWoIrmC\/Ilqh7mfmRZ43g5upjkepHNd93ONuY8=",
+ "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEwTCCAqmgAwIBAgIUWv0iujufs5lUr0svCf\/qTQvoyKAwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIyNDk1M1oXDTE2MTEwMzIyNDk1M1owEjEQMA4GA1UEAwwHU29tZUFwcDCCAiIw\r\nDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK8q0x62agGSRBqeWsaeEwFfepMk\r\nF8cAobMMi50qHCv9IrOn\/ZH9l52xBrbIkErVmRjmly0d4JhD8Ymhidsh9ONKYl\/j\r\n+ishsZDM8eNNdp3Ew+fEYVvY1W7mR1qU24NWj0bzVsClI7hvPVIuw7AjfBDq1C5+\r\nA+ZSLSXYvOK2cEWjdxQfuNZwEZSjmA63DUllBIrm35IaTvfuyhU6BW9yHZxmb8+M\r\nw0xDv30D5UkE\/2N7Pa\/HQJLxCR+3zKibRK3nUyRDLSXxMkU9PnFNaPNX59VPgyj4\r\nGB1CFSToldJVPF4pzh7p36uGXZVxs8m3LFD4Ol8mhi7jkxDZjqFN46gzR0r23Py6\r\ndol9vfawGIoUwp9LvL0S7MvdRY0oazLXwClLP4OQ17zpSMAiCj7fgNT661JamPGj\r\nt5O7Zn2wA7I4ddDS\/HDTWCu98Zwc9fHIpsJPgCZ9awoqxi4Mnf7Pk9g5nnXhszGC\r\ncxxIASQKM+GhdzoRxKknax2RzUCwCzcPRtCj8AQT\/x\/mqN3PfRmlnFBNACUw9bpZ\r\nSOoNq2pCF9igftDWpSIXQ38pVpKLWowjjg3DVRmVKBgivHnUnVLyzYBahHPj0vaz\r\ntFtUFRaqXDnt+4qyUGyrT5h5pjZaTcHIcSB4PiarYwdVvgslgwnQzOUcGAzRWBD4\r\n6jV2brP5vFY3g6iPAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBACTY3CCHC+Z28gCf\r\nFWGKQ3wAKs+k4+0yoti0qm2EKX7rSGQ0PHSas6uW79WstC4Rj+DYkDtIhGMSg8FS\r\nHVGZHGBCc0HwdX+BOAt3zi4p7Sf3oQef70\/4imPoKxbAVCpd\/cveVcFyDC19j1yB\r\nBapwu87oh+muoeaZxOlqQI4UxjBlR\/uRSMhOn2UGauIr3dWJgAF4pGt7TtIzt+1v\r\n0uA6FtN1Y4R5O8AaJPh1bIG0CVvFBE58esGzjEYLhOydgKFnEP94kVPgJD5ds9C3\r\npPhEpo1dRpiXaF7WGIV1X6DI\/ipWvfrF7CEy6I\/kP1InY\/vMDjQjeDnJ\/VrXIWXO\r\nyZvHXVaN\/m+1RlETsH7YO\/QmxRue9ZHN3gvvWtmpCeA95sfpepOk7UcHxHZYyQbF\r\n49\/au8j+5tsr4A83xzsT1JbcKRxkAaQ7WDJpOnE5O1+H0fB+BaLakTg6XX9d4Fo7\r\n7Gin7hVWX7pL+JIyxMzME3LhfI61+CRcqZQIrpyaafUziPQbWIPfEs7h8tCOWyvW\r\nUO8ZLervYCB3j44ivkrxPlcBklDCqqKKBzDP9dYOtS\/P4RB1NkHA9+NTvmBpTonS\r\nSFXdg9fFMD7VfjDE3Vnk+8DWkVH5wBYowTAD7w9Wuzr7DumiAULexnP\/Y7xwxLv7\r\n4B+pXTAcRK0zECDEaX3npS8xWzrB\r\n-----END CERTIFICATE-----"
+}';
+ $this->fileAccessHelper
+ ->expects($this->exactly(2))
+ ->method('file_get_contents')
+ ->withConsecutive(
+ [\OC::$SERVERROOT . '/tests/data/integritycheck/app//core/signature.json'],
+ [\OC::$SERVERROOT . '/tests/data/integritycheck/app//resources/codesigning/root.crt'],
+ )->willReturnOnConsecutiveCalls(
+ $signatureDataFile,
+ file_get_contents(__DIR__ .'/../../data/integritycheck/root.crt')
+ );
+
+ $expected = [
+ 'EXCEPTION' => [
+ 'class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class,
+ 'message' => 'Certificate is not valid for required scope. (Requested: core, current: CN=SomeApp)',
+ ]
+ ];
+ $this->assertSame($expected, $this->checker->verifyCoreSignature());
+ }
+
+ public function testRunInstanceVerification(): void {
+ $this->checker = $this->getMockBuilder(\OC\IntegrityCheck\Checker::class)
+ ->setConstructorArgs([
+ $this->environmentHelper,
+ $this->fileAccessHelper,
+ $this->appLocator,
+ $this->config,
+ $this->appConfig,
+ $this->cacheFactory,
+ $this->appManager,
+ $this->mimeTypeDetector,
+ ])
+ ->setMethods([
+ 'verifyCoreSignature',
+ 'verifyAppSignature',
+ ])
+ ->getMock();
+
+ $this->checker
+ ->expects($this->once())
+ ->method('verifyCoreSignature');
+ $this->appManager
+ ->expects($this->once())
+ ->method('getAllAppsInAppsFolders')
+ ->willReturn([
+ 'files',
+ 'calendar',
+ 'contacts',
+ 'dav',
+ ]);
+ $this->appManager
+ ->expects($this->exactly(4))
+ ->method('isShipped')
+ ->withConsecutive(
+ ['files'],
+ ['calendar'],
+ ['contacts'],
+ ['dav'],
+ )->willReturnOnConsecutiveCalls(
+ true,
+ false,
+ false,
+ true,
+ );
+ $this->checker
+ ->expects($this->exactly(3))
+ ->method('verifyAppSignature')
+ ->withConsecutive(
+ ['files'],
+ ['calendar'],
+ ['dav'],
+ );
+ $this->appLocator
+ ->expects($this->exactly(2))
+ ->method('getAppPath')
+ ->withConsecutive(
+ ['calendar'],
+ ['contacts'],
+ )->willReturnOnConsecutiveCalls(
+ '/apps/calendar',
+ '/apps/contacts',
+ );
+ $this->fileAccessHelper
+ ->expects($this->exactly(2))
+ ->method('file_exists')
+ ->withConsecutive(
+ ['/apps/calendar/appinfo/signature.json'],
+ ['/apps/contacts/appinfo/signature.json'],
+ )->willReturnOnConsecutiveCalls(
+ true,
+ false,
+ );
+ $this->appConfig
+ ->expects($this->once())
+ ->method('deleteKey')
+ ->with('core', 'oc.integritycheck.checker');
+
+ $this->checker->runInstanceVerification();
+ }
+
+ public function testVerifyAppSignatureWithoutSignatureDataAndCodeCheckerDisabled(): void {
+ $this->environmentHelper
+ ->expects($this->once())
+ ->method('getChannel')
+ ->willReturn('stable');
+ $this->config
+ ->expects($this->any())
+ ->method('getSystemValueBool')
+ ->with('integrity.check.disabled', false)
+ ->willReturn(true);
+
+ $expected = [];
+ $this->assertSame($expected, $this->checker->verifyAppSignature('SomeApp'));
+ }
+
+ /**
+ * @return array
+ */
+ public function channelDataProvider() {
+ return [
+ ['stable', true],
+ ['git', false],
+ ];
+ }
+
+ /**
+ * @param string $channel
+ * @param bool $isCodeSigningEnforced
+ * @dataProvider channelDataProvider
+ */
+ public function testIsCodeCheckEnforced($channel, $isCodeSigningEnforced): void {
+ $this->environmentHelper
+ ->expects($this->once())
+ ->method('getChannel')
+ ->willReturn($channel);
+ $this->config
+ ->expects($this->any())
+ ->method('getSystemValueBool')
+ ->with('integrity.check.disabled', false)
+ ->willReturn(false);
+
+ $this->assertSame($isCodeSigningEnforced, $this->checker->isCodeCheckEnforced());
+ }
+
+ /**
+ * @param string $channel
+ * @dataProvider channelDataProvider
+ */
+ public function testIsCodeCheckEnforcedWithDisabledConfigSwitch($channel): void {
+ $this->environmentHelper
+ ->expects($this->once())
+ ->method('getChannel')
+ ->willReturn($channel);
+ $this->config
+ ->expects($this->any())
+ ->method('getSystemValueBool')
+ ->with('integrity.check.disabled', false)
+ ->willReturn(true);
+
+ $this->assertFalse(self::invokePrivate($this->checker, 'isCodeCheckEnforced'));
+ }
+}
diff --git a/tests/lib/IntegrityCheck/Helpers/AppLocatorTest.php b/tests/lib/IntegrityCheck/Helpers/AppLocatorTest.php
index d99a42e0d63..6d3006bb3c4 100644
--- a/tests/lib/IntegrityCheck/Helpers/AppLocatorTest.php
+++ b/tests/lib/IntegrityCheck/Helpers/AppLocatorTest.php
@@ -19,12 +19,12 @@ class AppLocatorTest extends TestCase {
$this->locator = new AppLocator();
}
- public function testGetAppPath() {
+ public function testGetAppPath(): void {
$this->assertSame(\OC_App::getAppPath('files'), $this->locator->getAppPath('files'));
}
- public function testGetAppPathNotExistentApp() {
+ 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 001733309a3..b8280d9816a 100644
--- a/tests/lib/IntegrityCheck/Helpers/EnvironmentHelperTest.php
+++ b/tests/lib/IntegrityCheck/Helpers/EnvironmentHelperTest.php
@@ -19,11 +19,11 @@ class EnvironmentHelperTest extends TestCase {
parent::setUp();
}
- public function testGetServerRoot() {
+ public function testGetServerRoot(): void {
$this->assertSame(\OC::$SERVERROOT, $this->environmentHelper->getServerRoot());
}
- public function testGetChannel() {
+ public function testGetChannel(): void {
$this->assertSame(\OC_Util::getChannel(), $this->environmentHelper->getChannel());
}
}
diff --git a/tests/lib/IntegrityCheck/Helpers/FileAccessHelperTest.php b/tests/lib/IntegrityCheck/Helpers/FileAccessHelperTest.php
index ea90b611f5e..866850b7cff 100644
--- a/tests/lib/IntegrityCheck/Helpers/FileAccessHelperTest.php
+++ b/tests/lib/IntegrityCheck/Helpers/FileAccessHelperTest.php
@@ -19,7 +19,7 @@ class FileAccessHelperTest extends TestCase {
$this->fileAccessHelper = new FileAccessHelper();
}
- public function testReadAndWrite() {
+ public function testReadAndWrite(): void {
$tempManager = \OC::$server->getTempManager();
$filePath = $tempManager->getTemporaryFile();
$data = 'SomeDataGeneratedByIntegrityCheck';
@@ -29,27 +29,27 @@ class FileAccessHelperTest extends TestCase {
}
- public function testFile_put_contentsWithException() {
+ public function testFile_put_contentsWithException(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Failed to write into /anabsolutelynotexistingfolder/on/the/system.txt');
$this->fileAccessHelper->file_put_contents('/anabsolutelynotexistingfolder/on/the/system.txt', 'MyFiles');
}
- public function testIs_writable() {
+ 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')));
}
- public function testAssertDirectoryExistsWithException() {
+ public function testAssertDirectoryExistsWithException(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Directory /anabsolutelynotexistingfolder/on/the/system does not exist.');
$this->fileAccessHelper->assertDirectoryExists('/anabsolutelynotexistingfolder/on/the/system');
}
- public function testAssertDirectoryExists() {
+ public function testAssertDirectoryExists(): void {
$this->fileAccessHelper->assertDirectoryExists(\OC::$server->getTempManager()->getTemporaryFolder('/testfolder/'));
$this->addToAssertionCount(1);
}
diff --git a/tests/lib/L10N/L10nTest.php b/tests/lib/L10N/L10nTest.php
index 92e40bf0e57..26f39e41c13 100644
--- a/tests/lib/L10N/L10nTest.php
+++ b/tests/lib/L10N/L10nTest.php
@@ -46,7 +46,7 @@ class L10nTest extends TestCase {
$this->assertEquals('Files:', $l->t('Files:'));
}
- public function testGermanPluralTranslations() {
+ public function testGermanPluralTranslations(): void {
$transFile = \OC::$SERVERROOT.'/tests/data/l10n/de.json';
$l = new L10N($this->getFactory(), 'test', 'de', 'de_AT', [$transFile]);
@@ -54,7 +54,7 @@ class L10nTest extends TestCase {
$this->assertEquals('2 Dateien', (string)$l->n('%n file', '%n files', 2));
}
- public function testRussianPluralTranslations() {
+ public function testRussianPluralTranslations(): void {
$transFile = \OC::$SERVERROOT.'/tests/data/l10n/ru.json';
$l = new L10N($this->getFactory(), 'test', 'ru', 'ru_UA', [$transFile]);
@@ -78,7 +78,7 @@ class L10nTest extends TestCase {
*/
}
- public function testCzechPluralTranslations() {
+ public function testCzechPluralTranslations(): void {
$transFile = \OC::$SERVERROOT.'/tests/data/l10n/cs.json';
$l = new L10N($this->getFactory(), 'test', 'cs', 'cs_CZ', [$transFile]);
@@ -87,7 +87,7 @@ class L10nTest extends TestCase {
$this->assertEquals('5 oken', (string)$l->n('%n window', '%n windows', 5));
}
- public function testGermanPluralWithCzechLocaleTranslations() {
+ public function testGermanPluralWithCzechLocaleTranslations(): void {
$transFile = \OC::$SERVERROOT.'/tests/data/l10n/de.json';
$l = new L10N($this->getFactory(), 'test', 'de', 'cs_CZ', [$transFile]);
@@ -156,7 +156,7 @@ class L10nTest extends TestCase {
/**
* @dataProvider localizationData
*/
- public function testNumericStringLocalization($expectedDate, $lang, $locale, $type, $value) {
+ public function testNumericStringLocalization($expectedDate, $lang, $locale, $type, $value): void {
$l = new L10N($this->getFactory(), 'test', $lang, $locale, []);
$this->assertSame($expectedDate, $l->l($type, $value));
}
@@ -174,7 +174,7 @@ class L10nTest extends TestCase {
* @param $lang
* @param $locale
*/
- public function testFirstWeekDay($expected, $lang, $locale) {
+ public function testFirstWeekDay($expected, $lang, $locale): void {
$l = new L10N($this->getFactory(), 'test', $lang, $locale, []);
$this->assertSame($expected, $l->l('firstday', 'firstday'));
}
@@ -192,22 +192,22 @@ class L10nTest extends TestCase {
* @param $lang
* @param $locale
*/
- public function testJSDate($expected, $lang, $locale) {
+ public function testJSDate($expected, $lang, $locale): void {
$l = new L10N($this->getFactory(), 'test', $lang, $locale, []);
$this->assertSame($expected, $l->l('jsdate', 'jsdate'));
}
- public function testFactoryGetLanguageCode() {
+ public function testFactoryGetLanguageCode(): void {
$l = $this->getFactory()->get('lib', 'de');
$this->assertEquals('de', $l->getLanguageCode());
}
- public function testServiceGetLanguageCode() {
+ public function testServiceGetLanguageCode(): void {
$l = \OCP\Util::getL10N('lib', 'de');
$this->assertEquals('de', $l->getLanguageCode());
}
- public function testWeekdayName() {
+ public function testWeekdayName(): void {
$l = \OCP\Util::getL10N('lib', 'de');
$this->assertEquals('Mo.', $l->l('weekdayName', new \DateTime('2017-11-6'), ['width' => 'abbreviated']));
}
@@ -217,7 +217,7 @@ class L10nTest extends TestCase {
* @param $locale
* @param $language
*/
- public function testFindLanguageFromLocale($locale, $language) {
+ public function testFindLanguageFromLocale($locale, $language): void {
$this->assertEquals(
$language,
\OC::$server->get(IFactory::class)->findLanguageFromLocale('lib', $locale)
diff --git a/tests/lib/L10N/LanguageIteratorTest.php b/tests/lib/L10N/LanguageIteratorTest.php
index 02c17a842d3..79998c36354 100644
--- a/tests/lib/L10N/LanguageIteratorTest.php
+++ b/tests/lib/L10N/LanguageIteratorTest.php
@@ -60,7 +60,7 @@ class LanguageIteratorTest extends TestCase {
/**
* @dataProvider languageSettingsProvider
*/
- public function testIterator($forcedLang, $userLang, $sysLang, $expectedValues) {
+ public function testIterator($forcedLang, $userLang, $sysLang, $expectedValues): void {
$this->config->expects($this->any())
->method('getSystemValue')
->willReturnMap([
diff --git a/tests/lib/LargeFileHelperGetFileSizeTest.php b/tests/lib/LargeFileHelperGetFileSizeTest.php
index b239c10e20a..247886fee6a 100644
--- a/tests/lib/LargeFileHelperGetFileSizeTest.php
+++ b/tests/lib/LargeFileHelperGetFileSizeTest.php
@@ -58,7 +58,7 @@ class LargeFileHelperGetFileSizeTest extends TestCase {
/**
* @dataProvider dataFileNameProvider
*/
- public function testGetFileSizeViaExec($filename, $fileSize) {
+ public function testGetFileSizeViaExec($filename, $fileSize): void {
if (escapeshellarg('strängé') !== '\'strängé\'') {
$this->markTestSkipped('Your escapeshell args removes accents');
}
@@ -76,7 +76,7 @@ class LargeFileHelperGetFileSizeTest extends TestCase {
/**
* @dataProvider dataFileNameProvider
*/
- public function testGetFileSizeNative($filename, $fileSize) {
+ public function testGetFileSizeNative($filename, $fileSize): void {
$this->assertSame(
$fileSize,
$this->helper->getFileSizeNative($filename)
diff --git a/tests/lib/LargeFileHelperTest.php b/tests/lib/LargeFileHelperTest.php
index 66c83f122af..2cccfa441ab 100644
--- a/tests/lib/LargeFileHelperTest.php
+++ b/tests/lib/LargeFileHelperTest.php
@@ -15,21 +15,21 @@ class LargeFileHelperTest extends TestCase {
$this->helper = new \OC\LargeFileHelper;
}
- public function testFormatUnsignedIntegerFloat() {
+ public function testFormatUnsignedIntegerFloat(): void {
$this->assertSame(
'9007199254740992',
$this->helper->formatUnsignedInteger((float)9007199254740992)
);
}
- public function testFormatUnsignedIntegerInt() {
+ public function testFormatUnsignedIntegerInt(): void {
$this->assertSame(
PHP_INT_SIZE === 4 ? '4294967295' : '18446744073709551615',
$this->helper->formatUnsignedInteger(-1)
);
}
- public function testFormatUnsignedIntegerString() {
+ public function testFormatUnsignedIntegerString(): void {
$this->assertSame(
'9007199254740993',
$this->helper->formatUnsignedInteger('9007199254740993')
@@ -37,7 +37,7 @@ class LargeFileHelperTest extends TestCase {
}
- public function testFormatUnsignedIntegerStringException() {
+ public function testFormatUnsignedIntegerStringException(): void {
$this->expectException(\UnexpectedValueException::class);
$this->helper->formatUnsignedInteger('900ABCD254740993');
diff --git a/tests/lib/LegacyHelperTest.php b/tests/lib/LegacyHelperTest.php
index 85960ef6f08..ea359d4e50c 100644
--- a/tests/lib/LegacyHelperTest.php
+++ b/tests/lib/LegacyHelperTest.php
@@ -26,7 +26,7 @@ class LegacyHelperTest extends \Test\TestCase {
/**
* @dataProvider humanFileSizeProvider
*/
- public function testHumanFileSize($expected, $input) {
+ public function testHumanFileSize($expected, $input): void {
$result = OC_Helper::humanFileSize($input);
$this->assertEquals($expected, $result);
}
@@ -46,7 +46,7 @@ class LegacyHelperTest extends \Test\TestCase {
/**
* @dataProvider providesComputerFileSize
*/
- public function testComputerFileSize($expected, $input) {
+ public function testComputerFileSize($expected, $input): void {
$result = OC_Helper::computerFileSize($input);
$this->assertEquals($expected, $result);
}
@@ -62,7 +62,7 @@ class LegacyHelperTest extends \Test\TestCase {
];
}
- public function testMb_array_change_key_case() {
+ public function testMb_array_change_key_case(): void {
$arrayStart = [
'Foo' => 'bar',
'Bar' => 'foo',
@@ -88,7 +88,7 @@ class LegacyHelperTest extends \Test\TestCase {
$this->assertEquals($result, $expected);
}
- public function testRecursiveArraySearch() {
+ public function testRecursiveArraySearch(): void {
$haystack = [
'Foo' => 'own',
'Bar' => 'Cloud',
@@ -102,7 +102,7 @@ class LegacyHelperTest extends \Test\TestCase {
$this->assertFalse($result);
}
- public function testBuildNotExistingFileNameForView() {
+ public function testBuildNotExistingFileNameForView(): void {
$viewMock = $this->createMock(View::class);
$this->assertEquals('/filename', OC_Helper::buildNotExistingFileNameForView('/', 'filename', $viewMock));
$this->assertEquals('dir/filename.ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename.ext', $viewMock));
@@ -205,7 +205,7 @@ class LegacyHelperTest extends \Test\TestCase {
/**
* @dataProvider streamCopyDataProvider
*/
- public function testStreamCopy($expectedCount, $expectedResult, $source, $target) {
+ public function testStreamCopy($expectedCount, $expectedResult, $source, $target): void {
if (is_string($source)) {
$source = fopen($source, 'r');
}
@@ -239,7 +239,7 @@ class LegacyHelperTest extends \Test\TestCase {
/**
* Tests recursive folder deletion with rmdirr()
*/
- public function testRecursiveFolderDeletion() {
+ 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);
diff --git a/tests/lib/Lock/DBLockingProviderTest.php b/tests/lib/Lock/DBLockingProviderTest.php
index 356b55f577e..1c02e8d7d77 100644
--- a/tests/lib/Lock/DBLockingProviderTest.php
+++ b/tests/lib/Lock/DBLockingProviderTest.php
@@ -59,7 +59,7 @@ class DBLockingProviderTest extends LockingProvider {
parent::tearDown();
}
- public function testCleanEmptyLocks() {
+ public function testCleanEmptyLocks(): void {
$this->currentTime = 100;
$this->instance->acquireLock('foo', ILockingProvider::LOCK_EXCLUSIVE);
$this->instance->acquireLock('asd', ILockingProvider::LOCK_EXCLUSIVE);
@@ -96,7 +96,7 @@ class DBLockingProviderTest extends LockingProvider {
return $rows;
}
- public function testDoubleShared() {
+ public function testDoubleShared(): void {
$this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED);
$this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED);
diff --git a/tests/lib/Lock/LockingProvider.php b/tests/lib/Lock/LockingProvider.php
index 2aa3980542b..b7e301c55a6 100644
--- a/tests/lib/Lock/LockingProvider.php
+++ b/tests/lib/Lock/LockingProvider.php
@@ -27,19 +27,19 @@ abstract class LockingProvider extends TestCase {
$this->instance = $this->getInstance();
}
- public function testExclusiveLock() {
+ public function testExclusiveLock(): void {
$this->instance->acquireLock('foo', ILockingProvider::LOCK_EXCLUSIVE);
$this->assertTrue($this->instance->isLocked('foo', ILockingProvider::LOCK_EXCLUSIVE));
$this->assertFalse($this->instance->isLocked('foo', ILockingProvider::LOCK_SHARED));
}
- public function testSharedLock() {
+ public function testSharedLock(): void {
$this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED);
$this->assertFalse($this->instance->isLocked('foo', ILockingProvider::LOCK_EXCLUSIVE));
$this->assertTrue($this->instance->isLocked('foo', ILockingProvider::LOCK_SHARED));
}
- public function testDoubleSharedLock() {
+ public function testDoubleSharedLock(): void {
$this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED);
$this->assertFalse($this->instance->isLocked('foo', ILockingProvider::LOCK_EXCLUSIVE));
$this->assertTrue($this->instance->isLocked('foo', ILockingProvider::LOCK_SHARED));
@@ -47,7 +47,7 @@ abstract class LockingProvider extends TestCase {
$this->assertTrue($this->instance->isLocked('foo', ILockingProvider::LOCK_SHARED));
}
- public function testReleaseSharedLock() {
+ public function testReleaseSharedLock(): void {
$this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED);
$this->assertFalse($this->instance->isLocked('foo', ILockingProvider::LOCK_EXCLUSIVE));
$this->assertTrue($this->instance->isLocked('foo', ILockingProvider::LOCK_SHARED));
@@ -60,7 +60,7 @@ abstract class LockingProvider extends TestCase {
}
- public function testDoubleExclusiveLock() {
+ public function testDoubleExclusiveLock(): void {
$this->expectException(\OCP\Lock\LockedException::class);
$this->instance->acquireLock('foo', ILockingProvider::LOCK_EXCLUSIVE);
@@ -68,7 +68,7 @@ abstract class LockingProvider extends TestCase {
$this->instance->acquireLock('foo', ILockingProvider::LOCK_EXCLUSIVE);
}
- public function testReleaseExclusiveLock() {
+ public function testReleaseExclusiveLock(): void {
$this->instance->acquireLock('foo', ILockingProvider::LOCK_EXCLUSIVE);
$this->assertTrue($this->instance->isLocked('foo', ILockingProvider::LOCK_EXCLUSIVE));
$this->instance->releaseLock('foo', ILockingProvider::LOCK_EXCLUSIVE);
@@ -77,7 +77,7 @@ abstract class LockingProvider extends TestCase {
}
- public function testExclusiveLockAfterShared() {
+ public function testExclusiveLockAfterShared(): void {
$this->expectException(\OCP\Lock\LockedException::class);
$this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED);
@@ -85,7 +85,7 @@ abstract class LockingProvider extends TestCase {
$this->instance->acquireLock('foo', ILockingProvider::LOCK_EXCLUSIVE);
}
- public function testExclusiveLockAfterSharedReleased() {
+ public function testExclusiveLockAfterSharedReleased(): void {
$this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED);
$this->assertTrue($this->instance->isLocked('foo', ILockingProvider::LOCK_SHARED));
$this->instance->releaseLock('foo', ILockingProvider::LOCK_SHARED);
@@ -93,7 +93,7 @@ abstract class LockingProvider extends TestCase {
$this->assertTrue($this->instance->isLocked('foo', ILockingProvider::LOCK_EXCLUSIVE));
}
- public function testReleaseAll() {
+ public function testReleaseAll(): void {
$this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED);
$this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED);
$this->instance->acquireLock('bar', ILockingProvider::LOCK_SHARED);
@@ -108,7 +108,7 @@ abstract class LockingProvider extends TestCase {
$this->assertFalse($this->instance->isLocked('fizz#A=23', ILockingProvider::LOCK_EXCLUSIVE));
}
- public function testReleaseAllAfterChange() {
+ public function testReleaseAllAfterChange(): void {
$this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED);
$this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED);
$this->instance->acquireLock('bar', ILockingProvider::LOCK_SHARED);
@@ -124,7 +124,7 @@ abstract class LockingProvider extends TestCase {
$this->assertFalse($this->instance->isLocked('asd', ILockingProvider::LOCK_EXCLUSIVE));
}
- public function testReleaseAllAfterUnlock() {
+ public function testReleaseAllAfterUnlock(): void {
$this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED);
$this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED);
$this->instance->acquireLock('bar', ILockingProvider::LOCK_SHARED);
@@ -138,7 +138,7 @@ abstract class LockingProvider extends TestCase {
$this->assertFalse($this->instance->isLocked('asd', ILockingProvider::LOCK_EXCLUSIVE));
}
- public function testReleaseAfterReleaseAll() {
+ public function testReleaseAfterReleaseAll(): void {
$this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED);
$this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED);
@@ -151,7 +151,7 @@ abstract class LockingProvider extends TestCase {
- public function testSharedLockAfterExclusive() {
+ public function testSharedLockAfterExclusive(): void {
$this->expectException(\OCP\Lock\LockedException::class);
$this->instance->acquireLock('foo', ILockingProvider::LOCK_EXCLUSIVE);
@@ -159,7 +159,7 @@ abstract class LockingProvider extends TestCase {
$this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED);
}
- public function testLockedExceptionHasPathForShared() {
+ public function testLockedExceptionHasPathForShared(): void {
try {
$this->instance->acquireLock('foo', ILockingProvider::LOCK_EXCLUSIVE);
$this->assertTrue($this->instance->isLocked('foo', ILockingProvider::LOCK_EXCLUSIVE));
@@ -171,7 +171,7 @@ abstract class LockingProvider extends TestCase {
}
}
- public function testLockedExceptionHasPathForExclusive() {
+ public function testLockedExceptionHasPathForExclusive(): void {
try {
$this->instance->acquireLock('foo', ILockingProvider::LOCK_EXCLUSIVE);
$this->assertTrue($this->instance->isLocked('foo', ILockingProvider::LOCK_EXCLUSIVE));
@@ -183,14 +183,14 @@ abstract class LockingProvider extends TestCase {
}
}
- public function testChangeLockToExclusive() {
+ public function testChangeLockToExclusive(): void {
$this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED);
$this->instance->changeLock('foo', ILockingProvider::LOCK_EXCLUSIVE);
$this->assertFalse($this->instance->isLocked('foo', ILockingProvider::LOCK_SHARED));
$this->assertTrue($this->instance->isLocked('foo', ILockingProvider::LOCK_EXCLUSIVE));
}
- public function testChangeLockToShared() {
+ public function testChangeLockToShared(): void {
$this->instance->acquireLock('foo', ILockingProvider::LOCK_EXCLUSIVE);
$this->instance->changeLock('foo', ILockingProvider::LOCK_SHARED);
$this->assertFalse($this->instance->isLocked('foo', ILockingProvider::LOCK_EXCLUSIVE));
@@ -198,7 +198,7 @@ abstract class LockingProvider extends TestCase {
}
- public function testChangeLockToExclusiveDoubleShared() {
+ public function testChangeLockToExclusiveDoubleShared(): void {
$this->expectException(\OCP\Lock\LockedException::class);
$this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED);
@@ -207,14 +207,14 @@ abstract class LockingProvider extends TestCase {
}
- public function testChangeLockToExclusiveNoShared() {
+ public function testChangeLockToExclusiveNoShared(): void {
$this->expectException(\OCP\Lock\LockedException::class);
$this->instance->changeLock('foo', ILockingProvider::LOCK_EXCLUSIVE);
}
- public function testChangeLockToExclusiveFromExclusive() {
+ public function testChangeLockToExclusiveFromExclusive(): void {
$this->expectException(\OCP\Lock\LockedException::class);
$this->instance->acquireLock('foo', ILockingProvider::LOCK_EXCLUSIVE);
@@ -222,21 +222,21 @@ abstract class LockingProvider extends TestCase {
}
- public function testChangeLockToSharedNoExclusive() {
+ public function testChangeLockToSharedNoExclusive(): void {
$this->expectException(\OCP\Lock\LockedException::class);
$this->instance->changeLock('foo', ILockingProvider::LOCK_SHARED);
}
- public function testChangeLockToSharedFromShared() {
+ public function testChangeLockToSharedFromShared(): void {
$this->expectException(\OCP\Lock\LockedException::class);
$this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED);
$this->instance->changeLock('foo', ILockingProvider::LOCK_SHARED);
}
- public function testReleaseNonExistingShared() {
+ public function testReleaseNonExistingShared(): void {
$this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED);
$this->instance->releaseLock('foo', ILockingProvider::LOCK_SHARED);
diff --git a/tests/lib/Lock/NonCachingDBLockingProviderTest.php b/tests/lib/Lock/NonCachingDBLockingProviderTest.php
index 5750d02fc4e..b79709a08e7 100644
--- a/tests/lib/Lock/NonCachingDBLockingProviderTest.php
+++ b/tests/lib/Lock/NonCachingDBLockingProviderTest.php
@@ -22,7 +22,7 @@ class NonCachingDBLockingProviderTest extends DBLockingProviderTest {
return new \OC\Lock\DBLockingProvider($this->connection, $this->timeFactory, 3600, false);
}
- public function testDoubleShared() {
+ public function testDoubleShared(): void {
$this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED);
$this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED);
diff --git a/tests/lib/Lockdown/Filesystem/NoFSTest.php b/tests/lib/Lockdown/Filesystem/NoFSTest.php
index 7a636fbaaaa..dedcf580992 100644
--- a/tests/lib/Lockdown/Filesystem/NoFSTest.php
+++ b/tests/lib/Lockdown/Filesystem/NoFSTest.php
@@ -38,7 +38,7 @@ class NoFSTest extends \Test\TestCase {
$this->createUser('foo', 'var');
}
- public function testSetupFS() {
+ public function testSetupFS(): void {
\OC_Util::tearDownFS();
\OC_Util::setupFS('foo');
diff --git a/tests/lib/Lockdown/Filesystem/NullCacheTest.php b/tests/lib/Lockdown/Filesystem/NullCacheTest.php
index eda4e10b1a6..5e120e9bdc7 100644
--- a/tests/lib/Lockdown/Filesystem/NullCacheTest.php
+++ b/tests/lib/Lockdown/Filesystem/NullCacheTest.php
@@ -22,15 +22,15 @@ class NulLCacheTest extends \Test\TestCase {
$this->cache = new NullCache();
}
- public function testGetNumericStorageId() {
+ public function testGetNumericStorageId(): void {
$this->assertSame(-1, $this->cache->getNumericStorageId());
}
- public function testGetEmpty() {
+ public function testGetEmpty(): void {
$this->assertNull($this->cache->get('foo'));
}
- public function testGet() {
+ public function testGet(): void {
$data = $this->cache->get('');
$this->assertEquals(-1, $data['fileid']);
@@ -44,63 +44,63 @@ class NulLCacheTest extends \Test\TestCase {
$this->assertEquals(Constants::PERMISSION_READ, $data['permissions']);
}
- public function testGetFolderContents() {
+ public function testGetFolderContents(): void {
$this->assertSame([], $this->cache->getFolderContents('foo'));
}
- public function testGetFolderContentsById() {
+ public function testGetFolderContentsById(): void {
$this->assertSame([], $this->cache->getFolderContentsById(42));
}
- public function testPut() {
+ public function testPut(): void {
$this->expectException(ForbiddenException::class);
$this->expectExceptionMessage('This request is not allowed to access the filesystem');
$this->cache->put('foo', ['size' => 100]);
}
- public function testInsert() {
+ public function testInsert(): void {
$this->expectException(ForbiddenException::class);
$this->expectExceptionMessage('This request is not allowed to access the filesystem');
$this->cache->insert('foo', ['size' => 100]);
}
- public function testUpdate() {
+ public function testUpdate(): void {
$this->expectException(ForbiddenException::class);
$this->expectExceptionMessage('This request is not allowed to access the filesystem');
$this->cache->update('foo', ['size' => 100]);
}
- public function testGetId() {
+ public function testGetId(): void {
$this->assertSame(-1, $this->cache->getId('foo'));
}
- public function testGetParentId() {
+ public function testGetParentId(): void {
$this->assertSame(-1, $this->cache->getParentId('foo'));
}
- public function testInCache() {
+ public function testInCache(): void {
$this->assertTrue($this->cache->inCache(''));
$this->assertFalse($this->cache->inCache('foo'));
}
- public function testRemove() {
+ public function testRemove(): void {
$this->expectException(ForbiddenException::class);
$this->expectExceptionMessage('This request is not allowed to access the filesystem');
$this->cache->remove('foo');
}
- public function testMove() {
+ public function testMove(): void {
$this->expectException(ForbiddenException::class);
$this->expectExceptionMessage('This request is not allowed to access the filesystem');
$this->cache->move('foo', 'bar');
}
- public function testMoveFromCache() {
+ public function testMoveFromCache(): void {
$sourceCache = $this->createMock(ICache::class);
$this->expectException(ForbiddenException::class);
@@ -109,27 +109,27 @@ class NulLCacheTest extends \Test\TestCase {
$this->cache->moveFromCache($sourceCache, 'foo', 'bar');
}
- public function testGetStatus() {
+ public function testGetStatus(): void {
$this->assertSame(ICache::COMPLETE, $this->cache->getStatus('foo'));
}
- public function testSearch() {
+ public function testSearch(): void {
$this->assertSame([], $this->cache->search('foo'));
}
- public function testSearchByMime() {
+ public function testSearchByMime(): void {
$this->assertSame([], $this->cache->searchByMime('foo'));
}
- public function testGetIncomplete() {
+ public function testGetIncomplete(): void {
$this->assertSame([], $this->cache->getIncomplete());
}
- public function testGetPathById() {
+ public function testGetPathById(): void {
$this->assertSame('', $this->cache->getPathById(42));
}
- public function testNormalize() {
+ public function testNormalize(): void {
$this->assertSame('foo/ bar /', $this->cache->normalize('foo/ bar /'));
}
}
diff --git a/tests/lib/Lockdown/Filesystem/NullStorageTest.php b/tests/lib/Lockdown/Filesystem/NullStorageTest.php
index 727ccb83e21..331adeb8a54 100644
--- a/tests/lib/Lockdown/Filesystem/NullStorageTest.php
+++ b/tests/lib/Lockdown/Filesystem/NullStorageTest.php
@@ -24,178 +24,178 @@ class NullStorageTest extends TestCase {
$this->storage = new NullStorage([]);
}
- public function testGetId() {
+ public function testGetId(): void {
$this->assertSame('null', $this->storage->getId());
}
- public function testMkdir() {
+ public function testMkdir(): void {
$this->expectException(ForbiddenException::class);
$this->expectExceptionMessage('This request is not allowed to access the filesystem');
$this->storage->mkdir('foo');
}
- public function testRmdir() {
+ public function testRmdir(): void {
$this->expectException(ForbiddenException::class);
$this->expectExceptionMessage('This request is not allowed to access the filesystem');
$this->storage->rmdir('foo');
}
- public function testOpendir() {
+ public function testOpendir(): void {
$this->assertInstanceOf(IteratorDirectory::class, $this->storage->opendir('foo'));
}
- public function testIs_dir() {
+ public function testIs_dir(): void {
$this->assertTrue($this->storage->is_dir(''));
$this->assertFalse($this->storage->is_dir('foo'));
}
- public function testIs_file() {
+ public function testIs_file(): void {
$this->assertFalse($this->storage->is_file('foo'));
}
- public function testStat() {
+ public function testStat(): void {
$this->expectException(ForbiddenException::class);
$this->expectExceptionMessage('This request is not allowed to access the filesystem');
$this->storage->stat('foo');
}
- public function testFiletype() {
+ public function testFiletype(): void {
$this->assertSame('dir', $this->storage->filetype(''));
$this->assertFalse($this->storage->filetype('foo'));
}
- public function testFilesize() {
+ public function testFilesize(): void {
$this->expectException(ForbiddenException::class);
$this->expectExceptionMessage('This request is not allowed to access the filesystem');
$this->storage->filesize('foo');
}
- public function testIsCreatable() {
+ public function testIsCreatable(): void {
$this->assertFalse($this->storage->isCreatable('foo'));
}
- public function testIsReadable() {
+ public function testIsReadable(): void {
$this->assertTrue($this->storage->isReadable(''));
$this->assertFalse($this->storage->isReadable('foo'));
}
- public function testIsUpdatable() {
+ public function testIsUpdatable(): void {
$this->assertFalse($this->storage->isUpdatable('foo'));
}
- public function testIsDeletable() {
+ public function testIsDeletable(): void {
$this->assertFalse($this->storage->isDeletable('foo'));
}
- public function testIsSharable() {
+ public function testIsSharable(): void {
$this->assertFalse($this->storage->isSharable('foo'));
}
- public function testGetPermissions() {
+ public function testGetPermissions(): void {
$this->assertNull($this->storage->getPermissions('foo'));
}
- public function testFile_exists() {
+ public function testFile_exists(): void {
$this->assertTrue($this->storage->file_exists(''));
$this->assertFalse($this->storage->file_exists('foo'));
}
- public function testFilemtime() {
+ public function testFilemtime(): void {
$this->assertFalse($this->storage->filemtime('foo'));
}
- public function testFile_get_contents() {
+ public function testFile_get_contents(): void {
$this->expectException(ForbiddenException::class);
$this->expectExceptionMessage('This request is not allowed to access the filesystem');
$this->storage->file_get_contents('foo');
}
- public function testFile_put_contents() {
+ public function testFile_put_contents(): void {
$this->expectException(ForbiddenException::class);
$this->expectExceptionMessage('This request is not allowed to access the filesystem');
$this->storage->file_put_contents('foo', 'bar');
}
- public function testUnlink() {
+ public function testUnlink(): void {
$this->expectException(ForbiddenException::class);
$this->expectExceptionMessage('This request is not allowed to access the filesystem');
$this->storage->unlink('foo');
}
- public function testRename() {
+ public function testRename(): void {
$this->expectException(ForbiddenException::class);
$this->expectExceptionMessage('This request is not allowed to access the filesystem');
$this->storage->rename('foo', 'bar');
}
- public function testCopy() {
+ public function testCopy(): void {
$this->expectException(ForbiddenException::class);
$this->expectExceptionMessage('This request is not allowed to access the filesystem');
$this->storage->copy('foo', 'bar');
}
- public function testFopen() {
+ public function testFopen(): void {
$this->expectException(ForbiddenException::class);
$this->expectExceptionMessage('This request is not allowed to access the filesystem');
$this->storage->fopen('foo', 'R');
}
- public function testGetMimeType() {
+ public function testGetMimeType(): void {
$this->expectException(ForbiddenException::class);
$this->expectExceptionMessage('This request is not allowed to access the filesystem');
$this->storage->getMimeType('foo');
}
- public function testHash() {
+ public function testHash(): void {
$this->expectException(ForbiddenException::class);
$this->expectExceptionMessage('This request is not allowed to access the filesystem');
$this->storage->hash('md5', 'foo', true);
}
- public function testFree_space() {
+ public function testFree_space(): void {
$this->assertSame(FileInfo::SPACE_UNKNOWN, $this->storage->free_space('foo'));
}
- public function testTouch() {
+ public function testTouch(): void {
$this->expectException(ForbiddenException::class);
$this->expectExceptionMessage('This request is not allowed to access the filesystem');
$this->storage->touch('foo');
}
- public function testGetLocalFile() {
+ public function testGetLocalFile(): void {
$this->assertFalse($this->storage->getLocalFile('foo'));
}
- public function testHasUpdated() {
+ public function testHasUpdated(): void {
$this->assertFalse($this->storage->hasUpdated('foo', 42));
}
- public function testGetETag() {
+ public function testGetETag(): void {
$this->assertSame('', $this->storage->getETag('foo'));
}
- public function testIsLocal() {
+ public function testIsLocal(): void {
$this->assertFalse($this->storage->isLocal());
}
- public function testGetDirectDownload() {
+ public function testGetDirectDownload(): void {
$this->assertFalse($this->storage->getDirectDownload('foo'));
}
- public function testCopyFromStorage() {
+ public function testCopyFromStorage(): void {
$sourceStorage = $this->createMock(Storage::class);
$this->expectException(ForbiddenException::class);
@@ -204,7 +204,7 @@ class NullStorageTest extends TestCase {
$this->storage->copyFromStorage($sourceStorage, 'foo', 'bar');
}
- public function testMoveFromStorage() {
+ public function testMoveFromStorage(): void {
$sourceStorage = $this->createMock(Storage::class);
$this->expectException(ForbiddenException::class);
@@ -218,11 +218,11 @@ class NullStorageTest extends TestCase {
return true;
}
- public function testGetOwner() {
+ public function testGetOwner(): void {
$this->assertNull($this->storage->getOwner('foo'));
}
- public function testGetCache() {
+ public function testGetCache(): void {
$this->assertInstanceOf(NullCache::class, $this->storage->getCache('foo'));
}
}
diff --git a/tests/lib/Lockdown/LockdownManagerTest.php b/tests/lib/Lockdown/LockdownManagerTest.php
index bb71a6e63de..1f747378c02 100644
--- a/tests/lib/Lockdown/LockdownManagerTest.php
+++ b/tests/lib/Lockdown/LockdownManagerTest.php
@@ -23,12 +23,12 @@ class LockdownManagerTest extends TestCase {
};
}
- public function testCanAccessFilesystemDisabled() {
+ public function testCanAccessFilesystemDisabled(): void {
$manager = new LockdownManager($this->sessionCallback);
$this->assertTrue($manager->canAccessFilesystem());
}
- public function testCanAccessFilesystemAllowed() {
+ public function testCanAccessFilesystemAllowed(): void {
$token = new PublicKeyToken();
$token->setScope([IToken::SCOPE_FILESYSTEM => true]);
$manager = new LockdownManager($this->sessionCallback);
@@ -36,7 +36,7 @@ class LockdownManagerTest extends TestCase {
$this->assertTrue($manager->canAccessFilesystem());
}
- public function testCanAccessFilesystemNotAllowed() {
+ public function testCanAccessFilesystemNotAllowed(): void {
$token = new PublicKeyToken();
$token->setScope([IToken::SCOPE_FILESYSTEM => false]);
$manager = new LockdownManager($this->sessionCallback);
diff --git a/tests/lib/Log/ExceptionSerializerTest.php b/tests/lib/Log/ExceptionSerializerTest.php
index 1ec422fb53d..6d5bc5cf19f 100644
--- a/tests/lib/Log/ExceptionSerializerTest.php
+++ b/tests/lib/Log/ExceptionSerializerTest.php
@@ -42,7 +42,7 @@ class ExceptionSerializerTest extends TestCase {
* exception was passed to the logger. The token was replaced, the original
* variable overwritten.
*/
- public function testSerializer() {
+ public function testSerializer(): void {
try {
$secret = ['Secret'];
$this->emit([&$secret]);
@@ -53,7 +53,7 @@ class ExceptionSerializerTest extends TestCase {
}
}
- public function testSerializerWithRegisteredMethods() {
+ public function testSerializerWithRegisteredMethods(): void {
$this->serializer->enlistSensitiveMethods(self::class, ['customMagicAuthThing']);
try {
$this->customMagicAuthThing('u57474', 'Secret');
diff --git a/tests/lib/Log/FileTest.php b/tests/lib/Log/FileTest.php
index 9deb6c8136c..b483da969f4 100644
--- a/tests/lib/Log/FileTest.php
+++ b/tests/lib/Log/FileTest.php
@@ -47,7 +47,7 @@ class FileTest extends TestCase {
parent::tearDown();
}
- public function testLogging() {
+ public function testLogging(): void {
$config = \OC::$server->get(IConfig::class);
# delete old logfile
unlink($config->getSystemValue('logfile'));
@@ -68,7 +68,7 @@ class FileTest extends TestCase {
$this->assertEquals('Testing logging', $values['message']);
}
- public function testMicrosecondsLogTimestamp() {
+ public function testMicrosecondsLogTimestamp(): void {
$config = \OC::$server->getConfig();
# delete old logfile
unlink($config->getSystemValue('logfile'));
diff --git a/tests/lib/Log/LogFactoryTest.php b/tests/lib/Log/LogFactoryTest.php
index c1232f7b28d..22ee0dfb268 100644
--- a/tests/lib/Log/LogFactoryTest.php
+++ b/tests/lib/Log/LogFactoryTest.php
@@ -61,7 +61,7 @@ class LogFactoryTest extends TestCase {
* @dataProvider fileTypeProvider
* @throws \OCP\AppFramework\QueryException
*/
- public function testFile(string $type) {
+ public function testFile(string $type): void {
$datadir = \OC::$SERVERROOT.'/data';
$defaultLog = $datadir . '/nextcloud.log';
@@ -91,7 +91,7 @@ class LogFactoryTest extends TestCase {
* @dataProvider logFilePathProvider
* @throws \OCP\AppFramework\QueryException
*/
- public function testFileCustomPath($path, $expected) {
+ public function testFileCustomPath($path, $expected): void {
$datadir = \OC::$SERVERROOT.'/data';
$defaultLog = $datadir . '/nextcloud.log';
@@ -108,7 +108,7 @@ class LogFactoryTest extends TestCase {
/**
* @throws \OCP\AppFramework\QueryException
*/
- public function testErrorLog() {
+ public function testErrorLog(): void {
$log = $this->factory->get('errorlog');
$this->assertInstanceOf(Errorlog::class, $log);
}
@@ -116,7 +116,7 @@ class LogFactoryTest extends TestCase {
/**
* @throws \OCP\AppFramework\QueryException
*/
- public function testSystemLog() {
+ public function testSystemLog(): void {
$this->c->expects($this->once())
->method('resolve')
->with(Syslog::class)
@@ -129,7 +129,7 @@ class LogFactoryTest extends TestCase {
/**
* @throws \OCP\AppFramework\QueryException
*/
- public function testSystemdLog() {
+ public function testSystemdLog(): void {
$this->c->expects($this->once())
->method('resolve')
->with(Systemdlog::class)
diff --git a/tests/lib/LoggerTest.php b/tests/lib/LoggerTest.php
index ff99a416904..c7c60e892aa 100644
--- a/tests/lib/LoggerTest.php
+++ b/tests/lib/LoggerTest.php
@@ -43,7 +43,7 @@ class LoggerTest extends TestCase implements IWriter {
])));
}
- public function testInterpolation() {
+ public function testInterpolation(): void {
$this->mockDefaultLogLevel();
$logger = $this->logger;
$logger->warning('{Message {nothing} {user} {foo.bar} a}', ['user' => 'Bob', 'foo.bar' => 'Bar']);
@@ -52,7 +52,7 @@ class LoggerTest extends TestCase implements IWriter {
$this->assertEquals($expected, $this->getLogs());
}
- public function testAppCondition() {
+ public function testAppCondition(): void {
$this->config->expects($this->any())
->method('getValue')
->will(($this->returnValueMap([
diff --git a/tests/lib/Mail/EMailTemplateTest.php b/tests/lib/Mail/EMailTemplateTest.php
index 45ccf543848..76b37d48ff3 100644
--- a/tests/lib/Mail/EMailTemplateTest.php
+++ b/tests/lib/Mail/EMailTemplateTest.php
@@ -45,7 +45,7 @@ class EMailTemplateTest extends TestCase {
);
}
- public function testEMailTemplateCustomFooter() {
+ public function testEMailTemplateCustomFooter(): void {
$this->defaults
->expects($this->any())
->method('getDefaultColorPrimary')
@@ -86,7 +86,7 @@ class EMailTemplateTest extends TestCase {
$this->assertSame($expectedTXT, $this->emailTemplate->renderText());
}
- public function testEMailTemplateDefaultFooter() {
+ public function testEMailTemplateDefaultFooter(): void {
$this->defaults
->expects($this->any())
->method('getDefaultColorPrimary')
@@ -129,7 +129,7 @@ class EMailTemplateTest extends TestCase {
$this->assertSame($expectedTXT, $this->emailTemplate->renderText());
}
- public function testEMailTemplateSingleButton() {
+ public function testEMailTemplateSingleButton(): void {
$this->defaults
->expects($this->any())
->method('getDefaultColorPrimary')
@@ -174,7 +174,7 @@ class EMailTemplateTest extends TestCase {
- public function testEMailTemplateAlternativePlainTexts() {
+ public function testEMailTemplateAlternativePlainTexts(): void {
$this->defaults
->expects($this->any())
->method('getDefaultColorPrimary')
diff --git a/tests/lib/Mail/MailerTest.php b/tests/lib/Mail/MailerTest.php
index 4d146cb72bb..c15b4b1a748 100644
--- a/tests/lib/Mail/MailerTest.php
+++ b/tests/lib/Mail/MailerTest.php
@@ -77,7 +77,7 @@ class MailerTest extends TestCase {
* @param $sendmailMode
* @param $binaryParam
*/
- public function testGetSendmailInstanceSendMail($sendmailMode, $binaryParam) {
+ public function testGetSendmailInstanceSendMail($sendmailMode, $binaryParam): void {
$this->config
->expects($this->exactly(2))
->method('getSystemValueString')
@@ -100,7 +100,7 @@ class MailerTest extends TestCase {
* @param $sendmailMode
* @param $binaryParam
*/
- public function testGetSendmailInstanceSendMailQmail($sendmailMode, $binaryParam) {
+ public function testGetSendmailInstanceSendMailQmail($sendmailMode, $binaryParam): void {
$this->config
->expects($this->exactly(2))
->method('getSystemValueString')
@@ -113,7 +113,7 @@ class MailerTest extends TestCase {
$this->assertEquals($sendmail, self::invokePrivate($this->mailer, 'getSendMailInstance'));
}
- public function testGetInstanceDefault() {
+ public function testGetInstanceDefault(): void {
$this->config
->method('getSystemValue')
->willReturnMap([
@@ -127,7 +127,7 @@ class MailerTest extends TestCase {
$this->assertInstanceOf(EsmtpTransport::class, $transport);
}
- public function testGetInstanceSendmail() {
+ public function testGetInstanceSendmail(): void {
$this->config
->method('getSystemValueString')
->willReturnMap([
@@ -141,7 +141,7 @@ class MailerTest extends TestCase {
$this->assertInstanceOf(SendmailTransport::class, $transport);
}
- public function testEvents() {
+ public function testEvents(): void {
$this->config
->method('getSystemValue')
->willReturnMap([
@@ -173,7 +173,7 @@ class MailerTest extends TestCase {
$this->mailer->send($message);
}
- public function testCreateMessage() {
+ public function testCreateMessage(): void {
$this->config
->expects($this->any())
->method('getSystemValueBool')
@@ -183,7 +183,7 @@ class MailerTest extends TestCase {
}
- public function testSendInvalidMailException() {
+ public function testSendInvalidMailException(): void {
$this->config
->method('getSystemValue')
->willReturnMap([
@@ -223,7 +223,7 @@ class MailerTest extends TestCase {
/**
* @dataProvider mailAddressProvider
*/
- public function testValidateMailAddress($email, $expected, $strict) {
+ public function testValidateMailAddress($email, $expected, $strict): void {
$this->config
->expects($this->atMost(1))
->method('getAppValue')
@@ -232,7 +232,7 @@ class MailerTest extends TestCase {
$this->assertSame($expected, $this->mailer->validateMailAddress($email));
}
- public function testCreateEMailTemplate() {
+ public function testCreateEMailTemplate(): void {
$this->config->method('getSystemValueString')
->with('mail_template_class', '')
->willReturnArgument(1);
@@ -243,7 +243,7 @@ class MailerTest extends TestCase {
$this->assertSame(EMailTemplate::class, get_class($this->mailer->createEMailTemplate('tests.MailerTest')));
}
- public function testStreamingOptions() {
+ public function testStreamingOptions(): void {
$this->config->method('getSystemValue')
->willReturnMap([
['mail_smtpstreamoptions', [], ['foo' => 1]],
@@ -267,7 +267,7 @@ class MailerTest extends TestCase {
$this->assertTrue(isset($transport->getStream()->getStreamOptions()['foo']));
}
- public function testStreamingOptionsWrongType() {
+ public function testStreamingOptionsWrongType(): void {
$this->config->method('getSystemValue')
->willReturnMap([
['mail_smtpstreamoptions', [], 'bar'],
diff --git a/tests/lib/Mail/MessageTest.php b/tests/lib/Mail/MessageTest.php
index 456d532d766..681ec033380 100644
--- a/tests/lib/Mail/MessageTest.php
+++ b/tests/lib/Mail/MessageTest.php
@@ -77,7 +77,7 @@ class MessageTest extends TestCase {
* @param string $unconverted
* @param string $expected
*/
- public function testConvertAddresses($unconverted, $expected) {
+ public function testConvertAddresses($unconverted, $expected): void {
$this->assertEquals($expected, self::invokePrivate($this->message, 'convertAddresses', [$unconverted]));
}
@@ -112,7 +112,7 @@ class MessageTest extends TestCase {
$this->message->setRecipients();
}
- public function testSetTo() {
+ public function testSetTo(): void {
$expected = ['pierres-general-store@stardewvalley.com' => 'Pierres General Store'];
$message = $this->message->setTo(['pierres-general-store@stardewvalley.com' => 'Pierres General Store']);
@@ -141,7 +141,7 @@ class MessageTest extends TestCase {
$message->setRecipients();
}
- public function testSetGetFrom() {
+ public function testSetGetFrom(): void {
$expected = ['pierres-general-store@stardewvalley.com' => 'Pierres General Store'];
$message = $this->message->setFrom(['pierres-general-store@stardewvalley.com' => 'Pierres General Store']);
@@ -149,7 +149,7 @@ class MessageTest extends TestCase {
$this->assertEquals($expected, $message->getFrom());
}
- public function testSetGetTo() {
+ public function testSetGetTo(): void {
$expected = ['lewis-tent@stardewvalley.com' => "Lewis' Tent Life"];
$message = $this->message->setTo(['lewis-tent@stardewvalley.com' => "Lewis' Tent Life"]);
@@ -157,7 +157,7 @@ class MessageTest extends TestCase {
$this->assertEquals($expected, $message->getTo());
}
- public function testSetGetReplyTo() {
+ public function testSetGetReplyTo(): void {
$expected = ['penny@stardewvalley-library.co.edu' => 'Penny'];
$message = $this->message->setReplyTo(['penny@stardewvalley-library.co.edu' => 'Penny']);
@@ -165,7 +165,7 @@ class MessageTest extends TestCase {
$this->assertEquals($expected, $message->getReplyTo());
}
- public function testSetGetCC() {
+ public function testSetGetCC(): void {
$expected = ['gunther@stardewvalley-library.co.edu' => 'Gunther'];
$message = $this->message->setCc(['gunther@stardewvalley-library.co.edu' => 'Gunther']);
@@ -173,7 +173,7 @@ class MessageTest extends TestCase {
$this->assertEquals($expected, $message->getCc());
}
- public function testSetGetBCC() {
+ public function testSetGetBCC(): void {
$expected = ['pam@stardewvalley-bus.com' => 'Pam'];
$message = $this->message->setBcc(['pam@stardewvalley-bus.com' => 'Pam']);
@@ -181,7 +181,7 @@ class MessageTest extends TestCase {
$this->assertEquals($expected, $message->getBcc());
}
- public function testSetPlainBody() {
+ public function testSetPlainBody(): void {
$this->symfonyEmail
->expects($this->once())
->method('text')
@@ -190,7 +190,7 @@ class MessageTest extends TestCase {
$this->message->setPlainBody('Fancy Body');
}
- public function testGetPlainBody() {
+ public function testGetPlainBody(): void {
$this->symfonyEmail
->expects($this->once())
->method('getTextBody')
@@ -199,7 +199,7 @@ class MessageTest extends TestCase {
$this->assertSame('Fancy Body', $this->message->getPlainBody());
}
- public function testSetHtmlBody() {
+ public function testSetHtmlBody(): void {
$this->symfonyEmail
->expects($this->once())
->method('html')
@@ -208,7 +208,7 @@ class MessageTest extends TestCase {
$this->message->setHtmlBody('<blink>Fancy Body</blink>');
}
- public function testPlainTextRenderOption() {
+ public function testPlainTextRenderOption(): void {
/** @var MockObject|Email $symfonyEmail */
$symfonyEmail = $this->getMockBuilder(Email::class)
->disableOriginalConstructor()->getMock();
@@ -231,7 +231,7 @@ class MessageTest extends TestCase {
$message->useTemplate($template);
}
- public function testBothRenderingOptions() {
+ public function testBothRenderingOptions(): void {
/** @var MockObject|Email $symfonyEmail */
$symfonyEmail = $this->getMockBuilder(Email::class)
->disableOriginalConstructor()->getMock();
@@ -254,7 +254,7 @@ class MessageTest extends TestCase {
$message->useTemplate($template);
}
- public function testSetAutoSubmitted1() {
+ public function testSetAutoSubmitted1(): void {
$headers = new Headers($this->createMock(HeaderInterface::class));
$headers->addTextHeader(AutoSubmitted::HEADER, 'yes');
$symfonyEmail = $this->createMock(Email::class);
@@ -267,7 +267,7 @@ class MessageTest extends TestCase {
$this->assertNotSame('no', $message->getAutoSubmitted());
}
- public function testSetAutoSubmitted2() {
+ public function testSetAutoSubmitted2(): void {
$headers = new Headers($this->createMock(HeaderInterface::class));
$headers->addTextHeader(AutoSubmitted::HEADER, 'no');
$symfonyEmail = $this->createMock(Email::class);
@@ -280,7 +280,7 @@ class MessageTest extends TestCase {
$this->assertSame('auto-generated', $message->getAutoSubmitted());
}
- public function testGetAutoSubmitted() {
+ public function testGetAutoSubmitted(): void {
$headers = new Headers($this->createMock(HeaderInterface::class));
$headers->addTextHeader(AutoSubmitted::HEADER, 'no');
$symfonyEmail = $this->createMock(Email::class);
diff --git a/tests/lib/Memcache/APCuTest.php b/tests/lib/Memcache/APCuTest.php
index c13d30da136..cb465d1f07a 100644
--- a/tests/lib/Memcache/APCuTest.php
+++ b/tests/lib/Memcache/APCuTest.php
@@ -23,13 +23,13 @@ class APCuTest extends Cache {
$this->instance = new \OC\Memcache\APCu($this->getUniqueID());
}
- public function testCasIntChanged() {
+ public function testCasIntChanged(): void {
$this->instance->set('foo', 1);
$this->assertTrue($this->instance->cas('foo', 1, 2));
$this->assertEquals(2, $this->instance->get('foo'));
}
- public function testCasIntNotChanged() {
+ public function testCasIntNotChanged(): void {
$this->instance->set('foo', 1);
$this->assertFalse($this->instance->cas('foo', 2, 3));
$this->assertEquals(1, $this->instance->get('foo'));
diff --git a/tests/lib/Memcache/Cache.php b/tests/lib/Memcache/Cache.php
index 4749e223fd5..5845d426311 100644
--- a/tests/lib/Memcache/Cache.php
+++ b/tests/lib/Memcache/Cache.php
@@ -14,65 +14,65 @@ abstract class Cache extends \Test\Cache\TestCache {
*/
protected $instance;
- public function testExistsAfterSet() {
+ public function testExistsAfterSet(): void {
$this->assertFalse($this->instance->hasKey('foo'));
$this->instance->set('foo', 'bar');
$this->assertTrue($this->instance->hasKey('foo'));
}
- public function testGetAfterSet() {
+ public function testGetAfterSet(): void {
$this->assertNull($this->instance->get('foo'));
$this->instance->set('foo', 'bar');
$this->assertEquals('bar', $this->instance->get('foo'));
}
- public function testGetArrayAfterSet() {
+ public function testGetArrayAfterSet(): void {
$this->assertNull($this->instance->get('foo'));
$this->instance->set('foo', ['bar']);
$this->assertEquals(['bar'], $this->instance->get('foo'));
}
- public function testDoesNotExistAfterRemove() {
+ public function testDoesNotExistAfterRemove(): void {
$this->instance->set('foo', 'bar');
$this->instance->remove('foo');
$this->assertFalse($this->instance->hasKey('foo'));
}
- public function testRemoveNonExisting() {
+ public function testRemoveNonExisting(): void {
$this->instance->remove('foo');
$this->assertFalse($this->instance->hasKey('foo'));
}
- public function testArrayAccessSet() {
+ public function testArrayAccessSet(): void {
$this->instance['foo'] = 'bar';
$this->assertEquals('bar', $this->instance->get('foo'));
}
- public function testArrayAccessGet() {
+ public function testArrayAccessGet(): void {
$this->instance->set('foo', 'bar');
$this->assertEquals('bar', $this->instance['foo']);
}
- public function testArrayAccessExists() {
+ public function testArrayAccessExists(): void {
$this->assertFalse(isset($this->instance['foo']));
$this->instance->set('foo', 'bar');
$this->assertTrue(isset($this->instance['foo']));
}
- public function testArrayAccessUnset() {
+ public function testArrayAccessUnset(): void {
$this->instance->set('foo', 'bar');
unset($this->instance['foo']);
$this->assertFalse($this->instance->hasKey('foo'));
}
- public function testAdd() {
+ public function testAdd(): void {
$this->assertTrue($this->instance->add('foo', 'bar'));
$this->assertEquals('bar', $this->instance->get('foo'));
$this->assertFalse($this->instance->add('foo', 'asd'));
$this->assertEquals('bar', $this->instance->get('foo'));
}
- public function testInc() {
+ public function testInc(): void {
$this->assertEquals(1, $this->instance->inc('foo'));
$this->assertEquals(1, $this->instance->get('foo'));
$this->assertEquals(2, $this->instance->inc('foo'));
@@ -85,7 +85,7 @@ abstract class Cache extends \Test\Cache\TestCache {
$this->assertEquals('bar', $this->instance->get('foo'));
}
- public function testDec() {
+ public function testDec(): void {
$this->assertFalse($this->instance->dec('foo'));
$this->instance->set('foo', 20);
$this->assertEquals(19, $this->instance->dec('foo'));
@@ -97,51 +97,51 @@ abstract class Cache extends \Test\Cache\TestCache {
$this->assertEquals('bar', $this->instance->get('foo'));
}
- public function testCasNotChanged() {
+ public function testCasNotChanged(): void {
$this->instance->set('foo', 'bar');
$this->assertTrue($this->instance->cas('foo', 'bar', 'asd'));
$this->assertEquals('asd', $this->instance->get('foo'));
}
- public function testCasChanged() {
+ public function testCasChanged(): void {
$this->instance->set('foo', 'bar1');
$this->assertFalse($this->instance->cas('foo', 'bar', 'asd'));
$this->assertEquals('bar1', $this->instance->get('foo'));
}
- public function testCasNotSet() {
+ public function testCasNotSet(): void {
$this->assertFalse($this->instance->cas('foo', 'bar', 'asd'));
}
- public function testCadNotChanged() {
+ public function testCadNotChanged(): void {
$this->instance->set('foo', 'bar');
$this->assertTrue($this->instance->cad('foo', 'bar'));
$this->assertFalse($this->instance->hasKey('foo'));
}
- public function testCadChanged() {
+ public function testCadChanged(): void {
$this->instance->set('foo', 'bar1');
$this->assertFalse($this->instance->cad('foo', 'bar'));
$this->assertTrue($this->instance->hasKey('foo'));
}
- public function testCadNotSet() {
+ public function testCadNotSet(): void {
$this->assertFalse($this->instance->cad('foo', 'bar'));
}
- public function testNcadNotChanged() {
+ public function testNcadNotChanged(): void {
$this->instance->set('foo', 'bar');
$this->assertFalse($this->instance->ncad('foo', 'bar'));
$this->assertTrue($this->instance->hasKey('foo'));
}
- public function testNcadChanged() {
+ public function testNcadChanged(): void {
$this->instance->set('foo', 'bar1');
$this->assertTrue($this->instance->ncad('foo', 'bar'));
$this->assertFalse($this->instance->hasKey('foo'));
}
- public function testNcadNotSet() {
+ public function testNcadNotSet(): void {
$this->assertFalse($this->instance->ncad('foo', 'bar'));
}
diff --git a/tests/lib/Memcache/CasTraitTest.php b/tests/lib/Memcache/CasTraitTest.php
index 1502366e647..c8b35d5cb0d 100644
--- a/tests/lib/Memcache/CasTraitTest.php
+++ b/tests/lib/Memcache/CasTraitTest.php
@@ -46,14 +46,14 @@ class CasTraitTest extends TestCase {
return $mock;
}
- public function testCasNotChanged() {
+ public function testCasNotChanged(): void {
$cache = $this->getCache();
$cache->set('foo', 'bar');
$this->assertTrue($cache->cas('foo', 'bar', 'asd'));
$this->assertEquals('asd', $cache->get('foo'));
}
- public function testCasChanged() {
+ public function testCasChanged(): void {
$cache = $this->getCache();
$cache->set('foo', 'bar1');
$this->assertFalse($cache->cas('foo', 'bar', 'asd'));
diff --git a/tests/lib/Memcache/FactoryTest.php b/tests/lib/Memcache/FactoryTest.php
index b973b5065ea..fa0d80c5153 100644
--- a/tests/lib/Memcache/FactoryTest.php
+++ b/tests/lib/Memcache/FactoryTest.php
@@ -107,7 +107,7 @@ class FactoryTest extends \Test\TestCase {
* @dataProvider cacheAvailabilityProvider
*/
public function testCacheAvailability($localCache, $distributedCache, $lockingCache,
- $expectedLocalCache, $expectedDistributedCache, $expectedLockingCache) {
+ $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);
@@ -119,7 +119,7 @@ class FactoryTest extends \Test\TestCase {
/**
* @dataProvider cacheUnavailableProvider
*/
- public function testCacheNotAvailableException($localCache, $distributedCache) {
+ public function testCacheNotAvailableException($localCache, $distributedCache): void {
$this->expectException(\OCP\HintException::class);
$logger = $this->getMockBuilder(LoggerInterface::class)->getMock();
diff --git a/tests/lib/Memcache/MemcachedTest.php b/tests/lib/Memcache/MemcachedTest.php
index 48f93a45ed9..346530e191d 100644
--- a/tests/lib/Memcache/MemcachedTest.php
+++ b/tests/lib/Memcache/MemcachedTest.php
@@ -30,7 +30,7 @@ class MemcachedTest extends Cache {
$this->instance = new \OC\Memcache\Memcached($this->getUniqueID());
}
- public function testClear() {
+ public function testClear(): void {
// Memcached is sometimes broken with clear(), so we don't test it thoroughly
$value = 'ipsum lorum';
$this->instance->set('1_value1', $value);
diff --git a/tests/lib/Memcache/RedisTest.php b/tests/lib/Memcache/RedisTest.php
index 8df286b2f93..d76da03eb85 100644
--- a/tests/lib/Memcache/RedisTest.php
+++ b/tests/lib/Memcache/RedisTest.php
@@ -63,20 +63,20 @@ class RedisTest extends Cache {
$this->instance = new \OC\Memcache\Redis($this->getUniqueID());
}
- public function testScriptHashes() {
+ public function testScriptHashes(): void {
foreach (\OC\Memcache\Redis::LUA_SCRIPTS as $script) {
$this->assertEquals(sha1($script[0]), $script[1]);
}
}
- public function testCasTtlNotChanged() {
+ public function testCasTtlNotChanged(): void {
$this->instance->set('foo', 'bar', 50);
$this->assertTrue($this->instance->compareSetTTL('foo', 'bar', 100));
// allow for 1s of inaccuracy due to time moving forward
$this->assertLessThan(1, 100 - $this->instance->getTTL('foo'));
}
- public function testCasTtlChanged() {
+ public function testCasTtlChanged(): void {
$this->instance->set('foo', 'bar1', 50);
$this->assertFalse($this->instance->compareSetTTL('foo', 'bar', 100));
// allow for 1s of inaccuracy due to time moving forward
diff --git a/tests/lib/MemoryInfoTest.php b/tests/lib/MemoryInfoTest.php
index fb9c9ac7bd4..2477de2d799 100644
--- a/tests/lib/MemoryInfoTest.php
+++ b/tests/lib/MemoryInfoTest.php
@@ -59,7 +59,7 @@ class MemoryInfoTest extends TestCase {
* @param int|float $expected The expected detected memory limit.
* @dataProvider getMemoryLimitTestData
*/
- public function testMemoryLimit(string $iniValue, int|float $expected) {
+ public function testMemoryLimit(string $iniValue, int|float $expected): void {
ini_set('memory_limit', $iniValue);
$memoryInfo = new MemoryInfo();
self::assertEquals($expected, $memoryInfo->getMemoryLimit());
@@ -87,7 +87,7 @@ class MemoryInfoTest extends TestCase {
* @dataProvider getSufficientMemoryTestData
* @return void
*/
- public function testIsMemoryLimitSufficient(int $memoryLimit, bool $expected) {
+ public function testIsMemoryLimitSufficient(int $memoryLimit, bool $expected): void {
/* @var MemoryInfo|MockObject $memoryInfo */
$memoryInfo = $this->getMockBuilder(MemoryInfo::class)
->setMethods(['getMemoryLimit',])
diff --git a/tests/lib/Migration/BackgroundRepairTest.php b/tests/lib/Migration/BackgroundRepairTest.php
index 0c4fe69fc89..318b3a36856 100644
--- a/tests/lib/Migration/BackgroundRepairTest.php
+++ b/tests/lib/Migration/BackgroundRepairTest.php
@@ -70,12 +70,12 @@ class BackgroundRepairTest extends TestCase {
->getMock();
}
- public function testNoArguments() {
+ public function testNoArguments(): void {
$this->jobList->expects($this->once())->method('remove');
$this->job->start($this->jobList);
}
- public function testAppUpgrading() {
+ public function testAppUpgrading(): void {
$this->jobList->expects($this->never())->method('remove');
$this->job->expects($this->once())->method('loadApp')->with('test')->willThrowException(new NeedsUpdateException());
$this->job->setArgument([
@@ -85,7 +85,7 @@ class BackgroundRepairTest extends TestCase {
$this->job->start($this->jobList);
}
- public function testUnknownStep() {
+ public function testUnknownStep(): void {
$this->dispatcher->expects($this->never())->method('dispatchTyped');
$this->jobList->expects($this->once())->method('remove');
@@ -98,7 +98,7 @@ class BackgroundRepairTest extends TestCase {
$this->job->start($this->jobList);
}
- public function testWorkingStep() {
+ public function testWorkingStep(): void {
$this->dispatcher->expects($this->once())->method('dispatchTyped')
->with($this->equalTo(new RepairStepEvent('A test repair step')));
diff --git a/tests/lib/NaturalSortTest.php b/tests/lib/NaturalSortTest.php
index a053687eaf9..3a07c5ceb66 100644
--- a/tests/lib/NaturalSortTest.php
+++ b/tests/lib/NaturalSortTest.php
@@ -11,7 +11,7 @@ class NaturalSortTest extends \Test\TestCase {
/**
* @dataProvider naturalSortDataProvider
*/
- public function testNaturalSortCompare($array, $sorted) {
+ 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;
@@ -24,7 +24,7 @@ class NaturalSortTest extends \Test\TestCase {
/**
* @dataProvider defaultCollatorDataProvider
*/
- public function testDefaultCollatorCompare($array, $sorted) {
+ public function testDefaultCollatorCompare($array, $sorted): void {
$comparator = new \OC\NaturalSort(new \OC\NaturalSort_DefaultCollator());
usort($array, [$comparator, 'compare']);
$this->assertEquals($sorted, $array);
diff --git a/tests/lib/NavigationManagerTest.php b/tests/lib/NavigationManagerTest.php
index 27f14e97bb0..1297bfdf669 100644
--- a/tests/lib/NavigationManagerTest.php
+++ b/tests/lib/NavigationManagerTest.php
@@ -118,7 +118,7 @@ class NavigationManagerTest extends TestCase {
* @param array $entry
* @param array $expectedEntry
*/
- public function testAddArray(array $entry, array $expectedEntry) {
+ public function testAddArray(array $entry, array $expectedEntry): void {
$this->assertEmpty($this->navigationManager->getAll('all'), 'Expected no navigation entry exists');
$this->navigationManager->add($entry);
@@ -136,7 +136,7 @@ class NavigationManagerTest extends TestCase {
* @param array $entry
* @param array $expectedEntry
*/
- public function testAddClosure(array $entry, array $expectedEntry) {
+ public function testAddClosure(array $entry, array $expectedEntry): void {
global $testAddClosureNumberOfCalls;
$testAddClosureNumberOfCalls = 0;
@@ -163,7 +163,7 @@ class NavigationManagerTest extends TestCase {
$this->assertEmpty($this->navigationManager->getAll('all'), 'Expected no navigation entry exists after clear()');
}
- public function testAddArrayClearGetAll() {
+ public function testAddArrayClearGetAll(): void {
$entry = [
'id' => 'entry id',
'name' => 'link text',
@@ -178,7 +178,7 @@ class NavigationManagerTest extends TestCase {
$this->assertEmpty($this->navigationManager->getAll(), 'Expected no navigation entry exists after clear()');
}
- public function testAddClosureClearGetAll() {
+ public function testAddClosureClearGetAll(): void {
$this->assertEmpty($this->navigationManager->getAll(), 'Expected no navigation entry exists');
$entry = [
@@ -209,7 +209,7 @@ class NavigationManagerTest extends TestCase {
/**
* @dataProvider providesNavigationConfig
*/
- public function testWithAppManager($expected, $navigation, $isAdmin = false) {
+ public function testWithAppManager($expected, $navigation, $isAdmin = false): void {
$l = $this->createMock(IL10N::class);
$l->expects($this->any())->method('t')->willReturnCallback(function ($text, $parameters = []) {
return vsprintf($text, $parameters);
@@ -489,7 +489,7 @@ class NavigationManagerTest extends TestCase {
];
}
- public function testWithAppManagerAndApporder() {
+ public function testWithAppManagerAndApporder(): void {
$l = $this->createMock(IL10N::class);
$l->expects($this->any())->method('t')->willReturnCallback(function ($text, $parameters = []) {
return vsprintf($text, $parameters);
@@ -693,7 +693,7 @@ class NavigationManagerTest extends TestCase {
/**
* @dataProvider provideDefaultEntries
*/
- public function testGetDefaultEntryIdForUser($defaultApps, $userDefaultApps, $userApporder, $withFallbacks, $expectedApp) {
+ public function testGetDefaultEntryIdForUser($defaultApps, $userDefaultApps, $userApporder, $withFallbacks, $expectedApp): void {
$this->navigationManager->add([
'id' => 'files',
]);
@@ -725,7 +725,7 @@ class NavigationManagerTest extends TestCase {
$this->assertEquals($expectedApp, $this->navigationManager->getDefaultEntryIdForUser(null, $withFallbacks));
}
- public function testDefaultEntryUpdated() {
+ public function testDefaultEntryUpdated(): void {
$this->appManager->method('getInstalledApps')->willReturn([]);
$user = $this->createMock(IUser::class);
diff --git a/tests/lib/Notification/ActionTest.php b/tests/lib/Notification/ActionTest.php
index bfcfbbe75db..3ae4b1db7e7 100644
--- a/tests/lib/Notification/ActionTest.php
+++ b/tests/lib/Notification/ActionTest.php
@@ -32,7 +32,7 @@ class ActionTest extends TestCase {
* @dataProvider dataSetLabel
* @param string $label
*/
- public function testSetLabel($label) {
+ public function testSetLabel($label): void {
$this->assertSame('', $this->action->getLabel());
$this->assertSame($this->action, $this->action->setLabel($label));
$this->assertSame($label, $this->action->getLabel());
@@ -50,7 +50,7 @@ class ActionTest extends TestCase {
* @param mixed $label
*
*/
- public function testSetLabelInvalid($label) {
+ public function testSetLabelInvalid($label): void {
$this->expectException(\InvalidArgumentException::class);
$this->action->setLabel($label);
@@ -68,7 +68,7 @@ class ActionTest extends TestCase {
* @dataProvider dataSetParsedLabel
* @param string $label
*/
- public function testSetParsedLabel($label) {
+ public function testSetParsedLabel($label): void {
$this->assertSame('', $this->action->getParsedLabel());
$this->assertSame($this->action, $this->action->setParsedLabel($label));
$this->assertSame($label, $this->action->getParsedLabel());
@@ -85,7 +85,7 @@ class ActionTest extends TestCase {
* @param mixed $label
*
*/
- public function testSetParsedLabelInvalid($label) {
+ public function testSetParsedLabelInvalid($label): void {
$this->expectException(\InvalidArgumentException::class);
$this->action->setParsedLabel($label);
@@ -105,7 +105,7 @@ class ActionTest extends TestCase {
* @param string $link
* @param string $type
*/
- public function testSetLink($link, $type) {
+ public function testSetLink($link, $type): void {
$this->assertSame('', $this->action->getLink());
$this->assertSame($this->action, $this->action->setLink($link, $type));
$this->assertSame($link, $this->action->getLink());
@@ -129,7 +129,7 @@ class ActionTest extends TestCase {
* @param mixed $type
*
*/
- public function testSetLinkInvalid($link, $type) {
+ public function testSetLinkInvalid($link, $type): void {
$this->expectException(\InvalidArgumentException::class);
$this->action->setLink($link, $type);
@@ -146,13 +146,13 @@ class ActionTest extends TestCase {
* @dataProvider dataSetPrimary
* @param bool $primary
*/
- public function testSetPrimary($primary) {
+ public function testSetPrimary($primary): void {
$this->assertSame(false, $this->action->isPrimary());
$this->assertSame($this->action, $this->action->setPrimary($primary));
$this->assertSame($primary, $this->action->isPrimary());
}
- public function testIsValid() {
+ public function testIsValid(): void {
$this->assertFalse($this->action->isValid());
$this->assertFalse($this->action->isValidParsed());
$this->action->setLabel('label');
@@ -163,7 +163,7 @@ class ActionTest extends TestCase {
$this->assertFalse($this->action->isValidParsed());
}
- public function testIsValidParsed() {
+ public function testIsValidParsed(): void {
$this->assertFalse($this->action->isValid());
$this->assertFalse($this->action->isValidParsed());
$this->action->setParsedLabel('label');
diff --git a/tests/lib/Notification/NotificationTest.php b/tests/lib/Notification/NotificationTest.php
index 9afc74db495..48a78bd0fe7 100644
--- a/tests/lib/Notification/NotificationTest.php
+++ b/tests/lib/Notification/NotificationTest.php
@@ -57,7 +57,7 @@ class NotificationTest extends TestCase {
* @dataProvider dataSetApp
* @param string $app
*/
- public function testSetApp($app) {
+ public function testSetApp($app): void {
$this->assertSame('', $this->notification->getApp());
$this->assertSame($this->notification, $this->notification->setApp($app));
$this->assertSame($app, $this->notification->getApp());
@@ -72,7 +72,7 @@ class NotificationTest extends TestCase {
* @param mixed $app
*
*/
- public function testSetAppInvalid($app) {
+ public function testSetAppInvalid($app): void {
$this->expectException(\InvalidArgumentException::class);
$this->notification->setApp($app);
@@ -87,7 +87,7 @@ class NotificationTest extends TestCase {
* @dataProvider dataSetUser
* @param string $user
*/
- public function testSetUser($user) {
+ public function testSetUser($user): void {
$this->assertSame('', $this->notification->getUser());
$this->assertSame($this->notification, $this->notification->setUser($user));
$this->assertSame($user, $this->notification->getUser());
@@ -102,7 +102,7 @@ class NotificationTest extends TestCase {
* @param mixed $user
*
*/
- public function testSetUserInvalid($user) {
+ public function testSetUserInvalid($user): void {
$this->expectException(\InvalidArgumentException::class);
$this->notification->setUser($user);
@@ -126,7 +126,7 @@ class NotificationTest extends TestCase {
* @dataProvider dataSetDateTime
* @param \DateTime $dateTime
*/
- public function testSetDateTime(\DateTime $dateTime) {
+ 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());
@@ -146,7 +146,7 @@ class NotificationTest extends TestCase {
*
* @expectedMessage 'The given date time is invalid'
*/
- public function testSetDateTimeZero($dateTime) {
+ public function testSetDateTimeZero($dateTime): void {
$this->expectException(\InvalidArgumentException::class);
$this->notification->setDateTime($dateTime);
@@ -164,7 +164,7 @@ class NotificationTest extends TestCase {
* @param string $type
* @param string $id
*/
- public function testSetObject($type, $id) {
+ public function testSetObject($type, $id): void {
$this->assertSame('', $this->notification->getObjectType());
$this->assertSame('', $this->notification->getObjectId());
$this->assertSame($this->notification, $this->notification->setObject($type, $id));
@@ -189,7 +189,7 @@ class NotificationTest extends TestCase {
*
* @expectedMessage 'The given object id is invalid'
*/
- public function testSetObjectIdInvalid($id) {
+ public function testSetObjectIdInvalid($id): void {
$this->expectException(\InvalidArgumentException::class);
$this->notification->setObject('object', $id);
@@ -208,7 +208,7 @@ class NotificationTest extends TestCase {
* @param string $subject
* @param array $parameters
*/
- public function testSetSubject($subject, $parameters) {
+ public function testSetSubject($subject, $parameters): void {
$this->assertSame('', $this->notification->getSubject());
$this->assertSame([], $this->notification->getSubjectParameters());
$this->assertSame($this->notification, $this->notification->setSubject($subject, $parameters));
@@ -225,7 +225,7 @@ class NotificationTest extends TestCase {
* @param mixed $subject
*
*/
- public function testSetSubjectInvalidSubject($subject) {
+ public function testSetSubjectInvalidSubject($subject): void {
$this->expectException(\InvalidArgumentException::class);
$this->notification->setSubject($subject, []);
@@ -239,7 +239,7 @@ class NotificationTest extends TestCase {
* @dataProvider dataSetParsedSubject
* @param string $subject
*/
- public function testSetParsedSubject($subject) {
+ public function testSetParsedSubject($subject): void {
$this->assertSame('', $this->notification->getParsedSubject());
$this->assertSame($this->notification, $this->notification->setParsedSubject($subject));
$this->assertSame($subject, $this->notification->getParsedSubject());
@@ -254,7 +254,7 @@ class NotificationTest extends TestCase {
* @param mixed $subject
*
*/
- public function testSetParsedSubjectInvalid($subject) {
+ public function testSetParsedSubjectInvalid($subject): void {
$this->expectException(\InvalidArgumentException::class);
$this->notification->setParsedSubject($subject);
@@ -273,7 +273,7 @@ class NotificationTest extends TestCase {
* @param string $message
* @param array $parameters
*/
- public function testSetMessage($message, $parameters) {
+ public function testSetMessage($message, $parameters): void {
$this->assertSame('', $this->notification->getMessage());
$this->assertSame([], $this->notification->getMessageParameters());
$this->assertSame($this->notification, $this->notification->setMessage($message, $parameters));
@@ -290,7 +290,7 @@ class NotificationTest extends TestCase {
* @param mixed $message
*
*/
- public function testSetMessageInvalidMessage($message) {
+ public function testSetMessageInvalidMessage($message): void {
$this->expectException(\InvalidArgumentException::class);
$this->notification->setMessage($message, []);
@@ -304,7 +304,7 @@ class NotificationTest extends TestCase {
* @dataProvider dataSetParsedMessage
* @param string $message
*/
- public function testSetParsedMessage($message) {
+ public function testSetParsedMessage($message): void {
$this->assertSame('', $this->notification->getParsedMessage());
$this->assertSame($this->notification, $this->notification->setParsedMessage($message));
$this->assertSame($message, $this->notification->getParsedMessage());
@@ -319,7 +319,7 @@ class NotificationTest extends TestCase {
* @param mixed $message
*
*/
- public function testSetParsedMessageInvalid($message) {
+ public function testSetParsedMessageInvalid($message): void {
$this->expectException(\InvalidArgumentException::class);
$this->notification->setParsedMessage($message);
@@ -333,7 +333,7 @@ class NotificationTest extends TestCase {
* @dataProvider dataSetLink
* @param string $link
*/
- public function testSetLink($link) {
+ public function testSetLink($link): void {
$this->assertSame('', $this->notification->getLink());
$this->assertSame($this->notification, $this->notification->setLink($link));
$this->assertSame($link, $this->notification->getLink());
@@ -348,7 +348,7 @@ class NotificationTest extends TestCase {
* @param mixed $link
*
*/
- public function testSetLinkInvalid($link) {
+ public function testSetLinkInvalid($link): void {
$this->expectException(\InvalidArgumentException::class);
$this->notification->setLink($link);
@@ -362,7 +362,7 @@ class NotificationTest extends TestCase {
* @dataProvider dataSetIcon
* @param string $icon
*/
- public function testSetIcon($icon) {
+ public function testSetIcon($icon): void {
$this->assertSame('', $this->notification->getIcon());
$this->assertSame($this->notification, $this->notification->setIcon($icon));
$this->assertSame($icon, $this->notification->getIcon());
@@ -377,18 +377,18 @@ class NotificationTest extends TestCase {
* @param mixed $icon
*
*/
- public function testSetIconInvalid($icon) {
+ public function testSetIconInvalid($icon): void {
$this->expectException(\InvalidArgumentException::class);
$this->notification->setIcon($icon);
}
- public function testCreateAction() {
+ public function testCreateAction(): void {
$action = $this->notification->createAction();
$this->assertInstanceOf(IAction::class, $action);
}
- public function testAddAction() {
+ public function testAddAction(): void {
/** @var \OCP\Notification\IAction|\PHPUnit\Framework\MockObject\MockObject $action */
$action = $this->createMock(IAction::class);
$action->expects($this->once())
@@ -404,7 +404,7 @@ class NotificationTest extends TestCase {
}
- public function testAddActionInvalid() {
+ public function testAddActionInvalid(): void {
$this->expectException(\InvalidArgumentException::class);
/** @var \OCP\Notification\IAction|\PHPUnit\Framework\MockObject\MockObject $action */
@@ -418,7 +418,7 @@ class NotificationTest extends TestCase {
$this->notification->addAction($action);
}
- public function testAddActionSecondPrimary() {
+ public function testAddActionSecondPrimary(): void {
/** @var \OCP\Notification\IAction|\PHPUnit\Framework\MockObject\MockObject $action */
$action = $this->createMock(IAction::class);
$action->expects($this->exactly(2))
@@ -434,7 +434,7 @@ class NotificationTest extends TestCase {
$this->notification->addAction($action);
}
- public function testAddParsedAction() {
+ public function testAddParsedAction(): void {
/** @var \OCP\Notification\IAction|\PHPUnit\Framework\MockObject\MockObject $action */
$action = $this->createMock(IAction::class);
$action->expects($this->once())
@@ -450,7 +450,7 @@ class NotificationTest extends TestCase {
}
- public function testAddParsedActionInvalid() {
+ public function testAddParsedActionInvalid(): void {
$this->expectException(\InvalidArgumentException::class);
/** @var \OCP\Notification\IAction|\PHPUnit\Framework\MockObject\MockObject $action */
@@ -464,7 +464,7 @@ class NotificationTest extends TestCase {
$this->notification->addParsedAction($action);
}
- public function testAddActionSecondParsedPrimary() {
+ public function testAddActionSecondParsedPrimary(): void {
/** @var \OCP\Notification\IAction|\PHPUnit\Framework\MockObject\MockObject $action */
$action = $this->createMock(IAction::class);
$action->expects($this->exactly(2))
@@ -480,7 +480,7 @@ class NotificationTest extends TestCase {
$this->notification->addParsedAction($action);
}
- public function testAddActionParsedPrimaryEnd() {
+ public function testAddActionParsedPrimaryEnd(): void {
/** @var \OCP\Notification\IAction|\PHPUnit\Framework\MockObject\MockObject $action */
$action1 = $this->createMock(IAction::class);
$action1->expects($this->exactly(2))
@@ -521,7 +521,7 @@ class NotificationTest extends TestCase {
* @param string $subject
* @param bool $expected
*/
- public function testIsValid($isValidCommon, $subject, $expected) {
+ public function testIsValid($isValidCommon, $subject, $expected): void {
/** @var \OCP\Notification\INotification|\PHPUnit\Framework\MockObject\MockObject $notification */
$notification = $this->getMockBuilder(Notification::class)
->setMethods([
@@ -554,7 +554,7 @@ class NotificationTest extends TestCase {
* @param string $subject
* @param bool $expected
*/
- public function testIsParsedValid($isValidCommon, $subject, $expected) {
+ public function testIsParsedValid($isValidCommon, $subject, $expected): void {
/** @var \OCP\Notification\INotification|\PHPUnit\Framework\MockObject\MockObject $notification */
$notification = $this->getMockBuilder(Notification::class)
->setMethods([
@@ -601,7 +601,7 @@ class NotificationTest extends TestCase {
* @param string $objectId
* @param bool $expected
*/
- public function testIsValidCommon($app, $user, $timestamp, $objectType, $objectId, $expected) {
+ public function testIsValidCommon($app, $user, $timestamp, $objectType, $objectId, $expected): void {
/** @var \OCP\Notification\INotification|\PHPUnit\Framework\MockObject\MockObject $notification */
$notification = $this->getMockBuilder(Notification::class)
->setMethods([
diff --git a/tests/lib/OCS/DiscoveryServiceTest.php b/tests/lib/OCS/DiscoveryServiceTest.php
index c3961c15a7a..3db3163e11d 100644
--- a/tests/lib/OCS/DiscoveryServiceTest.php
+++ b/tests/lib/OCS/DiscoveryServiceTest.php
@@ -40,7 +40,7 @@ class DiscoveryServiceTest extends TestCase {
* @param string $url
* @param bool $expected
*/
- public function testIsSafeUrl($url, $expected) {
+ public function testIsSafeUrl($url, $expected): void {
$result = $this->invokePrivate($this->discoveryService, 'isSafeUrl', [$url]);
$this->assertSame($expected, $result);
}
@@ -64,7 +64,7 @@ class DiscoveryServiceTest extends TestCase {
* @param string $service
* @param array $expected
*/
- public function testGetEndpoints($decodedServices, $service, $expected) {
+ public function testGetEndpoints($decodedServices, $service, $expected): void {
$result = $this->invokePrivate($this->discoveryService, 'getEndpoints', [$decodedServices, $service]);
$this->assertSame($expected, $result);
}
diff --git a/tests/lib/OCS/ProviderTest.php b/tests/lib/OCS/ProviderTest.php
index c4a319db09b..a86a2b1aebb 100644
--- a/tests/lib/OCS/ProviderTest.php
+++ b/tests/lib/OCS/ProviderTest.php
@@ -25,7 +25,7 @@ class ProviderTest extends \Test\TestCase {
$this->ocsProvider = new Provider('ocs_provider', $this->request, $this->appManager);
}
- public function testBuildProviderListWithoutAnythingEnabled() {
+ public function testBuildProviderListWithoutAnythingEnabled(): void {
$this->appManager
->expects($this->exactly(4))
->method('isEnabledForUser')
@@ -56,7 +56,7 @@ class ProviderTest extends \Test\TestCase {
$this->assertEquals($expected, $this->ocsProvider->buildProviderList());
}
- public function testBuildProviderListWithSharingEnabled() {
+ public function testBuildProviderListWithSharingEnabled(): void {
$this->appManager
->expects($this->exactly(4))
->method('isEnabledForUser')
@@ -105,7 +105,7 @@ class ProviderTest extends \Test\TestCase {
$this->assertEquals($expected, $this->ocsProvider->buildProviderList());
}
- public function testBuildProviderListWithFederationEnabled() {
+ public function testBuildProviderListWithFederationEnabled(): void {
$this->appManager
->expects($this->exactly(4))
->method('isEnabledForUser')
@@ -149,7 +149,7 @@ class ProviderTest extends \Test\TestCase {
$this->assertEquals($expected, $this->ocsProvider->buildProviderList());
}
- public function testBuildProviderListWithEverythingEnabled() {
+ public function testBuildProviderListWithEverythingEnabled(): void {
$this->appManager
->expects($this->any())
->method('isEnabledForUser')
diff --git a/tests/lib/Preview/BackgroundCleanupJobTest.php b/tests/lib/Preview/BackgroundCleanupJobTest.php
index 82f19797728..d9ea1718491 100644
--- a/tests/lib/Preview/BackgroundCleanupJobTest.php
+++ b/tests/lib/Preview/BackgroundCleanupJobTest.php
@@ -121,7 +121,7 @@ class BackgroundCleanupJobTest extends \Test\TestCase {
return $i;
}
- public function testCleanupSystemCron() {
+ public function testCleanupSystemCron(): void {
$files = $this->setup11Previews();
$fileIds = array_map(function (File $f) {
return $f->getId();
@@ -145,7 +145,7 @@ class BackgroundCleanupJobTest extends \Test\TestCase {
$this->assertSame(0, $this->countPreviews($root, $fileIds));
}
- public function testCleanupAjax() {
+ public function testCleanupAjax(): void {
if ($this->connection->getShardDefinition('filecache')) {
$this->markTestSkipped('ajax cron is not supported for sharded setups');
return;
@@ -177,7 +177,7 @@ class BackgroundCleanupJobTest extends \Test\TestCase {
$this->assertSame(0, $this->countPreviews($root, $fileIds));
}
- public function testOldPreviews() {
+ public function testOldPreviews(): void {
if ($this->connection->getShardDefinition('filecache')) {
$this->markTestSkipped('old previews are not supported for sharded setups');
return;
diff --git a/tests/lib/Preview/GeneratorTest.php b/tests/lib/Preview/GeneratorTest.php
index d458062f561..7bd121250fb 100644
--- a/tests/lib/Preview/GeneratorTest.php
+++ b/tests/lib/Preview/GeneratorTest.php
@@ -57,7 +57,7 @@ class GeneratorTest extends \Test\TestCase {
);
}
- public function testGetCachedPreview() {
+ public function testGetCachedPreview(): void {
$file = $this->createMock(File::class);
$file->method('isReadable')
->willReturn(true);
@@ -97,7 +97,7 @@ class GeneratorTest extends \Test\TestCase {
$this->assertSame($previewFile, $result);
}
- public function testGetNewPreview() {
+ public function testGetNewPreview(): void {
$file = $this->createMock(File::class);
$file->method('isReadable')
->willReturn(true);
@@ -225,7 +225,7 @@ class GeneratorTest extends \Test\TestCase {
$this->assertSame($previewFile, $result);
}
- public function testInvalidMimeType() {
+ public function testInvalidMimeType(): void {
$this->expectException(NotFoundException::class);
$file = $this->createMock(File::class);
@@ -263,7 +263,7 @@ class GeneratorTest extends \Test\TestCase {
$this->generator->getPreview($file, 1024, 512, true, IPreview::MODE_COVER, 'invalidType');
}
- public function testReturnCachedPreviewsWithoutCheckingSupportedMimetype() {
+ public function testReturnCachedPreviewsWithoutCheckingSupportedMimetype(): void {
$file = $this->createMock(File::class);
$file->method('isReadable')
->willReturn(true);
@@ -301,7 +301,7 @@ class GeneratorTest extends \Test\TestCase {
$this->assertSame($preview, $result);
}
- public function testNoProvider() {
+ public function testNoProvider(): void {
$file = $this->createMock(File::class);
$file->method('isReadable')
->willReturn(true);
@@ -398,7 +398,7 @@ class GeneratorTest extends \Test\TestCase {
* @param int $expectedX
* @param int $expectedY
*/
- public function testCorrectSize($maxX, $maxY, $reqX, $reqY, $crop, $mode, $expectedX, $expectedY) {
+ public function testCorrectSize($maxX, $maxY, $reqX, $reqY, $crop, $mode, $expectedX, $expectedY): void {
$file = $this->createMock(File::class);
$file->method('isReadable')
->willReturn(true);
@@ -458,7 +458,7 @@ class GeneratorTest extends \Test\TestCase {
}
}
- public function testUnreadbleFile() {
+ public function testUnreadbleFile(): void {
$file = $this->createMock(File::class);
$file->method('isReadable')
->willReturn(false);
diff --git a/tests/lib/Preview/Provider.php b/tests/lib/Preview/Provider.php
index 6cecd8a0762..41a2a4ca3c4 100644
--- a/tests/lib/Preview/Provider.php
+++ b/tests/lib/Preview/Provider.php
@@ -78,7 +78,7 @@ abstract class Provider extends \Test\TestCase {
* @param int $widthAdjustment
* @param int $heightAdjustment
*/
- public function testGetThumbnail($widthAdjustment, $heightAdjustment) {
+ public function testGetThumbnail($widthAdjustment, $heightAdjustment): void {
$ratio = round($this->width / $this->height, 2);
$this->maxWidth = $this->width - $widthAdjustment;
$this->maxHeight = $this->height - $heightAdjustment;
diff --git a/tests/lib/PublicNamespace/UtilTest.php b/tests/lib/PublicNamespace/UtilTest.php
index 6931b191a4d..4fa31bd902a 100644
--- a/tests/lib/PublicNamespace/UtilTest.php
+++ b/tests/lib/PublicNamespace/UtilTest.php
@@ -13,7 +13,7 @@ class UtilTest extends \Test\TestCase {
*
* @param string $channel
*/
- public function testOverrideChannel($channel) {
+ public function testOverrideChannel($channel): void {
\OCP\Util::setChannel($channel);
$actual = \OCP\Util::getChannel($channel);
$this->assertEquals($channel, $actual);
diff --git a/tests/lib/Remote/Api/OCSTest.php b/tests/lib/Remote/Api/OCSTest.php
index d47bb50cc35..3fcc486f246 100644
--- a/tests/lib/Remote/Api/OCSTest.php
+++ b/tests/lib/Remote/Api/OCSTest.php
@@ -40,7 +40,7 @@ class OCSTest extends TestCase {
return 'https://example.com/ocs/v2.php/' . $url;
}
- public function testGetUser() {
+ public function testGetUser(): void {
$client = $this->getOCSClient();
$this->expectGetRequest($this->getOCSUrl('cloud/users/user'),
@@ -53,7 +53,7 @@ class OCSTest extends TestCase {
}
- public function testGetUserInvalidResponse() {
+ public function testGetUserInvalidResponse(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Invalid user response, expected field email not found');
@@ -67,7 +67,7 @@ class OCSTest extends TestCase {
}
- public function testInvalidPassword() {
+ public function testInvalidPassword(): void {
$this->expectException(\OC\ForbiddenException::class);
$client = $this->getOCSClient();
diff --git a/tests/lib/Remote/InstanceTest.php b/tests/lib/Remote/InstanceTest.php
index 3e4ffda15b7..027a67010be 100644
--- a/tests/lib/Remote/InstanceTest.php
+++ b/tests/lib/Remote/InstanceTest.php
@@ -24,7 +24,7 @@ class InstanceTest extends TestCase {
$this->cache = new ArrayCache();
}
- public function testBasicStatus() {
+ public function testBasicStatus(): void {
$instance = new Instance('example.com', $this->cache, $this->getClientService());
$this->expectGetRequest('https://example.com/status.php', '{"installed":true,"maintenance":false,"needsDbUpgrade":false,"version":"13.0.0.5","versionstring":"13.0.0 alpha","edition":"","productname":"Nextcloud"}');
@@ -34,7 +34,7 @@ class InstanceTest extends TestCase {
$this->assertEquals('https://example.com', $instance->getFullUrl());
}
- public function testHttpFallback() {
+ public function testHttpFallback(): void {
$instance = new Instance('example.com', $this->cache, $this->getClientService());
$this->expectGetRequest('https://example.com/status.php', new \Exception());
$this->expectGetRequest('http://example.com/status.php', '{"installed":true,"maintenance":false,"needsDbUpgrade":false,"version":"13.0.0.5","versionstring":"13.0.0 alpha","edition":"","productname":"Nextcloud"}');
@@ -43,7 +43,7 @@ class InstanceTest extends TestCase {
$this->assertEquals('http://example.com', $instance->getFullUrl());
}
- public function testRerequestHttps() {
+ public function testRerequestHttps(): void {
$instance = new Instance('example.com', $this->cache, $this->getClientService());
$this->expectGetRequest('https://example.com/status.php', '{"installed":true,"maintenance":false,"needsDbUpgrade":false,"version":"13.0.0.5","versionstring":"13.0.0 alpha","edition":"","productname":"Nextcloud"}');
@@ -58,7 +58,7 @@ class InstanceTest extends TestCase {
}
- public function testPreventDowngradeAttach() {
+ 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 6c25248df77..f484a0cd1aa 100644
--- a/tests/lib/Repair/CleanTagsTest.php
+++ b/tests/lib/Repair/CleanTagsTest.php
@@ -69,7 +69,7 @@ class CleanTagsTest extends \Test\TestCase {
->execute();
}
- public function testRun() {
+ public function testRun(): void {
$cat1 = $this->addTagCategory('TestRepairCleanTags', 'files'); // Retained
$cat2 = $this->addTagCategory('TestRepairCleanTags2', 'files'); // Deleted: Category will be empty
$this->addTagCategory('TestRepairCleanTags3', 'files'); // Deleted: Category is empty
diff --git a/tests/lib/Repair/ClearFrontendCachesTest.php b/tests/lib/Repair/ClearFrontendCachesTest.php
index 640e272f3b7..e48db295d45 100644
--- a/tests/lib/Repair/ClearFrontendCachesTest.php
+++ b/tests/lib/Repair/ClearFrontendCachesTest.php
@@ -36,7 +36,7 @@ class ClearFrontendCachesTest extends \Test\TestCase {
}
- public function testRun() {
+ public function testRun(): void {
$imagePathCache = $this->createMock(ICache::class);
$imagePathCache->expects($this->once())
->method('clear')
diff --git a/tests/lib/Repair/ClearGeneratedAvatarCacheTest.php b/tests/lib/Repair/ClearGeneratedAvatarCacheTest.php
index 994e2a49f1a..c03b9082446 100644
--- a/tests/lib/Repair/ClearGeneratedAvatarCacheTest.php
+++ b/tests/lib/Repair/ClearGeneratedAvatarCacheTest.php
@@ -57,7 +57,7 @@ class ClearGeneratedAvatarCacheTest extends \Test\TestCase {
* @param string $from
* @param boolean $expected
*/
- public function testShouldRun($from, $expected) {
+ public function testShouldRun($from, $expected): void {
$this->config->expects($this->any())
->method('getSystemValueString')
->with('version', '0.0.0.0')
diff --git a/tests/lib/Repair/OldGroupMembershipSharesTest.php b/tests/lib/Repair/OldGroupMembershipSharesTest.php
index c734f0a9e13..269e2f016cf 100644
--- a/tests/lib/Repair/OldGroupMembershipSharesTest.php
+++ b/tests/lib/Repair/OldGroupMembershipSharesTest.php
@@ -51,7 +51,7 @@ class OldGroupMembershipSharesTest extends \Test\TestCase {
$qb->delete('share')->execute();
}
- public function testRun() {
+ public function testRun(): void {
$repair = new OldGroupMembershipShares(
$this->connection,
$this->groupManager
diff --git a/tests/lib/Repair/RepairCollationTest.php b/tests/lib/Repair/RepairCollationTest.php
index bfeae9e769e..82d0a3702a0 100644
--- a/tests/lib/Repair/RepairCollationTest.php
+++ b/tests/lib/Repair/RepairCollationTest.php
@@ -76,7 +76,7 @@ class RepairCollationTest extends TestCase {
parent::tearDown();
}
- public function testCollationConvert() {
+ public function testCollationConvert(): void {
$tables = $this->repair->getAllNonUTF8BinTables($this->connection);
$this->assertGreaterThanOrEqual(1, count($tables));
diff --git a/tests/lib/Repair/RepairDavSharesTest.php b/tests/lib/Repair/RepairDavSharesTest.php
index 9831365e974..3a97de4d25d 100644
--- a/tests/lib/Repair/RepairDavSharesTest.php
+++ b/tests/lib/Repair/RepairDavSharesTest.php
@@ -52,7 +52,7 @@ class RepairDavSharesTest extends TestCase {
);
}
- public function testRun() {
+ public function testRun(): void {
$this->config->expects($this->any())
->method('getSystemValueString')
->with('version', '0.0.0')
diff --git a/tests/lib/Repair/RepairInvalidSharesTest.php b/tests/lib/Repair/RepairInvalidSharesTest.php
index d43b3969a29..23d03ba14af 100644
--- a/tests/lib/Repair/RepairInvalidSharesTest.php
+++ b/tests/lib/Repair/RepairInvalidSharesTest.php
@@ -60,7 +60,7 @@ class RepairInvalidSharesTest extends TestCase {
/**
* Test remove shares where the parent share does not exist anymore
*/
- public function testSharesNonExistingParent() {
+ public function testSharesNonExistingParent(): void {
$qb = $this->connection->getQueryBuilder();
$shareValues = [
'share_type' => $qb->expr()->literal(IShare::TYPE_USER),
@@ -153,7 +153,7 @@ class RepairInvalidSharesTest extends TestCase {
*
* @dataProvider fileSharePermissionsProvider
*/
- public function testFileSharePermissions($itemType, $testPerms, $expectedPerms) {
+ public function testFileSharePermissions($itemType, $testPerms, $expectedPerms): void {
$qb = $this->connection->getQueryBuilder();
$qb->insert('share')
->values([
diff --git a/tests/lib/Repair/RepairMimeTypesTest.php b/tests/lib/Repair/RepairMimeTypesTest.php
index 393187b9ab9..3efef4b3bf5 100644
--- a/tests/lib/Repair/RepairMimeTypesTest.php
+++ b/tests/lib/Repair/RepairMimeTypesTest.php
@@ -113,7 +113,7 @@ class RepairMimeTypesTest extends \Test\TestCase {
/**
* Test renaming the additional image mime types
*/
- public function testRenameImageTypes() {
+ public function testRenameImageTypes(): void {
$currentMimeTypes = [
['test.jp2', 'application/octet-stream'],
['test.webp', 'application/octet-stream'],
@@ -130,7 +130,7 @@ class RepairMimeTypesTest extends \Test\TestCase {
/**
* Test renaming the richdocuments additional office mime types
*/
- public function testRenameWindowsProgramTypes() {
+ public function testRenameWindowsProgramTypes(): void {
$currentMimeTypes = [
['test.htaccess', 'application/octet-stream'],
['.htaccess', 'application/octet-stream'],
@@ -152,7 +152,7 @@ class RepairMimeTypesTest extends \Test\TestCase {
* Test that nothing happens and no error happens when all mimetypes are
* already correct and no old ones exist..
*/
- public function testDoNothingWhenOnlyNewFiles() {
+ public function testDoNothingWhenOnlyNewFiles(): void {
$currentMimeTypes = [
['test.doc', 'application/msword'],
['test.docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
@@ -267,7 +267,7 @@ class RepairMimeTypesTest extends \Test\TestCase {
/**
* Test that mime type renaming does not affect folders
*/
- public function testDoNotChangeFolderMimeType() {
+ public function testDoNotChangeFolderMimeType(): void {
$currentMimeTypes = [
['test.conf', 'httpd/unix-directory'],
['test.cnf', 'httpd/unix-directory'],
diff --git a/tests/lib/RepairTest.php b/tests/lib/RepairTest.php
index ab60b14d47e..97c278a1d10 100644
--- a/tests/lib/RepairTest.php
+++ b/tests/lib/RepairTest.php
@@ -61,7 +61,7 @@ class RepairTest extends TestCase {
});
}
- public function testRunRepairStep() {
+ public function testRunRepairStep(): void {
$this->repair->addStep(new TestRepairStep(false));
$this->repair->run();
@@ -74,7 +74,7 @@ class RepairTest extends TestCase {
);
}
- public function testRunRepairStepThatFail() {
+ public function testRunRepairStepThatFail(): void {
$this->repair->addStep(new TestRepairStep(true));
$this->repair->run();
@@ -87,7 +87,7 @@ class RepairTest extends TestCase {
);
}
- public function testRunRepairStepsWithException() {
+ public function testRunRepairStepsWithException(): void {
$mock = $this->createMock(TestRepairStep::class);
$mock->expects($this->any())
->method('run')
@@ -119,7 +119,7 @@ class RepairTest extends TestCase {
);
}
- public function testRunRepairStepsContinueAfterWarning() {
+ public function testRunRepairStepsContinueAfterWarning(): void {
$this->repair->addStep(new TestRepairStep(true));
$this->repair->addStep(new TestRepairStep(false));
$this->repair->run();
diff --git a/tests/lib/RichObjectStrings/DefinitionsTest.php b/tests/lib/RichObjectStrings/DefinitionsTest.php
index efe372a25e8..9299a556972 100644
--- a/tests/lib/RichObjectStrings/DefinitionsTest.php
+++ b/tests/lib/RichObjectStrings/DefinitionsTest.php
@@ -20,7 +20,7 @@ class DefinitionsTest extends TestCase {
}
- public function testGetDefinitionNotExisting() {
+ public function testGetDefinitionNotExisting(): void {
$this->expectException(\OCP\RichObjectStrings\InvalidObjectExeption::class);
$this->expectExceptionMessage('Object type is undefined');
@@ -33,7 +33,7 @@ class DefinitionsTest extends TestCase {
* @param string $type
* @param array $expected
*/
- public function testGetDefinition($type, array $expected) {
+ 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 91fe10916d2..e5230efe462 100644
--- a/tests/lib/RichObjectStrings/ValidatorTest.php
+++ b/tests/lib/RichObjectStrings/ValidatorTest.php
@@ -12,7 +12,7 @@ use OCP\RichObjectStrings\InvalidObjectExeption;
use Test\TestCase;
class ValidatorTest extends TestCase {
- public function test() {
+ public function test(): void {
$v = new Validator(new Definitions());
$v->validate('test', []);
$v->validate('test {string1} test {foo} test {bar}.', [
diff --git a/tests/lib/Security/Bruteforce/ThrottlerTest.php b/tests/lib/Security/Bruteforce/ThrottlerTest.php
index 69d20cccd3a..a94f1849c8a 100644
--- a/tests/lib/Security/Bruteforce/ThrottlerTest.php
+++ b/tests/lib/Security/Bruteforce/ThrottlerTest.php
@@ -183,7 +183,7 @@ class ThrottlerTest extends TestCase {
*/
public function testIsIpWhiteListedWithEnabledProtection($ip,
$whitelists,
- $isWhiteListed) {
+ $isWhiteListed): void {
$this->isIpWhiteListedHelper(
$ip,
$whitelists,
@@ -201,7 +201,7 @@ class ThrottlerTest extends TestCase {
*/
public function testIsIpWhiteListedWithDisabledProtection($ip,
$whitelists,
- $isWhiteListed) {
+ $isWhiteListed): void {
$this->isIpWhiteListedHelper(
$ip,
$whitelists,
diff --git a/tests/lib/Security/CSP/AddContentSecurityPolicyEventTest.php b/tests/lib/Security/CSP/AddContentSecurityPolicyEventTest.php
index edc0c613655..39dd7a95890 100644
--- a/tests/lib/Security/CSP/AddContentSecurityPolicyEventTest.php
+++ b/tests/lib/Security/CSP/AddContentSecurityPolicyEventTest.php
@@ -15,7 +15,7 @@ use OCP\Security\CSP\AddContentSecurityPolicyEvent;
use Test\TestCase;
class AddContentSecurityPolicyEventTest extends TestCase {
- public function testAddEvent() {
+ public function testAddEvent(): void {
$cspManager = $this->createMock(ContentSecurityPolicyManager::class);
$policy = $this->createMock(ContentSecurityPolicy::class);
$event = new AddContentSecurityPolicyEvent($cspManager);
diff --git a/tests/lib/Security/CSP/ContentSecurityPolicyManagerTest.php b/tests/lib/Security/CSP/ContentSecurityPolicyManagerTest.php
index dc0fe7c8340..63a5565e7fa 100644
--- a/tests/lib/Security/CSP/ContentSecurityPolicyManagerTest.php
+++ b/tests/lib/Security/CSP/ContentSecurityPolicyManagerTest.php
@@ -28,12 +28,12 @@ class ContentSecurityPolicyManagerTest extends TestCase {
$this->contentSecurityPolicyManager = new ContentSecurityPolicyManager($this->dispatcher);
}
- public function testAddDefaultPolicy() {
+ public function testAddDefaultPolicy(): void {
$this->contentSecurityPolicyManager->addDefaultPolicy(new \OCP\AppFramework\Http\ContentSecurityPolicy());
$this->addToAssertionCount(1);
}
- public function testGetDefaultPolicyWithPolicies() {
+ public function testGetDefaultPolicyWithPolicies(): void {
$policy = new \OCP\AppFramework\Http\ContentSecurityPolicy();
$policy->addAllowedFontDomain('mydomain.com');
$policy->addAllowedImageDomain('anotherdomain.de');
@@ -64,7 +64,7 @@ class ContentSecurityPolicyManagerTest extends TestCase {
$this->assertSame($expectedStringPolicy, $this->contentSecurityPolicyManager->getDefaultPolicy()->buildPolicy());
}
- public function testGetDefaultPolicyWithPoliciesViaEvent() {
+ public function testGetDefaultPolicyWithPoliciesViaEvent(): void {
$this->dispatcher->addListener(AddContentSecurityPolicyEvent::class, function (AddContentSecurityPolicyEvent $e) {
$policy = new \OCP\AppFramework\Http\ContentSecurityPolicy();
$policy->addAllowedFontDomain('mydomain.com');
diff --git a/tests/lib/Security/CSP/ContentSecurityPolicyNonceManagerTest.php b/tests/lib/Security/CSP/ContentSecurityPolicyNonceManagerTest.php
index 54c8fe832cc..3765311155a 100644
--- a/tests/lib/Security/CSP/ContentSecurityPolicyNonceManagerTest.php
+++ b/tests/lib/Security/CSP/ContentSecurityPolicyNonceManagerTest.php
@@ -33,7 +33,7 @@ class ContentSecurityPolicyNonceManagerTest extends TestCase {
);
}
- public function testGetNonce() {
+ public function testGetNonce(): void {
$secret = base64_encode('secret');
$tokenValue = base64_encode('secret' ^ 'value_') . ':' . $secret;
$token = $this->createMock(CsrfToken::class);
@@ -52,7 +52,7 @@ class ContentSecurityPolicyNonceManagerTest extends TestCase {
$this->assertSame($secret, $this->nonceManager->getNonce());
}
- public function testGetNonceServerVar() {
+ public function testGetNonceServerVar(): void {
$token = 'SERVERNONCE';
$this->request
->method('__isset')
diff --git a/tests/lib/Security/CSRF/CsrfTokenGeneratorTest.php b/tests/lib/Security/CSRF/CsrfTokenGeneratorTest.php
index 449a7956756..dca60d022d2 100644
--- a/tests/lib/Security/CSRF/CsrfTokenGeneratorTest.php
+++ b/tests/lib/Security/CSRF/CsrfTokenGeneratorTest.php
@@ -23,7 +23,7 @@ class CsrfTokenGeneratorTest extends \Test\TestCase {
$this->csrfTokenGenerator = new \OC\Security\CSRF\CsrfTokenGenerator($this->random);
}
- public function testGenerateTokenWithCustomNumber() {
+ public function testGenerateTokenWithCustomNumber(): void {
$this->random
->expects($this->once())
->method('generate')
@@ -32,7 +32,7 @@ class CsrfTokenGeneratorTest extends \Test\TestCase {
$this->assertSame('abc', $this->csrfTokenGenerator->generateToken(3));
}
- public function testGenerateTokenWithDefault() {
+ public function testGenerateTokenWithDefault(): void {
$this->random
->expects($this->once())
->method('generate')
diff --git a/tests/lib/Security/CSRF/CsrfTokenManagerTest.php b/tests/lib/Security/CSRF/CsrfTokenManagerTest.php
index 5c4ad6346e7..aeb512f1521 100644
--- a/tests/lib/Security/CSRF/CsrfTokenManagerTest.php
+++ b/tests/lib/Security/CSRF/CsrfTokenManagerTest.php
@@ -31,7 +31,7 @@ class CsrfTokenManagerTest extends \Test\TestCase {
);
}
- public function testGetTokenWithExistingToken() {
+ public function testGetTokenWithExistingToken(): void {
$this->storageInterface
->expects($this->once())
->method('hasToken')
@@ -45,7 +45,7 @@ class CsrfTokenManagerTest extends \Test\TestCase {
$this->assertEquals($expected, $this->csrfTokenManager->getToken());
}
- public function testGetTokenWithExistingTokenKeepsOnSecondRequest() {
+ public function testGetTokenWithExistingTokenKeepsOnSecondRequest(): void {
$this->storageInterface
->expects($this->once())
->method('hasToken')
@@ -61,7 +61,7 @@ class CsrfTokenManagerTest extends \Test\TestCase {
$this->assertSame($token, $this->csrfTokenManager->getToken());
}
- public function testGetTokenWithoutExistingToken() {
+ public function testGetTokenWithoutExistingToken(): void {
$this->storageInterface
->expects($this->once())
->method('hasToken')
@@ -79,7 +79,7 @@ class CsrfTokenManagerTest extends \Test\TestCase {
$this->assertEquals($expected, $this->csrfTokenManager->getToken());
}
- public function testRefreshToken() {
+ public function testRefreshToken(): void {
$this->tokenGenerator
->expects($this->once())
->method('generateToken')
@@ -93,7 +93,7 @@ class CsrfTokenManagerTest extends \Test\TestCase {
$this->assertEquals($expected, $this->csrfTokenManager->refreshToken());
}
- public function testRemoveToken() {
+ public function testRemoveToken(): void {
$this->storageInterface
->expects($this->once())
->method('removeToken');
@@ -101,7 +101,7 @@ class CsrfTokenManagerTest extends \Test\TestCase {
$this->csrfTokenManager->removeToken();
}
- public function testIsTokenValidWithoutToken() {
+ public function testIsTokenValidWithoutToken(): void {
$this->storageInterface
->expects($this->once())
->method('hasToken')
@@ -111,7 +111,7 @@ class CsrfTokenManagerTest extends \Test\TestCase {
$this->assertSame(false, $this->csrfTokenManager->isTokenValid($token));
}
- public function testIsTokenValidWithWrongToken() {
+ public function testIsTokenValidWithWrongToken(): void {
$this->storageInterface
->expects($this->once())
->method('hasToken')
@@ -125,7 +125,7 @@ class CsrfTokenManagerTest extends \Test\TestCase {
$this->assertSame(false, $this->csrfTokenManager->isTokenValid($token));
}
- public function testIsTokenValidWithValidToken() {
+ public function testIsTokenValidWithValidToken(): void {
$a = 'abc';
$b = 'def';
$xorB64 = 'BQcF';
diff --git a/tests/lib/Security/CSRF/CsrfTokenTest.php b/tests/lib/Security/CSRF/CsrfTokenTest.php
index c6f9aaa5be7..9ecbbe9f23a 100644
--- a/tests/lib/Security/CSRF/CsrfTokenTest.php
+++ b/tests/lib/Security/CSRF/CsrfTokenTest.php
@@ -11,20 +11,20 @@ declare(strict_types=1);
namespace Test\Security\CSRF;
class CsrfTokenTest extends \Test\TestCase {
- public function testGetEncryptedValue() {
+ public function testGetEncryptedValue(): void {
$csrfToken = new \OC\Security\CSRF\CsrfToken('MyCsrfToken');
$this->assertSame(33, strlen($csrfToken->getEncryptedValue()));
$this->assertSame(':', $csrfToken->getEncryptedValue()[16]);
}
- public function testGetEncryptedValueStaysSameOnSecondRequest() {
+ public function testGetEncryptedValueStaysSameOnSecondRequest(): void {
$csrfToken = new \OC\Security\CSRF\CsrfToken('MyCsrfToken');
$tokenValue = $csrfToken->getEncryptedValue();
$this->assertSame($tokenValue, $csrfToken->getEncryptedValue());
$this->assertSame($tokenValue, $csrfToken->getEncryptedValue());
}
- public function testGetDecryptedValue() {
+ public function testGetDecryptedValue(): void {
$a = 'abc';
$b = 'def';
$xorB64 = 'BQcF';
diff --git a/tests/lib/Security/CSRF/TokenStorage/SessionStorageTest.php b/tests/lib/Security/CSRF/TokenStorage/SessionStorageTest.php
index 8e5c8b8e481..f8386124626 100644
--- a/tests/lib/Security/CSRF/TokenStorage/SessionStorageTest.php
+++ b/tests/lib/Security/CSRF/TokenStorage/SessionStorageTest.php
@@ -44,7 +44,7 @@ class SessionStorageTest extends \Test\TestCase {
* @dataProvider getTokenDataProvider
*
*/
- public function testGetTokenWithEmptyToken($token) {
+ public function testGetTokenWithEmptyToken($token): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Session does not contain a requesttoken');
@@ -56,7 +56,7 @@ class SessionStorageTest extends \Test\TestCase {
$this->sessionStorage->getToken();
}
- public function testGetTokenWithValidToken() {
+ public function testGetTokenWithValidToken(): void {
$this->session
->expects($this->once())
->method('get')
@@ -65,7 +65,7 @@ class SessionStorageTest extends \Test\TestCase {
$this->assertSame('MyFancyCsrfToken', $this->sessionStorage->getToken());
}
- public function testSetToken() {
+ public function testSetToken(): void {
$this->session
->expects($this->once())
->method('set')
@@ -73,7 +73,7 @@ class SessionStorageTest extends \Test\TestCase {
$this->sessionStorage->setToken('TokenToSet');
}
- public function testRemoveToken() {
+ public function testRemoveToken(): void {
$this->session
->expects($this->once())
->method('remove')
@@ -81,7 +81,7 @@ class SessionStorageTest extends \Test\TestCase {
$this->sessionStorage->removeToken();
}
- public function testHasTokenWithExistingToken() {
+ public function testHasTokenWithExistingToken(): void {
$this->session
->expects($this->once())
->method('exists')
@@ -90,7 +90,7 @@ class SessionStorageTest extends \Test\TestCase {
$this->assertSame(true, $this->sessionStorage->hasToken());
}
- public function testHasTokenWithoutExistingToken() {
+ public function testHasTokenWithoutExistingToken(): void {
$this->session
->expects($this->once())
->method('exists')
@@ -99,7 +99,7 @@ class SessionStorageTest extends \Test\TestCase {
$this->assertSame(false, $this->sessionStorage->hasToken());
}
- public function testSetSession() {
+ public function testSetSession(): void {
$session = $this->createMock(ISession::class);
$session
->expects($this->once())
diff --git a/tests/lib/Security/CertificateManagerTest.php b/tests/lib/Security/CertificateManagerTest.php
index 1e2d5fb601e..e6177272875 100644
--- a/tests/lib/Security/CertificateManagerTest.php
+++ b/tests/lib/Security/CertificateManagerTest.php
@@ -76,7 +76,7 @@ class CertificateManagerTest extends \Test\TestCase {
$this->assertEquals($expected, $actual);
}
- public function testListCertificates() {
+ public function testListCertificates(): void {
// Test empty certificate bundle
$this->assertSame([], $this->certificateManager->listCertificates());
@@ -93,7 +93,7 @@ class CertificateManagerTest extends \Test\TestCase {
}
- public function testAddInvalidCertificate() {
+ public function testAddInvalidCertificate(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Certificate could not get parsed.');
@@ -115,21 +115,21 @@ class CertificateManagerTest extends \Test\TestCase {
* @dataProvider dangerousFileProvider
* @param string $filename
*/
- public function testAddDangerousFile($filename) {
+ public function testAddDangerousFile($filename): void {
$this->expectException(InvalidPathException::class);
$this->certificateManager->addCertificate(file_get_contents(__DIR__ . '/../../data/certificates/expiredCertificate.crt'), $filename);
}
- public function testRemoveDangerousFile() {
+ public function testRemoveDangerousFile(): void {
$this->assertFalse($this->certificateManager->removeCertificate('../../foo.txt'));
}
- public function testRemoveExistingFile() {
+ public function testRemoveExistingFile(): void {
$this->certificateManager->addCertificate(file_get_contents(__DIR__ . '/../../data/certificates/goodCertificate.crt'), 'GoodCertificate');
$this->assertTrue($this->certificateManager->removeCertificate('GoodCertificate'));
}
- public function testGetCertificateBundle() {
+ public function testGetCertificateBundle(): void {
$this->assertSame('/files_external/rootcerts.crt', $this->certificateManager->getCertificateBundle());
}
@@ -145,7 +145,7 @@ class CertificateManagerTest extends \Test\TestCase {
$targetBundleMtime,
$targetBundleExists,
$expected
- ) {
+ ): void {
$view = $this->getMockBuilder(View::class)
->disableOriginalConstructor()->getMock();
$config = $this->createMock(IConfig::class);
diff --git a/tests/lib/Security/CertificateTest.php b/tests/lib/Security/CertificateTest.php
index 6f4e736263b..8b084ca41b3 100644
--- a/tests/lib/Security/CertificateTest.php
+++ b/tests/lib/Security/CertificateTest.php
@@ -32,7 +32,7 @@ class CertificateTest extends \Test\TestCase {
}
- public function testBogusData() {
+ public function testBogusData(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Certificate could not get parsed.');
@@ -41,36 +41,36 @@ class CertificateTest extends \Test\TestCase {
}
- public function testCertificateStartingWithFileReference() {
+ public function testCertificateStartingWithFileReference(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Certificate could not get parsed.');
new Certificate('file://'.__DIR__ . '/../../data/certificates/goodCertificate.crt', 'bar');
}
- public function testGetName() {
+ public function testGetName(): void {
$this->assertSame('GoodCertificate', $this->goodCertificate->getName());
$this->assertSame('BadCertificate', $this->invalidCertificate->getName());
}
- public function testGetCommonName() {
+ public function testGetCommonName(): void {
$this->assertSame('security.owncloud.com', $this->goodCertificate->getCommonName());
$this->assertSame(null, $this->invalidCertificate->getCommonName());
}
- public function testGetOrganization() {
+ public function testGetOrganization(): void {
$this->assertSame('ownCloud Security', $this->goodCertificate->getOrganization());
$this->assertSame('Internet Widgits Pty Ltd', $this->invalidCertificate->getOrganization());
}
- public function testGetIssueDate() {
+ public function testGetIssueDate(): void {
$expected = new \DateTime('2015-08-27 20:03:42 GMT');
$this->assertEquals($expected->getTimestamp(), $this->goodCertificate->getIssueDate()->getTimestamp());
$expected = new \DateTime('2015-08-27 20:19:13 GMT');
$this->assertEquals($expected->getTimestamp(), $this->invalidCertificate->getIssueDate()->getTimestamp());
}
- public function testGetExpireDate() {
+ public function testGetExpireDate(): void {
$expected = new \DateTime('2025-08-24 20:03:42 GMT');
$this->assertEquals($expected->getTimestamp(), $this->goodCertificate->getExpireDate()->getTimestamp());
$expected = new \DateTime('2025-08-24 20:19:13 GMT');
@@ -79,19 +79,19 @@ class CertificateTest extends \Test\TestCase {
$this->assertEquals($expected->getTimestamp(), $this->expiredCertificate->getExpireDate()->getTimestamp());
}
- public function testIsExpired() {
+ public function testIsExpired(): void {
$this->assertSame(false, $this->goodCertificate->isExpired());
$this->assertSame(false, $this->invalidCertificate->isExpired());
$this->assertSame(true, $this->expiredCertificate->isExpired());
}
- public function testGetIssuerName() {
+ public function testGetIssuerName(): void {
$this->assertSame('security.owncloud.com', $this->goodCertificate->getIssuerName());
$this->assertSame(null, $this->invalidCertificate->getIssuerName());
$this->assertSame(null, $this->expiredCertificate->getIssuerName());
}
- public function testGetIssuerOrganization() {
+ public function testGetIssuerOrganization(): void {
$this->assertSame('ownCloud Security', $this->goodCertificate->getIssuerOrganization());
$this->assertSame('Internet Widgits Pty Ltd', $this->invalidCertificate->getIssuerOrganization());
$this->assertSame('Internet Widgits Pty Ltd', $this->expiredCertificate->getIssuerOrganization());
diff --git a/tests/lib/Security/CredentialsManagerTest.php b/tests/lib/Security/CredentialsManagerTest.php
index d9272627e5b..ce60a2f62a2 100644
--- a/tests/lib/Security/CredentialsManagerTest.php
+++ b/tests/lib/Security/CredentialsManagerTest.php
@@ -20,7 +20,7 @@ class CredentialsManagerTest extends \Test\TestCase {
/**
* @dataProvider credentialsProvider
*/
- public function testWithDB($userId, $identifier) {
+ public function testWithDB($userId, $identifier): void {
$credentialsManager = Server::get(ICredentialsManager::class);
$secrets = 'Open Sesame';
diff --git a/tests/lib/Security/CryptoTest.php b/tests/lib/Security/CryptoTest.php
index b65a9a36985..ef96f8d5ddb 100644
--- a/tests/lib/Security/CryptoTest.php
+++ b/tests/lib/Security/CryptoTest.php
@@ -32,13 +32,13 @@ class CryptoTest extends \Test\TestCase {
/**
* @dataProvider defaultEncryptionProvider
*/
- public function testDefaultEncrypt($stringToEncrypt) {
+ public function testDefaultEncrypt($stringToEncrypt): void {
$ciphertext = $this->crypto->encrypt($stringToEncrypt);
$this->assertEquals($stringToEncrypt, $this->crypto->decrypt($ciphertext));
}
- public function testWrongPassword() {
+ public function testWrongPassword(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('HMAC does not match.');
@@ -47,14 +47,14 @@ class CryptoTest extends \Test\TestCase {
$this->crypto->decrypt($ciphertext, 'A wrong password!');
}
- public function testLaterDecryption() {
+ public function testLaterDecryption(): void {
$stringToEncrypt = 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt.';
$encryptedString = '44a35023cca2e7a6125e06c29fc4b2ad9d8a33d0873a8b45b0de4ef9284f260c6c46bf25dc62120644c59b8bafe4281ddc47a70c35ae6c29ef7a63d79eefacc297e60b13042ac582733598d0a6b4de37311556bb5c480fd2633de4e6ebafa868c2d1e2d80a5d24f9660360dba4d6e0c8|lhrFgK0zd9U160Wo|a75e57ab701f9124e1113543fd1dc596f21e20d456a0d1e813d5a8aaec9adcb11213788e96598b67fe9486a9f0b99642c18296d0175db44b1ae426e4e91080ee';
$this->assertEquals($stringToEncrypt, $this->crypto->decrypt($encryptedString, 'ThisIsAVeryS3cur3P4ssw0rd'));
}
- public function testWrongIV() {
+ public function testWrongIV(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('HMAC does not match.');
@@ -63,7 +63,7 @@ class CryptoTest extends \Test\TestCase {
}
- public function testWrongParameters() {
+ public function testWrongParameters(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Authenticated ciphertext could not be decoded.');
@@ -71,14 +71,14 @@ class CryptoTest extends \Test\TestCase {
$this->crypto->decrypt($encryptedString, 'ThisIsAVeryS3cur3P4ssw0rd');
}
- public function testLegacy() {
+ public function testLegacy(): void {
$cipherText = 'e16599188e3d212f5c7f17fdc2abca46|M1WfLAxbcAmITeD6|509457885d6ca5e6c3bfd3741852687a7f2bffce197f8d5ae97b65818b15a1b7f616b68326ff312371540f4ca8ac55f8e2de4aa13aab3474bd3431e51214e3ee';
$password = 'mypass';
$this->assertSame('legacy test', $this->crypto->decrypt($cipherText, $password));
}
- public function testVersion2CiphertextDecryptsToCorrectPlaintext() {
+ public function testVersion2CiphertextDecryptsToCorrectPlaintext(): void {
$this->assertSame(
'This is a plaintext value that will be encrypted with version 2. Which addresses the reduced permutations on the IV.',
$this->crypto->decrypt(
@@ -88,7 +88,7 @@ class CryptoTest extends \Test\TestCase {
);
}
- public function testVersion3CiphertextDecryptsToCorrectPlaintext() {
+ public function testVersion3CiphertextDecryptsToCorrectPlaintext(): void {
$this->assertSame(
'Another plaintext value that will be encrypted with version 3. It addresses the related key issue. Old ciphertexts should be decrypted properly, but only use the better version for encryption.',
$this->crypto->decrypt(
diff --git a/tests/lib/Security/Events/GenerateSecurePasswordEventTest.php b/tests/lib/Security/Events/GenerateSecurePasswordEventTest.php
index 29002a90488..e589f20f62c 100644
--- a/tests/lib/Security/Events/GenerateSecurePasswordEventTest.php
+++ b/tests/lib/Security/Events/GenerateSecurePasswordEventTest.php
@@ -14,19 +14,19 @@ use OCP\Security\PasswordContext;
class GenerateSecurePasswordEventTest extends \Test\TestCase {
- public function testDefaultProperties() {
+ public function testDefaultProperties(): void {
$event = new GenerateSecurePasswordEvent();
$this->assertNull($event->getPassword());
$this->assertEquals(PasswordContext::ACCOUNT, $event->getContext());
}
- public function testSettingPassword() {
+ public function testSettingPassword(): void {
$event = new GenerateSecurePasswordEvent();
$event->setPassword('example');
$this->assertEquals('example', $event->getPassword());
}
- public function testSettingContext() {
+ public function testSettingContext(): void {
$event = new GenerateSecurePasswordEvent(PasswordContext::SHARING);
$this->assertEquals(PasswordContext::SHARING, $event->getContext());
}
diff --git a/tests/lib/Security/Events/ValidatePasswordPolicyEventTest.php b/tests/lib/Security/Events/ValidatePasswordPolicyEventTest.php
index 8a7bc3b2f29..272f34e31aa 100644
--- a/tests/lib/Security/Events/ValidatePasswordPolicyEventTest.php
+++ b/tests/lib/Security/Events/ValidatePasswordPolicyEventTest.php
@@ -14,14 +14,14 @@ use OCP\Security\PasswordContext;
class ValidatePasswordPolicyEventTest extends \Test\TestCase {
- public function testDefaultProperties() {
+ public function testDefaultProperties(): void {
$password = 'example';
$event = new ValidatePasswordPolicyEvent($password);
$this->assertEquals($password, $event->getPassword());
$this->assertEquals(PasswordContext::ACCOUNT, $event->getContext());
}
- public function testSettingContext() {
+ public function testSettingContext(): void {
$event = new ValidatePasswordPolicyEvent('example', PasswordContext::SHARING);
$this->assertEquals(PasswordContext::SHARING, $event->getContext());
}
diff --git a/tests/lib/Security/FeaturePolicy/AddFeaturePolicyEventTest.php b/tests/lib/Security/FeaturePolicy/AddFeaturePolicyEventTest.php
index 3c964972238..1fe01e26280 100644
--- a/tests/lib/Security/FeaturePolicy/AddFeaturePolicyEventTest.php
+++ b/tests/lib/Security/FeaturePolicy/AddFeaturePolicyEventTest.php
@@ -14,7 +14,7 @@ use OCP\Security\FeaturePolicy\AddFeaturePolicyEvent;
use Test\TestCase;
class AddFeaturePolicyEventTest extends TestCase {
- public function testAddEvent() {
+ public function testAddEvent(): void {
$manager = $this->createMock(FeaturePolicyManager::class);
$policy = $this->createMock(FeaturePolicy::class);
$event = new AddFeaturePolicyEvent($manager);
diff --git a/tests/lib/Security/FeaturePolicy/FeaturePolicyManagerTest.php b/tests/lib/Security/FeaturePolicy/FeaturePolicyManagerTest.php
index 7110effb261..7386aa023a9 100644
--- a/tests/lib/Security/FeaturePolicy/FeaturePolicyManagerTest.php
+++ b/tests/lib/Security/FeaturePolicy/FeaturePolicyManagerTest.php
@@ -27,12 +27,12 @@ class FeaturePolicyManagerTest extends TestCase {
$this->manager = new FeaturePolicyManager($this->dispatcher);
}
- public function testAddDefaultPolicy() {
+ public function testAddDefaultPolicy(): void {
$this->manager->addDefaultPolicy(new FeaturePolicy());
$this->addToAssertionCount(1);
}
- public function testGetDefaultPolicyWithPoliciesViaEvent() {
+ public function testGetDefaultPolicyWithPoliciesViaEvent(): void {
$this->dispatcher->addListener(AddFeaturePolicyEvent::class, function (AddFeaturePolicyEvent $e) {
$policy = new FeaturePolicy();
$policy->addAllowedMicrophoneDomain('mydomain.com');
diff --git a/tests/lib/Security/HasherTest.php b/tests/lib/Security/HasherTest.php
index f51b4ee39db..41cad7f323f 100644
--- a/tests/lib/Security/HasherTest.php
+++ b/tests/lib/Security/HasherTest.php
@@ -122,7 +122,7 @@ class HasherTest extends \Test\TestCase {
$this->hasher = new Hasher($this->config);
}
- public function testHash() {
+ public function testHash(): void {
$hash = $this->hasher->hash('String To Hash');
$this->assertNotNull($hash);
}
@@ -130,7 +130,7 @@ class HasherTest extends \Test\TestCase {
/**
* @dataProvider versionHashProvider
*/
- public function testSplitHash($hash, $expected) {
+ public function testSplitHash($hash, $expected): void {
$relativePath = self::invokePrivate($this->hasher, 'splitHash', [$hash]);
$this->assertSame($expected, $relativePath);
}
@@ -139,7 +139,7 @@ class HasherTest extends \Test\TestCase {
/**
* @dataProvider hashProviders70_71
*/
- public function testVerify($password, $hash, $expected) {
+ public function testVerify($password, $hash, $expected): void {
$this->config
->expects($this->any())
->method('getSystemValue')
@@ -157,7 +157,7 @@ class HasherTest extends \Test\TestCase {
/**
* @dataProvider hashProviders72
*/
- public function testVerifyArgon2i($password, $hash, $expected) {
+ public function testVerifyArgon2i($password, $hash, $expected): void {
if (!\defined('PASSWORD_ARGON2I')) {
$this->markTestSkipped('Need ARGON2 support to test ARGON2 hashes');
}
@@ -169,7 +169,7 @@ class HasherTest extends \Test\TestCase {
/**
* @dataProvider hashProviders73
*/
- public function testVerifyArgon2id(string $password, string $hash, bool $expected) {
+ public function testVerifyArgon2id(string $password, string $hash, bool $expected): void {
if (!\defined('PASSWORD_ARGON2ID')) {
$this->markTestSkipped('Need ARGON2ID support to test ARGON2ID hashes');
}
@@ -178,7 +178,7 @@ class HasherTest extends \Test\TestCase {
$this->assertSame($expected, $result);
}
- public function testUpgradeHashBlowFishToArgon2() {
+ public function testUpgradeHashBlowFishToArgon2(): void {
if (!\defined('PASSWORD_ARGON2I')) {
$this->markTestSkipped('Need ARGON2 support to test ARGON2 hashes');
}
@@ -203,7 +203,7 @@ class HasherTest extends \Test\TestCase {
$this->assertFalse(password_needs_rehash($relativePath['hash'], $newAlg, []));
}
- public function testUsePasswordDefaultArgon2iVerify() {
+ public function testUsePasswordDefaultArgon2iVerify(): void {
if (!\defined('PASSWORD_ARGON2I')) {
$this->markTestSkipped('Need ARGON2 support to test ARGON2 hashes');
}
@@ -227,7 +227,7 @@ class HasherTest extends \Test\TestCase {
$this->assertTrue(password_verify($message, $relativePath['hash']));
}
- public function testDoNotUsePasswordDefaultArgon2idVerify() {
+ public function testDoNotUsePasswordDefaultArgon2idVerify(): void {
if (!\defined('PASSWORD_ARGON2ID')) {
$this->markTestSkipped('Need ARGON2ID support to test ARGON2ID hashes');
}
@@ -245,7 +245,7 @@ class HasherTest extends \Test\TestCase {
$this->assertNull($newHash);
}
- public function testHashUsePasswordDefault() {
+ public function testHashUsePasswordDefault(): void {
if (!\defined('PASSWORD_ARGON2I')) {
$this->markTestSkipped('Need ARGON2 support to test ARGON2 hashes');
}
@@ -265,7 +265,7 @@ class HasherTest extends \Test\TestCase {
$this->assertEquals(PASSWORD_BCRYPT, $info['algo']);
}
- public function testValidHash() {
+ public function testValidHash(): void {
$hash = '3|$argon2id$v=19$m=65536,t=4,p=1$czFCSjk3LklVdXppZ2VCWA$li0NgdXe2/jwSRxgteGQPWlzJU0E0xdtfHbCbrpych0';
$isValid = $this->hasher->validate($hash);
@@ -273,7 +273,7 @@ class HasherTest extends \Test\TestCase {
$this->assertTrue($isValid);
}
- public function testValidGeneratedHash() {
+ public function testValidGeneratedHash(): void {
$message = 'secret';
$hash = $this->hasher->hash($message);
@@ -282,7 +282,7 @@ class HasherTest extends \Test\TestCase {
$this->assertTrue($isValid);
}
- public function testInvalidHash() {
+ public function testInvalidHash(): void {
$invalidHash = 'someInvalidHash';
$isValid = $this->hasher->validate($invalidHash);
diff --git a/tests/lib/Security/IdentityProof/KeyTest.php b/tests/lib/Security/IdentityProof/KeyTest.php
index 19dc02e2ad1..572bfbea619 100644
--- a/tests/lib/Security/IdentityProof/KeyTest.php
+++ b/tests/lib/Security/IdentityProof/KeyTest.php
@@ -22,11 +22,11 @@ class KeyTest extends TestCase {
$this->key = new Key('public', 'private');
}
- public function testGetPrivate() {
+ public function testGetPrivate(): void {
$this->assertSame('private', $this->key->getPrivate());
}
- public function testGetPublic() {
+ public function testGetPublic(): void {
$this->assertSame('public', $this->key->getPublic());
}
}
diff --git a/tests/lib/Security/IdentityProof/ManagerTest.php b/tests/lib/Security/IdentityProof/ManagerTest.php
index bb5b01d563c..722555efe01 100644
--- a/tests/lib/Security/IdentityProof/ManagerTest.php
+++ b/tests/lib/Security/IdentityProof/ManagerTest.php
@@ -79,7 +79,7 @@ class ManagerTest extends TestCase {
}
}
- public function testGetKeyWithExistingKey() {
+ public function testGetKeyWithExistingKey(): void {
$user = $this->createMock(IUser::class);
$user
->expects($this->once())
@@ -122,7 +122,7 @@ class ManagerTest extends TestCase {
$this->assertEquals($expected, $this->manager->getKey($user));
}
- public function testGetKeyWithNotExistingKey() {
+ public function testGetKeyWithNotExistingKey(): void {
$user = $this->createMock(IUser::class);
$user
->expects($this->once())
@@ -177,7 +177,7 @@ class ManagerTest extends TestCase {
$this->assertEquals($expected, $this->manager->getKey($user));
}
- public function testGenerateKeyPair() {
+ public function testGenerateKeyPair(): void {
$manager = $this->getManager();
$data = 'MyTestData';
@@ -189,7 +189,7 @@ class ManagerTest extends TestCase {
$this->assertSame(2048, $details['bits']);
}
- public function testGetSystemKey() {
+ public function testGetSystemKey(): void {
$manager = $this->getManager(['retrieveKey']);
/** @var Key|\PHPUnit\Framework\MockObject\MockObject $key */
@@ -206,7 +206,7 @@ class ManagerTest extends TestCase {
- public function testGetSystemKeyFailure() {
+ public function testGetSystemKeyFailure(): void {
$this->expectException(\RuntimeException::class);
$manager = $this->getManager(['retrieveKey']);
diff --git a/tests/lib/Security/IdentityProof/SignerTest.php b/tests/lib/Security/IdentityProof/SignerTest.php
index 8b8d93e6b9a..6dc73c072e4 100644
--- a/tests/lib/Security/IdentityProof/SignerTest.php
+++ b/tests/lib/Security/IdentityProof/SignerTest.php
@@ -90,7 +90,7 @@ gQIDAQAB
);
}
- public function testSign() {
+ public function testSign(): void {
$user = $this->createMock(IUser::class);
$user->method('getCloudId')
->willReturn('foo@example.com');
@@ -123,7 +123,7 @@ gQIDAQAB
$this->assertEquals($expects, $result);
}
- public function testVerifyValid() {
+ public function testVerifyValid(): void {
$data = [
'message' => [
'data' => [
@@ -151,7 +151,7 @@ gQIDAQAB
$this->assertTrue($this->signer->verify($data));
}
- public function testVerifyInvalid() {
+ public function testVerifyInvalid(): void {
$data = [
'message' => [
'data' => [
@@ -179,7 +179,7 @@ gQIDAQAB
$this->assertFalse($this->signer->verify($data));
}
- public function testVerifyInvalidData() {
+ public function testVerifyInvalidData(): void {
$data = [
];
diff --git a/tests/lib/Security/Normalizer/IpAddressTest.php b/tests/lib/Security/Normalizer/IpAddressTest.php
index ae6b5cbc9ca..55cb149309a 100644
--- a/tests/lib/Security/Normalizer/IpAddressTest.php
+++ b/tests/lib/Security/Normalizer/IpAddressTest.php
@@ -60,11 +60,11 @@ class IpAddressTest extends TestCase {
* @param string $input
* @param string $expected
*/
- public function testGetSubnet($input, $expected) {
+ public function testGetSubnet($input, $expected): void {
$this->assertSame($expected, (new IpAddress($input))->getSubnet());
}
- public function testToString() {
+ public function testToString(): void {
$this->assertSame('127.0.0.1', (string)(new IpAddress('127.0.0.1')));
}
}
diff --git a/tests/lib/Security/RateLimiting/Backend/MemoryCacheBackendTest.php b/tests/lib/Security/RateLimiting/Backend/MemoryCacheBackendTest.php
index 62325461ef1..ddbcecd72f9 100644
--- a/tests/lib/Security/RateLimiting/Backend/MemoryCacheBackendTest.php
+++ b/tests/lib/Security/RateLimiting/Backend/MemoryCacheBackendTest.php
@@ -53,7 +53,7 @@ class MemoryCacheBackendTest extends TestCase {
);
}
- public function testGetAttemptsWithNoAttemptsBefore() {
+ public function testGetAttemptsWithNoAttemptsBefore(): void {
$this->cache
->expects($this->once())
->method('get')
@@ -63,7 +63,7 @@ class MemoryCacheBackendTest extends TestCase {
$this->assertSame(0, $this->memoryCache->getAttempts('Method', 'User'));
}
- public function testGetAttempts() {
+ public function testGetAttempts(): void {
$this->timeFactory
->expects($this->once())
->method('getTime')
@@ -84,7 +84,7 @@ class MemoryCacheBackendTest extends TestCase {
$this->assertSame(3, $this->memoryCache->getAttempts('Method', 'User'));
}
- public function testRegisterAttemptWithNoAttemptsBefore() {
+ public function testRegisterAttemptWithNoAttemptsBefore(): void {
$this->timeFactory
->expects($this->once())
->method('getTime')
@@ -106,7 +106,7 @@ class MemoryCacheBackendTest extends TestCase {
$this->memoryCache->registerAttempt('Method', 'User', 100);
}
- public function testRegisterAttempt() {
+ public function testRegisterAttempt(): void {
$this->timeFactory
->expects($this->once())
->method('getTime')
diff --git a/tests/lib/Security/RateLimiting/LimiterTest.php b/tests/lib/Security/RateLimiting/LimiterTest.php
index 332f26b81d0..92600e22de8 100644
--- a/tests/lib/Security/RateLimiting/LimiterTest.php
+++ b/tests/lib/Security/RateLimiting/LimiterTest.php
@@ -31,7 +31,7 @@ class LimiterTest extends TestCase {
}
- public function testRegisterAnonRequestExceeded() {
+ public function testRegisterAnonRequestExceeded(): void {
$this->expectException(\OC\Security\RateLimiting\Exception\RateLimitExceededException::class);
$this->expectExceptionMessage('Rate limit exceeded');
@@ -47,7 +47,7 @@ class LimiterTest extends TestCase {
$this->limiter->registerAnonRequest('MyIdentifier', 100, 100, '127.0.0.1');
}
- public function testRegisterAnonRequestSuccess() {
+ public function testRegisterAnonRequestSuccess(): void {
$this->backend
->expects($this->once())
->method('getAttempts')
@@ -69,7 +69,7 @@ class LimiterTest extends TestCase {
}
- public function testRegisterUserRequestExceeded() {
+ public function testRegisterUserRequestExceeded(): void {
$this->expectException(\OC\Security\RateLimiting\Exception\RateLimitExceededException::class);
$this->expectExceptionMessage('Rate limit exceeded');
@@ -91,7 +91,7 @@ class LimiterTest extends TestCase {
$this->limiter->registerUserRequest('MyIdentifier', 100, 100, $user);
}
- public function testRegisterUserRequestSuccess() {
+ public function testRegisterUserRequestSuccess(): void {
/** @var IUser|\PHPUnit\Framework\MockObject\MockObject $user */
$user = $this->createMock(IUser::class);
$user
diff --git a/tests/lib/Security/SecureRandomTest.php b/tests/lib/Security/SecureRandomTest.php
index 6e5f3587630..08d33d4a1b3 100644
--- a/tests/lib/Security/SecureRandomTest.php
+++ b/tests/lib/Security/SecureRandomTest.php
@@ -43,7 +43,7 @@ class SecureRandomTest extends \Test\TestCase {
/**
* @dataProvider stringGenerationProvider
*/
- public function testGetLowStrengthGeneratorLength($length, $expectedLength) {
+ public function testGetLowStrengthGeneratorLength($length, $expectedLength): void {
$generator = $this->rng;
$this->assertEquals($expectedLength, strlen($generator->generate($length)));
@@ -52,7 +52,7 @@ class SecureRandomTest extends \Test\TestCase {
/**
* @dataProvider stringGenerationProvider
*/
- public function testMediumLowStrengthGeneratorLength($length, $expectedLength) {
+ public function testMediumLowStrengthGeneratorLength($length, $expectedLength): void {
$generator = $this->rng;
$this->assertEquals($expectedLength, strlen($generator->generate($length)));
@@ -61,14 +61,14 @@ class SecureRandomTest extends \Test\TestCase {
/**
* @dataProvider stringGenerationProvider
*/
- public function testUninitializedGenerate($length, $expectedLength) {
+ public function testUninitializedGenerate($length, $expectedLength): void {
$this->assertEquals($expectedLength, strlen($this->rng->generate($length)));
}
/**
* @dataProvider charCombinations
*/
- public function testScheme($charName, $chars) {
+ public function testScheme($charName, $chars): void {
$generator = $this->rng;
$scheme = constant('OCP\Security\ISecureRandom::' . $charName);
$randomString = $generator->generate(100, $scheme);
@@ -86,7 +86,7 @@ class SecureRandomTest extends \Test\TestCase {
/**
* @dataProvider invalidLengths
*/
- public function testInvalidLengths($length) {
+ public function testInvalidLengths($length): void {
$this->expectException(\LengthException::class);
$generator = $this->rng;
$generator->generate($length);
diff --git a/tests/lib/Security/TrustedDomainHelperTest.php b/tests/lib/Security/TrustedDomainHelperTest.php
index 3dbaf376b52..656b7a77206 100644
--- a/tests/lib/Security/TrustedDomainHelperTest.php
+++ b/tests/lib/Security/TrustedDomainHelperTest.php
@@ -32,7 +32,7 @@ class TrustedDomainHelperTest extends \Test\TestCase {
* @param string $testDomain
* @param bool $result
*/
- public function testIsTrustedUrl($trustedDomains, $testDomain, $result) {
+ public function testIsTrustedUrl($trustedDomains, $testDomain, $result): void {
$this->config->method('getSystemValue')
->willReturnMap([
['overwritehost', '', ''],
@@ -49,7 +49,7 @@ class TrustedDomainHelperTest extends \Test\TestCase {
* @param string $testDomain
* @param bool $result
*/
- public function testIsTrustedDomain($trustedDomains, $testDomain, $result) {
+ public function testIsTrustedDomain($trustedDomains, $testDomain, $result): void {
$this->config->method('getSystemValue')
->willReturnMap([
['overwritehost', '', ''],
@@ -134,7 +134,7 @@ class TrustedDomainHelperTest extends \Test\TestCase {
];
}
- public function testIsTrustedDomainOverwriteHost() {
+ public function testIsTrustedDomainOverwriteHost(): void {
$this->config->method('getSystemValue')
->with('overwritehost')
->willReturn('myproxyhost');
diff --git a/tests/lib/Security/VerificationToken/VerificationTokenTest.php b/tests/lib/Security/VerificationToken/VerificationTokenTest.php
index f8573478fa5..7123cc8b013 100644
--- a/tests/lib/Security/VerificationToken/VerificationTokenTest.php
+++ b/tests/lib/Security/VerificationToken/VerificationTokenTest.php
@@ -52,13 +52,13 @@ class VerificationTokenTest extends TestCase {
);
}
- public function testTokenUserUnknown() {
+ public function testTokenUserUnknown(): void {
$this->expectException(InvalidTokenException::class);
$this->expectExceptionCode(InvalidTokenException::USER_UNKNOWN);
$this->token->check('encryptedToken', null, 'fingerprintToken', 'foobar');
}
- public function testTokenUserUnknown2() {
+ public function testTokenUserUnknown2(): void {
$user = $this->createMock(IUser::class);
$user->expects($this->atLeastOnce())
->method('isEnabled')
@@ -69,7 +69,7 @@ class VerificationTokenTest extends TestCase {
$this->token->check('encryptedToken', $user, 'fingerprintToken', 'foobar');
}
- public function testTokenNotFound() {
+ public function testTokenNotFound(): void {
$user = $this->createMock(IUser::class);
$user->expects($this->atLeastOnce())
->method('isEnabled')
@@ -85,7 +85,7 @@ class VerificationTokenTest extends TestCase {
$this->token->check('encryptedToken', $user, 'fingerprintToken', 'foobar');
}
- public function testTokenDecryptionError() {
+ public function testTokenDecryptionError(): void {
$user = $this->createMock(IUser::class);
$user->expects($this->atLeastOnce())
->method('isEnabled')
@@ -112,7 +112,7 @@ class VerificationTokenTest extends TestCase {
$this->token->check('encryptedToken', $user, 'fingerprintToken', 'foobar');
}
- public function testTokenInvalidFormat() {
+ public function testTokenInvalidFormat(): void {
$user = $this->createMock(IUser::class);
$user->expects($this->atLeastOnce())
->method('isEnabled')
@@ -139,7 +139,7 @@ class VerificationTokenTest extends TestCase {
$this->token->check('encryptedToken', $user, 'fingerprintToken', 'foobar');
}
- public function testTokenExpired() {
+ public function testTokenExpired(): void {
$user = $this->createMock(IUser::class);
$user->expects($this->atLeastOnce())
->method('isEnabled')
@@ -173,7 +173,7 @@ class VerificationTokenTest extends TestCase {
$this->token->check('encryptedToken', $user, 'fingerprintToken', 'foobar');
}
- public function testTokenExpiredByLogin() {
+ public function testTokenExpiredByLogin(): void {
$user = $this->createMock(IUser::class);
$user->expects($this->atLeastOnce())
->method('isEnabled')
@@ -207,7 +207,7 @@ class VerificationTokenTest extends TestCase {
$this->token->check('encryptedToken', $user, 'fingerprintToken', 'foobar', true);
}
- public function testTokenMismatch() {
+ public function testTokenMismatch(): void {
$user = $this->createMock(IUser::class);
$user->expects($this->atLeastOnce())
->method('isEnabled')
@@ -241,7 +241,7 @@ class VerificationTokenTest extends TestCase {
$this->token->check('encryptedToken', $user, 'fingerprintToken', 'foobar');
}
- public function testTokenSuccess() {
+ public function testTokenSuccess(): void {
$user = $this->createMock(IUser::class);
$user->expects($this->atLeastOnce())
->method('isEnabled')
@@ -273,7 +273,7 @@ class VerificationTokenTest extends TestCase {
$this->token->check('barfoo', $user, 'fingerprintToken', 'foobar');
}
- public function testCreate() {
+ public function testCreate(): void {
$user = $this->createMock(IUser::class);
$user->expects($this->any())
->method('getUID')
diff --git a/tests/lib/ServerTest.php b/tests/lib/ServerTest.php
index 3ccda8fce7c..881531af246 100644
--- a/tests/lib/ServerTest.php
+++ b/tests/lib/ServerTest.php
@@ -1,175 +1,175 @@
-<?php
-/**
- * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
- * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
- * SPDX-License-Identifier: AGPL-3.0-only
- */
-
-namespace Test;
-
-use OC\App\AppStore\Fetcher\AppFetcher;
-use OC\App\AppStore\Fetcher\CategoryFetcher;
-use OCP\Comments\ICommentsManager;
-
-/**
- * Class Server
- *
- * @group DB
- *
- * @package Test
- */
-class ServerTest extends \Test\TestCase {
- /** @var \OC\Server */
- protected $server;
-
-
- protected function setUp(): void {
- parent::setUp();
- $config = new \OC\Config(\OC::$configDir);
- $this->server = new \OC\Server('', $config);
- }
-
- public function dataTestQuery() {
- return [
- ['ActivityManager', \OC\Activity\Manager::class],
- ['ActivityManager', \OCP\Activity\IManager::class],
- ['AllConfig', \OC\AllConfig::class],
- ['AllConfig', \OCP\IConfig::class],
- ['AppConfig', \OC\AppConfig::class],
- ['AppConfig', \OCP\IAppConfig::class],
- ['AppFetcher', AppFetcher::class],
- ['AppManager', \OC\App\AppManager::class],
- ['AppManager', \OCP\App\IAppManager::class],
- ['AsyncCommandBus', \OC\Command\AsyncBus::class],
- ['AsyncCommandBus', \OCP\Command\IBus::class],
- ['AvatarManager', \OC\Avatar\AvatarManager::class],
- ['AvatarManager', \OCP\IAvatarManager::class],
-
- ['CategoryFetcher', CategoryFetcher::class],
- ['CapabilitiesManager', \OC\CapabilitiesManager::class],
- ['ContactsManager', \OC\ContactsManager::class],
- ['ContactsManager', \OCP\Contacts\IManager::class],
- ['ContentSecurityPolicyManager', \OC\Security\CSP\ContentSecurityPolicyManager::class],
- ['CommentsManager', \OCP\Comments\ICommentsManager::class],
- ['Crypto', \OC\Security\Crypto::class],
- ['Crypto', \OCP\Security\ICrypto::class],
- ['CryptoWrapper', \OC\Session\CryptoWrapper::class],
- ['CsrfTokenManager', \OC\Security\CSRF\CsrfTokenManager::class],
-
- ['DatabaseConnection', \OC\DB\ConnectionAdapter::class],
- ['DatabaseConnection', \OCP\IDBConnection::class],
- ['DateTimeFormatter', \OC\DateTimeFormatter::class],
- ['DateTimeFormatter', \OCP\IDateTimeFormatter::class],
- ['DateTimeZone', \OC\DateTimeZone::class],
- ['DateTimeZone', \OCP\IDateTimeZone::class],
-
- ['EncryptionFileHelper', \OC\Encryption\File::class],
- ['EncryptionFileHelper', \OCP\Encryption\IFile::class],
- ['EncryptionKeyStorage', \OC\Encryption\Keys\Storage::class],
- ['EncryptionKeyStorage', \OCP\Encryption\Keys\IStorage::class],
- ['EncryptionManager', \OC\Encryption\Manager::class],
- ['EncryptionManager', \OCP\Encryption\IManager::class],
- ['EventLogger', \OCP\Diagnostics\IEventLogger::class],
-
- ['GroupManager', \OC\Group\Manager::class],
- ['GroupManager', \OCP\IGroupManager::class],
-
- ['Hasher', \OC\Security\Hasher::class],
- ['Hasher', \OCP\Security\IHasher::class],
- ['HttpClientService', \OC\Http\Client\ClientService::class],
- ['HttpClientService', \OCP\Http\Client\IClientService::class],
-
- ['IniWrapper', '\bantu\IniGetWrapper\IniGetWrapper'],
- ['MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class],
- ['MimeTypeDetector', \OC\Files\Type\Detection::class],
-
- ['JobList', \OC\BackgroundJob\JobList::class],
- ['JobList', \OCP\BackgroundJob\IJobList::class],
-
- ['L10NFactory', \OC\L10N\Factory::class],
- ['L10NFactory', \OCP\L10N\IFactory::class],
- ['LockingProvider', \OCP\Lock\ILockingProvider::class],
- ['Logger', \OC\Log::class],
- ['Logger', \OCP\ILogger::class],
-
- ['Mailer', \OC\Mail\Mailer::class],
- ['Mailer', \OCP\Mail\IMailer::class],
- ['MemCacheFactory', \OC\Memcache\Factory::class],
- ['MemCacheFactory', \OCP\ICacheFactory::class],
- ['MountConfigManager', \OC\Files\Config\MountProviderCollection::class],
- ['MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class],
-
- ['NavigationManager', \OC\NavigationManager::class],
- ['NavigationManager', \OCP\INavigationManager::class],
- ['NotificationManager', \OC\Notification\Manager::class],
- ['NotificationManager', \OCP\Notification\IManager::class],
- ['UserCache', \OC\Cache\File::class],
- ['UserCache', \OCP\ICache::class],
-
- ['PreviewManager', \OC\PreviewManager::class],
- ['PreviewManager', \OCP\IPreview::class],
-
- ['QueryLogger', \OCP\Diagnostics\IQueryLogger::class],
-
- ['Request', \OC\AppFramework\Http\Request::class],
- ['Request', \OCP\IRequest::class],
- ['RootFolder', \OC\Files\Node\Root::class],
- ['RootFolder', \OC\Files\Node\Folder::class],
- ['RootFolder', \OCP\Files\IRootFolder::class],
- ['RootFolder', \OCP\Files\Folder::class],
- ['Router', \OCP\Route\IRouter::class],
-
- ['SecureRandom', \OC\Security\SecureRandom::class],
- ['SecureRandom', \OCP\Security\ISecureRandom::class],
- ['ShareManager', \OC\Share20\Manager::class],
- ['ShareManager', \OCP\Share\IManager::class],
- ['SystemConfig', \OC\SystemConfig::class],
-
- ['URLGenerator', \OC\URLGenerator::class],
- ['URLGenerator', \OCP\IURLGenerator::class],
- ['UserManager', \OC\User\Manager::class],
- ['UserManager', \OCP\IUserManager::class],
- ['UserSession', \OC\User\Session::class],
- ['UserSession', \OCP\IUserSession::class],
-
- ['TagMapper', \OC\Tagging\TagMapper::class],
- ['TagMapper', \OCP\AppFramework\Db\QBMapper::class],
- ['TagManager', \OC\TagManager::class],
- ['TagManager', \OCP\ITagManager::class],
- ['TempManager', \OC\TempManager::class],
- ['TempManager', \OCP\ITempManager::class],
- ['ThemingDefaults', \OCA\Theming\ThemingDefaults::class],
- ['TrustedDomainHelper', \OC\Security\TrustedDomainHelper::class],
-
- ['SystemTagManager', \OCP\SystemTag\ISystemTagManager::class],
- ['SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class],
- ];
- }
-
- /**
- * @dataProvider dataTestQuery
- *
- * @param string $serviceName
- * @param string $instanceOf
- */
- public function testQuery($serviceName, $instanceOf) {
- $this->assertInstanceOf($instanceOf, $this->server->query($serviceName), 'Service "' . $serviceName . '"" did not return the right class');
- }
-
- public function testGetCertificateManager() {
- $this->assertInstanceOf(\OC\Security\CertificateManager::class, $this->server->getCertificateManager(), 'service returned by "getCertificateManager" did not return the right class');
- $this->assertInstanceOf(\OCP\ICertificateManager::class, $this->server->getCertificateManager(), 'service returned by "getCertificateManager" did not return the right class');
- }
-
- public function testOverwriteDefaultCommentsManager() {
- $config = $this->server->getConfig();
- $defaultManagerFactory = $config->getSystemValue('comments.managerFactory', \OC\Comments\ManagerFactory::class);
-
- $config->setSystemValue('comments.managerFactory', \Test\Comments\FakeFactory::class);
-
- $manager = $this->server->get(ICommentsManager::class);
- $this->assertInstanceOf(\OCP\Comments\ICommentsManager::class, $manager);
-
- $config->setSystemValue('comments.managerFactory', $defaultManagerFactory);
- }
-}
+<?php
+/**
+ * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
+ */
+
+namespace Test;
+
+use OC\App\AppStore\Fetcher\AppFetcher;
+use OC\App\AppStore\Fetcher\CategoryFetcher;
+use OCP\Comments\ICommentsManager;
+
+/**
+ * Class Server
+ *
+ * @group DB
+ *
+ * @package Test
+ */
+class ServerTest extends \Test\TestCase {
+ /** @var \OC\Server */
+ protected $server;
+
+
+ protected function setUp(): void {
+ parent::setUp();
+ $config = new \OC\Config(\OC::$configDir);
+ $this->server = new \OC\Server('', $config);
+ }
+
+ public function dataTestQuery() {
+ return [
+ ['ActivityManager', \OC\Activity\Manager::class],
+ ['ActivityManager', \OCP\Activity\IManager::class],
+ ['AllConfig', \OC\AllConfig::class],
+ ['AllConfig', \OCP\IConfig::class],
+ ['AppConfig', \OC\AppConfig::class],
+ ['AppConfig', \OCP\IAppConfig::class],
+ ['AppFetcher', AppFetcher::class],
+ ['AppManager', \OC\App\AppManager::class],
+ ['AppManager', \OCP\App\IAppManager::class],
+ ['AsyncCommandBus', \OC\Command\AsyncBus::class],
+ ['AsyncCommandBus', \OCP\Command\IBus::class],
+ ['AvatarManager', \OC\Avatar\AvatarManager::class],
+ ['AvatarManager', \OCP\IAvatarManager::class],
+
+ ['CategoryFetcher', CategoryFetcher::class],
+ ['CapabilitiesManager', \OC\CapabilitiesManager::class],
+ ['ContactsManager', \OC\ContactsManager::class],
+ ['ContactsManager', \OCP\Contacts\IManager::class],
+ ['ContentSecurityPolicyManager', \OC\Security\CSP\ContentSecurityPolicyManager::class],
+ ['CommentsManager', \OCP\Comments\ICommentsManager::class],
+ ['Crypto', \OC\Security\Crypto::class],
+ ['Crypto', \OCP\Security\ICrypto::class],
+ ['CryptoWrapper', \OC\Session\CryptoWrapper::class],
+ ['CsrfTokenManager', \OC\Security\CSRF\CsrfTokenManager::class],
+
+ ['DatabaseConnection', \OC\DB\ConnectionAdapter::class],
+ ['DatabaseConnection', \OCP\IDBConnection::class],
+ ['DateTimeFormatter', \OC\DateTimeFormatter::class],
+ ['DateTimeFormatter', \OCP\IDateTimeFormatter::class],
+ ['DateTimeZone', \OC\DateTimeZone::class],
+ ['DateTimeZone', \OCP\IDateTimeZone::class],
+
+ ['EncryptionFileHelper', \OC\Encryption\File::class],
+ ['EncryptionFileHelper', \OCP\Encryption\IFile::class],
+ ['EncryptionKeyStorage', \OC\Encryption\Keys\Storage::class],
+ ['EncryptionKeyStorage', \OCP\Encryption\Keys\IStorage::class],
+ ['EncryptionManager', \OC\Encryption\Manager::class],
+ ['EncryptionManager', \OCP\Encryption\IManager::class],
+ ['EventLogger', \OCP\Diagnostics\IEventLogger::class],
+
+ ['GroupManager', \OC\Group\Manager::class],
+ ['GroupManager', \OCP\IGroupManager::class],
+
+ ['Hasher', \OC\Security\Hasher::class],
+ ['Hasher', \OCP\Security\IHasher::class],
+ ['HttpClientService', \OC\Http\Client\ClientService::class],
+ ['HttpClientService', \OCP\Http\Client\IClientService::class],
+
+ ['IniWrapper', '\bantu\IniGetWrapper\IniGetWrapper'],
+ ['MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class],
+ ['MimeTypeDetector', \OC\Files\Type\Detection::class],
+
+ ['JobList', \OC\BackgroundJob\JobList::class],
+ ['JobList', \OCP\BackgroundJob\IJobList::class],
+
+ ['L10NFactory', \OC\L10N\Factory::class],
+ ['L10NFactory', \OCP\L10N\IFactory::class],
+ ['LockingProvider', \OCP\Lock\ILockingProvider::class],
+ ['Logger', \OC\Log::class],
+ ['Logger', \OCP\ILogger::class],
+
+ ['Mailer', \OC\Mail\Mailer::class],
+ ['Mailer', \OCP\Mail\IMailer::class],
+ ['MemCacheFactory', \OC\Memcache\Factory::class],
+ ['MemCacheFactory', \OCP\ICacheFactory::class],
+ ['MountConfigManager', \OC\Files\Config\MountProviderCollection::class],
+ ['MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class],
+
+ ['NavigationManager', \OC\NavigationManager::class],
+ ['NavigationManager', \OCP\INavigationManager::class],
+ ['NotificationManager', \OC\Notification\Manager::class],
+ ['NotificationManager', \OCP\Notification\IManager::class],
+ ['UserCache', \OC\Cache\File::class],
+ ['UserCache', \OCP\ICache::class],
+
+ ['PreviewManager', \OC\PreviewManager::class],
+ ['PreviewManager', \OCP\IPreview::class],
+
+ ['QueryLogger', \OCP\Diagnostics\IQueryLogger::class],
+
+ ['Request', \OC\AppFramework\Http\Request::class],
+ ['Request', \OCP\IRequest::class],
+ ['RootFolder', \OC\Files\Node\Root::class],
+ ['RootFolder', \OC\Files\Node\Folder::class],
+ ['RootFolder', \OCP\Files\IRootFolder::class],
+ ['RootFolder', \OCP\Files\Folder::class],
+ ['Router', \OCP\Route\IRouter::class],
+
+ ['SecureRandom', \OC\Security\SecureRandom::class],
+ ['SecureRandom', \OCP\Security\ISecureRandom::class],
+ ['ShareManager', \OC\Share20\Manager::class],
+ ['ShareManager', \OCP\Share\IManager::class],
+ ['SystemConfig', \OC\SystemConfig::class],
+
+ ['URLGenerator', \OC\URLGenerator::class],
+ ['URLGenerator', \OCP\IURLGenerator::class],
+ ['UserManager', \OC\User\Manager::class],
+ ['UserManager', \OCP\IUserManager::class],
+ ['UserSession', \OC\User\Session::class],
+ ['UserSession', \OCP\IUserSession::class],
+
+ ['TagMapper', \OC\Tagging\TagMapper::class],
+ ['TagMapper', \OCP\AppFramework\Db\QBMapper::class],
+ ['TagManager', \OC\TagManager::class],
+ ['TagManager', \OCP\ITagManager::class],
+ ['TempManager', \OC\TempManager::class],
+ ['TempManager', \OCP\ITempManager::class],
+ ['ThemingDefaults', \OCA\Theming\ThemingDefaults::class],
+ ['TrustedDomainHelper', \OC\Security\TrustedDomainHelper::class],
+
+ ['SystemTagManager', \OCP\SystemTag\ISystemTagManager::class],
+ ['SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class],
+ ];
+ }
+
+ /**
+ * @dataProvider dataTestQuery
+ *
+ * @param string $serviceName
+ * @param string $instanceOf
+ */
+ public function testQuery($serviceName, $instanceOf): void {
+ $this->assertInstanceOf($instanceOf, $this->server->query($serviceName), 'Service "' . $serviceName . '"" did not return the right class');
+ }
+
+ public function testGetCertificateManager(): void {
+ $this->assertInstanceOf(\OC\Security\CertificateManager::class, $this->server->getCertificateManager(), 'service returned by "getCertificateManager" did not return the right class');
+ $this->assertInstanceOf(\OCP\ICertificateManager::class, $this->server->getCertificateManager(), 'service returned by "getCertificateManager" did not return the right class');
+ }
+
+ public function testOverwriteDefaultCommentsManager(): void {
+ $config = $this->server->getConfig();
+ $defaultManagerFactory = $config->getSystemValue('comments.managerFactory', \OC\Comments\ManagerFactory::class);
+
+ $config->setSystemValue('comments.managerFactory', \Test\Comments\FakeFactory::class);
+
+ $manager = $this->server->get(ICommentsManager::class);
+ $this->assertInstanceOf(\OCP\Comments\ICommentsManager::class, $manager);
+
+ $config->setSystemValue('comments.managerFactory', $defaultManagerFactory);
+ }
+}
diff --git a/tests/lib/Session/CryptoWrappingTest.php b/tests/lib/Session/CryptoWrappingTest.php
index da29f7470e6..f8c5ba44a9a 100644
--- a/tests/lib/Session/CryptoWrappingTest.php
+++ b/tests/lib/Session/CryptoWrappingTest.php
@@ -47,7 +47,7 @@ class CryptoWrappingTest extends TestCase {
$this->instance = new CryptoSessionData($this->wrappedSession, $this->crypto, 'PASS');
}
- public function testUnwrappingGet() {
+ public function testUnwrappingGet(): void {
$unencryptedValue = 'foobar';
$encryptedValue = $this->crypto->encrypt($unencryptedValue);
diff --git a/tests/lib/Session/MemoryTest.php b/tests/lib/Session/MemoryTest.php
index f5d9685039d..24bfc06b274 100644
--- a/tests/lib/Session/MemoryTest.php
+++ b/tests/lib/Session/MemoryTest.php
@@ -15,7 +15,7 @@ class MemoryTest extends Session {
}
- public function testThrowsExceptionOnGetId() {
+ public function testThrowsExceptionOnGetId(): void {
$this->expectException(\OCP\Session\Exceptions\SessionNotAvailableException::class);
$this->instance->getId();
diff --git a/tests/lib/Session/Session.php b/tests/lib/Session/Session.php
index 63fa4554477..1e2e9370825 100644
--- a/tests/lib/Session/Session.php
+++ b/tests/lib/Session/Session.php
@@ -19,43 +19,43 @@ abstract class Session extends \Test\TestCase {
parent::tearDown();
}
- public function testNotExistsEmpty() {
+ public function testNotExistsEmpty(): void {
$this->assertFalse($this->instance->exists('foo'));
}
- public function testExistsAfterSet() {
+ public function testExistsAfterSet(): void {
$this->instance->set('foo', 1);
$this->assertTrue($this->instance->exists('foo'));
}
- public function testNotExistsAfterRemove() {
+ public function testNotExistsAfterRemove(): void {
$this->instance->set('foo', 1);
$this->instance->remove('foo');
$this->assertFalse($this->instance->exists('foo'));
}
- public function testGetNonExisting() {
+ public function testGetNonExisting(): void {
$this->assertNull($this->instance->get('foo'));
}
- public function testGetAfterSet() {
+ public function testGetAfterSet(): void {
$this->instance->set('foo', 'bar');
$this->assertEquals('bar', $this->instance->get(('foo')));
}
- public function testRemoveNonExisting() {
+ public function testRemoveNonExisting(): void {
$this->assertFalse($this->instance->exists('foo'));
$this->instance->remove('foo');
$this->assertFalse($this->instance->exists('foo'));
}
- public function testNotExistsAfterClear() {
+ public function testNotExistsAfterClear(): void {
$this->instance->set('foo', 1);
$this->instance->clear();
$this->assertFalse($this->instance->exists('foo'));
}
- public function testArrayInterface() {
+ public function testArrayInterface(): void {
$this->assertFalse(isset($this->instance['foo']));
$this->instance['foo'] = 'bar';
$this->assertTrue(isset($this->instance['foo']));
diff --git a/tests/lib/Settings/ManagerTest.php b/tests/lib/Settings/ManagerTest.php
index 6ed8ed74359..90c195e6bd0 100644
--- a/tests/lib/Settings/ManagerTest.php
+++ b/tests/lib/Settings/ManagerTest.php
@@ -64,7 +64,7 @@ class ManagerTest extends TestCase {
);
}
- public function testGetAdminSections() {
+ public function testGetAdminSections(): void {
$this->manager->registerSection('admin', \OCA\WorkflowEngine\Settings\Section::class);
$section = \OC::$server->query(\OCA\WorkflowEngine\Settings\Section::class);
@@ -77,7 +77,7 @@ class ManagerTest extends TestCase {
], $this->manager->getAdminSections());
}
- public function testGetPersonalSections() {
+ public function testGetPersonalSections(): void {
$this->manager->registerSection('personal', \OCA\WorkflowEngine\Settings\Section::class);
$section = \OC::$server->query(\OCA\WorkflowEngine\Settings\Section::class);
@@ -90,11 +90,11 @@ class ManagerTest extends TestCase {
], $this->manager->getPersonalSections());
}
- public function testGetAdminSectionsEmptySection() {
+ public function testGetAdminSectionsEmptySection(): void {
$this->assertEquals([], $this->manager->getAdminSections());
}
- public function testGetPersonalSectionsEmptySection() {
+ public function testGetPersonalSectionsEmptySection(): void {
$this->l10nFactory
->expects($this->once())
->method('get')
@@ -108,7 +108,7 @@ class ManagerTest extends TestCase {
$this->assertEquals([], $this->manager->getPersonalSections());
}
- public function testGetAdminSettings() {
+ public function testGetAdminSettings(): void {
$section = $this->createMock(ISettings::class);
$section->method('getPriority')
->willReturn(13);
@@ -126,7 +126,7 @@ class ManagerTest extends TestCase {
], $settings);
}
- public function testGetAdminSettingsAsSubAdmin() {
+ public function testGetAdminSettingsAsSubAdmin(): void {
$section = $this->createMock(ISettings::class);
$section->method('getPriority')
->willReturn(13);
@@ -142,7 +142,7 @@ class ManagerTest extends TestCase {
$this->assertEquals([], $settings);
}
- public function testGetSubAdminSettingsAsSubAdmin() {
+ public function testGetSubAdminSettingsAsSubAdmin(): void {
$section = $this->createMock(ISubAdminSettings::class);
$section->method('getPriority')
->willReturn(13);
@@ -161,7 +161,7 @@ class ManagerTest extends TestCase {
], $settings);
}
- public function testGetPersonalSettings() {
+ public function testGetPersonalSettings(): void {
$section = $this->createMock(ISettings::class);
$section->method('getPriority')
->willReturn(16);
@@ -195,7 +195,7 @@ class ManagerTest extends TestCase {
], $settings);
}
- public function testSameSectionAsPersonalAndAdmin() {
+ public function testSameSectionAsPersonalAndAdmin(): void {
$this->l10nFactory
->expects($this->once())
->method('get')
diff --git a/tests/lib/Settings/SectionTest.php b/tests/lib/Settings/SectionTest.php
index 964256f303c..dd69f8ae110 100644
--- a/tests/lib/Settings/SectionTest.php
+++ b/tests/lib/Settings/SectionTest.php
@@ -10,13 +10,13 @@ use OC\Settings\Section;
use Test\TestCase;
class SectionTest extends TestCase {
- public function testGetID() {
+ public function testGetID(): void {
$this->assertSame('ldap', (new Section('ldap', 'name', 1))->getID());
}
- public function testGetName() {
+ public function testGetName(): void {
$this->assertSame('name', (new Section('ldap', 'name', 1))->getName());
}
- public function testGetPriority() {
+ public function testGetPriority(): void {
$this->assertSame(1, (new Section('ldap', 'name', 1))->getPriority());
}
}
diff --git a/tests/lib/SetupTest.php b/tests/lib/SetupTest.php
index 5216d2a730a..b5e1b7000c3 100644
--- a/tests/lib/SetupTest.php
+++ b/tests/lib/SetupTest.php
@@ -47,7 +47,7 @@ class SetupTest extends \Test\TestCase {
->getMock();
}
- public function testGetSupportedDatabasesWithOneWorking() {
+ public function testGetSupportedDatabasesWithOneWorking(): void {
$this->config
->expects($this->once())
->method('getValue')
@@ -70,7 +70,7 @@ class SetupTest extends \Test\TestCase {
$this->assertSame($expectedResult, $result);
}
- public function testGetSupportedDatabasesWithNoWorking() {
+ public function testGetSupportedDatabasesWithNoWorking(): void {
$this->config
->expects($this->once())
->method('getValue')
@@ -90,7 +90,7 @@ class SetupTest extends \Test\TestCase {
$this->assertSame([], $result);
}
- public function testGetSupportedDatabasesWithAllWorking() {
+ public function testGetSupportedDatabasesWithAllWorking(): void {
$this->config
->expects($this->once())
->method('getValue')
@@ -116,7 +116,7 @@ class SetupTest extends \Test\TestCase {
}
- public function testGetSupportedDatabaseException() {
+ public function testGetSupportedDatabaseException(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Supported databases are not properly configured.');
@@ -132,7 +132,7 @@ class SetupTest extends \Test\TestCase {
* @param $url
* @param $expected
*/
- public function testFindWebRootCli($url, $expected) {
+ public function testFindWebRootCli($url, $expected): void {
$cliState = \OC::$CLI;
$this->config
diff --git a/tests/lib/Share/HelperTest.php b/tests/lib/Share/HelperTest.php
index f92effebd5d..c923bb0480a 100644
--- a/tests/lib/Share/HelperTest.php
+++ b/tests/lib/Share/HelperTest.php
@@ -36,7 +36,7 @@ class HelperTest extends \Test\TestCase {
/**
* @dataProvider expireDateProvider
*/
- public function testCalculateExpireDate($defaultExpireSettings, $creationTime, $userExpireDate, $expected) {
+ public function testCalculateExpireDate($defaultExpireSettings, $creationTime, $userExpireDate, $expected): void {
$result = \OC\Share\Helper::calculateExpireDate($defaultExpireSettings, $creationTime, $userExpireDate);
$this->assertSame($expected, $result);
}
@@ -48,7 +48,7 @@ class HelperTest extends \Test\TestCase {
* @param string $server2
* @param bool $expected
*/
- public function testIsSameUserOnSameServer($user1, $server1, $user2, $server2, $expected) {
+ public function testIsSameUserOnSameServer($user1, $server1, $user2, $server2, $expected): void {
$this->assertSame($expected,
\OC\Share\Helper::isSameUserOnSameServer($user1, $server1, $user2, $server2)
);
diff --git a/tests/lib/Share/ShareTest.php b/tests/lib/Share/ShareTest.php
index 9938048450d..72bd4ac99ec 100644
--- a/tests/lib/Share/ShareTest.php
+++ b/tests/lib/Share/ShareTest.php
@@ -126,7 +126,7 @@ class ShareTest extends \Test\TestCase {
* @param string $url
* @param string $expectedResult
*/
- public function testRemoveProtocolFromUrl($url, $expectedResult) {
+ public function testRemoveProtocolFromUrl($url, $expectedResult): void {
$share = new Share();
$result = self::invokePrivate($share, 'removeProtocolFromUrl', [$url]);
$this->assertSame($expectedResult, $result);
@@ -145,7 +145,7 @@ class ShareTest extends \Test\TestCase {
* @param array $ungrouped
* @param array $grouped
*/
- public function testGroupItems($ungrouped, $grouped) {
+ public function testGroupItems($ungrouped, $grouped): void {
$result = DummyShareClass::groupItemsTest($ungrouped);
$this->compareArrays($grouped, $result);
diff --git a/tests/lib/Share20/DefaultShareProviderTest.php b/tests/lib/Share20/DefaultShareProviderTest.php
index 50940819b15..36f070d7c99 100644
--- a/tests/lib/Share20/DefaultShareProviderTest.php
+++ b/tests/lib/Share20/DefaultShareProviderTest.php
@@ -175,13 +175,13 @@ class DefaultShareProviderTest extends \Test\TestCase {
- public function testGetShareByIdNotExist() {
+ public function testGetShareByIdNotExist(): void {
$this->expectException(\OCP\Share\Exceptions\ShareNotFound::class);
$this->provider->getShareById(1);
}
- public function testGetShareByIdUserShare() {
+ public function testGetShareByIdUserShare(): void {
$qb = $this->dbConn->getQueryBuilder();
$qb->insert('share')
@@ -228,7 +228,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertEquals('myTarget', $share->getTarget());
}
- public function testGetShareByIdLazy() {
+ public function testGetShareByIdLazy(): void {
$qb = $this->dbConn->getQueryBuilder();
$qb->insert('share')
@@ -263,7 +263,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertEquals('myTarget', $share->getTarget());
}
- public function testGetShareByIdLazy2() {
+ public function testGetShareByIdLazy2(): void {
$qb = $this->dbConn->getQueryBuilder();
$qb->insert('share')
@@ -307,7 +307,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertEquals('myTarget', $share->getTarget());
}
- public function testGetShareByIdGroupShare() {
+ public function testGetShareByIdGroupShare(): void {
$qb = $this->dbConn->getQueryBuilder();
$qb->insert('share')
@@ -350,7 +350,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertEquals('myTarget', $share->getTarget());
}
- public function testGetShareByIdUserGroupShare() {
+ public function testGetShareByIdUserGroupShare(): void {
$id = $this->addShareToDB(IShare::TYPE_GROUP, 'group0', 'user0', 'user0', 'file', 42, 'myTarget', 31, null, null);
$this->addShareToDB(2, 'user1', 'user0', 'user0', 'file', 42, 'userTarget', 0, null, null, $id);
@@ -390,7 +390,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertEquals('userTarget', $share->getTarget());
}
- public function testGetShareByIdLinkShare() {
+ public function testGetShareByIdLinkShare(): void {
$qb = $this->dbConn->getQueryBuilder();
$qb->insert('share')
@@ -437,7 +437,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertEquals('myTarget', $share->getTarget());
}
- public function testDeleteSingleShare() {
+ public function testDeleteSingleShare(): void {
$qb = $this->dbConn->getQueryBuilder();
$qb->insert('share')
->values([
@@ -487,7 +487,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertEmpty($result);
}
- public function testDeleteSingleShareLazy() {
+ public function testDeleteSingleShareLazy(): void {
$qb = $this->dbConn->getQueryBuilder();
$qb->insert('share')
->values([
@@ -520,7 +520,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertEmpty($result);
}
- public function testDeleteGroupShareWithUserGroupShares() {
+ public function testDeleteGroupShareWithUserGroupShares(): void {
$qb = $this->dbConn->getQueryBuilder();
$qb->insert('share')
->values([
@@ -584,7 +584,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertEmpty($result);
}
- public function testGetChildren() {
+ public function testGetChildren(): void {
$qb = $this->dbConn->getQueryBuilder();
$qb->insert('share')
->values([
@@ -672,7 +672,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertEquals('myTarget2', $children[1]->getTarget());
}
- public function testCreateUserShare() {
+ public function testCreateUserShare(): void {
$share = new \OC\Share20\Share($this->rootFolder, $this->userManager);
$shareOwner = $this->createMock(IUser::class);
@@ -744,7 +744,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
);
}
- public function testCreateGroupShare() {
+ public function testCreateGroupShare(): void {
$share = new \OC\Share20\Share($this->rootFolder, $this->userManager);
$shareOwner = $this->createMock(IUser::class);
@@ -814,7 +814,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
);
}
- public function testCreateLinkShare() {
+ public function testCreateLinkShare(): void {
$share = new \OC\Share20\Share($this->rootFolder, $this->userManager);
$shareOwner = $this->createMock(IUser::class);
@@ -869,7 +869,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertEquals($expireDate->getTimestamp(), $share2->getExpirationDate()->getTimestamp());
}
- public function testGetShareByToken() {
+ public function testGetShareByToken(): void {
$qb = $this->dbConn->getQueryBuilder();
$qb->insert('share')
@@ -904,7 +904,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
}
- public function testGetShareByTokenNotFound() {
+ public function testGetShareByTokenNotFound(): void {
$this->expectException(\OCP\Share\Exceptions\ShareNotFound::class);
$this->provider->getShareByToken('invalidtoken');
@@ -947,7 +947,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
/**
* @dataProvider storageAndFileNameProvider
*/
- public function testGetSharedWithUser($storageStringId, $fileName1, $fileName2) {
+ public function testGetSharedWithUser($storageStringId, $fileName1, $fileName2): void {
$storageId = $this->createTestStorageEntry($storageStringId);
$fileId = $this->createTestFileEntry($fileName1, $storageId);
$fileId2 = $this->createTestFileEntry($fileName2, $storageId);
@@ -998,7 +998,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
/**
* @dataProvider storageAndFileNameProvider
*/
- public function testGetSharedWithGroup($storageStringId, $fileName1, $fileName2) {
+ public function testGetSharedWithGroup($storageStringId, $fileName1, $fileName2): void {
$storageId = $this->createTestStorageEntry($storageStringId);
$fileId = $this->createTestFileEntry($fileName1, $storageId);
$fileId2 = $this->createTestFileEntry($fileName2, $storageId);
@@ -1072,7 +1072,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
/**
* @dataProvider storageAndFileNameProvider
*/
- public function testGetSharedWithGroupUserModified($storageStringId, $fileName1, $fileName2) {
+ public function testGetSharedWithGroupUserModified($storageStringId, $fileName1, $fileName2): void {
$storageId = $this->createTestStorageEntry($storageStringId);
$fileId = $this->createTestFileEntry($fileName1, $storageId);
$qb = $this->dbConn->getQueryBuilder();
@@ -1164,7 +1164,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
/**
* @dataProvider storageAndFileNameProvider
*/
- public function testGetSharedWithUserWithNode($storageStringId, $fileName1, $fileName2) {
+ public function testGetSharedWithUserWithNode($storageStringId, $fileName1, $fileName2): void {
$storageId = $this->createTestStorageEntry($storageStringId);
$fileId = $this->createTestFileEntry($fileName1, $storageId);
$fileId2 = $this->createTestFileEntry($fileName2, $storageId);
@@ -1206,7 +1206,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
/**
* @dataProvider storageAndFileNameProvider
*/
- public function testGetSharedWithGroupWithNode($storageStringId, $fileName1, $fileName2) {
+ public function testGetSharedWithGroupWithNode($storageStringId, $fileName1, $fileName2): void {
$storageId = $this->createTestStorageEntry($storageStringId);
$fileId = $this->createTestFileEntry($fileName1, $storageId);
$fileId2 = $this->createTestFileEntry($fileName2, $storageId);
@@ -1258,7 +1258,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
/**
* @dataProvider shareTypesProvider
*/
- public function testGetSharedWithWithDeletedFile($shareType, $trashed) {
+ public function testGetSharedWithWithDeletedFile($shareType, $trashed): void {
if ($trashed) {
// exists in database but is in trash
$storageId = $this->createTestStorageEntry('home::shareOwner');
@@ -1312,7 +1312,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertCount(0, $share);
}
- public function testGetSharesBy() {
+ public function testGetSharesBy(): void {
$qb = $this->dbConn->getQueryBuilder();
$qb->insert('share')
->values([
@@ -1361,7 +1361,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertEquals('myTarget', $share->getTarget());
}
- public function testGetSharesNode() {
+ public function testGetSharesNode(): void {
$qb = $this->dbConn->getQueryBuilder();
$qb->insert('share')
->values([
@@ -1411,7 +1411,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertEquals('myTarget', $share->getTarget());
}
- public function testGetSharesReshare() {
+ public function testGetSharesReshare(): void {
$qb = $this->dbConn->getQueryBuilder();
$qb->insert('share')
->values([
@@ -1470,7 +1470,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertEquals('userTarget', $share->getTarget());
}
- public function testDeleteFromSelfGroupNoCustomShare() {
+ public function testDeleteFromSelfGroupNoCustomShare(): void {
$qb = $this->dbConn->getQueryBuilder();
$stmt = $qb->insert('share')
->values([
@@ -1527,7 +1527,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertEquals('user2', $share2['share_with']);
}
- public function testDeleteFromSelfGroupAlreadyCustomShare() {
+ public function testDeleteFromSelfGroupAlreadyCustomShare(): void {
$qb = $this->dbConn->getQueryBuilder();
$stmt = $qb->insert('share')
->values([
@@ -1600,7 +1600,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
}
- public function testDeleteFromSelfGroupUserNotInGroup() {
+ public function testDeleteFromSelfGroupUserNotInGroup(): void {
$qb = $this->dbConn->getQueryBuilder();
$stmt = $qb->insert('share')
->values([
@@ -1643,7 +1643,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
}
- public function testDeleteFromSelfGroupDoesNotExist() {
+ public function testDeleteFromSelfGroupDoesNotExist(): void {
$this->expectException(\OC\Share20\Exception\ProviderException::class);
$this->expectExceptionMessage('Group "group" does not exist');
@@ -1684,7 +1684,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->provider->deleteFromSelf($share, 'user2');
}
- public function testDeleteFromSelfUser() {
+ public function testDeleteFromSelfUser(): void {
$qb = $this->dbConn->getQueryBuilder();
$stmt = $qb->insert('share')
->values([
@@ -1734,7 +1734,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
}
- public function testDeleteFromSelfUserNotRecipient() {
+ public function testDeleteFromSelfUserNotRecipient(): void {
$this->expectException(\OC\Share20\Exception\ProviderException::class);
$this->expectExceptionMessage('Recipient does not match');
@@ -1777,7 +1777,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
}
- public function testDeleteFromSelfLink() {
+ public function testDeleteFromSelfLink(): void {
$this->expectException(\OC\Share20\Exception\ProviderException::class);
$this->expectExceptionMessage('Invalid shareType');
@@ -1813,7 +1813,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->provider->deleteFromSelf($share, $user1);
}
- public function testUpdateUser() {
+ public function testUpdateUser(): void {
$id = $this->addShareToDB(IShare::TYPE_USER, 'user0', 'user1', 'user2',
'file', 42, 'target', 31, null, null);
@@ -1871,7 +1871,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertSame(1, $share2->getPermissions());
}
- public function testUpdateLink() {
+ public function testUpdateLink(): void {
$id = $this->addShareToDB(IShare::TYPE_LINK, null, 'user1', 'user2',
'file', 42, 'target', 31, null, null);
@@ -1931,7 +1931,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertSame(1, $share2->getPermissions());
}
- public function testUpdateLinkRemovePassword() {
+ public function testUpdateLinkRemovePassword(): void {
$id = $this->addShareToDB(IShare::TYPE_LINK, 'foo', 'user1', 'user2',
'file', 42, 'target', 31, null, null);
@@ -1994,7 +1994,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertSame(1, $share2->getPermissions());
}
- public function testUpdateGroupNoSub() {
+ public function testUpdateGroupNoSub(): void {
$id = $this->addShareToDB(IShare::TYPE_GROUP, 'group0', 'user1', 'user2',
'file', 42, 'target', 31, null, null);
@@ -2067,7 +2067,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertSame(1, $share2->getPermissions());
}
- public function testUpdateGroupSubShares() {
+ public function testUpdateGroupSubShares(): void {
$id = $this->addShareToDB(IShare::TYPE_GROUP, 'group0', 'user1', 'user2',
'file', 42, 'target', 31, null, null);
@@ -2168,7 +2168,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$stmt->closeCursor();
}
- public function testMoveUserShare() {
+ public function testMoveUserShare(): void {
$id = $this->addShareToDB(IShare::TYPE_USER, 'user0', 'user1', 'user1', 'file',
42, 'mytaret', 31, null, null);
@@ -2199,7 +2199,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertSame('/newTarget', $share->getTarget());
}
- public function testMoveGroupShare() {
+ public function testMoveGroupShare(): void {
$id = $this->addShareToDB(IShare::TYPE_GROUP, 'group0', 'user1', 'user1', 'file',
42, 'mytaret', 31, null, null);
@@ -2270,7 +2270,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
* @param string $deletedUser The user that is deleted
* @param bool $rowDeleted Is the row deleted in this setup
*/
- public function testDeleteUser($type, $owner, $initiator, $recipient, $deletedUser, $rowDeleted) {
+ public function testDeleteUser($type, $owner, $initiator, $recipient, $deletedUser, $rowDeleted): void {
$qb = $this->dbConn->getQueryBuilder();
$qb->insert('share')
->setValue('share_type', $qb->createNamedParameter($type))
@@ -2318,7 +2318,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
* @param bool $groupShareDeleted
* @param bool $userGroupShareDeleted
*/
- public function testDeleteUserGroup($owner, $initiator, $recipient, $deletedUser, $groupShareDeleted, $userGroupShareDeleted) {
+ public function testDeleteUserGroup($owner, $initiator, $recipient, $deletedUser, $groupShareDeleted, $userGroupShareDeleted): void {
$qb = $this->dbConn->getQueryBuilder();
$qb->insert('share')
->setValue('share_type', $qb->createNamedParameter(IShare::TYPE_GROUP))
@@ -2421,7 +2421,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
* @param $groupToDelete
* @param $shouldBeDeleted
*/
- public function testGroupDeleted($shares, $groupToDelete, $shouldBeDeleted) {
+ public function testGroupDeleted($shares, $groupToDelete, $shouldBeDeleted): void {
$qb = $this->dbConn->getQueryBuilder();
$qb->insert('share')
->setValue('share_type', $qb->createNamedParameter($shares['type']))
@@ -2481,7 +2481,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
* @param string $user
* @param bool $toDelete
*/
- public function testUserDeletedFromGroup($group, $user, $toDelete) {
+ public function testUserDeletedFromGroup($group, $user, $toDelete): void {
$qb = $this->dbConn->getQueryBuilder();
$qb->insert('share')
->setValue('share_type', $qb->createNamedParameter(IShare::TYPE_GROUP))
@@ -2520,7 +2520,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertCount($toDelete ? 0 : 1, $data);
}
- public function testGetSharesInFolder() {
+ public function testGetSharesInFolder(): void {
$userManager = \OC::$server->getUserManager();
$groupManager = \OC::$server->getGroupManager();
$rootFolder = \OC::$server->get(IRootFolder::class);
@@ -2620,7 +2620,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$g1->delete();
}
- public function testGetAccessListNoCurrentAccessRequired() {
+ public function testGetAccessListNoCurrentAccessRequired(): void {
$userManager = \OC::$server->getUserManager();
$groupManager = \OC::$server->getGroupManager();
$rootFolder = \OC::$server->get(IRootFolder::class);
@@ -2718,7 +2718,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$g1->delete();
}
- public function testGetAccessListCurrentAccessRequired() {
+ public function testGetAccessListCurrentAccessRequired(): void {
$userManager = \OC::$server->getUserManager();
$groupManager = \OC::$server->getGroupManager();
$rootFolder = \OC::$server->get(IRootFolder::class);
@@ -2815,7 +2815,7 @@ class DefaultShareProviderTest extends \Test\TestCase {
$g1->delete();
}
- public function testGetAllShares() {
+ public function testGetAllShares(): void {
$qb = $this->dbConn->getQueryBuilder();
$qb->insert('share')
diff --git a/tests/lib/Share20/LegacyHooksTest.php b/tests/lib/Share20/LegacyHooksTest.php
index 115bfa07797..3699d95182b 100644
--- a/tests/lib/Share20/LegacyHooksTest.php
+++ b/tests/lib/Share20/LegacyHooksTest.php
@@ -43,7 +43,7 @@ class LegacyHooksTest extends TestCase {
$this->manager = \OC::$server->get(IShareManager::class);
}
- public function testPreUnshare() {
+ public function testPreUnshare(): void {
$path = $this->createMock(File::class);
$path->method('getId')->willReturn(1);
@@ -84,7 +84,7 @@ class LegacyHooksTest extends TestCase {
$this->eventDispatcher->dispatchTyped($event);
}
- public function testPostUnshare() {
+ public function testPostUnshare(): void {
$path = $this->createMock(File::class);
$path->method('getId')->willReturn(1);
@@ -138,7 +138,7 @@ class LegacyHooksTest extends TestCase {
$this->eventDispatcher->dispatchTyped($event);
}
- public function testPostUnshareFromSelf() {
+ public function testPostUnshareFromSelf(): void {
$path = $this->createMock(File::class);
$path->method('getId')->willReturn(1);
@@ -194,7 +194,7 @@ class LegacyHooksTest extends TestCase {
$this->eventDispatcher->dispatchTyped($event);
}
- public function testPreShare() {
+ public function testPreShare(): void {
$path = $this->createMock(File::class);
$path->method('getId')->willReturn(1);
@@ -242,7 +242,7 @@ class LegacyHooksTest extends TestCase {
$this->eventDispatcher->dispatchTyped($event);
}
- public function testPreShareError() {
+ public function testPreShareError(): void {
$path = $this->createMock(File::class);
$path->method('getId')->willReturn(1);
@@ -297,7 +297,7 @@ class LegacyHooksTest extends TestCase {
$this->assertSame('I error', $event->getError());
}
- public function testPostShare() {
+ public function testPostShare(): void {
$path = $this->createMock(File::class);
$path->method('getId')->willReturn(1);
diff --git a/tests/lib/Share20/ManagerTest.php b/tests/lib/Share20/ManagerTest.php
index 527164ea334..759e11f10dc 100644
--- a/tests/lib/Share20/ManagerTest.php
+++ b/tests/lib/Share20/ManagerTest.php
@@ -1,4690 +1,4690 @@
-<?php
-/**
- * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
- * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
- * SPDX-License-Identifier: AGPL-3.0-only
- */
-
-namespace Test\Share20;
-
-use DateTimeZone;
-use OC\Files\Mount\MoveableMount;
-use OC\KnownUser\KnownUserService;
-use OC\Share20\DefaultShareProvider;
-use OC\Share20\Exception;
-use OC\Share20\Manager;
-use OC\Share20\Share;
-use OC\Share20\ShareDisableChecker;
-use OCP\EventDispatcher\Event;
-use OCP\EventDispatcher\IEventDispatcher;
-use OCP\Files\File;
-use OCP\Files\Folder;
-use OCP\Files\IRootFolder;
-use OCP\Files\Mount\IMountManager;
-use OCP\Files\Mount\IMountPoint;
-use OCP\Files\Node;
-use OCP\Files\Storage;
-use OCP\HintException;
-use OCP\IConfig;
-use OCP\IDateTimeZone;
-use OCP\IGroup;
-use OCP\IGroupManager;
-use OCP\IL10N;
-use OCP\IServerContainer;
-use OCP\IURLGenerator;
-use OCP\IUser;
-use OCP\IUserManager;
-use OCP\IUserSession;
-use OCP\L10N\IFactory;
-use OCP\Mail\IMailer;
-use OCP\Security\Events\ValidatePasswordPolicyEvent;
-use OCP\Security\IHasher;
-use OCP\Security\ISecureRandom;
-use OCP\Share\Events\BeforeShareCreatedEvent;
-use OCP\Share\Events\BeforeShareDeletedEvent;
-use OCP\Share\Events\ShareCreatedEvent;
-use OCP\Share\Events\ShareDeletedEvent;
-use OCP\Share\Events\ShareDeletedFromSelfEvent;
-use OCP\Share\Exceptions\AlreadySharedException;
-use OCP\Share\Exceptions\ShareNotFound;
-use OCP\Share\IManager;
-use OCP\Share\IProviderFactory;
-use OCP\Share\IShare;
-use OCP\Share\IShareProvider;
-use PHPUnit\Framework\MockObject\MockBuilder;
-use PHPUnit\Framework\MockObject\MockObject;
-use Psr\Log\LoggerInterface;
-
-/**
- * Class ManagerTest
- *
- * @package Test\Share20
- * @group DB
- */
-class ManagerTest extends \Test\TestCase {
- /** @var Manager */
- protected $manager;
- /** @var LoggerInterface|MockObject */
- protected $logger;
- /** @var IConfig|MockObject */
- protected $config;
- /** @var ISecureRandom|MockObject */
- protected $secureRandom;
- /** @var IHasher|MockObject */
- protected $hasher;
- /** @var IShareProvider|MockObject */
- protected $defaultProvider;
- /** @var IMountManager|MockObject */
- protected $mountManager;
- /** @var IGroupManager|MockObject */
- protected $groupManager;
- /** @var IL10N|MockObject */
- protected $l;
- /** @var IFactory|MockObject */
- protected $l10nFactory;
- /** @var DummyFactory */
- protected $factory;
- /** @var IUserManager|MockObject */
- protected $userManager;
- /** @var IRootFolder | MockObject */
- protected $rootFolder;
- /** @var IEventDispatcher|MockObject */
- protected $dispatcher;
- /** @var IMailer|MockObject */
- protected $mailer;
- /** @var IURLGenerator|MockObject */
- protected $urlGenerator;
- /** @var \OC_Defaults|MockObject */
- protected $defaults;
- /** @var IUserSession|MockObject */
- protected $userSession;
- /** @var KnownUserService|MockObject */
- protected $knownUserService;
- /** @var ShareDisableChecker|MockObject */
- protected $shareDisabledChecker;
- private DateTimeZone $timezone;
- /** @var IDateTimeZone|MockObject */
- protected $dateTimeZone;
-
- protected function setUp(): void {
- $this->logger = $this->createMock(LoggerInterface::class);
- $this->config = $this->createMock(IConfig::class);
- $this->secureRandom = $this->createMock(ISecureRandom::class);
- $this->hasher = $this->createMock(IHasher::class);
- $this->mountManager = $this->createMock(IMountManager::class);
- $this->groupManager = $this->createMock(IGroupManager::class);
- $this->userManager = $this->createMock(IUserManager::class);
- $this->rootFolder = $this->createMock(IRootFolder::class);
- $this->mailer = $this->createMock(IMailer::class);
- $this->urlGenerator = $this->createMock(IURLGenerator::class);
- $this->defaults = $this->createMock(\OC_Defaults::class);
- $this->dispatcher = $this->createMock(IEventDispatcher::class);
- $this->userSession = $this->createMock(IUserSession::class);
- $this->knownUserService = $this->createMock(KnownUserService::class);
-
- $this->shareDisabledChecker = new ShareDisableChecker($this->config, $this->userManager, $this->groupManager);
- $this->dateTimeZone = $this->createMock(IDateTimeZone::class);
- $this->timezone = new \DateTimeZone('Pacific/Auckland');
- $this->dateTimeZone->method('getTimeZone')->willReturnCallback(fn () => $this->timezone);
-
- $this->l10nFactory = $this->createMock(IFactory::class);
- $this->l = $this->createMock(IL10N::class);
- $this->l->method('t')
- ->willReturnCallback(function ($text, $parameters = []) {
- return vsprintf($text, $parameters);
- });
- $this->l->method('n')
- ->willReturnCallback(function ($singular, $plural, $count, $parameters = []) {
- return vsprintf(str_replace('%n', $count, ($count === 1) ? $singular : $plural), $parameters);
- });
- $this->l10nFactory->method('get')->willReturn($this->l);
-
- $this->factory = new DummyFactory(\OC::$server);
-
- $this->manager = $this->createManager($this->factory);
-
- $this->defaultProvider = $this->createMock(DefaultShareProvider::class);
- $this->defaultProvider->method('identifier')->willReturn('default');
- $this->factory->setProvider($this->defaultProvider);
- }
-
- private function createManager(IProviderFactory $factory): Manager {
- return new Manager(
- $this->logger,
- $this->config,
- $this->secureRandom,
- $this->hasher,
- $this->mountManager,
- $this->groupManager,
- $this->l10nFactory,
- $factory,
- $this->userManager,
- $this->rootFolder,
- $this->mailer,
- $this->urlGenerator,
- $this->defaults,
- $this->dispatcher,
- $this->userSession,
- $this->knownUserService,
- $this->shareDisabledChecker,
- $this->dateTimeZone,
- );
- }
-
- /**
- * @return MockBuilder
- */
- private function createManagerMock() {
- return $this->getMockBuilder(Manager::class)
- ->setConstructorArgs([
- $this->logger,
- $this->config,
- $this->secureRandom,
- $this->hasher,
- $this->mountManager,
- $this->groupManager,
- $this->l10nFactory,
- $this->factory,
- $this->userManager,
- $this->rootFolder,
- $this->mailer,
- $this->urlGenerator,
- $this->defaults,
- $this->dispatcher,
- $this->userSession,
- $this->knownUserService,
- $this->shareDisabledChecker,
- $this->dateTimeZone,
- ]);
- }
-
-
- public function testDeleteNoShareId() {
- $this->expectException(\InvalidArgumentException::class);
-
- $share = $this->manager->newShare();
-
- $this->manager->deleteShare($share);
- }
-
- public function dataTestDelete() {
- $user = $this->createMock(IUser::class);
- $user->method('getUID')->willReturn('sharedWithUser');
-
- $group = $this->createMock(IGroup::class);
- $group->method('getGID')->willReturn('sharedWithGroup');
-
- return [
- [IShare::TYPE_USER, 'sharedWithUser'],
- [IShare::TYPE_GROUP, 'sharedWithGroup'],
- [IShare::TYPE_LINK, ''],
- [IShare::TYPE_REMOTE, 'foo@bar.com'],
- ];
- }
-
- /**
- * @dataProvider dataTestDelete
- */
- public function testDelete($shareType, $sharedWith) {
- $manager = $this->createManagerMock()
- ->setMethods(['getShareById', 'deleteChildren'])
- ->getMock();
-
- $manager->method('deleteChildren')->willReturn([]);
-
- $path = $this->createMock(File::class);
- $path->method('getId')->willReturn(1);
-
- $share = $this->manager->newShare();
- $share->setId(42)
- ->setProviderId('prov')
- ->setShareType($shareType)
- ->setSharedWith($sharedWith)
- ->setSharedBy('sharedBy')
- ->setNode($path)
- ->setTarget('myTarget');
-
- $manager->expects($this->once())->method('deleteChildren')->with($share);
-
- $this->defaultProvider
- ->expects($this->once())
- ->method('delete')
- ->with($share);
-
- $this->dispatcher->expects($this->exactly(2))
- ->method('dispatchTyped')
- ->withConsecutive(
- [
- $this->callBack(function (BeforeShareDeletedEvent $e) use ($share) {
- return $e->getShare() === $share;
- })],
- [
- $this->callBack(function (ShareDeletedEvent $e) use ($share) {
- return $e->getShare() === $share;
- })]
- );
-
- $manager->deleteShare($share);
- }
-
- public function testDeleteLazyShare() {
- $manager = $this->createManagerMock()
- ->setMethods(['getShareById', 'deleteChildren'])
- ->getMock();
-
- $manager->method('deleteChildren')->willReturn([]);
-
- $share = $this->manager->newShare();
- $share->setId(42)
- ->setProviderId('prov')
- ->setShareType(IShare::TYPE_USER)
- ->setSharedWith('sharedWith')
- ->setSharedBy('sharedBy')
- ->setShareOwner('shareOwner')
- ->setTarget('myTarget')
- ->setNodeId(1)
- ->setNodeType('file');
-
- $this->rootFolder->expects($this->never())->method($this->anything());
-
- $manager->expects($this->once())->method('deleteChildren')->with($share);
-
- $this->defaultProvider
- ->expects($this->once())
- ->method('delete')
- ->with($share);
-
- $this->dispatcher->expects($this->exactly(2))
- ->method('dispatchTyped')
- ->withConsecutive(
- [
- $this->callBack(function (BeforeShareDeletedEvent $e) use ($share) {
- return $e->getShare() === $share;
- })],
- [
- $this->callBack(function (ShareDeletedEvent $e) use ($share) {
- return $e->getShare() === $share;
- })]
- );
-
- $manager->deleteShare($share);
- }
-
- public function testDeleteNested() {
- $manager = $this->createManagerMock()
- ->setMethods(['getShareById'])
- ->getMock();
-
- $path = $this->createMock(File::class);
- $path->method('getId')->willReturn(1);
-
- $share1 = $this->manager->newShare();
- $share1->setId(42)
- ->setProviderId('prov')
- ->setShareType(IShare::TYPE_USER)
- ->setSharedWith('sharedWith1')
- ->setSharedBy('sharedBy1')
- ->setNode($path)
- ->setTarget('myTarget1');
-
- $share2 = $this->manager->newShare();
- $share2->setId(43)
- ->setProviderId('prov')
- ->setShareType(IShare::TYPE_GROUP)
- ->setSharedWith('sharedWith2')
- ->setSharedBy('sharedBy2')
- ->setNode($path)
- ->setTarget('myTarget2')
- ->setParent(42);
-
- $share3 = $this->manager->newShare();
- $share3->setId(44)
- ->setProviderId('prov')
- ->setShareType(IShare::TYPE_LINK)
- ->setSharedBy('sharedBy3')
- ->setNode($path)
- ->setTarget('myTarget3')
- ->setParent(43);
-
- $this->defaultProvider
- ->method('getChildren')
- ->willReturnMap([
- [$share1, [$share2]],
- [$share2, [$share3]],
- [$share3, []],
- ]);
-
- $this->defaultProvider
- ->method('delete')
- ->withConsecutive([$share3], [$share2], [$share1]);
-
- $this->dispatcher->expects($this->exactly(6))
- ->method('dispatchTyped')
- ->withConsecutive(
- [
- $this->callBack(function (BeforeShareDeletedEvent $e) use ($share1) {
- return $e->getShare()->getId() === $share1->getId();
- })
- ],
- [
- $this->callBack(function (BeforeShareDeletedEvent $e) use ($share2) {
- return $e->getShare()->getId() === $share2->getId();
- })
- ],
- [
- $this->callBack(function (BeforeShareDeletedEvent $e) use ($share3) {
- return $e->getShare()->getId() === $share3->getId();
- })
- ],
- [
- $this->callBack(function (ShareDeletedEvent $e) use ($share3) {
- return $e->getShare()->getId() === $share3->getId();
- })
- ],
- [
- $this->callBack(function (ShareDeletedEvent $e) use ($share2) {
- return $e->getShare()->getId() === $share2->getId();
- })
- ],
- [
- $this->callBack(function (ShareDeletedEvent $e) use ($share1) {
- return $e->getShare()->getId() === $share1->getId();
- })
- ],
- );
-
- $manager->deleteShare($share1);
- }
-
- public function testDeleteFromSelf() {
- $manager = $this->createManagerMock()
- ->setMethods(['getShareById'])
- ->getMock();
-
- $recipientId = 'unshareFrom';
- $share = $this->manager->newShare();
- $share->setId(42)
- ->setProviderId('prov')
- ->setShareType(IShare::TYPE_USER)
- ->setSharedWith('sharedWith')
- ->setSharedBy('sharedBy')
- ->setShareOwner('shareOwner')
- ->setTarget('myTarget')
- ->setNodeId(1)
- ->setNodeType('file');
-
- $this->defaultProvider
- ->expects($this->once())
- ->method('deleteFromSelf')
- ->with($share, $recipientId);
-
- $this->dispatcher->expects($this->once())
- ->method('dispatchTyped')
- ->with(
- $this->callBack(function (ShareDeletedFromSelfEvent $e) use ($share) {
- return $e->getShare() === $share;
- })
- );
-
- $manager->deleteFromSelf($share, $recipientId);
- }
-
- public function testDeleteChildren() {
- $manager = $this->createManagerMock()
- ->setMethods(['deleteShare'])
- ->getMock();
-
- $share = $this->createMock(IShare::class);
- $share->method('getShareType')->willReturn(IShare::TYPE_USER);
-
- $child1 = $this->createMock(IShare::class);
- $child1->method('getShareType')->willReturn(IShare::TYPE_USER);
- $child2 = $this->createMock(IShare::class);
- $child2->method('getShareType')->willReturn(IShare::TYPE_USER);
- $child3 = $this->createMock(IShare::class);
- $child3->method('getShareType')->willReturn(IShare::TYPE_USER);
-
- $shares = [
- $child1,
- $child2,
- $child3,
- ];
-
- $this->defaultProvider
- ->expects($this->exactly(4))
- ->method('getChildren')
- ->willReturnCallback(function ($_share) use ($share, $shares) {
- if ($_share === $share) {
- return $shares;
- }
- return [];
- });
-
- $this->defaultProvider
- ->expects($this->exactly(3))
- ->method('delete')
- ->withConsecutive([$child1], [$child2], [$child3]);
-
- $result = self::invokePrivate($manager, 'deleteChildren', [$share]);
- $this->assertSame($shares, $result);
- }
-
- public function testGetShareById() {
- $share = $this->createMock(IShare::class);
-
- $this->defaultProvider
- ->expects($this->once())
- ->method('getShareById')
- ->with(42)
- ->willReturn($share);
-
- $this->assertEquals($share, $this->manager->getShareById('default:42'));
- }
-
-
- public function testGetExpiredShareById() {
- $this->expectException(\OCP\Share\Exceptions\ShareNotFound::class);
-
- $manager = $this->createManagerMock()
- ->setMethods(['deleteShare'])
- ->getMock();
-
- $date = new \DateTime();
- $date->setTime(0, 0, 0);
-
- $share = $this->manager->newShare();
- $share->setExpirationDate($date)
- ->setShareType(IShare::TYPE_LINK);
-
- $this->defaultProvider->expects($this->once())
- ->method('getShareById')
- ->with('42')
- ->willReturn($share);
-
- $manager->expects($this->once())
- ->method('deleteShare')
- ->with($share);
-
- $manager->getShareById('default:42');
- }
-
-
- public function testVerifyPasswordNullButEnforced() {
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('Passwords are enforced for link and mail shares');
-
- $this->config->method('getAppValue')->willReturnMap([
- ['core', 'shareapi_enforce_links_password_excluded_groups', '', ''],
- ['core', 'shareapi_enforce_links_password', 'no', 'yes'],
- ]);
-
- self::invokePrivate($this->manager, 'verifyPassword', [null]);
- }
-
- public function testVerifyPasswordNotEnforcedGroup() {
- $this->config->method('getAppValue')->willReturnMap([
- ['core', 'shareapi_enforce_links_password_excluded_groups', '', '["admin"]'],
- ['core', 'shareapi_enforce_links_password', 'no', 'yes'],
- ]);
-
- // Create admin user
- $user = $this->createMock(IUser::class);
- $this->userSession->method('getUser')->willReturn($user);
- $this->groupManager->method('getUserGroupIds')->with($user)->willReturn(['admin']);
-
- $result = self::invokePrivate($this->manager, 'verifyPassword', [null]);
- $this->assertNull($result);
- }
-
- public function testVerifyPasswordNotEnforcedMultipleGroups() {
- $this->config->method('getAppValue')->willReturnMap([
- ['core', 'shareapi_enforce_links_password_excluded_groups', '', '["admin", "special"]'],
- ['core', 'shareapi_enforce_links_password', 'no', 'yes'],
- ]);
-
- // Create admin user
- $user = $this->createMock(IUser::class);
- $this->userSession->method('getUser')->willReturn($user);
- $this->groupManager->method('getUserGroupIds')->with($user)->willReturn(['special']);
-
- $result = self::invokePrivate($this->manager, 'verifyPassword', [null]);
- $this->assertNull($result);
- }
-
- public function testVerifyPasswordNull() {
- $this->config->method('getAppValue')->willReturnMap([
- ['core', 'shareapi_enforce_links_password_excluded_groups', '', ''],
- ['core', 'shareapi_enforce_links_password', 'no', 'no'],
- ]);
-
- $result = self::invokePrivate($this->manager, 'verifyPassword', [null]);
- $this->assertNull($result);
- }
-
- public function testVerifyPasswordHook() {
- $this->config->method('getAppValue')->willReturnMap([
- ['core', 'shareapi_enforce_links_password_excluded_groups', '', ''],
- ['core', 'shareapi_enforce_links_password', 'no', 'no'],
- ]);
-
- $this->dispatcher->expects($this->once())->method('dispatchTyped')
- ->willReturnCallback(function (Event $event) {
- $this->assertInstanceOf(ValidatePasswordPolicyEvent::class, $event);
- /** @var ValidatePasswordPolicyEvent $event */
- $this->assertSame('password', $event->getPassword());
- }
- );
-
- $result = self::invokePrivate($this->manager, 'verifyPassword', ['password']);
- $this->assertNull($result);
- }
-
-
- public function testVerifyPasswordHookFails() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('password not accepted');
-
- $this->config->method('getAppValue')->willReturnMap([
- ['core', 'shareapi_enforce_links_password_excluded_groups', '', ''],
- ['core', 'shareapi_enforce_links_password', 'no', 'no'],
- ]);
-
- $this->dispatcher->expects($this->once())->method('dispatchTyped')
- ->willReturnCallback(function (Event $event) {
- $this->assertInstanceOf(ValidatePasswordPolicyEvent::class, $event);
- /** @var ValidatePasswordPolicyEvent $event */
- $this->assertSame('password', $event->getPassword());
- throw new HintException('message', 'password not accepted');
- }
- );
-
- self::invokePrivate($this->manager, 'verifyPassword', ['password']);
- }
-
- public function createShare($id, $type, $node, $sharedWith, $sharedBy, $shareOwner,
- $permissions, $expireDate = null, $password = null, $attributes = null) {
- $share = $this->createMock(IShare::class);
-
- $share->method('getShareType')->willReturn($type);
- $share->method('getSharedWith')->willReturn($sharedWith);
- $share->method('getSharedBy')->willReturn($sharedBy);
- $share->method('getShareOwner')->willReturn($shareOwner);
- $share->method('getNode')->willReturn($node);
- if ($node && $node->getId()) {
- $share->method('getNodeId')->willReturn($node->getId());
- }
- $share->method('getPermissions')->willReturn($permissions);
- $share->method('getAttributes')->willReturn($attributes);
- $share->method('getExpirationDate')->willReturn($expireDate);
- $share->method('getPassword')->willReturn($password);
-
- return $share;
- }
-
- public function dataGeneralChecks() {
- $user0 = 'user0';
- $user2 = 'user1';
- $group0 = 'group0';
- $owner = $this->createMock(IUser::class);
- $owner->method('getUID')
- ->willReturn($user0);
-
- $file = $this->createMock(File::class);
- $node = $this->createMock(Node::class);
- $storage = $this->createMock(Storage\IStorage::class);
- $storage->method('instanceOfStorage')
- ->with(\OCA\Files_Sharing\External\Storage::class)
- ->willReturn(false);
- $file->method('getStorage')
- ->willReturn($storage);
- $file->method('getId')->willReturn(108);
- $node->method('getStorage')
- ->willReturn($storage);
- $node->method('getId')->willReturn(108);
-
- $data = [
- [$this->createShare(null, IShare::TYPE_USER, $file, null, $user0, $user0, 31, null, null), 'SharedWith is not a valid user', true],
- [$this->createShare(null, IShare::TYPE_USER, $file, $group0, $user0, $user0, 31, null, null), 'SharedWith is not a valid user', true],
- [$this->createShare(null, IShare::TYPE_USER, $file, 'foo@bar.com', $user0, $user0, 31, null, null), 'SharedWith is not a valid user', true],
- [$this->createShare(null, IShare::TYPE_GROUP, $file, null, $user0, $user0, 31, null, null), 'SharedWith is not a valid group', true],
- [$this->createShare(null, IShare::TYPE_GROUP, $file, $user2, $user0, $user0, 31, null, null), 'SharedWith is not a valid group', true],
- [$this->createShare(null, IShare::TYPE_GROUP, $file, 'foo@bar.com', $user0, $user0, 31, null, null), 'SharedWith is not a valid group', true],
- [$this->createShare(null, IShare::TYPE_LINK, $file, $user2, $user0, $user0, 31, null, null), 'SharedWith should be empty', true],
- [$this->createShare(null, IShare::TYPE_LINK, $file, $group0, $user0, $user0, 31, null, null), 'SharedWith should be empty', true],
- [$this->createShare(null, IShare::TYPE_LINK, $file, 'foo@bar.com', $user0, $user0, 31, null, null), 'SharedWith should be empty', true],
- [$this->createShare(null, -1, $file, null, $user0, $user0, 31, null, null), 'Unknown share type', true],
-
- [$this->createShare(null, IShare::TYPE_USER, $file, $user2, null, $user0, 31, null, null), 'SharedBy should be set', true],
- [$this->createShare(null, IShare::TYPE_GROUP, $file, $group0, null, $user0, 31, null, null), 'SharedBy should be set', true],
- [$this->createShare(null, IShare::TYPE_LINK, $file, null, null, $user0, 31, null, null), 'SharedBy should be set', true],
-
- [$this->createShare(null, IShare::TYPE_USER, $file, $user0, $user0, $user0, 31, null, null), 'Cannot share with yourself', true],
-
- [$this->createShare(null, IShare::TYPE_USER, null, $user2, $user0, $user0, 31, null, null), 'Path should be set', true],
- [$this->createShare(null, IShare::TYPE_GROUP, null, $group0, $user0, $user0, 31, null, null), 'Path should be set', true],
- [$this->createShare(null, IShare::TYPE_LINK, null, null, $user0, $user0, 31, null, null), 'Path should be set', true],
-
- [$this->createShare(null, IShare::TYPE_USER, $node, $user2, $user0, $user0, 31, null, null), 'Path should be either a file or a folder', true],
- [$this->createShare(null, IShare::TYPE_GROUP, $node, $group0, $user0, $user0, 31, null, null), 'Path should be either a file or a folder', true],
- [$this->createShare(null, IShare::TYPE_LINK, $node, null, $user0, $user0, 31, null, null), 'Path should be either a file or a folder', true],
- ];
-
- $nonShareAble = $this->createMock(Folder::class);
- $nonShareAble->method('getId')->willReturn(108);
- $nonShareAble->method('isShareable')->willReturn(false);
- $nonShareAble->method('getPath')->willReturn('path');
- $nonShareAble->method('getName')->willReturn('name');
- $nonShareAble->method('getOwner')
- ->willReturn($owner);
- $nonShareAble->method('getStorage')
- ->willReturn($storage);
-
- $data[] = [$this->createShare(null, IShare::TYPE_USER, $nonShareAble, $user2, $user0, $user0, 31, null, null), 'You are not allowed to share name', true];
- $data[] = [$this->createShare(null, IShare::TYPE_GROUP, $nonShareAble, $group0, $user0, $user0, 31, null, null), 'You are not allowed to share name', true];
- $data[] = [$this->createShare(null, IShare::TYPE_LINK, $nonShareAble, null, $user0, $user0, 31, null, null), 'You are not allowed to share name', true];
-
- $limitedPermssions = $this->createMock(File::class);
- $limitedPermssions->method('isShareable')->willReturn(true);
- $limitedPermssions->method('getPermissions')->willReturn(\OCP\Constants::PERMISSION_READ);
- $limitedPermssions->method('getId')->willReturn(108);
- $limitedPermssions->method('getPath')->willReturn('path');
- $limitedPermssions->method('getName')->willReturn('name');
- $limitedPermssions->method('getOwner')
- ->willReturn($owner);
- $limitedPermssions->method('getStorage')
- ->willReturn($storage);
-
- $data[] = [$this->createShare(null, IShare::TYPE_USER, $limitedPermssions, $user2, $user0, $user0, null, null, null), 'A share requires permissions', true];
- $data[] = [$this->createShare(null, IShare::TYPE_GROUP, $limitedPermssions, $group0, $user0, $user0, null, null, null), 'A share requires permissions', true];
- $data[] = [$this->createShare(null, IShare::TYPE_LINK, $limitedPermssions, null, $user0, $user0, null, null, null), 'A share requires permissions', true];
-
- $mount = $this->createMock(MoveableMount::class);
- $limitedPermssions->method('getMountPoint')->willReturn($mount);
-
-
- $data[] = [$this->createShare(null, IShare::TYPE_USER, $limitedPermssions, $user2, $user0, $user0, 31, null, null), 'Cannot increase permissions of path', true];
- $data[] = [$this->createShare(null, IShare::TYPE_GROUP, $limitedPermssions, $group0, $user0, $user0, 17, null, null), 'Cannot increase permissions of path', true];
- $data[] = [$this->createShare(null, IShare::TYPE_LINK, $limitedPermssions, null, $user0, $user0, 3, null, null), 'Cannot increase permissions of path', true];
-
- $nonMovableStorage = $this->createMock(Storage\IStorage::class);
- $nonMovableStorage->method('instanceOfStorage')
- ->with(\OCA\Files_Sharing\External\Storage::class)
- ->willReturn(false);
- $nonMovableStorage->method('getPermissions')->willReturn(\OCP\Constants::PERMISSION_ALL);
- $nonMoveableMountPermssions = $this->createMock(Folder::class);
- $nonMoveableMountPermssions->method('isShareable')->willReturn(true);
- $nonMoveableMountPermssions->method('getPermissions')->willReturn(\OCP\Constants::PERMISSION_READ);
- $nonMoveableMountPermssions->method('getId')->willReturn(108);
- $nonMoveableMountPermssions->method('getPath')->willReturn('path');
- $nonMoveableMountPermssions->method('getName')->willReturn('name');
- $nonMoveableMountPermssions->method('getInternalPath')->willReturn('');
- $nonMoveableMountPermssions->method('getOwner')
- ->willReturn($owner);
- $nonMoveableMountPermssions->method('getStorage')
- ->willReturn($nonMovableStorage);
-
- $data[] = [$this->createShare(null, IShare::TYPE_USER, $nonMoveableMountPermssions, $user2, $user0, $user0, 11, null, null), 'Cannot increase permissions of path', false];
- $data[] = [$this->createShare(null, IShare::TYPE_GROUP, $nonMoveableMountPermssions, $group0, $user0, $user0, 11, null, null), 'Cannot increase permissions of path', false];
-
- $rootFolder = $this->createMock(Folder::class);
- $rootFolder->method('isShareable')->willReturn(true);
- $rootFolder->method('getPermissions')->willReturn(\OCP\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];
- $data[] = [$this->createShare(null, IShare::TYPE_GROUP, $rootFolder, $group0, $user0, $user0, 2, null, null), 'You cannot share your root folder', true];
- $data[] = [$this->createShare(null, IShare::TYPE_LINK, $rootFolder, null, $user0, $user0, 16, null, null), 'You cannot share your root folder', true];
-
- $allPermssions = $this->createMock(Folder::class);
- $allPermssions->method('isShareable')->willReturn(true);
- $allPermssions->method('getPermissions')->willReturn(\OCP\Constants::PERMISSION_ALL);
- $allPermssions->method('getId')->willReturn(108);
- $allPermssions->method('getOwner')
- ->willReturn($owner);
- $allPermssions->method('getStorage')
- ->willReturn($storage);
-
- $data[] = [$this->createShare(null, IShare::TYPE_USER, $allPermssions, $user2, $user0, $user0, 30, null, null), 'Shares need at least read permissions', true];
- $data[] = [$this->createShare(null, IShare::TYPE_GROUP, $allPermssions, $group0, $user0, $user0, 2, null, null), 'Shares need at least read permissions', true];
-
- $data[] = [$this->createShare(null, IShare::TYPE_USER, $allPermssions, $user2, $user0, $user0, 31, null, null), null, false];
- $data[] = [$this->createShare(null, IShare::TYPE_GROUP, $allPermssions, $group0, $user0, $user0, 3, null, null), null, false];
- $data[] = [$this->createShare(null, IShare::TYPE_LINK, $allPermssions, null, $user0, $user0, 17, null, null), null, false];
-
-
- $remoteStorage = $this->createMock(Storage\IStorage::class);
- $remoteStorage->method('instanceOfStorage')
- ->with(\OCA\Files_Sharing\External\Storage::class)
- ->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('getId')->willReturn(108);
- $remoteFile->method('getOwner')
- ->willReturn($owner);
- $remoteFile->method('getStorage')
- ->willReturn($storage);
- $data[] = [$this->createShare(null, IShare::TYPE_REMOTE, $remoteFile, $user2, $user0, $user0, 1, null, null), null, false];
- $data[] = [$this->createShare(null, IShare::TYPE_REMOTE, $remoteFile, $user2, $user0, $user0, 3, null, null), null, false];
- $data[] = [$this->createShare(null, IShare::TYPE_REMOTE, $remoteFile, $user2, $user0, $user0, 31, null, null), 'Cannot increase permissions of ', true];
-
- return $data;
- }
-
- /**
- * @dataProvider dataGeneralChecks
- *
- * @param $share
- * @param $exceptionMessage
- * @param $exception
- */
- public function testGeneralChecks($share, $exceptionMessage, $exception) {
- $thrown = null;
-
- $this->userManager->method('userExists')->willReturnMap([
- ['user0', true],
- ['user1', true],
- ]);
-
- $this->groupManager->method('groupExists')->willReturnMap([
- ['group0', true],
- ]);
-
- $userFolder = $this->createMock(Folder::class);
- $userFolder->expects($this->any())
- ->method('getId')
- ->willReturn(42);
- // Id 108 is used in the data to refer to the node of the share.
- $userFolder->method('getById')
- ->with(108)
- ->willReturn([$share->getNode()]);
- $userFolder->expects($this->any())
- ->method('getRelativePath')
- ->willReturnArgument(0);
- $this->rootFolder->method('getUserFolder')->willReturn($userFolder);
-
-
- try {
- self::invokePrivate($this->manager, 'generalCreateChecks', [$share]);
- $thrown = false;
- } catch (\OCP\Share\Exceptions\GenericShareException $e) {
- $this->assertEquals($exceptionMessage, $e->getHint());
- $thrown = true;
- } catch (\InvalidArgumentException $e) {
- $this->assertEquals($exceptionMessage, $e->getMessage());
- $thrown = true;
- }
-
- $this->assertSame($exception, $thrown);
- }
-
-
- public function testGeneralCheckShareRoot() {
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('You cannot share your root folder');
-
- $thrown = null;
-
- $this->userManager->method('userExists')->willReturnMap([
- ['user0', true],
- ['user1', true],
- ]);
-
- $userFolder = $this->createMock(Folder::class);
- $userFolder->method('isSubNode')->with($userFolder)->willReturn(false);
- $this->rootFolder->method('getUserFolder')->willReturn($userFolder);
-
- $share = $this->manager->newShare();
-
- $share->setShareType(IShare::TYPE_USER)
- ->setSharedWith('user0')
- ->setSharedBy('user1')
- ->setNode($userFolder);
-
- self::invokePrivate($this->manager, 'generalCreateChecks', [$share]);
- }
-
- public function validateExpirationDateInternalProvider() {
- return [[IShare::TYPE_USER], [IShare::TYPE_REMOTE], [IShare::TYPE_REMOTE_GROUP]];
- }
-
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
- public function testValidateExpirationDateInternalInPast($shareType) {
- $this->expectException(\OCP\Share\Exceptions\GenericShareException::class);
- $this->expectExceptionMessage('Expiration date is in the past');
-
- // Expire date in the past
- $past = new \DateTime();
- $past->sub(new \DateInterval('P1D'));
-
- $share = $this->manager->newShare();
- $share->setShareType($shareType);
- $share->setExpirationDate($past);
-
- self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
- }
-
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
- public function testValidateExpirationDateInternalEnforceButNotSet($shareType) {
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('Expiration date is enforced');
-
- $share = $this->manager->newShare();
- $share->setProviderId('foo')->setId('bar');
- $share->setShareType($shareType);
- if ($shareType === IShare::TYPE_USER) {
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_default_internal_expire_date', 'no', 'yes'],
- ['core', 'shareapi_enforce_internal_expire_date', 'no', 'yes'],
- ]);
- } else {
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_default_remote_expire_date', 'no', 'yes'],
- ['core', 'shareapi_enforce_remote_expire_date', 'no', 'yes'],
- ]);
- }
-
- self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
- }
-
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
- public function testValidateExpirationDateInternalEnforceButNotEnabledAndNotSet($shareType) {
- $share = $this->manager->newShare();
- $share->setProviderId('foo')->setId('bar');
- $share->setShareType($shareType);
-
- if ($shareType === IShare::TYPE_USER) {
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_enforce_internal_expire_date', 'no', 'yes'],
- ]);
- } else {
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_enforce_remote_expire_date', 'no', 'yes'],
- ]);
- }
-
- self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
-
- $this->assertNull($share->getExpirationDate());
- }
-
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
- public function testValidateExpirationDateInternalEnforceButNotSetNewShare($shareType) {
- $share = $this->manager->newShare();
- $share->setShareType($shareType);
-
- if ($shareType === IShare::TYPE_USER) {
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_enforce_internal_expire_date', 'no', 'yes'],
- ['core', 'shareapi_internal_expire_after_n_days', '7', '3'],
- ['core', 'shareapi_default_internal_expire_date', 'no', 'yes'],
- ['core', 'internal_defaultExpDays', '3', '3'],
- ]);
- } else {
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_enforce_remote_expire_date', 'no', 'yes'],
- ['core', 'shareapi_remote_expire_after_n_days', '7', '3'],
- ['core', 'shareapi_default_remote_expire_date', 'no', 'yes'],
- ['core', 'remote_defaultExpDays', '3', '3'],
- ]);
- }
-
- $expected = new \DateTime('now', $this->timezone);
- $expected->setTime(0, 0, 0);
- $expected->add(new \DateInterval('P3D'));
-
- self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
-
- $this->assertNotNull($share->getExpirationDate());
- $this->assertEquals($expected, $share->getExpirationDate());
- }
-
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
- public function testValidateExpirationDateInternalEnforceRelaxedDefaultButNotSetNewShare($shareType) {
- $share = $this->manager->newShare();
- $share->setShareType($shareType);
-
- if ($shareType === IShare::TYPE_USER) {
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_enforce_internal_expire_date', 'no', 'yes'],
- ['core', 'shareapi_internal_expire_after_n_days', '7', '3'],
- ['core', 'shareapi_default_internal_expire_date', 'no', 'yes'],
- ['core', 'internal_defaultExpDays', '3', '1'],
- ]);
- } else {
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_enforce_remote_expire_date', 'no', 'yes'],
- ['core', 'shareapi_remote_expire_after_n_days', '7', '3'],
- ['core', 'shareapi_default_remote_expire_date', 'no', 'yes'],
- ['core', 'remote_defaultExpDays', '3', '1'],
- ]);
- }
-
- $expected = new \DateTime('now', $this->timezone);
- $expected->setTime(0, 0, 0);
- $expected->add(new \DateInterval('P1D'));
-
- self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
-
- $this->assertNotNull($share->getExpirationDate());
- $this->assertEquals($expected, $share->getExpirationDate());
- }
-
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
- public function testValidateExpirationDateInternalEnforceTooFarIntoFuture($shareType) {
- $this->expectException(\OCP\Share\Exceptions\GenericShareException::class);
- $this->expectExceptionMessage('Cannot set expiration date more than 3 days in the future');
-
- $future = new \DateTime();
- $future->add(new \DateInterval('P7D'));
-
- $share = $this->manager->newShare();
- $share->setShareType($shareType);
- $share->setExpirationDate($future);
-
- if ($shareType === IShare::TYPE_USER) {
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_enforce_internal_expire_date', 'no', 'yes'],
- ['core', 'shareapi_internal_expire_after_n_days', '7', '3'],
- ['core', 'shareapi_default_internal_expire_date', 'no', 'yes'],
- ]);
- } else {
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_enforce_remote_expire_date', 'no', 'yes'],
- ['core', 'shareapi_remote_expire_after_n_days', '7', '3'],
- ['core', 'shareapi_default_remote_expire_date', 'no', 'yes'],
- ]);
- }
-
- self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
- }
-
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
- public function testValidateExpirationDateInternalEnforceValid($shareType) {
- $future = new \DateTime('now', $this->dateTimeZone->getTimeZone());
- $future->add(new \DateInterval('P2D'));
- $future->setTime(1, 2, 3);
-
- $expected = clone $future;
- $expected->setTime(0, 0, 0);
-
- $share = $this->manager->newShare();
- $share->setShareType($shareType);
- $share->setExpirationDate($future);
-
- if ($shareType === IShare::TYPE_USER) {
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_enforce_internal_expire_date', 'no', 'yes'],
- ['core', 'shareapi_internal_expire_after_n_days', '7', '3'],
- ['core', 'shareapi_default_internal_expire_date', 'no', 'yes'],
- ]);
- } else {
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_enforce_remote_expire_date', 'no', 'yes'],
- ['core', 'shareapi_remote_expire_after_n_days', '7', '3'],
- ['core', 'shareapi_default_remote_expire_date', 'no', 'yes'],
- ]);
- }
-
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
- \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener');
- $hookListener->expects($this->once())->method('listener')->with($this->callback(function ($data) use ($future) {
- return $data['expirationDate'] == $future;
- }));
-
- self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
-
- $this->assertEquals($expected, $share->getExpirationDate());
- }
-
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
- public function testValidateExpirationDateInternalNoDefault($shareType) {
- $date = new \DateTime('now', $this->dateTimeZone->getTimeZone());
- $date->add(new \DateInterval('P5D'));
- $date->setTime(1, 2, 3);
-
- $expected = clone $date;
- $expected->setTime(0, 0, 0);
-
- $share = $this->manager->newShare();
- $share->setShareType($shareType);
- $share->setExpirationDate($date);
-
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
- \OCP\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;
- }));
-
- self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
-
- $this->assertEquals($expected, $share->getExpirationDate());
- }
-
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
- public function testValidateExpirationDateInternalNoDateNoDefault($shareType) {
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
- \OCP\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;
- }));
-
- $share = $this->manager->newShare();
- $share->setShareType($shareType);
- $share->setPassword('password');
-
- self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
-
- $this->assertNull($share->getExpirationDate());
- }
-
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
- public function testValidateExpirationDateInternalNoDateDefault($shareType) {
- $share = $this->manager->newShare();
- $share->setShareType($shareType);
-
- $expected = new \DateTime('now', $this->timezone);
- $expected->setTime(0, 0);
- $expected->add(new \DateInterval('P3D'));
- $expected->setTimezone(new \DateTimeZone(date_default_timezone_get()));
-
- if ($shareType === IShare::TYPE_USER) {
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_default_internal_expire_date', 'no', 'yes'],
- ['core', 'shareapi_internal_expire_after_n_days', '7', '3'],
- ['core', 'internal_defaultExpDays', '3', '3'],
- ]);
- } else {
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_default_remote_expire_date', 'no', 'yes'],
- ['core', 'shareapi_remote_expire_after_n_days', '7', '3'],
- ['core', 'remote_defaultExpDays', '3', '3'],
- ]);
- }
-
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
- \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener');
- $hookListener->expects($this->once())->method('listener')->with($this->callback(function ($data) use ($expected) {
- return $data['expirationDate'] == $expected;
- }));
-
- self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
-
- $this->assertEquals($expected, $share->getExpirationDate());
- }
-
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
- public function testValidateExpirationDateInternalDefault($shareType) {
- $future = new \DateTime('now', $this->timezone);
- $future->add(new \DateInterval('P5D'));
- $future->setTime(1, 2, 3);
-
- $expected = clone $future;
- $expected->setTime(0, 0);
-
- $share = $this->manager->newShare();
- $share->setShareType($shareType);
- $share->setExpirationDate($future);
-
- if ($shareType === IShare::TYPE_USER) {
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_default_internal_expire_date', 'no', 'yes'],
- ['core', 'shareapi_internal_expire_after_n_days', '7', '3'],
- ['core', 'internal_defaultExpDays', '3', '1'],
- ]);
- } else {
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_default_remote_expire_date', 'no', 'yes'],
- ['core', 'shareapi_remote_expire_after_n_days', '7', '3'],
- ['core', 'remote_defaultExpDays', '3', '1'],
- ]);
- }
-
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
- \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener');
- $hookListener->expects($this->once())->method('listener')->with($this->callback(function ($data) use ($expected) {
- return $data['expirationDate'] == $expected;
- }));
-
- self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
-
- $this->assertEquals($expected, $share->getExpirationDate());
- }
-
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
- public function testValidateExpirationDateInternalHookModification($shareType) {
- $nextWeek = new \DateTime('now', $this->timezone);
- $nextWeek->add(new \DateInterval('P7D'));
- $nextWeek->setTime(0, 0, 0);
-
- $save = clone $nextWeek;
-
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
- \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener');
- $hookListener->expects($this->once())->method('listener')->willReturnCallback(function ($data) {
- $data['expirationDate']->sub(new \DateInterval('P2D'));
- });
-
- $share = $this->manager->newShare();
- $share->setShareType($shareType);
- $share->setExpirationDate($nextWeek);
-
- self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
-
- $save->sub(new \DateInterval('P2D'));
- $this->assertEquals($save, $share->getExpirationDate());
- }
-
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
- public function testValidateExpirationDateInternalHookException($shareType) {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('Invalid date!');
-
- $nextWeek = new \DateTime();
- $nextWeek->add(new \DateInterval('P7D'));
- $nextWeek->setTime(0, 0, 0);
-
- $share = $this->manager->newShare();
- $share->setShareType($shareType);
- $share->setExpirationDate($nextWeek);
-
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
- \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener');
- $hookListener->expects($this->once())->method('listener')->willReturnCallback(function ($data) {
- $data['accepted'] = false;
- $data['message'] = 'Invalid date!';
- });
-
- self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
- }
-
- /**
- * @dataProvider validateExpirationDateInternalProvider
- */
- public function testValidateExpirationDateInternalExistingShareNoDefault($shareType) {
- $share = $this->manager->newShare();
- $share->setShareType($shareType);
- $share->setId('42')->setProviderId('foo');
-
- if ($shareType === IShare::TYPE_USER) {
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_default_internal_expire_date', 'no', 'yes'],
- ['core', 'shareapi_internal_expire_after_n_days', '7', '6'],
- ]);
- } else {
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_default_remote_expire_date', 'no', 'yes'],
- ['core', 'shareapi_remote_expire_after_n_days', '7', '6'],
- ]);
- }
-
- self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
-
- $this->assertEquals(null, $share->getExpirationDate());
- }
-
- public function testValidateExpirationDateInPast() {
- $this->expectException(\OCP\Share\Exceptions\GenericShareException::class);
- $this->expectExceptionMessage('Expiration date is in the past');
-
- // Expire date in the past
- $past = new \DateTime();
- $past->sub(new \DateInterval('P1D'));
-
- $share = $this->manager->newShare();
- $share->setExpirationDate($past);
-
- self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
- }
-
- public function testValidateExpirationDateEnforceButNotSet() {
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('Expiration date is enforced');
-
- $share = $this->manager->newShare();
- $share->setProviderId('foo')->setId('bar');
-
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_default_expire_date', 'no', 'yes'],
- ['core', 'shareapi_enforce_expire_date', 'no', 'yes'],
- ]);
-
- self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
- }
-
- public function testValidateExpirationDateEnforceButNotEnabledAndNotSet() {
- $share = $this->manager->newShare();
- $share->setProviderId('foo')->setId('bar');
-
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_enforce_expire_date', 'no', 'yes'],
- ]);
-
- self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
-
- $this->assertNull($share->getExpirationDate());
- }
-
- public function testValidateExpirationDateEnforceButNotSetNewShare() {
- $share = $this->manager->newShare();
-
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_enforce_expire_date', 'no', 'yes'],
- ['core', 'shareapi_expire_after_n_days', '7', '3'],
- ['core', 'shareapi_default_expire_date', 'no', 'yes'],
- ['core', 'link_defaultExpDays', '3', '3'],
- ]);
-
- $expected = new \DateTime('now', $this->timezone);
- $expected->setTime(0, 0, 0);
- $expected->add(new \DateInterval('P3D'));
-
- self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
-
- $this->assertNotNull($share->getExpirationDate());
- $this->assertEquals($expected, $share->getExpirationDate());
- }
-
- public function testValidateExpirationDateEnforceRelaxedDefaultButNotSetNewShare() {
- $share = $this->manager->newShare();
-
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_enforce_expire_date', 'no', 'yes'],
- ['core', 'shareapi_expire_after_n_days', '7', '3'],
- ['core', 'shareapi_default_expire_date', 'no', 'yes'],
- ['core', 'link_defaultExpDays', '3', '1'],
- ]);
-
- $expected = new \DateTime('now', $this->timezone);
- $expected->setTime(0, 0, 0);
- $expected->add(new \DateInterval('P1D'));
-
- self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
-
- $this->assertNotNull($share->getExpirationDate());
- $this->assertEquals($expected, $share->getExpirationDate());
- }
-
- public function testValidateExpirationDateEnforceTooFarIntoFuture() {
- $this->expectException(\OCP\Share\Exceptions\GenericShareException::class);
- $this->expectExceptionMessage('Cannot set expiration date more than 3 days in the future');
-
- $future = new \DateTime();
- $future->add(new \DateInterval('P7D'));
-
- $share = $this->manager->newShare();
- $share->setExpirationDate($future);
-
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_enforce_expire_date', 'no', 'yes'],
- ['core', 'shareapi_expire_after_n_days', '7', '3'],
- ['core', 'shareapi_default_expire_date', 'no', 'yes'],
- ]);
-
- self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
- }
-
- public function testValidateExpirationDateEnforceValid() {
- $future = new \DateTime('now', $this->timezone);
- $future->add(new \DateInterval('P2D'));
- $future->setTime(1, 2, 3);
-
- $expected = clone $future;
- $expected->setTime(0, 0, 0);
-
- $share = $this->manager->newShare();
- $share->setExpirationDate($future);
-
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_enforce_expire_date', 'no', 'yes'],
- ['core', 'shareapi_expire_after_n_days', '7', '3'],
- ['core', 'shareapi_default_expire_date', 'no', 'yes'],
- ]);
-
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
- \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener');
- $hookListener->expects($this->once())->method('listener')->with($this->callback(function ($data) use ($future) {
- return $data['expirationDate'] == $future;
- }));
-
- self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
-
- $this->assertEquals($expected, $share->getExpirationDate());
- }
-
- public function testValidateExpirationDateNoDefault() {
- $date = new \DateTime('now', $this->timezone);
- $date->add(new \DateInterval('P5D'));
- $date->setTime(1, 2, 3);
-
- $expected = clone $date;
- $expected->setTime(0, 0);
- $expected->setTimezone(new \DateTimeZone(date_default_timezone_get()));
-
- $share = $this->manager->newShare();
- $share->setExpirationDate($date);
-
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
- \OCP\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;
- }));
-
- self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
-
- $this->assertEquals($expected, $share->getExpirationDate());
- }
-
- public function testValidateExpirationDateNoDateNoDefault() {
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
- \OCP\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;
- }));
-
- $share = $this->manager->newShare();
- $share->setPassword('password');
-
- self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
-
- $this->assertNull($share->getExpirationDate());
- }
-
- public function testValidateExpirationDateNoDateDefault() {
- $share = $this->manager->newShare();
-
- $expected = new \DateTime('now', $this->timezone);
- $expected->add(new \DateInterval('P3D'));
- $expected->setTime(0, 0);
- $expected->setTimezone(new \DateTimeZone(date_default_timezone_get()));
-
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_default_expire_date', 'no', 'yes'],
- ['core', 'shareapi_expire_after_n_days', '7', '3'],
- ['core', 'link_defaultExpDays', '3', '3'],
- ]);
-
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
- \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener');
- $hookListener->expects($this->once())->method('listener')->with($this->callback(function ($data) use ($expected) {
- return $data['expirationDate'] == $expected;
- }));
-
- self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
-
- $this->assertEquals($expected, $share->getExpirationDate());
- }
-
- public function testValidateExpirationDateDefault() {
- $future = new \DateTime('now', $this->timezone);
- $future->add(new \DateInterval('P5D'));
- $future->setTime(1, 2, 3);
-
- $expected = clone $future;
- $expected->setTime(0, 0);
- $expected->setTimezone(new \DateTimeZone(date_default_timezone_get()));
-
- $share = $this->manager->newShare();
- $share->setExpirationDate($future);
-
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_default_expire_date', 'no', 'yes'],
- ['core', 'shareapi_expire_after_n_days', '7', '3'],
- ['core', 'link_defaultExpDays', '3', '1'],
- ]);
-
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
- \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener');
- $hookListener->expects($this->once())->method('listener')->with($this->callback(function ($data) use ($expected) {
- return $data['expirationDate'] == $expected;
- }));
-
- self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
-
- $this->assertEquals($expected, $share->getExpirationDate());
- }
-
- public function testValidateExpirationNegativeOffsetTimezone() {
- $this->timezone = new \DateTimeZone('Pacific/Tahiti');
- $future = new \DateTime();
- $future->add(new \DateInterval('P5D'));
-
- $expected = clone $future;
- $expected->setTimezone($this->timezone);
- $expected->setTime(0, 0);
- $expected->setTimezone(new \DateTimeZone(date_default_timezone_get()));
-
- $share = $this->manager->newShare();
- $share->setExpirationDate($future);
-
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_default_expire_date', 'no', 'yes'],
- ['core', 'shareapi_expire_after_n_days', '7', '3'],
- ['core', 'link_defaultExpDays', '3', '1'],
- ]);
-
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
- \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener');
- $hookListener->expects($this->once())->method('listener')->with($this->callback(function ($data) use ($expected) {
- return $data['expirationDate'] == $expected;
- }));
-
- self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
-
- $this->assertEquals($expected, $share->getExpirationDate());
- }
-
- public function testValidateExpirationDateHookModification() {
- $nextWeek = new \DateTime('now', $this->timezone);
- $nextWeek->add(new \DateInterval('P7D'));
-
- $save = clone $nextWeek;
- $save->setTime(0, 0);
- $save->sub(new \DateInterval('P2D'));
- $save->setTimezone(new \DateTimeZone(date_default_timezone_get()));
-
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
- \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener');
- $hookListener->expects($this->once())->method('listener')->willReturnCallback(function ($data) {
- $data['expirationDate']->sub(new \DateInterval('P2D'));
- });
-
- $share = $this->manager->newShare();
- $share->setExpirationDate($nextWeek);
-
- self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
-
- $this->assertEquals($save, $share->getExpirationDate());
- }
-
- public function testValidateExpirationDateHookException() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('Invalid date!');
-
- $nextWeek = new \DateTime();
- $nextWeek->add(new \DateInterval('P7D'));
- $nextWeek->setTime(0, 0, 0);
-
- $share = $this->manager->newShare();
- $share->setExpirationDate($nextWeek);
-
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
- \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener');
- $hookListener->expects($this->once())->method('listener')->willReturnCallback(function ($data) {
- $data['accepted'] = false;
- $data['message'] = 'Invalid date!';
- });
-
- self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
- }
-
- public function testValidateExpirationDateExistingShareNoDefault() {
- $share = $this->manager->newShare();
-
- $share->setId('42')->setProviderId('foo');
-
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_default_expire_date', 'no', 'yes'],
- ['core', 'shareapi_expire_after_n_days', '7', '6'],
- ]);
-
- self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
-
- $this->assertEquals(null, $share->getExpirationDate());
- }
-
- public function testUserCreateChecksShareWithGroupMembersOnlyDifferentGroups() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('Sharing is only allowed with group members');
-
- $share = $this->manager->newShare();
-
- $sharedBy = $this->createMock(IUser::class);
- $sharedWith = $this->createMock(IUser::class);
- $share->setSharedBy('sharedBy')->setSharedWith('sharedWith');
-
- $this->groupManager
- ->method('getUserGroupIds')
- ->willReturnMap(
- [
- [$sharedBy, ['group1']],
- [$sharedWith, ['group2']],
- ]
- );
-
- $this->userManager->method('get')->willReturnMap([
- ['sharedBy', $sharedBy],
- ['sharedWith', $sharedWith],
- ]);
-
- $this->config
- ->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_only_share_with_group_members', 'no', 'yes'],
- ['core', 'shareapi_only_share_with_group_members_exclude_group_list', '', '[]'],
- ]);
-
- self::invokePrivate($this->manager, 'userCreateChecks', [$share]);
- }
-
- public function testUserCreateChecksShareWithGroupMembersOnlySharedGroup() {
- $share = $this->manager->newShare();
-
- $sharedBy = $this->createMock(IUser::class);
- $sharedWith = $this->createMock(IUser::class);
- $share->setSharedBy('sharedBy')->setSharedWith('sharedWith');
-
- $path = $this->createMock(Node::class);
- $share->setNode($path);
-
- $this->groupManager
- ->method('getUserGroupIds')
- ->willReturnMap(
- [
- [$sharedBy, ['group1', 'group3']],
- [$sharedWith, ['group2', 'group3']],
- ]
- );
-
- $this->userManager->method('get')->willReturnMap([
- ['sharedBy', $sharedBy],
- ['sharedWith', $sharedWith],
- ]);
-
- $this->config
- ->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_only_share_with_group_members', 'no', 'yes'],
- ['core', 'shareapi_only_share_with_group_members_exclude_group_list', '', '[]'],
- ]);
-
- $this->defaultProvider
- ->method('getSharesByPath')
- ->with($path)
- ->willReturn([]);
-
- self::invokePrivate($this->manager, 'userCreateChecks', [$share]);
- $this->addToAssertionCount(1);
- }
-
-
- public function testUserCreateChecksIdenticalShareExists() {
- $this->expectException(AlreadySharedException::class);
- $this->expectExceptionMessage('Sharing name.txt failed, because this item is already shared with the account user');
-
- $share = $this->manager->newShare();
- $share->setSharedWithDisplayName('user');
- $share2 = $this->manager->newShare();
-
- $sharedWith = $this->createMock(IUser::class);
- $path = $this->createMock(Node::class);
-
- $share->setSharedWith('sharedWith')->setNode($path)
- ->setProviderId('foo')->setId('bar');
-
- $share2->setSharedWith('sharedWith')->setNode($path)
- ->setProviderId('foo')->setId('baz');
-
- $this->defaultProvider
- ->method('getSharesByPath')
- ->with($path)
- ->willReturn([$share2]);
-
- $path->method('getName')
- ->willReturn('name.txt');
-
- self::invokePrivate($this->manager, 'userCreateChecks', [$share]);
- }
-
-
- public function testUserCreateChecksIdenticalPathSharedViaGroup() {
- $this->expectException(AlreadySharedException::class);
- $this->expectExceptionMessage('Sharing name2.txt failed, because this item is already shared with the account userName');
-
- $share = $this->manager->newShare();
-
- $sharedWith = $this->createMock(IUser::class);
- $sharedWith->method('getUID')->willReturn('sharedWith');
-
- $this->userManager->method('get')->with('sharedWith')->willReturn($sharedWith);
-
- $path = $this->createMock(Node::class);
-
- $share->setSharedWith('sharedWith')
- ->setNode($path)
- ->setShareOwner('shareOwner')
- ->setSharedWithDisplayName('userName')
- ->setProviderId('foo')
- ->setId('bar');
-
- $share2 = $this->manager->newShare();
- $share2->setShareType(IShare::TYPE_GROUP)
- ->setShareOwner('shareOwner2')
- ->setProviderId('foo')
- ->setId('baz')
- ->setSharedWith('group');
-
- $group = $this->createMock(IGroup::class);
- $group->method('inGroup')
- ->with($sharedWith)
- ->willReturn(true);
-
- $this->groupManager->method('get')->with('group')->willReturn($group);
-
- $this->defaultProvider
- ->method('getSharesByPath')
- ->with($path)
- ->willReturn([$share2]);
-
- $path->method('getName')
- ->willReturn('name2.txt');
-
- self::invokePrivate($this->manager, 'userCreateChecks', [$share]);
- }
-
- public function testUserCreateChecksIdenticalPathSharedViaDeletedGroup() {
- $share = $this->manager->newShare();
-
- $sharedWith = $this->createMock(IUser::class);
- $sharedWith->method('getUID')->willReturn('sharedWith');
-
- $this->userManager->method('get')->with('sharedWith')->willReturn($sharedWith);
-
- $path = $this->createMock(Node::class);
-
- $share->setSharedWith('sharedWith')
- ->setNode($path)
- ->setShareOwner('shareOwner')
- ->setProviderId('foo')
- ->setId('bar');
-
- $share2 = $this->manager->newShare();
- $share2->setShareType(IShare::TYPE_GROUP)
- ->setShareOwner('shareOwner2')
- ->setProviderId('foo')
- ->setId('baz')
- ->setSharedWith('group');
-
- $this->groupManager->method('get')->with('group')->willReturn(null);
-
- $this->defaultProvider
- ->method('getSharesByPath')
- ->with($path)
- ->willReturn([$share2]);
-
- $this->assertNull($this->invokePrivate($this->manager, 'userCreateChecks', [$share]));
- }
-
- public function testUserCreateChecksIdenticalPathNotSharedWithUser() {
- $share = $this->manager->newShare();
- $sharedWith = $this->createMock(IUser::class);
- $path = $this->createMock(Node::class);
- $share->setSharedWith('sharedWith')
- ->setNode($path)
- ->setShareOwner('shareOwner')
- ->setProviderId('foo')
- ->setId('bar');
-
- $this->userManager->method('get')->with('sharedWith')->willReturn($sharedWith);
-
- $share2 = $this->manager->newShare();
- $share2->setShareType(IShare::TYPE_GROUP)
- ->setShareOwner('shareOwner2')
- ->setProviderId('foo')
- ->setId('baz');
-
- $group = $this->createMock(IGroup::class);
- $group->method('inGroup')
- ->with($sharedWith)
- ->willReturn(false);
-
- $this->groupManager->method('get')->with('group')->willReturn($group);
-
- $share2->setSharedWith('group');
-
- $this->defaultProvider
- ->method('getSharesByPath')
- ->with($path)
- ->willReturn([$share2]);
-
- self::invokePrivate($this->manager, 'userCreateChecks', [$share]);
- $this->addToAssertionCount(1);
- }
-
-
- public function testGroupCreateChecksShareWithGroupMembersGroupSharingNotAllowed() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('Group sharing is now allowed');
-
- $share = $this->manager->newShare();
-
- $this->config
- ->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_allow_group_sharing', 'yes', 'no'],
- ]);
-
- self::invokePrivate($this->manager, 'groupCreateChecks', [$share]);
- }
-
-
- public function testGroupCreateChecksShareWithGroupMembersOnlyNotInGroup() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('Sharing is only allowed within your own groups');
-
- $share = $this->manager->newShare();
-
- $user = $this->createMock(IUser::class);
- $group = $this->createMock(IGroup::class);
- $share->setSharedBy('user')->setSharedWith('group');
-
- $group->method('inGroup')->with($user)->willReturn(false);
-
- $this->groupManager->method('get')->with('group')->willReturn($group);
- $this->userManager->method('get')->with('user')->willReturn($user);
-
- $this->config
- ->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_only_share_with_group_members', 'no', 'yes'],
- ['core', 'shareapi_allow_group_sharing', 'yes', 'yes'],
- ['core', 'shareapi_only_share_with_group_members_exclude_group_list', '', '[]'],
- ]);
-
- self::invokePrivate($this->manager, 'groupCreateChecks', [$share]);
- }
-
-
- public function testGroupCreateChecksShareWithGroupMembersOnlyNullGroup() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('Sharing is only allowed within your own groups');
-
- $share = $this->manager->newShare();
-
- $user = $this->createMock(IUser::class);
- $share->setSharedBy('user')->setSharedWith('group');
-
- $this->groupManager->method('get')->with('group')->willReturn(null);
- $this->userManager->method('get')->with('user')->willReturn($user);
-
- $this->config
- ->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_only_share_with_group_members', 'no', 'yes'],
- ['core', 'shareapi_allow_group_sharing', 'yes', 'yes'],
- ['core', 'shareapi_only_share_with_group_members_exclude_group_list', '', '[]'],
- ]);
-
- $this->assertNull($this->invokePrivate($this->manager, 'groupCreateChecks', [$share]));
- }
-
- public function testGroupCreateChecksShareWithGroupMembersOnlyInGroup() {
- $share = $this->manager->newShare();
-
- $user = $this->createMock(IUser::class);
- $group = $this->createMock(IGroup::class);
- $share->setSharedBy('user')->setSharedWith('group');
-
- $this->userManager->method('get')->with('user')->willReturn($user);
- $this->groupManager->method('get')->with('group')->willReturn($group);
-
- $group->method('inGroup')->with($user)->willReturn(true);
-
- $path = $this->createMock(Node::class);
- $share->setNode($path);
-
- $this->defaultProvider->method('getSharesByPath')
- ->with($path)
- ->willReturn([]);
-
- $this->config
- ->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_only_share_with_group_members', 'no', 'yes'],
- ['core', 'shareapi_allow_group_sharing', 'yes', 'yes'],
- ['core', 'shareapi_only_share_with_group_members_exclude_group_list', '', '[]'],
- ]);
-
- self::invokePrivate($this->manager, 'groupCreateChecks', [$share]);
- $this->addToAssertionCount(1);
- }
-
-
- public function testGroupCreateChecksPathAlreadySharedWithSameGroup() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('Path is already shared with this group');
-
- $share = $this->manager->newShare();
-
- $path = $this->createMock(Node::class);
- $share->setSharedWith('sharedWith')
- ->setNode($path)
- ->setProviderId('foo')
- ->setId('bar');
-
- $share2 = $this->manager->newShare();
- $share2->setSharedWith('sharedWith')
- ->setProviderId('foo')
- ->setId('baz');
-
- $this->defaultProvider->method('getSharesByPath')
- ->with($path)
- ->willReturn([$share2]);
-
- $this->config
- ->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_allow_group_sharing', 'yes', 'yes'],
- ]);
-
- self::invokePrivate($this->manager, 'groupCreateChecks', [$share]);
- }
-
- public function testGroupCreateChecksPathAlreadySharedWithDifferentGroup() {
- $share = $this->manager->newShare();
-
- $share->setSharedWith('sharedWith');
-
- $path = $this->createMock(Node::class);
- $share->setNode($path);
-
- $share2 = $this->manager->newShare();
- $share2->setSharedWith('sharedWith2');
-
- $this->defaultProvider->method('getSharesByPath')
- ->with($path)
- ->willReturn([$share2]);
-
- $this->config
- ->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_allow_group_sharing', 'yes', 'yes'],
- ]);
-
- self::invokePrivate($this->manager, 'groupCreateChecks', [$share]);
- $this->addToAssertionCount(1);
- }
-
-
- public function testLinkCreateChecksNoLinkSharesAllowed() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('Link sharing is not allowed');
-
- $share = $this->manager->newShare();
-
- $this->config
- ->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_allow_links', 'yes', 'no'],
- ]);
-
- self::invokePrivate($this->manager, 'linkCreateChecks', [$share]);
- }
-
-
- public function testFileLinkCreateChecksNoPublicUpload() {
- $share = $this->manager->newShare();
-
- $share->setPermissions(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE);
- $share->setNodeType('file');
-
- $this->config
- ->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_allow_links', 'yes', 'yes'],
- ['core', 'shareapi_allow_public_upload', 'yes', 'no']
- ]);
-
- self::invokePrivate($this->manager, 'linkCreateChecks', [$share]);
- $this->addToAssertionCount(1);
- }
-
- public function testFolderLinkCreateChecksNoPublicUpload() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('Public upload is not allowed');
-
- $share = $this->manager->newShare();
-
- $share->setPermissions(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE);
- $share->setNodeType('folder');
-
- $this->config
- ->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_allow_links', 'yes', 'yes'],
- ['core', 'shareapi_allow_public_upload', 'yes', 'no']
- ]);
-
- self::invokePrivate($this->manager, 'linkCreateChecks', [$share]);
- }
-
- public function testLinkCreateChecksPublicUpload() {
- $share = $this->manager->newShare();
-
- $share->setPermissions(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE);
- $share->setSharedWith('sharedWith');
- $folder = $this->createMock(\OC\Files\Node\Folder::class);
- $share->setNode($folder);
-
- $this->config
- ->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_allow_links', 'yes', 'yes'],
- ['core', 'shareapi_allow_public_upload', 'yes', 'yes']
- ]);
-
- self::invokePrivate($this->manager, 'linkCreateChecks', [$share]);
- $this->addToAssertionCount(1);
- }
-
- public function testLinkCreateChecksReadOnly() {
- $share = $this->manager->newShare();
-
- $share->setPermissions(\OCP\Constants::PERMISSION_READ);
- $share->setSharedWith('sharedWith');
- $folder = $this->createMock(\OC\Files\Node\Folder::class);
- $share->setNode($folder);
-
- $this->config
- ->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_allow_links', 'yes', 'yes'],
- ['core', 'shareapi_allow_public_upload', 'yes', 'no']
- ]);
-
- self::invokePrivate($this->manager, 'linkCreateChecks', [$share]);
- $this->addToAssertionCount(1);
- }
-
-
- public function testPathCreateChecksContainsSharedMount() {
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('Path contains files shared with you');
-
- $path = $this->createMock(Folder::class);
- $path->method('getPath')->willReturn('path');
-
- $mount = $this->createMock(IMountPoint::class);
- $storage = $this->createMock(Storage::class);
- $mount->method('getStorage')->willReturn($storage);
- $storage->method('instanceOfStorage')->with(\OCA\Files_Sharing\ISharedStorage::class)->willReturn(true);
-
- $this->mountManager->method('findIn')->with('path')->willReturn([$mount]);
-
- self::invokePrivate($this->manager, 'pathCreateChecks', [$path]);
- }
-
- public function testPathCreateChecksContainsNoSharedMount() {
- $path = $this->createMock(Folder::class);
- $path->method('getPath')->willReturn('path');
-
- $mount = $this->createMock(IMountPoint::class);
- $storage = $this->createMock(Storage::class);
- $mount->method('getStorage')->willReturn($storage);
- $storage->method('instanceOfStorage')->with(\OCA\Files_Sharing\ISharedStorage::class)->willReturn(false);
-
- $this->mountManager->method('findIn')->with('path')->willReturn([$mount]);
-
- self::invokePrivate($this->manager, 'pathCreateChecks', [$path]);
- $this->addToAssertionCount(1);
- }
-
- public function testPathCreateChecksContainsNoFolder() {
- $path = $this->createMock(File::class);
-
- self::invokePrivate($this->manager, 'pathCreateChecks', [$path]);
- $this->addToAssertionCount(1);
- }
-
- public function dataIsSharingDisabledForUser() {
- $data = [];
-
- // No exclude groups
- $data[] = ['no', null, null, [], false];
-
- // empty exclude / allow list, user no groups
- $data[] = ['yes', '', json_encode(['']), [], false];
- $data[] = ['allow', '', json_encode(['']), [], true];
-
- // empty exclude / allow list, user groups
- $data[] = ['yes', '', json_encode(['']), ['group1', 'group2'], false];
- $data[] = ['allow', '', json_encode(['']), ['group1', 'group2'], true];
-
- // Convert old list to json
- $data[] = ['yes', 'group1,group2', json_encode(['group1', 'group2']), [], false];
- $data[] = ['allow', 'group1,group2', json_encode(['group1', 'group2']), [], true];
-
- // Old list partly groups in common
- $data[] = ['yes', 'group1,group2', json_encode(['group1', 'group2']), ['group1', 'group3'], false];
- $data[] = ['allow', 'group1,group2', json_encode(['group1', 'group2']), ['group1', 'group3'], false];
-
- // Old list only groups in common
- $data[] = ['yes', 'group1,group2', json_encode(['group1', 'group2']), ['group1'], true];
- $data[] = ['allow', 'group1,group2', json_encode(['group1', 'group2']), ['group1'], false];
-
- // New list partly in common
- $data[] = ['yes', json_encode(['group1', 'group2']), null, ['group1', 'group3'], false];
- $data[] = ['allow', json_encode(['group1', 'group2']), null, ['group1', 'group3'], false];
-
- // New list only groups in common
- $data[] = ['yes', json_encode(['group1', 'group2']), null, ['group2'], true];
- $data[] = ['allow', json_encode(['group1', 'group2']), null, ['group2'], false];
-
- return $data;
- }
-
- /**
- * @dataProvider dataIsSharingDisabledForUser
- *
- * @param string $excludeGroups
- * @param string $groupList
- * @param string $setList
- * @param string[] $groupIds
- * @param bool $expected
- */
- public function testIsSharingDisabledForUser($excludeGroups, $groupList, $setList, $groupIds, $expected) {
- $user = $this->createMock(IUser::class);
-
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_exclude_groups', 'no', $excludeGroups],
- ['core', 'shareapi_exclude_groups_list', '', $groupList],
- ]);
-
- if ($setList !== null) {
- $this->config->expects($this->once())
- ->method('setAppValue')
- ->with('core', 'shareapi_exclude_groups_list', $setList);
- } else {
- $this->config->expects($this->never())
- ->method('setAppValue');
- }
-
- $this->groupManager->method('getUserGroupIds')
- ->with($user)
- ->willReturn($groupIds);
-
- $this->userManager->method('get')->with('user')->willReturn($user);
-
- $res = $this->manager->sharingDisabledForUser('user');
- $this->assertEquals($expected, $res);
- }
-
- public function dataCanShare() {
- $data = [];
-
- /*
- * [expected, sharing enabled, disabled for user]
- */
-
- $data[] = [false, 'no', false];
- $data[] = [false, 'no', true];
- $data[] = [true, 'yes', false];
- $data[] = [false, 'yes', true];
-
- return $data;
- }
-
- /**
- * @dataProvider dataCanShare
- *
- * @param bool $expected
- * @param string $sharingEnabled
- * @param bool $disabledForUser
- */
- public function testCanShare($expected, $sharingEnabled, $disabledForUser) {
- $this->config->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_enabled', 'yes', $sharingEnabled],
- ]);
-
- $manager = $this->createManagerMock()
- ->setMethods(['sharingDisabledForUser'])
- ->getMock();
-
- $manager->method('sharingDisabledForUser')
- ->with('user')
- ->willReturn($disabledForUser);
-
- $share = $this->manager->newShare();
- $share->setSharedBy('user');
-
- $exception = false;
- try {
- $res = self::invokePrivate($manager, 'canShare', [$share]);
- } catch (\Exception $e) {
- $exception = true;
- }
-
- $this->assertEquals($expected, !$exception);
- }
-
- public function testCreateShareUser() {
- $manager = $this->createManagerMock()
- ->setMethods(['canShare', 'generalCreateChecks', 'userCreateChecks', 'pathCreateChecks'])
- ->getMock();
-
- $shareOwner = $this->createMock(IUser::class);
- $shareOwner->method('getUID')->willReturn('shareOwner');
-
- $storage = $this->createMock(Storage::class);
- $path = $this->createMock(File::class);
- $path->method('getOwner')->willReturn($shareOwner);
- $path->method('getName')->willReturn('target');
- $path->method('getStorage')->willReturn($storage);
-
- $share = $this->createShare(
- null,
- IShare::TYPE_USER,
- $path,
- 'sharedWith',
- 'sharedBy',
- null,
- \OCP\Constants::PERMISSION_ALL);
-
- $manager->expects($this->once())
- ->method('canShare')
- ->with($share)
- ->willReturn(true);
- $manager->expects($this->once())
- ->method('generalCreateChecks')
- ->with($share);
- ;
- $manager->expects($this->once())
- ->method('userCreateChecks')
- ->with($share);
- ;
- $manager->expects($this->once())
- ->method('pathCreateChecks')
- ->with($path);
-
- $this->defaultProvider
- ->expects($this->once())
- ->method('create')
- ->with($share)
- ->willReturnArgument(0);
-
- $share->expects($this->once())
- ->method('setShareOwner')
- ->with('shareOwner');
- $share->expects($this->once())
- ->method('setTarget')
- ->with('/target');
-
- $manager->createShare($share);
- }
-
- public function testCreateShareGroup() {
- $manager = $this->createManagerMock()
- ->setMethods(['canShare', 'generalCreateChecks', 'groupCreateChecks', 'pathCreateChecks'])
- ->getMock();
-
- $shareOwner = $this->createMock(IUser::class);
- $shareOwner->method('getUID')->willReturn('shareOwner');
-
- $storage = $this->createMock(Storage::class);
- $path = $this->createMock(File::class);
- $path->method('getOwner')->willReturn($shareOwner);
- $path->method('getName')->willReturn('target');
- $path->method('getStorage')->willReturn($storage);
-
- $share = $this->createShare(
- null,
- IShare::TYPE_GROUP,
- $path,
- 'sharedWith',
- 'sharedBy',
- null,
- \OCP\Constants::PERMISSION_ALL);
-
- $manager->expects($this->once())
- ->method('canShare')
- ->with($share)
- ->willReturn(true);
- $manager->expects($this->once())
- ->method('generalCreateChecks')
- ->with($share);
- ;
- $manager->expects($this->once())
- ->method('groupCreateChecks')
- ->with($share);
- ;
- $manager->expects($this->once())
- ->method('pathCreateChecks')
- ->with($path);
-
- $this->defaultProvider
- ->expects($this->once())
- ->method('create')
- ->with($share)
- ->willReturnArgument(0);
-
- $share->expects($this->once())
- ->method('setShareOwner')
- ->with('shareOwner');
- $share->expects($this->once())
- ->method('setTarget')
- ->with('/target');
-
- $manager->createShare($share);
- }
-
- public function testCreateShareLink() {
- $manager = $this->createManagerMock()
- ->setMethods([
- 'canShare',
- 'generalCreateChecks',
- 'linkCreateChecks',
- 'pathCreateChecks',
- 'validateExpirationDateLink',
- 'verifyPassword',
- 'setLinkParent',
- ])
- ->getMock();
-
- $shareOwner = $this->createMock(IUser::class);
- $shareOwner->method('getUID')->willReturn('shareOwner');
-
- $storage = $this->createMock(Storage::class);
- $path = $this->createMock(File::class);
- $path->method('getOwner')->willReturn($shareOwner);
- $path->method('getName')->willReturn('target');
- $path->method('getId')->willReturn(1);
- $path->method('getStorage')->willReturn($storage);
-
- $date = new \DateTime();
-
- $share = $this->manager->newShare();
- $share->setShareType(IShare::TYPE_LINK)
- ->setNode($path)
- ->setSharedBy('sharedBy')
- ->setPermissions(\OCP\Constants::PERMISSION_ALL)
- ->setExpirationDate($date)
- ->setPassword('password');
-
- $manager->expects($this->once())
- ->method('canShare')
- ->with($share)
- ->willReturn(true);
- $manager->expects($this->once())
- ->method('generalCreateChecks')
- ->with($share);
- ;
- $manager->expects($this->once())
- ->method('linkCreateChecks')
- ->with($share);
- ;
- $manager->expects($this->once())
- ->method('pathCreateChecks')
- ->with($path);
- $manager->expects($this->once())
- ->method('validateExpirationDateLink')
- ->with($share)
- ->willReturn($share);
- $manager->expects($this->once())
- ->method('verifyPassword')
- ->with('password');
- $manager->expects($this->once())
- ->method('setLinkParent')
- ->with($share);
-
- $this->hasher->expects($this->once())
- ->method('hash')
- ->with('password')
- ->willReturn('hashed');
-
- $this->secureRandom->method('generate')
- ->willReturn('token');
-
- $this->defaultProvider
- ->expects($this->once())
- ->method('create')
- ->with($share)
- ->willReturnCallback(function (Share $share) {
- return $share->setId(42);
- });
-
- $this->dispatcher->expects($this->exactly(2))
- ->method('dispatchTyped')
- ->withConsecutive(
- // Pre share
- [
- $this->callback(function (BeforeShareCreatedEvent $e) use ($path, $date) {
- $share = $e->getShare();
-
- return $share->getShareType() === IShare::TYPE_LINK &&
- $share->getNode() === $path &&
- $share->getSharedBy() === 'sharedBy' &&
- $share->getPermissions() === \OCP\Constants::PERMISSION_ALL &&
- $share->getExpirationDate() === $date &&
- $share->getPassword() === 'hashed' &&
- $share->getToken() === 'token';
- })
- ],
- // Post share
- [
- $this->callback(function (ShareCreatedEvent $e) use ($path, $date) {
- $share = $e->getShare();
-
- return $share->getShareType() === IShare::TYPE_LINK &&
- $share->getNode() === $path &&
- $share->getSharedBy() === 'sharedBy' &&
- $share->getPermissions() === \OCP\Constants::PERMISSION_ALL &&
- $share->getExpirationDate() === $date &&
- $share->getPassword() === 'hashed' &&
- $share->getToken() === 'token' &&
- $share->getId() === '42' &&
- $share->getTarget() === '/target';
- })
- ]
- );
-
- /** @var IShare $share */
- $share = $manager->createShare($share);
-
- $this->assertSame('shareOwner', $share->getShareOwner());
- $this->assertEquals('/target', $share->getTarget());
- $this->assertSame($date, $share->getExpirationDate());
- $this->assertEquals('token', $share->getToken());
- $this->assertEquals('hashed', $share->getPassword());
- }
-
- public function testCreateShareMail() {
- $manager = $this->createManagerMock()
- ->setMethods([
- 'canShare',
- 'generalCreateChecks',
- 'linkCreateChecks',
- 'pathCreateChecks',
- 'validateExpirationDateLink',
- 'verifyPassword',
- 'setLinkParent',
- ])
- ->getMock();
-
- $shareOwner = $this->createMock(IUser::class);
- $shareOwner->method('getUID')->willReturn('shareOwner');
-
- $storage = $this->createMock(Storage::class);
- $path = $this->createMock(File::class);
- $path->method('getOwner')->willReturn($shareOwner);
- $path->method('getName')->willReturn('target');
- $path->method('getId')->willReturn(1);
- $path->method('getStorage')->willReturn($storage);
-
- $share = $this->manager->newShare();
- $share->setShareType(IShare::TYPE_EMAIL)
- ->setNode($path)
- ->setSharedBy('sharedBy')
- ->setPermissions(\OCP\Constants::PERMISSION_ALL);
-
- $manager->expects($this->once())
- ->method('canShare')
- ->with($share)
- ->willReturn(true);
- $manager->expects($this->once())
- ->method('generalCreateChecks')
- ->with($share);
-
- $manager->expects($this->once())
- ->method('linkCreateChecks');
- $manager->expects($this->once())
- ->method('pathCreateChecks')
- ->with($path);
- $manager->expects($this->once())
- ->method('validateExpirationDateLink')
- ->with($share)
- ->willReturn($share);
- $manager->expects($this->once())
- ->method('verifyPassword');
- $manager->expects($this->once())
- ->method('setLinkParent');
-
- $this->secureRandom->method('generate')
- ->willReturn('token');
-
- $this->defaultProvider
- ->expects($this->once())
- ->method('create')
- ->with($share)
- ->willReturnCallback(function (Share $share) {
- return $share->setId(42);
- });
-
- $this->dispatcher->expects($this->exactly(2))
- ->method('dispatchTyped')
- ->withConsecutive(
- [
- $this->callback(function (BeforeShareCreatedEvent $e) use ($path) {
- $share = $e->getShare();
-
- return $share->getShareType() === IShare::TYPE_EMAIL &&
- $share->getNode() === $path &&
- $share->getSharedBy() === 'sharedBy' &&
- $share->getPermissions() === \OCP\Constants::PERMISSION_ALL &&
- $share->getExpirationDate() === null &&
- $share->getPassword() === null &&
- $share->getToken() === 'token';
- })
- ],
- [
- $this->callback(function (ShareCreatedEvent $e) use ($path) {
- $share = $e->getShare();
-
- return $share->getShareType() === IShare::TYPE_EMAIL &&
- $share->getNode() === $path &&
- $share->getSharedBy() === 'sharedBy' &&
- $share->getPermissions() === \OCP\Constants::PERMISSION_ALL &&
- $share->getExpirationDate() === null &&
- $share->getPassword() === null &&
- $share->getToken() === 'token' &&
- $share->getId() === '42' &&
- $share->getTarget() === '/target';
- })
- ],
- );
-
- /** @var IShare $share */
- $share = $manager->createShare($share);
-
- $this->assertSame('shareOwner', $share->getShareOwner());
- $this->assertEquals('/target', $share->getTarget());
- $this->assertEquals('token', $share->getToken());
- }
-
-
- public function testCreateShareHookError() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('I won\'t let you share');
-
- $manager = $this->createManagerMock()
- ->setMethods([
- 'canShare',
- 'generalCreateChecks',
- 'userCreateChecks',
- 'pathCreateChecks',
- ])
- ->getMock();
-
- $shareOwner = $this->createMock(IUser::class);
- $shareOwner->method('getUID')->willReturn('shareOwner');
-
- $storage = $this->createMock(Storage::class);
- $path = $this->createMock(File::class);
- $path->method('getOwner')->willReturn($shareOwner);
- $path->method('getName')->willReturn('target');
- $path->method('getStorage')->willReturn($storage);
-
- $share = $this->createShare(
- null,
- IShare::TYPE_USER,
- $path,
- 'sharedWith',
- 'sharedBy',
- null,
- \OCP\Constants::PERMISSION_ALL);
-
- $manager->expects($this->once())
- ->method('canShare')
- ->with($share)
- ->willReturn(true);
- $manager->expects($this->once())
- ->method('generalCreateChecks')
- ->with($share);
- ;
- $manager->expects($this->once())
- ->method('userCreateChecks')
- ->with($share);
- ;
- $manager->expects($this->once())
- ->method('pathCreateChecks')
- ->with($path);
-
- $share->expects($this->once())
- ->method('setShareOwner')
- ->with('shareOwner');
- $share->expects($this->once())
- ->method('setTarget')
- ->with('/target');
-
- // Pre share
- $this->dispatcher->expects($this->once())
- ->method('dispatchTyped')
- ->with(
- $this->isInstanceOf(BeforeShareCreatedEvent::class)
- )->willReturnCallback(function (BeforeShareCreatedEvent $e) {
- $e->setError('I won\'t let you share!');
- $e->stopPropagation();
- }
- );
-
- $manager->createShare($share);
- }
-
- public function testCreateShareOfIncomingFederatedShare() {
- $manager = $this->createManagerMock()
- ->setMethods(['canShare', 'generalCreateChecks', 'userCreateChecks', 'pathCreateChecks'])
- ->getMock();
-
- $shareOwner = $this->createMock(IUser::class);
- $shareOwner->method('getUID')->willReturn('shareOwner');
-
- $storage = $this->createMock(Storage::class);
- $storage->method('instanceOfStorage')
- ->with(\OCA\Files_Sharing\External\Storage::class)
- ->willReturn(true);
-
- $storage2 = $this->createMock(Storage::class);
- $storage2->method('instanceOfStorage')
- ->with(\OCA\Files_Sharing\External\Storage::class)
- ->willReturn(false);
-
- $path = $this->createMock(File::class);
- $path->expects($this->never())->method('getOwner');
- $path->method('getName')->willReturn('target');
- $path->method('getStorage')->willReturn($storage);
-
- $parent = $this->createMock(Folder::class);
- $parent->method('getStorage')->willReturn($storage);
-
- $parentParent = $this->createMock(Folder::class);
- $parentParent->method('getStorage')->willReturn($storage2);
- $parentParent->method('getOwner')->willReturn($shareOwner);
-
- $path->method('getParent')->willReturn($parent);
- $parent->method('getParent')->willReturn($parentParent);
-
- $share = $this->createShare(
- null,
- IShare::TYPE_USER,
- $path,
- 'sharedWith',
- 'sharedBy',
- null,
- \OCP\Constants::PERMISSION_ALL);
-
- $manager->expects($this->once())
- ->method('canShare')
- ->with($share)
- ->willReturn(true);
- $manager->expects($this->once())
- ->method('generalCreateChecks')
- ->with($share);
- ;
- $manager->expects($this->once())
- ->method('userCreateChecks')
- ->with($share);
- ;
- $manager->expects($this->once())
- ->method('pathCreateChecks')
- ->with($path);
-
- $this->defaultProvider
- ->expects($this->once())
- ->method('create')
- ->with($share)
- ->willReturnArgument(0);
-
- $share->expects($this->once())
- ->method('setShareOwner')
- ->with('shareOwner');
- $share->expects($this->once())
- ->method('setTarget')
- ->with('/target');
-
- $manager->createShare($share);
- }
-
- public function testGetSharesBy() {
- $share = $this->manager->newShare();
-
- $node = $this->createMock(Folder::class);
-
- $this->defaultProvider->expects($this->once())
- ->method('getSharesBy')
- ->with(
- $this->equalTo('user'),
- $this->equalTo(IShare::TYPE_USER),
- $this->equalTo($node),
- $this->equalTo(true),
- $this->equalTo(1),
- $this->equalTo(1)
- )->willReturn([$share]);
-
- $shares = $this->manager->getSharesBy('user', IShare::TYPE_USER, $node, true, 1, 1);
-
- $this->assertCount(1, $shares);
- $this->assertSame($share, $shares[0]);
- }
-
- /**
- * Test to ensure we correctly remove expired link shares
- *
- * We have 8 Shares and we want the 3 first valid shares.
- * share 3-6 and 8 are expired. Thus at the end of this test we should
- * have received share 1,2 and 7. And from the manager. Share 3-6 should be
- * deleted (as they are evaluated). but share 8 should still be there.
- */
- public function testGetSharesByExpiredLinkShares() {
- $manager = $this->createManagerMock()
- ->setMethods(['deleteShare'])
- ->getMock();
-
- /** @var \OCP\Share\IShare[] $shares */
- $shares = [];
-
- /*
- * This results in an array of 8 IShare elements
- */
- for ($i = 0; $i < 8; $i++) {
- $share = $this->manager->newShare();
- $share->setId($i);
- $shares[] = $share;
- }
-
- $today = new \DateTime();
- $today->setTime(0, 0, 0);
-
- /*
- * Set the expiration date to today for some shares
- */
- $shares[2]->setExpirationDate($today);
- $shares[3]->setExpirationDate($today);
- $shares[4]->setExpirationDate($today);
- $shares[5]->setExpirationDate($today);
-
- /** @var \OCP\Share\IShare[] $i */
- $shares2 = [];
- for ($i = 0; $i < 8; $i++) {
- $shares2[] = clone $shares[$i];
- }
-
- $node = $this->createMock(File::class);
-
- /*
- * Simulate the getSharesBy call.
- */
- $this->defaultProvider
- ->method('getSharesBy')
- ->willReturnCallback(function ($uid, $type, $node, $reshares, $limit, $offset) use (&$shares2) {
- return array_slice($shares2, $offset, $limit);
- });
-
- /*
- * Simulate the deleteShare call.
- */
- $manager->method('deleteShare')
- ->willReturnCallback(function ($share) use (&$shares2) {
- for ($i = 0; $i < count($shares2); $i++) {
- if ($shares2[$i]->getId() === $share->getId()) {
- array_splice($shares2, $i, 1);
- break;
- }
- }
- });
-
- $res = $manager->getSharesBy('user', IShare::TYPE_LINK, $node, true, 3, 0);
-
- $this->assertCount(3, $res);
- $this->assertEquals($shares[0]->getId(), $res[0]->getId());
- $this->assertEquals($shares[1]->getId(), $res[1]->getId());
- $this->assertEquals($shares[6]->getId(), $res[2]->getId());
-
- $this->assertCount(4, $shares2);
- $this->assertEquals(0, $shares2[0]->getId());
- $this->assertEquals(1, $shares2[1]->getId());
- $this->assertEquals(6, $shares2[2]->getId());
- $this->assertEquals(7, $shares2[3]->getId());
- $this->assertSame($today, $shares[3]->getExpirationDate());
- }
-
- public function testGetShareByToken() {
- $this->config
- ->expects($this->exactly(2))
- ->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_allow_links', 'yes', 'yes'],
- ['files_sharing', 'hide_disabled_user_shares', 'no', 'no'],
- ]);
-
- $factory = $this->createMock(IProviderFactory::class);
-
- $manager = $this->createManager($factory);
-
- $share = $this->createMock(IShare::class);
-
- $factory->expects($this->once())
- ->method('getProviderForType')
- ->with(IShare::TYPE_LINK)
- ->willReturn($this->defaultProvider);
-
- $this->defaultProvider->expects($this->once())
- ->method('getShareByToken')
- ->with('token')
- ->willReturn($share);
-
- $ret = $manager->getShareByToken('token');
- $this->assertSame($share, $ret);
- }
-
- public function testGetShareByTokenRoom() {
- $this->config
- ->expects($this->exactly(2))
- ->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_allow_links', 'yes', 'no'],
- ['files_sharing', 'hide_disabled_user_shares', 'no', 'no'],
- ]);
-
- $factory = $this->createMock(IProviderFactory::class);
-
- $manager = $this->createManager($factory);
-
- $share = $this->createMock(IShare::class);
-
- $roomShareProvider = $this->createMock(IShareProvider::class);
-
- $factory->expects($this->any())
- ->method('getProviderForType')
- ->willReturnCallback(function ($shareType) use ($roomShareProvider) {
- if ($shareType !== IShare::TYPE_ROOM) {
- throw new Exception\ProviderException();
- }
-
- return $roomShareProvider;
- });
-
- $roomShareProvider->expects($this->once())
- ->method('getShareByToken')
- ->with('token')
- ->willReturn($share);
-
- $ret = $manager->getShareByToken('token');
- $this->assertSame($share, $ret);
- }
-
- public function testGetShareByTokenWithException() {
- $this->config
- ->expects($this->exactly(2))
- ->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_allow_links', 'yes', 'yes'],
- ['files_sharing', 'hide_disabled_user_shares', 'no', 'no'],
- ]);
-
- $factory = $this->createMock(IProviderFactory::class);
-
- $manager = $this->createManager($factory);
-
- $share = $this->createMock(IShare::class);
-
- $factory->expects($this->exactly(2))
- ->method('getProviderForType')
- ->withConsecutive(
- [IShare::TYPE_LINK],
- [IShare::TYPE_REMOTE]
- )
- ->willReturn($this->defaultProvider);
-
- $this->defaultProvider->expects($this->exactly(2))
- ->method('getShareByToken')
- ->with('token')
- ->willReturnOnConsecutiveCalls(
- $this->throwException(new ShareNotFound()),
- $share
- );
-
- $ret = $manager->getShareByToken('token');
- $this->assertSame($share, $ret);
- }
-
-
- public function testGetShareByTokenHideDisabledUser() {
- $this->expectException(\OCP\Share\Exceptions\ShareNotFound::class);
- $this->expectExceptionMessage('The requested share comes from a disabled user');
-
- $this->config
- ->expects($this->exactly(2))
- ->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_allow_links', 'yes', 'yes'],
- ['files_sharing', 'hide_disabled_user_shares', 'no', 'yes'],
- ]);
-
- $this->l->expects($this->once())
- ->method('t')
- ->willReturnArgument(0);
-
- $manager = $this->createManagerMock()
- ->setMethods(['deleteShare'])
- ->getMock();
-
- $date = new \DateTime();
- $date->setTime(0, 0, 0);
- $date->add(new \DateInterval('P2D'));
- $share = $this->manager->newShare();
- $share->setExpirationDate($date);
- $share->setShareOwner('owner');
- $share->setSharedBy('sharedBy');
-
- $sharedBy = $this->createMock(IUser::class);
- $owner = $this->createMock(IUser::class);
-
- $this->userManager->method('get')->willReturnMap([
- ['sharedBy', $sharedBy],
- ['owner', $owner],
- ]);
-
- $owner->expects($this->once())
- ->method('isEnabled')
- ->willReturn(true);
- $sharedBy->expects($this->once())
- ->method('isEnabled')
- ->willReturn(false);
-
- $this->defaultProvider->expects($this->once())
- ->method('getShareByToken')
- ->with('expiredToken')
- ->willReturn($share);
-
- $manager->expects($this->never())
- ->method('deleteShare');
-
- $manager->getShareByToken('expiredToken');
- }
-
-
- public function testGetShareByTokenExpired() {
- $this->expectException(\OCP\Share\Exceptions\ShareNotFound::class);
- $this->expectExceptionMessage('The requested share does not exist anymore');
-
- $this->config
- ->expects($this->once())
- ->method('getAppValue')
- ->with('core', 'shareapi_allow_links', 'yes')
- ->willReturn('yes');
-
- $this->l->expects($this->once())
- ->method('t')
- ->willReturnArgument(0);
-
- $manager = $this->createManagerMock()
- ->setMethods(['deleteShare'])
- ->getMock();
-
- $date = new \DateTime();
- $date->setTime(0, 0, 0);
- $share = $this->manager->newShare();
- $share->setExpirationDate($date);
-
- $this->defaultProvider->expects($this->once())
- ->method('getShareByToken')
- ->with('expiredToken')
- ->willReturn($share);
-
- $manager->expects($this->once())
- ->method('deleteShare')
- ->with($this->equalTo($share));
-
- $manager->getShareByToken('expiredToken');
- }
-
- public function testGetShareByTokenNotExpired() {
- $this->config
- ->expects($this->exactly(2))
- ->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_allow_links', 'yes', 'yes'],
- ['files_sharing', 'hide_disabled_user_shares', 'no', 'no'],
- ]);
-
- $date = new \DateTime();
- $date->setTime(0, 0, 0);
- $date->add(new \DateInterval('P2D'));
- $share = $this->manager->newShare();
- $share->setExpirationDate($date);
-
- $this->defaultProvider->expects($this->once())
- ->method('getShareByToken')
- ->with('expiredToken')
- ->willReturn($share);
-
- $res = $this->manager->getShareByToken('expiredToken');
-
- $this->assertSame($share, $res);
- }
-
-
- public function testGetShareByTokenWithPublicLinksDisabled() {
- $this->expectException(\OCP\Share\Exceptions\ShareNotFound::class);
-
- $this->config
- ->expects($this->once())
- ->method('getAppValue')
- ->with('core', 'shareapi_allow_links', 'yes')
- ->willReturn('no');
- $this->manager->getShareByToken('validToken');
- }
-
- public function testGetShareByTokenPublicUploadDisabled() {
- $this->config
- ->expects($this->exactly(3))
- ->method('getAppValue')
- ->willReturnMap([
- ['core', 'shareapi_allow_links', 'yes', 'yes'],
- ['core', 'shareapi_allow_public_upload', 'yes', 'no'],
- ['files_sharing', 'hide_disabled_user_shares', 'no', 'no'],
- ]);
-
- $share = $this->manager->newShare();
- $share->setShareType(IShare::TYPE_LINK)
- ->setPermissions(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE);
- $share->setSharedWith('sharedWith');
- $folder = $this->createMock(\OC\Files\Node\Folder::class);
- $share->setNode($folder);
-
- $this->defaultProvider->expects($this->once())
- ->method('getShareByToken')
- ->willReturn('validToken')
- ->willReturn($share);
-
- $res = $this->manager->getShareByToken('validToken');
-
- $this->assertSame(\OCP\Constants::PERMISSION_READ, $res->getPermissions());
- }
-
- public function testCheckPasswordNoLinkShare() {
- $share = $this->createMock(IShare::class);
- $share->method('getShareType')->willReturn(IShare::TYPE_USER);
- $this->assertFalse($this->manager->checkPassword($share, 'password'));
- }
-
- public function testCheckPasswordNoPassword() {
- $share = $this->createMock(IShare::class);
- $share->method('getShareType')->willReturn(IShare::TYPE_LINK);
- $this->assertFalse($this->manager->checkPassword($share, 'password'));
-
- $share->method('getPassword')->willReturn('password');
- $this->assertFalse($this->manager->checkPassword($share, null));
- }
-
- public function testCheckPasswordInvalidPassword() {
- $share = $this->createMock(IShare::class);
- $share->method('getShareType')->willReturn(IShare::TYPE_LINK);
- $share->method('getPassword')->willReturn('password');
-
- $this->hasher->method('verify')->with('invalidpassword', 'password', '')->willReturn(false);
-
- $this->assertFalse($this->manager->checkPassword($share, 'invalidpassword'));
- }
-
- public function testCheckPasswordValidPassword() {
- $share = $this->createMock(IShare::class);
- $share->method('getShareType')->willReturn(IShare::TYPE_LINK);
- $share->method('getPassword')->willReturn('passwordHash');
-
- $this->hasher->method('verify')->with('password', 'passwordHash', '')->willReturn(true);
-
- $this->assertTrue($this->manager->checkPassword($share, 'password'));
- }
-
- public function testCheckPasswordUpdateShare() {
- $share = $this->manager->newShare();
- $share->setShareType(IShare::TYPE_LINK)
- ->setPassword('passwordHash');
-
- $this->hasher->method('verify')->with('password', 'passwordHash', '')
- ->willReturnCallback(function ($pass, $hash, &$newHash) {
- $newHash = 'newHash';
-
- return true;
- });
-
- $this->defaultProvider->expects($this->once())
- ->method('update')
- ->with($this->callback(function (\OCP\Share\IShare $share) {
- return $share->getPassword() === 'newHash';
- }));
-
- $this->assertTrue($this->manager->checkPassword($share, 'password'));
- }
-
-
- public function testUpdateShareCantChangeShareType() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('Cannot change share type');
-
- $manager = $this->createManagerMock()
- ->setMethods([
- 'canShare',
- 'getShareById'
- ])
- ->getMock();
-
- $originalShare = $this->manager->newShare();
- $originalShare->setShareType(IShare::TYPE_GROUP);
-
- $manager->expects($this->once())->method('canShare')->willReturn(true);
- $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
-
- $share = $this->manager->newShare();
- $attrs = $this->manager->newShare()->newAttributes();
- $attrs->setAttribute('app1', 'perm1', true);
- $share->setProviderId('foo')
- ->setId('42')
- ->setShareType(IShare::TYPE_USER);
-
- $manager->updateShare($share);
- }
-
-
- public function testUpdateShareCantChangeRecipientForGroupShare() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('Can only update recipient on user shares');
-
- $manager = $this->createManagerMock()
- ->setMethods([
- 'canShare',
- 'getShareById'
- ])
- ->getMock();
-
- $originalShare = $this->manager->newShare();
- $originalShare->setShareType(IShare::TYPE_GROUP)
- ->setSharedWith('origGroup');
-
- $manager->expects($this->once())->method('canShare')->willReturn(true);
- $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
-
- $share = $this->manager->newShare();
- $share->setProviderId('foo')
- ->setId('42')
- ->setShareType(IShare::TYPE_GROUP)
- ->setSharedWith('newGroup');
-
- $manager->updateShare($share);
- }
-
-
- public function testUpdateShareCantShareWithOwner() {
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('Cannot share with the share owner');
-
- $manager = $this->createManagerMock()
- ->setMethods([
- 'canShare',
- 'getShareById'
- ])
- ->getMock();
-
- $originalShare = $this->manager->newShare();
- $originalShare->setShareType(IShare::TYPE_USER)
- ->setSharedWith('sharedWith');
-
- $manager->expects($this->once())->method('canShare')->willReturn(true);
- $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
-
- $share = $this->manager->newShare();
- $share->setProviderId('foo')
- ->setId('42')
- ->setShareType(IShare::TYPE_USER)
- ->setSharedWith('newUser')
- ->setShareOwner('newUser');
-
- $manager->updateShare($share);
- }
-
- public function testUpdateShareUser() {
- $this->userManager->expects($this->any())->method('userExists')->willReturn(true);
-
- $manager = $this->createManagerMock()
- ->setMethods([
- 'canShare',
- 'getShareById',
- 'generalCreateChecks',
- 'userCreateChecks',
- 'pathCreateChecks',
- ])
- ->getMock();
-
- $originalShare = $this->manager->newShare();
- $originalShare->setShareType(IShare::TYPE_USER)
- ->setSharedWith('origUser')
- ->setPermissions(1);
-
- $node = $this->createMock(File::class);
- $node->method('getId')->willReturn(100);
- $node->method('getPath')->willReturn('/newUser/files/myPath');
-
- $manager->expects($this->once())->method('canShare')->willReturn(true);
- $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
-
- $share = $this->manager->newShare();
- $attrs = $this->manager->newShare()->newAttributes();
- $attrs->setAttribute('app1', 'perm1', true);
- $share->setProviderId('foo')
- ->setId('42')
- ->setShareType(IShare::TYPE_USER)
- ->setSharedWith('origUser')
- ->setShareOwner('newUser')
- ->setSharedBy('sharer')
- ->setPermissions(31)
- ->setAttributes($attrs)
- ->setNode($node);
-
- $this->defaultProvider->expects($this->once())
- ->method('update')
- ->with($share)
- ->willReturn($share);
-
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, '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->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListener2, 'post');
- $hookListener2->expects($this->once())->method('post')->with([
- 'itemType' => 'file',
- 'itemSource' => 100,
- 'shareType' => IShare::TYPE_USER,
- 'shareWith' => 'origUser',
- 'uidOwner' => 'sharer',
- 'permissions' => 31,
- 'path' => '/myPath',
- 'attributes' => $attrs->toArray(),
- ]);
-
- $manager->updateShare($share);
- }
-
- public function testUpdateShareGroup() {
- $manager = $this->createManagerMock()
- ->setMethods([
- 'canShare',
- 'getShareById',
- 'generalCreateChecks',
- 'groupCreateChecks',
- 'pathCreateChecks',
- ])
- ->getMock();
-
- $originalShare = $this->manager->newShare();
- $originalShare->setShareType(IShare::TYPE_GROUP)
- ->setSharedWith('origUser')
- ->setPermissions(31);
-
- $manager->expects($this->once())->method('canShare')->willReturn(true);
- $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
-
- $node = $this->createMock(File::class);
-
- $share = $this->manager->newShare();
- $share->setProviderId('foo')
- ->setId('42')
- ->setShareType(IShare::TYPE_GROUP)
- ->setSharedWith('origUser')
- ->setShareOwner('owner')
- ->setNode($node)
- ->setPermissions(31);
-
- $this->defaultProvider->expects($this->once())
- ->method('update')
- ->with($share)
- ->willReturn($share);
-
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListener, 'post');
- $hookListener->expects($this->never())->method('post');
-
- $hookListener2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListener2, 'post');
- $hookListener2->expects($this->never())->method('post');
-
- $manager->updateShare($share);
- }
-
- public function testUpdateShareLink() {
- $manager = $this->createManagerMock()
- ->setMethods([
- 'canShare',
- 'getShareById',
- 'generalCreateChecks',
- 'linkCreateChecks',
- 'pathCreateChecks',
- 'verifyPassword',
- 'validateExpirationDateLink',
- ])
- ->getMock();
-
- $originalShare = $this->manager->newShare();
- $originalShare->setShareType(IShare::TYPE_LINK)
- ->setPermissions(15);
-
- $tomorrow = new \DateTime();
- $tomorrow->setTime(0, 0, 0);
- $tomorrow->add(new \DateInterval('P1D'));
-
- $file = $this->createMock(File::class);
- $file->method('getId')->willReturn(100);
-
- $share = $this->manager->newShare();
- $share->setProviderId('foo')
- ->setId('42')
- ->setShareType(IShare::TYPE_LINK)
- ->setToken('token')
- ->setSharedBy('owner')
- ->setShareOwner('owner')
- ->setPassword('password')
- ->setExpirationDate($tomorrow)
- ->setNode($file)
- ->setPermissions(15);
-
- $manager->expects($this->once())->method('canShare')->willReturn(true);
- $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
- $manager->expects($this->once())->method('validateExpirationDateLink')->with($share);
- $manager->expects($this->once())->method('verifyPassword')->with('password');
-
- $this->hasher->expects($this->once())
- ->method('hash')
- ->with('password')
- ->willReturn('hashed');
-
- $this->defaultProvider->expects($this->once())
- ->method('update')
- ->with($share)
- ->willReturn($share);
-
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListener, 'post');
- $hookListener->expects($this->once())->method('post')->with([
- 'itemType' => 'file',
- 'itemSource' => 100,
- 'date' => $tomorrow,
- 'uidOwner' => 'owner',
- ]);
-
- $hookListener2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_update_password', $hookListener2, 'post');
- $hookListener2->expects($this->once())->method('post')->with([
- 'itemType' => 'file',
- 'itemSource' => 100,
- 'uidOwner' => 'owner',
- 'token' => 'token',
- 'disabled' => false,
- ]);
-
- $hookListener3 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListener3, 'post');
- $hookListener3->expects($this->never())->method('post');
-
-
- $manager->updateShare($share);
- }
-
- public function testUpdateShareLinkEnableSendPasswordByTalkWithNoPassword() {
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('Cannot enable sending the password by Talk with an empty password');
-
- $manager = $this->createManagerMock()
- ->setMethods([
- 'canShare',
- 'getShareById',
- 'generalCreateChecks',
- 'linkCreateChecks',
- 'pathCreateChecks',
- 'verifyPassword',
- 'validateExpirationDateLink',
- ])
- ->getMock();
-
- $originalShare = $this->manager->newShare();
- $originalShare->setShareType(IShare::TYPE_LINK)
- ->setPermissions(15);
-
- $tomorrow = new \DateTime();
- $tomorrow->setTime(0, 0, 0);
- $tomorrow->add(new \DateInterval('P1D'));
-
- $file = $this->createMock(File::class);
- $file->method('getId')->willReturn(100);
-
- $share = $this->manager->newShare();
- $share->setProviderId('foo')
- ->setId('42')
- ->setShareType(IShare::TYPE_LINK)
- ->setToken('token')
- ->setSharedBy('owner')
- ->setShareOwner('owner')
- ->setPassword(null)
- ->setSendPasswordByTalk(true)
- ->setExpirationDate($tomorrow)
- ->setNode($file)
- ->setPermissions(15);
-
- $manager->expects($this->once())->method('canShare')->willReturn(true);
- $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
- $manager->expects($this->once())->method('generalCreateChecks')->with($share);
- $manager->expects($this->once())->method('linkCreateChecks')->with($share);
- $manager->expects($this->never())->method('verifyPassword');
- $manager->expects($this->never())->method('pathCreateChecks');
- $manager->expects($this->never())->method('validateExpirationDateLink');
-
- $this->hasher->expects($this->never())
- ->method('hash');
-
- $this->defaultProvider->expects($this->never())
- ->method('update');
-
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListener, 'post');
- $hookListener->expects($this->never())->method('post');
-
- $hookListener2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_update_password', $hookListener2, 'post');
- $hookListener2->expects($this->never())->method('post');
-
- $hookListener3 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListener3, 'post');
- $hookListener3->expects($this->never())->method('post');
-
- $manager->updateShare($share);
- }
-
- public function testUpdateShareMail() {
- $manager = $this->createManagerMock()
- ->setMethods([
- 'canShare',
- 'getShareById',
- 'generalCreateChecks',
- 'verifyPassword',
- 'pathCreateChecks',
- 'linkCreateChecks',
- 'validateExpirationDateLink',
- ])
- ->getMock();
-
- $originalShare = $this->manager->newShare();
- $originalShare->setShareType(IShare::TYPE_EMAIL)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL);
-
- $tomorrow = new \DateTime();
- $tomorrow->setTime(0, 0, 0);
- $tomorrow->add(new \DateInterval('P1D'));
-
- $file = $this->createMock(File::class);
- $file->method('getId')->willReturn(100);
-
- $share = $this->manager->newShare();
- $share->setProviderId('foo')
- ->setId('42')
- ->setShareType(IShare::TYPE_EMAIL)
- ->setToken('token')
- ->setSharedBy('owner')
- ->setShareOwner('owner')
- ->setPassword('password')
- ->setExpirationDate($tomorrow)
- ->setNode($file)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL);
-
- $manager->expects($this->once())->method('canShare')->willReturn(true);
- $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
- $manager->expects($this->once())->method('generalCreateChecks')->with($share);
- $manager->expects($this->once())->method('verifyPassword')->with('password');
- $manager->expects($this->once())->method('pathCreateChecks')->with($file);
- $manager->expects($this->once())->method('linkCreateChecks');
- $manager->expects($this->once())->method('validateExpirationDateLink');
-
- $this->hasher->expects($this->once())
- ->method('hash')
- ->with('password')
- ->willReturn('hashed');
-
- $this->defaultProvider->expects($this->once())
- ->method('update')
- ->with($share, 'password')
- ->willReturn($share);
-
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListener, 'post');
- $hookListener->expects($this->once())->method('post')->with([
- 'itemType' => 'file',
- 'itemSource' => 100,
- 'date' => $tomorrow,
- 'uidOwner' => 'owner',
- ]);
-
- $hookListener2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_update_password', $hookListener2, 'post');
- $hookListener2->expects($this->once())->method('post')->with([
- 'itemType' => 'file',
- 'itemSource' => 100,
- 'uidOwner' => 'owner',
- 'token' => 'token',
- 'disabled' => false,
- ]);
-
- $hookListener3 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListener3, 'post');
- $hookListener3->expects($this->never())->method('post');
-
- $manager->updateShare($share);
- }
-
- public function testUpdateShareMailEnableSendPasswordByTalk() {
- $manager = $this->createManagerMock()
- ->setMethods([
- 'canShare',
- 'getShareById',
- 'generalCreateChecks',
- 'verifyPassword',
- 'pathCreateChecks',
- 'linkCreateChecks',
- 'validateExpirationDateLink',
- ])
- ->getMock();
-
- $originalShare = $this->manager->newShare();
- $originalShare->setShareType(IShare::TYPE_EMAIL)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL)
- ->setPassword(null)
- ->setSendPasswordByTalk(false);
-
- $tomorrow = new \DateTime();
- $tomorrow->setTime(0, 0, 0);
- $tomorrow->add(new \DateInterval('P1D'));
-
- $file = $this->createMock(File::class);
- $file->method('getId')->willReturn(100);
-
- $share = $this->manager->newShare();
- $share->setProviderId('foo')
- ->setId('42')
- ->setShareType(IShare::TYPE_EMAIL)
- ->setToken('token')
- ->setSharedBy('owner')
- ->setShareOwner('owner')
- ->setPassword('password')
- ->setSendPasswordByTalk(true)
- ->setExpirationDate($tomorrow)
- ->setNode($file)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL);
-
- $manager->expects($this->once())->method('canShare')->willReturn(true);
- $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
- $manager->expects($this->once())->method('generalCreateChecks')->with($share);
- $manager->expects($this->once())->method('verifyPassword')->with('password');
- $manager->expects($this->once())->method('pathCreateChecks')->with($file);
- $manager->expects($this->once())->method('linkCreateChecks');
- $manager->expects($this->once())->method('validateExpirationDateLink');
-
- $this->hasher->expects($this->once())
- ->method('hash')
- ->with('password')
- ->willReturn('hashed');
-
- $this->defaultProvider->expects($this->once())
- ->method('update')
- ->with($share, 'password')
- ->willReturn($share);
-
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListener, 'post');
- $hookListener->expects($this->once())->method('post')->with([
- 'itemType' => 'file',
- 'itemSource' => 100,
- 'date' => $tomorrow,
- 'uidOwner' => 'owner',
- ]);
-
- $hookListener2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_update_password', $hookListener2, 'post');
- $hookListener2->expects($this->once())->method('post')->with([
- 'itemType' => 'file',
- 'itemSource' => 100,
- 'uidOwner' => 'owner',
- 'token' => 'token',
- 'disabled' => false,
- ]);
-
- $hookListener3 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListener3, 'post');
- $hookListener3->expects($this->never())->method('post');
-
- $manager->updateShare($share);
- }
-
- public function testUpdateShareMailEnableSendPasswordByTalkWithDifferentPassword() {
- $manager = $this->createManagerMock()
- ->setMethods([
- 'canShare',
- 'getShareById',
- 'generalCreateChecks',
- 'verifyPassword',
- 'pathCreateChecks',
- 'linkCreateChecks',
- 'validateExpirationDateLink',
- ])
- ->getMock();
-
- $originalShare = $this->manager->newShare();
- $originalShare->setShareType(IShare::TYPE_EMAIL)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL)
- ->setPassword('anotherPasswordHash')
- ->setSendPasswordByTalk(false);
-
- $tomorrow = new \DateTime();
- $tomorrow->setTime(0, 0, 0);
- $tomorrow->add(new \DateInterval('P1D'));
-
- $file = $this->createMock(File::class);
- $file->method('getId')->willReturn(100);
-
- $share = $this->manager->newShare();
- $share->setProviderId('foo')
- ->setId('42')
- ->setShareType(IShare::TYPE_EMAIL)
- ->setToken('token')
- ->setSharedBy('owner')
- ->setShareOwner('owner')
- ->setPassword('password')
- ->setSendPasswordByTalk(true)
- ->setExpirationDate($tomorrow)
- ->setNode($file)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL);
-
- $manager->expects($this->once())->method('canShare')->willReturn(true);
- $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
- $manager->expects($this->once())->method('generalCreateChecks')->with($share);
- $manager->expects($this->once())->method('verifyPassword')->with('password');
- $manager->expects($this->once())->method('pathCreateChecks')->with($file);
- $manager->expects($this->once())->method('linkCreateChecks');
- $manager->expects($this->once())->method('validateExpirationDateLink');
-
- $this->hasher->expects($this->once())
- ->method('verify')
- ->with('password', 'anotherPasswordHash')
- ->willReturn(false);
-
- $this->hasher->expects($this->once())
- ->method('hash')
- ->with('password')
- ->willReturn('hashed');
-
- $this->defaultProvider->expects($this->once())
- ->method('update')
- ->with($share, 'password')
- ->willReturn($share);
-
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListener, 'post');
- $hookListener->expects($this->once())->method('post')->with([
- 'itemType' => 'file',
- 'itemSource' => 100,
- 'date' => $tomorrow,
- 'uidOwner' => 'owner',
- ]);
-
- $hookListener2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_update_password', $hookListener2, 'post');
- $hookListener2->expects($this->once())->method('post')->with([
- 'itemType' => 'file',
- 'itemSource' => 100,
- 'uidOwner' => 'owner',
- 'token' => 'token',
- 'disabled' => false,
- ]);
-
- $hookListener3 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListener3, 'post');
- $hookListener3->expects($this->never())->method('post');
-
- $manager->updateShare($share);
- }
-
- public function testUpdateShareMailEnableSendPasswordByTalkWithNoPassword() {
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('Cannot enable sending the password by Talk with an empty password');
-
- $manager = $this->createManagerMock()
- ->setMethods([
- 'canShare',
- 'getShareById',
- 'generalCreateChecks',
- 'verifyPassword',
- 'pathCreateChecks',
- 'linkCreateChecks',
- 'validateExpirationDateLink',
- ])
- ->getMock();
-
- $originalShare = $this->manager->newShare();
- $originalShare->setShareType(IShare::TYPE_EMAIL)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL)
- ->setPassword(null)
- ->setSendPasswordByTalk(false);
-
- $tomorrow = new \DateTime();
- $tomorrow->setTime(0, 0, 0);
- $tomorrow->add(new \DateInterval('P1D'));
-
- $file = $this->createMock(File::class);
- $file->method('getId')->willReturn(100);
-
- $share = $this->manager->newShare();
- $share->setProviderId('foo')
- ->setId('42')
- ->setShareType(IShare::TYPE_EMAIL)
- ->setToken('token')
- ->setSharedBy('owner')
- ->setShareOwner('owner')
- ->setPassword(null)
- ->setSendPasswordByTalk(true)
- ->setExpirationDate($tomorrow)
- ->setNode($file)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL);
-
- $manager->expects($this->once())->method('canShare')->willReturn(true);
- $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
- $manager->expects($this->once())->method('generalCreateChecks')->with($share);
- $manager->expects($this->never())->method('verifyPassword');
- $manager->expects($this->never())->method('pathCreateChecks');
- $manager->expects($this->once())->method('linkCreateChecks');
- $manager->expects($this->never())->method('validateExpirationDateLink');
-
- // If the password is empty, we have nothing to hash
- $this->hasher->expects($this->never())
- ->method('hash');
-
- $this->defaultProvider->expects($this->never())
- ->method('update');
-
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListener, 'post');
- $hookListener->expects($this->never())->method('post');
-
- $hookListener2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_update_password', $hookListener2, 'post');
- $hookListener2->expects($this->never())->method('post');
-
- $hookListener3 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListener3, 'post');
- $hookListener3->expects($this->never())->method('post');
-
- $manager->updateShare($share);
- }
-
-
- public function testUpdateShareMailEnableSendPasswordByTalkRemovingPassword() {
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('Cannot enable sending the password by Talk with an empty password');
-
- $manager = $this->createManagerMock()
- ->setMethods([
- 'canShare',
- 'getShareById',
- 'generalCreateChecks',
- 'verifyPassword',
- 'pathCreateChecks',
- 'linkCreateChecks',
- 'validateExpirationDateLink',
- ])
- ->getMock();
-
- $originalShare = $this->manager->newShare();
- $originalShare->setShareType(IShare::TYPE_EMAIL)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL)
- ->setPassword('passwordHash')
- ->setSendPasswordByTalk(false);
-
- $tomorrow = new \DateTime();
- $tomorrow->setTime(0, 0, 0);
- $tomorrow->add(new \DateInterval('P1D'));
-
- $file = $this->createMock(File::class);
- $file->method('getId')->willReturn(100);
-
- $share = $this->manager->newShare();
- $share->setProviderId('foo')
- ->setId('42')
- ->setShareType(IShare::TYPE_EMAIL)
- ->setToken('token')
- ->setSharedBy('owner')
- ->setShareOwner('owner')
- ->setPassword(null)
- ->setSendPasswordByTalk(true)
- ->setExpirationDate($tomorrow)
- ->setNode($file)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL);
-
- $manager->expects($this->once())->method('canShare')->willReturn(true);
- $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
- $manager->expects($this->once())->method('generalCreateChecks')->with($share);
- $manager->expects($this->once())->method('verifyPassword');
- $manager->expects($this->never())->method('pathCreateChecks');
- $manager->expects($this->once())->method('linkCreateChecks');
- $manager->expects($this->never())->method('validateExpirationDateLink');
-
- // If the password is empty, we have nothing to hash
- $this->hasher->expects($this->never())
- ->method('hash');
-
- $this->defaultProvider->expects($this->never())
- ->method('update');
-
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListener, 'post');
- $hookListener->expects($this->never())->method('post');
-
- $hookListener2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_update_password', $hookListener2, 'post');
- $hookListener2->expects($this->never())->method('post');
-
- $hookListener3 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListener3, 'post');
- $hookListener3->expects($this->never())->method('post');
-
- $manager->updateShare($share);
- }
-
-
- public function testUpdateShareMailEnableSendPasswordByTalkRemovingPasswordWithEmptyString() {
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('Cannot enable sending the password by Talk with an empty password');
-
- $manager = $this->createManagerMock()
- ->setMethods([
- 'canShare',
- 'getShareById',
- 'generalCreateChecks',
- 'verifyPassword',
- 'pathCreateChecks',
- 'linkCreateChecks',
- 'validateExpirationDateLink',
- ])
- ->getMock();
-
- $originalShare = $this->manager->newShare();
- $originalShare->setShareType(IShare::TYPE_EMAIL)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL)
- ->setPassword('passwordHash')
- ->setSendPasswordByTalk(false);
-
- $tomorrow = new \DateTime();
- $tomorrow->setTime(0, 0, 0);
- $tomorrow->add(new \DateInterval('P1D'));
-
- $file = $this->createMock(File::class);
- $file->method('getId')->willReturn(100);
-
- $share = $this->manager->newShare();
- $share->setProviderId('foo')
- ->setId('42')
- ->setShareType(IShare::TYPE_EMAIL)
- ->setToken('token')
- ->setSharedBy('owner')
- ->setShareOwner('owner')
- ->setPassword('')
- ->setSendPasswordByTalk(true)
- ->setExpirationDate($tomorrow)
- ->setNode($file)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL);
-
- $manager->expects($this->once())->method('canShare')->willReturn(true);
- $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
- $manager->expects($this->once())->method('generalCreateChecks')->with($share);
- $manager->expects($this->once())->method('verifyPassword');
- $manager->expects($this->never())->method('pathCreateChecks');
- $manager->expects($this->once())->method('linkCreateChecks');
- $manager->expects($this->never())->method('validateExpirationDateLink');
-
- // If the password is empty, we have nothing to hash
- $this->hasher->expects($this->never())
- ->method('hash');
-
- $this->defaultProvider->expects($this->never())
- ->method('update');
-
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListener, 'post');
- $hookListener->expects($this->never())->method('post');
-
- $hookListener2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_update_password', $hookListener2, 'post');
- $hookListener2->expects($this->never())->method('post');
-
- $hookListener3 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListener3, 'post');
- $hookListener3->expects($this->never())->method('post');
-
- $manager->updateShare($share);
- }
-
-
- public function testUpdateShareMailEnableSendPasswordByTalkWithPreviousPassword() {
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('Cannot enable sending the password by Talk without setting a new password');
-
- $manager = $this->createManagerMock()
- ->setMethods([
- 'canShare',
- 'getShareById',
- 'generalCreateChecks',
- 'verifyPassword',
- 'pathCreateChecks',
- 'linkCreateChecks',
- 'validateExpirationDateLink',
- ])
- ->getMock();
-
- $originalShare = $this->manager->newShare();
- $originalShare->setShareType(IShare::TYPE_EMAIL)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL)
- ->setPassword('password')
- ->setSendPasswordByTalk(false);
-
- $tomorrow = new \DateTime();
- $tomorrow->setTime(0, 0, 0);
- $tomorrow->add(new \DateInterval('P1D'));
-
- $file = $this->createMock(File::class);
- $file->method('getId')->willReturn(100);
-
- $share = $this->manager->newShare();
- $share->setProviderId('foo')
- ->setId('42')
- ->setShareType(IShare::TYPE_EMAIL)
- ->setToken('token')
- ->setSharedBy('owner')
- ->setShareOwner('owner')
- ->setPassword('password')
- ->setSendPasswordByTalk(true)
- ->setExpirationDate($tomorrow)
- ->setNode($file)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL);
-
- $manager->expects($this->once())->method('canShare')->willReturn(true);
- $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
- $manager->expects($this->once())->method('generalCreateChecks')->with($share);
- $manager->expects($this->never())->method('verifyPassword');
- $manager->expects($this->never())->method('pathCreateChecks');
- $manager->expects($this->once())->method('linkCreateChecks');
- $manager->expects($this->never())->method('validateExpirationDateLink');
-
- // If the old & new passwords are the same, we don't do anything
- $this->hasher->expects($this->never())
- ->method('verify');
- $this->hasher->expects($this->never())
- ->method('hash');
-
- $this->defaultProvider->expects($this->never())
- ->method('update');
-
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListener, 'post');
- $hookListener->expects($this->never())->method('post');
-
- $hookListener2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_update_password', $hookListener2, 'post');
- $hookListener2->expects($this->never())->method('post');
-
- $hookListener3 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListener3, 'post');
- $hookListener3->expects($this->never())->method('post');
-
- $manager->updateShare($share);
- }
-
- public function testUpdateShareMailDisableSendPasswordByTalkWithPreviousPassword() {
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('Cannot disable sending the password by Talk without setting a new password');
-
- $manager = $this->createManagerMock()
- ->setMethods([
- 'canShare',
- 'getShareById',
- 'generalCreateChecks',
- 'verifyPassword',
- 'pathCreateChecks',
- 'linkCreateChecks',
- 'validateExpirationDateLink',
- ])
- ->getMock();
-
- $originalShare = $this->manager->newShare();
- $originalShare->setShareType(IShare::TYPE_EMAIL)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL)
- ->setPassword('passwordHash')
- ->setSendPasswordByTalk(true);
-
- $tomorrow = new \DateTime();
- $tomorrow->setTime(0, 0, 0);
- $tomorrow->add(new \DateInterval('P1D'));
-
- $file = $this->createMock(File::class);
- $file->method('getId')->willReturn(100);
-
- $share = $this->manager->newShare();
- $share->setProviderId('foo')
- ->setId('42')
- ->setShareType(IShare::TYPE_EMAIL)
- ->setToken('token')
- ->setSharedBy('owner')
- ->setShareOwner('owner')
- ->setPassword('passwordHash')
- ->setSendPasswordByTalk(false)
- ->setExpirationDate($tomorrow)
- ->setNode($file)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL);
-
- $manager->expects($this->once())->method('canShare')->willReturn(true);
- $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
- $manager->expects($this->once())->method('generalCreateChecks')->with($share);
- $manager->expects($this->never())->method('verifyPassword');
- $manager->expects($this->never())->method('pathCreateChecks');
- $manager->expects($this->once())->method('linkCreateChecks');
- $manager->expects($this->never())->method('validateExpirationDateLink');
-
- // If the old & new passwords are the same, we don't do anything
- $this->hasher->expects($this->never())
- ->method('verify');
- $this->hasher->expects($this->never())
- ->method('hash');
-
- $this->defaultProvider->expects($this->never())
- ->method('update');
-
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListener, 'post');
- $hookListener->expects($this->never())->method('post');
-
- $hookListener2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_update_password', $hookListener2, 'post');
- $hookListener2->expects($this->never())->method('post');
-
- $hookListener3 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListener3, 'post');
- $hookListener3->expects($this->never())->method('post');
-
- $manager->updateShare($share);
- }
-
- public function testUpdateShareMailDisableSendPasswordByTalkWithoutChangingPassword() {
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('Cannot disable sending the password by Talk without setting a new password');
-
- $manager = $this->createManagerMock()
- ->setMethods([
- 'canShare',
- 'getShareById',
- 'generalCreateChecks',
- 'verifyPassword',
- 'pathCreateChecks',
- 'linkCreateChecks',
- 'validateExpirationDateLink',
- ])
- ->getMock();
-
- $originalShare = $this->manager->newShare();
- $originalShare->setShareType(IShare::TYPE_EMAIL)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL)
- ->setPassword('passwordHash')
- ->setSendPasswordByTalk(true);
-
- $tomorrow = new \DateTime();
- $tomorrow->setTime(0, 0, 0);
- $tomorrow->add(new \DateInterval('P1D'));
-
- $file = $this->createMock(File::class);
- $file->method('getId')->willReturn(100);
-
- $share = $this->manager->newShare();
- $share->setProviderId('foo')
- ->setId('42')
- ->setShareType(IShare::TYPE_EMAIL)
- ->setToken('token')
- ->setSharedBy('owner')
- ->setShareOwner('owner')
- ->setPassword('passwordHash')
- ->setSendPasswordByTalk(false)
- ->setExpirationDate($tomorrow)
- ->setNode($file)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL);
-
- $manager->expects($this->once())->method('canShare')->willReturn(true);
- $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
- $manager->expects($this->once())->method('generalCreateChecks')->with($share);
- $manager->expects($this->never())->method('verifyPassword');
- $manager->expects($this->never())->method('pathCreateChecks');
- $manager->expects($this->once())->method('linkCreateChecks');
- $manager->expects($this->never())->method('validateExpirationDateLink');
-
- // If the old & new passwords are the same, we don't do anything
- $this->hasher->expects($this->never())
- ->method('verify');
- $this->hasher->expects($this->never())
- ->method('hash');
-
- $this->defaultProvider->expects($this->never())
- ->method('update');
-
- $hookListener = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListener, 'post');
- $hookListener->expects($this->never())->method('post');
-
- $hookListener2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_update_password', $hookListener2, 'post');
- $hookListener2->expects($this->never())->method('post');
-
- $hookListener3 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
- \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListener3, 'post');
- $hookListener3->expects($this->never())->method('post');
-
- $manager->updateShare($share);
- }
-
- public function testMoveShareLink() {
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('Cannot change target of link share');
-
- $share = $this->manager->newShare();
- $share->setShareType(IShare::TYPE_LINK);
-
- $recipient = $this->createMock(IUser::class);
-
- $this->manager->moveShare($share, $recipient);
- }
-
-
- public function testMoveShareUserNotRecipient() {
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('Invalid recipient');
-
- $share = $this->manager->newShare();
- $share->setShareType(IShare::TYPE_USER);
-
- $share->setSharedWith('sharedWith');
-
- $this->manager->moveShare($share, 'recipient');
- }
-
- public function testMoveShareUser() {
- $share = $this->manager->newShare();
- $share->setShareType(IShare::TYPE_USER)
- ->setId('42')
- ->setProviderId('foo');
-
- $share->setSharedWith('recipient');
-
- $this->defaultProvider->method('move')->with($share, 'recipient')->willReturnArgument(0);
-
- $this->manager->moveShare($share, 'recipient');
- $this->addToAssertionCount(1);
- }
-
-
- public function testMoveShareGroupNotRecipient() {
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('Invalid recipient');
-
- $share = $this->manager->newShare();
- $share->setShareType(IShare::TYPE_GROUP);
-
- $sharedWith = $this->createMock(IGroup::class);
- $share->setSharedWith('shareWith');
-
- $recipient = $this->createMock(IUser::class);
- $sharedWith->method('inGroup')->with($recipient)->willReturn(false);
-
- $this->groupManager->method('get')->with('shareWith')->willReturn($sharedWith);
- $this->userManager->method('get')->with('recipient')->willReturn($recipient);
-
- $this->manager->moveShare($share, 'recipient');
- }
-
-
- public function testMoveShareGroupNull() {
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('Group "shareWith" does not exist');
-
- $share = $this->manager->newShare();
- $share->setShareType(IShare::TYPE_GROUP);
- $share->setSharedWith('shareWith');
-
- $recipient = $this->createMock(IUser::class);
-
- $this->groupManager->method('get')->with('shareWith')->willReturn(null);
- $this->userManager->method('get')->with('recipient')->willReturn($recipient);
-
- $this->manager->moveShare($share, 'recipient');
- }
-
- public function testMoveShareGroup() {
- $share = $this->manager->newShare();
- $share->setShareType(IShare::TYPE_GROUP)
- ->setId('42')
- ->setProviderId('foo');
-
- $group = $this->createMock(IGroup::class);
- $share->setSharedWith('group');
-
- $recipient = $this->createMock(IUser::class);
- $group->method('inGroup')->with($recipient)->willReturn(true);
-
- $this->groupManager->method('get')->with('group')->willReturn($group);
- $this->userManager->method('get')->with('recipient')->willReturn($recipient);
-
- $this->defaultProvider->method('move')->with($share, 'recipient')->willReturnArgument(0);
-
- $this->manager->moveShare($share, 'recipient');
- $this->addToAssertionCount(1);
- }
-
- /**
- * @dataProvider dataTestShareProviderExists
- */
- public function testShareProviderExists($shareType, $expected) {
- $factory = $this->getMockBuilder(\OCP\Share\IProviderFactory::class)->getMock();
- $factory->expects($this->any())->method('getProviderForType')
- ->willReturnCallback(function ($id) {
- if ($id === IShare::TYPE_USER) {
- return true;
- }
- throw new Exception\ProviderException();
- });
-
- $manager = $this->createManager($factory);
- $this->assertSame($expected,
- $manager->shareProviderExists($shareType)
- );
- }
-
- public function dataTestShareProviderExists() {
- return [
- [IShare::TYPE_USER, true],
- [42, false],
- ];
- }
-
- public function testGetSharesInFolder() {
- $factory = new DummyFactory2($this->createMock(IServerContainer::class));
-
- $manager = $this->createManager($factory);
-
- $factory->setProvider($this->defaultProvider);
- $extraProvider = $this->createMock(IShareProvider::class);
- $factory->setSecondProvider($extraProvider);
-
- $share1 = $this->createMock(IShare::class);
- $share2 = $this->createMock(IShare::class);
- $share3 = $this->createMock(IShare::class);
- $share4 = $this->createMock(IShare::class);
-
- $folder = $this->createMock(Folder::class);
-
- $this->defaultProvider->method('getSharesInFolder')
- ->with(
- $this->equalTo('user'),
- $this->equalTo($folder),
- $this->equalTo(false)
- )->willReturn([
- 1 => [$share1],
- 2 => [$share2],
- ]);
-
- $extraProvider->method('getSharesInFolder')
- ->with(
- $this->equalTo('user'),
- $this->equalTo($folder),
- $this->equalTo(false)
- )->willReturn([
- 2 => [$share3],
- 3 => [$share4],
- ]);
-
- $result = $manager->getSharesInFolder('user', $folder, false);
-
- $expects = [
- 1 => [$share1],
- 2 => [$share2, $share3],
- 3 => [$share4],
- ];
-
- $this->assertSame($expects, $result);
- }
-
- public function testGetAccessList() {
- $factory = new DummyFactory2($this->createMock(IServerContainer::class));
-
- $manager = $this->createManager($factory);
-
- $factory->setProvider($this->defaultProvider);
- $extraProvider = $this->createMock(IShareProvider::class);
- $factory->setSecondProvider($extraProvider);
-
- $nodeOwner = $this->createMock(IUser::class);
- $nodeOwner->expects($this->once())
- ->method('getUID')
- ->willReturn('user1');
-
- $node = $this->createMock(Node::class);
- $node->expects($this->once())
- ->method('getOwner')
- ->willReturn($nodeOwner);
- $node->method('getId')
- ->willReturn(42);
-
- $userFolder = $this->createMock(Folder::class);
- $file = $this->createMock(File::class);
- $folder = $this->createMock(Folder::class);
-
- $owner = $this->createMock(IUser::class);
- $owner->expects($this->once())
- ->method('getUID')
- ->willReturn('owner');
-
- $file->method('getParent')
- ->willReturn($folder);
- $file->method('getPath')
- ->willReturn('/owner/files/folder/file');
- $file->method('getOwner')
- ->willReturn($owner);
- $file->method('getId')
- ->willReturn(23);
- $folder->method('getParent')
- ->willReturn($userFolder);
- $folder->method('getPath')
- ->willReturn('/owner/files/folder');
- $userFolder->method('getFirstNodeById')
- ->with($this->equalTo(42))
- ->willReturn($file);
- $userFolder->method('getPath')
- ->willReturn('/user1/files');
-
- $this->userManager->method('userExists')
- ->with($this->equalTo('user1'))
- ->willReturn(true);
-
- $this->defaultProvider->method('getAccessList')
- ->with(
- $this->equalTo([$file, $folder]),
- false
- )
- ->willReturn([
- 'users' => [
- 'user1',
- 'user2',
- 'user3',
- '123456',
- ],
- 'public' => true,
- ]);
-
- $extraProvider->method('getAccessList')
- ->with(
- $this->equalTo([$file, $folder]),
- false
- )
- ->willReturn([
- 'users' => [
- 'user3',
- 'user4',
- 'user5',
- '234567',
- ],
- 'remote' => true,
- ]);
-
- $this->rootFolder->method('getUserFolder')
- ->with($this->equalTo('user1'))
- ->willReturn($userFolder);
-
- $expected = [
- 'users' => ['owner', 'user1', 'user2', 'user3', '123456','user4', 'user5', '234567'],
- 'remote' => true,
- 'public' => true,
- ];
-
- $result = $manager->getAccessList($node, true, false);
-
- $this->assertSame($expected['public'], $result['public']);
- $this->assertSame($expected['remote'], $result['remote']);
- $this->assertSame($expected['users'], $result['users']);
- }
-
- public function testGetAccessListWithCurrentAccess() {
- $factory = new DummyFactory2($this->createMock(IServerContainer::class));
-
- $manager = $this->createManager($factory);
-
- $factory->setProvider($this->defaultProvider);
- $extraProvider = $this->createMock(IShareProvider::class);
- $factory->setSecondProvider($extraProvider);
-
- $nodeOwner = $this->createMock(IUser::class);
- $nodeOwner->expects($this->once())
- ->method('getUID')
- ->willReturn('user1');
-
- $node = $this->createMock(Node::class);
- $node->expects($this->once())
- ->method('getOwner')
- ->willReturn($nodeOwner);
- $node->method('getId')
- ->willReturn(42);
-
- $userFolder = $this->createMock(Folder::class);
- $file = $this->createMock(File::class);
-
- $owner = $this->createMock(IUser::class);
- $owner->expects($this->once())
- ->method('getUID')
- ->willReturn('owner');
- $folder = $this->createMock(Folder::class);
-
- $file->method('getParent')
- ->willReturn($folder);
- $file->method('getPath')
- ->willReturn('/owner/files/folder/file');
- $file->method('getOwner')
- ->willReturn($owner);
- $file->method('getId')
- ->willReturn(23);
- $folder->method('getParent')
- ->willReturn($userFolder);
- $folder->method('getPath')
- ->willReturn('/owner/files/folder');
- $userFolder->method('getFirstNodeById')
- ->with($this->equalTo(42))
- ->willReturn($file);
- $userFolder->method('getPath')
- ->willReturn('/user1/files');
-
- $this->userManager->method('userExists')
- ->with($this->equalTo('user1'))
- ->willReturn(true);
-
- $this->defaultProvider->method('getAccessList')
- ->with(
- $this->equalTo([$file, $folder]),
- true
- )
- ->willReturn([
- 'users' => [
- 'user1' => [],
- 'user2' => [],
- 'user3' => [],
- '123456' => [],
- ],
- 'public' => true,
- ]);
-
- $extraProvider->method('getAccessList')
- ->with(
- $this->equalTo([$file, $folder]),
- true
- )
- ->willReturn([
- 'users' => [
- 'user3' => [],
- 'user4' => [],
- 'user5' => [],
- '234567' => [],
- ],
- 'remote' => [
- 'remote1',
- ],
- ]);
-
- $this->rootFolder->method('getUserFolder')
- ->with($this->equalTo('user1'))
- ->willReturn($userFolder);
-
- $expected = [
- 'users' => [
- 'owner' => [
- 'node_id' => 23,
- 'node_path' => '/folder/file'
- ]
- , 'user1' => [], 'user2' => [], 'user3' => [], '123456' => [], 'user4' => [], 'user5' => [], '234567' => []],
- 'remote' => [
- 'remote1',
- ],
- 'public' => true,
- ];
-
- $result = $manager->getAccessList($node, true, true);
-
- $this->assertSame($expected['public'], $result['public']);
- $this->assertSame($expected['remote'], $result['remote']);
- $this->assertSame($expected['users'], $result['users']);
- }
-
- public function testGetAllShares() {
- $factory = new DummyFactory2($this->createMock(IServerContainer::class));
-
- $manager = $this->createManager($factory);
-
- $factory->setProvider($this->defaultProvider);
- $extraProvider = $this->createMock(IShareProvider::class);
- $factory->setSecondProvider($extraProvider);
-
- $share1 = $this->createMock(IShare::class);
- $share2 = $this->createMock(IShare::class);
- $share3 = $this->createMock(IShare::class);
- $share4 = $this->createMock(IShare::class);
-
- $this->defaultProvider->method('getAllShares')
- ->willReturnCallback(function () use ($share1, $share2) {
- yield $share1;
- yield $share2;
- });
- $extraProvider->method('getAllShares')
- ->willReturnCallback(function () use ($share3, $share4) {
- yield $share3;
- yield $share4;
- });
-
- // "yield from", used in "getAllShares()", does not reset the keys, so
- // "use_keys" has to be disabled to collect all the values while
- // ignoring the keys returned by the generator.
- $result = iterator_to_array($manager->getAllShares(), $use_keys = false);
-
- $expects = [$share1, $share2, $share3, $share4];
-
- $this->assertSame($expects, $result);
- }
-
- public function dataCurrentUserCanEnumerateTargetUser(): array {
- return [
- 'Full match guest' => [true, true, false, false, false, false, false, true],
- 'Full match user' => [false, true, false, false, false, false, false, true],
- 'Enumeration off guest' => [true, false, false, false, false, false, false, false],
- 'Enumeration off user' => [false, false, false, false, false, false, false, false],
- 'Enumeration guest' => [true, false, true, false, false, false, false, true],
- 'Enumeration user' => [false, false, true, false, false, false, false, true],
-
- // Restricted enumerations guests never works
- 'Guest phone' => [true, false, true, true, false, false, false, false],
- 'Guest group' => [true, false, true, false, true, false, false, false],
- 'Guest both' => [true, false, true, true, true, false, false, false],
-
- // Restricted enumerations users
- 'User phone but not known' => [false, false, true, true, false, false, false, false],
- 'User phone known' => [false, false, true, true, false, true, false, true],
- 'User group but no match' => [false, false, true, false, true, false, false, false],
- 'User group with match' => [false, false, true, false, true, false, true, true],
- ];
- }
-
- /**
- * @dataProvider dataCurrentUserCanEnumerateTargetUser
- * @param bool $expected
- */
- 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()
- ->setMethods([
- 'allowEnumerationFullMatch',
- 'allowEnumeration',
- 'limitEnumerationToPhone',
- 'limitEnumerationToGroups',
- ])
- ->getMock();
-
- $manager->method('allowEnumerationFullMatch')
- ->willReturn($allowEnumerationFullMatch);
- $manager->method('allowEnumeration')
- ->willReturn($allowEnumeration);
- $manager->method('limitEnumerationToPhone')
- ->willReturn($limitEnumerationToPhone);
- $manager->method('limitEnumerationToGroups')
- ->willReturn($limitEnumerationToGroups);
-
- $this->knownUserService->method('isKnownToUser')
- ->with('current', 'target')
- ->willReturn($isKnownToUser);
-
- $currentUser = null;
- if (!$currentUserIsGuest) {
- $currentUser = $this->createMock(IUser::class);
- $currentUser->method('getUID')
- ->willReturn('current');
- }
- $targetUser = $this->createMock(IUser::class);
- $targetUser->method('getUID')
- ->willReturn('target');
-
- if ($haveCommonGroup) {
- $this->groupManager->method('getUserGroupIds')
- ->willReturnMap([
- [$targetUser, ['gid1', 'gid2']],
- [$currentUser, ['gid2', 'gid3']],
- ]);
- } else {
- $this->groupManager->method('getUserGroupIds')
- ->willReturnMap([
- [$targetUser, ['gid1', 'gid2']],
- [$currentUser, ['gid3', 'gid4']],
- ]);
- }
-
- $this->assertSame($expected, $manager->currentUserCanEnumerateTargetUser($currentUser, $targetUser));
- }
-}
-
-class DummyFactory implements IProviderFactory {
- /** @var IShareProvider */
- protected $provider;
-
- public function __construct(\OCP\IServerContainer $serverContainer) {
- }
-
- /**
- * @param IShareProvider $provider
- */
- public function setProvider($provider) {
- $this->provider = $provider;
- }
-
- /**
- * @param string $id
- * @return IShareProvider
- */
- public function getProvider($id) {
- return $this->provider;
- }
-
- /**
- * @param int $shareType
- * @return IShareProvider
- */
- public function getProviderForType($shareType) {
- return $this->provider;
- }
-
- /**
- * @return IShareProvider[]
- */
- public function getAllProviders() {
- return [$this->provider];
- }
-
- public function registerProvider(string $shareProvier): void {
- }
-}
-
-class DummyFactory2 extends DummyFactory {
- /** @var IShareProvider */
- private $provider2;
-
- /**
- * @param IShareProvider $provider
- */
- public function setSecondProvider($provider) {
- $this->provider2 = $provider;
- }
-
- public function getAllProviders() {
- return [$this->provider, $this->provider2];
- }
-
- public function registerProvider(string $shareProvier): void {
- }
-}
+<?php
+/**
+ * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
+ */
+
+namespace Test\Share20;
+
+use DateTimeZone;
+use OC\Files\Mount\MoveableMount;
+use OC\KnownUser\KnownUserService;
+use OC\Share20\DefaultShareProvider;
+use OC\Share20\Exception;
+use OC\Share20\Manager;
+use OC\Share20\Share;
+use OC\Share20\ShareDisableChecker;
+use OCP\EventDispatcher\Event;
+use OCP\EventDispatcher\IEventDispatcher;
+use OCP\Files\File;
+use OCP\Files\Folder;
+use OCP\Files\IRootFolder;
+use OCP\Files\Mount\IMountManager;
+use OCP\Files\Mount\IMountPoint;
+use OCP\Files\Node;
+use OCP\Files\Storage;
+use OCP\HintException;
+use OCP\IConfig;
+use OCP\IDateTimeZone;
+use OCP\IGroup;
+use OCP\IGroupManager;
+use OCP\IL10N;
+use OCP\IServerContainer;
+use OCP\IURLGenerator;
+use OCP\IUser;
+use OCP\IUserManager;
+use OCP\IUserSession;
+use OCP\L10N\IFactory;
+use OCP\Mail\IMailer;
+use OCP\Security\Events\ValidatePasswordPolicyEvent;
+use OCP\Security\IHasher;
+use OCP\Security\ISecureRandom;
+use OCP\Share\Events\BeforeShareCreatedEvent;
+use OCP\Share\Events\BeforeShareDeletedEvent;
+use OCP\Share\Events\ShareCreatedEvent;
+use OCP\Share\Events\ShareDeletedEvent;
+use OCP\Share\Events\ShareDeletedFromSelfEvent;
+use OCP\Share\Exceptions\AlreadySharedException;
+use OCP\Share\Exceptions\ShareNotFound;
+use OCP\Share\IManager;
+use OCP\Share\IProviderFactory;
+use OCP\Share\IShare;
+use OCP\Share\IShareProvider;
+use PHPUnit\Framework\MockObject\MockBuilder;
+use PHPUnit\Framework\MockObject\MockObject;
+use Psr\Log\LoggerInterface;
+
+/**
+ * Class ManagerTest
+ *
+ * @package Test\Share20
+ * @group DB
+ */
+class ManagerTest extends \Test\TestCase {
+ /** @var Manager */
+ protected $manager;
+ /** @var LoggerInterface|MockObject */
+ protected $logger;
+ /** @var IConfig|MockObject */
+ protected $config;
+ /** @var ISecureRandom|MockObject */
+ protected $secureRandom;
+ /** @var IHasher|MockObject */
+ protected $hasher;
+ /** @var IShareProvider|MockObject */
+ protected $defaultProvider;
+ /** @var IMountManager|MockObject */
+ protected $mountManager;
+ /** @var IGroupManager|MockObject */
+ protected $groupManager;
+ /** @var IL10N|MockObject */
+ protected $l;
+ /** @var IFactory|MockObject */
+ protected $l10nFactory;
+ /** @var DummyFactory */
+ protected $factory;
+ /** @var IUserManager|MockObject */
+ protected $userManager;
+ /** @var IRootFolder | MockObject */
+ protected $rootFolder;
+ /** @var IEventDispatcher|MockObject */
+ protected $dispatcher;
+ /** @var IMailer|MockObject */
+ protected $mailer;
+ /** @var IURLGenerator|MockObject */
+ protected $urlGenerator;
+ /** @var \OC_Defaults|MockObject */
+ protected $defaults;
+ /** @var IUserSession|MockObject */
+ protected $userSession;
+ /** @var KnownUserService|MockObject */
+ protected $knownUserService;
+ /** @var ShareDisableChecker|MockObject */
+ protected $shareDisabledChecker;
+ private DateTimeZone $timezone;
+ /** @var IDateTimeZone|MockObject */
+ protected $dateTimeZone;
+
+ protected function setUp(): void {
+ $this->logger = $this->createMock(LoggerInterface::class);
+ $this->config = $this->createMock(IConfig::class);
+ $this->secureRandom = $this->createMock(ISecureRandom::class);
+ $this->hasher = $this->createMock(IHasher::class);
+ $this->mountManager = $this->createMock(IMountManager::class);
+ $this->groupManager = $this->createMock(IGroupManager::class);
+ $this->userManager = $this->createMock(IUserManager::class);
+ $this->rootFolder = $this->createMock(IRootFolder::class);
+ $this->mailer = $this->createMock(IMailer::class);
+ $this->urlGenerator = $this->createMock(IURLGenerator::class);
+ $this->defaults = $this->createMock(\OC_Defaults::class);
+ $this->dispatcher = $this->createMock(IEventDispatcher::class);
+ $this->userSession = $this->createMock(IUserSession::class);
+ $this->knownUserService = $this->createMock(KnownUserService::class);
+
+ $this->shareDisabledChecker = new ShareDisableChecker($this->config, $this->userManager, $this->groupManager);
+ $this->dateTimeZone = $this->createMock(IDateTimeZone::class);
+ $this->timezone = new \DateTimeZone('Pacific/Auckland');
+ $this->dateTimeZone->method('getTimeZone')->willReturnCallback(fn () => $this->timezone);
+
+ $this->l10nFactory = $this->createMock(IFactory::class);
+ $this->l = $this->createMock(IL10N::class);
+ $this->l->method('t')
+ ->willReturnCallback(function ($text, $parameters = []) {
+ return vsprintf($text, $parameters);
+ });
+ $this->l->method('n')
+ ->willReturnCallback(function ($singular, $plural, $count, $parameters = []) {
+ return vsprintf(str_replace('%n', $count, ($count === 1) ? $singular : $plural), $parameters);
+ });
+ $this->l10nFactory->method('get')->willReturn($this->l);
+
+ $this->factory = new DummyFactory(\OC::$server);
+
+ $this->manager = $this->createManager($this->factory);
+
+ $this->defaultProvider = $this->createMock(DefaultShareProvider::class);
+ $this->defaultProvider->method('identifier')->willReturn('default');
+ $this->factory->setProvider($this->defaultProvider);
+ }
+
+ private function createManager(IProviderFactory $factory): Manager {
+ return new Manager(
+ $this->logger,
+ $this->config,
+ $this->secureRandom,
+ $this->hasher,
+ $this->mountManager,
+ $this->groupManager,
+ $this->l10nFactory,
+ $factory,
+ $this->userManager,
+ $this->rootFolder,
+ $this->mailer,
+ $this->urlGenerator,
+ $this->defaults,
+ $this->dispatcher,
+ $this->userSession,
+ $this->knownUserService,
+ $this->shareDisabledChecker,
+ $this->dateTimeZone,
+ );
+ }
+
+ /**
+ * @return MockBuilder
+ */
+ private function createManagerMock() {
+ return $this->getMockBuilder(Manager::class)
+ ->setConstructorArgs([
+ $this->logger,
+ $this->config,
+ $this->secureRandom,
+ $this->hasher,
+ $this->mountManager,
+ $this->groupManager,
+ $this->l10nFactory,
+ $this->factory,
+ $this->userManager,
+ $this->rootFolder,
+ $this->mailer,
+ $this->urlGenerator,
+ $this->defaults,
+ $this->dispatcher,
+ $this->userSession,
+ $this->knownUserService,
+ $this->shareDisabledChecker,
+ $this->dateTimeZone,
+ ]);
+ }
+
+
+ public function testDeleteNoShareId(): void {
+ $this->expectException(\InvalidArgumentException::class);
+
+ $share = $this->manager->newShare();
+
+ $this->manager->deleteShare($share);
+ }
+
+ public function dataTestDelete() {
+ $user = $this->createMock(IUser::class);
+ $user->method('getUID')->willReturn('sharedWithUser');
+
+ $group = $this->createMock(IGroup::class);
+ $group->method('getGID')->willReturn('sharedWithGroup');
+
+ return [
+ [IShare::TYPE_USER, 'sharedWithUser'],
+ [IShare::TYPE_GROUP, 'sharedWithGroup'],
+ [IShare::TYPE_LINK, ''],
+ [IShare::TYPE_REMOTE, 'foo@bar.com'],
+ ];
+ }
+
+ /**
+ * @dataProvider dataTestDelete
+ */
+ public function testDelete($shareType, $sharedWith): void {
+ $manager = $this->createManagerMock()
+ ->setMethods(['getShareById', 'deleteChildren'])
+ ->getMock();
+
+ $manager->method('deleteChildren')->willReturn([]);
+
+ $path = $this->createMock(File::class);
+ $path->method('getId')->willReturn(1);
+
+ $share = $this->manager->newShare();
+ $share->setId(42)
+ ->setProviderId('prov')
+ ->setShareType($shareType)
+ ->setSharedWith($sharedWith)
+ ->setSharedBy('sharedBy')
+ ->setNode($path)
+ ->setTarget('myTarget');
+
+ $manager->expects($this->once())->method('deleteChildren')->with($share);
+
+ $this->defaultProvider
+ ->expects($this->once())
+ ->method('delete')
+ ->with($share);
+
+ $this->dispatcher->expects($this->exactly(2))
+ ->method('dispatchTyped')
+ ->withConsecutive(
+ [
+ $this->callBack(function (BeforeShareDeletedEvent $e) use ($share) {
+ return $e->getShare() === $share;
+ })],
+ [
+ $this->callBack(function (ShareDeletedEvent $e) use ($share) {
+ return $e->getShare() === $share;
+ })]
+ );
+
+ $manager->deleteShare($share);
+ }
+
+ public function testDeleteLazyShare(): void {
+ $manager = $this->createManagerMock()
+ ->setMethods(['getShareById', 'deleteChildren'])
+ ->getMock();
+
+ $manager->method('deleteChildren')->willReturn([]);
+
+ $share = $this->manager->newShare();
+ $share->setId(42)
+ ->setProviderId('prov')
+ ->setShareType(IShare::TYPE_USER)
+ ->setSharedWith('sharedWith')
+ ->setSharedBy('sharedBy')
+ ->setShareOwner('shareOwner')
+ ->setTarget('myTarget')
+ ->setNodeId(1)
+ ->setNodeType('file');
+
+ $this->rootFolder->expects($this->never())->method($this->anything());
+
+ $manager->expects($this->once())->method('deleteChildren')->with($share);
+
+ $this->defaultProvider
+ ->expects($this->once())
+ ->method('delete')
+ ->with($share);
+
+ $this->dispatcher->expects($this->exactly(2))
+ ->method('dispatchTyped')
+ ->withConsecutive(
+ [
+ $this->callBack(function (BeforeShareDeletedEvent $e) use ($share) {
+ return $e->getShare() === $share;
+ })],
+ [
+ $this->callBack(function (ShareDeletedEvent $e) use ($share) {
+ return $e->getShare() === $share;
+ })]
+ );
+
+ $manager->deleteShare($share);
+ }
+
+ public function testDeleteNested(): void {
+ $manager = $this->createManagerMock()
+ ->setMethods(['getShareById'])
+ ->getMock();
+
+ $path = $this->createMock(File::class);
+ $path->method('getId')->willReturn(1);
+
+ $share1 = $this->manager->newShare();
+ $share1->setId(42)
+ ->setProviderId('prov')
+ ->setShareType(IShare::TYPE_USER)
+ ->setSharedWith('sharedWith1')
+ ->setSharedBy('sharedBy1')
+ ->setNode($path)
+ ->setTarget('myTarget1');
+
+ $share2 = $this->manager->newShare();
+ $share2->setId(43)
+ ->setProviderId('prov')
+ ->setShareType(IShare::TYPE_GROUP)
+ ->setSharedWith('sharedWith2')
+ ->setSharedBy('sharedBy2')
+ ->setNode($path)
+ ->setTarget('myTarget2')
+ ->setParent(42);
+
+ $share3 = $this->manager->newShare();
+ $share3->setId(44)
+ ->setProviderId('prov')
+ ->setShareType(IShare::TYPE_LINK)
+ ->setSharedBy('sharedBy3')
+ ->setNode($path)
+ ->setTarget('myTarget3')
+ ->setParent(43);
+
+ $this->defaultProvider
+ ->method('getChildren')
+ ->willReturnMap([
+ [$share1, [$share2]],
+ [$share2, [$share3]],
+ [$share3, []],
+ ]);
+
+ $this->defaultProvider
+ ->method('delete')
+ ->withConsecutive([$share3], [$share2], [$share1]);
+
+ $this->dispatcher->expects($this->exactly(6))
+ ->method('dispatchTyped')
+ ->withConsecutive(
+ [
+ $this->callBack(function (BeforeShareDeletedEvent $e) use ($share1) {
+ return $e->getShare()->getId() === $share1->getId();
+ })
+ ],
+ [
+ $this->callBack(function (BeforeShareDeletedEvent $e) use ($share2) {
+ return $e->getShare()->getId() === $share2->getId();
+ })
+ ],
+ [
+ $this->callBack(function (BeforeShareDeletedEvent $e) use ($share3) {
+ return $e->getShare()->getId() === $share3->getId();
+ })
+ ],
+ [
+ $this->callBack(function (ShareDeletedEvent $e) use ($share3) {
+ return $e->getShare()->getId() === $share3->getId();
+ })
+ ],
+ [
+ $this->callBack(function (ShareDeletedEvent $e) use ($share2) {
+ return $e->getShare()->getId() === $share2->getId();
+ })
+ ],
+ [
+ $this->callBack(function (ShareDeletedEvent $e) use ($share1) {
+ return $e->getShare()->getId() === $share1->getId();
+ })
+ ],
+ );
+
+ $manager->deleteShare($share1);
+ }
+
+ public function testDeleteFromSelf(): void {
+ $manager = $this->createManagerMock()
+ ->setMethods(['getShareById'])
+ ->getMock();
+
+ $recipientId = 'unshareFrom';
+ $share = $this->manager->newShare();
+ $share->setId(42)
+ ->setProviderId('prov')
+ ->setShareType(IShare::TYPE_USER)
+ ->setSharedWith('sharedWith')
+ ->setSharedBy('sharedBy')
+ ->setShareOwner('shareOwner')
+ ->setTarget('myTarget')
+ ->setNodeId(1)
+ ->setNodeType('file');
+
+ $this->defaultProvider
+ ->expects($this->once())
+ ->method('deleteFromSelf')
+ ->with($share, $recipientId);
+
+ $this->dispatcher->expects($this->once())
+ ->method('dispatchTyped')
+ ->with(
+ $this->callBack(function (ShareDeletedFromSelfEvent $e) use ($share) {
+ return $e->getShare() === $share;
+ })
+ );
+
+ $manager->deleteFromSelf($share, $recipientId);
+ }
+
+ public function testDeleteChildren(): void {
+ $manager = $this->createManagerMock()
+ ->setMethods(['deleteShare'])
+ ->getMock();
+
+ $share = $this->createMock(IShare::class);
+ $share->method('getShareType')->willReturn(IShare::TYPE_USER);
+
+ $child1 = $this->createMock(IShare::class);
+ $child1->method('getShareType')->willReturn(IShare::TYPE_USER);
+ $child2 = $this->createMock(IShare::class);
+ $child2->method('getShareType')->willReturn(IShare::TYPE_USER);
+ $child3 = $this->createMock(IShare::class);
+ $child3->method('getShareType')->willReturn(IShare::TYPE_USER);
+
+ $shares = [
+ $child1,
+ $child2,
+ $child3,
+ ];
+
+ $this->defaultProvider
+ ->expects($this->exactly(4))
+ ->method('getChildren')
+ ->willReturnCallback(function ($_share) use ($share, $shares) {
+ if ($_share === $share) {
+ return $shares;
+ }
+ return [];
+ });
+
+ $this->defaultProvider
+ ->expects($this->exactly(3))
+ ->method('delete')
+ ->withConsecutive([$child1], [$child2], [$child3]);
+
+ $result = self::invokePrivate($manager, 'deleteChildren', [$share]);
+ $this->assertSame($shares, $result);
+ }
+
+ public function testGetShareById(): void {
+ $share = $this->createMock(IShare::class);
+
+ $this->defaultProvider
+ ->expects($this->once())
+ ->method('getShareById')
+ ->with(42)
+ ->willReturn($share);
+
+ $this->assertEquals($share, $this->manager->getShareById('default:42'));
+ }
+
+
+ public function testGetExpiredShareById(): void {
+ $this->expectException(\OCP\Share\Exceptions\ShareNotFound::class);
+
+ $manager = $this->createManagerMock()
+ ->setMethods(['deleteShare'])
+ ->getMock();
+
+ $date = new \DateTime();
+ $date->setTime(0, 0, 0);
+
+ $share = $this->manager->newShare();
+ $share->setExpirationDate($date)
+ ->setShareType(IShare::TYPE_LINK);
+
+ $this->defaultProvider->expects($this->once())
+ ->method('getShareById')
+ ->with('42')
+ ->willReturn($share);
+
+ $manager->expects($this->once())
+ ->method('deleteShare')
+ ->with($share);
+
+ $manager->getShareById('default:42');
+ }
+
+
+ public function testVerifyPasswordNullButEnforced(): void {
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('Passwords are enforced for link and mail shares');
+
+ $this->config->method('getAppValue')->willReturnMap([
+ ['core', 'shareapi_enforce_links_password_excluded_groups', '', ''],
+ ['core', 'shareapi_enforce_links_password', 'no', 'yes'],
+ ]);
+
+ self::invokePrivate($this->manager, 'verifyPassword', [null]);
+ }
+
+ public function testVerifyPasswordNotEnforcedGroup(): void {
+ $this->config->method('getAppValue')->willReturnMap([
+ ['core', 'shareapi_enforce_links_password_excluded_groups', '', '["admin"]'],
+ ['core', 'shareapi_enforce_links_password', 'no', 'yes'],
+ ]);
+
+ // Create admin user
+ $user = $this->createMock(IUser::class);
+ $this->userSession->method('getUser')->willReturn($user);
+ $this->groupManager->method('getUserGroupIds')->with($user)->willReturn(['admin']);
+
+ $result = self::invokePrivate($this->manager, 'verifyPassword', [null]);
+ $this->assertNull($result);
+ }
+
+ public function testVerifyPasswordNotEnforcedMultipleGroups(): void {
+ $this->config->method('getAppValue')->willReturnMap([
+ ['core', 'shareapi_enforce_links_password_excluded_groups', '', '["admin", "special"]'],
+ ['core', 'shareapi_enforce_links_password', 'no', 'yes'],
+ ]);
+
+ // Create admin user
+ $user = $this->createMock(IUser::class);
+ $this->userSession->method('getUser')->willReturn($user);
+ $this->groupManager->method('getUserGroupIds')->with($user)->willReturn(['special']);
+
+ $result = self::invokePrivate($this->manager, 'verifyPassword', [null]);
+ $this->assertNull($result);
+ }
+
+ public function testVerifyPasswordNull(): void {
+ $this->config->method('getAppValue')->willReturnMap([
+ ['core', 'shareapi_enforce_links_password_excluded_groups', '', ''],
+ ['core', 'shareapi_enforce_links_password', 'no', 'no'],
+ ]);
+
+ $result = self::invokePrivate($this->manager, 'verifyPassword', [null]);
+ $this->assertNull($result);
+ }
+
+ public function testVerifyPasswordHook(): void {
+ $this->config->method('getAppValue')->willReturnMap([
+ ['core', 'shareapi_enforce_links_password_excluded_groups', '', ''],
+ ['core', 'shareapi_enforce_links_password', 'no', 'no'],
+ ]);
+
+ $this->dispatcher->expects($this->once())->method('dispatchTyped')
+ ->willReturnCallback(function (Event $event) {
+ $this->assertInstanceOf(ValidatePasswordPolicyEvent::class, $event);
+ /** @var ValidatePasswordPolicyEvent $event */
+ $this->assertSame('password', $event->getPassword());
+ }
+ );
+
+ $result = self::invokePrivate($this->manager, 'verifyPassword', ['password']);
+ $this->assertNull($result);
+ }
+
+
+ public function testVerifyPasswordHookFails(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('password not accepted');
+
+ $this->config->method('getAppValue')->willReturnMap([
+ ['core', 'shareapi_enforce_links_password_excluded_groups', '', ''],
+ ['core', 'shareapi_enforce_links_password', 'no', 'no'],
+ ]);
+
+ $this->dispatcher->expects($this->once())->method('dispatchTyped')
+ ->willReturnCallback(function (Event $event) {
+ $this->assertInstanceOf(ValidatePasswordPolicyEvent::class, $event);
+ /** @var ValidatePasswordPolicyEvent $event */
+ $this->assertSame('password', $event->getPassword());
+ throw new HintException('message', 'password not accepted');
+ }
+ );
+
+ self::invokePrivate($this->manager, 'verifyPassword', ['password']);
+ }
+
+ public function createShare($id, $type, $node, $sharedWith, $sharedBy, $shareOwner,
+ $permissions, $expireDate = null, $password = null, $attributes = null) {
+ $share = $this->createMock(IShare::class);
+
+ $share->method('getShareType')->willReturn($type);
+ $share->method('getSharedWith')->willReturn($sharedWith);
+ $share->method('getSharedBy')->willReturn($sharedBy);
+ $share->method('getShareOwner')->willReturn($shareOwner);
+ $share->method('getNode')->willReturn($node);
+ if ($node && $node->getId()) {
+ $share->method('getNodeId')->willReturn($node->getId());
+ }
+ $share->method('getPermissions')->willReturn($permissions);
+ $share->method('getAttributes')->willReturn($attributes);
+ $share->method('getExpirationDate')->willReturn($expireDate);
+ $share->method('getPassword')->willReturn($password);
+
+ return $share;
+ }
+
+ public function dataGeneralChecks() {
+ $user0 = 'user0';
+ $user2 = 'user1';
+ $group0 = 'group0';
+ $owner = $this->createMock(IUser::class);
+ $owner->method('getUID')
+ ->willReturn($user0);
+
+ $file = $this->createMock(File::class);
+ $node = $this->createMock(Node::class);
+ $storage = $this->createMock(Storage\IStorage::class);
+ $storage->method('instanceOfStorage')
+ ->with(\OCA\Files_Sharing\External\Storage::class)
+ ->willReturn(false);
+ $file->method('getStorage')
+ ->willReturn($storage);
+ $file->method('getId')->willReturn(108);
+ $node->method('getStorage')
+ ->willReturn($storage);
+ $node->method('getId')->willReturn(108);
+
+ $data = [
+ [$this->createShare(null, IShare::TYPE_USER, $file, null, $user0, $user0, 31, null, null), 'SharedWith is not a valid user', true],
+ [$this->createShare(null, IShare::TYPE_USER, $file, $group0, $user0, $user0, 31, null, null), 'SharedWith is not a valid user', true],
+ [$this->createShare(null, IShare::TYPE_USER, $file, 'foo@bar.com', $user0, $user0, 31, null, null), 'SharedWith is not a valid user', true],
+ [$this->createShare(null, IShare::TYPE_GROUP, $file, null, $user0, $user0, 31, null, null), 'SharedWith is not a valid group', true],
+ [$this->createShare(null, IShare::TYPE_GROUP, $file, $user2, $user0, $user0, 31, null, null), 'SharedWith is not a valid group', true],
+ [$this->createShare(null, IShare::TYPE_GROUP, $file, 'foo@bar.com', $user0, $user0, 31, null, null), 'SharedWith is not a valid group', true],
+ [$this->createShare(null, IShare::TYPE_LINK, $file, $user2, $user0, $user0, 31, null, null), 'SharedWith should be empty', true],
+ [$this->createShare(null, IShare::TYPE_LINK, $file, $group0, $user0, $user0, 31, null, null), 'SharedWith should be empty', true],
+ [$this->createShare(null, IShare::TYPE_LINK, $file, 'foo@bar.com', $user0, $user0, 31, null, null), 'SharedWith should be empty', true],
+ [$this->createShare(null, -1, $file, null, $user0, $user0, 31, null, null), 'Unknown share type', true],
+
+ [$this->createShare(null, IShare::TYPE_USER, $file, $user2, null, $user0, 31, null, null), 'SharedBy should be set', true],
+ [$this->createShare(null, IShare::TYPE_GROUP, $file, $group0, null, $user0, 31, null, null), 'SharedBy should be set', true],
+ [$this->createShare(null, IShare::TYPE_LINK, $file, null, null, $user0, 31, null, null), 'SharedBy should be set', true],
+
+ [$this->createShare(null, IShare::TYPE_USER, $file, $user0, $user0, $user0, 31, null, null), 'Cannot share with yourself', true],
+
+ [$this->createShare(null, IShare::TYPE_USER, null, $user2, $user0, $user0, 31, null, null), 'Path should be set', true],
+ [$this->createShare(null, IShare::TYPE_GROUP, null, $group0, $user0, $user0, 31, null, null), 'Path should be set', true],
+ [$this->createShare(null, IShare::TYPE_LINK, null, null, $user0, $user0, 31, null, null), 'Path should be set', true],
+
+ [$this->createShare(null, IShare::TYPE_USER, $node, $user2, $user0, $user0, 31, null, null), 'Path should be either a file or a folder', true],
+ [$this->createShare(null, IShare::TYPE_GROUP, $node, $group0, $user0, $user0, 31, null, null), 'Path should be either a file or a folder', true],
+ [$this->createShare(null, IShare::TYPE_LINK, $node, null, $user0, $user0, 31, null, null), 'Path should be either a file or a folder', true],
+ ];
+
+ $nonShareAble = $this->createMock(Folder::class);
+ $nonShareAble->method('getId')->willReturn(108);
+ $nonShareAble->method('isShareable')->willReturn(false);
+ $nonShareAble->method('getPath')->willReturn('path');
+ $nonShareAble->method('getName')->willReturn('name');
+ $nonShareAble->method('getOwner')
+ ->willReturn($owner);
+ $nonShareAble->method('getStorage')
+ ->willReturn($storage);
+
+ $data[] = [$this->createShare(null, IShare::TYPE_USER, $nonShareAble, $user2, $user0, $user0, 31, null, null), 'You are not allowed to share name', true];
+ $data[] = [$this->createShare(null, IShare::TYPE_GROUP, $nonShareAble, $group0, $user0, $user0, 31, null, null), 'You are not allowed to share name', true];
+ $data[] = [$this->createShare(null, IShare::TYPE_LINK, $nonShareAble, null, $user0, $user0, 31, null, null), 'You are not allowed to share name', true];
+
+ $limitedPermssions = $this->createMock(File::class);
+ $limitedPermssions->method('isShareable')->willReturn(true);
+ $limitedPermssions->method('getPermissions')->willReturn(\OCP\Constants::PERMISSION_READ);
+ $limitedPermssions->method('getId')->willReturn(108);
+ $limitedPermssions->method('getPath')->willReturn('path');
+ $limitedPermssions->method('getName')->willReturn('name');
+ $limitedPermssions->method('getOwner')
+ ->willReturn($owner);
+ $limitedPermssions->method('getStorage')
+ ->willReturn($storage);
+
+ $data[] = [$this->createShare(null, IShare::TYPE_USER, $limitedPermssions, $user2, $user0, $user0, null, null, null), 'A share requires permissions', true];
+ $data[] = [$this->createShare(null, IShare::TYPE_GROUP, $limitedPermssions, $group0, $user0, $user0, null, null, null), 'A share requires permissions', true];
+ $data[] = [$this->createShare(null, IShare::TYPE_LINK, $limitedPermssions, null, $user0, $user0, null, null, null), 'A share requires permissions', true];
+
+ $mount = $this->createMock(MoveableMount::class);
+ $limitedPermssions->method('getMountPoint')->willReturn($mount);
+
+
+ $data[] = [$this->createShare(null, IShare::TYPE_USER, $limitedPermssions, $user2, $user0, $user0, 31, null, null), 'Cannot increase permissions of path', true];
+ $data[] = [$this->createShare(null, IShare::TYPE_GROUP, $limitedPermssions, $group0, $user0, $user0, 17, null, null), 'Cannot increase permissions of path', true];
+ $data[] = [$this->createShare(null, IShare::TYPE_LINK, $limitedPermssions, null, $user0, $user0, 3, null, null), 'Cannot increase permissions of path', true];
+
+ $nonMovableStorage = $this->createMock(Storage\IStorage::class);
+ $nonMovableStorage->method('instanceOfStorage')
+ ->with(\OCA\Files_Sharing\External\Storage::class)
+ ->willReturn(false);
+ $nonMovableStorage->method('getPermissions')->willReturn(\OCP\Constants::PERMISSION_ALL);
+ $nonMoveableMountPermssions = $this->createMock(Folder::class);
+ $nonMoveableMountPermssions->method('isShareable')->willReturn(true);
+ $nonMoveableMountPermssions->method('getPermissions')->willReturn(\OCP\Constants::PERMISSION_READ);
+ $nonMoveableMountPermssions->method('getId')->willReturn(108);
+ $nonMoveableMountPermssions->method('getPath')->willReturn('path');
+ $nonMoveableMountPermssions->method('getName')->willReturn('name');
+ $nonMoveableMountPermssions->method('getInternalPath')->willReturn('');
+ $nonMoveableMountPermssions->method('getOwner')
+ ->willReturn($owner);
+ $nonMoveableMountPermssions->method('getStorage')
+ ->willReturn($nonMovableStorage);
+
+ $data[] = [$this->createShare(null, IShare::TYPE_USER, $nonMoveableMountPermssions, $user2, $user0, $user0, 11, null, null), 'Cannot increase permissions of path', false];
+ $data[] = [$this->createShare(null, IShare::TYPE_GROUP, $nonMoveableMountPermssions, $group0, $user0, $user0, 11, null, null), 'Cannot increase permissions of path', false];
+
+ $rootFolder = $this->createMock(Folder::class);
+ $rootFolder->method('isShareable')->willReturn(true);
+ $rootFolder->method('getPermissions')->willReturn(\OCP\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];
+ $data[] = [$this->createShare(null, IShare::TYPE_GROUP, $rootFolder, $group0, $user0, $user0, 2, null, null), 'You cannot share your root folder', true];
+ $data[] = [$this->createShare(null, IShare::TYPE_LINK, $rootFolder, null, $user0, $user0, 16, null, null), 'You cannot share your root folder', true];
+
+ $allPermssions = $this->createMock(Folder::class);
+ $allPermssions->method('isShareable')->willReturn(true);
+ $allPermssions->method('getPermissions')->willReturn(\OCP\Constants::PERMISSION_ALL);
+ $allPermssions->method('getId')->willReturn(108);
+ $allPermssions->method('getOwner')
+ ->willReturn($owner);
+ $allPermssions->method('getStorage')
+ ->willReturn($storage);
+
+ $data[] = [$this->createShare(null, IShare::TYPE_USER, $allPermssions, $user2, $user0, $user0, 30, null, null), 'Shares need at least read permissions', true];
+ $data[] = [$this->createShare(null, IShare::TYPE_GROUP, $allPermssions, $group0, $user0, $user0, 2, null, null), 'Shares need at least read permissions', true];
+
+ $data[] = [$this->createShare(null, IShare::TYPE_USER, $allPermssions, $user2, $user0, $user0, 31, null, null), null, false];
+ $data[] = [$this->createShare(null, IShare::TYPE_GROUP, $allPermssions, $group0, $user0, $user0, 3, null, null), null, false];
+ $data[] = [$this->createShare(null, IShare::TYPE_LINK, $allPermssions, null, $user0, $user0, 17, null, null), null, false];
+
+
+ $remoteStorage = $this->createMock(Storage\IStorage::class);
+ $remoteStorage->method('instanceOfStorage')
+ ->with(\OCA\Files_Sharing\External\Storage::class)
+ ->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('getId')->willReturn(108);
+ $remoteFile->method('getOwner')
+ ->willReturn($owner);
+ $remoteFile->method('getStorage')
+ ->willReturn($storage);
+ $data[] = [$this->createShare(null, IShare::TYPE_REMOTE, $remoteFile, $user2, $user0, $user0, 1, null, null), null, false];
+ $data[] = [$this->createShare(null, IShare::TYPE_REMOTE, $remoteFile, $user2, $user0, $user0, 3, null, null), null, false];
+ $data[] = [$this->createShare(null, IShare::TYPE_REMOTE, $remoteFile, $user2, $user0, $user0, 31, null, null), 'Cannot increase permissions of ', true];
+
+ return $data;
+ }
+
+ /**
+ * @dataProvider dataGeneralChecks
+ *
+ * @param $share
+ * @param $exceptionMessage
+ * @param $exception
+ */
+ public function testGeneralChecks($share, $exceptionMessage, $exception): void {
+ $thrown = null;
+
+ $this->userManager->method('userExists')->willReturnMap([
+ ['user0', true],
+ ['user1', true],
+ ]);
+
+ $this->groupManager->method('groupExists')->willReturnMap([
+ ['group0', true],
+ ]);
+
+ $userFolder = $this->createMock(Folder::class);
+ $userFolder->expects($this->any())
+ ->method('getId')
+ ->willReturn(42);
+ // Id 108 is used in the data to refer to the node of the share.
+ $userFolder->method('getById')
+ ->with(108)
+ ->willReturn([$share->getNode()]);
+ $userFolder->expects($this->any())
+ ->method('getRelativePath')
+ ->willReturnArgument(0);
+ $this->rootFolder->method('getUserFolder')->willReturn($userFolder);
+
+
+ try {
+ self::invokePrivate($this->manager, 'generalCreateChecks', [$share]);
+ $thrown = false;
+ } catch (\OCP\Share\Exceptions\GenericShareException $e) {
+ $this->assertEquals($exceptionMessage, $e->getHint());
+ $thrown = true;
+ } catch (\InvalidArgumentException $e) {
+ $this->assertEquals($exceptionMessage, $e->getMessage());
+ $thrown = true;
+ }
+
+ $this->assertSame($exception, $thrown);
+ }
+
+
+ public function testGeneralCheckShareRoot(): void {
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('You cannot share your root folder');
+
+ $thrown = null;
+
+ $this->userManager->method('userExists')->willReturnMap([
+ ['user0', true],
+ ['user1', true],
+ ]);
+
+ $userFolder = $this->createMock(Folder::class);
+ $userFolder->method('isSubNode')->with($userFolder)->willReturn(false);
+ $this->rootFolder->method('getUserFolder')->willReturn($userFolder);
+
+ $share = $this->manager->newShare();
+
+ $share->setShareType(IShare::TYPE_USER)
+ ->setSharedWith('user0')
+ ->setSharedBy('user1')
+ ->setNode($userFolder);
+
+ self::invokePrivate($this->manager, 'generalCreateChecks', [$share]);
+ }
+
+ public function validateExpirationDateInternalProvider() {
+ return [[IShare::TYPE_USER], [IShare::TYPE_REMOTE], [IShare::TYPE_REMOTE_GROUP]];
+ }
+
+ /**
+ * @dataProvider validateExpirationDateInternalProvider
+ */
+ public function testValidateExpirationDateInternalInPast($shareType): void {
+ $this->expectException(\OCP\Share\Exceptions\GenericShareException::class);
+ $this->expectExceptionMessage('Expiration date is in the past');
+
+ // Expire date in the past
+ $past = new \DateTime();
+ $past->sub(new \DateInterval('P1D'));
+
+ $share = $this->manager->newShare();
+ $share->setShareType($shareType);
+ $share->setExpirationDate($past);
+
+ self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
+ }
+
+ /**
+ * @dataProvider validateExpirationDateInternalProvider
+ */
+ public function testValidateExpirationDateInternalEnforceButNotSet($shareType): void {
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('Expiration date is enforced');
+
+ $share = $this->manager->newShare();
+ $share->setProviderId('foo')->setId('bar');
+ $share->setShareType($shareType);
+ if ($shareType === IShare::TYPE_USER) {
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_default_internal_expire_date', 'no', 'yes'],
+ ['core', 'shareapi_enforce_internal_expire_date', 'no', 'yes'],
+ ]);
+ } else {
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_default_remote_expire_date', 'no', 'yes'],
+ ['core', 'shareapi_enforce_remote_expire_date', 'no', 'yes'],
+ ]);
+ }
+
+ self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
+ }
+
+ /**
+ * @dataProvider validateExpirationDateInternalProvider
+ */
+ public function testValidateExpirationDateInternalEnforceButNotEnabledAndNotSet($shareType): void {
+ $share = $this->manager->newShare();
+ $share->setProviderId('foo')->setId('bar');
+ $share->setShareType($shareType);
+
+ if ($shareType === IShare::TYPE_USER) {
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_enforce_internal_expire_date', 'no', 'yes'],
+ ]);
+ } else {
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_enforce_remote_expire_date', 'no', 'yes'],
+ ]);
+ }
+
+ self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
+
+ $this->assertNull($share->getExpirationDate());
+ }
+
+ /**
+ * @dataProvider validateExpirationDateInternalProvider
+ */
+ public function testValidateExpirationDateInternalEnforceButNotSetNewShare($shareType): void {
+ $share = $this->manager->newShare();
+ $share->setShareType($shareType);
+
+ if ($shareType === IShare::TYPE_USER) {
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_enforce_internal_expire_date', 'no', 'yes'],
+ ['core', 'shareapi_internal_expire_after_n_days', '7', '3'],
+ ['core', 'shareapi_default_internal_expire_date', 'no', 'yes'],
+ ['core', 'internal_defaultExpDays', '3', '3'],
+ ]);
+ } else {
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_enforce_remote_expire_date', 'no', 'yes'],
+ ['core', 'shareapi_remote_expire_after_n_days', '7', '3'],
+ ['core', 'shareapi_default_remote_expire_date', 'no', 'yes'],
+ ['core', 'remote_defaultExpDays', '3', '3'],
+ ]);
+ }
+
+ $expected = new \DateTime('now', $this->timezone);
+ $expected->setTime(0, 0, 0);
+ $expected->add(new \DateInterval('P3D'));
+
+ self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
+
+ $this->assertNotNull($share->getExpirationDate());
+ $this->assertEquals($expected, $share->getExpirationDate());
+ }
+
+ /**
+ * @dataProvider validateExpirationDateInternalProvider
+ */
+ public function testValidateExpirationDateInternalEnforceRelaxedDefaultButNotSetNewShare($shareType): void {
+ $share = $this->manager->newShare();
+ $share->setShareType($shareType);
+
+ if ($shareType === IShare::TYPE_USER) {
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_enforce_internal_expire_date', 'no', 'yes'],
+ ['core', 'shareapi_internal_expire_after_n_days', '7', '3'],
+ ['core', 'shareapi_default_internal_expire_date', 'no', 'yes'],
+ ['core', 'internal_defaultExpDays', '3', '1'],
+ ]);
+ } else {
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_enforce_remote_expire_date', 'no', 'yes'],
+ ['core', 'shareapi_remote_expire_after_n_days', '7', '3'],
+ ['core', 'shareapi_default_remote_expire_date', 'no', 'yes'],
+ ['core', 'remote_defaultExpDays', '3', '1'],
+ ]);
+ }
+
+ $expected = new \DateTime('now', $this->timezone);
+ $expected->setTime(0, 0, 0);
+ $expected->add(new \DateInterval('P1D'));
+
+ self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
+
+ $this->assertNotNull($share->getExpirationDate());
+ $this->assertEquals($expected, $share->getExpirationDate());
+ }
+
+ /**
+ * @dataProvider validateExpirationDateInternalProvider
+ */
+ public function testValidateExpirationDateInternalEnforceTooFarIntoFuture($shareType): void {
+ $this->expectException(\OCP\Share\Exceptions\GenericShareException::class);
+ $this->expectExceptionMessage('Cannot set expiration date more than 3 days in the future');
+
+ $future = new \DateTime();
+ $future->add(new \DateInterval('P7D'));
+
+ $share = $this->manager->newShare();
+ $share->setShareType($shareType);
+ $share->setExpirationDate($future);
+
+ if ($shareType === IShare::TYPE_USER) {
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_enforce_internal_expire_date', 'no', 'yes'],
+ ['core', 'shareapi_internal_expire_after_n_days', '7', '3'],
+ ['core', 'shareapi_default_internal_expire_date', 'no', 'yes'],
+ ]);
+ } else {
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_enforce_remote_expire_date', 'no', 'yes'],
+ ['core', 'shareapi_remote_expire_after_n_days', '7', '3'],
+ ['core', 'shareapi_default_remote_expire_date', 'no', 'yes'],
+ ]);
+ }
+
+ self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
+ }
+
+ /**
+ * @dataProvider validateExpirationDateInternalProvider
+ */
+ public function testValidateExpirationDateInternalEnforceValid($shareType): void {
+ $future = new \DateTime('now', $this->dateTimeZone->getTimeZone());
+ $future->add(new \DateInterval('P2D'));
+ $future->setTime(1, 2, 3);
+
+ $expected = clone $future;
+ $expected->setTime(0, 0, 0);
+
+ $share = $this->manager->newShare();
+ $share->setShareType($shareType);
+ $share->setExpirationDate($future);
+
+ if ($shareType === IShare::TYPE_USER) {
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_enforce_internal_expire_date', 'no', 'yes'],
+ ['core', 'shareapi_internal_expire_after_n_days', '7', '3'],
+ ['core', 'shareapi_default_internal_expire_date', 'no', 'yes'],
+ ]);
+ } else {
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_enforce_remote_expire_date', 'no', 'yes'],
+ ['core', 'shareapi_remote_expire_after_n_days', '7', '3'],
+ ['core', 'shareapi_default_remote_expire_date', 'no', 'yes'],
+ ]);
+ }
+
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
+ \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener');
+ $hookListener->expects($this->once())->method('listener')->with($this->callback(function ($data) use ($future) {
+ return $data['expirationDate'] == $future;
+ }));
+
+ self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
+
+ $this->assertEquals($expected, $share->getExpirationDate());
+ }
+
+ /**
+ * @dataProvider validateExpirationDateInternalProvider
+ */
+ public function testValidateExpirationDateInternalNoDefault($shareType): void {
+ $date = new \DateTime('now', $this->dateTimeZone->getTimeZone());
+ $date->add(new \DateInterval('P5D'));
+ $date->setTime(1, 2, 3);
+
+ $expected = clone $date;
+ $expected->setTime(0, 0, 0);
+
+ $share = $this->manager->newShare();
+ $share->setShareType($shareType);
+ $share->setExpirationDate($date);
+
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
+ \OCP\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;
+ }));
+
+ self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
+
+ $this->assertEquals($expected, $share->getExpirationDate());
+ }
+
+ /**
+ * @dataProvider validateExpirationDateInternalProvider
+ */
+ public function testValidateExpirationDateInternalNoDateNoDefault($shareType): void {
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
+ \OCP\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;
+ }));
+
+ $share = $this->manager->newShare();
+ $share->setShareType($shareType);
+ $share->setPassword('password');
+
+ self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
+
+ $this->assertNull($share->getExpirationDate());
+ }
+
+ /**
+ * @dataProvider validateExpirationDateInternalProvider
+ */
+ public function testValidateExpirationDateInternalNoDateDefault($shareType): void {
+ $share = $this->manager->newShare();
+ $share->setShareType($shareType);
+
+ $expected = new \DateTime('now', $this->timezone);
+ $expected->setTime(0, 0);
+ $expected->add(new \DateInterval('P3D'));
+ $expected->setTimezone(new \DateTimeZone(date_default_timezone_get()));
+
+ if ($shareType === IShare::TYPE_USER) {
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_default_internal_expire_date', 'no', 'yes'],
+ ['core', 'shareapi_internal_expire_after_n_days', '7', '3'],
+ ['core', 'internal_defaultExpDays', '3', '3'],
+ ]);
+ } else {
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_default_remote_expire_date', 'no', 'yes'],
+ ['core', 'shareapi_remote_expire_after_n_days', '7', '3'],
+ ['core', 'remote_defaultExpDays', '3', '3'],
+ ]);
+ }
+
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
+ \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener');
+ $hookListener->expects($this->once())->method('listener')->with($this->callback(function ($data) use ($expected) {
+ return $data['expirationDate'] == $expected;
+ }));
+
+ self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
+
+ $this->assertEquals($expected, $share->getExpirationDate());
+ }
+
+ /**
+ * @dataProvider validateExpirationDateInternalProvider
+ */
+ public function testValidateExpirationDateInternalDefault($shareType): void {
+ $future = new \DateTime('now', $this->timezone);
+ $future->add(new \DateInterval('P5D'));
+ $future->setTime(1, 2, 3);
+
+ $expected = clone $future;
+ $expected->setTime(0, 0);
+
+ $share = $this->manager->newShare();
+ $share->setShareType($shareType);
+ $share->setExpirationDate($future);
+
+ if ($shareType === IShare::TYPE_USER) {
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_default_internal_expire_date', 'no', 'yes'],
+ ['core', 'shareapi_internal_expire_after_n_days', '7', '3'],
+ ['core', 'internal_defaultExpDays', '3', '1'],
+ ]);
+ } else {
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_default_remote_expire_date', 'no', 'yes'],
+ ['core', 'shareapi_remote_expire_after_n_days', '7', '3'],
+ ['core', 'remote_defaultExpDays', '3', '1'],
+ ]);
+ }
+
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
+ \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener');
+ $hookListener->expects($this->once())->method('listener')->with($this->callback(function ($data) use ($expected) {
+ return $data['expirationDate'] == $expected;
+ }));
+
+ self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
+
+ $this->assertEquals($expected, $share->getExpirationDate());
+ }
+
+ /**
+ * @dataProvider validateExpirationDateInternalProvider
+ */
+ public function testValidateExpirationDateInternalHookModification($shareType): void {
+ $nextWeek = new \DateTime('now', $this->timezone);
+ $nextWeek->add(new \DateInterval('P7D'));
+ $nextWeek->setTime(0, 0, 0);
+
+ $save = clone $nextWeek;
+
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
+ \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener');
+ $hookListener->expects($this->once())->method('listener')->willReturnCallback(function ($data) {
+ $data['expirationDate']->sub(new \DateInterval('P2D'));
+ });
+
+ $share = $this->manager->newShare();
+ $share->setShareType($shareType);
+ $share->setExpirationDate($nextWeek);
+
+ self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
+
+ $save->sub(new \DateInterval('P2D'));
+ $this->assertEquals($save, $share->getExpirationDate());
+ }
+
+ /**
+ * @dataProvider validateExpirationDateInternalProvider
+ */
+ public function testValidateExpirationDateInternalHookException($shareType): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('Invalid date!');
+
+ $nextWeek = new \DateTime();
+ $nextWeek->add(new \DateInterval('P7D'));
+ $nextWeek->setTime(0, 0, 0);
+
+ $share = $this->manager->newShare();
+ $share->setShareType($shareType);
+ $share->setExpirationDate($nextWeek);
+
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
+ \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener');
+ $hookListener->expects($this->once())->method('listener')->willReturnCallback(function ($data) {
+ $data['accepted'] = false;
+ $data['message'] = 'Invalid date!';
+ });
+
+ self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
+ }
+
+ /**
+ * @dataProvider validateExpirationDateInternalProvider
+ */
+ public function testValidateExpirationDateInternalExistingShareNoDefault($shareType): void {
+ $share = $this->manager->newShare();
+ $share->setShareType($shareType);
+ $share->setId('42')->setProviderId('foo');
+
+ if ($shareType === IShare::TYPE_USER) {
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_default_internal_expire_date', 'no', 'yes'],
+ ['core', 'shareapi_internal_expire_after_n_days', '7', '6'],
+ ]);
+ } else {
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_default_remote_expire_date', 'no', 'yes'],
+ ['core', 'shareapi_remote_expire_after_n_days', '7', '6'],
+ ]);
+ }
+
+ self::invokePrivate($this->manager, 'validateExpirationDateInternal', [$share]);
+
+ $this->assertEquals(null, $share->getExpirationDate());
+ }
+
+ public function testValidateExpirationDateInPast(): void {
+ $this->expectException(\OCP\Share\Exceptions\GenericShareException::class);
+ $this->expectExceptionMessage('Expiration date is in the past');
+
+ // Expire date in the past
+ $past = new \DateTime();
+ $past->sub(new \DateInterval('P1D'));
+
+ $share = $this->manager->newShare();
+ $share->setExpirationDate($past);
+
+ self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
+ }
+
+ public function testValidateExpirationDateEnforceButNotSet(): void {
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('Expiration date is enforced');
+
+ $share = $this->manager->newShare();
+ $share->setProviderId('foo')->setId('bar');
+
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_default_expire_date', 'no', 'yes'],
+ ['core', 'shareapi_enforce_expire_date', 'no', 'yes'],
+ ]);
+
+ self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
+ }
+
+ public function testValidateExpirationDateEnforceButNotEnabledAndNotSet(): void {
+ $share = $this->manager->newShare();
+ $share->setProviderId('foo')->setId('bar');
+
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_enforce_expire_date', 'no', 'yes'],
+ ]);
+
+ self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
+
+ $this->assertNull($share->getExpirationDate());
+ }
+
+ public function testValidateExpirationDateEnforceButNotSetNewShare(): void {
+ $share = $this->manager->newShare();
+
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_enforce_expire_date', 'no', 'yes'],
+ ['core', 'shareapi_expire_after_n_days', '7', '3'],
+ ['core', 'shareapi_default_expire_date', 'no', 'yes'],
+ ['core', 'link_defaultExpDays', '3', '3'],
+ ]);
+
+ $expected = new \DateTime('now', $this->timezone);
+ $expected->setTime(0, 0, 0);
+ $expected->add(new \DateInterval('P3D'));
+
+ self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
+
+ $this->assertNotNull($share->getExpirationDate());
+ $this->assertEquals($expected, $share->getExpirationDate());
+ }
+
+ public function testValidateExpirationDateEnforceRelaxedDefaultButNotSetNewShare(): void {
+ $share = $this->manager->newShare();
+
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_enforce_expire_date', 'no', 'yes'],
+ ['core', 'shareapi_expire_after_n_days', '7', '3'],
+ ['core', 'shareapi_default_expire_date', 'no', 'yes'],
+ ['core', 'link_defaultExpDays', '3', '1'],
+ ]);
+
+ $expected = new \DateTime('now', $this->timezone);
+ $expected->setTime(0, 0, 0);
+ $expected->add(new \DateInterval('P1D'));
+
+ self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
+
+ $this->assertNotNull($share->getExpirationDate());
+ $this->assertEquals($expected, $share->getExpirationDate());
+ }
+
+ public function testValidateExpirationDateEnforceTooFarIntoFuture(): void {
+ $this->expectException(\OCP\Share\Exceptions\GenericShareException::class);
+ $this->expectExceptionMessage('Cannot set expiration date more than 3 days in the future');
+
+ $future = new \DateTime();
+ $future->add(new \DateInterval('P7D'));
+
+ $share = $this->manager->newShare();
+ $share->setExpirationDate($future);
+
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_enforce_expire_date', 'no', 'yes'],
+ ['core', 'shareapi_expire_after_n_days', '7', '3'],
+ ['core', 'shareapi_default_expire_date', 'no', 'yes'],
+ ]);
+
+ self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
+ }
+
+ public function testValidateExpirationDateEnforceValid(): void {
+ $future = new \DateTime('now', $this->timezone);
+ $future->add(new \DateInterval('P2D'));
+ $future->setTime(1, 2, 3);
+
+ $expected = clone $future;
+ $expected->setTime(0, 0, 0);
+
+ $share = $this->manager->newShare();
+ $share->setExpirationDate($future);
+
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_enforce_expire_date', 'no', 'yes'],
+ ['core', 'shareapi_expire_after_n_days', '7', '3'],
+ ['core', 'shareapi_default_expire_date', 'no', 'yes'],
+ ]);
+
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
+ \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener');
+ $hookListener->expects($this->once())->method('listener')->with($this->callback(function ($data) use ($future) {
+ return $data['expirationDate'] == $future;
+ }));
+
+ self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
+
+ $this->assertEquals($expected, $share->getExpirationDate());
+ }
+
+ public function testValidateExpirationDateNoDefault(): void {
+ $date = new \DateTime('now', $this->timezone);
+ $date->add(new \DateInterval('P5D'));
+ $date->setTime(1, 2, 3);
+
+ $expected = clone $date;
+ $expected->setTime(0, 0);
+ $expected->setTimezone(new \DateTimeZone(date_default_timezone_get()));
+
+ $share = $this->manager->newShare();
+ $share->setExpirationDate($date);
+
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
+ \OCP\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;
+ }));
+
+ self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
+
+ $this->assertEquals($expected, $share->getExpirationDate());
+ }
+
+ public function testValidateExpirationDateNoDateNoDefault(): void {
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
+ \OCP\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;
+ }));
+
+ $share = $this->manager->newShare();
+ $share->setPassword('password');
+
+ self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
+
+ $this->assertNull($share->getExpirationDate());
+ }
+
+ public function testValidateExpirationDateNoDateDefault(): void {
+ $share = $this->manager->newShare();
+
+ $expected = new \DateTime('now', $this->timezone);
+ $expected->add(new \DateInterval('P3D'));
+ $expected->setTime(0, 0);
+ $expected->setTimezone(new \DateTimeZone(date_default_timezone_get()));
+
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_default_expire_date', 'no', 'yes'],
+ ['core', 'shareapi_expire_after_n_days', '7', '3'],
+ ['core', 'link_defaultExpDays', '3', '3'],
+ ]);
+
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
+ \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener');
+ $hookListener->expects($this->once())->method('listener')->with($this->callback(function ($data) use ($expected) {
+ return $data['expirationDate'] == $expected;
+ }));
+
+ self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
+
+ $this->assertEquals($expected, $share->getExpirationDate());
+ }
+
+ public function testValidateExpirationDateDefault(): void {
+ $future = new \DateTime('now', $this->timezone);
+ $future->add(new \DateInterval('P5D'));
+ $future->setTime(1, 2, 3);
+
+ $expected = clone $future;
+ $expected->setTime(0, 0);
+ $expected->setTimezone(new \DateTimeZone(date_default_timezone_get()));
+
+ $share = $this->manager->newShare();
+ $share->setExpirationDate($future);
+
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_default_expire_date', 'no', 'yes'],
+ ['core', 'shareapi_expire_after_n_days', '7', '3'],
+ ['core', 'link_defaultExpDays', '3', '1'],
+ ]);
+
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
+ \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener');
+ $hookListener->expects($this->once())->method('listener')->with($this->callback(function ($data) use ($expected) {
+ return $data['expirationDate'] == $expected;
+ }));
+
+ self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
+
+ $this->assertEquals($expected, $share->getExpirationDate());
+ }
+
+ public function testValidateExpirationNegativeOffsetTimezone(): void {
+ $this->timezone = new \DateTimeZone('Pacific/Tahiti');
+ $future = new \DateTime();
+ $future->add(new \DateInterval('P5D'));
+
+ $expected = clone $future;
+ $expected->setTimezone($this->timezone);
+ $expected->setTime(0, 0);
+ $expected->setTimezone(new \DateTimeZone(date_default_timezone_get()));
+
+ $share = $this->manager->newShare();
+ $share->setExpirationDate($future);
+
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_default_expire_date', 'no', 'yes'],
+ ['core', 'shareapi_expire_after_n_days', '7', '3'],
+ ['core', 'link_defaultExpDays', '3', '1'],
+ ]);
+
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
+ \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener');
+ $hookListener->expects($this->once())->method('listener')->with($this->callback(function ($data) use ($expected) {
+ return $data['expirationDate'] == $expected;
+ }));
+
+ self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
+
+ $this->assertEquals($expected, $share->getExpirationDate());
+ }
+
+ public function testValidateExpirationDateHookModification(): void {
+ $nextWeek = new \DateTime('now', $this->timezone);
+ $nextWeek->add(new \DateInterval('P7D'));
+
+ $save = clone $nextWeek;
+ $save->setTime(0, 0);
+ $save->sub(new \DateInterval('P2D'));
+ $save->setTimezone(new \DateTimeZone(date_default_timezone_get()));
+
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
+ \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener');
+ $hookListener->expects($this->once())->method('listener')->willReturnCallback(function ($data) {
+ $data['expirationDate']->sub(new \DateInterval('P2D'));
+ });
+
+ $share = $this->manager->newShare();
+ $share->setExpirationDate($nextWeek);
+
+ self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
+
+ $this->assertEquals($save, $share->getExpirationDate());
+ }
+
+ public function testValidateExpirationDateHookException(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('Invalid date!');
+
+ $nextWeek = new \DateTime();
+ $nextWeek->add(new \DateInterval('P7D'));
+ $nextWeek->setTime(0, 0, 0);
+
+ $share = $this->manager->newShare();
+ $share->setExpirationDate($nextWeek);
+
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock();
+ \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListener, 'listener');
+ $hookListener->expects($this->once())->method('listener')->willReturnCallback(function ($data) {
+ $data['accepted'] = false;
+ $data['message'] = 'Invalid date!';
+ });
+
+ self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
+ }
+
+ public function testValidateExpirationDateExistingShareNoDefault(): void {
+ $share = $this->manager->newShare();
+
+ $share->setId('42')->setProviderId('foo');
+
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_default_expire_date', 'no', 'yes'],
+ ['core', 'shareapi_expire_after_n_days', '7', '6'],
+ ]);
+
+ self::invokePrivate($this->manager, 'validateExpirationDateLink', [$share]);
+
+ $this->assertEquals(null, $share->getExpirationDate());
+ }
+
+ public function testUserCreateChecksShareWithGroupMembersOnlyDifferentGroups(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('Sharing is only allowed with group members');
+
+ $share = $this->manager->newShare();
+
+ $sharedBy = $this->createMock(IUser::class);
+ $sharedWith = $this->createMock(IUser::class);
+ $share->setSharedBy('sharedBy')->setSharedWith('sharedWith');
+
+ $this->groupManager
+ ->method('getUserGroupIds')
+ ->willReturnMap(
+ [
+ [$sharedBy, ['group1']],
+ [$sharedWith, ['group2']],
+ ]
+ );
+
+ $this->userManager->method('get')->willReturnMap([
+ ['sharedBy', $sharedBy],
+ ['sharedWith', $sharedWith],
+ ]);
+
+ $this->config
+ ->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_only_share_with_group_members', 'no', 'yes'],
+ ['core', 'shareapi_only_share_with_group_members_exclude_group_list', '', '[]'],
+ ]);
+
+ self::invokePrivate($this->manager, 'userCreateChecks', [$share]);
+ }
+
+ public function testUserCreateChecksShareWithGroupMembersOnlySharedGroup(): void {
+ $share = $this->manager->newShare();
+
+ $sharedBy = $this->createMock(IUser::class);
+ $sharedWith = $this->createMock(IUser::class);
+ $share->setSharedBy('sharedBy')->setSharedWith('sharedWith');
+
+ $path = $this->createMock(Node::class);
+ $share->setNode($path);
+
+ $this->groupManager
+ ->method('getUserGroupIds')
+ ->willReturnMap(
+ [
+ [$sharedBy, ['group1', 'group3']],
+ [$sharedWith, ['group2', 'group3']],
+ ]
+ );
+
+ $this->userManager->method('get')->willReturnMap([
+ ['sharedBy', $sharedBy],
+ ['sharedWith', $sharedWith],
+ ]);
+
+ $this->config
+ ->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_only_share_with_group_members', 'no', 'yes'],
+ ['core', 'shareapi_only_share_with_group_members_exclude_group_list', '', '[]'],
+ ]);
+
+ $this->defaultProvider
+ ->method('getSharesByPath')
+ ->with($path)
+ ->willReturn([]);
+
+ self::invokePrivate($this->manager, 'userCreateChecks', [$share]);
+ $this->addToAssertionCount(1);
+ }
+
+
+ public function testUserCreateChecksIdenticalShareExists(): void {
+ $this->expectException(AlreadySharedException::class);
+ $this->expectExceptionMessage('Sharing name.txt failed, because this item is already shared with the account user');
+
+ $share = $this->manager->newShare();
+ $share->setSharedWithDisplayName('user');
+ $share2 = $this->manager->newShare();
+
+ $sharedWith = $this->createMock(IUser::class);
+ $path = $this->createMock(Node::class);
+
+ $share->setSharedWith('sharedWith')->setNode($path)
+ ->setProviderId('foo')->setId('bar');
+
+ $share2->setSharedWith('sharedWith')->setNode($path)
+ ->setProviderId('foo')->setId('baz');
+
+ $this->defaultProvider
+ ->method('getSharesByPath')
+ ->with($path)
+ ->willReturn([$share2]);
+
+ $path->method('getName')
+ ->willReturn('name.txt');
+
+ self::invokePrivate($this->manager, 'userCreateChecks', [$share]);
+ }
+
+
+ public function testUserCreateChecksIdenticalPathSharedViaGroup(): void {
+ $this->expectException(AlreadySharedException::class);
+ $this->expectExceptionMessage('Sharing name2.txt failed, because this item is already shared with the account userName');
+
+ $share = $this->manager->newShare();
+
+ $sharedWith = $this->createMock(IUser::class);
+ $sharedWith->method('getUID')->willReturn('sharedWith');
+
+ $this->userManager->method('get')->with('sharedWith')->willReturn($sharedWith);
+
+ $path = $this->createMock(Node::class);
+
+ $share->setSharedWith('sharedWith')
+ ->setNode($path)
+ ->setShareOwner('shareOwner')
+ ->setSharedWithDisplayName('userName')
+ ->setProviderId('foo')
+ ->setId('bar');
+
+ $share2 = $this->manager->newShare();
+ $share2->setShareType(IShare::TYPE_GROUP)
+ ->setShareOwner('shareOwner2')
+ ->setProviderId('foo')
+ ->setId('baz')
+ ->setSharedWith('group');
+
+ $group = $this->createMock(IGroup::class);
+ $group->method('inGroup')
+ ->with($sharedWith)
+ ->willReturn(true);
+
+ $this->groupManager->method('get')->with('group')->willReturn($group);
+
+ $this->defaultProvider
+ ->method('getSharesByPath')
+ ->with($path)
+ ->willReturn([$share2]);
+
+ $path->method('getName')
+ ->willReturn('name2.txt');
+
+ self::invokePrivate($this->manager, 'userCreateChecks', [$share]);
+ }
+
+ public function testUserCreateChecksIdenticalPathSharedViaDeletedGroup(): void {
+ $share = $this->manager->newShare();
+
+ $sharedWith = $this->createMock(IUser::class);
+ $sharedWith->method('getUID')->willReturn('sharedWith');
+
+ $this->userManager->method('get')->with('sharedWith')->willReturn($sharedWith);
+
+ $path = $this->createMock(Node::class);
+
+ $share->setSharedWith('sharedWith')
+ ->setNode($path)
+ ->setShareOwner('shareOwner')
+ ->setProviderId('foo')
+ ->setId('bar');
+
+ $share2 = $this->manager->newShare();
+ $share2->setShareType(IShare::TYPE_GROUP)
+ ->setShareOwner('shareOwner2')
+ ->setProviderId('foo')
+ ->setId('baz')
+ ->setSharedWith('group');
+
+ $this->groupManager->method('get')->with('group')->willReturn(null);
+
+ $this->defaultProvider
+ ->method('getSharesByPath')
+ ->with($path)
+ ->willReturn([$share2]);
+
+ $this->assertNull($this->invokePrivate($this->manager, 'userCreateChecks', [$share]));
+ }
+
+ public function testUserCreateChecksIdenticalPathNotSharedWithUser(): void {
+ $share = $this->manager->newShare();
+ $sharedWith = $this->createMock(IUser::class);
+ $path = $this->createMock(Node::class);
+ $share->setSharedWith('sharedWith')
+ ->setNode($path)
+ ->setShareOwner('shareOwner')
+ ->setProviderId('foo')
+ ->setId('bar');
+
+ $this->userManager->method('get')->with('sharedWith')->willReturn($sharedWith);
+
+ $share2 = $this->manager->newShare();
+ $share2->setShareType(IShare::TYPE_GROUP)
+ ->setShareOwner('shareOwner2')
+ ->setProviderId('foo')
+ ->setId('baz');
+
+ $group = $this->createMock(IGroup::class);
+ $group->method('inGroup')
+ ->with($sharedWith)
+ ->willReturn(false);
+
+ $this->groupManager->method('get')->with('group')->willReturn($group);
+
+ $share2->setSharedWith('group');
+
+ $this->defaultProvider
+ ->method('getSharesByPath')
+ ->with($path)
+ ->willReturn([$share2]);
+
+ self::invokePrivate($this->manager, 'userCreateChecks', [$share]);
+ $this->addToAssertionCount(1);
+ }
+
+
+ public function testGroupCreateChecksShareWithGroupMembersGroupSharingNotAllowed(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('Group sharing is now allowed');
+
+ $share = $this->manager->newShare();
+
+ $this->config
+ ->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_allow_group_sharing', 'yes', 'no'],
+ ]);
+
+ self::invokePrivate($this->manager, 'groupCreateChecks', [$share]);
+ }
+
+
+ public function testGroupCreateChecksShareWithGroupMembersOnlyNotInGroup(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('Sharing is only allowed within your own groups');
+
+ $share = $this->manager->newShare();
+
+ $user = $this->createMock(IUser::class);
+ $group = $this->createMock(IGroup::class);
+ $share->setSharedBy('user')->setSharedWith('group');
+
+ $group->method('inGroup')->with($user)->willReturn(false);
+
+ $this->groupManager->method('get')->with('group')->willReturn($group);
+ $this->userManager->method('get')->with('user')->willReturn($user);
+
+ $this->config
+ ->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_only_share_with_group_members', 'no', 'yes'],
+ ['core', 'shareapi_allow_group_sharing', 'yes', 'yes'],
+ ['core', 'shareapi_only_share_with_group_members_exclude_group_list', '', '[]'],
+ ]);
+
+ self::invokePrivate($this->manager, 'groupCreateChecks', [$share]);
+ }
+
+
+ public function testGroupCreateChecksShareWithGroupMembersOnlyNullGroup(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('Sharing is only allowed within your own groups');
+
+ $share = $this->manager->newShare();
+
+ $user = $this->createMock(IUser::class);
+ $share->setSharedBy('user')->setSharedWith('group');
+
+ $this->groupManager->method('get')->with('group')->willReturn(null);
+ $this->userManager->method('get')->with('user')->willReturn($user);
+
+ $this->config
+ ->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_only_share_with_group_members', 'no', 'yes'],
+ ['core', 'shareapi_allow_group_sharing', 'yes', 'yes'],
+ ['core', 'shareapi_only_share_with_group_members_exclude_group_list', '', '[]'],
+ ]);
+
+ $this->assertNull($this->invokePrivate($this->manager, 'groupCreateChecks', [$share]));
+ }
+
+ public function testGroupCreateChecksShareWithGroupMembersOnlyInGroup(): void {
+ $share = $this->manager->newShare();
+
+ $user = $this->createMock(IUser::class);
+ $group = $this->createMock(IGroup::class);
+ $share->setSharedBy('user')->setSharedWith('group');
+
+ $this->userManager->method('get')->with('user')->willReturn($user);
+ $this->groupManager->method('get')->with('group')->willReturn($group);
+
+ $group->method('inGroup')->with($user)->willReturn(true);
+
+ $path = $this->createMock(Node::class);
+ $share->setNode($path);
+
+ $this->defaultProvider->method('getSharesByPath')
+ ->with($path)
+ ->willReturn([]);
+
+ $this->config
+ ->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_only_share_with_group_members', 'no', 'yes'],
+ ['core', 'shareapi_allow_group_sharing', 'yes', 'yes'],
+ ['core', 'shareapi_only_share_with_group_members_exclude_group_list', '', '[]'],
+ ]);
+
+ self::invokePrivate($this->manager, 'groupCreateChecks', [$share]);
+ $this->addToAssertionCount(1);
+ }
+
+
+ public function testGroupCreateChecksPathAlreadySharedWithSameGroup(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('Path is already shared with this group');
+
+ $share = $this->manager->newShare();
+
+ $path = $this->createMock(Node::class);
+ $share->setSharedWith('sharedWith')
+ ->setNode($path)
+ ->setProviderId('foo')
+ ->setId('bar');
+
+ $share2 = $this->manager->newShare();
+ $share2->setSharedWith('sharedWith')
+ ->setProviderId('foo')
+ ->setId('baz');
+
+ $this->defaultProvider->method('getSharesByPath')
+ ->with($path)
+ ->willReturn([$share2]);
+
+ $this->config
+ ->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_allow_group_sharing', 'yes', 'yes'],
+ ]);
+
+ self::invokePrivate($this->manager, 'groupCreateChecks', [$share]);
+ }
+
+ public function testGroupCreateChecksPathAlreadySharedWithDifferentGroup(): void {
+ $share = $this->manager->newShare();
+
+ $share->setSharedWith('sharedWith');
+
+ $path = $this->createMock(Node::class);
+ $share->setNode($path);
+
+ $share2 = $this->manager->newShare();
+ $share2->setSharedWith('sharedWith2');
+
+ $this->defaultProvider->method('getSharesByPath')
+ ->with($path)
+ ->willReturn([$share2]);
+
+ $this->config
+ ->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_allow_group_sharing', 'yes', 'yes'],
+ ]);
+
+ self::invokePrivate($this->manager, 'groupCreateChecks', [$share]);
+ $this->addToAssertionCount(1);
+ }
+
+
+ public function testLinkCreateChecksNoLinkSharesAllowed(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('Link sharing is not allowed');
+
+ $share = $this->manager->newShare();
+
+ $this->config
+ ->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_allow_links', 'yes', 'no'],
+ ]);
+
+ self::invokePrivate($this->manager, 'linkCreateChecks', [$share]);
+ }
+
+
+ public function testFileLinkCreateChecksNoPublicUpload(): void {
+ $share = $this->manager->newShare();
+
+ $share->setPermissions(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE);
+ $share->setNodeType('file');
+
+ $this->config
+ ->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_allow_links', 'yes', 'yes'],
+ ['core', 'shareapi_allow_public_upload', 'yes', 'no']
+ ]);
+
+ self::invokePrivate($this->manager, 'linkCreateChecks', [$share]);
+ $this->addToAssertionCount(1);
+ }
+
+ public function testFolderLinkCreateChecksNoPublicUpload(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('Public upload is not allowed');
+
+ $share = $this->manager->newShare();
+
+ $share->setPermissions(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE);
+ $share->setNodeType('folder');
+
+ $this->config
+ ->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_allow_links', 'yes', 'yes'],
+ ['core', 'shareapi_allow_public_upload', 'yes', 'no']
+ ]);
+
+ self::invokePrivate($this->manager, 'linkCreateChecks', [$share]);
+ }
+
+ public function testLinkCreateChecksPublicUpload(): void {
+ $share = $this->manager->newShare();
+
+ $share->setPermissions(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE);
+ $share->setSharedWith('sharedWith');
+ $folder = $this->createMock(\OC\Files\Node\Folder::class);
+ $share->setNode($folder);
+
+ $this->config
+ ->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_allow_links', 'yes', 'yes'],
+ ['core', 'shareapi_allow_public_upload', 'yes', 'yes']
+ ]);
+
+ self::invokePrivate($this->manager, 'linkCreateChecks', [$share]);
+ $this->addToAssertionCount(1);
+ }
+
+ public function testLinkCreateChecksReadOnly(): void {
+ $share = $this->manager->newShare();
+
+ $share->setPermissions(\OCP\Constants::PERMISSION_READ);
+ $share->setSharedWith('sharedWith');
+ $folder = $this->createMock(\OC\Files\Node\Folder::class);
+ $share->setNode($folder);
+
+ $this->config
+ ->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_allow_links', 'yes', 'yes'],
+ ['core', 'shareapi_allow_public_upload', 'yes', 'no']
+ ]);
+
+ self::invokePrivate($this->manager, 'linkCreateChecks', [$share]);
+ $this->addToAssertionCount(1);
+ }
+
+
+ public function testPathCreateChecksContainsSharedMount(): void {
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('Path contains files shared with you');
+
+ $path = $this->createMock(Folder::class);
+ $path->method('getPath')->willReturn('path');
+
+ $mount = $this->createMock(IMountPoint::class);
+ $storage = $this->createMock(Storage::class);
+ $mount->method('getStorage')->willReturn($storage);
+ $storage->method('instanceOfStorage')->with(\OCA\Files_Sharing\ISharedStorage::class)->willReturn(true);
+
+ $this->mountManager->method('findIn')->with('path')->willReturn([$mount]);
+
+ self::invokePrivate($this->manager, 'pathCreateChecks', [$path]);
+ }
+
+ public function testPathCreateChecksContainsNoSharedMount(): void {
+ $path = $this->createMock(Folder::class);
+ $path->method('getPath')->willReturn('path');
+
+ $mount = $this->createMock(IMountPoint::class);
+ $storage = $this->createMock(Storage::class);
+ $mount->method('getStorage')->willReturn($storage);
+ $storage->method('instanceOfStorage')->with(\OCA\Files_Sharing\ISharedStorage::class)->willReturn(false);
+
+ $this->mountManager->method('findIn')->with('path')->willReturn([$mount]);
+
+ self::invokePrivate($this->manager, 'pathCreateChecks', [$path]);
+ $this->addToAssertionCount(1);
+ }
+
+ public function testPathCreateChecksContainsNoFolder(): void {
+ $path = $this->createMock(File::class);
+
+ self::invokePrivate($this->manager, 'pathCreateChecks', [$path]);
+ $this->addToAssertionCount(1);
+ }
+
+ public function dataIsSharingDisabledForUser() {
+ $data = [];
+
+ // No exclude groups
+ $data[] = ['no', null, null, [], false];
+
+ // empty exclude / allow list, user no groups
+ $data[] = ['yes', '', json_encode(['']), [], false];
+ $data[] = ['allow', '', json_encode(['']), [], true];
+
+ // empty exclude / allow list, user groups
+ $data[] = ['yes', '', json_encode(['']), ['group1', 'group2'], false];
+ $data[] = ['allow', '', json_encode(['']), ['group1', 'group2'], true];
+
+ // Convert old list to json
+ $data[] = ['yes', 'group1,group2', json_encode(['group1', 'group2']), [], false];
+ $data[] = ['allow', 'group1,group2', json_encode(['group1', 'group2']), [], true];
+
+ // Old list partly groups in common
+ $data[] = ['yes', 'group1,group2', json_encode(['group1', 'group2']), ['group1', 'group3'], false];
+ $data[] = ['allow', 'group1,group2', json_encode(['group1', 'group2']), ['group1', 'group3'], false];
+
+ // Old list only groups in common
+ $data[] = ['yes', 'group1,group2', json_encode(['group1', 'group2']), ['group1'], true];
+ $data[] = ['allow', 'group1,group2', json_encode(['group1', 'group2']), ['group1'], false];
+
+ // New list partly in common
+ $data[] = ['yes', json_encode(['group1', 'group2']), null, ['group1', 'group3'], false];
+ $data[] = ['allow', json_encode(['group1', 'group2']), null, ['group1', 'group3'], false];
+
+ // New list only groups in common
+ $data[] = ['yes', json_encode(['group1', 'group2']), null, ['group2'], true];
+ $data[] = ['allow', json_encode(['group1', 'group2']), null, ['group2'], false];
+
+ return $data;
+ }
+
+ /**
+ * @dataProvider dataIsSharingDisabledForUser
+ *
+ * @param string $excludeGroups
+ * @param string $groupList
+ * @param string $setList
+ * @param string[] $groupIds
+ * @param bool $expected
+ */
+ public function testIsSharingDisabledForUser($excludeGroups, $groupList, $setList, $groupIds, $expected): void {
+ $user = $this->createMock(IUser::class);
+
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_exclude_groups', 'no', $excludeGroups],
+ ['core', 'shareapi_exclude_groups_list', '', $groupList],
+ ]);
+
+ if ($setList !== null) {
+ $this->config->expects($this->once())
+ ->method('setAppValue')
+ ->with('core', 'shareapi_exclude_groups_list', $setList);
+ } else {
+ $this->config->expects($this->never())
+ ->method('setAppValue');
+ }
+
+ $this->groupManager->method('getUserGroupIds')
+ ->with($user)
+ ->willReturn($groupIds);
+
+ $this->userManager->method('get')->with('user')->willReturn($user);
+
+ $res = $this->manager->sharingDisabledForUser('user');
+ $this->assertEquals($expected, $res);
+ }
+
+ public function dataCanShare() {
+ $data = [];
+
+ /*
+ * [expected, sharing enabled, disabled for user]
+ */
+
+ $data[] = [false, 'no', false];
+ $data[] = [false, 'no', true];
+ $data[] = [true, 'yes', false];
+ $data[] = [false, 'yes', true];
+
+ return $data;
+ }
+
+ /**
+ * @dataProvider dataCanShare
+ *
+ * @param bool $expected
+ * @param string $sharingEnabled
+ * @param bool $disabledForUser
+ */
+ public function testCanShare($expected, $sharingEnabled, $disabledForUser): void {
+ $this->config->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_enabled', 'yes', $sharingEnabled],
+ ]);
+
+ $manager = $this->createManagerMock()
+ ->setMethods(['sharingDisabledForUser'])
+ ->getMock();
+
+ $manager->method('sharingDisabledForUser')
+ ->with('user')
+ ->willReturn($disabledForUser);
+
+ $share = $this->manager->newShare();
+ $share->setSharedBy('user');
+
+ $exception = false;
+ try {
+ $res = self::invokePrivate($manager, 'canShare', [$share]);
+ } catch (\Exception $e) {
+ $exception = true;
+ }
+
+ $this->assertEquals($expected, !$exception);
+ }
+
+ public function testCreateShareUser(): void {
+ $manager = $this->createManagerMock()
+ ->setMethods(['canShare', 'generalCreateChecks', 'userCreateChecks', 'pathCreateChecks'])
+ ->getMock();
+
+ $shareOwner = $this->createMock(IUser::class);
+ $shareOwner->method('getUID')->willReturn('shareOwner');
+
+ $storage = $this->createMock(Storage::class);
+ $path = $this->createMock(File::class);
+ $path->method('getOwner')->willReturn($shareOwner);
+ $path->method('getName')->willReturn('target');
+ $path->method('getStorage')->willReturn($storage);
+
+ $share = $this->createShare(
+ null,
+ IShare::TYPE_USER,
+ $path,
+ 'sharedWith',
+ 'sharedBy',
+ null,
+ \OCP\Constants::PERMISSION_ALL);
+
+ $manager->expects($this->once())
+ ->method('canShare')
+ ->with($share)
+ ->willReturn(true);
+ $manager->expects($this->once())
+ ->method('generalCreateChecks')
+ ->with($share);
+ ;
+ $manager->expects($this->once())
+ ->method('userCreateChecks')
+ ->with($share);
+ ;
+ $manager->expects($this->once())
+ ->method('pathCreateChecks')
+ ->with($path);
+
+ $this->defaultProvider
+ ->expects($this->once())
+ ->method('create')
+ ->with($share)
+ ->willReturnArgument(0);
+
+ $share->expects($this->once())
+ ->method('setShareOwner')
+ ->with('shareOwner');
+ $share->expects($this->once())
+ ->method('setTarget')
+ ->with('/target');
+
+ $manager->createShare($share);
+ }
+
+ public function testCreateShareGroup(): void {
+ $manager = $this->createManagerMock()
+ ->setMethods(['canShare', 'generalCreateChecks', 'groupCreateChecks', 'pathCreateChecks'])
+ ->getMock();
+
+ $shareOwner = $this->createMock(IUser::class);
+ $shareOwner->method('getUID')->willReturn('shareOwner');
+
+ $storage = $this->createMock(Storage::class);
+ $path = $this->createMock(File::class);
+ $path->method('getOwner')->willReturn($shareOwner);
+ $path->method('getName')->willReturn('target');
+ $path->method('getStorage')->willReturn($storage);
+
+ $share = $this->createShare(
+ null,
+ IShare::TYPE_GROUP,
+ $path,
+ 'sharedWith',
+ 'sharedBy',
+ null,
+ \OCP\Constants::PERMISSION_ALL);
+
+ $manager->expects($this->once())
+ ->method('canShare')
+ ->with($share)
+ ->willReturn(true);
+ $manager->expects($this->once())
+ ->method('generalCreateChecks')
+ ->with($share);
+ ;
+ $manager->expects($this->once())
+ ->method('groupCreateChecks')
+ ->with($share);
+ ;
+ $manager->expects($this->once())
+ ->method('pathCreateChecks')
+ ->with($path);
+
+ $this->defaultProvider
+ ->expects($this->once())
+ ->method('create')
+ ->with($share)
+ ->willReturnArgument(0);
+
+ $share->expects($this->once())
+ ->method('setShareOwner')
+ ->with('shareOwner');
+ $share->expects($this->once())
+ ->method('setTarget')
+ ->with('/target');
+
+ $manager->createShare($share);
+ }
+
+ public function testCreateShareLink(): void {
+ $manager = $this->createManagerMock()
+ ->setMethods([
+ 'canShare',
+ 'generalCreateChecks',
+ 'linkCreateChecks',
+ 'pathCreateChecks',
+ 'validateExpirationDateLink',
+ 'verifyPassword',
+ 'setLinkParent',
+ ])
+ ->getMock();
+
+ $shareOwner = $this->createMock(IUser::class);
+ $shareOwner->method('getUID')->willReturn('shareOwner');
+
+ $storage = $this->createMock(Storage::class);
+ $path = $this->createMock(File::class);
+ $path->method('getOwner')->willReturn($shareOwner);
+ $path->method('getName')->willReturn('target');
+ $path->method('getId')->willReturn(1);
+ $path->method('getStorage')->willReturn($storage);
+
+ $date = new \DateTime();
+
+ $share = $this->manager->newShare();
+ $share->setShareType(IShare::TYPE_LINK)
+ ->setNode($path)
+ ->setSharedBy('sharedBy')
+ ->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ ->setExpirationDate($date)
+ ->setPassword('password');
+
+ $manager->expects($this->once())
+ ->method('canShare')
+ ->with($share)
+ ->willReturn(true);
+ $manager->expects($this->once())
+ ->method('generalCreateChecks')
+ ->with($share);
+ ;
+ $manager->expects($this->once())
+ ->method('linkCreateChecks')
+ ->with($share);
+ ;
+ $manager->expects($this->once())
+ ->method('pathCreateChecks')
+ ->with($path);
+ $manager->expects($this->once())
+ ->method('validateExpirationDateLink')
+ ->with($share)
+ ->willReturn($share);
+ $manager->expects($this->once())
+ ->method('verifyPassword')
+ ->with('password');
+ $manager->expects($this->once())
+ ->method('setLinkParent')
+ ->with($share);
+
+ $this->hasher->expects($this->once())
+ ->method('hash')
+ ->with('password')
+ ->willReturn('hashed');
+
+ $this->secureRandom->method('generate')
+ ->willReturn('token');
+
+ $this->defaultProvider
+ ->expects($this->once())
+ ->method('create')
+ ->with($share)
+ ->willReturnCallback(function (Share $share) {
+ return $share->setId(42);
+ });
+
+ $this->dispatcher->expects($this->exactly(2))
+ ->method('dispatchTyped')
+ ->withConsecutive(
+ // Pre share
+ [
+ $this->callback(function (BeforeShareCreatedEvent $e) use ($path, $date) {
+ $share = $e->getShare();
+
+ return $share->getShareType() === IShare::TYPE_LINK &&
+ $share->getNode() === $path &&
+ $share->getSharedBy() === 'sharedBy' &&
+ $share->getPermissions() === \OCP\Constants::PERMISSION_ALL &&
+ $share->getExpirationDate() === $date &&
+ $share->getPassword() === 'hashed' &&
+ $share->getToken() === 'token';
+ })
+ ],
+ // Post share
+ [
+ $this->callback(function (ShareCreatedEvent $e) use ($path, $date) {
+ $share = $e->getShare();
+
+ return $share->getShareType() === IShare::TYPE_LINK &&
+ $share->getNode() === $path &&
+ $share->getSharedBy() === 'sharedBy' &&
+ $share->getPermissions() === \OCP\Constants::PERMISSION_ALL &&
+ $share->getExpirationDate() === $date &&
+ $share->getPassword() === 'hashed' &&
+ $share->getToken() === 'token' &&
+ $share->getId() === '42' &&
+ $share->getTarget() === '/target';
+ })
+ ]
+ );
+
+ /** @var IShare $share */
+ $share = $manager->createShare($share);
+
+ $this->assertSame('shareOwner', $share->getShareOwner());
+ $this->assertEquals('/target', $share->getTarget());
+ $this->assertSame($date, $share->getExpirationDate());
+ $this->assertEquals('token', $share->getToken());
+ $this->assertEquals('hashed', $share->getPassword());
+ }
+
+ public function testCreateShareMail(): void {
+ $manager = $this->createManagerMock()
+ ->setMethods([
+ 'canShare',
+ 'generalCreateChecks',
+ 'linkCreateChecks',
+ 'pathCreateChecks',
+ 'validateExpirationDateLink',
+ 'verifyPassword',
+ 'setLinkParent',
+ ])
+ ->getMock();
+
+ $shareOwner = $this->createMock(IUser::class);
+ $shareOwner->method('getUID')->willReturn('shareOwner');
+
+ $storage = $this->createMock(Storage::class);
+ $path = $this->createMock(File::class);
+ $path->method('getOwner')->willReturn($shareOwner);
+ $path->method('getName')->willReturn('target');
+ $path->method('getId')->willReturn(1);
+ $path->method('getStorage')->willReturn($storage);
+
+ $share = $this->manager->newShare();
+ $share->setShareType(IShare::TYPE_EMAIL)
+ ->setNode($path)
+ ->setSharedBy('sharedBy')
+ ->setPermissions(\OCP\Constants::PERMISSION_ALL);
+
+ $manager->expects($this->once())
+ ->method('canShare')
+ ->with($share)
+ ->willReturn(true);
+ $manager->expects($this->once())
+ ->method('generalCreateChecks')
+ ->with($share);
+
+ $manager->expects($this->once())
+ ->method('linkCreateChecks');
+ $manager->expects($this->once())
+ ->method('pathCreateChecks')
+ ->with($path);
+ $manager->expects($this->once())
+ ->method('validateExpirationDateLink')
+ ->with($share)
+ ->willReturn($share);
+ $manager->expects($this->once())
+ ->method('verifyPassword');
+ $manager->expects($this->once())
+ ->method('setLinkParent');
+
+ $this->secureRandom->method('generate')
+ ->willReturn('token');
+
+ $this->defaultProvider
+ ->expects($this->once())
+ ->method('create')
+ ->with($share)
+ ->willReturnCallback(function (Share $share) {
+ return $share->setId(42);
+ });
+
+ $this->dispatcher->expects($this->exactly(2))
+ ->method('dispatchTyped')
+ ->withConsecutive(
+ [
+ $this->callback(function (BeforeShareCreatedEvent $e) use ($path) {
+ $share = $e->getShare();
+
+ return $share->getShareType() === IShare::TYPE_EMAIL &&
+ $share->getNode() === $path &&
+ $share->getSharedBy() === 'sharedBy' &&
+ $share->getPermissions() === \OCP\Constants::PERMISSION_ALL &&
+ $share->getExpirationDate() === null &&
+ $share->getPassword() === null &&
+ $share->getToken() === 'token';
+ })
+ ],
+ [
+ $this->callback(function (ShareCreatedEvent $e) use ($path) {
+ $share = $e->getShare();
+
+ return $share->getShareType() === IShare::TYPE_EMAIL &&
+ $share->getNode() === $path &&
+ $share->getSharedBy() === 'sharedBy' &&
+ $share->getPermissions() === \OCP\Constants::PERMISSION_ALL &&
+ $share->getExpirationDate() === null &&
+ $share->getPassword() === null &&
+ $share->getToken() === 'token' &&
+ $share->getId() === '42' &&
+ $share->getTarget() === '/target';
+ })
+ ],
+ );
+
+ /** @var IShare $share */
+ $share = $manager->createShare($share);
+
+ $this->assertSame('shareOwner', $share->getShareOwner());
+ $this->assertEquals('/target', $share->getTarget());
+ $this->assertEquals('token', $share->getToken());
+ }
+
+
+ public function testCreateShareHookError(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('I won\'t let you share');
+
+ $manager = $this->createManagerMock()
+ ->setMethods([
+ 'canShare',
+ 'generalCreateChecks',
+ 'userCreateChecks',
+ 'pathCreateChecks',
+ ])
+ ->getMock();
+
+ $shareOwner = $this->createMock(IUser::class);
+ $shareOwner->method('getUID')->willReturn('shareOwner');
+
+ $storage = $this->createMock(Storage::class);
+ $path = $this->createMock(File::class);
+ $path->method('getOwner')->willReturn($shareOwner);
+ $path->method('getName')->willReturn('target');
+ $path->method('getStorage')->willReturn($storage);
+
+ $share = $this->createShare(
+ null,
+ IShare::TYPE_USER,
+ $path,
+ 'sharedWith',
+ 'sharedBy',
+ null,
+ \OCP\Constants::PERMISSION_ALL);
+
+ $manager->expects($this->once())
+ ->method('canShare')
+ ->with($share)
+ ->willReturn(true);
+ $manager->expects($this->once())
+ ->method('generalCreateChecks')
+ ->with($share);
+ ;
+ $manager->expects($this->once())
+ ->method('userCreateChecks')
+ ->with($share);
+ ;
+ $manager->expects($this->once())
+ ->method('pathCreateChecks')
+ ->with($path);
+
+ $share->expects($this->once())
+ ->method('setShareOwner')
+ ->with('shareOwner');
+ $share->expects($this->once())
+ ->method('setTarget')
+ ->with('/target');
+
+ // Pre share
+ $this->dispatcher->expects($this->once())
+ ->method('dispatchTyped')
+ ->with(
+ $this->isInstanceOf(BeforeShareCreatedEvent::class)
+ )->willReturnCallback(function (BeforeShareCreatedEvent $e) {
+ $e->setError('I won\'t let you share!');
+ $e->stopPropagation();
+ }
+ );
+
+ $manager->createShare($share);
+ }
+
+ public function testCreateShareOfIncomingFederatedShare(): void {
+ $manager = $this->createManagerMock()
+ ->setMethods(['canShare', 'generalCreateChecks', 'userCreateChecks', 'pathCreateChecks'])
+ ->getMock();
+
+ $shareOwner = $this->createMock(IUser::class);
+ $shareOwner->method('getUID')->willReturn('shareOwner');
+
+ $storage = $this->createMock(Storage::class);
+ $storage->method('instanceOfStorage')
+ ->with(\OCA\Files_Sharing\External\Storage::class)
+ ->willReturn(true);
+
+ $storage2 = $this->createMock(Storage::class);
+ $storage2->method('instanceOfStorage')
+ ->with(\OCA\Files_Sharing\External\Storage::class)
+ ->willReturn(false);
+
+ $path = $this->createMock(File::class);
+ $path->expects($this->never())->method('getOwner');
+ $path->method('getName')->willReturn('target');
+ $path->method('getStorage')->willReturn($storage);
+
+ $parent = $this->createMock(Folder::class);
+ $parent->method('getStorage')->willReturn($storage);
+
+ $parentParent = $this->createMock(Folder::class);
+ $parentParent->method('getStorage')->willReturn($storage2);
+ $parentParent->method('getOwner')->willReturn($shareOwner);
+
+ $path->method('getParent')->willReturn($parent);
+ $parent->method('getParent')->willReturn($parentParent);
+
+ $share = $this->createShare(
+ null,
+ IShare::TYPE_USER,
+ $path,
+ 'sharedWith',
+ 'sharedBy',
+ null,
+ \OCP\Constants::PERMISSION_ALL);
+
+ $manager->expects($this->once())
+ ->method('canShare')
+ ->with($share)
+ ->willReturn(true);
+ $manager->expects($this->once())
+ ->method('generalCreateChecks')
+ ->with($share);
+ ;
+ $manager->expects($this->once())
+ ->method('userCreateChecks')
+ ->with($share);
+ ;
+ $manager->expects($this->once())
+ ->method('pathCreateChecks')
+ ->with($path);
+
+ $this->defaultProvider
+ ->expects($this->once())
+ ->method('create')
+ ->with($share)
+ ->willReturnArgument(0);
+
+ $share->expects($this->once())
+ ->method('setShareOwner')
+ ->with('shareOwner');
+ $share->expects($this->once())
+ ->method('setTarget')
+ ->with('/target');
+
+ $manager->createShare($share);
+ }
+
+ public function testGetSharesBy(): void {
+ $share = $this->manager->newShare();
+
+ $node = $this->createMock(Folder::class);
+
+ $this->defaultProvider->expects($this->once())
+ ->method('getSharesBy')
+ ->with(
+ $this->equalTo('user'),
+ $this->equalTo(IShare::TYPE_USER),
+ $this->equalTo($node),
+ $this->equalTo(true),
+ $this->equalTo(1),
+ $this->equalTo(1)
+ )->willReturn([$share]);
+
+ $shares = $this->manager->getSharesBy('user', IShare::TYPE_USER, $node, true, 1, 1);
+
+ $this->assertCount(1, $shares);
+ $this->assertSame($share, $shares[0]);
+ }
+
+ /**
+ * Test to ensure we correctly remove expired link shares
+ *
+ * We have 8 Shares and we want the 3 first valid shares.
+ * share 3-6 and 8 are expired. Thus at the end of this test we should
+ * have received share 1,2 and 7. And from the manager. Share 3-6 should be
+ * deleted (as they are evaluated). but share 8 should still be there.
+ */
+ public function testGetSharesByExpiredLinkShares(): void {
+ $manager = $this->createManagerMock()
+ ->setMethods(['deleteShare'])
+ ->getMock();
+
+ /** @var \OCP\Share\IShare[] $shares */
+ $shares = [];
+
+ /*
+ * This results in an array of 8 IShare elements
+ */
+ for ($i = 0; $i < 8; $i++) {
+ $share = $this->manager->newShare();
+ $share->setId($i);
+ $shares[] = $share;
+ }
+
+ $today = new \DateTime();
+ $today->setTime(0, 0, 0);
+
+ /*
+ * Set the expiration date to today for some shares
+ */
+ $shares[2]->setExpirationDate($today);
+ $shares[3]->setExpirationDate($today);
+ $shares[4]->setExpirationDate($today);
+ $shares[5]->setExpirationDate($today);
+
+ /** @var \OCP\Share\IShare[] $i */
+ $shares2 = [];
+ for ($i = 0; $i < 8; $i++) {
+ $shares2[] = clone $shares[$i];
+ }
+
+ $node = $this->createMock(File::class);
+
+ /*
+ * Simulate the getSharesBy call.
+ */
+ $this->defaultProvider
+ ->method('getSharesBy')
+ ->willReturnCallback(function ($uid, $type, $node, $reshares, $limit, $offset) use (&$shares2) {
+ return array_slice($shares2, $offset, $limit);
+ });
+
+ /*
+ * Simulate the deleteShare call.
+ */
+ $manager->method('deleteShare')
+ ->willReturnCallback(function ($share) use (&$shares2) {
+ for ($i = 0; $i < count($shares2); $i++) {
+ if ($shares2[$i]->getId() === $share->getId()) {
+ array_splice($shares2, $i, 1);
+ break;
+ }
+ }
+ });
+
+ $res = $manager->getSharesBy('user', IShare::TYPE_LINK, $node, true, 3, 0);
+
+ $this->assertCount(3, $res);
+ $this->assertEquals($shares[0]->getId(), $res[0]->getId());
+ $this->assertEquals($shares[1]->getId(), $res[1]->getId());
+ $this->assertEquals($shares[6]->getId(), $res[2]->getId());
+
+ $this->assertCount(4, $shares2);
+ $this->assertEquals(0, $shares2[0]->getId());
+ $this->assertEquals(1, $shares2[1]->getId());
+ $this->assertEquals(6, $shares2[2]->getId());
+ $this->assertEquals(7, $shares2[3]->getId());
+ $this->assertSame($today, $shares[3]->getExpirationDate());
+ }
+
+ public function testGetShareByToken(): void {
+ $this->config
+ ->expects($this->exactly(2))
+ ->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_allow_links', 'yes', 'yes'],
+ ['files_sharing', 'hide_disabled_user_shares', 'no', 'no'],
+ ]);
+
+ $factory = $this->createMock(IProviderFactory::class);
+
+ $manager = $this->createManager($factory);
+
+ $share = $this->createMock(IShare::class);
+
+ $factory->expects($this->once())
+ ->method('getProviderForType')
+ ->with(IShare::TYPE_LINK)
+ ->willReturn($this->defaultProvider);
+
+ $this->defaultProvider->expects($this->once())
+ ->method('getShareByToken')
+ ->with('token')
+ ->willReturn($share);
+
+ $ret = $manager->getShareByToken('token');
+ $this->assertSame($share, $ret);
+ }
+
+ public function testGetShareByTokenRoom(): void {
+ $this->config
+ ->expects($this->exactly(2))
+ ->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_allow_links', 'yes', 'no'],
+ ['files_sharing', 'hide_disabled_user_shares', 'no', 'no'],
+ ]);
+
+ $factory = $this->createMock(IProviderFactory::class);
+
+ $manager = $this->createManager($factory);
+
+ $share = $this->createMock(IShare::class);
+
+ $roomShareProvider = $this->createMock(IShareProvider::class);
+
+ $factory->expects($this->any())
+ ->method('getProviderForType')
+ ->willReturnCallback(function ($shareType) use ($roomShareProvider) {
+ if ($shareType !== IShare::TYPE_ROOM) {
+ throw new Exception\ProviderException();
+ }
+
+ return $roomShareProvider;
+ });
+
+ $roomShareProvider->expects($this->once())
+ ->method('getShareByToken')
+ ->with('token')
+ ->willReturn($share);
+
+ $ret = $manager->getShareByToken('token');
+ $this->assertSame($share, $ret);
+ }
+
+ public function testGetShareByTokenWithException(): void {
+ $this->config
+ ->expects($this->exactly(2))
+ ->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_allow_links', 'yes', 'yes'],
+ ['files_sharing', 'hide_disabled_user_shares', 'no', 'no'],
+ ]);
+
+ $factory = $this->createMock(IProviderFactory::class);
+
+ $manager = $this->createManager($factory);
+
+ $share = $this->createMock(IShare::class);
+
+ $factory->expects($this->exactly(2))
+ ->method('getProviderForType')
+ ->withConsecutive(
+ [IShare::TYPE_LINK],
+ [IShare::TYPE_REMOTE]
+ )
+ ->willReturn($this->defaultProvider);
+
+ $this->defaultProvider->expects($this->exactly(2))
+ ->method('getShareByToken')
+ ->with('token')
+ ->willReturnOnConsecutiveCalls(
+ $this->throwException(new ShareNotFound()),
+ $share
+ );
+
+ $ret = $manager->getShareByToken('token');
+ $this->assertSame($share, $ret);
+ }
+
+
+ public function testGetShareByTokenHideDisabledUser(): void {
+ $this->expectException(\OCP\Share\Exceptions\ShareNotFound::class);
+ $this->expectExceptionMessage('The requested share comes from a disabled user');
+
+ $this->config
+ ->expects($this->exactly(2))
+ ->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_allow_links', 'yes', 'yes'],
+ ['files_sharing', 'hide_disabled_user_shares', 'no', 'yes'],
+ ]);
+
+ $this->l->expects($this->once())
+ ->method('t')
+ ->willReturnArgument(0);
+
+ $manager = $this->createManagerMock()
+ ->setMethods(['deleteShare'])
+ ->getMock();
+
+ $date = new \DateTime();
+ $date->setTime(0, 0, 0);
+ $date->add(new \DateInterval('P2D'));
+ $share = $this->manager->newShare();
+ $share->setExpirationDate($date);
+ $share->setShareOwner('owner');
+ $share->setSharedBy('sharedBy');
+
+ $sharedBy = $this->createMock(IUser::class);
+ $owner = $this->createMock(IUser::class);
+
+ $this->userManager->method('get')->willReturnMap([
+ ['sharedBy', $sharedBy],
+ ['owner', $owner],
+ ]);
+
+ $owner->expects($this->once())
+ ->method('isEnabled')
+ ->willReturn(true);
+ $sharedBy->expects($this->once())
+ ->method('isEnabled')
+ ->willReturn(false);
+
+ $this->defaultProvider->expects($this->once())
+ ->method('getShareByToken')
+ ->with('expiredToken')
+ ->willReturn($share);
+
+ $manager->expects($this->never())
+ ->method('deleteShare');
+
+ $manager->getShareByToken('expiredToken');
+ }
+
+
+ public function testGetShareByTokenExpired(): void {
+ $this->expectException(\OCP\Share\Exceptions\ShareNotFound::class);
+ $this->expectExceptionMessage('The requested share does not exist anymore');
+
+ $this->config
+ ->expects($this->once())
+ ->method('getAppValue')
+ ->with('core', 'shareapi_allow_links', 'yes')
+ ->willReturn('yes');
+
+ $this->l->expects($this->once())
+ ->method('t')
+ ->willReturnArgument(0);
+
+ $manager = $this->createManagerMock()
+ ->setMethods(['deleteShare'])
+ ->getMock();
+
+ $date = new \DateTime();
+ $date->setTime(0, 0, 0);
+ $share = $this->manager->newShare();
+ $share->setExpirationDate($date);
+
+ $this->defaultProvider->expects($this->once())
+ ->method('getShareByToken')
+ ->with('expiredToken')
+ ->willReturn($share);
+
+ $manager->expects($this->once())
+ ->method('deleteShare')
+ ->with($this->equalTo($share));
+
+ $manager->getShareByToken('expiredToken');
+ }
+
+ public function testGetShareByTokenNotExpired(): void {
+ $this->config
+ ->expects($this->exactly(2))
+ ->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_allow_links', 'yes', 'yes'],
+ ['files_sharing', 'hide_disabled_user_shares', 'no', 'no'],
+ ]);
+
+ $date = new \DateTime();
+ $date->setTime(0, 0, 0);
+ $date->add(new \DateInterval('P2D'));
+ $share = $this->manager->newShare();
+ $share->setExpirationDate($date);
+
+ $this->defaultProvider->expects($this->once())
+ ->method('getShareByToken')
+ ->with('expiredToken')
+ ->willReturn($share);
+
+ $res = $this->manager->getShareByToken('expiredToken');
+
+ $this->assertSame($share, $res);
+ }
+
+
+ public function testGetShareByTokenWithPublicLinksDisabled(): void {
+ $this->expectException(\OCP\Share\Exceptions\ShareNotFound::class);
+
+ $this->config
+ ->expects($this->once())
+ ->method('getAppValue')
+ ->with('core', 'shareapi_allow_links', 'yes')
+ ->willReturn('no');
+ $this->manager->getShareByToken('validToken');
+ }
+
+ public function testGetShareByTokenPublicUploadDisabled(): void {
+ $this->config
+ ->expects($this->exactly(3))
+ ->method('getAppValue')
+ ->willReturnMap([
+ ['core', 'shareapi_allow_links', 'yes', 'yes'],
+ ['core', 'shareapi_allow_public_upload', 'yes', 'no'],
+ ['files_sharing', 'hide_disabled_user_shares', 'no', 'no'],
+ ]);
+
+ $share = $this->manager->newShare();
+ $share->setShareType(IShare::TYPE_LINK)
+ ->setPermissions(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE);
+ $share->setSharedWith('sharedWith');
+ $folder = $this->createMock(\OC\Files\Node\Folder::class);
+ $share->setNode($folder);
+
+ $this->defaultProvider->expects($this->once())
+ ->method('getShareByToken')
+ ->willReturn('validToken')
+ ->willReturn($share);
+
+ $res = $this->manager->getShareByToken('validToken');
+
+ $this->assertSame(\OCP\Constants::PERMISSION_READ, $res->getPermissions());
+ }
+
+ public function testCheckPasswordNoLinkShare(): void {
+ $share = $this->createMock(IShare::class);
+ $share->method('getShareType')->willReturn(IShare::TYPE_USER);
+ $this->assertFalse($this->manager->checkPassword($share, 'password'));
+ }
+
+ public function testCheckPasswordNoPassword(): void {
+ $share = $this->createMock(IShare::class);
+ $share->method('getShareType')->willReturn(IShare::TYPE_LINK);
+ $this->assertFalse($this->manager->checkPassword($share, 'password'));
+
+ $share->method('getPassword')->willReturn('password');
+ $this->assertFalse($this->manager->checkPassword($share, null));
+ }
+
+ public function testCheckPasswordInvalidPassword(): void {
+ $share = $this->createMock(IShare::class);
+ $share->method('getShareType')->willReturn(IShare::TYPE_LINK);
+ $share->method('getPassword')->willReturn('password');
+
+ $this->hasher->method('verify')->with('invalidpassword', 'password', '')->willReturn(false);
+
+ $this->assertFalse($this->manager->checkPassword($share, 'invalidpassword'));
+ }
+
+ public function testCheckPasswordValidPassword(): void {
+ $share = $this->createMock(IShare::class);
+ $share->method('getShareType')->willReturn(IShare::TYPE_LINK);
+ $share->method('getPassword')->willReturn('passwordHash');
+
+ $this->hasher->method('verify')->with('password', 'passwordHash', '')->willReturn(true);
+
+ $this->assertTrue($this->manager->checkPassword($share, 'password'));
+ }
+
+ public function testCheckPasswordUpdateShare(): void {
+ $share = $this->manager->newShare();
+ $share->setShareType(IShare::TYPE_LINK)
+ ->setPassword('passwordHash');
+
+ $this->hasher->method('verify')->with('password', 'passwordHash', '')
+ ->willReturnCallback(function ($pass, $hash, &$newHash) {
+ $newHash = 'newHash';
+
+ return true;
+ });
+
+ $this->defaultProvider->expects($this->once())
+ ->method('update')
+ ->with($this->callback(function (\OCP\Share\IShare $share) {
+ return $share->getPassword() === 'newHash';
+ }));
+
+ $this->assertTrue($this->manager->checkPassword($share, 'password'));
+ }
+
+
+ public function testUpdateShareCantChangeShareType(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('Cannot change share type');
+
+ $manager = $this->createManagerMock()
+ ->setMethods([
+ 'canShare',
+ 'getShareById'
+ ])
+ ->getMock();
+
+ $originalShare = $this->manager->newShare();
+ $originalShare->setShareType(IShare::TYPE_GROUP);
+
+ $manager->expects($this->once())->method('canShare')->willReturn(true);
+ $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
+
+ $share = $this->manager->newShare();
+ $attrs = $this->manager->newShare()->newAttributes();
+ $attrs->setAttribute('app1', 'perm1', true);
+ $share->setProviderId('foo')
+ ->setId('42')
+ ->setShareType(IShare::TYPE_USER);
+
+ $manager->updateShare($share);
+ }
+
+
+ public function testUpdateShareCantChangeRecipientForGroupShare(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('Can only update recipient on user shares');
+
+ $manager = $this->createManagerMock()
+ ->setMethods([
+ 'canShare',
+ 'getShareById'
+ ])
+ ->getMock();
+
+ $originalShare = $this->manager->newShare();
+ $originalShare->setShareType(IShare::TYPE_GROUP)
+ ->setSharedWith('origGroup');
+
+ $manager->expects($this->once())->method('canShare')->willReturn(true);
+ $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
+
+ $share = $this->manager->newShare();
+ $share->setProviderId('foo')
+ ->setId('42')
+ ->setShareType(IShare::TYPE_GROUP)
+ ->setSharedWith('newGroup');
+
+ $manager->updateShare($share);
+ }
+
+
+ public function testUpdateShareCantShareWithOwner(): void {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('Cannot share with the share owner');
+
+ $manager = $this->createManagerMock()
+ ->setMethods([
+ 'canShare',
+ 'getShareById'
+ ])
+ ->getMock();
+
+ $originalShare = $this->manager->newShare();
+ $originalShare->setShareType(IShare::TYPE_USER)
+ ->setSharedWith('sharedWith');
+
+ $manager->expects($this->once())->method('canShare')->willReturn(true);
+ $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
+
+ $share = $this->manager->newShare();
+ $share->setProviderId('foo')
+ ->setId('42')
+ ->setShareType(IShare::TYPE_USER)
+ ->setSharedWith('newUser')
+ ->setShareOwner('newUser');
+
+ $manager->updateShare($share);
+ }
+
+ public function testUpdateShareUser(): void {
+ $this->userManager->expects($this->any())->method('userExists')->willReturn(true);
+
+ $manager = $this->createManagerMock()
+ ->setMethods([
+ 'canShare',
+ 'getShareById',
+ 'generalCreateChecks',
+ 'userCreateChecks',
+ 'pathCreateChecks',
+ ])
+ ->getMock();
+
+ $originalShare = $this->manager->newShare();
+ $originalShare->setShareType(IShare::TYPE_USER)
+ ->setSharedWith('origUser')
+ ->setPermissions(1);
+
+ $node = $this->createMock(File::class);
+ $node->method('getId')->willReturn(100);
+ $node->method('getPath')->willReturn('/newUser/files/myPath');
+
+ $manager->expects($this->once())->method('canShare')->willReturn(true);
+ $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
+
+ $share = $this->manager->newShare();
+ $attrs = $this->manager->newShare()->newAttributes();
+ $attrs->setAttribute('app1', 'perm1', true);
+ $share->setProviderId('foo')
+ ->setId('42')
+ ->setShareType(IShare::TYPE_USER)
+ ->setSharedWith('origUser')
+ ->setShareOwner('newUser')
+ ->setSharedBy('sharer')
+ ->setPermissions(31)
+ ->setAttributes($attrs)
+ ->setNode($node);
+
+ $this->defaultProvider->expects($this->once())
+ ->method('update')
+ ->with($share)
+ ->willReturn($share);
+
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, '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->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListener2, 'post');
+ $hookListener2->expects($this->once())->method('post')->with([
+ 'itemType' => 'file',
+ 'itemSource' => 100,
+ 'shareType' => IShare::TYPE_USER,
+ 'shareWith' => 'origUser',
+ 'uidOwner' => 'sharer',
+ 'permissions' => 31,
+ 'path' => '/myPath',
+ 'attributes' => $attrs->toArray(),
+ ]);
+
+ $manager->updateShare($share);
+ }
+
+ public function testUpdateShareGroup(): void {
+ $manager = $this->createManagerMock()
+ ->setMethods([
+ 'canShare',
+ 'getShareById',
+ 'generalCreateChecks',
+ 'groupCreateChecks',
+ 'pathCreateChecks',
+ ])
+ ->getMock();
+
+ $originalShare = $this->manager->newShare();
+ $originalShare->setShareType(IShare::TYPE_GROUP)
+ ->setSharedWith('origUser')
+ ->setPermissions(31);
+
+ $manager->expects($this->once())->method('canShare')->willReturn(true);
+ $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
+
+ $node = $this->createMock(File::class);
+
+ $share = $this->manager->newShare();
+ $share->setProviderId('foo')
+ ->setId('42')
+ ->setShareType(IShare::TYPE_GROUP)
+ ->setSharedWith('origUser')
+ ->setShareOwner('owner')
+ ->setNode($node)
+ ->setPermissions(31);
+
+ $this->defaultProvider->expects($this->once())
+ ->method('update')
+ ->with($share)
+ ->willReturn($share);
+
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListener, 'post');
+ $hookListener->expects($this->never())->method('post');
+
+ $hookListener2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListener2, 'post');
+ $hookListener2->expects($this->never())->method('post');
+
+ $manager->updateShare($share);
+ }
+
+ public function testUpdateShareLink(): void {
+ $manager = $this->createManagerMock()
+ ->setMethods([
+ 'canShare',
+ 'getShareById',
+ 'generalCreateChecks',
+ 'linkCreateChecks',
+ 'pathCreateChecks',
+ 'verifyPassword',
+ 'validateExpirationDateLink',
+ ])
+ ->getMock();
+
+ $originalShare = $this->manager->newShare();
+ $originalShare->setShareType(IShare::TYPE_LINK)
+ ->setPermissions(15);
+
+ $tomorrow = new \DateTime();
+ $tomorrow->setTime(0, 0, 0);
+ $tomorrow->add(new \DateInterval('P1D'));
+
+ $file = $this->createMock(File::class);
+ $file->method('getId')->willReturn(100);
+
+ $share = $this->manager->newShare();
+ $share->setProviderId('foo')
+ ->setId('42')
+ ->setShareType(IShare::TYPE_LINK)
+ ->setToken('token')
+ ->setSharedBy('owner')
+ ->setShareOwner('owner')
+ ->setPassword('password')
+ ->setExpirationDate($tomorrow)
+ ->setNode($file)
+ ->setPermissions(15);
+
+ $manager->expects($this->once())->method('canShare')->willReturn(true);
+ $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
+ $manager->expects($this->once())->method('validateExpirationDateLink')->with($share);
+ $manager->expects($this->once())->method('verifyPassword')->with('password');
+
+ $this->hasher->expects($this->once())
+ ->method('hash')
+ ->with('password')
+ ->willReturn('hashed');
+
+ $this->defaultProvider->expects($this->once())
+ ->method('update')
+ ->with($share)
+ ->willReturn($share);
+
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListener, 'post');
+ $hookListener->expects($this->once())->method('post')->with([
+ 'itemType' => 'file',
+ 'itemSource' => 100,
+ 'date' => $tomorrow,
+ 'uidOwner' => 'owner',
+ ]);
+
+ $hookListener2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_update_password', $hookListener2, 'post');
+ $hookListener2->expects($this->once())->method('post')->with([
+ 'itemType' => 'file',
+ 'itemSource' => 100,
+ 'uidOwner' => 'owner',
+ 'token' => 'token',
+ 'disabled' => false,
+ ]);
+
+ $hookListener3 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListener3, 'post');
+ $hookListener3->expects($this->never())->method('post');
+
+
+ $manager->updateShare($share);
+ }
+
+ public function testUpdateShareLinkEnableSendPasswordByTalkWithNoPassword(): void {
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('Cannot enable sending the password by Talk with an empty password');
+
+ $manager = $this->createManagerMock()
+ ->setMethods([
+ 'canShare',
+ 'getShareById',
+ 'generalCreateChecks',
+ 'linkCreateChecks',
+ 'pathCreateChecks',
+ 'verifyPassword',
+ 'validateExpirationDateLink',
+ ])
+ ->getMock();
+
+ $originalShare = $this->manager->newShare();
+ $originalShare->setShareType(IShare::TYPE_LINK)
+ ->setPermissions(15);
+
+ $tomorrow = new \DateTime();
+ $tomorrow->setTime(0, 0, 0);
+ $tomorrow->add(new \DateInterval('P1D'));
+
+ $file = $this->createMock(File::class);
+ $file->method('getId')->willReturn(100);
+
+ $share = $this->manager->newShare();
+ $share->setProviderId('foo')
+ ->setId('42')
+ ->setShareType(IShare::TYPE_LINK)
+ ->setToken('token')
+ ->setSharedBy('owner')
+ ->setShareOwner('owner')
+ ->setPassword(null)
+ ->setSendPasswordByTalk(true)
+ ->setExpirationDate($tomorrow)
+ ->setNode($file)
+ ->setPermissions(15);
+
+ $manager->expects($this->once())->method('canShare')->willReturn(true);
+ $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
+ $manager->expects($this->once())->method('generalCreateChecks')->with($share);
+ $manager->expects($this->once())->method('linkCreateChecks')->with($share);
+ $manager->expects($this->never())->method('verifyPassword');
+ $manager->expects($this->never())->method('pathCreateChecks');
+ $manager->expects($this->never())->method('validateExpirationDateLink');
+
+ $this->hasher->expects($this->never())
+ ->method('hash');
+
+ $this->defaultProvider->expects($this->never())
+ ->method('update');
+
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListener, 'post');
+ $hookListener->expects($this->never())->method('post');
+
+ $hookListener2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_update_password', $hookListener2, 'post');
+ $hookListener2->expects($this->never())->method('post');
+
+ $hookListener3 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListener3, 'post');
+ $hookListener3->expects($this->never())->method('post');
+
+ $manager->updateShare($share);
+ }
+
+ public function testUpdateShareMail(): void {
+ $manager = $this->createManagerMock()
+ ->setMethods([
+ 'canShare',
+ 'getShareById',
+ 'generalCreateChecks',
+ 'verifyPassword',
+ 'pathCreateChecks',
+ 'linkCreateChecks',
+ 'validateExpirationDateLink',
+ ])
+ ->getMock();
+
+ $originalShare = $this->manager->newShare();
+ $originalShare->setShareType(IShare::TYPE_EMAIL)
+ ->setPermissions(\OCP\Constants::PERMISSION_ALL);
+
+ $tomorrow = new \DateTime();
+ $tomorrow->setTime(0, 0, 0);
+ $tomorrow->add(new \DateInterval('P1D'));
+
+ $file = $this->createMock(File::class);
+ $file->method('getId')->willReturn(100);
+
+ $share = $this->manager->newShare();
+ $share->setProviderId('foo')
+ ->setId('42')
+ ->setShareType(IShare::TYPE_EMAIL)
+ ->setToken('token')
+ ->setSharedBy('owner')
+ ->setShareOwner('owner')
+ ->setPassword('password')
+ ->setExpirationDate($tomorrow)
+ ->setNode($file)
+ ->setPermissions(\OCP\Constants::PERMISSION_ALL);
+
+ $manager->expects($this->once())->method('canShare')->willReturn(true);
+ $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
+ $manager->expects($this->once())->method('generalCreateChecks')->with($share);
+ $manager->expects($this->once())->method('verifyPassword')->with('password');
+ $manager->expects($this->once())->method('pathCreateChecks')->with($file);
+ $manager->expects($this->once())->method('linkCreateChecks');
+ $manager->expects($this->once())->method('validateExpirationDateLink');
+
+ $this->hasher->expects($this->once())
+ ->method('hash')
+ ->with('password')
+ ->willReturn('hashed');
+
+ $this->defaultProvider->expects($this->once())
+ ->method('update')
+ ->with($share, 'password')
+ ->willReturn($share);
+
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListener, 'post');
+ $hookListener->expects($this->once())->method('post')->with([
+ 'itemType' => 'file',
+ 'itemSource' => 100,
+ 'date' => $tomorrow,
+ 'uidOwner' => 'owner',
+ ]);
+
+ $hookListener2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_update_password', $hookListener2, 'post');
+ $hookListener2->expects($this->once())->method('post')->with([
+ 'itemType' => 'file',
+ 'itemSource' => 100,
+ 'uidOwner' => 'owner',
+ 'token' => 'token',
+ 'disabled' => false,
+ ]);
+
+ $hookListener3 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListener3, 'post');
+ $hookListener3->expects($this->never())->method('post');
+
+ $manager->updateShare($share);
+ }
+
+ public function testUpdateShareMailEnableSendPasswordByTalk(): void {
+ $manager = $this->createManagerMock()
+ ->setMethods([
+ 'canShare',
+ 'getShareById',
+ 'generalCreateChecks',
+ 'verifyPassword',
+ 'pathCreateChecks',
+ 'linkCreateChecks',
+ 'validateExpirationDateLink',
+ ])
+ ->getMock();
+
+ $originalShare = $this->manager->newShare();
+ $originalShare->setShareType(IShare::TYPE_EMAIL)
+ ->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ ->setPassword(null)
+ ->setSendPasswordByTalk(false);
+
+ $tomorrow = new \DateTime();
+ $tomorrow->setTime(0, 0, 0);
+ $tomorrow->add(new \DateInterval('P1D'));
+
+ $file = $this->createMock(File::class);
+ $file->method('getId')->willReturn(100);
+
+ $share = $this->manager->newShare();
+ $share->setProviderId('foo')
+ ->setId('42')
+ ->setShareType(IShare::TYPE_EMAIL)
+ ->setToken('token')
+ ->setSharedBy('owner')
+ ->setShareOwner('owner')
+ ->setPassword('password')
+ ->setSendPasswordByTalk(true)
+ ->setExpirationDate($tomorrow)
+ ->setNode($file)
+ ->setPermissions(\OCP\Constants::PERMISSION_ALL);
+
+ $manager->expects($this->once())->method('canShare')->willReturn(true);
+ $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
+ $manager->expects($this->once())->method('generalCreateChecks')->with($share);
+ $manager->expects($this->once())->method('verifyPassword')->with('password');
+ $manager->expects($this->once())->method('pathCreateChecks')->with($file);
+ $manager->expects($this->once())->method('linkCreateChecks');
+ $manager->expects($this->once())->method('validateExpirationDateLink');
+
+ $this->hasher->expects($this->once())
+ ->method('hash')
+ ->with('password')
+ ->willReturn('hashed');
+
+ $this->defaultProvider->expects($this->once())
+ ->method('update')
+ ->with($share, 'password')
+ ->willReturn($share);
+
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListener, 'post');
+ $hookListener->expects($this->once())->method('post')->with([
+ 'itemType' => 'file',
+ 'itemSource' => 100,
+ 'date' => $tomorrow,
+ 'uidOwner' => 'owner',
+ ]);
+
+ $hookListener2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_update_password', $hookListener2, 'post');
+ $hookListener2->expects($this->once())->method('post')->with([
+ 'itemType' => 'file',
+ 'itemSource' => 100,
+ 'uidOwner' => 'owner',
+ 'token' => 'token',
+ 'disabled' => false,
+ ]);
+
+ $hookListener3 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListener3, 'post');
+ $hookListener3->expects($this->never())->method('post');
+
+ $manager->updateShare($share);
+ }
+
+ public function testUpdateShareMailEnableSendPasswordByTalkWithDifferentPassword(): void {
+ $manager = $this->createManagerMock()
+ ->setMethods([
+ 'canShare',
+ 'getShareById',
+ 'generalCreateChecks',
+ 'verifyPassword',
+ 'pathCreateChecks',
+ 'linkCreateChecks',
+ 'validateExpirationDateLink',
+ ])
+ ->getMock();
+
+ $originalShare = $this->manager->newShare();
+ $originalShare->setShareType(IShare::TYPE_EMAIL)
+ ->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ ->setPassword('anotherPasswordHash')
+ ->setSendPasswordByTalk(false);
+
+ $tomorrow = new \DateTime();
+ $tomorrow->setTime(0, 0, 0);
+ $tomorrow->add(new \DateInterval('P1D'));
+
+ $file = $this->createMock(File::class);
+ $file->method('getId')->willReturn(100);
+
+ $share = $this->manager->newShare();
+ $share->setProviderId('foo')
+ ->setId('42')
+ ->setShareType(IShare::TYPE_EMAIL)
+ ->setToken('token')
+ ->setSharedBy('owner')
+ ->setShareOwner('owner')
+ ->setPassword('password')
+ ->setSendPasswordByTalk(true)
+ ->setExpirationDate($tomorrow)
+ ->setNode($file)
+ ->setPermissions(\OCP\Constants::PERMISSION_ALL);
+
+ $manager->expects($this->once())->method('canShare')->willReturn(true);
+ $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
+ $manager->expects($this->once())->method('generalCreateChecks')->with($share);
+ $manager->expects($this->once())->method('verifyPassword')->with('password');
+ $manager->expects($this->once())->method('pathCreateChecks')->with($file);
+ $manager->expects($this->once())->method('linkCreateChecks');
+ $manager->expects($this->once())->method('validateExpirationDateLink');
+
+ $this->hasher->expects($this->once())
+ ->method('verify')
+ ->with('password', 'anotherPasswordHash')
+ ->willReturn(false);
+
+ $this->hasher->expects($this->once())
+ ->method('hash')
+ ->with('password')
+ ->willReturn('hashed');
+
+ $this->defaultProvider->expects($this->once())
+ ->method('update')
+ ->with($share, 'password')
+ ->willReturn($share);
+
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListener, 'post');
+ $hookListener->expects($this->once())->method('post')->with([
+ 'itemType' => 'file',
+ 'itemSource' => 100,
+ 'date' => $tomorrow,
+ 'uidOwner' => 'owner',
+ ]);
+
+ $hookListener2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_update_password', $hookListener2, 'post');
+ $hookListener2->expects($this->once())->method('post')->with([
+ 'itemType' => 'file',
+ 'itemSource' => 100,
+ 'uidOwner' => 'owner',
+ 'token' => 'token',
+ 'disabled' => false,
+ ]);
+
+ $hookListener3 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListener3, 'post');
+ $hookListener3->expects($this->never())->method('post');
+
+ $manager->updateShare($share);
+ }
+
+ public function testUpdateShareMailEnableSendPasswordByTalkWithNoPassword(): void {
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('Cannot enable sending the password by Talk with an empty password');
+
+ $manager = $this->createManagerMock()
+ ->setMethods([
+ 'canShare',
+ 'getShareById',
+ 'generalCreateChecks',
+ 'verifyPassword',
+ 'pathCreateChecks',
+ 'linkCreateChecks',
+ 'validateExpirationDateLink',
+ ])
+ ->getMock();
+
+ $originalShare = $this->manager->newShare();
+ $originalShare->setShareType(IShare::TYPE_EMAIL)
+ ->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ ->setPassword(null)
+ ->setSendPasswordByTalk(false);
+
+ $tomorrow = new \DateTime();
+ $tomorrow->setTime(0, 0, 0);
+ $tomorrow->add(new \DateInterval('P1D'));
+
+ $file = $this->createMock(File::class);
+ $file->method('getId')->willReturn(100);
+
+ $share = $this->manager->newShare();
+ $share->setProviderId('foo')
+ ->setId('42')
+ ->setShareType(IShare::TYPE_EMAIL)
+ ->setToken('token')
+ ->setSharedBy('owner')
+ ->setShareOwner('owner')
+ ->setPassword(null)
+ ->setSendPasswordByTalk(true)
+ ->setExpirationDate($tomorrow)
+ ->setNode($file)
+ ->setPermissions(\OCP\Constants::PERMISSION_ALL);
+
+ $manager->expects($this->once())->method('canShare')->willReturn(true);
+ $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
+ $manager->expects($this->once())->method('generalCreateChecks')->with($share);
+ $manager->expects($this->never())->method('verifyPassword');
+ $manager->expects($this->never())->method('pathCreateChecks');
+ $manager->expects($this->once())->method('linkCreateChecks');
+ $manager->expects($this->never())->method('validateExpirationDateLink');
+
+ // If the password is empty, we have nothing to hash
+ $this->hasher->expects($this->never())
+ ->method('hash');
+
+ $this->defaultProvider->expects($this->never())
+ ->method('update');
+
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListener, 'post');
+ $hookListener->expects($this->never())->method('post');
+
+ $hookListener2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_update_password', $hookListener2, 'post');
+ $hookListener2->expects($this->never())->method('post');
+
+ $hookListener3 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListener3, 'post');
+ $hookListener3->expects($this->never())->method('post');
+
+ $manager->updateShare($share);
+ }
+
+
+ public function testUpdateShareMailEnableSendPasswordByTalkRemovingPassword(): void {
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('Cannot enable sending the password by Talk with an empty password');
+
+ $manager = $this->createManagerMock()
+ ->setMethods([
+ 'canShare',
+ 'getShareById',
+ 'generalCreateChecks',
+ 'verifyPassword',
+ 'pathCreateChecks',
+ 'linkCreateChecks',
+ 'validateExpirationDateLink',
+ ])
+ ->getMock();
+
+ $originalShare = $this->manager->newShare();
+ $originalShare->setShareType(IShare::TYPE_EMAIL)
+ ->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ ->setPassword('passwordHash')
+ ->setSendPasswordByTalk(false);
+
+ $tomorrow = new \DateTime();
+ $tomorrow->setTime(0, 0, 0);
+ $tomorrow->add(new \DateInterval('P1D'));
+
+ $file = $this->createMock(File::class);
+ $file->method('getId')->willReturn(100);
+
+ $share = $this->manager->newShare();
+ $share->setProviderId('foo')
+ ->setId('42')
+ ->setShareType(IShare::TYPE_EMAIL)
+ ->setToken('token')
+ ->setSharedBy('owner')
+ ->setShareOwner('owner')
+ ->setPassword(null)
+ ->setSendPasswordByTalk(true)
+ ->setExpirationDate($tomorrow)
+ ->setNode($file)
+ ->setPermissions(\OCP\Constants::PERMISSION_ALL);
+
+ $manager->expects($this->once())->method('canShare')->willReturn(true);
+ $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
+ $manager->expects($this->once())->method('generalCreateChecks')->with($share);
+ $manager->expects($this->once())->method('verifyPassword');
+ $manager->expects($this->never())->method('pathCreateChecks');
+ $manager->expects($this->once())->method('linkCreateChecks');
+ $manager->expects($this->never())->method('validateExpirationDateLink');
+
+ // If the password is empty, we have nothing to hash
+ $this->hasher->expects($this->never())
+ ->method('hash');
+
+ $this->defaultProvider->expects($this->never())
+ ->method('update');
+
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListener, 'post');
+ $hookListener->expects($this->never())->method('post');
+
+ $hookListener2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_update_password', $hookListener2, 'post');
+ $hookListener2->expects($this->never())->method('post');
+
+ $hookListener3 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListener3, 'post');
+ $hookListener3->expects($this->never())->method('post');
+
+ $manager->updateShare($share);
+ }
+
+
+ public function testUpdateShareMailEnableSendPasswordByTalkRemovingPasswordWithEmptyString(): void {
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('Cannot enable sending the password by Talk with an empty password');
+
+ $manager = $this->createManagerMock()
+ ->setMethods([
+ 'canShare',
+ 'getShareById',
+ 'generalCreateChecks',
+ 'verifyPassword',
+ 'pathCreateChecks',
+ 'linkCreateChecks',
+ 'validateExpirationDateLink',
+ ])
+ ->getMock();
+
+ $originalShare = $this->manager->newShare();
+ $originalShare->setShareType(IShare::TYPE_EMAIL)
+ ->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ ->setPassword('passwordHash')
+ ->setSendPasswordByTalk(false);
+
+ $tomorrow = new \DateTime();
+ $tomorrow->setTime(0, 0, 0);
+ $tomorrow->add(new \DateInterval('P1D'));
+
+ $file = $this->createMock(File::class);
+ $file->method('getId')->willReturn(100);
+
+ $share = $this->manager->newShare();
+ $share->setProviderId('foo')
+ ->setId('42')
+ ->setShareType(IShare::TYPE_EMAIL)
+ ->setToken('token')
+ ->setSharedBy('owner')
+ ->setShareOwner('owner')
+ ->setPassword('')
+ ->setSendPasswordByTalk(true)
+ ->setExpirationDate($tomorrow)
+ ->setNode($file)
+ ->setPermissions(\OCP\Constants::PERMISSION_ALL);
+
+ $manager->expects($this->once())->method('canShare')->willReturn(true);
+ $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
+ $manager->expects($this->once())->method('generalCreateChecks')->with($share);
+ $manager->expects($this->once())->method('verifyPassword');
+ $manager->expects($this->never())->method('pathCreateChecks');
+ $manager->expects($this->once())->method('linkCreateChecks');
+ $manager->expects($this->never())->method('validateExpirationDateLink');
+
+ // If the password is empty, we have nothing to hash
+ $this->hasher->expects($this->never())
+ ->method('hash');
+
+ $this->defaultProvider->expects($this->never())
+ ->method('update');
+
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListener, 'post');
+ $hookListener->expects($this->never())->method('post');
+
+ $hookListener2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_update_password', $hookListener2, 'post');
+ $hookListener2->expects($this->never())->method('post');
+
+ $hookListener3 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListener3, 'post');
+ $hookListener3->expects($this->never())->method('post');
+
+ $manager->updateShare($share);
+ }
+
+
+ public function testUpdateShareMailEnableSendPasswordByTalkWithPreviousPassword(): void {
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('Cannot enable sending the password by Talk without setting a new password');
+
+ $manager = $this->createManagerMock()
+ ->setMethods([
+ 'canShare',
+ 'getShareById',
+ 'generalCreateChecks',
+ 'verifyPassword',
+ 'pathCreateChecks',
+ 'linkCreateChecks',
+ 'validateExpirationDateLink',
+ ])
+ ->getMock();
+
+ $originalShare = $this->manager->newShare();
+ $originalShare->setShareType(IShare::TYPE_EMAIL)
+ ->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ ->setPassword('password')
+ ->setSendPasswordByTalk(false);
+
+ $tomorrow = new \DateTime();
+ $tomorrow->setTime(0, 0, 0);
+ $tomorrow->add(new \DateInterval('P1D'));
+
+ $file = $this->createMock(File::class);
+ $file->method('getId')->willReturn(100);
+
+ $share = $this->manager->newShare();
+ $share->setProviderId('foo')
+ ->setId('42')
+ ->setShareType(IShare::TYPE_EMAIL)
+ ->setToken('token')
+ ->setSharedBy('owner')
+ ->setShareOwner('owner')
+ ->setPassword('password')
+ ->setSendPasswordByTalk(true)
+ ->setExpirationDate($tomorrow)
+ ->setNode($file)
+ ->setPermissions(\OCP\Constants::PERMISSION_ALL);
+
+ $manager->expects($this->once())->method('canShare')->willReturn(true);
+ $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
+ $manager->expects($this->once())->method('generalCreateChecks')->with($share);
+ $manager->expects($this->never())->method('verifyPassword');
+ $manager->expects($this->never())->method('pathCreateChecks');
+ $manager->expects($this->once())->method('linkCreateChecks');
+ $manager->expects($this->never())->method('validateExpirationDateLink');
+
+ // If the old & new passwords are the same, we don't do anything
+ $this->hasher->expects($this->never())
+ ->method('verify');
+ $this->hasher->expects($this->never())
+ ->method('hash');
+
+ $this->defaultProvider->expects($this->never())
+ ->method('update');
+
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListener, 'post');
+ $hookListener->expects($this->never())->method('post');
+
+ $hookListener2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_update_password', $hookListener2, 'post');
+ $hookListener2->expects($this->never())->method('post');
+
+ $hookListener3 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListener3, 'post');
+ $hookListener3->expects($this->never())->method('post');
+
+ $manager->updateShare($share);
+ }
+
+ public function testUpdateShareMailDisableSendPasswordByTalkWithPreviousPassword(): void {
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('Cannot disable sending the password by Talk without setting a new password');
+
+ $manager = $this->createManagerMock()
+ ->setMethods([
+ 'canShare',
+ 'getShareById',
+ 'generalCreateChecks',
+ 'verifyPassword',
+ 'pathCreateChecks',
+ 'linkCreateChecks',
+ 'validateExpirationDateLink',
+ ])
+ ->getMock();
+
+ $originalShare = $this->manager->newShare();
+ $originalShare->setShareType(IShare::TYPE_EMAIL)
+ ->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ ->setPassword('passwordHash')
+ ->setSendPasswordByTalk(true);
+
+ $tomorrow = new \DateTime();
+ $tomorrow->setTime(0, 0, 0);
+ $tomorrow->add(new \DateInterval('P1D'));
+
+ $file = $this->createMock(File::class);
+ $file->method('getId')->willReturn(100);
+
+ $share = $this->manager->newShare();
+ $share->setProviderId('foo')
+ ->setId('42')
+ ->setShareType(IShare::TYPE_EMAIL)
+ ->setToken('token')
+ ->setSharedBy('owner')
+ ->setShareOwner('owner')
+ ->setPassword('passwordHash')
+ ->setSendPasswordByTalk(false)
+ ->setExpirationDate($tomorrow)
+ ->setNode($file)
+ ->setPermissions(\OCP\Constants::PERMISSION_ALL);
+
+ $manager->expects($this->once())->method('canShare')->willReturn(true);
+ $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
+ $manager->expects($this->once())->method('generalCreateChecks')->with($share);
+ $manager->expects($this->never())->method('verifyPassword');
+ $manager->expects($this->never())->method('pathCreateChecks');
+ $manager->expects($this->once())->method('linkCreateChecks');
+ $manager->expects($this->never())->method('validateExpirationDateLink');
+
+ // If the old & new passwords are the same, we don't do anything
+ $this->hasher->expects($this->never())
+ ->method('verify');
+ $this->hasher->expects($this->never())
+ ->method('hash');
+
+ $this->defaultProvider->expects($this->never())
+ ->method('update');
+
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListener, 'post');
+ $hookListener->expects($this->never())->method('post');
+
+ $hookListener2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_update_password', $hookListener2, 'post');
+ $hookListener2->expects($this->never())->method('post');
+
+ $hookListener3 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListener3, 'post');
+ $hookListener3->expects($this->never())->method('post');
+
+ $manager->updateShare($share);
+ }
+
+ public function testUpdateShareMailDisableSendPasswordByTalkWithoutChangingPassword(): void {
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('Cannot disable sending the password by Talk without setting a new password');
+
+ $manager = $this->createManagerMock()
+ ->setMethods([
+ 'canShare',
+ 'getShareById',
+ 'generalCreateChecks',
+ 'verifyPassword',
+ 'pathCreateChecks',
+ 'linkCreateChecks',
+ 'validateExpirationDateLink',
+ ])
+ ->getMock();
+
+ $originalShare = $this->manager->newShare();
+ $originalShare->setShareType(IShare::TYPE_EMAIL)
+ ->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ ->setPassword('passwordHash')
+ ->setSendPasswordByTalk(true);
+
+ $tomorrow = new \DateTime();
+ $tomorrow->setTime(0, 0, 0);
+ $tomorrow->add(new \DateInterval('P1D'));
+
+ $file = $this->createMock(File::class);
+ $file->method('getId')->willReturn(100);
+
+ $share = $this->manager->newShare();
+ $share->setProviderId('foo')
+ ->setId('42')
+ ->setShareType(IShare::TYPE_EMAIL)
+ ->setToken('token')
+ ->setSharedBy('owner')
+ ->setShareOwner('owner')
+ ->setPassword('passwordHash')
+ ->setSendPasswordByTalk(false)
+ ->setExpirationDate($tomorrow)
+ ->setNode($file)
+ ->setPermissions(\OCP\Constants::PERMISSION_ALL);
+
+ $manager->expects($this->once())->method('canShare')->willReturn(true);
+ $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare);
+ $manager->expects($this->once())->method('generalCreateChecks')->with($share);
+ $manager->expects($this->never())->method('verifyPassword');
+ $manager->expects($this->never())->method('pathCreateChecks');
+ $manager->expects($this->once())->method('linkCreateChecks');
+ $manager->expects($this->never())->method('validateExpirationDateLink');
+
+ // If the old & new passwords are the same, we don't do anything
+ $this->hasher->expects($this->never())
+ ->method('verify');
+ $this->hasher->expects($this->never())
+ ->method('hash');
+
+ $this->defaultProvider->expects($this->never())
+ ->method('update');
+
+ $hookListener = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListener, 'post');
+ $hookListener->expects($this->never())->method('post');
+
+ $hookListener2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_update_password', $hookListener2, 'post');
+ $hookListener2->expects($this->never())->method('post');
+
+ $hookListener3 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock();
+ \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListener3, 'post');
+ $hookListener3->expects($this->never())->method('post');
+
+ $manager->updateShare($share);
+ }
+
+ public function testMoveShareLink(): void {
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('Cannot change target of link share');
+
+ $share = $this->manager->newShare();
+ $share->setShareType(IShare::TYPE_LINK);
+
+ $recipient = $this->createMock(IUser::class);
+
+ $this->manager->moveShare($share, $recipient);
+ }
+
+
+ public function testMoveShareUserNotRecipient(): void {
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('Invalid recipient');
+
+ $share = $this->manager->newShare();
+ $share->setShareType(IShare::TYPE_USER);
+
+ $share->setSharedWith('sharedWith');
+
+ $this->manager->moveShare($share, 'recipient');
+ }
+
+ public function testMoveShareUser(): void {
+ $share = $this->manager->newShare();
+ $share->setShareType(IShare::TYPE_USER)
+ ->setId('42')
+ ->setProviderId('foo');
+
+ $share->setSharedWith('recipient');
+
+ $this->defaultProvider->method('move')->with($share, 'recipient')->willReturnArgument(0);
+
+ $this->manager->moveShare($share, 'recipient');
+ $this->addToAssertionCount(1);
+ }
+
+
+ public function testMoveShareGroupNotRecipient(): void {
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('Invalid recipient');
+
+ $share = $this->manager->newShare();
+ $share->setShareType(IShare::TYPE_GROUP);
+
+ $sharedWith = $this->createMock(IGroup::class);
+ $share->setSharedWith('shareWith');
+
+ $recipient = $this->createMock(IUser::class);
+ $sharedWith->method('inGroup')->with($recipient)->willReturn(false);
+
+ $this->groupManager->method('get')->with('shareWith')->willReturn($sharedWith);
+ $this->userManager->method('get')->with('recipient')->willReturn($recipient);
+
+ $this->manager->moveShare($share, 'recipient');
+ }
+
+
+ public function testMoveShareGroupNull(): void {
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('Group "shareWith" does not exist');
+
+ $share = $this->manager->newShare();
+ $share->setShareType(IShare::TYPE_GROUP);
+ $share->setSharedWith('shareWith');
+
+ $recipient = $this->createMock(IUser::class);
+
+ $this->groupManager->method('get')->with('shareWith')->willReturn(null);
+ $this->userManager->method('get')->with('recipient')->willReturn($recipient);
+
+ $this->manager->moveShare($share, 'recipient');
+ }
+
+ public function testMoveShareGroup(): void {
+ $share = $this->manager->newShare();
+ $share->setShareType(IShare::TYPE_GROUP)
+ ->setId('42')
+ ->setProviderId('foo');
+
+ $group = $this->createMock(IGroup::class);
+ $share->setSharedWith('group');
+
+ $recipient = $this->createMock(IUser::class);
+ $group->method('inGroup')->with($recipient)->willReturn(true);
+
+ $this->groupManager->method('get')->with('group')->willReturn($group);
+ $this->userManager->method('get')->with('recipient')->willReturn($recipient);
+
+ $this->defaultProvider->method('move')->with($share, 'recipient')->willReturnArgument(0);
+
+ $this->manager->moveShare($share, 'recipient');
+ $this->addToAssertionCount(1);
+ }
+
+ /**
+ * @dataProvider dataTestShareProviderExists
+ */
+ public function testShareProviderExists($shareType, $expected): void {
+ $factory = $this->getMockBuilder(\OCP\Share\IProviderFactory::class)->getMock();
+ $factory->expects($this->any())->method('getProviderForType')
+ ->willReturnCallback(function ($id) {
+ if ($id === IShare::TYPE_USER) {
+ return true;
+ }
+ throw new Exception\ProviderException();
+ });
+
+ $manager = $this->createManager($factory);
+ $this->assertSame($expected,
+ $manager->shareProviderExists($shareType)
+ );
+ }
+
+ public function dataTestShareProviderExists() {
+ return [
+ [IShare::TYPE_USER, true],
+ [42, false],
+ ];
+ }
+
+ public function testGetSharesInFolder(): void {
+ $factory = new DummyFactory2($this->createMock(IServerContainer::class));
+
+ $manager = $this->createManager($factory);
+
+ $factory->setProvider($this->defaultProvider);
+ $extraProvider = $this->createMock(IShareProvider::class);
+ $factory->setSecondProvider($extraProvider);
+
+ $share1 = $this->createMock(IShare::class);
+ $share2 = $this->createMock(IShare::class);
+ $share3 = $this->createMock(IShare::class);
+ $share4 = $this->createMock(IShare::class);
+
+ $folder = $this->createMock(Folder::class);
+
+ $this->defaultProvider->method('getSharesInFolder')
+ ->with(
+ $this->equalTo('user'),
+ $this->equalTo($folder),
+ $this->equalTo(false)
+ )->willReturn([
+ 1 => [$share1],
+ 2 => [$share2],
+ ]);
+
+ $extraProvider->method('getSharesInFolder')
+ ->with(
+ $this->equalTo('user'),
+ $this->equalTo($folder),
+ $this->equalTo(false)
+ )->willReturn([
+ 2 => [$share3],
+ 3 => [$share4],
+ ]);
+
+ $result = $manager->getSharesInFolder('user', $folder, false);
+
+ $expects = [
+ 1 => [$share1],
+ 2 => [$share2, $share3],
+ 3 => [$share4],
+ ];
+
+ $this->assertSame($expects, $result);
+ }
+
+ public function testGetAccessList(): void {
+ $factory = new DummyFactory2($this->createMock(IServerContainer::class));
+
+ $manager = $this->createManager($factory);
+
+ $factory->setProvider($this->defaultProvider);
+ $extraProvider = $this->createMock(IShareProvider::class);
+ $factory->setSecondProvider($extraProvider);
+
+ $nodeOwner = $this->createMock(IUser::class);
+ $nodeOwner->expects($this->once())
+ ->method('getUID')
+ ->willReturn('user1');
+
+ $node = $this->createMock(Node::class);
+ $node->expects($this->once())
+ ->method('getOwner')
+ ->willReturn($nodeOwner);
+ $node->method('getId')
+ ->willReturn(42);
+
+ $userFolder = $this->createMock(Folder::class);
+ $file = $this->createMock(File::class);
+ $folder = $this->createMock(Folder::class);
+
+ $owner = $this->createMock(IUser::class);
+ $owner->expects($this->once())
+ ->method('getUID')
+ ->willReturn('owner');
+
+ $file->method('getParent')
+ ->willReturn($folder);
+ $file->method('getPath')
+ ->willReturn('/owner/files/folder/file');
+ $file->method('getOwner')
+ ->willReturn($owner);
+ $file->method('getId')
+ ->willReturn(23);
+ $folder->method('getParent')
+ ->willReturn($userFolder);
+ $folder->method('getPath')
+ ->willReturn('/owner/files/folder');
+ $userFolder->method('getFirstNodeById')
+ ->with($this->equalTo(42))
+ ->willReturn($file);
+ $userFolder->method('getPath')
+ ->willReturn('/user1/files');
+
+ $this->userManager->method('userExists')
+ ->with($this->equalTo('user1'))
+ ->willReturn(true);
+
+ $this->defaultProvider->method('getAccessList')
+ ->with(
+ $this->equalTo([$file, $folder]),
+ false
+ )
+ ->willReturn([
+ 'users' => [
+ 'user1',
+ 'user2',
+ 'user3',
+ '123456',
+ ],
+ 'public' => true,
+ ]);
+
+ $extraProvider->method('getAccessList')
+ ->with(
+ $this->equalTo([$file, $folder]),
+ false
+ )
+ ->willReturn([
+ 'users' => [
+ 'user3',
+ 'user4',
+ 'user5',
+ '234567',
+ ],
+ 'remote' => true,
+ ]);
+
+ $this->rootFolder->method('getUserFolder')
+ ->with($this->equalTo('user1'))
+ ->willReturn($userFolder);
+
+ $expected = [
+ 'users' => ['owner', 'user1', 'user2', 'user3', '123456','user4', 'user5', '234567'],
+ 'remote' => true,
+ 'public' => true,
+ ];
+
+ $result = $manager->getAccessList($node, true, false);
+
+ $this->assertSame($expected['public'], $result['public']);
+ $this->assertSame($expected['remote'], $result['remote']);
+ $this->assertSame($expected['users'], $result['users']);
+ }
+
+ public function testGetAccessListWithCurrentAccess(): void {
+ $factory = new DummyFactory2($this->createMock(IServerContainer::class));
+
+ $manager = $this->createManager($factory);
+
+ $factory->setProvider($this->defaultProvider);
+ $extraProvider = $this->createMock(IShareProvider::class);
+ $factory->setSecondProvider($extraProvider);
+
+ $nodeOwner = $this->createMock(IUser::class);
+ $nodeOwner->expects($this->once())
+ ->method('getUID')
+ ->willReturn('user1');
+
+ $node = $this->createMock(Node::class);
+ $node->expects($this->once())
+ ->method('getOwner')
+ ->willReturn($nodeOwner);
+ $node->method('getId')
+ ->willReturn(42);
+
+ $userFolder = $this->createMock(Folder::class);
+ $file = $this->createMock(File::class);
+
+ $owner = $this->createMock(IUser::class);
+ $owner->expects($this->once())
+ ->method('getUID')
+ ->willReturn('owner');
+ $folder = $this->createMock(Folder::class);
+
+ $file->method('getParent')
+ ->willReturn($folder);
+ $file->method('getPath')
+ ->willReturn('/owner/files/folder/file');
+ $file->method('getOwner')
+ ->willReturn($owner);
+ $file->method('getId')
+ ->willReturn(23);
+ $folder->method('getParent')
+ ->willReturn($userFolder);
+ $folder->method('getPath')
+ ->willReturn('/owner/files/folder');
+ $userFolder->method('getFirstNodeById')
+ ->with($this->equalTo(42))
+ ->willReturn($file);
+ $userFolder->method('getPath')
+ ->willReturn('/user1/files');
+
+ $this->userManager->method('userExists')
+ ->with($this->equalTo('user1'))
+ ->willReturn(true);
+
+ $this->defaultProvider->method('getAccessList')
+ ->with(
+ $this->equalTo([$file, $folder]),
+ true
+ )
+ ->willReturn([
+ 'users' => [
+ 'user1' => [],
+ 'user2' => [],
+ 'user3' => [],
+ '123456' => [],
+ ],
+ 'public' => true,
+ ]);
+
+ $extraProvider->method('getAccessList')
+ ->with(
+ $this->equalTo([$file, $folder]),
+ true
+ )
+ ->willReturn([
+ 'users' => [
+ 'user3' => [],
+ 'user4' => [],
+ 'user5' => [],
+ '234567' => [],
+ ],
+ 'remote' => [
+ 'remote1',
+ ],
+ ]);
+
+ $this->rootFolder->method('getUserFolder')
+ ->with($this->equalTo('user1'))
+ ->willReturn($userFolder);
+
+ $expected = [
+ 'users' => [
+ 'owner' => [
+ 'node_id' => 23,
+ 'node_path' => '/folder/file'
+ ]
+ , 'user1' => [], 'user2' => [], 'user3' => [], '123456' => [], 'user4' => [], 'user5' => [], '234567' => []],
+ 'remote' => [
+ 'remote1',
+ ],
+ 'public' => true,
+ ];
+
+ $result = $manager->getAccessList($node, true, true);
+
+ $this->assertSame($expected['public'], $result['public']);
+ $this->assertSame($expected['remote'], $result['remote']);
+ $this->assertSame($expected['users'], $result['users']);
+ }
+
+ public function testGetAllShares(): void {
+ $factory = new DummyFactory2($this->createMock(IServerContainer::class));
+
+ $manager = $this->createManager($factory);
+
+ $factory->setProvider($this->defaultProvider);
+ $extraProvider = $this->createMock(IShareProvider::class);
+ $factory->setSecondProvider($extraProvider);
+
+ $share1 = $this->createMock(IShare::class);
+ $share2 = $this->createMock(IShare::class);
+ $share3 = $this->createMock(IShare::class);
+ $share4 = $this->createMock(IShare::class);
+
+ $this->defaultProvider->method('getAllShares')
+ ->willReturnCallback(function () use ($share1, $share2) {
+ yield $share1;
+ yield $share2;
+ });
+ $extraProvider->method('getAllShares')
+ ->willReturnCallback(function () use ($share3, $share4) {
+ yield $share3;
+ yield $share4;
+ });
+
+ // "yield from", used in "getAllShares()", does not reset the keys, so
+ // "use_keys" has to be disabled to collect all the values while
+ // ignoring the keys returned by the generator.
+ $result = iterator_to_array($manager->getAllShares(), $use_keys = false);
+
+ $expects = [$share1, $share2, $share3, $share4];
+
+ $this->assertSame($expects, $result);
+ }
+
+ public function dataCurrentUserCanEnumerateTargetUser(): array {
+ return [
+ 'Full match guest' => [true, true, false, false, false, false, false, true],
+ 'Full match user' => [false, true, false, false, false, false, false, true],
+ 'Enumeration off guest' => [true, false, false, false, false, false, false, false],
+ 'Enumeration off user' => [false, false, false, false, false, false, false, false],
+ 'Enumeration guest' => [true, false, true, false, false, false, false, true],
+ 'Enumeration user' => [false, false, true, false, false, false, false, true],
+
+ // Restricted enumerations guests never works
+ 'Guest phone' => [true, false, true, true, false, false, false, false],
+ 'Guest group' => [true, false, true, false, true, false, false, false],
+ 'Guest both' => [true, false, true, true, true, false, false, false],
+
+ // Restricted enumerations users
+ 'User phone but not known' => [false, false, true, true, false, false, false, false],
+ 'User phone known' => [false, false, true, true, false, true, false, true],
+ 'User group but no match' => [false, false, true, false, true, false, false, false],
+ 'User group with match' => [false, false, true, false, true, false, true, true],
+ ];
+ }
+
+ /**
+ * @dataProvider dataCurrentUserCanEnumerateTargetUser
+ * @param bool $expected
+ */
+ 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()
+ ->setMethods([
+ 'allowEnumerationFullMatch',
+ 'allowEnumeration',
+ 'limitEnumerationToPhone',
+ 'limitEnumerationToGroups',
+ ])
+ ->getMock();
+
+ $manager->method('allowEnumerationFullMatch')
+ ->willReturn($allowEnumerationFullMatch);
+ $manager->method('allowEnumeration')
+ ->willReturn($allowEnumeration);
+ $manager->method('limitEnumerationToPhone')
+ ->willReturn($limitEnumerationToPhone);
+ $manager->method('limitEnumerationToGroups')
+ ->willReturn($limitEnumerationToGroups);
+
+ $this->knownUserService->method('isKnownToUser')
+ ->with('current', 'target')
+ ->willReturn($isKnownToUser);
+
+ $currentUser = null;
+ if (!$currentUserIsGuest) {
+ $currentUser = $this->createMock(IUser::class);
+ $currentUser->method('getUID')
+ ->willReturn('current');
+ }
+ $targetUser = $this->createMock(IUser::class);
+ $targetUser->method('getUID')
+ ->willReturn('target');
+
+ if ($haveCommonGroup) {
+ $this->groupManager->method('getUserGroupIds')
+ ->willReturnMap([
+ [$targetUser, ['gid1', 'gid2']],
+ [$currentUser, ['gid2', 'gid3']],
+ ]);
+ } else {
+ $this->groupManager->method('getUserGroupIds')
+ ->willReturnMap([
+ [$targetUser, ['gid1', 'gid2']],
+ [$currentUser, ['gid3', 'gid4']],
+ ]);
+ }
+
+ $this->assertSame($expected, $manager->currentUserCanEnumerateTargetUser($currentUser, $targetUser));
+ }
+}
+
+class DummyFactory implements IProviderFactory {
+ /** @var IShareProvider */
+ protected $provider;
+
+ public function __construct(\OCP\IServerContainer $serverContainer) {
+ }
+
+ /**
+ * @param IShareProvider $provider
+ */
+ public function setProvider($provider) {
+ $this->provider = $provider;
+ }
+
+ /**
+ * @param string $id
+ * @return IShareProvider
+ */
+ public function getProvider($id) {
+ return $this->provider;
+ }
+
+ /**
+ * @param int $shareType
+ * @return IShareProvider
+ */
+ public function getProviderForType($shareType) {
+ return $this->provider;
+ }
+
+ /**
+ * @return IShareProvider[]
+ */
+ public function getAllProviders() {
+ return [$this->provider];
+ }
+
+ public function registerProvider(string $shareProvier): void {
+ }
+}
+
+class DummyFactory2 extends DummyFactory {
+ /** @var IShareProvider */
+ private $provider2;
+
+ /**
+ * @param IShareProvider $provider
+ */
+ public function setSecondProvider($provider) {
+ $this->provider2 = $provider;
+ }
+
+ public function getAllProviders() {
+ return [$this->provider, $this->provider2];
+ }
+
+ public function registerProvider(string $shareProvier): void {
+ }
+}
diff --git a/tests/lib/Share20/ShareByMailProviderTest.php b/tests/lib/Share20/ShareByMailProviderTest.php
index 7e3eee106e8..01029e421e0 100644
--- a/tests/lib/Share20/ShareByMailProviderTest.php
+++ b/tests/lib/Share20/ShareByMailProviderTest.php
@@ -189,7 +189,7 @@ class ShareByMailProviderTest extends TestCase {
return $qb->getLastInsertId();
}
- public function testGetSharesByWithResharesAndNoNode() {
+ public function testGetSharesByWithResharesAndNoNode(): void {
$this->addShareToDB(
IShare::TYPE_EMAIL,
'external.one@domain.tld',
@@ -236,7 +236,7 @@ class ShareByMailProviderTest extends TestCase {
$this->assertEquals('external.one@domain.tld', $actual[0]->getSharedWith());
}
- public function testGetSharesByWithResharesAndNode() {
+ public function testGetSharesByWithResharesAndNode(): void {
$this->addShareToDB(
IShare::TYPE_EMAIL,
'external.one@domain.tld',
diff --git a/tests/lib/Share20/ShareHelperTest.php b/tests/lib/Share20/ShareHelperTest.php
index 04a079db0e9..8aaa8350ea9 100644
--- a/tests/lib/Share20/ShareHelperTest.php
+++ b/tests/lib/Share20/ShareHelperTest.php
@@ -51,7 +51,7 @@ class ShareHelperTest extends TestCase {
/**
* @dataProvider dataGetPathsForAccessList
*/
- public function testGetPathsForAccessList(array $userList, array $userMap, $resolveUsers, array $remoteList, array $remoteMap, $resolveRemotes, array $expected) {
+ public function testGetPathsForAccessList(array $userList, array $userMap, $resolveUsers, array $remoteList, array $remoteMap, $resolveRemotes, array $expected): void {
$this->manager->expects($this->once())
->method('getAccessList')
->willReturn([
@@ -107,7 +107,7 @@ class ShareHelperTest extends TestCase {
* @param array $nodes
* @param array $expected
*/
- public function testGetPathsForUsers(array $users, array $nodes, array $expected) {
+ public function testGetPathsForUsers(array $users, array $nodes, array $expected): void {
$lastNode = null;
foreach ($nodes as $nodeId => $nodeName) {
/** @var Node|\PHPUnit\Framework\MockObject\MockObject $node */
@@ -164,7 +164,7 @@ class ShareHelperTest extends TestCase {
* @param array $nodes
* @param array $expected
*/
- public function testGetPathsForRemotes(array $remotes, array $nodes, array $expected) {
+ public function testGetPathsForRemotes(array $remotes, array $nodes, array $expected): void {
$lastNode = null;
foreach ($nodes as $nodeId => $nodePath) {
/** @var Node|\PHPUnit\Framework\MockObject\MockObject $node */
@@ -202,7 +202,7 @@ class ShareHelperTest extends TestCase {
* @param string $path
* @param string $expected
*/
- public function testGetMountedPath($path, $expected) {
+ public function testGetMountedPath($path, $expected): void {
/** @var Node|\PHPUnit\Framework\MockObject\MockObject $node */
$node = $this->createMock(Node::class);
$node->expects($this->once())
diff --git a/tests/lib/Share20/ShareTest.php b/tests/lib/Share20/ShareTest.php
index 6769683aafe..72f3b46190c 100644
--- a/tests/lib/Share20/ShareTest.php
+++ b/tests/lib/Share20/ShareTest.php
@@ -31,26 +31,26 @@ class ShareTest extends \Test\TestCase {
}
- public function testSetIdInvalid() {
+ public function testSetIdInvalid(): void {
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('String expected.');
$this->share->setId(1.2);
}
- public function testSetIdInt() {
+ public function testSetIdInt(): void {
$this->share->setId(42);
$this->assertEquals('42', $this->share->getId());
}
- public function testSetIdString() {
+ public function testSetIdString(): void {
$this->share->setId('foo');
$this->assertEquals('foo', $this->share->getId());
}
- public function testSetIdOnce() {
+ public function testSetIdOnce(): void {
$this->expectException(\OCP\Share\Exceptions\IllegalIDChangeException::class);
$this->expectExceptionMessage('Not allowed to assign a new internal id to a share');
@@ -59,7 +59,7 @@ class ShareTest extends \Test\TestCase {
}
- public function testSetProviderIdInt() {
+ public function testSetProviderIdInt(): void {
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('String expected.');
@@ -67,14 +67,14 @@ class ShareTest extends \Test\TestCase {
}
- public function testSetProviderIdString() {
+ public function testSetProviderIdString(): void {
$this->share->setProviderId('foo');
$this->share->setId('bar');
$this->assertEquals('foo:bar', $this->share->getFullId());
}
- public function testSetProviderIdOnce() {
+ public function testSetProviderIdOnce(): void {
$this->expectException(\OCP\Share\Exceptions\IllegalIDChangeException::class);
$this->expectExceptionMessage('Not allowed to assign a new provider id to a share');
diff --git a/tests/lib/SubAdminTest.php b/tests/lib/SubAdminTest.php
index a4138fa922b..2827fe84d78 100644
--- a/tests/lib/SubAdminTest.php
+++ b/tests/lib/SubAdminTest.php
@@ -94,7 +94,7 @@ class SubAdminTest extends \Test\TestCase {
->execute();
}
- public function testCreateSubAdmin() {
+ public function testCreateSubAdmin(): void {
$subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher);
$subAdmin->createSubAdmin($this->users[0], $this->groups[0]);
@@ -119,7 +119,7 @@ class SubAdminTest extends \Test\TestCase {
->execute();
}
- public function testDeleteSubAdmin() {
+ public function testDeleteSubAdmin(): void {
$subAdmin = new \OC\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]);
@@ -135,7 +135,7 @@ class SubAdminTest extends \Test\TestCase {
$this->assertEmpty($result);
}
- public function testGetSubAdminsGroups() {
+ public function testGetSubAdminsGroups(): void {
$subAdmin = new \OC\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]);
@@ -151,7 +151,7 @@ class SubAdminTest extends \Test\TestCase {
$subAdmin->deleteSubAdmin($this->users[0], $this->groups[1]);
}
- public function testGetGroupsSubAdmins() {
+ public function testGetGroupsSubAdmins(): void {
$subAdmin = new \OC\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]);
@@ -167,7 +167,7 @@ class SubAdminTest extends \Test\TestCase {
$subAdmin->deleteSubAdmin($this->users[1], $this->groups[0]);
}
- public function testGetAllSubAdmin() {
+ public function testGetAllSubAdmin(): void {
$subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher);
$subAdmin->createSubAdmin($this->users[0], $this->groups[0]);
@@ -182,7 +182,7 @@ class SubAdminTest extends \Test\TestCase {
$this->assertNotContains(['user' => null, 'group' => null], $result);
}
- public function testIsSubAdminofGroup() {
+ public function testIsSubAdminofGroup(): void {
$subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher);
$subAdmin->createSubAdmin($this->users[0], $this->groups[0]);
@@ -193,7 +193,7 @@ class SubAdminTest extends \Test\TestCase {
$subAdmin->deleteSubAdmin($this->users[0], $this->groups[0]);
}
- public function testIsSubAdmin() {
+ public function testIsSubAdmin(): void {
$subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher);
$subAdmin->createSubAdmin($this->users[0], $this->groups[0]);
@@ -203,14 +203,14 @@ class SubAdminTest extends \Test\TestCase {
$subAdmin->deleteSubAdmin($this->users[0], $this->groups[0]);
}
- public function testIsSubAdminAsAdmin() {
+ public function testIsSubAdminAsAdmin(): void {
$subAdmin = new \OC\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() {
+ public function testIsUserAccessible(): void {
$subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher);
$this->groups[0]->addUser($this->users[1]);
$this->groups[1]->addUser($this->users[1]);
@@ -226,12 +226,12 @@ class SubAdminTest extends \Test\TestCase {
$subAdmin->deleteSubAdmin($this->users[2], $this->groups[2]);
}
- public function testIsUserAccessibleAsUser() {
+ public function testIsUserAccessibleAsUser(): void {
$subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher);
$this->assertFalse($subAdmin->isUserAccessible($this->users[0], $this->users[1]));
}
- public function testIsUserAccessibleAdmin() {
+ public function testIsUserAccessibleAdmin(): void {
$subAdmin = new \OC\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]);
@@ -239,7 +239,7 @@ class SubAdminTest extends \Test\TestCase {
$this->assertFalse($subAdmin->isUserAccessible($this->users[0], $this->users[1]));
}
- public function testPostDeleteUser() {
+ public function testPostDeleteUser(): void {
$subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher);
$user = array_shift($this->users);
@@ -251,7 +251,7 @@ class SubAdminTest extends \Test\TestCase {
$this->assertEmpty($subAdmin->getAllSubAdmins());
}
- public function testPostDeleteGroup() {
+ public function testPostDeleteGroup(): void {
$subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher);
$group = array_shift($this->groups);
@@ -263,7 +263,7 @@ class SubAdminTest extends \Test\TestCase {
$this->assertEmpty($subAdmin->getAllSubAdmins());
}
- public function testHooks() {
+ public function testHooks(): void {
$subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn, $this->eventDispatcher);
$test = $this;
diff --git a/tests/lib/Support/Subscription/RegistryTest.php b/tests/lib/Support/Subscription/RegistryTest.php
index de7f7600496..869c1498c41 100644
--- a/tests/lib/Support/Subscription/RegistryTest.php
+++ b/tests/lib/Support/Subscription/RegistryTest.php
@@ -66,13 +66,13 @@ class RegistryTest extends TestCase {
/**
* Doesn't assert anything, just checks whether anything "explodes"
*/
- public function testDelegateToNone() {
+ public function testDelegateToNone(): void {
$this->registry->delegateHasValidSubscription();
$this->addToAssertionCount(1);
}
- public function testDoubleRegistration() {
+ public function testDoubleRegistration(): void {
$this->expectException(\OCP\Support\Subscription\Exception\AlreadyRegisteredException::class);
/* @var ISubscription $subscription1 */
@@ -83,12 +83,12 @@ class RegistryTest extends TestCase {
$this->registry->register($subscription2);
}
- public function testNoSupportApp() {
+ public function testNoSupportApp(): void {
$this->assertSame([], $this->registry->delegateGetSupportedApps());
$this->assertSame(false, $this->registry->delegateHasValidSubscription());
}
- public function testDelegateHasValidSubscription() {
+ public function testDelegateHasValidSubscription(): void {
/* @var ISubscription|\PHPUnit\Framework\MockObject\MockObject $subscription */
$subscription = $this->createMock(ISubscription::class);
$subscription->expects($this->once())
@@ -99,7 +99,7 @@ class RegistryTest extends TestCase {
$this->assertSame(true, $this->registry->delegateHasValidSubscription());
}
- public function testDelegateHasValidSubscriptionConfig() {
+ public function testDelegateHasValidSubscriptionConfig(): void {
/* @var ISubscription|\PHPUnit\Framework\MockObject\MockObject $subscription */
$this->config->expects($this->once())
->method('getSystemValueBool')
@@ -109,7 +109,7 @@ class RegistryTest extends TestCase {
$this->assertSame(true, $this->registry->delegateHasValidSubscription());
}
- public function testDelegateHasExtendedSupport() {
+ public function testDelegateHasExtendedSupport(): void {
/* @var ISubscription|\PHPUnit\Framework\MockObject\MockObject $subscription */
$subscription = $this->createMock(ISubscription::class);
$subscription->expects($this->once())
@@ -121,7 +121,7 @@ class RegistryTest extends TestCase {
}
- public function testDelegateGetSupportedApps() {
+ public function testDelegateGetSupportedApps(): void {
/* @var ISupportedApps|\PHPUnit\Framework\MockObject\MockObject $subscription */
$subscription = $this->createMock(ISupportedApps::class);
$subscription->expects($this->once())
@@ -132,7 +132,7 @@ class RegistryTest extends TestCase {
$this->assertSame(['abc'], $this->registry->delegateGetSupportedApps());
}
- public function testSubscriptionService() {
+ public function testSubscriptionService(): void {
$this->serverContainer->method('query')
->with(DummySubscription::class)
->willReturn(new DummySubscription(true, false, false));
@@ -142,7 +142,7 @@ class RegistryTest extends TestCase {
$this->assertFalse($this->registry->delegateHasExtendedSupport());
}
- public function testDelegateIsHardUserLimitReached() {
+ public function testDelegateIsHardUserLimitReached(): void {
/* @var ISubscription|\PHPUnit\Framework\MockObject\MockObject $subscription */
$subscription = $this->createMock(ISubscription::class);
$subscription->expects($this->once())
@@ -163,7 +163,7 @@ class RegistryTest extends TestCase {
$this->assertSame(true, $this->registry->delegateIsHardUserLimitReached($this->notificationManager));
}
- public function testDelegateIsHardUserLimitReachedWithoutSupportApp() {
+ public function testDelegateIsHardUserLimitReachedWithoutSupportApp(): void {
$this->config->expects($this->once())
->method('getSystemValueBool')
->with('one-click-instance')
@@ -185,7 +185,7 @@ class RegistryTest extends TestCase {
/**
* @dataProvider dataForUserLimitCheck
*/
- public function testDelegateIsHardUserLimitReachedWithoutSupportAppAndUserCount($userLimit, $userCount, $disabledUsers, $expectedResult) {
+ public function testDelegateIsHardUserLimitReachedWithoutSupportAppAndUserCount($userLimit, $userCount, $disabledUsers, $expectedResult): void {
$this->config->expects($this->once())
->method('getSystemValueBool')
->with('one-click-instance')
diff --git a/tests/lib/SystemTag/SystemTagManagerTest.php b/tests/lib/SystemTag/SystemTagManagerTest.php
index 5029eaa7df6..7b93d900bee 100644
--- a/tests/lib/SystemTag/SystemTagManagerTest.php
+++ b/tests/lib/SystemTag/SystemTagManagerTest.php
@@ -102,7 +102,7 @@ class SystemTagManagerTest extends TestCase {
/**
* @dataProvider getAllTagsDataProvider
*/
- public function testGetAllTags($testTags) {
+ public function testGetAllTags($testTags): void {
$testTagsById = [];
foreach ($testTags as $testTag) {
$tag = $this->tagManager->createTag($testTag[0], $testTag[1], $testTag[2]);
@@ -211,7 +211,7 @@ class SystemTagManagerTest extends TestCase {
/**
* @dataProvider getAllTagsFilteredDataProvider
*/
- public function testGetAllTagsFiltered($testTags, $visibilityFilter, $nameSearch, $expectedResults) {
+ public function testGetAllTagsFiltered($testTags, $visibilityFilter, $nameSearch, $expectedResults): void {
foreach ($testTags as $testTag) {
$this->tagManager->createTag($testTag[0], $testTag[1], $testTag[2]);
}
@@ -244,7 +244,7 @@ class SystemTagManagerTest extends TestCase {
/**
* @dataProvider oneTagMultipleFlagsProvider
*/
- public function testCreateDuplicate($name, $userVisible, $userAssignable) {
+ public function testCreateDuplicate($name, $userVisible, $userAssignable): void {
$this->expectException(\OCP\SystemTag\TagAlreadyExistsException::class);
try {
@@ -255,7 +255,7 @@ class SystemTagManagerTest extends TestCase {
$this->tagManager->createTag($name, $userVisible, $userAssignable);
}
- public function testCreateOverlongName() {
+ public function testCreateOverlongName(): void {
$tag = $this->tagManager->createTag('Zona circundante do Palácio Nacional da Ajuda (Jardim das Damas, Salão de Física, Torre Sineira, Paço Velho e Jardim Botânico)', true, true);
$this->assertSame('Zona circundante do Palácio Nacional da Ajuda (Jardim das Damas', $tag->getName()); // 63 characters but 64 bytes due to "á"
}
@@ -263,14 +263,14 @@ class SystemTagManagerTest extends TestCase {
/**
* @dataProvider oneTagMultipleFlagsProvider
*/
- public function testGetExistingTag($name, $userVisible, $userAssignable) {
+ public function testGetExistingTag($name, $userVisible, $userAssignable): void {
$tag1 = $this->tagManager->createTag($name, $userVisible, $userAssignable);
$tag2 = $this->tagManager->getTag($name, $userVisible, $userAssignable);
$this->assertSameTag($tag1, $tag2);
}
- public function testGetExistingTagById() {
+ public function testGetExistingTagById(): void {
$tag1 = $this->tagManager->createTag('one', true, false);
$tag2 = $this->tagManager->createTag('two', false, true);
@@ -283,14 +283,14 @@ class SystemTagManagerTest extends TestCase {
}
- public function testGetNonExistingTag() {
+ public function testGetNonExistingTag(): void {
$this->expectException(\OCP\SystemTag\TagNotFoundException::class);
$this->tagManager->getTag('nonexist', false, false);
}
- public function testGetNonExistingTagsById() {
+ public function testGetNonExistingTagsById(): void {
$this->expectException(\OCP\SystemTag\TagNotFoundException::class);
$tag1 = $this->tagManager->createTag('one', true, false);
@@ -298,7 +298,7 @@ class SystemTagManagerTest extends TestCase {
}
- public function testGetInvalidTagIdFormat() {
+ public function testGetInvalidTagIdFormat(): void {
$this->expectException(\InvalidArgumentException::class);
$tag1 = $this->tagManager->createTag('one', true, false);
@@ -333,7 +333,7 @@ class SystemTagManagerTest extends TestCase {
/**
* @dataProvider updateTagProvider
*/
- public function testUpdateTag($tagCreate, $tagUpdated) {
+ public function testUpdateTag($tagCreate, $tagUpdated): void {
$tag1 = $this->tagManager->createTag(
$tagCreate[0],
$tagCreate[1],
@@ -360,7 +360,7 @@ class SystemTagManagerTest extends TestCase {
/**
* @dataProvider updateTagProvider
*/
- public function testUpdateTagDuplicate($tagCreate, $tagUpdated) {
+ public function testUpdateTagDuplicate($tagCreate, $tagUpdated): void {
$this->expectException(\OCP\SystemTag\TagAlreadyExistsException::class);
$this->tagManager->createTag(
@@ -383,7 +383,7 @@ class SystemTagManagerTest extends TestCase {
);
}
- public function testDeleteTags() {
+ public function testDeleteTags(): void {
$tag1 = $this->tagManager->createTag('one', true, false);
$tag2 = $this->tagManager->createTag('two', false, true);
@@ -393,13 +393,13 @@ class SystemTagManagerTest extends TestCase {
}
- public function testDeleteNonExistingTag() {
+ public function testDeleteNonExistingTag(): void {
$this->expectException(\OCP\SystemTag\TagNotFoundException::class);
$this->tagManager->deleteTags([100]);
}
- public function testDeleteTagRemovesRelations() {
+ public function testDeleteTagRemovesRelations(): void {
$tag1 = $this->tagManager->createTag('one', true, false);
$tag2 = $this->tagManager->createTag('two', true, true);
@@ -434,7 +434,7 @@ class SystemTagManagerTest extends TestCase {
/**
* @dataProvider visibilityCheckProvider
*/
- public function testVisibilityCheck($userVisible, $userAssignable, $isAdmin, $expectedResult) {
+ public function testVisibilityCheck($userVisible, $userAssignable, $isAdmin, $expectedResult): void {
$user = $this->getMockBuilder(IUser::class)->getMock();
$user->expects($this->any())
->method('getUID')
@@ -481,7 +481,7 @@ class SystemTagManagerTest extends TestCase {
/**
* @dataProvider assignabilityCheckProvider
*/
- public function testAssignabilityCheck($userVisible, $userAssignable, $isAdmin, $expectedResult, $userGroupIds = [], $tagGroupIds = []) {
+ public function testAssignabilityCheck($userVisible, $userAssignable, $isAdmin, $expectedResult, $userGroupIds = [], $tagGroupIds = []): void {
$user = $this->getMockBuilder(IUser::class)->getMock();
$user->expects($this->any())
->method('getUID')
@@ -501,7 +501,7 @@ class SystemTagManagerTest extends TestCase {
$this->assertEquals($expectedResult, $this->tagManager->canUserAssignTag($tag1, $user));
}
- public function testTagGroups() {
+ public function testTagGroups(): void {
$tag1 = $this->tagManager->createTag('tag1', true, false);
$tag2 = $this->tagManager->createTag('tag2', true, false);
$this->tagManager->setTagGroups($tag1, ['group1', 'group2']);
@@ -521,7 +521,7 @@ class SystemTagManagerTest extends TestCase {
/**
* empty groupIds should be ignored
*/
- public function testEmptyTagGroup() {
+ public function testEmptyTagGroup(): void {
$tag1 = $this->tagManager->createTag('tag1', true, false);
$this->tagManager->setTagGroups($tag1, ['']);
$this->assertEquals([], $this->tagManager->getTagGroups($tag1));
diff --git a/tests/lib/SystemTag/SystemTagObjectMapperTest.php b/tests/lib/SystemTag/SystemTagObjectMapperTest.php
index 7beb1c1f1e1..3569c98b5bc 100644
--- a/tests/lib/SystemTag/SystemTagObjectMapperTest.php
+++ b/tests/lib/SystemTag/SystemTagObjectMapperTest.php
@@ -113,7 +113,7 @@ class SystemTagObjectMapperTest extends TestCase {
$query->delete(SystemTagManager::TAG_TABLE)->execute();
}
- public function testGetTagIdsForObjects() {
+ public function testGetTagIdsForObjects(): void {
$tagIdMapping = $this->tagMapper->getTagIdsForObjects(
['1', '2', '3', '4'],
'testtype'
@@ -127,7 +127,7 @@ class SystemTagObjectMapperTest extends TestCase {
], $tagIdMapping);
}
- public function testGetTagIdsForNoObjects() {
+ public function testGetTagIdsForNoObjects(): void {
$tagIdMapping = $this->tagMapper->getTagIdsForObjects(
[],
'testtype'
@@ -136,7 +136,7 @@ class SystemTagObjectMapperTest extends TestCase {
$this->assertEquals([], $tagIdMapping);
}
- public function testGetTagIdsForALotOfObjects() {
+ public function testGetTagIdsForALotOfObjects(): void {
$ids = range(1, 10500);
$tagIdMapping = $this->tagMapper->getTagIdsForObjects(
$ids,
@@ -147,7 +147,7 @@ class SystemTagObjectMapperTest extends TestCase {
$this->assertEquals([$this->tag1->getId(), $this->tag2->getId()], $tagIdMapping[1]);
}
- public function testGetObjectsForTags() {
+ public function testGetObjectsForTags(): void {
$objectIds = $this->tagMapper->getObjectIdsForTags(
[$this->tag1->getId(), $this->tag2->getId(), $this->tag3->getId()],
'testtype'
@@ -160,7 +160,7 @@ class SystemTagObjectMapperTest extends TestCase {
], $objectIds);
}
- public function testGetObjectsForTagsLimit() {
+ public function testGetObjectsForTagsLimit(): void {
$objectIds = $this->tagMapper->getObjectIdsForTags(
[$this->tag1->getId()],
'testtype',
@@ -173,7 +173,7 @@ class SystemTagObjectMapperTest extends TestCase {
}
- public function testGetObjectsForTagsLimitWithMultipleTags() {
+ public function testGetObjectsForTagsLimitWithMultipleTags(): void {
$this->expectException(\InvalidArgumentException::class);
$this->tagMapper->getObjectIdsForTags(
@@ -183,7 +183,7 @@ class SystemTagObjectMapperTest extends TestCase {
);
}
- public function testGetObjectsForTagsLimitOffset() {
+ public function testGetObjectsForTagsLimitOffset(): void {
$objectIds = $this->tagMapper->getObjectIdsForTags(
[$this->tag1->getId()],
'testtype',
@@ -197,7 +197,7 @@ class SystemTagObjectMapperTest extends TestCase {
}
- public function testGetObjectsForNonExistingTag() {
+ public function testGetObjectsForNonExistingTag(): void {
$this->expectException(\OCP\SystemTag\TagNotFoundException::class);
$this->tagMapper->getObjectIdsForTags(
@@ -206,7 +206,7 @@ class SystemTagObjectMapperTest extends TestCase {
);
}
- public function testAssignUnassignTags() {
+ public function testAssignUnassignTags(): void {
$this->tagMapper->unassignTags('1', 'testtype', [$this->tag1->getId()]);
$tagIdMapping = $this->tagMapper->getTagIdsForObjects('1', 'testtype');
@@ -224,7 +224,7 @@ class SystemTagObjectMapperTest extends TestCase {
], $tagIdMapping);
}
- public function testReAssignUnassignTags() {
+ public function testReAssignUnassignTags(): void {
// reassign tag1
$this->tagMapper->assignTags('1', 'testtype', [$this->tag1->getId()]);
@@ -235,13 +235,13 @@ class SystemTagObjectMapperTest extends TestCase {
}
- public function testAssignNonExistingTags() {
+ public function testAssignNonExistingTags(): void {
$this->expectException(\OCP\SystemTag\TagNotFoundException::class);
$this->tagMapper->assignTags('1', 'testtype', [100]);
}
- public function testAssignNonExistingTagInArray() {
+ public function testAssignNonExistingTagInArray(): void {
$caught = false;
try {
$this->tagMapper->assignTags('1', 'testtype', [100, $this->tag3->getId()]);
@@ -262,13 +262,13 @@ class SystemTagObjectMapperTest extends TestCase {
}
- public function testUnassignNonExistingTags() {
+ public function testUnassignNonExistingTags(): void {
$this->expectException(\OCP\SystemTag\TagNotFoundException::class);
$this->tagMapper->unassignTags('1', 'testtype', [100]);
}
- public function testUnassignNonExistingTagsInArray() {
+ public function testUnassignNonExistingTagsInArray(): void {
$caught = false;
try {
$this->tagMapper->unassignTags('1', 'testtype', [100, $this->tag1->getId()]);
@@ -288,7 +288,7 @@ class SystemTagObjectMapperTest extends TestCase {
], $tagIdMapping, 'None of the tags got unassigned');
}
- public function testHaveTagAllMatches() {
+ public function testHaveTagAllMatches(): void {
$this->assertTrue(
$this->tagMapper->haveTag(
['1'],
@@ -340,7 +340,7 @@ class SystemTagObjectMapperTest extends TestCase {
);
}
- public function testHaveTagAtLeastOneMatch() {
+ public function testHaveTagAtLeastOneMatch(): void {
$this->assertTrue(
$this->tagMapper->haveTag(
['1'],
@@ -393,7 +393,7 @@ class SystemTagObjectMapperTest extends TestCase {
}
- public function testHaveTagNonExisting() {
+ public function testHaveTagNonExisting(): void {
$this->expectException(\OCP\SystemTag\TagNotFoundException::class);
$this->tagMapper->haveTag(
diff --git a/tests/lib/TagsTest.php b/tests/lib/TagsTest.php
index a3e0c8f750f..18768970954 100644
--- a/tests/lib/TagsTest.php
+++ b/tests/lib/TagsTest.php
@@ -59,7 +59,7 @@ class TagsTest extends \Test\TestCase {
parent::tearDown();
}
- public function testTagManagerWithoutUserReturnsNull() {
+ public function testTagManagerWithoutUserReturnsNull(): void {
$this->userSession = $this->createMock(IUserSession::class);
$this->userSession
->expects($this->any())
@@ -69,7 +69,7 @@ class TagsTest extends \Test\TestCase {
$this->assertNull($this->tagMgr->load($this->objectType));
}
- public function testInstantiateWithDefaults() {
+ public function testInstantiateWithDefaults(): void {
$defaultTags = ['Friends', 'Family', 'Work', 'Other'];
$tagger = $this->tagMgr->load($this->objectType, $defaultTags);
@@ -77,7 +77,7 @@ class TagsTest extends \Test\TestCase {
$this->assertEquals(4, count($tagger->getTags()));
}
- public function testAddTags() {
+ public function testAddTags(): void {
$tags = ['Friends', 'Family', 'Work', 'Other'];
$tagger = $this->tagMgr->load($this->objectType);
@@ -94,7 +94,7 @@ class TagsTest extends \Test\TestCase {
$this->assertCount(4, $tagger->getTags(), 'Wrong number of added tags');
}
- public function testAddMultiple() {
+ public function testAddMultiple(): void {
$tags = ['Friends', 'Family', 'Work', 'Other'];
$tagger = $this->tagMgr->load($this->objectType);
@@ -142,7 +142,7 @@ class TagsTest extends \Test\TestCase {
$this->assertCount(4, $tagger->getTags(), 'Not all previously saved tags found');
}
- public function testIsEmpty() {
+ public function testIsEmpty(): void {
$tagger = $this->tagMgr->load($this->objectType);
$this->assertEquals(0, count($tagger->getTags()));
@@ -154,7 +154,7 @@ class TagsTest extends \Test\TestCase {
$this->assertFalse($tagger->isEmpty());
}
- public function testGetTagsForObjects() {
+ public function testGetTagsForObjects(): void {
$defaultTags = ['Friends', 'Family', 'Work', 'Other'];
$tagger = $this->tagMgr->load($this->objectType, $defaultTags);
@@ -184,7 +184,7 @@ class TagsTest extends \Test\TestCase {
);
}
- public function testGetTagsForObjectsMassiveResults() {
+ public function testGetTagsForObjectsMassiveResults(): void {
$defaultTags = ['tag1'];
$tagger = $this->tagMgr->load($this->objectType, $defaultTags);
$tagData = $tagger->getTags();
@@ -209,7 +209,7 @@ class TagsTest extends \Test\TestCase {
$this->assertEquals(1500, count($tags));
}
- public function testDeleteTags() {
+ public function testDeleteTags(): void {
$defaultTags = ['Friends', 'Family', 'Work', 'Other'];
$tagger = $this->tagMgr->load($this->objectType, $defaultTags);
@@ -222,7 +222,7 @@ class TagsTest extends \Test\TestCase {
$this->assertEquals(0, count($tagger->getTags()));
}
- public function testRenameTag() {
+ public function testRenameTag(): void {
$defaultTags = ['Friends', 'Family', 'Wrok', 'Other'];
$tagger = $this->tagMgr->load($this->objectType, $defaultTags);
@@ -233,7 +233,7 @@ class TagsTest extends \Test\TestCase {
$this->assertFalse($tagger->rename('Work', 'Family')); // Collide with existing tag.
}
- public function testTagAs() {
+ public function testTagAs(): void {
$objids = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$tagger = $this->tagMgr->load($this->objectType);
@@ -249,7 +249,7 @@ class TagsTest extends \Test\TestCase {
/**
* @depends testTagAs
*/
- public function testUnTag() {
+ public function testUnTag(): void {
$objIds = [1, 2, 3, 4, 5, 6, 7, 8, 9];
// Is this "legal"?
@@ -266,7 +266,7 @@ class TagsTest extends \Test\TestCase {
$this->assertEquals(0, count($tagger->getIdsForTag('Family')));
}
- public function testFavorite() {
+ public function testFavorite(): void {
$tagger = $this->tagMgr->load($this->objectType);
$this->assertTrue($tagger->addToFavorites(1));
$this->assertEquals([1], $tagger->getFavorites());
diff --git a/tests/lib/TaskProcessing/TaskProcessingTest.php b/tests/lib/TaskProcessing/TaskProcessingTest.php
index 624f09ae2d8..38675e826bf 100644
--- a/tests/lib/TaskProcessing/TaskProcessingTest.php
+++ b/tests/lib/TaskProcessing/TaskProcessingTest.php
@@ -484,7 +484,7 @@ class TaskProcessingTest extends \Test\TestCase {
return $file;
}
- public function testShouldNotHaveAnyProviders() {
+ public function testShouldNotHaveAnyProviders(): void {
$this->registrationContext->expects($this->any())->method('getTaskProcessingProviders')->willReturn([]);
self::assertCount(0, $this->manager->getAvailableTaskTypes());
self::assertFalse($this->manager->hasProviders());
@@ -492,7 +492,7 @@ class TaskProcessingTest extends \Test\TestCase {
$this->manager->scheduleTask(new Task(TextToText::ID, ['input' => 'Hello'], 'test', null));
}
- public function testProviderShouldBeRegisteredAndTaskFailValidation() {
+ public function testProviderShouldBeRegisteredAndTaskFailValidation(): void {
$this->registrationContext->expects($this->any())->method('getTaskProcessingProviders')->willReturn([
new ServiceRegistration('test', BrokenSyncProvider::class)
]);
@@ -504,7 +504,7 @@ class TaskProcessingTest extends \Test\TestCase {
$this->manager->scheduleTask($task);
}
- public function testProviderShouldBeRegisteredAndTaskWithFilesFailValidation() {
+ public function testProviderShouldBeRegisteredAndTaskWithFilesFailValidation(): void {
$this->registrationContext->expects($this->any())->method('getTaskProcessingTaskTypes')->willReturn([
new ServiceRegistration('test', AudioToImage::class)
]);
@@ -528,7 +528,7 @@ class TaskProcessingTest extends \Test\TestCase {
$this->manager->scheduleTask($task);
}
- public function testProviderShouldBeRegisteredAndFail() {
+ public function testProviderShouldBeRegisteredAndFail(): void {
$this->registrationContext->expects($this->any())->method('getTaskProcessingProviders')->willReturn([
new ServiceRegistration('test', FailingSyncProvider::class)
]);
@@ -556,7 +556,7 @@ class TaskProcessingTest extends \Test\TestCase {
self::assertEquals(FailingSyncProvider::ERROR_MESSAGE, $task->getErrorMessage());
}
- public function testProviderShouldBeRegisteredAndFailOutputValidation() {
+ public function testProviderShouldBeRegisteredAndFailOutputValidation(): void {
$this->registrationContext->expects($this->any())->method('getTaskProcessingProviders')->willReturn([
new ServiceRegistration('test', BrokenSyncProvider::class)
]);
@@ -584,7 +584,7 @@ class TaskProcessingTest extends \Test\TestCase {
self::assertEquals('The task was processed successfully but the provider\'s output doesn\'t pass validation against the task type\'s outputShape spec and/or the provider\'s own optionalOutputShape spec', $task->getErrorMessage());
}
- public function testProviderShouldBeRegisteredAndRun() {
+ public function testProviderShouldBeRegisteredAndRun(): void {
$this->registrationContext->expects($this->any())->method('getTaskProcessingProviders')->willReturn([
new ServiceRegistration('test', SuccessfulSyncProvider::class)
]);
@@ -630,7 +630,7 @@ class TaskProcessingTest extends \Test\TestCase {
self::assertEquals(1, $task->getProgress());
}
- public function testAsyncProviderWithFilesShouldBeRegisteredAndRunReturningRawFileData() {
+ public function testAsyncProviderWithFilesShouldBeRegisteredAndRunReturningRawFileData(): void {
$this->registrationContext->expects($this->any())->method('getTaskProcessingTaskTypes')->willReturn([
new ServiceRegistration('test', AudioToImage::class)
]);
@@ -682,7 +682,7 @@ class TaskProcessingTest extends \Test\TestCase {
self::assertEquals('World', $node->getContent());
}
- public function testAsyncProviderWithFilesShouldBeRegisteredAndRunReturningFileIds() {
+ public function testAsyncProviderWithFilesShouldBeRegisteredAndRunReturningFileIds(): void {
$this->registrationContext->expects($this->any())->method('getTaskProcessingTaskTypes')->willReturn([
new ServiceRegistration('test', AudioToImage::class)
]);
@@ -734,12 +734,12 @@ class TaskProcessingTest extends \Test\TestCase {
self::assertEquals('World', $node->getContent());
}
- public function testNonexistentTask() {
+ public function testNonexistentTask(): void {
$this->expectException(\OCP\TaskProcessing\Exception\NotFoundException::class);
$this->manager->getTask(2147483646);
}
- public function testOldTasksShouldBeCleanedUp() {
+ public function testOldTasksShouldBeCleanedUp(): void {
$currentTime = new \DateTime('now');
$timeFactory = $this->createMock(ITimeFactory::class);
$timeFactory->expects($this->any())->method('getDateTime')->willReturnCallback(fn () => $currentTime);
@@ -785,7 +785,7 @@ class TaskProcessingTest extends \Test\TestCase {
$this->manager->getTask($task->getId());
}
- public function testShouldTransparentlyHandleTextProcessingProviders() {
+ public function testShouldTransparentlyHandleTextProcessingProviders(): void {
$this->registrationContext->expects($this->any())->method('getTextProcessingProviders')->willReturn([
new ServiceRegistration('test', SuccessfulTextProcessingSummaryProvider::class)
]);
@@ -816,7 +816,7 @@ class TaskProcessingTest extends \Test\TestCase {
self::assertTrue($this->providers[SuccessfulTextProcessingSummaryProvider::class]->ran);
}
- public function testShouldTransparentlyHandleFailingTextProcessingProviders() {
+ public function testShouldTransparentlyHandleFailingTextProcessingProviders(): void {
$this->registrationContext->expects($this->any())->method('getTextProcessingProviders')->willReturn([
new ServiceRegistration('test', FailingTextProcessingSummaryProvider::class)
]);
@@ -846,7 +846,7 @@ class TaskProcessingTest extends \Test\TestCase {
self::assertTrue($this->providers[FailingTextProcessingSummaryProvider::class]->ran);
}
- public function testShouldTransparentlyHandleText2ImageProviders() {
+ public function testShouldTransparentlyHandleText2ImageProviders(): void {
$this->registrationContext->expects($this->any())->method('getTextToImageProviders')->willReturn([
new ServiceRegistration('test', SuccessfulTextToImageProvider::class)
]);
@@ -882,7 +882,7 @@ class TaskProcessingTest extends \Test\TestCase {
self::assertEquals('test', $node->getContent());
}
- public function testShouldTransparentlyHandleFailingText2ImageProviders() {
+ public function testShouldTransparentlyHandleFailingText2ImageProviders(): void {
$this->registrationContext->expects($this->any())->method('getTextToImageProviders')->willReturn([
new ServiceRegistration('test', FailingTextToImageProvider::class)
]);
diff --git a/tests/lib/TempManagerTest.php b/tests/lib/TempManagerTest.php
index c66690b9656..a981338f42a 100644
--- a/tests/lib/TempManagerTest.php
+++ b/tests/lib/TempManagerTest.php
@@ -55,7 +55,7 @@ class TempManagerTest extends \Test\TestCase {
return $manager;
}
- public function testGetFile() {
+ public function testGetFile(): void {
$manager = $this->getManager();
$file = $manager->getTemporaryFile('txt');
$this->assertStringEndsWith('.txt', $file);
@@ -66,7 +66,7 @@ class TempManagerTest extends \Test\TestCase {
$this->assertEquals('bar', file_get_contents($file));
}
- public function testGetFolder() {
+ public function testGetFolder(): void {
$manager = $this->getManager();
$folder = $manager->getTemporaryFolder();
$this->assertStringEndsWith('/', $folder);
@@ -77,7 +77,7 @@ class TempManagerTest extends \Test\TestCase {
$this->assertEquals('bar', file_get_contents($folder . 'foo.txt'));
}
- public function testCleanFiles() {
+ public function testCleanFiles(): void {
$manager = $this->getManager();
$file1 = $manager->getTemporaryFile('txt');
$file2 = $manager->getTemporaryFile('txt');
@@ -90,7 +90,7 @@ class TempManagerTest extends \Test\TestCase {
$this->assertFalse(file_exists($file2));
}
- public function testCleanFolder() {
+ public function testCleanFolder(): void {
$manager = $this->getManager();
$folder1 = $manager->getTemporaryFolder();
$folder2 = $manager->getTemporaryFolder();
@@ -109,7 +109,7 @@ class TempManagerTest extends \Test\TestCase {
$this->assertFalse(file_exists($folder1 . 'bar.txt'));
}
- public function testCleanOld() {
+ public function testCleanOld(): void {
$manager = $this->getManager();
$oldFile = $manager->getTemporaryFile('txt');
$newFile = $manager->getTemporaryFile('txt');
@@ -130,7 +130,7 @@ class TempManagerTest extends \Test\TestCase {
$this->assertTrue(file_exists($newFile));
}
- public function testLogCantCreateFile() {
+ public function testLogCantCreateFile(): void {
$this->markTestSkipped('TODO: Disable because fails on drone');
$logger = $this->createMock(LoggerInterface::class);
@@ -142,7 +142,7 @@ class TempManagerTest extends \Test\TestCase {
$this->assertFalse($manager->getTemporaryFile('txt'));
}
- public function testLogCantCreateFolder() {
+ public function testLogCantCreateFolder(): void {
$this->markTestSkipped('TODO: Disable because fails on drone');
$logger = $this->createMock(LoggerInterface::class);
@@ -154,7 +154,7 @@ class TempManagerTest extends \Test\TestCase {
$this->assertFalse($manager->getTemporaryFolder());
}
- public function testBuildFileNameWithPostfix() {
+ public function testBuildFileNameWithPostfix(): void {
$logger = $this->createMock(LoggerInterface::class);
$tmpManager = self::invokePrivate(
$this->getManager($logger),
@@ -165,7 +165,7 @@ class TempManagerTest extends \Test\TestCase {
$this->assertEquals('/tmp/myTemporaryFile-.postfix', $tmpManager);
}
- public function testBuildFileNameWithoutPostfix() {
+ public function testBuildFileNameWithoutPostfix(): void {
$logger = $this->createMock(LoggerInterface::class);
$tmpManager = self::invokePrivate(
$this->getManager($logger),
@@ -176,7 +176,7 @@ class TempManagerTest extends \Test\TestCase {
$this->assertEquals('/tmp/myTemporaryFile', $tmpManager);
}
- public function testBuildFileNameWithSuffixPathTraversal() {
+ public function testBuildFileNameWithSuffixPathTraversal(): void {
$logger = $this->createMock(LoggerInterface::class);
$tmpManager = self::invokePrivate(
$this->getManager($logger),
@@ -188,7 +188,7 @@ class TempManagerTest extends \Test\TestCase {
$this->assertStringEndsWith('.Traversal..FileName', $tmpManager);
}
- public function testGetTempBaseDirFromConfig() {
+ public function testGetTempBaseDirFromConfig(): void {
$dir = $this->getManager()->getTemporaryFolder();
$config = $this->createMock(IConfig::class);
diff --git a/tests/lib/Template/CSSResourceLocatorTest.php b/tests/lib/Template/CSSResourceLocatorTest.php
index 64c31d9c94c..ed02358a8c9 100644
--- a/tests/lib/Template/CSSResourceLocatorTest.php
+++ b/tests/lib/Template/CSSResourceLocatorTest.php
@@ -77,7 +77,7 @@ class CSSResourceLocatorTest extends \Test\TestCase {
return sha1(uniqid(mt_rand(), true));
}
- public function testFindWithAppPathSymlink() {
+ public function testFindWithAppPathSymlink(): void {
// First create new apps path, and a symlink to it
$apps_dirname = $this->randomString();
$new_apps_path = sys_get_temp_dir() . '/' . $apps_dirname;
diff --git a/tests/lib/Template/JSCombinerTest.php b/tests/lib/Template/JSCombinerTest.php
index d9de4b088d1..63a52f34047 100644
--- a/tests/lib/Template/JSCombinerTest.php
+++ b/tests/lib/Template/JSCombinerTest.php
@@ -55,7 +55,7 @@ class JSCombinerTest extends \Test\TestCase {
);
}
- public function testProcessDebugMode() {
+ public function testProcessDebugMode(): void {
$this->config
->expects($this->once())
->method('getValue')
@@ -66,7 +66,7 @@ class JSCombinerTest extends \Test\TestCase {
$this->assertFalse($actual);
}
- public function testProcessNotInstalled() {
+ public function testProcessNotInstalled(): void {
$this->config
->expects($this->exactly(2))
->method('getValue')
@@ -83,7 +83,7 @@ class JSCombinerTest extends \Test\TestCase {
$this->assertFalse($actual);
}
- public function testProcessUncachedFileNoAppDataFolder() {
+ public function testProcessUncachedFileNoAppDataFolder(): void {
$this->config
->expects($this->exactly(2))
->method('getValue')
@@ -123,7 +123,7 @@ class JSCombinerTest extends \Test\TestCase {
$this->assertTrue($actual);
}
- public function testProcessUncachedFile() {
+ public function testProcessUncachedFile(): void {
$this->config
->expects($this->exactly(2))
->method('getValue')
@@ -161,7 +161,7 @@ class JSCombinerTest extends \Test\TestCase {
$this->assertTrue($actual);
}
- public function testProcessCachedFile() {
+ public function testProcessCachedFile(): void {
$this->config
->expects($this->exactly(2))
->method('getValue')
@@ -202,7 +202,7 @@ class JSCombinerTest extends \Test\TestCase {
$this->assertTrue($actual);
}
- public function testProcessCachedFileMemcache() {
+ public function testProcessCachedFileMemcache(): void {
$this->config
->expects($this->exactly(2))
->method('getValue')
@@ -243,7 +243,7 @@ class JSCombinerTest extends \Test\TestCase {
$this->assertTrue($actual);
}
- public function testIsCachedNoDepsFile() {
+ public function testIsCachedNoDepsFile(): void {
$fileName = 'combine.json';
$folder = $this->createMock(ISimpleFolder::class);
$file = $this->createMock(ISimpleFile::class);
@@ -263,7 +263,7 @@ class JSCombinerTest extends \Test\TestCase {
$this->assertFalse($actual);
}
- public function testIsCachedWithNotExistingFile() {
+ public function testIsCachedWithNotExistingFile(): void {
$fileName = 'combine.json';
$folder = $this->createMock(ISimpleFolder::class);
$folder->method('fileExists')
@@ -281,7 +281,7 @@ class JSCombinerTest extends \Test\TestCase {
$this->assertFalse($actual);
}
- public function testIsCachedWithOlderMtime() {
+ public function testIsCachedWithOlderMtime(): void {
$fileName = 'combine.json';
$folder = $this->createMock(ISimpleFolder::class);
$folder->method('fileExists')
@@ -299,7 +299,7 @@ class JSCombinerTest extends \Test\TestCase {
$this->assertFalse($actual);
}
- public function testIsCachedWithoutContent() {
+ public function testIsCachedWithoutContent(): void {
$fileName = 'combine.json';
$folder = $this->createMock(ISimpleFolder::class);
$folder->method('fileExists')
@@ -319,7 +319,7 @@ class JSCombinerTest extends \Test\TestCase {
$this->assertFalse($actual);
}
- public function testCacheNoFile() {
+ public function testCacheNoFile(): void {
$fileName = 'combine.js';
$folder = $this->createMock(ISimpleFolder::class);
@@ -352,7 +352,7 @@ class JSCombinerTest extends \Test\TestCase {
$this->assertTrue($actual);
}
- public function testCache() {
+ public function testCache(): void {
$fileName = 'combine.js';
$folder = $this->createMock(ISimpleFolder::class);
@@ -383,7 +383,7 @@ class JSCombinerTest extends \Test\TestCase {
$this->assertTrue($actual);
}
- public function testCacheNotPermittedException() {
+ public function testCacheNotPermittedException(): void {
$fileName = 'combine.js';
$folder = $this->createMock(ISimpleFolder::class);
@@ -429,7 +429,7 @@ var b = \'world\';
$this->assertFalse($actual);
}
- public function testCacheSuccess() {
+ public function testCacheSuccess(): void {
$fileName = 'combine.js';
$folder = $this->createMock(ISimpleFolder::class);
@@ -497,7 +497,7 @@ var b = \'world\';
* @param $result
* @dataProvider dataGetCachedSCSS
*/
- public function testGetCachedSCSS($appName, $fileName, $result) {
+ public function testGetCachedSCSS($appName, $fileName, $result): void {
$this->urlGenerator->expects($this->once())
->method('linkToRoute')
->with('core.Js.getJs', [
@@ -510,7 +510,7 @@ var b = \'world\';
$this->assertEquals(substr($result, 1), $actual);
}
- public function testGetContent() {
+ public function testGetContent(): void {
// Create temporary file with some content
$tmpFile = \OC::$server->getTempManager()->getTemporaryFile('JSCombinerTest');
$pathInfo = pathinfo($tmpFile);
@@ -525,7 +525,7 @@ var b = \'world\';
$this->assertEquals($expected, $this->jsCombiner->getContent($pathInfo['dirname'], $pathInfo['basename']));
}
- public function testGetContentInvalidJson() {
+ public function testGetContentInvalidJson(): void {
// Create temporary file with some content
$tmpFile = \OC::$server->getTempManager()->getTemporaryFile('JSCombinerTest');
$pathInfo = pathinfo($tmpFile);
@@ -534,7 +534,7 @@ var b = \'world\';
$this->assertEquals($expected, $this->jsCombiner->getContent($pathInfo['dirname'], $pathInfo['basename']));
}
- public function testResetCache() {
+ public function testResetCache(): void {
$file = $this->createMock(ISimpleFile::class);
$file->expects($this->once())
->method('delete');
diff --git a/tests/lib/Template/JSResourceLocatorTest.php b/tests/lib/Template/JSResourceLocatorTest.php
index c6f62990d9a..bb2c2bec6c4 100644
--- a/tests/lib/Template/JSResourceLocatorTest.php
+++ b/tests/lib/Template/JSResourceLocatorTest.php
@@ -72,7 +72,7 @@ class JSResourceLocatorTest extends \Test\TestCase {
return sha1(uniqid(mt_rand(), true));
}
- public function testFindWithAppPathSymlink() {
+ public function testFindWithAppPathSymlink(): void {
$appName = 'test-js-app';
// First create new apps path, and a symlink to it
@@ -123,7 +123,7 @@ class JSResourceLocatorTest extends \Test\TestCase {
$this->rrmdir($new_apps_path);
}
- public function testNotExistingTranslationHandledSilent() {
+ public function testNotExistingTranslationHandledSilent(): void {
$this->appManager->expects($this->once())
->method('getAppPath')
->with('core')
@@ -144,7 +144,7 @@ class JSResourceLocatorTest extends \Test\TestCase {
$this->assertCount(0, $resources);
}
- public function testFindModuleJSWithFallback() {
+ public function testFindModuleJSWithFallback(): void {
// First create new apps path, and a symlink to it
$apps_dirname = $this->randomString();
$new_apps_path = sys_get_temp_dir() . '/' . $apps_dirname;
diff --git a/tests/lib/Template/ResourceLocatorTest.php b/tests/lib/Template/ResourceLocatorTest.php
index 6841efc185f..d308968d861 100644
--- a/tests/lib/Template/ResourceLocatorTest.php
+++ b/tests/lib/Template/ResourceLocatorTest.php
@@ -37,7 +37,7 @@ class ResourceLocatorTest extends \Test\TestCase {
'', true, true, true, []);
}
- public function testFind() {
+ public function testFind(): void {
$locator = $this->getResourceLocator('theme');
$locator->expects($this->once())
->method('doFind')
@@ -49,7 +49,7 @@ class ResourceLocatorTest extends \Test\TestCase {
$locator->find(['foo']);
}
- public function testFindNotFound() {
+ public function testFindNotFound(): void {
$systemConfig = $this->createMock(SystemConfig::class);
$systemConfig->method('getValue')
->with('theme', '')
@@ -72,7 +72,7 @@ class ResourceLocatorTest extends \Test\TestCase {
$locator->find(['foo']);
}
- public function testAppendIfExist() {
+ public function testAppendIfExist(): void {
$locator = $this->getResourceLocator('theme');
/** @var \OC\Template\ResourceLocator $locator */
$method = new \ReflectionMethod($locator, 'appendIfExist');
diff --git a/tests/lib/TemplateFunctionsTest.php b/tests/lib/TemplateFunctionsTest.php
index 754551a415b..a693a39c580 100644
--- a/tests/lib/TemplateFunctionsTest.php
+++ b/tests/lib/TemplateFunctionsTest.php
@@ -14,50 +14,50 @@ class TemplateFunctionsTest extends \Test\TestCase {
require_once \OC::$SERVERROOT . '/lib/private/legacy/OC_Template.php';
}
- public function testPJavaScript() {
+ public function testPJavaScript(): void {
$this->expectOutputString('&lt;img onload=&quot;alert(1)&quot; /&gt;');
p('<img onload="alert(1)" />');
}
- public function testPJavaScriptWithScriptTags() {
+ public function testPJavaScriptWithScriptTags(): void {
$this->expectOutputString('&lt;script&gt;alert(&#039;Hacked!&#039;);&lt;/script&gt;');
p("<script>alert('Hacked!');</script>");
}
- public function testPNormalString() {
+ public function testPNormalString(): void {
$string = 'This is a good string without HTML.';
$this->expectOutputString($string);
p($string);
}
- public function testPrintUnescaped() {
+ public function testPrintUnescaped(): void {
$htmlString = "<script>alert('xss');</script>";
$this->expectOutputString($htmlString);
print_unescaped($htmlString);
}
- public function testPrintUnescapedNormalString() {
+ public function testPrintUnescapedNormalString(): void {
$string = 'This is a good string!';
$this->expectOutputString($string);
print_unescaped($string);
}
- public function testEmitScriptTagWithContent() {
+ public function testEmitScriptTagWithContent(): void {
$this->expectOutputRegex('/<script nonce="[^"]+">\nalert\(\)\n<\/script>\n?/');
emit_script_tag('', 'alert()');
}
- public function testEmitScriptTagWithSource() {
+ public function testEmitScriptTagWithSource(): void {
$this->expectOutputRegex('/<script nonce=".*" defer src="some.js"><\/script>/');
emit_script_tag('some.js');
}
- public function testEmitScriptTagWithModuleSource() {
+ public function testEmitScriptTagWithModuleSource(): void {
$this->expectOutputRegex('/<script nonce=".*" defer src="some.mjs" type="module"><\/script>/');
emit_script_tag('some.mjs', '', 'module');
}
- public function testEmitScriptLoadingTags() {
+ public function testEmitScriptLoadingTags(): void {
// Test mjs js and inline content
$pattern = '/src="some\.mjs"[^>]+type="module"[^>]*>.+\n'; // some.mjs with type = module
$pattern .= '<script[^>]+src="other\.js"[^>]*>.+\n'; // other.js as plain javascript
@@ -71,7 +71,7 @@ class TemplateFunctionsTest extends \Test\TestCase {
]);
}
- public function testEmitScriptLoadingTagsWithVersion() {
+ public function testEmitScriptLoadingTagsWithVersion(): void {
// Test mjs js and inline content
$pattern = '/src="some\.mjs\?v=ab123cd"[^>]+type="module"[^>]*>.+\n'; // some.mjs with type = module
$pattern .= '<script[^>]+src="other\.js\?v=12abc34"[^>]*>.+\n'; // other.js as plain javascript
@@ -86,7 +86,7 @@ class TemplateFunctionsTest extends \Test\TestCase {
// ---------------------------------------------------------------------------
// Test relative_modified_date with dates only
// ---------------------------------------------------------------------------
- public function testRelativeDateToday() {
+ public function testRelativeDateToday(): void {
$currentTime = 1380703592;
$elementTime = $currentTime;
$result = (string)relative_modified_date($elementTime, $currentTime, true);
@@ -100,7 +100,7 @@ class TemplateFunctionsTest extends \Test\TestCase {
$this->assertEquals('today', $result);
}
- public function testRelativeDateYesterday() {
+ public function testRelativeDateYesterday(): void {
$currentTime = 1380703592;
$elementTime = $currentTime - 24 * 3600;
$result = (string)relative_modified_date($elementTime, $currentTime, true);
@@ -114,7 +114,7 @@ class TemplateFunctionsTest extends \Test\TestCase {
$this->assertEquals('yesterday', $result);
}
- public function testRelativeDate2DaysAgo() {
+ public function testRelativeDate2DaysAgo(): void {
$currentTime = 1380703592;
$elementTime = $currentTime - 48 * 3600;
$result = (string)relative_modified_date($elementTime, $currentTime, true);
@@ -128,7 +128,7 @@ class TemplateFunctionsTest extends \Test\TestCase {
$this->assertEquals('2 days ago', $result);
}
- public function testRelativeDateLastMonth() {
+ public function testRelativeDateLastMonth(): void {
$currentTime = 1380703592;
$elementTime = $currentTime - 86400 * 31;
$result = (string)relative_modified_date($elementTime, $currentTime, true);
@@ -141,7 +141,7 @@ class TemplateFunctionsTest extends \Test\TestCase {
$this->assertEquals('last month', $result);
}
- public function testRelativeDateMonthsAgo() {
+ public function testRelativeDateMonthsAgo(): void {
$currentTime = 1380703592;
$elementTime = $currentTime - 86400 * 65;
$result = (string)relative_modified_date($elementTime, $currentTime, true);
@@ -154,7 +154,7 @@ class TemplateFunctionsTest extends \Test\TestCase {
$this->assertEquals('4 months ago', $result);
}
- public function testRelativeDateLastYear() {
+ public function testRelativeDateLastYear(): void {
$currentTime = 1380703592;
$elementTime = $currentTime - 86400 * 365;
$result = (string)relative_modified_date($elementTime, $currentTime, true);
@@ -167,7 +167,7 @@ class TemplateFunctionsTest extends \Test\TestCase {
$this->assertEquals('last year', $result);
}
- public function testRelativeDateYearsAgo() {
+ public function testRelativeDateYearsAgo(): void {
$currentTime = 1380703592;
$elementTime = $currentTime - 86400 * 365.25 * 2;
$result = (string)relative_modified_date($elementTime, $currentTime, true);
@@ -184,7 +184,7 @@ class TemplateFunctionsTest extends \Test\TestCase {
// Test relative_modified_date with timestamps only (date + time value)
// ---------------------------------------------------------------------------
- public function testRelativeTimeSecondsAgo() {
+ public function testRelativeTimeSecondsAgo(): void {
$currentTime = 1380703592;
$elementTime = $currentTime - 5;
$result = (string)relative_modified_date($elementTime, $currentTime, false);
@@ -192,7 +192,7 @@ class TemplateFunctionsTest extends \Test\TestCase {
$this->assertEquals('seconds ago', $result);
}
- public function testRelativeTimeMinutesAgo() {
+ public function testRelativeTimeMinutesAgo(): void {
$currentTime = 1380703592;
$elementTime = $currentTime - 190;
$result = (string)relative_modified_date($elementTime, $currentTime, false);
@@ -200,7 +200,7 @@ class TemplateFunctionsTest extends \Test\TestCase {
$this->assertEquals('3 minutes ago', $result);
}
- public function testRelativeTimeHoursAgo() {
+ public function testRelativeTimeHoursAgo(): void {
$currentTime = 1380703592;
$elementTime = $currentTime - 7500;
$result = (string)relative_modified_date($elementTime, $currentTime, false);
@@ -208,7 +208,7 @@ class TemplateFunctionsTest extends \Test\TestCase {
$this->assertEquals('2 hours ago', $result);
}
- public function testRelativeTime2DaysAgo() {
+ public function testRelativeTime2DaysAgo(): void {
$currentTime = 1380703592;
$elementTime = $currentTime - 48 * 3600;
$result = (string)relative_modified_date($elementTime, $currentTime, false);
@@ -222,7 +222,7 @@ class TemplateFunctionsTest extends \Test\TestCase {
$this->assertEquals('2 days ago', $result);
}
- public function testRelativeTimeLastMonth() {
+ public function testRelativeTimeLastMonth(): void {
$currentTime = 1380703592;
$elementTime = $currentTime - 86400 * 31;
$result = (string)relative_modified_date($elementTime, $currentTime, false);
@@ -235,7 +235,7 @@ class TemplateFunctionsTest extends \Test\TestCase {
$this->assertEquals('last month', $result);
}
- public function testRelativeTimeMonthsAgo() {
+ public function testRelativeTimeMonthsAgo(): void {
$currentTime = 1380703592;
$elementTime = $currentTime - 86400 * 65;
$result = (string)relative_modified_date($elementTime, $currentTime, false);
@@ -248,7 +248,7 @@ class TemplateFunctionsTest extends \Test\TestCase {
$this->assertEquals('4 months ago', $result);
}
- public function testRelativeTimeLastYear() {
+ public function testRelativeTimeLastYear(): void {
$currentTime = 1380703592;
$elementTime = $currentTime - 86400 * 365;
$result = (string)relative_modified_date($elementTime, $currentTime, false);
@@ -261,7 +261,7 @@ class TemplateFunctionsTest extends \Test\TestCase {
$this->assertEquals('last year', $result);
}
- public function testRelativeTimeYearsAgo() {
+ public function testRelativeTimeYearsAgo(): void {
$currentTime = 1380703592;
$elementTime = $currentTime - 86400 * 365.25 * 2;
$result = (string)relative_modified_date($elementTime, $currentTime, false);
diff --git a/tests/lib/TextProcessing/TextProcessingTest.php b/tests/lib/TextProcessing/TextProcessingTest.php
index 9c759e52458..84c5492a4a2 100644
--- a/tests/lib/TextProcessing/TextProcessingTest.php
+++ b/tests/lib/TextProcessing/TextProcessingTest.php
@@ -184,7 +184,7 @@ class TextProcessingTest extends \Test\TestCase {
);
}
- public function testShouldNotHaveAnyProviders() {
+ public function testShouldNotHaveAnyProviders(): void {
$this->registrationContext->expects($this->any())->method('getTextProcessingProviders')->willReturn([]);
$this->assertCount(0, $this->manager->getAvailableTaskTypes());
$this->assertFalse($this->manager->hasProviders());
@@ -192,7 +192,7 @@ class TextProcessingTest extends \Test\TestCase {
$this->manager->runTask(new \OCP\TextProcessing\Task(FreePromptTaskType::class, 'Hello', 'test', null));
}
- public function testProviderShouldBeRegisteredAndRun() {
+ public function testProviderShouldBeRegisteredAndRun(): void {
$this->registrationContext->expects($this->any())->method('getTextProcessingProviders')->willReturn([
new ServiceRegistration('test', SuccessfulSummaryProvider::class)
]);
@@ -205,7 +205,7 @@ class TextProcessingTest extends \Test\TestCase {
$this->manager->runTask(new Task(FreePromptTaskType::class, 'Hello', 'test', null));
}
- public function testProviderShouldBeRegisteredAndScheduled() {
+ public function testProviderShouldBeRegisteredAndScheduled(): void {
// register provider
$this->registrationContext->expects($this->any())->method('getTextProcessingProviders')->willReturn([
new ServiceRegistration('test', SuccessfulSummaryProvider::class)
@@ -256,7 +256,7 @@ class TextProcessingTest extends \Test\TestCase {
$this->assertEquals(Task::STATUS_SUCCESSFUL, $task3->getStatus());
}
- public function testMultipleProvidersShouldBeRegisteredAndRunCorrectly() {
+ public function testMultipleProvidersShouldBeRegisteredAndRunCorrectly(): void {
$this->registrationContext->expects($this->any())->method('getTextProcessingProviders')->willReturn([
new ServiceRegistration('test', SuccessfulSummaryProvider::class),
new ServiceRegistration('test', FreePromptProvider::class),
@@ -275,12 +275,12 @@ class TextProcessingTest extends \Test\TestCase {
$this->manager->runTask(new Task(TopicsTaskType::class, 'Hello', 'test', null));
}
- public function testNonexistentTask() {
+ public function testNonexistentTask(): void {
$this->expectException(NotFoundException::class);
$this->manager->getTask(2147483646);
}
- public function testTaskFailure() {
+ public function testTaskFailure(): void {
// register provider
$this->registrationContext->expects($this->any())->method('getTextProcessingProviders')->willReturn([
new ServiceRegistration('test', FailingSummaryProvider::class),
@@ -331,7 +331,7 @@ class TextProcessingTest extends \Test\TestCase {
$this->assertEquals(Task::STATUS_FAILED, $task3->getStatus());
}
- public function testOldTasksShouldBeCleanedUp() {
+ public function testOldTasksShouldBeCleanedUp(): void {
$this->registrationContext->expects($this->any())->method('getTextProcessingProviders')->willReturn([
new ServiceRegistration('test', SuccessfulSummaryProvider::class)
]);
diff --git a/tests/lib/Updater/ChangesCheckTest.php b/tests/lib/Updater/ChangesCheckTest.php
index 26da6579d33..81eaa95d1fe 100644
--- a/tests/lib/Updater/ChangesCheckTest.php
+++ b/tests/lib/Updater/ChangesCheckTest.php
@@ -54,7 +54,7 @@ class ChangesCheckTest extends TestCase {
/**
* @dataProvider statusCodeProvider
*/
- public function testEvaluateResponse(int $statusCode, int $expected) {
+ public function testEvaluateResponse(int $statusCode, int $expected): void {
$response = $this->createMock(IResponse::class);
$response->expects($this->atLeastOnce())
->method('getStatusCode')
@@ -69,7 +69,7 @@ class ChangesCheckTest extends TestCase {
$this->assertSame($expected, $evaluation);
}
- public function testCacheResultInsert() {
+ public function testCacheResultInsert(): void {
$version = '13.0.4';
$entry = $this->createMock(Changes::class);
$entry->expects($this->exactly(2))
@@ -85,7 +85,7 @@ class ChangesCheckTest extends TestCase {
$this->invokePrivate($this->checker, 'cacheResult', [$entry, $version]);
}
- public function testCacheResultUpdate() {
+ public function testCacheResultUpdate(): void {
$version = '13.0.4';
$entry = $this->createMock(Changes::class);
$entry->expects($this->once())
@@ -272,7 +272,7 @@ class ChangesCheckTest extends TestCase {
/**
* @dataProvider changesXMLProvider
*/
- public function testExtractData(string $body, array $expected) {
+ public function testExtractData(string $body, array $expected): void {
$actual = $this->invokePrivate($this->checker, 'extractData', [$body]);
$this->assertSame($expected, $actual);
}
@@ -287,7 +287,7 @@ class ChangesCheckTest extends TestCase {
/**
* @dataProvider etagProvider
*/
- public function testQueryChangesServer(string $etag) {
+ public function testQueryChangesServer(string $etag): void {
$uri = 'https://changes.nextcloud.server/?13.0.5';
$entry = $this->createMock(Changes::class);
$entry->expects($this->any())
@@ -324,7 +324,7 @@ class ChangesCheckTest extends TestCase {
/**
* @dataProvider versionProvider
*/
- public function testNormalizeVersion(string $input, string $expected) {
+ public function testNormalizeVersion(string $input, string $expected): void {
$normalized = $this->checker->normalizeVersion($input);
$this->assertSame($expected, $normalized);
}
@@ -344,7 +344,7 @@ class ChangesCheckTest extends TestCase {
* @dataProvider changeDataProvider
*
*/
- public function testGetChangesForVersion(string $inputVersion, string $normalizedVersion, bool $isFound) {
+ public function testGetChangesForVersion(string $inputVersion, string $normalizedVersion, bool $isFound): void {
$mocker = $this->mapper->expects($this->once())
->method('getChanges')
->with($normalizedVersion);
@@ -368,7 +368,7 @@ class ChangesCheckTest extends TestCase {
$this->assertTrue(isset($data['changelogURL']));
}
- public function testGetChangesForVersionEmptyData() {
+ public function testGetChangesForVersionEmptyData(): void {
$entry = $this->createMock(Changes::class);
$entry->expects($this->once())
->method('__call')
diff --git a/tests/lib/Updater/ReleaseMetadataTest.php b/tests/lib/Updater/ReleaseMetadataTest.php
index 66b31f4da69..87961613ce6 100644
--- a/tests/lib/Updater/ReleaseMetadataTest.php
+++ b/tests/lib/Updater/ReleaseMetadataTest.php
@@ -22,7 +22,7 @@ class ReleaseMetadataTest extends \Test\TestCase {
->getMock();
}
- public function testDownloadMetadata() {
+ public function testDownloadMetadata(): void {
$client = $this->createMock(IClient::class);
$response = $this->createMock(IResponse::class);
$this->clientService->expects($this->once())
@@ -48,7 +48,7 @@ class ReleaseMetadataTest extends \Test\TestCase {
* @param string $version
* @param string $url
*/
- public function testGetMetadata(string $version, string $url) {
+ public function testGetMetadata(string $version, string $url): void {
$client = $this->createMock(IClient::class);
$response = $this->createMock(IResponse::class);
$this->clientService->expects($this->once())
diff --git a/tests/lib/Updater/VersionCheckTest.php b/tests/lib/Updater/VersionCheckTest.php
index b8a32680fb0..b33829a2155 100644
--- a/tests/lib/Updater/VersionCheckTest.php
+++ b/tests/lib/Updater/VersionCheckTest.php
@@ -66,7 +66,7 @@ class VersionCheckTest extends \Test\TestCase {
return $baseUrl . '?version='.implode('x', Util::getVersion()).'xinstalledatx' . time() . 'x'.\OC_Util::getChannel().'xxx'.PHP_MAJOR_VERSION.'x'.PHP_MINOR_VERSION.'x'.PHP_RELEASE_VERSION.'x0x0';
}
- public function testCheckInCache() {
+ public function testCheckInCache(): void {
$expectedResult = [
'version' => '8.0.4.2',
'versionstring' => 'ownCloud 8.0.4',
@@ -94,7 +94,7 @@ class VersionCheckTest extends \Test\TestCase {
$this->assertSame($expectedResult, $this->updater->check());
}
- public function testCheckWithoutUpdateUrl() {
+ public function testCheckWithoutUpdateUrl(): void {
$expectedResult = [
'version' => '8.0.4.2',
'versionstring' => 'ownCloud 8.0.4',
@@ -155,7 +155,7 @@ class VersionCheckTest extends \Test\TestCase {
$this->assertSame($expectedResult, $this->updater->check());
}
- public function testCheckWithInvalidXml() {
+ public function testCheckWithInvalidXml(): void {
$this->config
->expects($this->once())
->method('getSystemValueBool')
@@ -198,7 +198,7 @@ class VersionCheckTest extends \Test\TestCase {
$this->assertSame([], $this->updater->check());
}
- public function testCheckWithEmptyValidXmlResponse() {
+ public function testCheckWithEmptyValidXmlResponse(): void {
$expectedResult = [
'version' => '',
'versionstring' => '',
@@ -258,7 +258,7 @@ class VersionCheckTest extends \Test\TestCase {
$this->assertSame($expectedResult, $this->updater->check());
}
- public function testCheckWithEmptyInvalidXmlResponse() {
+ public function testCheckWithEmptyInvalidXmlResponse(): void {
$expectedResult = [];
$this->config
@@ -303,7 +303,7 @@ class VersionCheckTest extends \Test\TestCase {
$this->assertSame($expectedResult, $this->updater->check());
}
- public function testCheckWithMissingAttributeXmlResponse() {
+ public function testCheckWithMissingAttributeXmlResponse(): void {
$expectedResult = [
'version' => '',
'versionstring' => '',
@@ -363,7 +363,7 @@ class VersionCheckTest extends \Test\TestCase {
$this->assertSame($expectedResult, $this->updater->check());
}
- public function testNoInternet() {
+ public function testNoInternet(): void {
$this->config
->expects($this->once())
->method('getSystemValueBool')
diff --git a/tests/lib/UpdaterTest.php b/tests/lib/UpdaterTest.php
index 118cb1b6d41..da48e581fbc 100644
--- a/tests/lib/UpdaterTest.php
+++ b/tests/lib/UpdaterTest.php
@@ -95,7 +95,7 @@ class UpdaterTest extends TestCase {
* @param bool $debug
* @param string $vendor
*/
- public function testIsUpgradePossible($oldVersion, $newVersion, $allowedVersions, $result, $debug = false, $vendor = 'nextcloud') {
+ public function testIsUpgradePossible($oldVersion, $newVersion, $allowedVersions, $result, $debug = false, $vendor = 'nextcloud'): void {
$this->config->expects($this->any())
->method('getSystemValueBool')
->with('debug', false)
diff --git a/tests/lib/UrlGeneratorTest.php b/tests/lib/UrlGeneratorTest.php
index d54698b7a0a..0f5e2984ce9 100644
--- a/tests/lib/UrlGeneratorTest.php
+++ b/tests/lib/UrlGeneratorTest.php
@@ -71,7 +71,7 @@ class UrlGeneratorTest extends \Test\TestCase {
* test linkTo URL construction
* @dataProvider provideDocRootAppUrlParts
*/
- public function testLinkToDocRoot($app, $file, $args, $expectedResult) {
+ public function testLinkToDocRoot($app, $file, $args, $expectedResult): void {
\OC::$WEBROOT = '';
$result = $this->urlGenerator->linkTo($app, $file, $args);
$this->assertEquals($expectedResult, $result);
@@ -82,7 +82,7 @@ class UrlGeneratorTest extends \Test\TestCase {
* test linkTo URL construction in sub directory
* @dataProvider provideSubDirAppUrlParts
*/
- public function testLinkToSubDir($app, $file, $args, $expectedResult) {
+ public function testLinkToSubDir($app, $file, $args, $expectedResult): void {
\OC::$WEBROOT = '/nextcloud';
$result = $this->urlGenerator->linkTo($app, $file, $args);
$this->assertEquals($expectedResult, $result);
@@ -91,7 +91,7 @@ class UrlGeneratorTest extends \Test\TestCase {
/**
* @dataProvider provideRoutes
*/
- public function testLinkToRouteAbsolute($route, $expected) {
+ public function testLinkToRouteAbsolute($route, $expected): void {
$this->mockBaseUrl();
\OC::$WEBROOT = '/nextcloud';
$this->router->expects($this->once())
@@ -135,7 +135,7 @@ class UrlGeneratorTest extends \Test\TestCase {
* test absolute URL construction
* @dataProvider provideDocRootURLs
*/
- public function testGetAbsoluteURLDocRoot($url, $expectedResult) {
+ public function testGetAbsoluteURLDocRoot($url, $expectedResult): void {
$this->mockBaseUrl();
\OC::$WEBROOT = '';
$result = $this->urlGenerator->getAbsoluteURL($url);
@@ -147,7 +147,7 @@ class UrlGeneratorTest extends \Test\TestCase {
* test absolute URL construction
* @dataProvider provideSubDirURLs
*/
- public function testGetAbsoluteURLSubDir($url, $expectedResult) {
+ public function testGetAbsoluteURLSubDir($url, $expectedResult): void {
$this->mockBaseUrl();
\OC::$WEBROOT = '/nextcloud';
$result = $this->urlGenerator->getAbsoluteURL($url);
@@ -174,7 +174,7 @@ class UrlGeneratorTest extends \Test\TestCase {
];
}
- public function testGetBaseUrl() {
+ public function testGetBaseUrl(): void {
$this->mockBaseUrl();
\OC::$WEBROOT = '/nextcloud';
$actual = $this->urlGenerator->getBaseUrl();
@@ -182,7 +182,7 @@ class UrlGeneratorTest extends \Test\TestCase {
$this->assertEquals($expected, $actual);
}
- public function testGetWebroot() {
+ public function testGetWebroot(): void {
\OC::$WEBROOT = '/nextcloud';
$actual = $this->urlGenerator->getWebroot();
$this->assertEquals(\OC::$WEBROOT, $actual);
@@ -234,14 +234,14 @@ class UrlGeneratorTest extends \Test\TestCase {
->willReturn($ignoreFrontControllerConfig);
}
- public function testLinkToDefaultPageUrlWithRedirectUrlWithoutFrontController() {
+ public function testLinkToDefaultPageUrlWithRedirectUrlWithoutFrontController(): void {
$this->mockBaseUrl();
$_REQUEST['redirect_url'] = 'myRedirectUrl.com';
$this->assertSame('http://localhost' . \OC::$WEBROOT . '/myRedirectUrl.com', $this->urlGenerator->linkToDefaultPageUrl());
}
- public function testLinkToDefaultPageUrlWithRedirectUrlRedirectBypassWithoutFrontController() {
+ public function testLinkToDefaultPageUrlWithRedirectUrlRedirectBypassWithoutFrontController(): void {
$this->mockBaseUrl();
$this->mockLinkToDefaultPageUrl();
putenv('front_controller_active=false');
@@ -250,7 +250,7 @@ class UrlGeneratorTest extends \Test\TestCase {
$this->assertSame('http://localhost' . \OC::$WEBROOT . '/index.php/apps/dashboard/', $this->urlGenerator->linkToDefaultPageUrl());
}
- public function testLinkToDefaultPageUrlWithRedirectUrlRedirectBypassWithFrontController() {
+ public function testLinkToDefaultPageUrlWithRedirectUrlRedirectBypassWithFrontController(): void {
$this->mockBaseUrl();
$this->mockLinkToDefaultPageUrl();
putenv('front_controller_active=true');
@@ -259,7 +259,7 @@ class UrlGeneratorTest extends \Test\TestCase {
$this->assertSame('http://localhost' . \OC::$WEBROOT . '/apps/dashboard/', $this->urlGenerator->linkToDefaultPageUrl());
}
- public function testLinkToDefaultPageUrlWithRedirectUrlWithIgnoreFrontController() {
+ public function testLinkToDefaultPageUrlWithRedirectUrlWithIgnoreFrontController(): void {
$this->mockBaseUrl();
$this->mockLinkToDefaultPageUrl(true);
putenv('front_controller_active=false');
diff --git a/tests/lib/User/Backend.php b/tests/lib/User/Backend.php
index 7efba2eaeb6..ed17776476a 100644
--- a/tests/lib/User/Backend.php
+++ b/tests/lib/User/Backend.php
@@ -32,7 +32,7 @@ abstract class Backend extends \Test\TestCase {
return $this->getUniqueID('test_');
}
- public function testAddRemove() {
+ public function testAddRemove(): void {
//get the number of groups we start with, in case there are exising groups
$startCount = count($this->backend->getUsers());
@@ -56,7 +56,7 @@ abstract class Backend extends \Test\TestCase {
$this->assertFalse((array_search($name2, $this->backend->getUsers()) !== false));
}
- public function testLogin() {
+ public function testLogin(): void {
$name1 = $this->getUser();
$name2 = $this->getUser();
@@ -84,7 +84,7 @@ abstract class Backend extends \Test\TestCase {
$this->assertFalse($this->backend->checkPassword($name2, 'newpass1'));
}
- public function testSearch() {
+ public function testSearch(): void {
$name1 = 'foobarbaz';
$name2 = 'bazbarfoo';
$name3 = 'notme';
diff --git a/tests/lib/User/DatabaseTest.php b/tests/lib/User/DatabaseTest.php
index 16b223aaaba..bd74ab333fb 100644
--- a/tests/lib/User/DatabaseTest.php
+++ b/tests/lib/User/DatabaseTest.php
@@ -49,7 +49,7 @@ class DatabaseTest extends Backend {
parent::tearDown();
}
- public function testVerifyPasswordEvent() {
+ public function testVerifyPasswordEvent(): void {
$user = $this->getUser();
$this->backend->createUser($user, 'pass1');
@@ -67,7 +67,7 @@ class DatabaseTest extends Backend {
}
- public function testVerifyPasswordEventFail() {
+ public function testVerifyPasswordEventFail(): void {
$this->expectException(\OCP\HintException::class);
$this->expectExceptionMessage('password change failed');
@@ -88,14 +88,14 @@ class DatabaseTest extends Backend {
$this->assertSame($user, $this->backend->checkPassword($user, 'newpass'));
}
- public function testCreateUserInvalidatesCache() {
+ public function testCreateUserInvalidatesCache(): void {
$user1 = $this->getUniqueID('test_');
$this->assertFalse($this->backend->userExists($user1));
$this->backend->createUser($user1, 'pw');
$this->assertTrue($this->backend->userExists($user1));
}
- public function testDeleteUserInvalidatesCache() {
+ public function testDeleteUserInvalidatesCache(): void {
$user1 = $this->getUniqueID('test_');
$this->backend->createUser($user1, 'pw');
$this->assertTrue($this->backend->userExists($user1));
@@ -105,7 +105,7 @@ class DatabaseTest extends Backend {
$this->assertTrue($this->backend->userExists($user1));
}
- public function testSearch() {
+ public function testSearch(): void {
parent::testSearch();
$user1 = $this->getUser();
diff --git a/tests/lib/User/ManagerTest.php b/tests/lib/User/ManagerTest.php
index c516b1de945..302cba4ea2b 100644
--- a/tests/lib/User/ManagerTest.php
+++ b/tests/lib/User/ManagerTest.php
@@ -47,7 +47,7 @@ class ManagerTest extends TestCase {
->willReturn($this->cache);
}
- public function testGetBackends() {
+ public function testGetBackends(): void {
$userDummyBackend = $this->createMock(\Test\Util\User\Dummy::class);
$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher);
$manager->registerBackend($userDummyBackend);
@@ -58,7 +58,7 @@ class ManagerTest extends TestCase {
}
- public function testUserExistsSingleBackendExists() {
+ public function testUserExistsSingleBackendExists(): void {
/**
* @var \Test\Util\User\Dummy | \PHPUnit\Framework\MockObject\MockObject $backend
*/
@@ -74,7 +74,7 @@ class ManagerTest extends TestCase {
$this->assertTrue($manager->userExists('foo'));
}
- public function testUserExistsSingleBackendNotExists() {
+ public function testUserExistsSingleBackendNotExists(): void {
/**
* @var \Test\Util\User\Dummy | \PHPUnit\Framework\MockObject\MockObject $backend
*/
@@ -90,13 +90,13 @@ class ManagerTest extends TestCase {
$this->assertFalse($manager->userExists('foo'));
}
- public function testUserExistsNoBackends() {
+ public function testUserExistsNoBackends(): void {
$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher);
$this->assertFalse($manager->userExists('foo'));
}
- public function testUserExistsTwoBackendsSecondExists() {
+ public function testUserExistsTwoBackendsSecondExists(): void {
/**
* @var \Test\Util\User\Dummy | \PHPUnit\Framework\MockObject\MockObject $backend1
*/
@@ -122,7 +122,7 @@ class ManagerTest extends TestCase {
$this->assertTrue($manager->userExists('foo'));
}
- public function testUserExistsTwoBackendsFirstExists() {
+ public function testUserExistsTwoBackendsFirstExists(): void {
/**
* @var \Test\Util\User\Dummy | \PHPUnit\Framework\MockObject\MockObject $backend1
*/
@@ -146,7 +146,7 @@ class ManagerTest extends TestCase {
$this->assertTrue($manager->userExists('foo'));
}
- public function testCheckPassword() {
+ public function testCheckPassword(): void {
/**
* @var \OC\User\Backend | \PHPUnit\Framework\MockObject\MockObject $backend
*/
@@ -173,7 +173,7 @@ class ManagerTest extends TestCase {
$this->assertTrue($user instanceof \OC\User\User);
}
- public function testCheckPasswordNotSupported() {
+ public function testCheckPasswordNotSupported(): void {
/**
* @var \OC\User\Backend | \PHPUnit\Framework\MockObject\MockObject $backend
*/
@@ -191,7 +191,7 @@ class ManagerTest extends TestCase {
$this->assertFalse($manager->checkPassword('foo', 'bar'));
}
- public function testGetOneBackendExists() {
+ public function testGetOneBackendExists(): void {
/**
* @var \Test\Util\User\Dummy | \PHPUnit\Framework\MockObject\MockObject $backend
*/
@@ -209,7 +209,7 @@ class ManagerTest extends TestCase {
$this->assertEquals('foo', $manager->get('foo')->getUID());
}
- public function testGetOneBackendNotExists() {
+ public function testGetOneBackendNotExists(): void {
/**
* @var \Test\Util\User\Dummy | \PHPUnit\Framework\MockObject\MockObject $backend
*/
@@ -225,7 +225,7 @@ class ManagerTest extends TestCase {
$this->assertEquals(null, $manager->get('foo'));
}
- public function testGetOneBackendDoNotTranslateLoginNames() {
+ public function testGetOneBackendDoNotTranslateLoginNames(): void {
/**
* @var \Test\Util\User\Dummy | \PHPUnit\Framework\MockObject\MockObject $backend
*/
@@ -243,7 +243,7 @@ class ManagerTest extends TestCase {
$this->assertEquals('bLeNdEr', $manager->get('bLeNdEr')->getUID());
}
- public function testSearchOneBackend() {
+ public function testSearchOneBackend(): void {
/**
* @var \Test\Util\User\Dummy | \PHPUnit\Framework\MockObject\MockObject $backend
*/
@@ -266,7 +266,7 @@ class ManagerTest extends TestCase {
$this->assertEquals('foo', array_shift($result)->getUID());
}
- public function testSearchTwoBackendLimitOffset() {
+ public function testSearchTwoBackendLimitOffset(): void {
/**
* @var \Test\Util\User\Dummy | \PHPUnit\Framework\MockObject\MockObject $backend1
*/
@@ -334,7 +334,7 @@ class ManagerTest extends TestCase {
/**
* @dataProvider dataCreateUserInvalid
*/
- public function testCreateUserInvalid($uid, $password, $exception) {
+ 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);
$backend->expects($this->once())
@@ -350,7 +350,7 @@ class ManagerTest extends TestCase {
$manager->createUser($uid, $password);
}
- public function testCreateUserSingleBackendNotExists() {
+ public function testCreateUserSingleBackendNotExists(): void {
/**
* @var \Test\Util\User\Dummy | \PHPUnit\Framework\MockObject\MockObject $backend
*/
@@ -378,7 +378,7 @@ class ManagerTest extends TestCase {
}
- public function testCreateUserSingleBackendExists() {
+ public function testCreateUserSingleBackendExists(): void {
$this->expectException(\Exception::class);
/**
@@ -403,7 +403,7 @@ class ManagerTest extends TestCase {
$manager->createUser('foo', 'bar');
}
- public function testCreateUserSingleBackendNotSupported() {
+ public function testCreateUserSingleBackendNotSupported(): void {
/**
* @var \Test\Util\User\Dummy | \PHPUnit\Framework\MockObject\MockObject $backend
*/
@@ -424,14 +424,14 @@ class ManagerTest extends TestCase {
$this->assertFalse($manager->createUser('foo', 'bar'));
}
- public function testCreateUserNoBackends() {
+ public function testCreateUserNoBackends(): void {
$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher);
$this->assertFalse($manager->createUser('foo', 'bar'));
}
- public function testCreateUserFromBackendWithBackendError() {
+ public function testCreateUserFromBackendWithBackendError(): void {
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Could not create account');
@@ -450,7 +450,7 @@ class ManagerTest extends TestCase {
}
- public function testCreateUserTwoBackendExists() {
+ public function testCreateUserTwoBackendExists(): void {
$this->expectException(\Exception::class);
/**
@@ -492,7 +492,7 @@ class ManagerTest extends TestCase {
$manager->createUser('foo', 'bar');
}
- public function testCountUsersNoBackend() {
+ public function testCountUsersNoBackend(): void {
$manager = new \OC\User\Manager($this->config, $this->cacheFactory, $this->eventDispatcher);
$result = $manager->countUsers();
@@ -500,7 +500,7 @@ class ManagerTest extends TestCase {
$this->assertTrue(empty($result));
}
- public function testCountUsersOneBackend() {
+ public function testCountUsersOneBackend(): void {
/**
* @var \Test\Util\User\Dummy | \PHPUnit\Framework\MockObject\MockObject $backend
*/
@@ -529,7 +529,7 @@ class ManagerTest extends TestCase {
$this->assertEquals(7, $users);
}
- public function testCountUsersTwoBackends() {
+ public function testCountUsersTwoBackends(): void {
/**
* @var \Test\Util\User\Dummy | \PHPUnit\Framework\MockObject\MockObject $backend
*/
@@ -574,7 +574,7 @@ class ManagerTest extends TestCase {
$this->assertEquals(7 + 16, $users);
}
- public function testCountUsersOnlyDisabled() {
+ public function testCountUsersOnlyDisabled(): void {
$manager = \OC::$server->getUserManager();
// count other users in the db before adding our own
$countBefore = $manager->countDisabledUsers();
@@ -599,7 +599,7 @@ class ManagerTest extends TestCase {
$user4->delete();
}
- public function testCountUsersOnlySeen() {
+ public function testCountUsersOnlySeen(): void {
$manager = \OC::$server->getUserManager();
// count other users in the db before adding our own
$countBefore = $manager->countSeenUsers();
@@ -625,7 +625,7 @@ class ManagerTest extends TestCase {
$user4->delete();
}
- public function testCallForSeenUsers() {
+ public function testCallForSeenUsers(): void {
$manager = \OC::$server->getUserManager();
// count other users in the db before adding our own
$count = 0;
@@ -659,7 +659,7 @@ class ManagerTest extends TestCase {
$user4->delete();
}
- public function testDeleteUser() {
+ public function testDeleteUser(): void {
$config = $this->getMockBuilder(AllConfig::class)
->disableOriginalConstructor()
->getMock();
@@ -682,7 +682,7 @@ class ManagerTest extends TestCase {
$this->assertFalse($manager->userExists('foo'));
}
- public function testGetByEmail() {
+ public function testGetByEmail(): void {
$config = $this->getMockBuilder(AllConfig::class)
->disableOriginalConstructor()
->getMock();
diff --git a/tests/lib/User/SessionTest.php b/tests/lib/User/SessionTest.php
index 84af7f552a7..fad5d11565c 100644
--- a/tests/lib/User/SessionTest.php
+++ b/tests/lib/User/SessionTest.php
@@ -113,7 +113,7 @@ class SessionTest extends \Test\TestCase {
/**
* @dataProvider isLoggedInData
*/
- public function testIsLoggedIn($isLoggedIn) {
+ public function testIsLoggedIn($isLoggedIn): void {
$session = $this->createMock(Memory::class);
$manager = $this->createMock(Manager::class);
@@ -131,7 +131,7 @@ class SessionTest extends \Test\TestCase {
$this->assertEquals($isLoggedIn, $userSession->isLoggedIn());
}
- public function testSetUser() {
+ public function testSetUser(): void {
$session = $this->createMock(Memory::class);
$session->expects($this->once())
->method('set')
@@ -150,7 +150,7 @@ class SessionTest extends \Test\TestCase {
$userSession->setUser($user);
}
- public function testLoginValidPasswordEnabled() {
+ public function testLoginValidPasswordEnabled(): void {
$session = $this->createMock(Memory::class);
$session->expects($this->once())
->method('regenerateId');
@@ -225,7 +225,7 @@ class SessionTest extends \Test\TestCase {
}
- public function testLoginValidPasswordDisabled() {
+ public function testLoginValidPasswordDisabled(): void {
$this->expectException(LoginException::class);
$session = $this->createMock(Memory::class);
@@ -269,7 +269,7 @@ class SessionTest extends \Test\TestCase {
$userSession->login('foo', 'bar');
}
- public function testLoginInvalidPassword() {
+ public function testLoginInvalidPassword(): void {
$session = $this->createMock(Memory::class);
$managerMethods = get_class_methods(Manager::class);
//keep following methods intact in order to ensure hooks are working
@@ -386,7 +386,7 @@ class SessionTest extends \Test\TestCase {
$userSession->login('foo', 'app-password');
}
- public function testLoginNonExisting() {
+ public function testLoginNonExisting(): void {
$session = $this->createMock(Memory::class);
$manager = $this->createMock(Manager::class);
$userSession = new Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher);
@@ -408,7 +408,7 @@ class SessionTest extends \Test\TestCase {
$userSession->login('foo', 'bar');
}
- public function testLogClientInNoTokenPasswordWith2fa() {
+ public function testLogClientInNoTokenPasswordWith2fa(): void {
$this->expectException(PasswordLoginForbiddenException::class);
$manager = $this->createMock(Manager::class);
@@ -446,7 +446,7 @@ class SessionTest extends \Test\TestCase {
$userSession->logClientIn('john', 'doe', $request, $this->throttler);
}
- public function testLogClientInUnexist() {
+ public function testLogClientInUnexist(): void {
$manager = $this->createMock(Manager::class);
$session = $this->createMock(ISession::class);
$request = $this->createMock(IRequest::class);
@@ -472,7 +472,7 @@ class SessionTest extends \Test\TestCase {
$this->assertFalse($userSession->logClientIn('unexist', 'doe', $request, $this->throttler));
}
- public function testLogClientInWithTokenPassword() {
+ public function testLogClientInWithTokenPassword(): void {
$manager = $this->createMock(Manager::class);
$session = $this->createMock(ISession::class);
$request = $this->createMock(IRequest::class);
@@ -512,7 +512,7 @@ class SessionTest extends \Test\TestCase {
}
- public function testLogClientInNoTokenPasswordNo2fa() {
+ public function testLogClientInNoTokenPasswordNo2fa(): void {
$this->expectException(PasswordLoginForbiddenException::class);
$manager = $this->createMock(Manager::class);
@@ -606,7 +606,7 @@ class SessionTest extends \Test\TestCase {
self::assertFalse($loginResult);
}
- public function testRememberLoginValidToken() {
+ public function testRememberLoginValidToken(): void {
$session = $this->createMock(Memory::class);
$managerMethods = get_class_methods(Manager::class);
//keep following methods intact in order to ensure hooks are working
@@ -695,7 +695,7 @@ class SessionTest extends \Test\TestCase {
$this->assertTrue($granted);
}
- public function testRememberLoginInvalidSessionToken() {
+ public function testRememberLoginInvalidSessionToken(): void {
$session = $this->createMock(Memory::class);
$managerMethods = get_class_methods(Manager::class);
//keep following methods intact in order to ensure hooks are working
@@ -759,7 +759,7 @@ class SessionTest extends \Test\TestCase {
$this->assertFalse($granted);
}
- public function testRememberLoginInvalidToken() {
+ public function testRememberLoginInvalidToken(): void {
$session = $this->createMock(Memory::class);
$managerMethods = get_class_methods(Manager::class);
//keep following methods intact in order to ensure hooks are working
@@ -811,7 +811,7 @@ class SessionTest extends \Test\TestCase {
$this->assertFalse($granted);
}
- public function testRememberLoginInvalidUser() {
+ public function testRememberLoginInvalidUser(): void {
$session = $this->createMock(Memory::class);
$managerMethods = get_class_methods(Manager::class);
//keep following methods intact in order to ensure hooks are working
@@ -856,7 +856,7 @@ class SessionTest extends \Test\TestCase {
$this->assertFalse($granted);
}
- public function testActiveUserAfterSetSession() {
+ public function testActiveUserAfterSetSession(): void {
$users = [
'foo' => new User('foo', null, $this->createMock(IEventDispatcher::class)),
'bar' => new User('bar', null, $this->createMock(IEventDispatcher::class))
@@ -891,7 +891,7 @@ class SessionTest extends \Test\TestCase {
$this->assertEquals($users['bar'], $userSession->getUser());
}
- public function testCreateSessionToken() {
+ public function testCreateSessionToken(): void {
$manager = $this->createMock(Manager::class);
$session = $this->createMock(ISession::class);
$user = $this->createMock(IUser::class);
@@ -932,7 +932,7 @@ class SessionTest extends \Test\TestCase {
$this->assertTrue($userSession->createSessionToken($request, $uid, $loginName, $password));
}
- public function testCreateRememberedSessionToken() {
+ public function testCreateRememberedSessionToken(): void {
$manager = $this->createMock(Manager::class);
$session = $this->createMock(ISession::class);
$user = $this->createMock(IUser::class);
@@ -973,7 +973,7 @@ class SessionTest extends \Test\TestCase {
$this->assertTrue($userSession->createSessionToken($request, $uid, $loginName, $password, true));
}
- public function testCreateSessionTokenWithTokenPassword() {
+ public function testCreateSessionTokenWithTokenPassword(): void {
$manager = $this->getMockBuilder(Manager::class)
->disableOriginalConstructor()
->getMock();
@@ -1022,7 +1022,7 @@ class SessionTest extends \Test\TestCase {
$this->assertTrue($userSession->createSessionToken($request, $uid, $loginName, $password));
}
- public function testCreateSessionTokenWithNonExistentUser() {
+ public function testCreateSessionTokenWithNonExistentUser(): void {
$manager = $this->getMockBuilder(Manager::class)
->disableOriginalConstructor()
->getMock();
@@ -1042,7 +1042,7 @@ class SessionTest extends \Test\TestCase {
$this->assertFalse($userSession->createSessionToken($request, $uid, $loginName, $password));
}
- public function testCreateRememberMeToken() {
+ public function testCreateRememberMeToken(): void {
$user = $this->createMock(IUser::class);
$user
->expects($this->exactly(2))
@@ -1065,7 +1065,7 @@ class SessionTest extends \Test\TestCase {
$this->userSession->createRememberMeToken($user);
}
- public function testTryBasicAuthLoginValid() {
+ public function testTryBasicAuthLoginValid(): void {
$request = $this->createMock(Request::class);
$request->method('__get')
->willReturn([
@@ -1135,7 +1135,7 @@ class SessionTest extends \Test\TestCase {
$this->assertSame(1000, $lastPasswordConfirmSet);
}
- public function testTryBasicAuthLoginNoLogin() {
+ public function testTryBasicAuthLoginNoLogin(): void {
$request = $this->createMock(Request::class);
$request->method('__get')
->willReturn([]);
@@ -1170,7 +1170,7 @@ class SessionTest extends \Test\TestCase {
$this->assertFalse($userSession->tryBasicAuthLogin($request, $this->throttler));
}
- public function testUpdateTokens() {
+ public function testUpdateTokens(): void {
$this->tokenProvider->expects($this->once())
->method('updatePasswords')
->with('uid', 'pass');
@@ -1178,7 +1178,7 @@ class SessionTest extends \Test\TestCase {
$this->userSession->updateTokens('uid', 'pass');
}
- public function testLogClientInThrottlerUsername() {
+ public function testLogClientInThrottlerUsername(): void {
$manager = $this->createMock(Manager::class);
$session = $this->createMock(ISession::class);
$request = $this->createMock(IRequest::class);
@@ -1224,7 +1224,7 @@ class SessionTest extends \Test\TestCase {
$this->assertFalse($userSession->logClientIn('john', 'I-AM-AN-PASSWORD', $request, $this->throttler));
}
- public function testLogClientInThrottlerEmail() {
+ public function testLogClientInThrottlerEmail(): void {
$manager = $this->createMock(Manager::class);
$session = $this->createMock(ISession::class);
$request = $this->createMock(IRequest::class);
diff --git a/tests/lib/User/UserTest.php b/tests/lib/User/UserTest.php
index 06ea98e72cd..55230b83667 100644
--- a/tests/lib/User/UserTest.php
+++ b/tests/lib/User/UserTest.php
@@ -41,7 +41,7 @@ class UserTest extends TestCase {
$this->dispatcher = Server::get(IEventDispatcher::class);
}
- public function testDisplayName() {
+ public function testDisplayName(): void {
/**
* @var \OC\User\Backend | MockObject $backend
*/
@@ -63,7 +63,7 @@ class UserTest extends TestCase {
/**
* if the display name contain whitespaces only, we expect the uid as result
*/
- public function testDisplayNameEmpty() {
+ public function testDisplayNameEmpty(): void {
/**
* @var \OC\User\Backend | MockObject $backend
*/
@@ -82,7 +82,7 @@ class UserTest extends TestCase {
$this->assertEquals('foo', $user->getDisplayName());
}
- public function testDisplayNameNotSupported() {
+ public function testDisplayNameNotSupported(): void {
/**
* @var \OC\User\Backend | MockObject $backend
*/
@@ -99,7 +99,7 @@ class UserTest extends TestCase {
$this->assertEquals('foo', $user->getDisplayName());
}
- public function testSetPassword() {
+ public function testSetPassword(): void {
/**
* @var Backend | MockObject $backend
*/
@@ -122,7 +122,7 @@ class UserTest extends TestCase {
$this->assertTrue($user->setPassword('bar', ''));
}
- public function testSetPasswordNotSupported() {
+ public function testSetPasswordNotSupported(): void {
/**
* @var Backend | MockObject $backend
*/
@@ -138,7 +138,7 @@ class UserTest extends TestCase {
$this->assertFalse($user->setPassword('bar', ''));
}
- public function testChangeAvatarSupportedYes() {
+ public function testChangeAvatarSupportedYes(): void {
/**
* @var Backend | MockObject $backend
*/
@@ -162,7 +162,7 @@ class UserTest extends TestCase {
$this->assertTrue($user->canChangeAvatar());
}
- public function testChangeAvatarSupportedNo() {
+ public function testChangeAvatarSupportedNo(): void {
/**
* @var Backend | MockObject $backend
*/
@@ -186,7 +186,7 @@ class UserTest extends TestCase {
$this->assertFalse($user->canChangeAvatar());
}
- public function testChangeAvatarNotSupported() {
+ public function testChangeAvatarNotSupported(): void {
/**
* @var Backend | MockObject $backend
*/
@@ -202,7 +202,7 @@ class UserTest extends TestCase {
$this->assertTrue($user->canChangeAvatar());
}
- public function testDelete() {
+ public function testDelete(): void {
/**
* @var Backend | MockObject $backend
*/
@@ -215,7 +215,7 @@ class UserTest extends TestCase {
$this->assertTrue($user->delete());
}
- public function testDeleteWithDifferentHome() {
+ public function testDeleteWithDifferentHome(): void {
/** @var ObjectHomeMountProvider $homeProvider */
$homeProvider = \OC::$server->get(ObjectHomeMountProvider::class);
$user = $this->createMock(IUser::class);
@@ -256,7 +256,7 @@ class UserTest extends TestCase {
$this->assertTrue($user->delete());
}
- public function testGetHome() {
+ public function testGetHome(): void {
/**
* @var Backend | MockObject $backend
*/
@@ -280,14 +280,14 @@ class UserTest extends TestCase {
$this->assertEquals('/home/foo', $user->getHome());
}
- public function testGetBackendClassName() {
+ 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);
$this->assertEquals('Database', $user->getBackendClassName());
}
- public function testGetHomeNotSupported() {
+ public function testGetHomeNotSupported(): void {
/**
* @var Backend | MockObject $backend
*/
@@ -314,7 +314,7 @@ class UserTest extends TestCase {
$this->assertEquals('arbitrary/path/foo', $user->getHome());
}
- public function testCanChangePassword() {
+ public function testCanChangePassword(): void {
/**
* @var Backend | MockObject $backend
*/
@@ -334,7 +334,7 @@ class UserTest extends TestCase {
$this->assertTrue($user->canChangePassword());
}
- public function testCanChangePasswordNotSupported() {
+ public function testCanChangePasswordNotSupported(): void {
/**
* @var Backend | MockObject $backend
*/
@@ -348,7 +348,7 @@ class UserTest extends TestCase {
$this->assertFalse($user->canChangePassword());
}
- public function testCanChangeDisplayName() {
+ public function testCanChangeDisplayName(): void {
/**
* @var Backend | MockObject $backend
*/
@@ -373,7 +373,7 @@ class UserTest extends TestCase {
$this->assertTrue($user->canChangeDisplayName());
}
- public function testCanChangeDisplayNameNotSupported() {
+ public function testCanChangeDisplayNameNotSupported(): void {
/**
* @var Backend | MockObject $backend
*/
@@ -387,7 +387,7 @@ class UserTest extends TestCase {
$this->assertFalse($user->canChangeDisplayName());
}
- public function testSetDisplayNameSupported() {
+ public function testSetDisplayNameSupported(): void {
/**
* @var Backend | MockObject $backend
*/
@@ -416,7 +416,7 @@ class UserTest extends TestCase {
/**
* don't allow display names containing whitespaces only
*/
- public function testSetDisplayNameEmpty() {
+ public function testSetDisplayNameEmpty(): void {
/**
* @var Backend | MockObject $backend
*/
@@ -437,7 +437,7 @@ class UserTest extends TestCase {
$this->assertEquals('foo', $user->getDisplayName());
}
- public function testSetDisplayNameNotSupported() {
+ public function testSetDisplayNameNotSupported(): void {
/**
* @var Backend | MockObject $backend
*/
@@ -455,7 +455,7 @@ class UserTest extends TestCase {
$this->assertEquals('foo', $user->getDisplayName());
}
- public function testSetPasswordHooks() {
+ public function testSetPasswordHooks(): void {
$hooksCalled = 0;
$test = $this;
@@ -508,7 +508,7 @@ class UserTest extends TestCase {
* @param bool $result
* @param int $expectedHooks
*/
- public function testDeleteHooks($result, $expectedHooks) {
+ public function testDeleteHooks($result, $expectedHooks): void {
$hooksCalled = 0;
$test = $this;
@@ -618,7 +618,7 @@ class UserTest extends TestCase {
$this->assertEquals($cloudId, $user->getCloudId());
}
- public function testSetEMailAddressEmpty() {
+ public function testSetEMailAddressEmpty(): void {
/**
* @var Backend | MockObject $backend
*/
@@ -654,7 +654,7 @@ class UserTest extends TestCase {
$user->setEMailAddress('');
}
- public function testSetEMailAddress() {
+ public function testSetEMailAddress(): void {
/**
* @var UserInterface | MockObject $backend
*/
@@ -691,7 +691,7 @@ class UserTest extends TestCase {
$user->setEMailAddress('foo@bar.com');
}
- public function testSetEMailAddressNoChange() {
+ public function testSetEMailAddressNoChange(): void {
/**
* @var UserInterface | MockObject $backend
*/
@@ -717,7 +717,7 @@ class UserTest extends TestCase {
$user->setEMailAddress('foo@bar.com');
}
- public function testSetQuota() {
+ public function testSetQuota(): void {
/**
* @var UserInterface | MockObject $backend
*/
@@ -754,7 +754,7 @@ class UserTest extends TestCase {
$user->setQuota('23 TB');
}
- public function testGetDefaultUnlimitedQuota() {
+ public function testGetDefaultUnlimitedQuota(): void {
/**
* @var UserInterface | MockObject $backend
*/
@@ -785,7 +785,7 @@ class UserTest extends TestCase {
$this->assertEquals('none', $quota);
}
- public function testGetDefaultUnlimitedQuotaForbidden() {
+ public function testGetDefaultUnlimitedQuotaForbidden(): void {
/**
* @var UserInterface | MockObject $backend
*/
@@ -819,7 +819,7 @@ class UserTest extends TestCase {
$this->assertEquals('1 GB', $quota);
}
- public function testSetQuotaAddressNoChange() {
+ public function testSetQuotaAddressNoChange(): void {
/**
* @var UserInterface | MockObject $backend
*/
@@ -841,7 +841,7 @@ class UserTest extends TestCase {
$user->setQuota('23 TB');
}
- public function testGetLastLogin() {
+ public function testGetLastLogin(): void {
/**
* @var Backend | MockObject $backend
*/
@@ -861,7 +861,7 @@ class UserTest extends TestCase {
$this->assertSame(42, $user->getLastLogin());
}
- public function testSetEnabled() {
+ public function testSetEnabled(): void {
/**
* @var Backend | MockObject $backend
*/
@@ -881,7 +881,7 @@ class UserTest extends TestCase {
$user->setEnabled(true);
}
- public function testSetDisabled() {
+ public function testSetDisabled(): void {
/**
* @var Backend | MockObject $backend
*/
@@ -921,7 +921,7 @@ class UserTest extends TestCase {
$user->setEnabled(false);
}
- public function testSetDisabledAlreadyDisabled() {
+ public function testSetDisabledAlreadyDisabled(): void {
/**
* @var Backend | MockObject $backend
*/
@@ -951,7 +951,7 @@ class UserTest extends TestCase {
$user->setEnabled(false);
}
- public function testGetEMailAddress() {
+ public function testGetEMailAddress(): void {
/**
* @var Backend | MockObject $backend
*/
diff --git a/tests/lib/UtilCheckServerTest.php b/tests/lib/UtilCheckServerTest.php
index a182db89475..b8351a5d2b3 100644
--- a/tests/lib/UtilCheckServerTest.php
+++ b/tests/lib/UtilCheckServerTest.php
@@ -52,7 +52,7 @@ class UtilCheckServerTest extends \Test\TestCase {
/**
* Test that checkServer() returns no errors in the regular case.
*/
- public function testCheckServer() {
+ public function testCheckServer(): void {
$result = \OC_Util::checkServer($this->getConfig([
'installed' => true
]));
@@ -64,7 +64,7 @@ class UtilCheckServerTest extends \Test\TestCase {
* when the server is not installed yet (else the setup cannot
* be run...)
*/
- public function testCheckServerSkipDataDirValidityOnSetup() {
+ public function testCheckServerSkipDataDirValidityOnSetup(): void {
// simulate old version that didn't have it
unlink($this->datadir . '/.ncdata');
@@ -81,7 +81,7 @@ class UtilCheckServerTest extends \Test\TestCase {
* when an upgrade is required (else the upgrade cannot be
* performed...)
*/
- public function testCheckServerSkipDataDirValidityOnUpgrade() {
+ public function testCheckServerSkipDataDirValidityOnUpgrade(): void {
// simulate old version that didn't have it
unlink($this->datadir . '/.ncdata');
@@ -107,7 +107,7 @@ class UtilCheckServerTest extends \Test\TestCase {
* Test that checkDataDirectoryValidity returns no error
* when ".ncdata" is present.
*/
- public function testCheckDataDirValidity() {
+ public function testCheckDataDirValidity(): void {
$result = \OC_Util::checkDataDirectoryValidity($this->datadir);
$this->assertEmpty($result);
}
@@ -116,7 +116,7 @@ class UtilCheckServerTest extends \Test\TestCase {
* Test that checkDataDirectoryValidity and checkServer
* both return an error when ".ncdata" is missing.
*/
- public function testCheckDataDirValidityWhenFileMissing() {
+ public function testCheckDataDirValidityWhenFileMissing(): void {
unlink($this->datadir . '/.ncdata');
$result = \OC_Util::checkDataDirectoryValidity($this->datadir);
$this->assertEquals(1, count($result));
@@ -131,7 +131,7 @@ class UtilCheckServerTest extends \Test\TestCase {
/**
* Tests that no error is given when the datadir is writable
*/
- public function testDataDirWritable() {
+ public function testDataDirWritable(): void {
$result = \OC_Util::checkServer($this->getConfig([
'installed' => true,
'version' => implode('.', \OCP\Util::getVersion())
@@ -142,7 +142,7 @@ class UtilCheckServerTest extends \Test\TestCase {
/**
* Tests an error is given when the datadir is not writable
*/
- public function testDataDirNotWritable() {
+ public function testDataDirNotWritable(): void {
$this->markTestSkipped('TODO: Disable because fails on drone');
chmod($this->datadir, 0300);
@@ -156,7 +156,7 @@ class UtilCheckServerTest extends \Test\TestCase {
/**
* Tests no error is given when the datadir is not writable during setup
*/
- public function testDataDirNotWritableSetup() {
+ public function testDataDirNotWritableSetup(): void {
chmod($this->datadir, 0300);
$result = \OC_Util::checkServer($this->getConfig([
'installed' => false,
diff --git a/tests/lib/UtilTest.php b/tests/lib/UtilTest.php
index 68c56675425..064b73d0b7e 100644
--- a/tests/lib/UtilTest.php
+++ b/tests/lib/UtilTest.php
@@ -16,7 +16,7 @@ use OC_Util;
* @group DB
*/
class UtilTest extends \Test\TestCase {
- public function testGetVersion() {
+ public function testGetVersion(): void {
$version = \OCP\Util::getVersion();
$this->assertTrue(is_array($version));
foreach ($version as $num) {
@@ -24,17 +24,17 @@ class UtilTest extends \Test\TestCase {
}
}
- public function testGetVersionString() {
+ public function testGetVersionString(): void {
$version = \OC_Util::getVersionString();
$this->assertTrue(is_string($version));
}
- public function testGetEditionString() {
+ public function testGetEditionString(): void {
$edition = \OC_Util::getEditionString();
$this->assertTrue(is_string($edition));
}
- public function testSanitizeHTML() {
+ public function testSanitizeHTML(): void {
$badArray = [
'While it is unusual to pass an array',
'this function actually <blink>supports</blink> it.',
@@ -67,13 +67,13 @@ class UtilTest extends \Test\TestCase {
$this->assertEquals('This is a good string without HTML.', $result);
}
- public function testEncodePath() {
+ public function testEncodePath(): void {
$component = '/§#@test%&^ä/-child';
$result = OC_Util::encodePath($component);
$this->assertEquals('/%C2%A7%23%40test%25%26%5E%C3%A4/-child', $result);
}
- public function testIsNonUTF8Locale() {
+ public function testIsNonUTF8Locale(): void {
// OC_Util::isNonUTF8Locale() assumes escapeshellcmd('§') returns '' with non-UTF-8 locale.
$locale = setlocale(LC_CTYPE, 0);
setlocale(LC_CTYPE, 'C');
@@ -85,7 +85,7 @@ class UtilTest extends \Test\TestCase {
setlocale(LC_CTYPE, $locale);
}
- public function testFileInfoLoaded() {
+ public function testFileInfoLoaded(): void {
$expected = function_exists('finfo_open');
$this->assertEquals($expected, \OC_Util::fileInfoLoaded());
}
@@ -95,7 +95,7 @@ class UtilTest extends \Test\TestCase {
* but not for default strict email verification that requires a top level domain.
* So we check that with strict email verification we fallback to the default
*/
- public function testGetDefaultEmailAddressStrict() {
+ public function testGetDefaultEmailAddressStrict(): void {
$email = \OCP\Util::getDefaultEmailAddress('no-reply');
$this->assertEquals('no-reply@localhost.localdomain', $email);
}
@@ -103,7 +103,7 @@ class UtilTest extends \Test\TestCase {
/**
* If no strict email check is enabled "localhost" should validate as a valid email domain
*/
- public function testGetDefaultEmailAddress() {
+ public function testGetDefaultEmailAddress(): void {
$config = \OC::$server->getConfig();
$config->setAppValue('core', 'enforce_strict_email_check', 'no');
$email = \OCP\Util::getDefaultEmailAddress('no-reply');
@@ -111,7 +111,7 @@ class UtilTest extends \Test\TestCase {
$config->deleteAppValue('core', 'enforce_strict_email_check');
}
- public function testGetDefaultEmailAddressFromConfig() {
+ public function testGetDefaultEmailAddressFromConfig(): void {
$config = \OC::$server->getConfig();
$config->setSystemValue('mail_domain', 'example.com');
$email = \OCP\Util::getDefaultEmailAddress('no-reply');
@@ -119,7 +119,7 @@ class UtilTest extends \Test\TestCase {
$config->deleteSystemValue('mail_domain');
}
- public function testGetConfiguredEmailAddressFromConfig() {
+ public function testGetConfiguredEmailAddressFromConfig(): void {
$config = \OC::$server->getConfig();
$config->setSystemValue('mail_domain', 'example.com');
$config->setSystemValue('mail_from_address', 'owncloud');
@@ -129,7 +129,7 @@ class UtilTest extends \Test\TestCase {
$config->deleteSystemValue('mail_from_address');
}
- public function testGetInstanceIdGeneratesValidId() {
+ public function testGetInstanceIdGeneratesValidId(): void {
\OC::$server->getConfig()->deleteSystemValue('instanceid');
$instanceId = OC_Util::getInstanceId();
$this->assertStringStartsWith('oc', $instanceId);
@@ -140,7 +140,7 @@ class UtilTest extends \Test\TestCase {
/**
* Test needUpgrade() when the core version is increased
*/
- public function testNeedUpgradeCore() {
+ public function testNeedUpgradeCore(): void {
$config = \OC::$server->getConfig();
$oldConfigVersion = $config->getSystemValue('version', '0.0.0');
$oldSessionVersion = \OC::$server->getSession()->get('OC_Version');
@@ -160,7 +160,7 @@ class UtilTest extends \Test\TestCase {
$this->assertFalse(\OCP\Util::needUpgrade());
}
- public function testCheckDataDirectoryValidity() {
+ public function testCheckDataDirectoryValidity(): void {
$dataDir = \OC::$server->getTempManager()->getTemporaryFolder();
touch($dataDir . '/.ncdata');
$errors = \OC_Util::checkDataDirectoryValidity($dataDir);
@@ -194,7 +194,7 @@ class UtilTest extends \Test\TestCase {
self::invokePrivate(\OCP\Util::class, 'scriptDeps', [[]]);
}
- public function testAddScript() {
+ public function testAddScript(): void {
\OCP\Util::addScript('first', 'myFirstJSFile');
\OCP\Util::addScript('core', 'myFancyJSFile1');
\OCP\Util::addScript('files', 'myFancyJSFile2', 'core');
@@ -287,7 +287,7 @@ class UtilTest extends \Test\TestCase {
}
}
- public function testAddScriptCircularDependency() {
+ public function testAddScriptCircularDependency(): void {
\OCP\Util::addScript('circular', 'file1', 'dependency');
\OCP\Util::addScript('dependency', 'file2', 'circular');
@@ -296,7 +296,7 @@ class UtilTest extends \Test\TestCase {
$this->assertContains('dependency/js/file2', $scripts);
}
- public function testAddVendorScript() {
+ public function testAddVendorScript(): void {
\OC_Util::addVendorScript('core', 'myFancyJSFile1');
\OC_Util::addVendorScript('myApp', 'myFancyJSFile2');
\OC_Util::addVendorScript('core', 'myFancyJSFile0', true);
@@ -313,7 +313,7 @@ class UtilTest extends \Test\TestCase {
$this->assertEquals([], \OC_Util::$styles);
}
- public function testAddTranslations() {
+ public function testAddTranslations(): void {
\OC_Util::addTranslations('appId', 'de');
$this->assertEquals([
@@ -322,7 +322,7 @@ class UtilTest extends \Test\TestCase {
$this->assertEquals([], \OC_Util::$styles);
}
- public function testAddStyle() {
+ public function testAddStyle(): void {
\OC_Util::addStyle('core', 'myFancyCSSFile1');
\OC_Util::addStyle('myApp', 'myFancyCSSFile2');
\OC_Util::addStyle('core', 'myFancyCSSFile0', true);
@@ -339,7 +339,7 @@ class UtilTest extends \Test\TestCase {
], \OC_Util::$styles);
}
- public function testAddVendorStyle() {
+ public function testAddVendorStyle(): void {
\OC_Util::addVendorStyle('core', 'myFancyCSSFile1');
\OC_Util::addVendorStyle('myApp', 'myFancyCSSFile2');
\OC_Util::addVendorStyle('core', 'myFancyCSSFile0', true);
@@ -356,7 +356,7 @@ class UtilTest extends \Test\TestCase {
], \OC_Util::$styles);
}
- public function testShortenMultibyteString() {
+ public function testShortenMultibyteString(): void {
$this->assertEquals('Short nuff', \OCP\Util::shortenMultibyteString('Short nuff', 255));
$this->assertEquals('ABC', \OCP\Util::shortenMultibyteString('ABCDEF', 3));
// each of the characters is 12 bytes