From 84ad6df2e348b8d584769bdde47f77eba31747f6 Mon Sep 17 00:00:00 2001 From: David Rawson Date: Tue, 21 May 2024 12:28:27 +1200 Subject: [PATCH] Add commit produced by llama3-a6990e --- .../impl/AdClickAttributionPluginTest.kt | 12 +- .../impl/AdClickFeatureTogglesPluginTest.kt | 16 +-- .../impl/DataRemovalAdClickWorkerTest.kt | 2 +- .../adclick/impl/DuckDuckGoAdClickDataTest.kt | 8 +- .../impl/DuckDuckGoAdClickManagerTest.kt | 56 ++++---- .../impl/RealAdClickAttributionTest.kt | 22 +-- .../pixels/AdClickDailyReportingWorkerTest.kt | 2 +- .../impl/pixels/RealAdClickPixelsTest.kt | 30 ++-- .../RealAdClickAttributionRepositoryTest.kt | 6 +- .../anr/GlobalUncaughtExceptionHandlerTest.kt | 8 +- .../duckduckgo/app/anr/RedactDomainTest.kt | 2 +- .../tracking/AppTPRMFMatchingAttributeTest.kt | 8 +- .../AppTPVpnConnectivityLossListenerTest.kt | 20 +-- .../app/tracking/AppTrackerDetectorTest.kt | 34 ++--- .../UnprotectedAppsBucketPixelSenderTest.kt | 14 +- .../vpn/VpnFeaturesRegistryImplTest.kt | 24 ++-- .../apps/ManageAppsProtectionViewModelTest.kt | 54 ++++---- .../TrackingProtectionAppsRepositoryTest.kt | 30 ++-- .../ReportBreakageAppListViewModelTest.kt | 16 +-- ...eakageCategorySingleChoiceViewModelTest.kt | 20 +-- .../breakage/ReportBreakageContractTest.kt | 4 +- .../vpn/bugreport/DeviceInfoCollectorTest.kt | 4 +- .../VpnAppTrackerListInfoCollectorTest.kt | 18 +-- .../vpn/cohort/CohortPixelInterceptorTest.kt | 6 +- .../vpn/cohort/RealCohortCalculatorTest.kt | 24 ++-- .../android/vpn/cohort/RealCohortStoreTest.kt | 12 +- .../feature/AppTpRemoteFeaturesStoreTest.kt | 10 +- .../ExceptionListsSettingStoreTest.kt | 4 +- .../android/vpn/health/AppTPCPUMonitorTest.kt | 6 +- .../vpn/integration/NgVpnNetworkStackTest.kt | 34 ++--- .../VpnNetworkStackProviderTest.kt | 8 +- .../vpn/pixels/DeviceShieldPixelNamesTest.kt | 2 +- .../vpn/pixels/RealDeviceShieldPixelsTest.kt | 52 +++---- .../vpn/service/RestartReceiverTest.kt | 8 +- ...ledNotificationContentPluginPointKtTest.kt | 6 +- .../android/vpn/service/VpnRoutesTest.kt | 48 +++---- ...etPEnabledNotificationContentPluginTest.kt | 32 ++--- ...pTpEnabledNotificationContentPluginTest.kt | 26 ++-- ...ReminderNotificationContentPluginKtTest.kt | 8 +- .../service/state/RealVpnStateMonitorTest.kt | 10 +- .../vpn/ui/PrivacyReportViewModelTest.kt | 6 +- .../AppTPReminderNotificationSchedulerTest.kt | 46 +++---- ...eviceShieldDailyNotificationFactoryTest.kt | 22 +-- ...viceShieldWeeklyNotificationFactoryTest.kt | 16 +-- .../SharedPreferencesVpnStoreTest.kt | 8 +- .../AppTPCompanyTrackersViewModelTest.kt | 8 +- .../DeviceShieldActivityFeedViewModelTest.kt | 12 +- ...eviceShieldTrackerActivityViewModelTest.kt | 46 +++---- .../AppTrackerBlockingStatsRepositoryTest.kt | 12 +- .../android/vpn/store/VpnDatabaseTest.kt | 2 +- .../vpn/trackers/AppTrackerJsonParserTest.kt | 2 +- .../vpn/trackers/AppTrackerRepositoryTest.kt | 6 +- .../app/about/AboutDuckDuckGoViewModelTest.kt | 16 +-- .../AccessibilitySettingsViewModelTest.kt | 26 ++-- .../app/appearance/AppearanceViewModelTest.kt | 18 +-- .../autocomplete/api/AutoCompleteApiTest.kt | 34 ++--- .../migration/BookmarksMigrationTest.kt | 22 +-- .../bookmarks/model/SavedSitesParserTest.kt | 22 +-- .../model/SavedSitesRepositoryTest.kt | 122 ++++++++-------- .../model/SyncSavedSitesRepositoryTest.kt | 76 +++++----- .../service/SavedSitesExporterTest.kt | 10 +- .../bookmarks/ui/BookmarksViewModelTest.kt | 46 +++---- .../BookmarkFoldersViewModelTest.kt | 6 +- .../app/brokensite/BrokenSiteDataTest.kt | 26 ++-- .../brokensite/api/BrokenSiteSubmitterTest.kt | 28 ++-- .../app/browser/BrowserViewModelTest.kt | 34 ++--- .../duckduckgo/app/browser/DosDetectorTest.kt | 12 +- .../browser/DuckDuckGoRequestRewriterTest.kt | 18 +-- .../app/browser/DuckDuckGoUrlDetectorTest.kt | 48 +++---- .../app/browser/EmptyNavigationStateTest.kt | 4 +- .../MajorWebViewVersionProviderTest.kt | 20 +-- .../app/browser/QueryUrlConverterTest.kt | 24 ++-- .../app/browser/SpecialUrlDetectorImplTest.kt | 84 +++++------ .../WebNavigationStateComparisonTest.kt | 28 ++-- .../browser/WebViewLongPressHandlerTest.kt | 36 ++--- .../app/browser/WebViewNavigationStateTest.kt | 6 +- .../applinks/DuckDuckGoAppLinksHandlerTest.kt | 38 ++--- ...alAutofillFireproofDialogSuppressorTest.kt | 6 +- .../customtabs/CustomTabViewModelTest.kt | 6 +- .../IntentDispatcherViewModelTest.kt | 14 +- .../DefaultBrowserObserverTest.kt | 8 +- .../BlobConverterJavascriptInterfaceTest.kt | 2 +- .../FileChooserIntentBuilderTest.kt | 26 ++-- .../LoginDetectionJavascriptInterfaceTest.kt | 2 +- .../NextPageLoginDetectionTest.kt | 32 ++--- .../logindetection/UriAuthExtensionKtTest.kt | 6 +- .../store/RealMediaPlaybackRepositoryTest.kt | 6 +- .../BrowserServiceWorkerClientTest.kt | 6 +- .../state/BrowserApplicationStateInfoTest.kt | 12 +- .../UrlExtractionJavascriptInterfaceTest.kt | 4 +- .../browser/webshare/WebShareChooserTest.kt | 20 +-- .../java/com/duckduckgo/app/cta/ui/CtaTest.kt | 62 ++++----- .../app/downloads/DownloadsViewModelTest.kt | 30 ++-- .../app/email/AppEmailManagerTest.kt | 58 ++++---- .../app/email/EmailJavascriptInterfaceTest.kt | 22 +-- .../com/duckduckgo/app/email/EmailSyncTest.kt | 18 +-- .../app/feedback/BrokenSiteViewModelTest.kt | 52 +++---- .../ui/common/FeedbackViewModelTest.kt | 52 +++---- .../data/FireproofWebsiteEntityKtTest.kt | 6 +- .../app/firebutton/FireButtonViewModelTest.kt | 30 ++-- .../app/global/HashUtilitiesTest.kt | 10 +- .../duckduckgo/app/global/UriExtensionTest.kt | 82 +++++------ .../duckduckgo/app/global/UriStringTest.kt | 130 +++++++++--------- .../api/PixelParamRemovalInterceptorTest.kt | 8 +- .../global/api/PixelReQueryInterceptorTest.kt | 6 +- .../app/global/install/AppInstallStoreTest.kt | 6 +- .../migrations/GpcMigrationPluginTest.kt | 4 +- .../MigrationLifecycleObserverTest.kt | 8 +- .../app/global/model/SiteMonitorTest.kt | 46 +++---- .../global/rating/InitialPromptDeciderTest.kt | 12 +- .../rating/InitialPromptTypeDeciderTest.kt | 6 +- .../rating/SecondaryPromptDeciderTest.kt | 6 +- .../app/global/uri/UriSubdomainRemoverTest.kt | 20 +-- .../ui/GlobalPrivacyControlViewModelTest.kt | 18 +-- .../duckduckgo/app/job/WorkSchedulerTest.kt | 2 +- .../app/launch/LaunchViewModelTest.kt | 12 +- .../data/LocationPermissionEntityTest.kt | 8 +- .../AndroidSchedulerNotificationTest.kt | 8 +- .../onboarding/store/AppUserStageStoreTest.kt | 10 +- .../ui/OnboardingPageManagerTest.kt | 12 +- .../onboarding/ui/OnboardingViewModelTest.kt | 2 +- .../page/DefaultBrowserPageViewModelTest.kt | 48 +++---- .../ui/page/WelcomePageViewModelTest.kt | 10 +- .../permissions/PermissionsViewModelTest.kt | 14 +- .../app/pixels/EnqueuedPixelWorkerTest.kt | 18 +-- .../privacy/db/UserAllowListRepositoryTest.kt | 12 +- .../app/privacy/model/EntityTest.kt | 4 +- .../app/privacy/model/TrustedSitesTest.kt | 4 +- .../PrivateSearchViewModelTest.kt | 4 +- .../referral/QueryParamReferrerParserTest.kt | 30 ++-- .../app/settings/SettingsViewModelTest.kt | 66 ++++----- .../PermissionsPerWebsiteViewModelTest.kt | 22 +-- .../SitePermissionsViewModelTest.kt | 24 ++-- .../app/statistics/pixels/PixelNameTest.kt | 2 +- .../app/surrogates/ResourceSurrogatesTest.kt | 10 +- .../app/survey/api/SurveyDownloaderTest.kt | 18 +-- .../app/survey/api/SurveyRepositoryTest.kt | 34 ++--- .../app/survey/rmf/SurveyActionMapperTest.kt | 10 +- .../app/survey/ui/SurveyViewModelTest.kt | 18 +-- ...alSavedSitesFormFactorSyncMigrationTest.kt | 14 +- .../sync/SavedSitesSyncDataProviderTest.kt | 38 ++--- .../SavedSitesDeduplicationPersisterTest.kt | 18 +-- .../SavedSitesDuplicateFinderTest.kt | 28 ++-- .../SavedSitesLocalWinsPersisterTest.kt | 18 +-- .../SavedSitesRemoteWinsPersisterTest.kt | 18 +-- .../SavedSitesTimestampPersisterTest.kt | 24 ++-- .../app/systemsearch/DeviceAppLookupTest.kt | 18 +-- .../systemsearch/SystemSearchViewModelTest.kt | 72 +++++----- .../app/tabs/ui/TabRendererExtensionTest.kt | 14 +- .../app/tabs/ui/TabSwitcherViewModelTest.kt | 20 +-- .../CloakedCnameDetectorImplTest.kt | 16 +-- .../app/trackerdetection/EntityLookupTest.kt | 14 +- .../app/trackerdetection/TdsClientTest.kt | 54 ++++---- .../trackerdetection/TrackerDataLoaderTest.kt | 2 +- .../TrackerDetectorClientTypeTest.kt | 4 +- .../trackerdetection/TrackerDetectorTest.kt | 60 ++++---- .../api/TdsDomainEntityJsonTest.kt | 6 +- .../trackerdetection/api/TdsEntityJsonTest.kt | 10 +- .../api/TdsTrackerJsonTest.kt | 8 +- .../api/TrackerDataDownloaderKtTest.kt | 6 +- .../WebTrackingProtectionViewModelTest.kt | 10 +- .../app/widget/AddWidgetCompatLauncherTest.kt | 4 +- .../pixel/AutofillUniquePixelSenderTest.kt | 12 +- .../MissingEntitiesRelationReconcilerTest.kt | 20 +-- .../impl/RealFavoritesDelegateTest.kt | 52 +++---- ...oritesDisplayModeSettingsRepositoryTest.kt | 28 ++-- .../WidgetVoiceSearchStatusListenerTest.kt | 2 +- .../api/SurveyEndpointInterceptorTest.kt | 8 +- .../impl/AutoconsentInterfaceTest.kt | 4 +- .../autoconsent/impl/RealAutoconsentTest.kt | 28 ++-- .../handlers/EvalMessageHandlerPluginTest.kt | 10 +- .../handlers/InitMessageHandlerPluginTest.kt | 16 +-- ...AutoconsentDoneMessageHandlerPluginTest.kt | 14 +- .../PopUpFoundMessageHandlerPluginTest.kt | 8 +- .../SelfTestResultMessageHandlerPluginTest.kt | 6 +- ...RealAutoconsentExceptionsRepositoryTest.kt | 6 +- ...utoconsentFeatureSettingsRepositoryTest.kt | 6 +- .../ui/AutoconsentSettingsViewModelTest.kt | 8 +- .../impl/AutofillCapabilityCheckerImplTest.kt | 20 +-- ...tofillStoredBackJavascriptInterfaceTest.kt | 42 +++--- .../impl/InlineBrowserAutofillTest.kt | 6 +- .../autofill/impl/RealAutofillTest.kt | 8 +- .../impl/RealDuckAddressLoginCreatorTest.kt | 14 +- .../SecureStoreBackedAutofillStoreTest.kt | 66 ++++----- .../InlineBrowserAutofillConfiguratorTest.kt | 4 +- .../RealAutofillRuntimeConfigProviderTest.kt | 32 ++--- .../RealRuntimeConfigurationWriterTest.kt | 8 +- .../RealAutofillLoginDeduplicatorTest.kt | 26 ++-- .../RealAutofillMatchTypeDetectorTest.kt | 10 +- ...ealLoginDeduplicatorBestMatchFinderTest.kt | 14 +- ...uplicatorUsernameAndPasswordMatcherTest.kt | 12 +- .../RealLoginSorterForDeduplicationTest.kt | 18 +-- ...llTimeBasedAuthorizationGracePeriodTest.kt | 8 +- .../deviceauth/RealDeviceAuthenticatorTest.kt | 12 +- ...lProtectionInContextSignupViewModelTest.kt | 30 ++-- ...ltHandlerEmailProtectionChooseEmailTest.kt | 18 +-- ...rotectionInContextAvailabilityRulesTest.kt | 12 +- ...ectionInContextRecentInstallCheckerTest.kt | 8 +- ...ctionInContextSignUpPromptViewModelTest.kt | 12 +- .../RealEmailProtectionLinkVerifierTest.kt | 10 +- .../encoding/UrlUnicodeNormalizerImplTest.kt | 8 +- .../EngagementPasswordAddedListenerTest.kt | 6 +- .../DefaultAutofillEngagementBucketingTest.kt | 10 +- ...DefaultAutofillEngagementRepositoryTest.kt | 6 +- ...ionInContextRemoteSettingsPersisterTest.kt | 8 +- .../RealInternalTestUserCheckerTest.kt | 16 +-- .../request/AutofillJsonRequestParserTest.kt | 18 +-- .../AutofillJsonResponseWriterTest.kt | 4 +- .../RealL2DataTransformerTest.kt | 8 +- .../RealSecureStorageKeyGeneratorTest.kt | 6 +- .../RealSecureStorageKeyProviderTest.kt | 10 +- .../securestorage/RealSecureStorageTest.kt | 38 ++--- .../AppleShareableCredentialsTest.kt | 8 +- .../AppleSharedCredentialsParserTest.kt | 4 +- ...ealShareableCredentialsUrlGeneratorTest.kt | 18 +-- .../store/RealNeverSavedSiteRepositoryTest.kt | 8 +- .../AutofillSettingsViewModelTest.kt | 118 ++++++++-------- .../management/CredentialGrouperTest.kt | 22 +-- .../CredentialInitialExtractorTest.kt | 24 ++-- .../management/CredentialListSorterTest.kt | 44 +++--- .../management/RegexBasedUrlIdentifierTest.kt | 12 +- ...mentScreenAutofillCredentialMatcherTest.kt | 14 +- ...anagementScreenCredentialListFilterTest.kt | 6 +- .../suggestion/SuggestionListBuilderTest.kt | 22 +-- .../suggestion/SuggestionMatcherTest.kt | 20 +-- .../survey/AutofillSurveyImplTest.kt | 24 ++-- .../survey/AutofillSurveyStoreImplTest.kt | 8 +- .../RealDuckAddressIdentifierTest.kt | 12 +- .../InMemoryAutoSavedLoginsMonitorTest.kt | 4 +- .../PasswordEventResolverTest.kt | 8 +- .../ResultHandlerUseGeneratedPasswordTest.kt | 20 +-- .../RemoteDuckAddressStatusRepositoryTest.kt | 22 +-- .../AutofillSavingCredentialsViewModelTest.kt | 4 +- .../AutofillSavingPixelEventNamesTest.kt | 18 +-- ...dlerPromptToDisableCredentialSavingTest.kt | 10 +- .../ResultHandlerSaveLoginCredentialsTest.kt | 10 +- .../AutofillDisablingDeclineCounterTest.kt | 22 +-- .../selecting/CredentialTextExtractorTest.kt | 4 +- .../LastUpdatedCredentialSorterTest.kt | 16 +-- .../selecting/LastUsedCredentialSorterTest.kt | 16 +-- ...ealAutofillSelectCredentialsGrouperTest.kt | 26 ++-- ...utofillSelectCredentialsListBuilderTest.kt | 22 +-- .../ResultHandlerCredentialSelectionTest.kt | 12 +- ...UpdatingExistingCredentialViewModelTest.kt | 6 +- ...ResultHandlerUpdateLoginCredentialsTest.kt | 6 +- .../AutofillDomainNameUrlMatcherTest.kt | 48 +++---- .../store/RealAutofillPrefsStoreTest.kt | 10 +- .../RealAutofillDefaultStateDeciderTest.kt | 8 +- .../AppCredentialsSyncFeatureListenerTest.kt | 12 +- .../CredentialsInvalidItemsViewModelTest.kt | 4 +- .../sync/CredentialsRateLimitViewModelTest.kt | 4 +- .../sync/CredentialsSyncDataPersisterTest.kt | 20 +-- .../sync/CredentialsSyncMapperTest.kt | 4 +- .../sync/CredentialsSyncMetadataTest.kt | 48 +++---- .../autofill/sync/CredentialsSyncTest.kt | 40 +++--- .../sync/RealCredentialsSyncStoreTest.kt | 4 +- .../sync/SyncCredentialsListenerTest.kt | 12 +- ...CredentialsLastModifiedWinsStrategyTest.kt | 16 +-- .../CredentialsLocalWinsStrategyTest.kt | 16 +-- .../CredentialsRemoteWinsStrategyTest.kt | 14 +- .../CrendentialsDedupStrategyTest.kt | 12 +- .../CredentialsSyncDataProviderTest.kt | 10 +- .../RealSecureStorageKeyRepositoryTest.kt | 20 +-- .../RealSecureStorageRepositoryTest.kt | 28 ++-- ...eanupBrokenSiteLastSentReportWorkerTest.kt | 2 +- .../impl/RealBrokenSiteLastSentReportTest.kt | 4 +- .../RealBrokenSiteReportRepositoryTest.kt | 12 +- .../ui/notifyme/NotifyMeViewModelTest.kt | 32 ++--- .../utils/extensions/LocaleExtensionsTest.kt | 4 +- .../formatters/data/DataSizeFormatterTest.kt | 12 +- .../time/DatabaseDateFormatterTest.kt | 12 +- .../formatters/time/model/TimePassedTest.kt | 26 ++-- .../utils/network/NetworkExtensionsTest.kt | 2 +- ...ContentScopeScriptsJsInjectorPluginTest.kt | 6 +- .../impl/RealContentScopeScriptsTest.kt | 18 +-- .../ContentScopeScriptsJsMessagingTest.kt | 18 +-- .../CookiesContentScopeConfigPluginTest.kt | 4 +- .../impl/CookiesFeatureNameUtilTest.kt | 6 +- .../cookies/impl/RemoveCookiesTest.kt | 4 +- .../cookies/impl/WebViewCookieManagerTest.kt | 8 +- .../impl/features/CookiesFeaturePluginTest.kt | 12 +- .../CookiesFeatureTogglesPluginTest.kt | 14 +- ...PartyCookiesModifierWorkerSchedulerTest.kt | 8 +- .../FirstPartyCookiesModifierWorkerTest.kt | 2 +- .../cookies/store/RealCookieRepositoryTest.kt | 8 +- .../RealCookiesFeatureToggleRepositoryTest.kt | 6 +- .../impl/SharedPreferencesProviderImplTest.kt | 6 +- .../downloads/impl/DataUriParserTest.kt | 34 ++--- .../impl/DefaultDownloadsRepositoryTest.kt | 20 +-- .../downloads/impl/DownloaderUtilTest.kt | 46 +++---- .../impl/FileDownloadCallbackTest.kt | 16 +-- .../impl/PendingFileDownloadCompressTest.kt | 15 +- .../RealUrlFileDownloadCallManagerTest.kt | 6 +- .../impl/UriUtilsFilenameExtractorTest.kt | 36 ++--- .../downloads/impl/UrlFileDownloaderTest.kt | 12 +- .../downloads/store/DownloadsDaoTest.kt | 14 +- ...ementHidingContentScopeConfigPluginTest.kt | 4 +- .../impl/ElementHidingFeaturePluginTest.kt | 6 +- .../store/ElementHidingRepositoryTest.kt | 6 +- .../impl/ExperimentFiltersManagerImplTest.kt | 10 +- .../impl/VariantManagerImplTest.kt | 30 ++-- .../experiments/impl/VariantManagerTest.kt | 6 +- .../reinstalls/ReinstallAtbListenerTest.kt | 12 +- .../feature/toggles/api/FeatureTogglesTest.kt | 70 +++++----- ...ntributesRemoteFeatureCodeGeneratorTest.kt | 84 ++++++----- .../toggles/impl/RealFeatureToggleImplTest.kt | 4 +- ...rprintProtectionSeedWorkerSchedulerTest.kt | 4 +- .../FingerprintProtectionSeedWorkerTest.kt | 2 +- ...tingBatteryContentScopeConfigPluginTest.kt | 4 +- .../FingerprintingBatteryFeaturePluginTest.kt | 6 +- ...ntingCanvasContentScopeConfigPluginTest.kt | 4 +- .../FingerprintingCanvasFeaturePluginTest.kt | 6 +- ...ingHardwareContentScopeConfigPluginTest.kt | 4 +- ...FingerprintingHardwareFeaturePluginTest.kt | 6 +- ...gScreenSizeContentScopeConfigPluginTest.kt | 4 +- ...ngerprintingScreenSizeFeaturePluginTest.kt | 6 +- ...raryStorageContentScopeConfigPluginTest.kt | 4 +- ...intingTemporaryStorageFeaturePluginTest.kt | 6 +- ...RealFingerprintingBatteryRepositoryTest.kt | 6 +- .../RealFingerprintingCanvasRepositoryTest.kt | 6 +- ...ealFingerprintingHardwareRepositoryTest.kt | 6 +- ...lFingerprintingScreenSizeRepositoryTest.kt | 6 +- ...rprintingTemporaryStorageRepositoryTest.kt | 6 +- ...FingerprintProtectionSeedRepositoryTest.kt | 4 +- .../impl/HttpsBloomFilterSpecJsonTest.kt | 2 +- .../impl/HttpsFalsePositivesJsonTest.kt | 2 +- .../store/HttpsBloomFilterSpecDaoTest.kt | 6 +- .../store/HttpsFalsePositivesDaoTest.kt | 14 +- .../InstallSourceLifecycleObserverTest.kt | 4 +- .../messaging/impl/RealJsMessageHelperTest.kt | 6 +- .../macos/impl/MacOsViewModelTest.kt | 4 +- .../impl/GlobalActivityStarterImplTest.kt | 20 +-- .../impl/WgVpnNetworkStackTest.kt | 20 +-- .../impl/cohort/NetPCohortUpdaterTest.kt | 10 +- .../cohort/NetpCohortPixelInterceptorTest.kt | 20 +-- .../NetpControllerRequestInterceptorTest.kt | 24 ++-- .../impl/configuration/RealWgServerApiTest.kt | 22 +-- .../impl/configuration/WgTunnelTest.kt | 12 +- .../ConnectionClassManagerTest.kt | 6 +- .../ConnectionQualityStoreTest.kt | 2 +- .../RealNetworkProtectionExclusionListTest.kt | 8 +- .../ui/NetpAppExclusionListViewModelTest.kt | 34 ++--- .../failure/FailureRecoveryHandlerTest.kt | 20 +-- ...etworkProtectionManagementViewModelTest.kt | 66 ++++----- .../NetPDisabledNotificationSchedulerTest.kt | 6 +- ...etPEnabledNotificationContentPluginTest.kt | 18 +-- .../pixels/NetworkProtectionPixelNamesTest.kt | 2 +- ...tworkProtectionRetentionPixelSenderTest.kt | 2 +- .../pixels/RealNetworkProtectionPixelTest.kt | 46 +++---- .../impl/rekey/RealNetPRekeyerTest.kt | 18 +-- .../NetpVpnAccessRevokedDialogMonitorTest.kt | 20 +-- .../settings/NetPVpnSettingsViewModelTest.kt | 22 +-- .../geoswitching/CountryUtilsKtTest.kt | 2 +- .../NetpGeoSwitchingViewModelTest.kt | 34 ++--- ...isplayablePreferredLocationProviderTest.kt | 10 +- .../RealNetpEgressServersProviderTest.kt | 12 +- .../RealNetworkProtectionRepositoryTest.kt | 4 +- .../NetworkProtectionAccessStateImplTest.kt | 22 +-- .../settings/ProSettingNetPViewModelTest.kt | 16 +-- .../feature/TestNetPInternalFeatureToggles.kt | 2 +- .../RealNetPExclusionListRepositoryTest.kt | 14 +- .../impl/RealPrivacyConfigDownloaderTest.kt | 6 +- .../impl/RealPrivacyConfigPersisterTest.kt | 24 ++-- .../features/amplinks/AmpLinksPluginTest.kt | 12 +- .../features/amplinks/RealAmpLinksTest.kt | 12 +- .../ContentBlockingPluginTest.kt | 12 +- .../RealContentBlockingTest.kt | 10 +- .../config/impl/features/drm/DrmPluginTest.kt | 12 +- .../config/impl/features/drm/RealDrmTest.kt | 10 +- .../gpc/GpcContentScopeConfigPluginTest.kt | 6 +- .../config/impl/features/gpc/GpcPluginTest.kt | 12 +- .../config/impl/features/gpc/RealGpcTest.kt | 40 +++--- .../impl/features/https/HttpsPluginTest.kt | 12 +- .../impl/features/https/RealHttpsTest.kt | 10 +- .../RealTrackerAllowlistTest.kt | 2 +- .../TrackerAllowlistPluginTest.kt | 12 +- .../RealTrackingParametersTest.kt | 2 +- .../TrackingParametersPluginTest.kt | 12 +- .../RealUnprotectedTemporaryTest.kt | 6 +- .../LocalPrivacyConfigObserverTest.kt | 2 +- .../PrivacyFeatureTogglesPluginTest.kt | 14 +- .../PrivacyConfigDownloadWorkerTest.kt | 4 +- .../store/RealPrivacyConfigRepositoryTest.kt | 6 +- ...RealPrivacyFeatureTogglesRepositoryTest.kt | 6 +- .../amplinks/RealAmpLinksRepositoryTest.kt | 6 +- .../RealContentBlockingRepositoryTest.kt | 6 +- .../features/drm/RealDrmRepositoryTest.kt | 6 +- .../features/gpc/RealGpcRepositoryTest.kt | 16 +-- .../features/https/RealHttpsRepositoryTest.kt | 6 +- .../RealTrackerAllowlistRepositoryTest.kt | 6 +- .../RealTrackingParametersRepositoryTest.kt | 6 +- .../RealUnprotectedTemporaryRepositoryTest.kt | 6 +- .../AppProtectionStatusViewStateMapperTest.kt | 10 +- .../AppSiteRequestDataViewStateMapperTest.kt | 18 +-- .../impl/ui/AppSiteViewStateMapperTest.kt | 10 +- .../ui/PrivacyDashboardHybridViewModelTest.kt | 18 +-- .../impl/ui/PrivacyDashboardRendererTest.kt | 6 +- .../impl/ui/PublicKeyInfoMapperTest.kt | 8 +- ...rotectionsPopupDomainsCleanupWorkerTest.kt | 2 +- .../PrivacyProtectionsPopupManagerImplTest.kt | 74 +++++----- .../impl/ProtectionsStateProviderTest.kt | 10 +- .../db/PopupDismissDomainRepositoryTest.kt | 12 +- .../PrivacyProtectionsPopupDataStoreTest.kt | 18 +-- .../impl/AppRemoteMessagingRepositoryTest.kt | 16 +-- .../RealRemoteMessagingConfigProcessorTest.kt | 8 +- .../RemoteMessagingConfigJsonMapperTest.kt | 14 +- .../impl/RemoteMessagingConfigMatcherTest.kt | 42 +++--- .../AndroidAppAttributeMatcherTest.kt | 44 +++--- .../matchers/DeviceAttributeMatcherTest.kt | 56 ++++---- .../InteractedWithMessageMatcherTest.kt | 16 +-- .../impl/matchers/UserAttributeMatcherTest.kt | 80 +++++------ .../feature/RmfStagingEnvInterceptorTest.kt | 8 +- ...ocalRemoteMessagingConfigRepositoryTest.kt | 4 +- .../RemoteMessagingCohortStoreImplTest.kt | 6 +- .../filterer/impl/RequestFiltererImplTest.kt | 28 ++-- .../RequestFiltererFeaturePluginTest.kt | 12 +- ...RequestFiltererFeatureTogglesPluginTest.kt | 14 +- ...tererRequestFeatureToggleRepositoryTest.kt | 6 +- .../RealRequestFiltererRepositoryTest.kt | 8 +- ...ntimeChecksContentScopeConfigPluginTest.kt | 4 +- .../impl/RuntimeChecksFeaturePluginTest.kt | 6 +- .../store/RuntimeChecksRepositoryTest.kt | 6 +- .../impl/service/SavedSitesManagerTest.kt | 10 +- .../AppSavedSitesSyncFeatureListenerTest.kt | 12 +- .../sync/DisplayModeSyncableSettingTest.kt | 12 +- .../impl/sync/DisplayModeViewModelTest.kt | 4 +- .../impl/sync/RealSavedSitesSyncStoreTest.kt | 4 +- .../sync/SavedSiteRateLimitViewModelTest.kt | 4 +- .../impl/sync/SavedSitesSyncPersisterTest.kt | 16 +-- .../SavedSitesSyncPersisterAlgorithmTest.kt | 10 +- .../SavedSitesSettingsSharedPrefStoreTest.kt | 6 +- .../impl/SitePermissionsManagerTest.kt | 24 ++-- .../impl/SitePermissionsRepositoryTest.kt | 44 +++--- .../impl/drmblock/RealDrmBlockTest.kt | 10 +- .../app/statistics/AtbInitializerTest.kt | 10 +- .../app/statistics/api/RxPixelSenderTest.kt | 34 ++--- .../statistics/api/StatisticsRequesterTest.kt | 30 ++-- .../app/statistics/model/AtbJsonTest.kt | 4 +- .../app/statistics/pixels/RxBasedPixelTest.kt | 12 +- .../store/PixelFiredRepositoryTest.kt | 8 +- .../impl/RealSubscriptionsManagerTest.kt | 118 ++++++++-------- .../impl/RealSubscriptionsTest.kt | 32 ++--- .../billing/RealPlayBillingManagerTest.kt | 16 +-- .../subscriptions/impl/billing/RetryTest.kt | 10 +- .../messaging/ItrMessagingInterfaceTest.kt | 18 +-- .../SubscriptionMessagingInterfaceTest.kt | 62 ++++----- ...bscriptionRefreshRetentionAtbPluginTest.kt | 4 +- .../impl/repository/RealAuthRepositoryTest.kt | 24 ++-- .../RMFPProEligibleMatchingAttributeTest.kt | 6 +- .../RMFPProSubscriberMatchingAttributeTest.kt | 6 +- .../settings/views/ItrSettingViewModelTest.kt | 8 +- .../settings/views/PirSettingViewModelTest.kt | 8 +- .../settings/views/ProSettingViewModelTest.kt | 10 +- .../impl/ui/AddDeviceViewModelTest.kt | 16 +-- .../ui/RestoreSubscriptionViewModelTest.kt | 22 +-- .../ui/SubscriptionSettingsViewModelTest.kt | 14 +- .../ui/SubscriptionWebViewViewModelTest.kt | 60 ++++---- .../duckduckgo/sync/AppSyncDeviceIdsTest.kt | 14 +- .../sync/impl/AppDeviceSyncStateTest.kt | 6 +- .../sync/impl/AppSyncAccountRepositoryTest.kt | 66 ++++----- .../sync/impl/RealSyncStateMonitorTest.kt | 10 +- .../duckduckgo/sync/impl/SyncCryptoTest.kt | 10 +- .../sync/impl/SyncRemoteFeatureToggleTest.kt | 24 ++-- .../sync/impl/SyncServiceRemoteTest.kt | 32 ++--- .../sync/impl/engine/SyncApiClientTest.kt | 20 +-- .../sync/impl/engine/SyncEngineTest.kt | 74 +++++----- .../sync/impl/engine/SyncSchedulerTest.kt | 10 +- .../sync/impl/engine/SyncStateObserverTest.kt | 6 +- .../impl/engine/SyncStateRepositoryTest.kt | 6 +- .../impl/error/SyncApiErrorRecorderTest.kt | 10 +- .../impl/error/SyncApiErrorRepositoryTest.kt | 10 +- .../error/SyncOperationErrorRecorderTest.kt | 2 +- .../error/SyncOperationErrorRepositoryTest.kt | 20 +-- .../favicons/FaviconsFetchingPromptTest.kt | 12 +- .../sync/impl/pixels/SyncPixelsTest.kt | 10 +- .../impl/stats/SyncStatsRepositoryTest.kt | 14 +- .../triggers/AppLifecycleSyncObserverTest.kt | 4 +- .../BackgroundSyncWorkerSchedulerTest.kt | 4 +- .../impl/triggers/BackgroundSyncWorkerTest.kt | 4 +- .../sync/impl/ui/EnterCodeViewModelTest.kt | 20 +-- .../sync/impl/ui/SyncActivityViewModelTest.kt | 80 +++++------ .../sync/impl/ui/SyncConnectViewModelTest.kt | 26 ++-- .../sync/impl/ui/SyncDisabledViewModelTest.kt | 24 ++-- .../sync/impl/ui/SyncLoginViewModelTest.kt | 6 +- .../ui/SyncWithAnotherDeviceViewModelTest.kt | 16 +-- .../ui/qrcode/SyncBarcodeViewModelTest.kt | 24 ++-- .../ui/setup/SaveRecoveryCodeViewModelTest.kt | 14 +- .../ui/setup/SetupAccountViewModelTest.kt | 20 +-- .../setup/SyncCreateAccountViewModelTest.kt | 4 +- .../ui/setup/SyncSetupIntroViewModelTest.kt | 10 +- .../SyncShowRecoveryCodeViewModelTest.kt | 2 +- .../impl/SettingsSyncDataPersisterTest.kt | 12 +- .../impl/SettingsSyncDataProviderTest.kt | 18 +-- .../sync/store/SyncSharedPrefsStoreTest.kt | 12 +- .../sync/store/dao/SyncApiErrorDaoTest.kt | 4 +- .../user/agent/impl/RealUserAgentTest.kt | 14 +- .../user/agent/impl/UserAgentPluginTest.kt | 12 +- .../user/agent/impl/UserAgentProviderTest.kt | 46 +++---- ...ealUserAgentFeatureToggleRepositoryTest.kt | 6 +- .../store/RealUserAgentRepositoryTest.kt | 6 +- .../VerificationCheckAppPackageImplTest.kt | 6 +- .../VerificationCheckBuildTypeImplTest.kt | 8 +- ...rificationCheckBuildCertificateImplTest.kt | 6 +- ...rificationCheckPlayStoreInstallImplTest.kt | 4 +- .../impl/MicrophonePermissionRequestTest.kt | 22 +-- .../PermissionAwareVoiceSearchLauncherTest.kt | 8 +- .../RealVoiceSearchActivityLauncherTest.kt | 20 +-- ...lVoiceSearchAvailabilityPixelLoggerTest.kt | 4 +- .../impl/RealVoiceSearchAvailabilityTest.kt | 42 +++--- .../RealLanguageSupportCheckerTest.kt | 8 +- .../listeningmode/VoiceSearchViewModelTest.kt | 28 ++-- .../RealVoiceSearchFeatureRepositoryTest.kt | 6 +- .../store/RealVoiceSearchRepositoryTest.kt | 12 +- .../WebCompatContentScopeConfigPluginTest.kt | 4 +- .../impl/WebCompatFeaturePluginTest.kt | 6 +- .../store/WebCompatRepositoryTest.kt | 6 +- .../windows/impl/ui/WindowsViewModelTest.kt | 4 +- 517 files changed, 4452 insertions(+), 4431 deletions(-) diff --git a/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/AdClickAttributionPluginTest.kt b/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/AdClickAttributionPluginTest.kt index 47389bdacfdc..04d9f34e2822 100644 --- a/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/AdClickAttributionPluginTest.kt +++ b/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/AdClickAttributionPluginTest.kt @@ -50,19 +50,19 @@ class AdClickAttributionPluginTest { } @Test - fun whenFeatureNameDoesNotMatchAdClickAttributionThenReturnFalse() { + fun `store - feature name does not match ad click attribution - returns false`() { AdClickFeatureName.values().filter { it != FEATURE_NAME }.forEach { assertFalse(testee.store(it.value, EMPTY_JSON_STRING)) } } @Test - fun whenFeatureNameMatchesAdClickAttributionThenReturnTrue() { + fun `store - feature name matches ad click attribution - returns true`() { assertTrue(testee.store(FEATURE_NAME_VALUE, EMPTY_JSON_STRING)) } @Test - fun whenFeatureNameMatchesAdClickAttributionAndIsEnabledThenStoreFeatureEnabled() { + fun `store - feature name matches ad click attribution and is enabled - store feature enabled`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/ad_click_attribution.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -71,7 +71,7 @@ class AdClickAttributionPluginTest { } @Test - fun whenFeatureNameMatchesAdClickAttributionAndIsNotEnabledThenStoreFeatureDisabled() { + fun `store - feature name matches ad click attribution and is not enabled - store feature disabled`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/ad_click_attribution_disabled.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -80,7 +80,7 @@ class AdClickAttributionPluginTest { } @Test - fun whenFeatureNameMatchesAdClickAttributionThenUpdateAllExistingLists() { + fun `whenFeatureNameMatchesAdClickAttributionThenUpdateAllExistingLists - update all existing lists`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/ad_click_attribution.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -124,7 +124,7 @@ class AdClickAttributionPluginTest { } @Test - fun whenFeatureNameMatchesAdClickAttributionAndHasMinSupportedVersionThenStoreMinSupportedVersion() { + fun `store - feature name matches ad click attribution and has min supported version - store min supported version`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/ad_click_attribution_min_supported_version.json") testee.store(FEATURE_NAME_VALUE, jsonString) diff --git a/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/AdClickFeatureTogglesPluginTest.kt b/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/AdClickFeatureTogglesPluginTest.kt index b3cb7ae8ef6b..356cdad86fc2 100644 --- a/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/AdClickFeatureTogglesPluginTest.kt +++ b/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/AdClickFeatureTogglesPluginTest.kt @@ -38,7 +38,7 @@ class AdClickFeatureTogglesPluginTest { } @Test - fun whenIsEnabledCalledOnAdCLickFeatureNameThenReturnRepositoryValue() { + fun `isEnabled - repository value`() { whenever(adClickFeatureToggleRepository.get(AdClickFeatureName.AdClickAttributionFeatureName, false)).thenReturn(true) Assert.assertEquals(true, plugin.isEnabled(AdClickFeatureName.AdClickAttributionFeatureName.value, false)) @@ -47,12 +47,12 @@ class AdClickFeatureTogglesPluginTest { } @Test - fun whenIsEnabledCalledOnOtherFeatureNameThenReturnRepositoryNull() { + fun `isEnabled - other feature name - return repository null`() { Assert.assertNull(plugin.isEnabled(TestFeatureName().value, false)) } @Test - fun whenIsEnabledAndFeatureIsAdCLickeatureThenReturnTrueWhenEnabled() = + fun `isEnabled - ad click feature enabled - returns true when enabled`() = runTest { givenAdCLickFeatureIsEnabled() @@ -62,7 +62,7 @@ class AdClickFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsAdCLickFeatureThenReturnFalseWhenDisabled() = + fun `isEnabled - ad click feature disabled - returns false`() = runTest { givenAdCLickFeatureIsDisabled() @@ -72,7 +72,7 @@ class AdClickFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsAdCLickFeatureThenReturnDefaultValueIfFeatureDoesNotExist() = + fun `isEnabled - ad click feature does not exist - returns default value`() = runTest { val defaultValue = true givenAdCLickFeatureReturnsDefaultValue(defaultValue) @@ -84,7 +84,7 @@ class AdClickFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsAdCLickFeatureAndAppVersionEqualToMinSupportedVersionThenReturnTrueWhenEnabled() = + fun `isEnabled - Ad click feature enabled and app version equal to min supported version - returns true when enabled`() = runTest { givenAdCLickFeatureIsEnabled() givenAppVersionIsEqualToMinSupportedVersion() @@ -95,7 +95,7 @@ class AdClickFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsAdCLickFeatureAndAppVersionIsGreaterThanMinSupportedVersionThenReturnTrueWhenEnabled() = + fun `isEnabled - Ad click feature enabled and app version greater than min supported version - returns true when enabled`() = runTest { givenAdCLickFeatureIsEnabled() givenAppVersionIsGreaterThanMinSupportedVersion() @@ -106,7 +106,7 @@ class AdClickFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsAdCLickFeatureAndAppVersionIsSmallerThanMinSupportedVersionThenReturnFalseWhenEnabled() = + fun `isEnabled - Ad click feature enabled and app version smaller than min supported version - returns false when enabled`() = runTest { givenAdCLickFeatureIsEnabled() givenAppVersionIsSmallerThanMinSupportedVersion() diff --git a/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/DataRemovalAdClickWorkerTest.kt b/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/DataRemovalAdClickWorkerTest.kt index bc3ad1ab500c..79f0091d8ed2 100644 --- a/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/DataRemovalAdClickWorkerTest.kt +++ b/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/DataRemovalAdClickWorkerTest.kt @@ -44,7 +44,7 @@ class DataRemovalAdClickWorkerTest { } @Test - fun whenDoWorkThenCallClearAllExpiredAsyncAndReturnSuccess() = + fun `doWork - clear all expired async - success`() = runTest { val worker = TestListenableWorkerBuilder(context = context).build() worker.adClickManager = mockAdClickManager diff --git a/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/DuckDuckGoAdClickDataTest.kt b/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/DuckDuckGoAdClickDataTest.kt index fc37c3481a72..041b5b23318b 100644 --- a/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/DuckDuckGoAdClickDataTest.kt +++ b/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/DuckDuckGoAdClickDataTest.kt @@ -33,14 +33,14 @@ class DuckDuckGoAdClickDataTest { } @Test - fun whenSetAdDomainForActiveTabCalledThenTheSameDomainIsRetrieved() { + fun `setAdDomainForActiveTab - same domain retrieved`() { testee.setAdDomainTldPlusOne("host") assertEquals("host", testee.getAdDomainTldPlusOne()) } @Test - fun whenRemoveAdDomainForActiveTabCalledThenAdDomainForTabIsRemoved() { + fun `removeAdDomain - ad domain for tab removed`() { testee.setAdDomainTldPlusOne("host") assertEquals("host", testee.getAdDomainTldPlusOne()) @@ -50,7 +50,7 @@ class DuckDuckGoAdClickDataTest { } @Test - fun whenRemoveExemptionForActiveTabCalledThenAllExemptionForTabAreRemoved() { + fun `removeExemption - all exemptions removed`() { testee.addExemption(dummyExpiration("host1")) assertTrue(testee.isHostExempted("host1")) @@ -60,7 +60,7 @@ class DuckDuckGoAdClickDataTest { } @Test - fun whenAddExemptionForActiveTabCalledForADifferentHostThenOnlyThatSecondHostExemptionExists() { + fun `addExemption - different host - only that second host exemption exists`() { val host = "host1" val otherHost = "host2" testee.addExemption(dummyExpiration(host)) diff --git a/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/DuckDuckGoAdClickManagerTest.kt b/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/DuckDuckGoAdClickManagerTest.kt index 114164aa1621..5cac52d5442c 100644 --- a/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/DuckDuckGoAdClickManagerTest.kt +++ b/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/DuckDuckGoAdClickManagerTest.kt @@ -47,21 +47,21 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenDetectAdClickCalledForNullUrlThenReturn() { + fun `detectAdClick - null url - return`() { testee.detectAdClick(url = null, isMainFrame = false) verifyNoInteractions(mockAdClickData) } @Test - fun whenDetectAdClickCalledForNonNullUrlAndNotMainFrameThenReturn() { + fun `detectAdClick - not main frame - return`() { testee.detectAdClick(url = "url", isMainFrame = false) verifyNoInteractions(mockAdClickData) } @Test - fun whenDetectAdClickCalledForAdUrlAndIsMainFrameAndOnlyHeuristicDetectionEnabledThenUpdateAdDomainWithEmptyString() { + fun `detectAdClick - ad click called for ad url and is main frame and only heuristic detection enabled - update ad domain with empty string`() { whenever(mockAdClickAttribution.isAdClick(any())).thenReturn(Pair(true, null)) whenever(mockAdClickAttribution.isDomainDetectionEnabled()).thenReturn(false) whenever(mockAdClickAttribution.isHeuristicDetectionEnabled()).thenReturn(true) @@ -73,7 +73,7 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenDetectAdClickCalledForAdUrlAndIsMainFrameAndOnlyDomainDetectionEnabledThenUpdateAdDomainWithValue() { + fun `detectAdClick - ad domain detection enabled - update ad domain`() { whenever(mockAdClickAttribution.isAdClick(any())).thenReturn(Pair(true, "domain.com")) whenever(mockAdClickAttribution.isDomainDetectionEnabled()).thenReturn(true) whenever(mockAdClickAttribution.isHeuristicDetectionEnabled()).thenReturn(false) @@ -85,7 +85,7 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenDetectAdClickCalledForAdUrlAndIsMainFrameAndBothDetectionsEnabledAndDomainPresentThenUpdateAdDomainWithValue() { + fun `detectAdClick - ad domain present - update ad domain value`() { whenever(mockAdClickAttribution.isAdClick(any())).thenReturn(Pair(true, "domain.com")) whenever(mockAdClickAttribution.isDomainDetectionEnabled()).thenReturn(true) whenever(mockAdClickAttribution.isHeuristicDetectionEnabled()).thenReturn(true) @@ -97,7 +97,7 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenDetectAdClickCalledForAdUrlAndIsMainFrameAndBothDetectionsEnabledAndNoDomainPresentThenUpdateAdDomainWithEmptyString() { + fun `detectAdClick - ad click detected - update ad domain with empty string`() { whenever(mockAdClickAttribution.isAdClick(any())).thenReturn(Pair(true, null)) whenever(mockAdClickAttribution.isDomainDetectionEnabled()).thenReturn(true) whenever(mockAdClickAttribution.isHeuristicDetectionEnabled()).thenReturn(true) @@ -109,7 +109,7 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenDetectAdClickCalledForNonAdUrlAndIsMainFrameAndExemptionExpiredThenUpdateExemptionsMap() { + fun `detectAdClick - non ad url and exemption expired - update exemptions map`() { whenever(mockAdClickAttribution.isAdClick(any())).thenReturn(Pair(false, null)) whenever(mockAdClickData.getExemption()).thenReturn(expired("host.com")) val url = "non_ad_url.com" @@ -121,7 +121,7 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenDetectAdClickCalledForNonAdUrlAndIsMainFrameAndExemptionNotExpiredThenUpdateExemptionsMap() { + fun `detectAdClick - non ad url and exemption not expired - update exemptions map`() { whenever(mockAdClickAttribution.isAdClick(any())).thenReturn(Pair(false, null)) whenever(mockAdClickData.getExemption()).thenReturn(notExpired("host.com")) val url = "non_ad_url.com" @@ -133,7 +133,7 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenSetActiveTabIdCalledWithNoSourceTabIdThenSetActiveTab() { + fun `setActiveTabId - no source tab id - set active tab`() { val tabId = "tab_id" testee.setActiveTabId(tabId = tabId, url = "url", sourceTabId = null, sourceTabUrl = null) @@ -143,7 +143,7 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenSetActiveTabIdCalledWithSourceTabInfoThenSetActiveTabAndPropagateExemption() { + fun `setActiveTabId - set active tab and propagate exemption`() { val tabId = "tab_id" val url = "https://asos.com/" val sourceTabId = "source_tab_id" @@ -158,7 +158,7 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenSetActiveTabIdCalledWithSourceTabInfoAndExemptionExistsThenSetActiveTabAndDoNotPropagateExemptionFromSource() { + fun `setActiveTabId - set active tab and do not propagate exemption from source - does not add exemption or update count pixel`() { val tabId = "tab_id" val url = "https://asos.com/" val sourceTabId = "source_tab_id" @@ -174,7 +174,7 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenDetectAdDomainCalledWithNoAdUrlThenRemoveAdDomain() { + fun `detectAdDomain - no ad url - remove ad domain`() { testee.detectAdDomain(url = "https://no_ad.com/") verify(mockAdClickData).removeAdDomain() @@ -182,14 +182,14 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenDetectAdDomainCalledWithDuckDuckGoUrlThenReturn() { + fun `detectAdDomain - duckduckgo url - return`() { testee.detectAdDomain(url = "https://duckduckgo.com") verify(mockAdClickData, never()).addExemption(any()) } @Test - fun whenDetectAdDomainCalledWithAdUrlThenAddExemptionAndRemoveAdDomain() { + fun `detectAdDomain - ad domain detected - add exemption and remove ad domain`() { whenever(mockAdClickData.getAdDomainTldPlusOne()).thenReturn("landing_page.com") testee.detectAdDomain(url = "https://landing_page.com/") @@ -199,7 +199,7 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenDetectAdDomainCalledWithAdUrlAndSerpDomainMatchesUrlDomainThenDomainDetectionPixelSentWithMatched() { + fun `detectAdDomain - ad domain matches - domain detection pixel sent with matched`() { whenever(mockAdClickData.getAdDomainTldPlusOne()).thenReturn("landing_page.com") testee.detectAdDomain(url = "https://landing_page.com/") @@ -213,7 +213,7 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenDetectAdDomainCalledWithAdUrlAndSerpDomainNotMatchesUrlDomainThenDomainDetectionPixelSentWithMismatch() { + fun `detectAdDomain - ad domain detection pixel sent with mismatch`() { whenever(mockAdClickData.getAdDomainTldPlusOne()).thenReturn("landing_page.com") testee.detectAdDomain(url = "https://other_landing_page.com/") @@ -227,7 +227,7 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenDetectAdDomainCalledWithAdUrlAndSerpDomainAndBrokenUrlDomainThenDomainDetectionPixelSentWithSerpOnly() { + fun `detectAdDomain - serp only - domain detection pixel sent`() { whenever(mockAdClickData.getAdDomainTldPlusOne()).thenReturn("landing_page") testee.detectAdDomain(url = "https://") @@ -241,7 +241,7 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenDetectAdDomainCalledWithAdUrlAndNoSerpDomainAndUrlDomainThenDomainDetectionPixelSentWithHeuristicOnly() { + fun `detectAdDomain - no serp domain and url domain - send domain detection pixel with heuristic only`() { whenever(mockAdClickData.getAdDomainTldPlusOne()).thenReturn("") testee.detectAdDomain(url = "https://landing_page.com/") @@ -255,7 +255,7 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenDetectAdDomainCalledWithAdUrlAndNoSerpDomainAndEmptyUrlDomainThenDomainDetectionPixelSentWithNone() { + fun `detectAdDomain - no serp domain and empty url domain - domain detection pixel sent with none`() { whenever(mockAdClickData.getAdDomainTldPlusOne()).thenReturn("") testee.detectAdDomain(url = "https://") @@ -269,7 +269,7 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenDetectAdDomainCalledAndHeuristicsEnabledThenDomainDetectionPixelSentWithHeuristicsToTrue() { + fun `detectAdDomain - heuristics enabled - domain detection pixel sent with heuristics to true`() { whenever(mockAdClickData.getAdDomainTldPlusOne()).thenReturn("") whenever(mockAdClickAttribution.isHeuristicDetectionEnabled()).thenReturn(true) @@ -284,7 +284,7 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenDetectAdDomainCalledAndDomainDetectionEnabledThenDomainDetectionPixelSentWithDomainDetectionToTrue() { + fun `detectAdDomain - domain detection enabled - sends domain detection pixel with to true`() { whenever(mockAdClickData.getAdDomainTldPlusOne()).thenReturn("") whenever(mockAdClickAttribution.isDomainDetectionEnabled()).thenReturn(true) @@ -299,7 +299,7 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenClearTabIdCalledForTabThenRemoveDataForTab() { + fun `clearTabId - remove data for tab`() { val tabId = "tab_id" testee.clearTabId(tabId) @@ -308,21 +308,21 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenClearAllCalledThenRemoveAllData() { + fun `clearAll - remove all data`() { testee.clearAll() verify(mockAdClickData).removeAll() } @Test - fun whenClearAllExpiredCalledThenRemoveAllExpiredData() { + fun `clearAllExpired - remove all expired data`() { testee.clearAllExpiredAsync() verify(mockAdClickData).removeAllExpired() } @Test - fun whenIsExemptionCalledWithDuckDuckGoDocumentUrlThenReturnFalse() { + fun `isExemption - duckduckgo document url - returns false`() { val documentUrl = "https://duckduckgo.com" val url = "https://tracker.com" @@ -332,7 +332,7 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenIsExemptionCalledWithUrlMatchingExpiredExemptionThenReturnFalse() { + fun `isExemption - is exemption called with url matching expired exemption - returns false`() { val documentUrl = "https://asos.com" val documentUrlHost = "asos.com" val url = "https://tracker.com" @@ -348,7 +348,7 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenIsExemptionCalledWithUrlNotMatchingExpiredExemptionNotMatchingTrackerThenReturnFalse() { + fun `isExemption - is exemption called with url not matching expired exemption not matching tracker - returns false`() { val documentUrl = "https://asos.com" val documentUrlHost = "asos.com" val url = "https://tracker.com" @@ -365,7 +365,7 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenIsExemptionCalledWithUrlNotMatchingExpiredExemptionAndMatchingTrackerThenSendPixelAndReturnTrue() { + fun `isExemption - called with url not matching expired exemption and matching tracker - send pixel and return true`() { val documentUrl = "https://asos.com" val documentUrlHost = "asos.com" val url = "https://bat.bing.com" diff --git a/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/RealAdClickAttributionTest.kt b/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/RealAdClickAttributionTest.kt index 0107ce360151..2f0a22675da0 100644 --- a/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/RealAdClickAttributionTest.kt +++ b/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/RealAdClickAttributionTest.kt @@ -39,7 +39,7 @@ class RealAdClickAttributionTest { private lateinit var testee: RealAdClickAttribution @Test - fun whenFeatureIsNotEnabledThenIsAllowedReturnsFalse() { + fun `isAllowed - feature not enabled - returns false`() { givenFeatureNotEnabled() testee = RealAdClickAttribution( mockAdClickAttributionRepository, @@ -52,7 +52,7 @@ class RealAdClickAttributionTest { } @Test - fun whenFeatureEnabledAndBothDetectionsDisabledThenIsAllowedReturnsFalse() { + fun `isAllowed - feature enabled and both detections disabled - returns false`() { givenFeatureNotEnabled() givenDetectionsEnabled(domainEnabled = false, heuristicEnabled = false) testee = RealAdClickAttribution( @@ -66,7 +66,7 @@ class RealAdClickAttributionTest { } @Test - fun whenFeatureEnabledAndNullHostThenIsAllowedReturnsFalse() { + fun `isAllowed - feature enabled and null host - returns false`() { givenFeatureEnabled() givenDetectionsEnabled(domainEnabled = true, heuristicEnabled = true) testee = RealAdClickAttribution( @@ -80,7 +80,7 @@ class RealAdClickAttributionTest { } @Test - fun whenFeatureEnabledAndHostNotInAllowlistHostThenIsAllowedReturnsFalse() { + fun `isAllowed - feature enabled and host not in allowlist host - returns false`() { givenFeatureEnabled() givenDetectionsEnabled(domainEnabled = true, heuristicEnabled = true) whenever(mockAdClickAttributionRepository.allowList).thenReturn( @@ -102,7 +102,7 @@ class RealAdClickAttributionTest { } @Test - fun whenFeatureEnabledAndHostInAllowlistHostThenIsAllowedReturnsTrue() { + fun `isAllowed - feature enabled and host in allowlist host - returns true`() { givenFeatureEnabled() givenDetectionsEnabled(domainEnabled = true, heuristicEnabled = true) whenever(mockAdClickAttributionRepository.allowList).thenReturn( @@ -124,7 +124,7 @@ class RealAdClickAttributionTest { } @Test - fun whenFeatureIsNotEnabledThenIsAdClickReturnsFalse() { + fun `isAdClick - feature not enabled - returns false`() { givenFeatureNotEnabled() testee = RealAdClickAttribution( mockAdClickAttributionRepository, @@ -137,7 +137,7 @@ class RealAdClickAttributionTest { } @Test - fun whenFeatureEnabledAndBothDetectionsDisabledThenIsAdClickReturnsFalse() { + fun `isAdClick - feature enabled and both detections disabled - returns false`() { givenFeatureNotEnabled() givenDetectionsEnabled(domainEnabled = false, heuristicEnabled = false) testee = RealAdClickAttribution( @@ -151,7 +151,7 @@ class RealAdClickAttributionTest { } @Test - fun whenFeatureEnabledAndUrlDoesntMatchLinkFormatThenIsAdClickReturnsFalse() { + fun `isAdClick - feature enabled and url doesn't match link format - returns false`() { givenFeatureEnabled() givenDetectionsEnabled(domainEnabled = true, heuristicEnabled = true) whenever(mockAdClickAttributionRepository.linkFormats).thenReturn( @@ -173,7 +173,7 @@ class RealAdClickAttributionTest { } @Test - fun whenFeatureEnabledAndUrlMatchesLinkFormatThenIsAdClickReturnsTrue() { + fun `isAdClick - feature enabled and url matches link format - returns true`() { givenFeatureEnabled() givenDetectionsEnabled(domainEnabled = true, heuristicEnabled = true) whenever(mockAdClickAttributionRepository.linkFormats).thenReturn( @@ -195,7 +195,7 @@ class RealAdClickAttributionTest { } @Test - fun whenFeatureEnabledAndUrlMatchesLinkFormatAndAdDomainParameterNameThenIsAdClickReturnsTrueAndAdDomain() { + fun `isAdClick - feature enabled - ad click returns true and ad domain`() { givenFeatureEnabled() givenDetectionsEnabled(domainEnabled = true, heuristicEnabled = true) whenever(mockAdClickAttributionRepository.linkFormats).thenReturn( @@ -218,7 +218,7 @@ class RealAdClickAttributionTest { } @Test - fun whenFeatureEnabledAndOnlyDomainDetectionEnabledAndUrlMatchesLinkFormatThenAdClickReturnsTrue() { + fun `isAdClick - feature enabled - ad click returns true`() { givenFeatureEnabled() givenDetectionsEnabled(domainEnabled = true, heuristicEnabled = false) whenever(mockAdClickAttributionRepository.linkFormats).thenReturn( diff --git a/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/pixels/AdClickDailyReportingWorkerTest.kt b/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/pixels/AdClickDailyReportingWorkerTest.kt index 318982589c32..a9dcddca974e 100644 --- a/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/pixels/AdClickDailyReportingWorkerTest.kt +++ b/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/pixels/AdClickDailyReportingWorkerTest.kt @@ -43,7 +43,7 @@ internal class AdClickDailyReportingWorkerTest { } @Test - fun whenDoWorkThenCallFireCountPixelWithCorrectParamNameAndReturnSuccess() = + fun `doWork - call fire count pixel with correct param name and return success`() = runTest { val worker = TestListenableWorkerBuilder(context = context).build() worker.adClickPixels = mockAdClickPixels diff --git a/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/pixels/RealAdClickPixelsTest.kt b/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/pixels/RealAdClickPixelsTest.kt index 6b70570a0e50..ef3bb21b9547 100644 --- a/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/pixels/RealAdClickPixelsTest.kt +++ b/ad-click/ad-click-impl/src/test/java/com/duckduckgo/adclick/impl/pixels/RealAdClickPixelsTest.kt @@ -56,7 +56,7 @@ class RealAdClickPixelsTest { } @Test - fun whenFireAdClickActivePixelCalledWithNullExemptionThenReturnFalse() { + fun `fireAdClickActivePixel - null exemption - returns false`() { val exemption = null val result = testee.fireAdClickActivePixel(exemption) @@ -65,7 +65,7 @@ class RealAdClickPixelsTest { } @Test - fun whenFireAdClickActivePixelCalledWithNonNullExemptionAndPixelAlreadyFiredThenReturnFalse() { + fun `fireAdClickActivePixel - pixel already fired - returns false`() { val exemption = Exemption( hostTldPlusOne = "ad_domain", navigationExemptionDeadline = 0L, @@ -79,7 +79,7 @@ class RealAdClickPixelsTest { } @Test - fun whenFireAdClickActivePixelCalledWithNonNullExemptionAndPixelNotAlreadyFiredThenFirePixelAndReturnTrue() { + fun `fireAdClickActivePixel - exemption present and not already fired - returns true`() { val exemption = Exemption( hostTldPlusOne = "ad_domain", navigationExemptionDeadline = 0L, @@ -94,7 +94,7 @@ class RealAdClickPixelsTest { } @Test - fun whenFireAdClickDetectedPixelCalledWithSavedAdDomainSameAsUrlAdDomainThenPixelSentWithMatchedParam() { + fun `fireAdClickDetectedPixel - saved ad domain same as url ad domain - pixel sent with matched param`() { val savedAdDomain = "ad_domain" val urlAdDomain = "ad_domain" val heuristicEnabled = true @@ -113,7 +113,7 @@ class RealAdClickPixelsTest { } @Test - fun whenFireAdClickDetectedPixelCalledWithSavedAdDomainDifferentThanUrlAdDomainThenPixelSentWithMismatchParam() { + fun `fireAdClickDetectedPixel - saved ad domain different than url ad domain - pixel sent with mismatch param`() { val savedAdDomain = "ad_domain" val urlAdDomain = "other_domain" val heuristicEnabled = true @@ -132,7 +132,7 @@ class RealAdClickPixelsTest { } @Test - fun whenFireAdClickDetectedPixelCalledWithSavedAdDomainAndNoUrlAdDomainThenPixelSentWithSerpOnlyParam() { + fun `fireAdClickDetectedPixel - saved ad domain and no url ad domain - pixel sent with serp only param`() { val savedAdDomain = "ad_domain" val urlAdDomain = "" val heuristicEnabled = true @@ -151,7 +151,7 @@ class RealAdClickPixelsTest { } @Test - fun whenFireAdClickDetectedPixelCalledWithNoSavedAdDomainAndUrlAdDomainThenPixelSentWithHeuristicOnlyParam() { + fun `fireAdClickDetectedPixel - no saved ad domain and url ad domain - pixel sent with heuristic only param`() { val savedAdDomain = "" val urlAdDomain = "ad_domain" val heuristicEnabled = true @@ -170,7 +170,7 @@ class RealAdClickPixelsTest { } @Test - fun whenFireAdClickDetectedPixelCalledWithNoSavedAdDomainAndNoUrlAdDomainThenPixelSentWithNoneParam() { + fun `fireAdClickDetectedPixel - no saved ad domain and no url ad domain - pixel sent with none param`() { val savedAdDomain = "" val urlAdDomain = "" val heuristicEnabled = true @@ -189,7 +189,7 @@ class RealAdClickPixelsTest { } @Test - fun whenFireAdClickDetectedPixelCalledWithDisabledHeuristicDetectionThenPixelSentWithCorrectParam() { + fun `fireAdClickDetectedPixel - heuristic detection disabled - pixel sent with correct param`() { val savedAdDomain = "" val urlAdDomain = "" val heuristicEnabled = false @@ -208,7 +208,7 @@ class RealAdClickPixelsTest { } @Test - fun whenFireAdClickDetectedPixelCalledWithDisabledDomainDetectionThenPixelSentWithCorrectParam() { + fun `fireAdClickDetectedPixel - domain detection disabled - pixel sent with correct param`() { val savedAdDomain = "" val urlAdDomain = "" val heuristicEnabled = true @@ -227,7 +227,7 @@ class RealAdClickPixelsTest { } @Test - fun whenUpdateCountPixelCalledThenSharedPrefUpdated() { + fun `updateCountPixel - shared pref updated`() { val key = "${AdClickPixelName.AD_CLICK_PAGELOADS_WITH_AD_ATTRIBUTION.pixelName}_count" assertEquals(0, prefs.getInt(key, 0)) @@ -238,7 +238,7 @@ class RealAdClickPixelsTest { } @Test - fun whenFireCountPixelCalledForZeroCountThenPixelNotSent() { + fun `fireCountPixel - count zero - pixel not sent`() { val key = "${AdClickPixelName.AD_CLICK_PAGELOADS_WITH_AD_ATTRIBUTION.pixelName}_count" assertEquals(0, prefs.getInt(key, 0)) @@ -253,7 +253,7 @@ class RealAdClickPixelsTest { } @Test - fun whenFireCountPixelCalledForNonZeroCountAndCurrentTimeNotSetThenPixelSent() { + fun `fireCountPixel - current time not set - pixel sent`() { val key = "${AdClickPixelName.AD_CLICK_PAGELOADS_WITH_AD_ATTRIBUTION.pixelName}_count" testee.updateCountPixel(AdClickPixelName.AD_CLICK_PAGELOADS_WITH_AD_ATTRIBUTION) assertEquals(1, prefs.getInt(key, 0)) @@ -269,7 +269,7 @@ class RealAdClickPixelsTest { } @Test - fun whenFireCountPixelCalledForNonZeroCountAndCurrentTimeBeforeTimestampThenPixelNotSent() { + fun `updateCountPixel - fire count pixel called for non-zero count and current time before timestamp - pixel not sent`() { val key = "${AdClickPixelName.AD_CLICK_PAGELOADS_WITH_AD_ATTRIBUTION.pixelName}_count" val timestampKey = "${AdClickPixelName.AD_CLICK_PAGELOADS_WITH_AD_ATTRIBUTION.pixelName}_timestamp" val now = Instant.now().toEpochMilli() @@ -288,7 +288,7 @@ class RealAdClickPixelsTest { } @Test - fun whenFireCountPixelCalledForNonZeroCountAndCurrentTimeAfterTimestampThenPixelSent() { + fun `fireCountPixel - non-zero count and current time after timestamp - pixel sent`() { val key = "${AdClickPixelName.AD_CLICK_PAGELOADS_WITH_AD_ATTRIBUTION.pixelName}_count" val timestampKey = "${AdClickPixelName.AD_CLICK_PAGELOADS_WITH_AD_ATTRIBUTION.pixelName}_timestamp" val now = Instant.now().toEpochMilli() diff --git a/ad-click/ad-click-store/src/test/java/com/duckduckgo/adclick/store/RealAdClickAttributionRepositoryTest.kt b/ad-click/ad-click-store/src/test/java/com/duckduckgo/adclick/store/RealAdClickAttributionRepositoryTest.kt index c89569f5151d..380d3b2f2432 100644 --- a/ad-click/ad-click-store/src/test/java/com/duckduckgo/adclick/store/RealAdClickAttributionRepositoryTest.kt +++ b/ad-click/ad-click-store/src/test/java/com/duckduckgo/adclick/store/RealAdClickAttributionRepositoryTest.kt @@ -53,7 +53,7 @@ class RealAdClickAttributionRepositoryTest { } @Test - fun whenRepositoryIsCreatedThenAllListsAreLoadedIntoMemory() { + fun `whenRepositoryIsCreated - all lists loaded into memory`() { assertEquals(linkFormatEntity, testee.linkFormats.first()) assertEquals(allowlistEntity, testee.allowList.first()) assertEquals(expirationEntity, testee.expirations.first()) @@ -61,7 +61,7 @@ class RealAdClickAttributionRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - set all called`() = runTest { testee.updateAll( linkFormats = listOf(), @@ -79,7 +79,7 @@ class RealAdClickAttributionRepositoryTest { } @Test - fun whenUpdateAllThenPreviousListsAreCleared() = + fun `updateAll - previous lists cleared`() = runTest { assertEquals(1, testee.linkFormats.size) assertEquals(1, testee.allowList.size) diff --git a/anrs/anrs-impl/src/test/java/com/duckduckgo/app/anr/GlobalUncaughtExceptionHandlerTest.kt b/anrs/anrs-impl/src/test/java/com/duckduckgo/app/anr/GlobalUncaughtExceptionHandlerTest.kt index 9a784b745165..7bddb534e99d 100644 --- a/anrs/anrs-impl/src/test/java/com/duckduckgo/app/anr/GlobalUncaughtExceptionHandlerTest.kt +++ b/anrs/anrs-impl/src/test/java/com/duckduckgo/app/anr/GlobalUncaughtExceptionHandlerTest.kt @@ -49,7 +49,7 @@ class GlobalUncaughtExceptionHandlerTest { } @Test - fun whenExceptionIsNotInIgnoreListThenCrashRecordedInDatabase() = runTest { + fun `uncaughtException - exception not in ignore list - crash recorded in database`() = runTest { testee.uncaughtException(Thread.currentThread(), NullPointerException("Deliberate")) advanceUntilIdle() @@ -58,7 +58,7 @@ class GlobalUncaughtExceptionHandlerTest { } @Test - fun whenExceptionIsNotInIgnoreListThenDefaultExceptionHandlerCalled() = runTest { + fun `uncaughtException - not in ignore list - default exception handler called`() = runTest { val exception = NullPointerException("Deliberate") testee.uncaughtException(Thread.currentThread(), exception) advanceUntilIdle() @@ -68,7 +68,7 @@ class GlobalUncaughtExceptionHandlerTest { } @Test - fun whenExceptionIsInterruptedIoExceptionThenCrashNotRecorded() = runTest { + fun `uncaughtException - interrupted io exception - crash not recorded`() = runTest { val exception = InterruptedIOException("Deliberate") testee.uncaughtException(Thread.currentThread(), exception) advanceUntilIdle() @@ -78,7 +78,7 @@ class GlobalUncaughtExceptionHandlerTest { } @Test - fun whenExceptionIsInterruptedExceptionThenCrashNotRecorded() = runTest { + fun `uncaughtException - exception is interruptedException - crash not recorded`() = runTest { val exception = InterruptedException("Deliberate") testee.uncaughtException(Thread.currentThread(), exception) advanceUntilIdle() diff --git a/anrs/anrs-impl/src/test/java/com/duckduckgo/app/anr/RedactDomainTest.kt b/anrs/anrs-impl/src/test/java/com/duckduckgo/app/anr/RedactDomainTest.kt index 6ba0647d5268..2fc83fbb556c 100644 --- a/anrs/anrs-impl/src/test/java/com/duckduckgo/app/anr/RedactDomainTest.kt +++ b/anrs/anrs-impl/src/test/java/com/duckduckgo/app/anr/RedactDomainTest.kt @@ -25,7 +25,7 @@ import org.junit.runner.RunWith class RedactDomainTest { @Test - fun `redact PII from stack trace`() { + fun `redact PII from stack trace - sanitize stack trace - expected outcome`() { val message = """ Exception in thread "main" java.lang.NullPointerException: Something went wrong at com.example.MyClass.method(MyClass.java:10) diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/app/tracking/AppTPRMFMatchingAttributeTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/app/tracking/AppTPRMFMatchingAttributeTest.kt index 621e7f8647a8..f0e5079f5bb7 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/app/tracking/AppTPRMFMatchingAttributeTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/app/tracking/AppTPRMFMatchingAttributeTest.kt @@ -18,7 +18,7 @@ class AppTPRMFMatchingAttributeTest { private val attribute = AppTPRMFMatchingAttribute(appTrackingProtection) @Test - fun evaluateWithWrongAttributeThenNull() = runTest { + fun `evaluate - wrong attribute - null`() = runTest { whenever(appTrackingProtection.isOnboarded()).thenReturn(false) assertNull(attribute.evaluate(FakeMatchingAttribute)) @@ -27,7 +27,7 @@ class AppTPRMFMatchingAttributeTest { } @Test - fun evaluateWithAppTPMatchingAttributeThenValue() = runTest { + fun `evaluateWithAppTPMatchingAttribute - value`() = runTest { whenever(appTrackingProtection.isOnboarded()).thenReturn(false) assertTrue(attribute.evaluate(AppTPMatchingAttribute(false))!!) @@ -42,14 +42,14 @@ class AppTPRMFMatchingAttributeTest { } @Test - fun mapAppTPMatchingAttributeKeyThenReturnAppTPMatchingAttribute() = runTest { + fun `mapAppTPMatchingAttribute - then return app tp matching attribute`() = runTest { assertNull(attribute.map("atpOnboarded", JsonMatchingAttribute(value = null))) assertEquals(AppTPMatchingAttribute(true), attribute.map("atpOnboarded", JsonMatchingAttribute(value = true))) assertEquals(AppTPMatchingAttribute(false), attribute.map("atpOnboarded", JsonMatchingAttribute(value = false))) } @Test - fun mapNoAppTPMatchingAttributeKeyThenReturnNull() = runTest { + fun `mapNoAppTPMatchingAttributeKey - return null`() = runTest { assertNull(attribute.map("wrong", JsonMatchingAttribute(value = null))) assertNull(attribute.map("wrong", JsonMatchingAttribute(value = true))) assertNull(attribute.map("wrong", JsonMatchingAttribute(value = false))) diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/app/tracking/AppTPVpnConnectivityLossListenerTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/app/tracking/AppTPVpnConnectivityLossListenerTest.kt index 219600a7e6de..73b16f4b5f4a 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/app/tracking/AppTPVpnConnectivityLossListenerTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/app/tracking/AppTPVpnConnectivityLossListenerTest.kt @@ -49,7 +49,7 @@ class AppTPVpnConnectivityLossListenerTest { } @Test - fun onVpnConnectivityLossThenRestartAppTPThirdConsecutiveTime() = runTest { + fun `onVpnConnectivityLoss - app tracking protection restarted third consecutive time - stopped`() = runTest { whenever(networkProtectionState.isEnabled()).thenReturn(false) whenever(appTrackingProtection.isEnabled()).thenReturn(true) @@ -83,7 +83,7 @@ class AppTPVpnConnectivityLossListenerTest { } @Test - fun whenRestartOnConnectivityLossIsDisabledThenNoop() = runTest { + fun `restartOnConnectivityLossIsDisabledThenNoop - no restart`() = runTest { whenever(networkProtectionState.isEnabled()).thenReturn(false) whenever(appTrackingProtection.isEnabled()).thenReturn(true) appTpRemoteFeatures.restartOnConnectivityLoss().setEnabled(Toggle.State(enable = false)) @@ -100,7 +100,7 @@ class AppTPVpnConnectivityLossListenerTest { } @Test - fun onVpnConnectivityLossNetPEnabledThenNoop() = runTest { + fun `onVpnConnectivityLoss - net p enabled - noop`() = runTest { whenever(networkProtectionState.isEnabled()).thenReturn(true) whenever(appTrackingProtection.isEnabled()).thenReturn(true) @@ -116,7 +116,7 @@ class AppTPVpnConnectivityLossListenerTest { } @Test - fun onVpnConnectivityLossAppTPDisabledThenNoop() = runTest { + fun `onVpnConnectivityLoss - app tracking protection disabled - no op`() = runTest { whenever(networkProtectionState.isEnabled()).thenReturn(true) whenever(appTrackingProtection.isEnabled()).thenReturn(false) @@ -132,7 +132,7 @@ class AppTPVpnConnectivityLossListenerTest { } @Test - fun onVpnConnectedResetsConnectivityLossCounter() = runTest { + fun `onVpnConnected - resets connectivity loss counter`() = runTest { whenever(networkProtectionState.isEnabled()).thenReturn(false) whenever(appTrackingProtection.isEnabled()).thenReturn(true) @@ -145,7 +145,7 @@ class AppTPVpnConnectivityLossListenerTest { } @Test - fun onVpnStartedResetsConnectivityLossCounter() = runTest { + fun `onVpnStarted - resets connectivity loss counter`() = runTest { whenever(networkProtectionState.isEnabled()).thenReturn(false) whenever(appTrackingProtection.isEnabled()).thenReturn(true) @@ -159,7 +159,7 @@ class AppTPVpnConnectivityLossListenerTest { } @Test - fun onVpnReconfiguredResetsConnectivityLossCounter() = runTest { + fun `onVpnReconfigured - resets connectivity loss counter`() = runTest { whenever(networkProtectionState.isEnabled()).thenReturn(false) whenever(appTrackingProtection.isEnabled()).thenReturn(true) @@ -172,7 +172,7 @@ class AppTPVpnConnectivityLossListenerTest { } @Test - fun onVpnStartingDoesNotAffectNormalBehavior() = runTest { + fun `onVpnStarting - does not affect normal behavior`() = runTest { whenever(networkProtectionState.isEnabled()).thenReturn(false) whenever(appTrackingProtection.isEnabled()).thenReturn(true) @@ -185,7 +185,7 @@ class AppTPVpnConnectivityLossListenerTest { } @Test - fun onVpnStartFailedDoesNotAffectNormalBehavior() = runTest { + fun `onVpnStartFailed - does not affect normal behavior`() = runTest { whenever(networkProtectionState.isEnabled()).thenReturn(false) whenever(appTrackingProtection.isEnabled()).thenReturn(true) @@ -198,7 +198,7 @@ class AppTPVpnConnectivityLossListenerTest { } @Test - fun onVpnStoppedResetsConnectivityLossCounter() = runTest { + fun `onVpnStopped - resets connectivity loss counter`() = runTest { whenever(networkProtectionState.isEnabled()).thenReturn(false) whenever(appTrackingProtection.isEnabled()).thenReturn(true) diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/app/tracking/AppTrackerDetectorTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/app/tracking/AppTrackerDetectorTest.kt index 5292bd8c4ca9..b35b29d1e771 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/app/tracking/AppTrackerDetectorTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/app/tracking/AppTrackerDetectorTest.kt @@ -70,7 +70,7 @@ class AppTrackerDetectorTest { } @Test - fun whenEvaluateThirdPartyTrackerThenReturnTracker() { + fun `evaluateThirdPartyTracker - return tracker`() { whenever(appTrackerRepository.findTracker(TEST_APP_TRACKER.hostname, APP_PACKAGE_ID)) .thenReturn(AppTrackerType.ThirdParty(TEST_APP_TRACKER)) whenever(appNameResolver.getPackageIdForUid(APP_UID)).thenReturn(APP_ORIGINATING_APP.packageId) @@ -90,7 +90,7 @@ class AppTrackerDetectorTest { } @Test - fun whenEvaluateThirdPartyTrackerAndSystemAppAndNotInExclusionListAndReturnNull() { + fun `evaluate - third party tracker and system app not in exclusion list - return null`() { whenever(appTrackerRepository.findTracker(TEST_APP_TRACKER.hostname, APP_PACKAGE_ID)) .thenReturn(AppTrackerType.ThirdParty(TEST_APP_TRACKER)) whenever(appNameResolver.getPackageIdForUid(APP_UID)).thenReturn(APP_ORIGINATING_APP.packageId) @@ -103,7 +103,7 @@ class AppTrackerDetectorTest { } @Test - fun whenEvaluateThirdPartyTrackerAndoverriddenSystemAppAndNotInExclusionListAndReturnTracker() { + fun `evaluate - third party tracker and overridden system app - returns tracker`() { whenever(appTrackerRepository.findTracker(TEST_APP_TRACKER.hostname, APP_PACKAGE_ID)) .thenReturn(AppTrackerType.ThirdParty(TEST_APP_TRACKER)) whenever(appNameResolver.getPackageIdForUid(APP_UID)).thenReturn(APP_ORIGINATING_APP.packageId) @@ -130,7 +130,7 @@ class AppTrackerDetectorTest { } @Test - fun whenEvaluateThirdPartyTrackerAndSystemAppAndInExclusionListAndReturnNull() { + fun `evaluate - third party tracker and system app in exclusion list - null`() { whenever(appTrackerRepository.findTracker(TEST_APP_TRACKER.hostname, APP_PACKAGE_ID)) .thenReturn(AppTrackerType.ThirdParty(TEST_APP_TRACKER)) whenever(appNameResolver.getPackageIdForUid(APP_UID)).thenReturn(APP_ORIGINATING_APP.packageId) @@ -147,7 +147,7 @@ class AppTrackerDetectorTest { } @Test - fun whenEvaluateThirdPartyTrackerAndOverriddenSystemAppAndInExclusionListAndReturnNull() { + fun `evaluate - third party tracker and overridden system app in exclusion list - null`() { whenever(appTrackerRepository.findTracker(TEST_APP_TRACKER.hostname, APP_PACKAGE_ID)) .thenReturn(AppTrackerType.ThirdParty(TEST_APP_TRACKER)) whenever(appNameResolver.getPackageIdForUid(APP_UID)).thenReturn(APP_ORIGINATING_APP.packageId) @@ -168,7 +168,7 @@ class AppTrackerDetectorTest { } @Test - fun whenEvaluateThirdPartyTrackerAndOverriddenSystemAppThenReturnTracker() { + fun `evaluate - third party tracker and overridden system app - return tracker`() { whenever(appTrackerRepository.findTracker(TEST_APP_TRACKER.hostname, APP_PACKAGE_ID)) .thenReturn(AppTrackerType.ThirdParty(TEST_APP_TRACKER)) whenever(appNameResolver.getPackageIdForUid(APP_UID)).thenReturn(APP_ORIGINATING_APP.packageId) @@ -193,7 +193,7 @@ class AppTrackerDetectorTest { } @Test - fun whenEvaluateThirdPartyTrackerAndManuallyUnprotectedThenReturnNull() { + fun `evaluate - third party tracker and manually unprotected - return null`() { whenever(appTrackerRepository.findTracker(TEST_APP_TRACKER.hostname, APP_PACKAGE_ID)) .thenReturn(AppTrackerType.ThirdParty(TEST_APP_TRACKER)) whenever(appNameResolver.getPackageIdForUid(APP_UID)).thenReturn(APP_ORIGINATING_APP.packageId) @@ -207,7 +207,7 @@ class AppTrackerDetectorTest { } @Test - fun whenEvaluateThirdPartyTrackerAndManuallyProtectedThenReturnTracker() { + fun `evaluate - third party tracker and manually protected - return tracker`() { whenever(appTrackerRepository.findTracker(TEST_APP_TRACKER.hostname, APP_PACKAGE_ID)) .thenReturn(AppTrackerType.ThirdParty(TEST_APP_TRACKER)) whenever(appNameResolver.getPackageIdForUid(APP_UID)).thenReturn(APP_ORIGINATING_APP.packageId) @@ -230,7 +230,7 @@ class AppTrackerDetectorTest { } @Test - fun whenEvaluateThirdPartyTrackerAndInExclusionListThenReturnNull() { + fun `evaluate - third party tracker in exclusion list - return null`() { whenever(appTrackerRepository.findTracker(TEST_APP_TRACKER.hostname, APP_PACKAGE_ID)) .thenReturn(AppTrackerType.ThirdParty(TEST_APP_TRACKER)) whenever(appNameResolver.getPackageIdForUid(APP_UID)).thenReturn(APP_ORIGINATING_APP.packageId) @@ -244,7 +244,7 @@ class AppTrackerDetectorTest { } @Test - fun whenEvaluateThirdPartyTrackerAndManuallyProtectedAndInExclusionListThenReturnTracker() { + fun `evaluate - third party tracker and manually protected in exclusion list - return tracker`() { whenever(appTrackerRepository.findTracker(TEST_APP_TRACKER.hostname, APP_PACKAGE_ID)) .thenReturn(AppTrackerType.ThirdParty(TEST_APP_TRACKER)) whenever(appNameResolver.getPackageIdForUid(APP_UID)).thenReturn(APP_ORIGINATING_APP.packageId) @@ -270,7 +270,7 @@ class AppTrackerDetectorTest { } @Test - fun whenEvaluateThirdPartyTrackerFromUnknownAppThenReturnNull() { + fun `evaluateThirdPartyTrackerFromUnknownApp - return null`() { val packageId = AppNameResolver.OriginatingApp.unknown().packageId whenever(appTrackerRepository.findTracker(TEST_APP_TRACKER.hostname, packageId)) @@ -282,7 +282,7 @@ class AppTrackerDetectorTest { } @Test - fun whenEvaluateThirdPartyTrackerFromDdgAppThenReturnNull() { + fun `evaluateThirdPartyTrackerFromDdgApp - return null`() { // This test case is just in case we pass the DDG traffic through the VPN. Our app doesn't embed trackers but web trackers might be detected // as app trackers. @@ -298,7 +298,7 @@ class AppTrackerDetectorTest { } @Test - fun whenEvaluateThirdPartyTrackerInExclusionListThenReturnTrackerNull() { + fun `evaluateThirdPartyTrackerInExclusionList - return tracker null`() { val packageId = APP_PACKAGE_ID whenever(appTrackerRepository.findTracker(TEST_APP_TRACKER.hostname, packageId)) @@ -313,7 +313,7 @@ class AppTrackerDetectorTest { } @Test - fun whenEvaluateFirstPartyTrackerThenReturnNull() { + fun `evaluateFirstPartyTracker - return null`() { whenever(appTrackerRepository.findTracker(TEST_APP_TRACKER.hostname, APP_PACKAGE_ID)) .thenReturn(AppTrackerType.FirstParty(TEST_APP_TRACKER)) whenever(appNameResolver.getPackageIdForUid(APP_UID)).thenReturn(APP_ORIGINATING_APP.packageId) @@ -324,7 +324,7 @@ class AppTrackerDetectorTest { } @Test - fun whenEvaluateNonTrackerThenReturnNull() { + fun `evaluate - non tracker - return null`() { whenever(appTrackerRepository.findTracker(TEST_APP_TRACKER.hostname, APP_PACKAGE_ID)).thenReturn(AppTrackerType.NotTracker) whenever(appNameResolver.getPackageIdForUid(APP_UID)).thenReturn(APP_ORIGINATING_APP.packageId) @@ -334,7 +334,7 @@ class AppTrackerDetectorTest { } @Test - fun whenAppTpDisabledReturnNull() = runTest { + fun `whenAppTpDisabledReturnNull - evaluate - null`() = runTest { whenever(vpnFeaturesRegistry.isFeatureRegistered(AppTpVpnFeature.APPTP_VPN)).thenReturn(false) val appTrackerDetectorDisabled = RealAppTrackerDetector( @@ -354,7 +354,7 @@ class AppTrackerDetectorTest { } @Test - fun whenNullPackageIdThenEvaluateReturnsNull() { + fun `evaluate - null package id - returns null`() { whenever(appNameResolver.getPackageIdForUid(APP_UID)).thenReturn(null) assertNull(appTrackerDetector.evaluate(TEST_APP_TRACKER.hostname, APP_UID)) diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/UnprotectedAppsBucketPixelSenderTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/UnprotectedAppsBucketPixelSenderTest.kt index 04cc3552a764..f5f140f6b702 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/UnprotectedAppsBucketPixelSenderTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/UnprotectedAppsBucketPixelSenderTest.kt @@ -53,7 +53,7 @@ class UnprotectedAppsBucketPixelSenderTest { } @Test - fun whenVpnStartedWithNoUnprotectedAppsThenSentPixelWithBucketSize20() = runTest { + fun `onVpnStarted - no unprotected apps - sent pixel with bucket size 20`() = runTest { whenever(mockTrackingProtectionAppsRepository.getAppsAndProtectionInfo()).thenReturn(protectedAppsChannel.receiveAsFlow()) protectedAppsChannel.send(listOf(app, app, app, app, app, app, app)) val expectedBucketSize = 20 @@ -64,7 +64,7 @@ class UnprotectedAppsBucketPixelSenderTest { } @Test - fun whenVpnStartedWith1UnprotectedAppsOutOf7ThenSentPixelWithBucketSize20() = runTest { + fun `onVpnStarted - 1 unprotected apps out of 7 - sent pixel with bucket size 20`() = runTest { whenever(mockTrackingProtectionAppsRepository.getAppsAndProtectionInfo()).thenReturn(protectedAppsChannel.receiveAsFlow()) protectedAppsChannel.send(listOf(app, app, app, app, app, excludedApp, app)) val expectedBucketSize = 20 @@ -75,7 +75,7 @@ class UnprotectedAppsBucketPixelSenderTest { } @Test - fun whenVpnStartedWith2UnprotectedAppsOutOf7ThenSentPixelWithBucketSize40() = runTest { + fun `onVpnStarted - 2 unprotected apps out of 7 - sent pixel with bucket size 40`() = runTest { whenever(mockTrackingProtectionAppsRepository.getAppsAndProtectionInfo()).thenReturn(protectedAppsChannel.receiveAsFlow()) protectedAppsChannel.send(listOf(app, app, app, app, app, excludedApp, excludedApp)) val expectedBucketSize = 40 @@ -86,7 +86,7 @@ class UnprotectedAppsBucketPixelSenderTest { } @Test - fun whenVpnStartedWith4UnprotectedAppsOutOf7ThenSentPixelWithBucketSize60() = runTest { + fun `onVpnStarted - 4 unprotected apps out of 7 - sent pixel with bucket size 60`() = runTest { whenever(mockTrackingProtectionAppsRepository.getAppsAndProtectionInfo()).thenReturn(protectedAppsChannel.receiveAsFlow()) protectedAppsChannel.send(listOf(app, app, excludedApp, app, excludedApp, excludedApp, excludedApp)) val expectedBucketSize = 60 @@ -97,7 +97,7 @@ class UnprotectedAppsBucketPixelSenderTest { } @Test - fun whenVpnStartedWith5UnprotectedAppsOutOf7ThenSentPixelWithBucketSize80() = runTest { + fun `onVpnStarted - 5 unprotected apps out of 7 - sent pixel with bucket size 80`() = runTest { whenever(mockTrackingProtectionAppsRepository.getAppsAndProtectionInfo()).thenReturn(protectedAppsChannel.receiveAsFlow()) protectedAppsChannel.send(listOf(app, app, excludedApp, excludedApp, excludedApp, excludedApp, excludedApp)) val expectedBucketSize = 80 @@ -108,7 +108,7 @@ class UnprotectedAppsBucketPixelSenderTest { } @Test - fun whenVpnStartedWith6UnprotectedAppsOutOf7ThenSentPixelWithBucketSize100() = runTest { + fun `onVpnStarted - 6 unprotected apps out of 7 - sent pixel with bucket size 100`() = runTest { whenever(mockTrackingProtectionAppsRepository.getAppsAndProtectionInfo()).thenReturn(protectedAppsChannel.receiveAsFlow()) protectedAppsChannel.send(listOf(app, excludedApp, excludedApp, excludedApp, excludedApp, excludedApp, excludedApp)) val expectedBucketSize = 100 @@ -119,7 +119,7 @@ class UnprotectedAppsBucketPixelSenderTest { } @Test - fun whenVpnStartedWithAllAppsUnprotectedThenSentPixelWithBucketSize100() = runTest { + fun `onVpnStarted - all apps unprotected - sent pixel with bucket size 100`() = runTest { whenever(mockTrackingProtectionAppsRepository.getAppsAndProtectionInfo()).thenReturn(protectedAppsChannel.receiveAsFlow()) protectedAppsChannel.send(listOf(excludedApp, excludedApp, excludedApp, excludedApp, excludedApp, excludedApp, excludedApp)) val expectedBucketSize = 100 diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/VpnFeaturesRegistryImplTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/VpnFeaturesRegistryImplTest.kt index fc96c15f70d1..9553e584ce59 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/VpnFeaturesRegistryImplTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/VpnFeaturesRegistryImplTest.kt @@ -58,7 +58,7 @@ class VpnFeaturesRegistryImplTest { } @Test - fun whenRegisterFeatureThenRestartVpnService() = runTest { + fun `registerFeature - restart vpn service`() = runTest { vpnFeaturesRegistry.registerFeature(TestVpnFeatures.FOO) assertEquals(0, vpnServiceWrapper.restartCount) @@ -66,7 +66,7 @@ class VpnFeaturesRegistryImplTest { } @Test - fun whenFeaturesAreRegisteredThenVpnIsStarted() = runTest { + fun `registerFeatures - vpn started`() = runTest { vpnFeaturesRegistry.registerFeature(TestVpnFeatures.FOO) vpnFeaturesRegistry.registerFeature(TestVpnFeatures.BAR) @@ -76,7 +76,7 @@ class VpnFeaturesRegistryImplTest { } @Test - fun whenIsFeatureRegisteredAndFeaturesAreRegisteredAndVpnIsRunningThenReturnTrue() = runTest { + fun `isFeatureRegistered - features registered - returns true`() = runTest { vpnFeaturesRegistry.registerFeature(TestVpnFeatures.FOO) vpnFeaturesRegistry.registerFeature(TestVpnFeatures.BAR) vpnServiceWrapper.startService() @@ -86,12 +86,12 @@ class VpnFeaturesRegistryImplTest { } @Test - fun whenIsAnyFeatureRegisteredAndFeaturesAreNotRegisteredThenReturnFalse() = runTest { + fun `isAnyFeatureRegistered - features not registered - returns false`() = runTest { vpnFeaturesRegistry.registerFeature(TestVpnFeatures.FOO) } @Test - fun whenIsAnyFeatureRegisteredAndFeaturesAreRegisteredThenReturnTrue() = runTest { + fun `isAnyFeatureRegistered - features registered - returns true`() = runTest { vpnFeaturesRegistry.registerFeature(TestVpnFeatures.FOO) assertTrue(vpnFeaturesRegistry.isAnyFeatureRunning()) @@ -99,7 +99,7 @@ class VpnFeaturesRegistryImplTest { } @Test - fun whenIsAnyFeatureRegisteredAndFeaturesAreRegisteredAndVpnDisabledThenReturnFalse() = runTest { + fun `isAnyFeatureRegistered - vpn disabled - returns false`() = runTest { vpnFeaturesRegistry.registerFeature(TestVpnFeatures.FOO) vpnServiceWrapper.stopService() @@ -108,7 +108,7 @@ class VpnFeaturesRegistryImplTest { } @Test - fun whenUnregisterFeatureThenFeatureIsUnregistered() = runTest { + fun `unregisterFeature - feature unregistered`() = runTest { vpnFeaturesRegistry.registerFeature(TestVpnFeatures.FOO) vpnFeaturesRegistry.unregisterFeature(TestVpnFeatures.FOO) @@ -116,7 +116,7 @@ class VpnFeaturesRegistryImplTest { } @Test - fun whenUnregisterLastFeatureThenVpnIsNotRunning() = runTest { + fun `unregisterLastFeature - vpn is not running`() = runTest { vpnFeaturesRegistry.registerFeature(TestVpnFeatures.FOO) vpnFeaturesRegistry.registerFeature(TestVpnFeatures.BAR) vpnFeaturesRegistry.unregisterFeature(TestVpnFeatures.FOO) @@ -126,7 +126,7 @@ class VpnFeaturesRegistryImplTest { } @Test - fun whenUnregisterFeatureIfFeaturesStillRegisteredThenRestartVpnService() = runTest { + fun `unregisterFeature - features still registered - restart vpn service`() = runTest { vpnFeaturesRegistry.registerFeature(TestVpnFeatures.FOO) // no restart vpnFeaturesRegistry.registerFeature(TestVpnFeatures.BAR) // restart vpnFeaturesRegistry.unregisterFeature(TestVpnFeatures.FOO) // restart @@ -135,14 +135,14 @@ class VpnFeaturesRegistryImplTest { } @Test - fun whenRefreshUnregisteredFeatureThenDoNotRestartVpn() = runTest { + fun `refreshFeature - unregistered feature - do not restart VPN`() = runTest { vpnFeaturesRegistry.refreshFeature(TestVpnFeatures.FOO) assertEquals(0, vpnServiceWrapper.restartCount) } @Test - fun whenRefreshRegisteredFeatureThenRestartVpn() = runTest { + fun `refreshRegisteredFeature - restart VPN`() = runTest { vpnFeaturesRegistry.registerFeature(TestVpnFeatures.FOO) vpnFeaturesRegistry.refreshFeature(TestVpnFeatures.FOO) @@ -151,7 +151,7 @@ class VpnFeaturesRegistryImplTest { } @Test - fun whenRegisterFeatureThenStartVpn() = runTest { + fun `registerFeature - start vpn`() = runTest { vpnFeaturesRegistry.registerFeature(TestVpnFeatures.FOO) assertTrue(vpnServiceWrapper.isServiceRunning()) diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/apps/ManageAppsProtectionViewModelTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/apps/ManageAppsProtectionViewModelTest.kt index 641001451524..c03377ee8e9e 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/apps/ManageAppsProtectionViewModelTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/apps/ManageAppsProtectionViewModelTest.kt @@ -78,7 +78,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenAppIsManuallyExcludedThenUserMadeChangesReturnsTrue() = runTest { + fun `onResume - app is manually excluded - user made changes returns true`() = runTest { manuallyExcludedApps.send(listOf()) viewModel.onResume(TestLifecycleOwner()) @@ -89,14 +89,14 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenNoManuallyExcludedAppsThenUserMadeChangesReturnsFalse() = runTest { + fun `whenNoManuallyExcludedAppsThenUserMadeChangesReturnsFalse - user made changes - false`() = runTest { manuallyExcludedApps.send(listOf()) assertFalse(viewModel.userMadeChanges()) } @Test - fun whenPackageNameIsExcludedThenProtectedAppsExcludesIt() = runTest { + fun `onAppProtectionDisabled - package name excluded - manually excludes app`() = runTest { val packageName = "com.package.name" val appName = "App" val report = true @@ -107,7 +107,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenAppProtectionisSubmittedAndReportIsSkippedThenSkipPixelIsSent() = runTest { + fun `onAppProtection - app protection submitted and report skipped - skip pixel sent`() = runTest { val packageName = "com.package.name" val appName = "App" val report = false @@ -118,7 +118,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenAppProtectionisSubmittedAndReportIsSentThenSubmitPixelIsSent() = runTest { + fun `onAppProtection - submit pixel sent`() = runTest { val packageName = "com.package.name" val appName = "App" val report = true @@ -129,7 +129,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenAppProtectionisSubmittedAndReportIsSentThenReportCommandIsSent() = runTest { + fun `onAppProtectionisSubmitted - report sent - report command is sent`() = runTest { val packageName = "com.package.name" val appName = "App" val report = true @@ -143,7 +143,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenPackageNameIsEnabledAndAppHasNoIssuesThenProtectedAppsEnablesIt() = runTest { + fun `onAppProtectionEnabled - package name enabled - enables it`() = runTest { val packageName = "com.package.name" viewModel.onAppProtectionEnabled(packageName) @@ -152,7 +152,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenPackageNameIsEnabledAndAppHasIssuesThenProtectedAppsEnablesItAndSendsPixel() = runTest { + fun `onAppProtectionEnabled - package name enabled and app has issues - sends pixel`() = runTest { val packageName = "com.package.name" viewModel.onAppProtectionEnabled(packageName) @@ -160,7 +160,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenUserWantsToRestoreDefaultThenDefaultListIsRestoredAndVpnRestarted() = runTest { + fun `restoreProtectedApps - default list restored - vpn restarted`() = runTest { viewModel.commands().test { viewModel.restoreProtectedApps() assertEquals(Command.RestartVpn, awaitItem()) @@ -171,7 +171,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenRestoreProtectionsThenDoNotRestartVpnOnLeavingScreen() = runTest { + fun `restoreProtectedApps - do not restart vpn on leaving screen`() = runTest { viewModel.commands().test { viewModel.restoreProtectedApps() assertEquals(Command.RestartVpn, awaitItem()) @@ -182,7 +182,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenUserLeavesScreenAndChangesWereMadeThenTheVpnIsRestarted() = runTest { + fun `onPause - vpn restarted`() = runTest { viewModel.commands().test { manuallyExcludedApps.send(listOf()) viewModel.onResume(TestLifecycleOwner()) @@ -194,7 +194,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenUserLeavesScreenAndNoChangesWereMadeThenTheVpnIsNotRestarted() = runTest { + fun `onPause - no changes made - vpn not restarted`() = runTest { viewModel.commands().test { manuallyExcludedApps.send(listOf()) viewModel.onResume(TestLifecycleOwner()) @@ -205,7 +205,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenAppWithKnownIssuesIsEnabledThenEnableProtectionDialogIsShown() = runTest { + fun `onAppProtectionChanged - enable protection dialog shown`() = runTest { viewModel.commands().test { viewModel.onAppProtectionChanged(appWithKnownIssues, 0, true) assertEquals(Command.ShowEnableProtectionDialog(appWithKnownIssues, 0), awaitItem()) @@ -214,7 +214,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenAppWithKnownIssuesIsDisabledThenNoDialogIsShown() = runTest { + fun `onAppProtectionChanged - app with known issues disabled - no dialog shown`() = runTest { viewModel.commands().test { viewModel.onAppProtectionChanged(appWithKnownIssues, 0, false) expectNoEvents() @@ -223,7 +223,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenAppLoadsWebsitesIsEnabledThenEnableProtectionDialogIsShown() = runTest { + fun `onAppProtectionChanged - app loads websites enabled - enable protection dialog shown`() = runTest { viewModel.commands().test { viewModel.onAppProtectionChanged(appLoadsWebsites, 0, true) assertEquals(Command.ShowEnableProtectionDialog(appLoadsWebsites, 0), awaitItem()) @@ -232,7 +232,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenAppLoadsWebsitesIsDisabledThenNoDialogIsShown() = runTest { + fun `onAppProtectionChanged - app loads websites disabled - no dialog shown`() = runTest { viewModel.commands().test { viewModel.onAppProtectionChanged(appLoadsWebsites, 0, false) expectNoEvents() @@ -241,7 +241,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenAppWithNoIssuesIsEnabledThenNoDialogIsShown() = runTest { + fun `onAppProtectionChanged - no issues - no dialog shown`() = runTest { viewModel.commands().test { viewModel.onAppProtectionChanged(appWithoutIssues, 0, true) expectNoEvents() @@ -250,7 +250,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenAppWithNoIssuesIsDisabledThenDisabledDialogIsShown() = runTest { + fun `onAppProtectionChanged - app with no issues disabled - show disable protection dialog`() = runTest { viewModel.commands().test { viewModel.onAppProtectionChanged(appWithoutIssues, 0, false) assertEquals(Command.ShowDisableProtectionDialog(appWithoutIssues), awaitItem()) @@ -259,7 +259,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenAppManuallyDisabledIsEnabledThenNoDialogIsShown() = runTest { + fun `onAppProtectionChanged - app manually disabled is enabled - no dialog shown`() = runTest { viewModel.commands().test { viewModel.onAppProtectionChanged(appManuallyExcluded, 0, true) expectNoEvents() @@ -268,7 +268,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenAppManuallyDisabledIsDisabledThenDisableDialogIsShown() = runTest { + fun `onAppProtectionChanged - app manually disabled - disable dialog shown`() = runTest { viewModel.commands().test { viewModel.onAppProtectionChanged(appManuallyExcluded, 0, false) assertEquals(Command.ShowDisableProtectionDialog(appManuallyExcluded), awaitItem()) @@ -277,7 +277,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenAllAppsFilterAppliedAndGetProtectedAppsCalledThenProtectedAndUnprotectedAppsAreReturned() = runTest { + fun `applyAppsFilter - get protected apps called - protected and unprotected apps returned`() = runTest { val protectedApps = listOf(appWithoutIssues) val unprotectedApps = listOf(appWithKnownIssues, appLoadsWebsites, appManuallyExcluded) val allApps = protectedApps + unprotectedApps @@ -306,7 +306,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenProtectedOnlyFilterAppliedAndGetProtectedAppsCalledThenOnlyProtectedAppsAreReturned() = runTest { + fun `getProtectedApps - when protected only filter applied - returns only protected apps`() = runTest { val protectedApps = listOf(appWithoutIssues) val unprotectedApps = listOf(appWithKnownIssues, appLoadsWebsites, appManuallyExcluded) val allApps = protectedApps + unprotectedApps @@ -335,7 +335,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenProtectedOnlyFilterAppliedAndAllAppsAreUnprotectedAndGetProtectedAppsCalledThenOnlyHeaderItemsAreReturned() = runTest { + fun `getProtectedApps - protected only filter applied - only header items returned`() = runTest { val protectedApps = emptyList() val unprotectedApps = listOf(appWithKnownIssues, appLoadsWebsites, appManuallyExcluded) val allApps = protectedApps + unprotectedApps @@ -356,7 +356,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenUnprotectedOnlyFilterAppliedAndAllAppsAreProtectedAndGetProtectedAppsCalledThenHeadersAreReturned() = runTest { + fun `getProtectedApps - apps list returned - unfiltered`() = runTest { val protectedApps = listOf(appWithoutIssues) val unprotectedApps = emptyList() val allApps = protectedApps + unprotectedApps @@ -380,7 +380,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenUnprotectedOnlyFilterAppliedAndGetProtectedAppsCalledThenOnlyUnprotectedAppsAreReturnedAndUnprotectedAppsBannerShown() = + fun `getProtectedApps - when unprotected only filter applied - returns only unprotected apps and shows banner`() = runTest { val protectedApps = listOf(appWithoutIssues) val unprotectedApps = listOf(appWithKnownIssues, appLoadsWebsites, appManuallyExcluded) @@ -405,7 +405,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenAtLeastOneAppManuallyExcludedAndGetProtectedAppsCalledThenShowAllOrProtectedBannerContent() = runTest { + fun `getProtectedApps - at least one app manually excluded - show all or protected banner content`() = runTest { val allApps = listOf(appWithKnownIssues, appManuallyExcluded) val panelType = InfoPanelType(ALL_OR_PROTECTED_APPS) val filterType = FilterType(string.atp_ExcludedAppsFilterAllLabel, allApps.size) @@ -424,7 +424,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenAtLeastOneAppProblematicNotExcludedAndGetProtectedAppsCalledThenShowCustomBannerContent() = runTest { + fun `getProtectedApps - at least one app problematic not excluded - show custom banner content`() = runTest { val allApps = listOf(appWithKnownIssues, appProblematicNotExcluded) val panelType = InfoPanelType(CUSTOMISED_PROTECTION) diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/apps/TrackingProtectionAppsRepositoryTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/apps/TrackingProtectionAppsRepositoryTest.kt index 92def0164a23..f829b721eb92 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/apps/TrackingProtectionAppsRepositoryTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/apps/TrackingProtectionAppsRepositoryTest.kt @@ -67,7 +67,7 @@ class TrackingProtectionAppsRepositoryTest { } @Test - fun whenGetExclusionAppListThenReturnExclusionList() = runTest { + fun `getExclusionAppList - return exclusion list`() = runTest { val exclusionList = trackingProtectionAppsRepository.getExclusionAppsList() assertEquals( @@ -77,7 +77,7 @@ class TrackingProtectionAppsRepositoryTest { } @Test - fun whenIsProtectionEnabledCalledOnDisabledAppThenReturnFalse() = runTest { + fun `getAppProtectionStatus - is protection enabled called on disabled app - returns false`() = runTest { whenever(packageManager.getApplicationInfo("com.example.app2", 0)) .thenReturn(ApplicationInfo().apply { packageName = "com.example.app2" }) whenever(networkProtectionExclusionList.isExcluded("com.example.app2")).thenReturn(false) @@ -88,7 +88,7 @@ class TrackingProtectionAppsRepositoryTest { } @Test - fun whenGetAppProtectionStatusCalledOnEnabledAppThenReturnProtected() = runTest { + fun `getAppProtectionStatus - app enabled - protected`() = runTest { whenever(packageManager.getApplicationInfo("com.example.app1", 0)) .thenReturn(ApplicationInfo().apply { packageName = "com.example.app1" }) whenever(networkProtectionExclusionList.isExcluded("com.example.app1")).thenReturn(false) @@ -99,7 +99,7 @@ class TrackingProtectionAppsRepositoryTest { } @Test - fun whenGetAppProtectionStatusCalledOnEnabledAppButExcludedInNetpThenReturnUnprotectedThroughNetP() = runTest { + fun `getAppProtectionStatus - excluded in netp - unprotected through netp`() = runTest { whenever(packageManager.getApplicationInfo("com.example.app1", 0)) .thenReturn(ApplicationInfo().apply { packageName = "com.example.app1" }) whenever(networkProtectionExclusionList.isExcluded("com.example.app1")).thenReturn(true) @@ -110,7 +110,7 @@ class TrackingProtectionAppsRepositoryTest { } @Test - fun whenGetAppProtectionStatusCalledOnGameThenReturnUnprotected() = runTest { + fun `getAppProtectionStatus - game - returns unprotected`() = runTest { whenever(packageManager.getApplicationInfo("com.example.game", 0)) .thenReturn( ApplicationInfo().apply { @@ -126,7 +126,7 @@ class TrackingProtectionAppsRepositoryTest { } @Test - fun whenGetAppProtectionStatusCalledOnDdgAppThenReturnUnprotected() = runTest { + fun `getAppProtectionStatus - DdgApp - unprotected`() = runTest { whenever(packageManager.getApplicationInfo("com.duckduckgo.mobile.android.vpn.test", 0)) .thenReturn(ApplicationInfo().apply { packageName = "com.duckduckgo.mobile.android.vpn.test" }) whenever(networkProtectionExclusionList.isExcluded("com.duckduckgo.mobile.android.vpn.test")).thenReturn(false) @@ -137,7 +137,7 @@ class TrackingProtectionAppsRepositoryTest { } @Test - fun whenGetAppProtectionStatusCalledOnUnknownPackageThenReturnProtected() = runTest { + fun `getAppProtectionStatus - unknown package - protected`() = runTest { whenever(packageManager.getApplicationInfo("com.example.unknown", 0)) .thenReturn(ApplicationInfo().apply { packageName = "com.example.unknown" }) whenever(networkProtectionExclusionList.isExcluded("com.example.unknown")).thenReturn(false) @@ -148,7 +148,7 @@ class TrackingProtectionAppsRepositoryTest { } @Test - fun whenGetAppProtectionStatusCalledAndNameNotFoundExceptionIsThrownThenReturnProtected() = runTest { + fun `getAppProtectionStatus - NameNotFoundException thrown - return protected`() = runTest { whenever(packageManager.getApplicationInfo("com.example.unknown", 0)) .thenThrow(NameNotFoundException()) @@ -158,7 +158,7 @@ class TrackingProtectionAppsRepositoryTest { } @Test - fun whenManuallyEnabledAppThenRemoveFromExclusionList() = runTest { + fun `manuallyEnabledApp - remove from exclusion list`() = runTest { trackingProtectionAppsRepository.manuallyEnabledApp("com.example.app2") val exclusionList = trackingProtectionAppsRepository.getExclusionAppsList() @@ -167,7 +167,7 @@ class TrackingProtectionAppsRepositoryTest { } @Test - fun whenManuallyExcludedAppsThenReturnExcludedApps() = runTest { + fun `manuallyExcludedApps - return excluded apps`() = runTest { trackingProtectionAppsRepository.manuallyExcludedApps().test { assertEquals( listOf("com.example.app1" to true, "com.example.app2" to false, "com.example.app3" to false), @@ -178,7 +178,7 @@ class TrackingProtectionAppsRepositoryTest { } @Test - fun whenManuallyExcludeAppThenAddToExclusionList() = runTest { + fun `manuallyExcludeApp - getExclusionAppsList - addToExclusionList`() = runTest { trackingProtectionAppsRepository.manuallyExcludeApp("com.example.app1") val exclusionList = trackingProtectionAppsRepository.getExclusionAppsList() @@ -197,7 +197,7 @@ class TrackingProtectionAppsRepositoryTest { } @Test - fun whenRestoreDefaultProtectedListThenClearManualExclusionList() = runTest { + fun `restoreDefaultProtectedList - clear manual exclusion list`() = runTest { trackingProtectionAppsRepository.restoreDefaultProtectedList() val exclusionList = trackingProtectionAppsRepository.getExclusionAppsList() @@ -209,7 +209,7 @@ class TrackingProtectionAppsRepositoryTest { } @Test - fun whenGetAppsAndProtectionInfoThenReturnAppsWithProtectionInfo() = runTest { + fun `getAppsAndProtectionInfo - return apps with protection info`() = runTest { whenever(networkProtectionExclusionList.isExcluded(any())).thenReturn(false) trackingProtectionAppsRepository.getAppsAndProtectionInfo().test { assertEquals( @@ -230,7 +230,7 @@ class TrackingProtectionAppsRepositoryTest { } @Test - fun whenGetAppsAndProtectionInfoWithAppInNetpExclusionListThenReturnAppsWithProtectionInfo() = runTest { + fun `getAppsAndProtectionInfo - app in netp exclusion list - returns apps with protection info`() = runTest { whenever(networkProtectionExclusionList.isExcluded(any())).thenReturn(true) trackingProtectionAppsRepository.getAppsAndProtectionInfo().test { @@ -252,7 +252,7 @@ class TrackingProtectionAppsRepositoryTest { } @Test - fun whenGetAppsAndProtectionInfoWithAppInNetpExclusionListThenReturnAppsWithProtectionInfoWithCorrectKnownProblem() = runTest { + fun `getAppsAndProtectionInfo - app in netp exclusion list - return apps with protection info with correct known problem`() = runTest { whenever(networkProtectionExclusionList.isExcluded(any())).thenReturn(true) trackingProtectionAppsRepository.getAppsAndProtectionInfo().test { diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/breakage/ReportBreakageAppListViewModelTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/breakage/ReportBreakageAppListViewModelTest.kt index 930040bd4234..1797621edf0d 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/breakage/ReportBreakageAppListViewModelTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/breakage/ReportBreakageAppListViewModelTest.kt @@ -50,7 +50,7 @@ class ReportBreakageAppListViewModelTest { } @Test - fun whenOnSubmitBreakageAndNoSelectedItemThenEmitNoCommand() = runTest { + fun `onSubmitBreakage - no selected item - emit no command`() = runTest { viewModel.commands().test { viewModel.onSubmitBreakage() @@ -60,7 +60,7 @@ class ReportBreakageAppListViewModelTest { } @Test - fun whenOnSubmitBreakageAndAppSelectedThenEmitLaunchBreakageFormCommand() = runTest { + fun `onSubmitBreakage - app selected - emit launch breakage form command`() = runTest { viewModel.commands().test { val expectedItem = InstalledApp(packageName = "com.android.ddg", name = "ddg", isSelected = true) viewModel.onAppSelected(expectedItem) @@ -72,7 +72,7 @@ class ReportBreakageAppListViewModelTest { } @Test - fun whenGetInstalledAppsAndNoInstalledAppsThenEmitNoItem() = runTest { + fun `getInstalledApps - no installed apps - emit no item`() = runTest { whenever(trackingProtectionAppsRepository.getAppsAndProtectionInfo()).thenReturn(protectedAppsChannel.receiveAsFlow()) viewModel.getInstalledApps().test { expectNoEvents() @@ -80,7 +80,7 @@ class ReportBreakageAppListViewModelTest { } @Test - fun whenGetInstalledAppsThenEmitState() = runTest { + fun `getInstalledApps - emit state - report breakage app list view state`() = runTest { whenever(trackingProtectionAppsRepository.getAppsAndProtectionInfo()).thenReturn(protectedAppsChannel.receiveAsFlow()) viewModel.getInstalledApps().test { protectedAppsChannel.send(listOf(appWithoutIssues)) @@ -95,7 +95,7 @@ class ReportBreakageAppListViewModelTest { } @Test - fun whenGetInstalledAppsAndSelectedAppThenEmitState() = runTest { + fun `getInstalledApps - selected app - emit state`() = runTest { whenever(trackingProtectionAppsRepository.getAppsAndProtectionInfo()).thenReturn(protectedAppsChannel.receiveAsFlow()) viewModel.getInstalledApps().test { viewModel.onAppSelected(InstalledApp(packageName = appWithIssues.packageName, name = appWithIssues.name)) @@ -112,7 +112,7 @@ class ReportBreakageAppListViewModelTest { } @Test - fun whenGetInstalledAppsAndUnknownSelectedAppThenEmitState() = runTest { + fun `getInstalledApps - unknown selected app - emit state`() = runTest { whenever(trackingProtectionAppsRepository.getAppsAndProtectionInfo()).thenReturn(protectedAppsChannel.receiveAsFlow()) viewModel.getInstalledApps().test { viewModel.onAppSelected(InstalledApp(packageName = "unknown.package.name", name = appWithIssues.name)) @@ -129,7 +129,7 @@ class ReportBreakageAppListViewModelTest { } @Test - fun whenOnBreakageSubmittedNoExtraInfoThenEmitSendBreakageInfoCommand() = runTest { + fun `onBreakageSubmitted - no extra info - emit send breakage info command`() = runTest { viewModel.commands().test { val selectedApp = InstalledApp("com.package.com", name = "AppName") viewModel.onAppSelected(selectedApp) @@ -145,7 +145,7 @@ class ReportBreakageAppListViewModelTest { } @Test - fun whenOnBreakageSubmittedWithExtraInfoThenEmitSendBreakageInfoCommand() = runTest { + fun `onBreakageSubmitted - with extra info - emit send breakage info command`() = runTest { viewModel.commands().test { val selectedApp = InstalledApp("com.package.com", name = "AppName") viewModel.onAppSelected(selectedApp) diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/breakage/ReportBreakageCategorySingleChoiceViewModelTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/breakage/ReportBreakageCategorySingleChoiceViewModelTest.kt index 94dcfc42293f..60e2c9841f0d 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/breakage/ReportBreakageCategorySingleChoiceViewModelTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/breakage/ReportBreakageCategorySingleChoiceViewModelTest.kt @@ -57,30 +57,30 @@ class ReportBreakageCategorySingleChoiceViewModelTest { } @Test - fun whenInitializedThenCannotSubmit() { + fun `initialized - view state submit not allowed`() { assertFalse(viewState.submitAllowed) } @Test - fun whenCategorySelectedThenCanSubmit() { + fun `selectAndAcceptCategory - view state updated - can submit`() { selectAndAcceptCategory() assertTrue(viewState.submitAllowed) } @Test - fun whenCategoryChangedButNotSelectedThenCannotSubmit() { + fun `onCategoryIndexChanged - view state updated - cannot submit`() { viewModel.onCategoryIndexChanged(0) assertFalse(viewState.submitAllowed) } @Test - fun whenNoCategorySelectedThenCannotSubmit() { + fun `selectAndAcceptCategory - view state submit not allowed`() { selectAndAcceptCategory(-1) assertFalse(viewState.submitAllowed) } @Test - fun whenCategorySelectedButNotChangedThenReturnOldCategory() { + fun `onCategoryIndexChanged - category not changed - return old category`() { viewModel.onCategoryIndexChanged(0) viewModel.onCategoryAccepted() viewModel.onCategoryIndexChanged(1) @@ -88,13 +88,13 @@ class ReportBreakageCategorySingleChoiceViewModelTest { } @Test - fun whenCategoryAcceptedAndIncorrectIndexThenReturnNullCategory() { + fun `selectAndAcceptCategory - category accepted and incorrect index - return null category`() { selectAndAcceptCategory(-1) assertNull(viewState.categorySelected) } @Test - fun whenCategoryAcceptedAndCorrectIndexThenReturnCategory() { + fun `selectAndAcceptCategory - category accepted and correct index - return category`() { val indexSelected = 0 selectAndAcceptCategory(indexSelected) @@ -102,7 +102,7 @@ class ReportBreakageCategorySingleChoiceViewModelTest { } @Test - fun whenCancelSelectionThenAssignOldIndexValue() { + fun `onCategorySelectionCancelled - index selected - 0`() { selectAndAcceptCategory(0) viewModel.onCategoryIndexChanged(1) viewModel.onCategorySelectionCancelled() @@ -111,7 +111,7 @@ class ReportBreakageCategorySingleChoiceViewModelTest { } @Test - fun whenCancelSelectionAndNoPreviousValueThenAssignMinusOne() { + fun `onCategorySelectionCancelled - no previous value - assign minus one`() { viewModel.onCategoryIndexChanged(1) viewModel.onCategorySelectionCancelled() @@ -119,7 +119,7 @@ class ReportBreakageCategorySingleChoiceViewModelTest { } @Test - fun whenOnSubmitPressedAndCategorySelectedThenEmitConfirmAndFinishCommand() = runTest { + fun `onSubmitPressed - category selected - confirm and finish command`() = runTest { selectAndAcceptCategory() viewModel.commands().test { diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/breakage/ReportBreakageContractTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/breakage/ReportBreakageContractTest.kt index 53d6a153b7ce..d261c4ff2562 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/breakage/ReportBreakageContractTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/breakage/ReportBreakageContractTest.kt @@ -37,7 +37,7 @@ class ReportBreakageContractTest { private val context = InstrumentationRegistry.getInstrumentation().targetContext @Test - fun whenCreateIntentForIssueDescriptionFormThenReturnCorrectIntent() { + fun `createIntent - whenCreateIntentForIssueDescriptionFormThenReturnCorrectIntent - return correct intent`() { whenever(globalActivityStarter.startIntent(any(), any())) .thenReturn(Intent(context, ReportBreakageCategorySingleChoiceActivity::class.java)) @@ -48,7 +48,7 @@ class ReportBreakageContractTest { } @Test - fun whenCreateIntentForListOfInstalledAppsThenReturnCorrectIntent() { + fun `createIntent - listOfInstalledApps - returns correct intent`() { whenever(globalActivityStarter.startIntent(context, OpenVpnReportBreakageFrom(ORIGIN, emptyList()))) .thenReturn(Intent(context, ReportBreakageAppListActivity::class.java)) diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/bugreport/DeviceInfoCollectorTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/bugreport/DeviceInfoCollectorTest.kt index 79ce1147f6f6..bb8b6deb713e 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/bugreport/DeviceInfoCollectorTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/bugreport/DeviceInfoCollectorTest.kt @@ -46,7 +46,7 @@ class DeviceInfoCollectorTest { } @Test - fun whenCollectVpnRelatedStateThenReturnDeviceInfo() = runTest { + fun `collectVpnRelatedState - return device info`() = runTest { val state = deviceInfoCollector.collectVpnRelatedState() assertEquals("deviceInfo", deviceInfoCollector.collectorName) @@ -58,7 +58,7 @@ class DeviceInfoCollectorTest { } @Test - fun whenIgnoringBatteryOptimizationsThenReportBatteryOptimizationsTrue() = runTest { + fun `collectVpnRelatedState - ignoring battery optimizations - report battery optimizations true`() = runTest { val state = DeviceInfoCollector(appBuildConfig, { true }).collectVpnRelatedState() assertEquals("deviceInfo", deviceInfoCollector.collectorName) diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/bugreport/VpnAppTrackerListInfoCollectorTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/bugreport/VpnAppTrackerListInfoCollectorTest.kt index 9d03fa9f637f..d7771b60cdc1 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/bugreport/VpnAppTrackerListInfoCollectorTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/bugreport/VpnAppTrackerListInfoCollectorTest.kt @@ -47,14 +47,14 @@ class VpnAppTrackerListInfoCollectorTest { } @Test - fun whenCollectStateAndBlocklistEtagNotPesentThenJsonEtagIsEmpty() = runTest { + fun `collect - state and blocklist etag not present - json etag is empty`() = runTest { val jsonObject = collector.collectVpnRelatedState(PACKAGE_ID) assertEquals("", jsonObject.get("appTrackerListEtag")) } @Test - fun whenCollectStateAndBlocklistEtagPesentThenJsonEtagHasValue() = runTest { + fun `collect - state and blocklist etag present - json etag has value`() = runTest { whenever(vpnAppTrackerBlockingDao.getTrackerBlocklistMetadata()).thenReturn(AppTrackerMetadata(0, "etag")) val jsonObject = collector.collectVpnRelatedState(PACKAGE_ID) @@ -62,14 +62,14 @@ class VpnAppTrackerListInfoCollectorTest { } @Test - fun whenCollectStateAndExclusionListEtagNotPresentThenJsonEtagIsEmpty() = runTest { + fun `collect - state and exclusion list etag not present - json etag is empty`() = runTest { val jsonObject = collector.collectVpnRelatedState(PACKAGE_ID) assertEquals("", jsonObject.get("appExclusionListEtag")) } @Test - fun whenCollectStateAndExclusionListEtagPresentThenJsonEtagHasValue() = runTest { + fun `collect - state and exclusion list etag present - json etag has value`() = runTest { whenever(vpnAppTrackerBlockingDao.getExclusionListMetadata()).thenReturn(AppTrackerExclusionListMetadata(0, "etag")) val jsonObject = collector.collectVpnRelatedState(PACKAGE_ID) @@ -77,14 +77,14 @@ class VpnAppTrackerListInfoCollectorTest { } @Test - fun whenCollectStateAndExclusionRuleListEtagNotPresentThenJsonEtagIsEmpty() = runTest { + fun `collect - state and exclusion rule list etag not present - json etag is empty`() = runTest { val jsonObject = collector.collectVpnRelatedState(PACKAGE_ID) assertEquals("", jsonObject.get("appExceptionRuleListEtag")) } @Test - fun whenCollectStateAndExclusionRuleListEtagPresentThenJsonEtagHasValue() = runTest { + fun `collect - state and exclusion rule list etag present - json etag has value`() = runTest { whenever(vpnAppTrackerBlockingDao.getTrackerExceptionRulesMetadata()).thenReturn(AppTrackerExceptionRuleMetadata(0, "etag")) val jsonObject = collector.collectVpnRelatedState(PACKAGE_ID) @@ -92,14 +92,14 @@ class VpnAppTrackerListInfoCollectorTest { } @Test - fun whenCollectStateAndAppNotGameOrInExclusionListThenReturnUnprotectedByDefaultFalse() = runTest { + fun `collect - state and app not game or in exclusion list - return unprotected by default false`() = runTest { val jsonObject = collector.collectVpnRelatedState(PACKAGE_ID) assertEquals("false", jsonObject.get("reportedAppUnprotectedByDefault")) } @Test - fun whenCollectStateAndProtectionOverridenThenOverridenDefaultProtectionTrue() = runTest { + fun `collect - state and protection overridden - overriden default protection true`() = runTest { whenever(appTrackerRepository.getManualAppExclusionList()).thenReturn(listOf((AppTrackerManualExcludedApp(PACKAGE_ID, true)))) val jsonObject = collector.collectVpnRelatedState(PACKAGE_ID) @@ -107,7 +107,7 @@ class VpnAppTrackerListInfoCollectorTest { } @Test - fun whenCollectStateAndProtectionOverridenThenOverridenDefaultProtectionFalse() = runTest { + fun `collect - state and protection overridden - overriden default protection false`() = runTest { whenever(appTrackerRepository.getManualAppExclusionList()).thenReturn(listOf((AppTrackerManualExcludedApp("other.package.id", true)))) val jsonObject = collector.collectVpnRelatedState(PACKAGE_ID) diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/cohort/CohortPixelInterceptorTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/cohort/CohortPixelInterceptorTest.kt index c49ad1505e07..1921a097108d 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/cohort/CohortPixelInterceptorTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/cohort/CohortPixelInterceptorTest.kt @@ -67,7 +67,7 @@ class CohortPixelInterceptorTest { } @Test - fun whenCohortNotSetPixelDropped() { + fun `getCohortNotSet - pixel dropped`() { Assert.assertNull(cohortStore.getCohortStoredLocalDate()) val pixelUrl = String.format(PIXEL_TEMPLATE, "m_atp_ev_restart_c") @@ -78,7 +78,7 @@ class CohortPixelInterceptorTest { } @Test - fun whenCohortSetPixelFired() { + fun `setCohort - pixel fired - cohort calculated`() { val date = LocalDate.now().plusDays(3) cohortStore.setCohortLocalDate(date) @@ -92,7 +92,7 @@ class CohortPixelInterceptorTest { } @Test - fun whenCohortSetPixelFiredCohortRemovedForException() { + fun `intercept - cohort set pixel fired - cohort removed for exception`() { val date = LocalDate.now().plusDays(3) cohortStore.setCohortLocalDate(date) diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/cohort/RealCohortCalculatorTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/cohort/RealCohortCalculatorTest.kt index c3c987da5d1c..ad12c4ef1925 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/cohort/RealCohortCalculatorTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/cohort/RealCohortCalculatorTest.kt @@ -32,7 +32,7 @@ class RealCohortCalculatorTest { } @Test - fun whenLocalDateIsFirstDayOfLastDayOf2021ThenReturnWeeklyCohort() { + fun `calculateCohortForDate - local date is first day of last day of 2021 - return weekly cohort`() { val date = LocalDate.of(2022, 1, 1) val now = date.plusWeeks(3) @@ -42,7 +42,7 @@ class RealCohortCalculatorTest { } @Test - fun whenLocalDateIsFirstDayOfLastDayOf2021ThenReturnMonthlyCohort() { + fun `calculateCohort - local date first day of last day of 2021 - return monthly cohort`() { val date = LocalDate.of(2022, 1, 1) val now = date.plusWeeks(12) @@ -51,7 +51,7 @@ class RealCohortCalculatorTest { } @Test - fun whenLocalDateIsFirstDayOfLastDayOf2021ThenReturnQuarterCohort() { + fun `calculateCohortForDate - local date is first day of last day of 2021 - return quarter cohort`() { val date = LocalDate.of(2022, 1, 1) val now = date.plusWeeks(25) @@ -60,7 +60,7 @@ class RealCohortCalculatorTest { } @Test - fun whenLocalDateIsFirstDayOfLastDayOf2021ThenReturnHalfYearCohort() { + fun `calculateCohortForDate - local date first day of last day of 2021 - return half year cohort`() { val date = LocalDate.of(2022, 1, 1) val now = date.plusWeeks(51) @@ -69,7 +69,7 @@ class RealCohortCalculatorTest { } @Test - fun whenLocalDateIsFirstDayOfLastDayOf2021ThenReturnUniqueCohort() { + fun `calculateCohort - local date first day of last day of 2021 - return unique cohort`() { val date = LocalDate.of(2022, 1, 1) val now = date.plusWeeks(53) @@ -78,49 +78,49 @@ class RealCohortCalculatorTest { } @Test - fun whenLocalDateNowThenReturnWeeklyCohort() { + fun `calculateCohortForDate - local date now - weekly cohort`() { val date = LocalDate.now() val year = date.year assertEquals("$year-week-${date.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR)}", cohortCalculator.calculateCohortForDate(date)) } @Test - fun whenLocalDate4WeeksAgoThenReturnWeeklyCohort() { + fun `calculateCohortForDate - local date 4 weeks ago - weekly cohort`() { val date = LocalDate.now().minusWeeks(4) val year = date.get(IsoFields.WEEK_BASED_YEAR) assertEquals("$year-week-${date.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR)}", cohortCalculator.calculateCohortForDate(date)) } @Test - fun whenLocalDateMoreThan4WeeksAgoThenReturnMonthCohort() { + fun `calculateCohortForDate - local date more than 4 weeks ago - return month cohort`() { val date = LocalDate.now().minusWeeks(5) val year = date.year assertEquals("$year-${date.month}", cohortCalculator.calculateCohortForDate(date)) } @Test - fun whenLocalDate13WeeksAgoThenReturnMonthCohort() { + fun `calculateCohortForDate - local date 13 weeks ago - return month cohort`() { val date = LocalDate.now().minusWeeks(13) val year = date.year assertEquals("$year-${date.month}", cohortCalculator.calculateCohortForDate(date)) } @Test - fun whenLocalDateMoreThan13WeeksAgoThenReturnQuarterCohort() { + fun `calculateCohortForDate - local date more than 13 weeks ago - return quarter cohort`() { val date = LocalDate.now().minusWeeks(14) val year = date.year assertEquals("$year-q${date.get(IsoFields.QUARTER_OF_YEAR)}", cohortCalculator.calculateCohortForDate(date)) } @Test - fun whenLocalDate26WeeksAgoThenReturnQuarterCohort() { + fun `calculateCohortForDate - local date 26 weeks ago - quarter cohort`() { val date = LocalDate.now().minusWeeks(26) val year = date.year assertEquals("$year-q${date.get(IsoFields.QUARTER_OF_YEAR)}", cohortCalculator.calculateCohortForDate(date)) } @Test - fun whenLocalDateMoreThan26WeeksAgoThenReturnHalfCohort() { + fun `calculateCohortForDate - local date more than 26 weeks ago - return half cohort`() { val date = LocalDate.now().minusWeeks(27) val year = date.year val half = if (date.monthValue > 6) "2" else "1" diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/cohort/RealCohortStoreTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/cohort/RealCohortStoreTest.kt index 1ad2f76d9a47..21d9260eb6a0 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/cohort/RealCohortStoreTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/cohort/RealCohortStoreTest.kt @@ -66,12 +66,12 @@ class RealCohortStoreTest { } @Test - fun whenCohortNotSetThenReturnNull() { + fun `getCohort - cohort not set - null`() { assertNull(cohortStore.getCohortStoredLocalDate()) } @Test - fun whenSetCohortLocalDateThenStoredCorrectly() { + fun `setCohortLocalDate - stored correctly`() { val date = LocalDate.now().plusDays(3) cohortStore.setCohortLocalDate(date) @@ -79,7 +79,7 @@ class RealCohortStoreTest { } @Test - fun whenInitialCohortFirstCalledThenStoreInitialCohort() = runTest { + fun `whenInitialCohortFirstCalled - store initial cohort - stored local date`() = runTest { vpnFeaturesRegistry.registerFeature(AppTpVpnFeature.APPTP_VPN) (cohortStore as RealCohortStore).onVpnStarted(TestScope()) @@ -87,7 +87,7 @@ class RealCohortStoreTest { } @Test - fun whenInitialCohortSubsequentCalledThenNoop() = runTest { + fun `registerFeature - subsequent cohort called - no-op`() = runTest { vpnFeaturesRegistry.registerFeature(AppTpVpnFeature.APPTP_VPN) val date = LocalDate.now().plusDays(3) cohortStore.setCohortLocalDate(date) @@ -98,14 +98,14 @@ class RealCohortStoreTest { } @Test - fun whenAppTpNotRegisteredThenDoNothingWithCohort() { + fun `getCohort - app tp not registered - do nothing with cohort`() { (cohortStore as RealCohortStore).onVpnStarted(TestScope()) assertNull(cohortStore.getCohortStoredLocalDate()) } @Test - fun whenVpnReconfiguredCalledThenStoreInitialCohort() = runTest { + fun `whenVpnReconfiguredCalled - store initial cohort - cohort stored`() = runTest { vpnFeaturesRegistry.registerFeature(AppTpVpnFeature.APPTP_VPN) (cohortStore as RealCohortStore).onVpnReconfigured(TestScope()) diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/feature/AppTpRemoteFeaturesStoreTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/feature/AppTpRemoteFeaturesStoreTest.kt index ebae5459a34a..7514c3faeb7a 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/feature/AppTpRemoteFeaturesStoreTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/feature/AppTpRemoteFeaturesStoreTest.kt @@ -51,7 +51,7 @@ class AppTpRemoteFeaturesStoreTest { } @Test - fun `test value set`() { + fun `set - remote features store updated`() { val expected = Toggle.State(enable = true) appTpRemoteFeaturesStore.set("key", expected) @@ -59,12 +59,12 @@ class AppTpRemoteFeaturesStoreTest { } @Test - fun `test get when value is missing`() { + fun `get - value is missing - null`() { assertNull(appTpRemoteFeaturesStore.get("key")) } @Test - fun `test get when value is not present`() { + fun `get - value not present - null`() { val expected = Toggle.State(enable = true) appTpRemoteFeaturesStore.set("key", expected) @@ -72,7 +72,7 @@ class AppTpRemoteFeaturesStoreTest { } @Test - fun `test load values`() { + fun `loadValues - state loaded`() { val expected = Toggle.State(enable = true) // use this store just to populate the preferences appTpRemoteFeaturesStore.set("key", expected) @@ -104,7 +104,7 @@ class AppTpRemoteFeaturesStoreTest { } @Test - fun `test preference change propagation`() { + fun `test preference change propagation - state updated`() { val adapter = Moshi.Builder().add(KotlinJsonAdapterFactory()).build().adapter(State::class.java) assertNull(appTpRemoteFeaturesStore.get("key")) diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/feature/settings/ExceptionListsSettingStoreTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/feature/settings/ExceptionListsSettingStoreTest.kt index 448b36495f15..4d7579a78d17 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/feature/settings/ExceptionListsSettingStoreTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/feature/settings/ExceptionListsSettingStoreTest.kt @@ -95,13 +95,13 @@ class ExceptionListsSettingStoreTest { } @Test - fun whenEmptyJsonStoreNothing() { + fun `store - empty json store nothing - no interactions`() { exceptionListsSettingStore.store("") verifyNoInteractions(mockVpnDatabase) } @Test - fun whenValidJSONUpdatesDB() = runTest { + fun `store - valid json updates db - updates tracker exception rules and exclusion list and system app overrides`() = runTest { exceptionListsSettingStore = ExceptionListsSettingStore( mockVpnDatabase, coroutineRule.testScope, diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/health/AppTPCPUMonitorTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/health/AppTPCPUMonitorTest.kt index 01a31e52694c..57c3e6c8df84 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/health/AppTPCPUMonitorTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/health/AppTPCPUMonitorTest.kt @@ -90,12 +90,12 @@ class AppTPCPUMonitorTest { } @Test - fun whenConfigEnabledStartWorker() { + fun `whenConfigEnabled - start worker`() { assertStartWorker() } @Test - fun whenVPNStoppedStopWorker() { + fun `onVpnStopped - stop worker`() { assertStartWorker() cpuMonitor.onVpnStopped(coroutineRule.testScope, SELF_STOP()) @@ -123,7 +123,7 @@ class AppTPCPUMonitorTest { } @Test - fun whenCPUBelow5NoAlert() { + fun `readCPUUsage - CPU below 5 - no alert`() { whenever(mockCPUUsageReader.readCPUUsage()).thenReturn(2.0) assertStartWorker() diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/integration/NgVpnNetworkStackTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/integration/NgVpnNetworkStackTest.kt index 8476c5a6ec49..f2f5f2e1aa99 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/integration/NgVpnNetworkStackTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/integration/NgVpnNetworkStackTest.kt @@ -79,19 +79,19 @@ class NgVpnNetworkStackTest { } @Test - fun whenOnCreateVpnNoErrorThenReturnSuccess() { + fun `onCreateVpn - no error - return success`() { assertTrue(ngVpnNetworkStack.onCreateVpn().isSuccess) } @Test - fun whenOnCreateVpnThenCreateVpnNetwork() { + fun `onCreateVpn - create vpn network`() { ngVpnNetworkStack.onCreateVpn() verify(vpnNetwork).create() } @Test - fun whenOnCreateVpnMultipleTimesThenDestroyPreviousNetwork() { + fun `onCreateVpn - multiple times - destroy previous network`() { ngVpnNetworkStack.onCreateVpn() ngVpnNetworkStack.onCreateVpn() @@ -100,7 +100,7 @@ class NgVpnNetworkStackTest { } @Test - fun whenOnCreateVpnMultipleTimesThenCreateVpnNetwork() { + fun `onCreateVpn - multiple times - create vpn network`() { ngVpnNetworkStack.onCreateVpn() ngVpnNetworkStack.onCreateVpn() @@ -108,7 +108,7 @@ class NgVpnNetworkStackTest { } @Test - fun whenOnPrepareVpnThenReturnCorrectVpnTunnelConfig() = runTest { + fun `onPrepareVpn - returns correct vpn tunnel config`() = runTest { whenever(appBuildConfig.model).thenReturn("") whenever(trackingProtectionAppsRepository.getExclusionAppsList()).thenReturn(listOf()) @@ -129,7 +129,7 @@ class NgVpnNetworkStackTest { } @Test - fun whenMotoGPlayThenConfigureSystemDns() = runTest { + fun `onPrepareVpn - moto g play - configure system dns`() = runTest { whenever(appBuildConfig.model).thenReturn("moto g play - 2023") fakeDnsProvider.mutableSystemDns.add(InetAddress.getLocalHost()) whenever(trackingProtectionAppsRepository.getExclusionAppsList()).thenReturn(listOf()) @@ -151,7 +151,7 @@ class NgVpnNetworkStackTest { } @Test - fun whenMotoGPowerThenConfigureSystemDns() = runTest { + fun `onPrepareVpn - moto g power - configure system dns`() = runTest { whenever(appBuildConfig.model).thenReturn("moto g stylus 5G") fakeDnsProvider.mutableSystemDns.add(InetAddress.getLocalHost()) whenever(trackingProtectionAppsRepository.getExclusionAppsList()).thenReturn(listOf()) @@ -173,7 +173,7 @@ class NgVpnNetworkStackTest { } @Test - fun whenPrivateDnsSetAndDeviceModelMatchesThenConfigureEmptyDns() = runTest { + fun `onPrepareVpn - private dns set and device model matches - configure empty dns`() = runTest { whenever(appBuildConfig.model).thenReturn("moto g stylus 5G") fakeDnsProvider.mutablePrivateDns.add(InetAddress.getLocalHost()) fakeDnsProvider.mutableSystemDns.add(InetAddress.getLocalHost()) @@ -196,7 +196,7 @@ class NgVpnNetworkStackTest { } @Test - fun whenDeviceModelNotMatchedThenConfigureEmptyDns() = runTest { + fun `onPrepareVpn - device model not matched - configure empty dns`() = runTest { whenever(appBuildConfig.model).thenReturn("wrong device") fakeDnsProvider.mutableSystemDns.add(InetAddress.getLocalHost()) whenever(trackingProtectionAppsRepository.getExclusionAppsList()).thenReturn(listOf()) @@ -218,7 +218,7 @@ class NgVpnNetworkStackTest { } @Test - fun whenMotoGAndPrivateDnsSetThenReturnNoDns() = runTest { + fun `onPrepareVpn - moto g play - return no dns`() = runTest { whenever(appBuildConfig.model).thenReturn("moto g play") fakeDnsProvider.mutableSystemDns.add(InetAddress.getLocalHost()) fakeDnsProvider.mutablePrivateDns.add(InetAddress.getLocalHost()) @@ -241,7 +241,7 @@ class NgVpnNetworkStackTest { } @Test - fun whenShortListedDeviceThenReturnSearchDomains() = runTest { + fun `onPrepareVpn - when shortlisted device - return search domains`() = runTest { whenever(appBuildConfig.model).thenReturn("moto g play") fakeDnsProvider.searchDomain = "internal.com" whenever(trackingProtectionAppsRepository.getExclusionAppsList()).thenReturn(listOf()) @@ -264,7 +264,7 @@ class NgVpnNetworkStackTest { } @Test - fun whenNotShortListedDeviceThenReturnSearchDomains() = runTest { + fun `onPrepareVpn - not short listed device - return search domains`() = runTest { whenever(appBuildConfig.model).thenReturn("wrong device") fakeDnsProvider.mutableSystemDns.add(InetAddress.getLocalHost()) fakeDnsProvider.searchDomain = "internal.com" @@ -288,14 +288,14 @@ class NgVpnNetworkStackTest { } @Test - fun whenOnEmFileErrorThenKillProcess() { + fun `onError - on Em file error - kill process`() { ngVpnNetworkStack.onError(24, "EmFileError") verify(runtime).exit(0) } @Test - fun whenOnAnyErrorOtherThanEmFileThenNoop() { + fun `onAnyErrorOtherThanEmFile - noop`() { for (error in 0..23) { ngVpnNetworkStack.onError(error, "SomeError") verify(runtime, never()).exit(0) @@ -308,14 +308,14 @@ class NgVpnNetworkStackTest { } @Test - fun whenOnExitThenKillProcess() { + fun `onExit - runtime exit`() { ngVpnNetworkStack.onExit("SomeError") verify(runtime).exit(0) } @Test - fun whenIsAddressBlockedAndDomainIsTrackerThenReturnFalse() { // false because we don't want to block based on IP addresses + fun `onDnsResolved - is address blocked - false`() { // false because we don't want to block based on IP addresses val uid = 1200 val tracker = AppTrackerDetector.AppTracker( "hostname", @@ -332,7 +332,7 @@ class NgVpnNetworkStackTest { } @Test - fun whenIsAddressBlockedAndDomainIsNotTrackerThenReturnFalse() { + fun `isAddressBlocked - domain is not tracker - returns false`() { val uid = 1200 whenever(appTrackerDetector.evaluate(TRACKER_HOSTNAME, uid)).thenReturn(null) diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/integration/VpnNetworkStackProviderTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/integration/VpnNetworkStackProviderTest.kt index facd3bc5f449..63b43bedd00e 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/integration/VpnNetworkStackProviderTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/integration/VpnNetworkStackProviderTest.kt @@ -47,12 +47,12 @@ class VpnNetworkStackProviderTest { } @Test - fun whenProvideNetworkStackAndNoFeaturesRegisteredThenThrowsException() = runTest { + fun `provideNetworkStack - no features registered - throws exception`() = runTest { assertEquals(VpnNetworkStack.EmptyVpnNetworkStack, vpnNetworkStackProvider.provideNetworkStack()) } @Test - fun whenProviderNetworkStackAndAppTpRegisteredThenReturnNetworkStack() = runTest { + fun `registerAppTp - return network stack`() = runTest { vpnFeaturesRegistry.registerFeature(AppTpVpnFeature.APPTP_VPN) val networkStack = vpnNetworkStackProvider.provideNetworkStack() @@ -60,14 +60,14 @@ class VpnNetworkStackProviderTest { } @Test - fun whenProviderNetworkStackAndUnknownFeatureRegisteredThenThrowsException() = runTest { + fun `provideNetworkStack - provider network stack and unknown feature registered - throws exception`() = runTest { vpnFeaturesRegistry.registerFeature(VpnFeature { "unknown" }) vpnNetworkStackProvider.provideNetworkStack() assertEquals(VpnNetworkStack.EmptyVpnNetworkStack, vpnNetworkStackProvider.provideNetworkStack()) } @Test - fun whenProviderNetworkStackAndFeaturesContainAppTpThenReturnNetworkStack() = runTest { + fun `provideNetworkStack - provider network stack and features contain app tp - return network stack`() = runTest { vpnFeaturesRegistry.registerFeature(VpnFeature { "unknown" }) vpnFeaturesRegistry.registerFeature(AppTpVpnFeature.APPTP_VPN) diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/pixels/DeviceShieldPixelNamesTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/pixels/DeviceShieldPixelNamesTest.kt index b9149999523f..a916536ec08e 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/pixels/DeviceShieldPixelNamesTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/pixels/DeviceShieldPixelNamesTest.kt @@ -21,7 +21,7 @@ import org.junit.Test class DeviceShieldPixelNamesTest { @Test - fun allAppTrackingProtectionPixelsShallBePrefixed() { + fun `allAppTrackingProtectionPixelsShallBePrefixed - all app tracking protection pixels prefixed`() { DeviceShieldPixelNames.values().map { it.pixelName }.forEach { pixel -> assertTrue(pixel.startsWith("m_atp") || pixel.startsWith("m_vpn")) } diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/pixels/RealDeviceShieldPixelsTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/pixels/RealDeviceShieldPixelsTest.kt index 0a093e0c4860..3e672ea58d25 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/pixels/RealDeviceShieldPixelsTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/pixels/RealDeviceShieldPixelsTest.kt @@ -42,7 +42,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenDeviceShieldEnabledOnSearchThenFireDailyPixel() { + fun `deviceShieldEnabledOnSearch - fire daily pixel`() { deviceShieldPixels.deviceShieldEnabledOnSearch() deviceShieldPixels.deviceShieldEnabledOnSearch() @@ -51,7 +51,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenDeviceShieldDisabledOnSearchThenFireDailyPixel() { + fun `whenDeviceShieldDisabledOnSearch - fire daily pixel`() { deviceShieldPixels.deviceShieldDisabledOnSearch() deviceShieldPixels.deviceShieldDisabledOnSearch() @@ -60,7 +60,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenReportEnableThenFireUniqueAndDailyPixel() { + fun `reportEnable - fire unique and daily pixel`() { deviceShieldPixels.reportEnabled() deviceShieldPixels.reportEnabled() @@ -70,7 +70,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenReportDisableThenFireDailyPixel() { + fun `reportDisable - fire daily pixel`() { deviceShieldPixels.reportDisabled() deviceShieldPixels.reportDisabled() @@ -79,7 +79,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenEnableFromReminderNotificationThenFireUniqueDailyAndCountPixels() { + fun `enableFromReminderNotification - fire unique daily and count pixels`() { deviceShieldPixels.enableFromReminderNotification() deviceShieldPixels.enableFromReminderNotification() @@ -90,7 +90,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenEnableFromSettingsThenFireUniqueDailyAndCountPixels() { + fun `enableFromSettings - fire unique daily and count pixels`() { deviceShieldPixels.enableFromOnboarding() deviceShieldPixels.enableFromOnboarding() @@ -101,7 +101,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenEnableFromSettingsTileThenFireUniqueDailyAndCountPixels() { + fun `enableFromSettingsTile - fire unique daily and count pixels`() { deviceShieldPixels.enableFromQuickSettingsTile() deviceShieldPixels.enableFromQuickSettingsTile() @@ -112,7 +112,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenEnableFromPrivacyReportThenFireUniqueDailyAndCountPixels() { + fun `enableFromPrivacyReport - fire unique daily and count pixels`() { deviceShieldPixels.enableFromSummaryTrackerActivity() deviceShieldPixels.enableFromSummaryTrackerActivity() @@ -123,7 +123,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenDisableFromSettingsTileThenFireDailyAndCountPixels() { + fun `disableFromSettingsTile - fire daily and count pixels`() { deviceShieldPixels.disableFromQuickSettingsTile() deviceShieldPixels.disableFromQuickSettingsTile() @@ -133,7 +133,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenDidShowDailyNotificationThenFireDailyPixel() { + fun `didShowDailyNotification - fire daily pixel`() { deviceShieldPixels.didShowDailyNotification(0) deviceShieldPixels.didShowDailyNotification(1) @@ -143,7 +143,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenDidPressDailyNotificationThenFireDailyPixel() { + fun `didPressDailyNotification - pixel fired`() { deviceShieldPixels.didPressOnDailyNotification(0) deviceShieldPixels.didPressOnDailyNotification(1) @@ -153,7 +153,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenDidShowWeeklyNotificationThenFireDailyPixel() { + fun `didShowWeeklyNotification - fire daily pixel`() { deviceShieldPixels.didShowWeeklyNotification(0) deviceShieldPixels.didShowWeeklyNotification(1) @@ -163,7 +163,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenDidPressWeeklyNotificationThenFireDailyPixel() { + fun `didPressWeeklyNotification - pixel fired`() { deviceShieldPixels.didPressOnWeeklyNotification(0) deviceShieldPixels.didPressOnWeeklyNotification(1) @@ -173,7 +173,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenDidPressOngoingNotificationThenFireDailyAndCountPixels() { + fun `didPressOngoingNotification - fire daily and count pixels`() { deviceShieldPixels.didPressOngoingNotification() deviceShieldPixels.didPressOngoingNotification() @@ -183,7 +183,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenDidShowReminderNotificationThenFireDailyAndCountPixels() { + fun `didShowReminderNotification - fire daily and count pixels`() { deviceShieldPixels.didShowReminderNotification() deviceShieldPixels.didShowReminderNotification() @@ -193,7 +193,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenDidPressReminderNotificationThenFireDailyAndCountPixels() { + fun `didPressReminderNotification - fire daily and count pixels`() { deviceShieldPixels.didPressReminderNotification() deviceShieldPixels.didPressReminderNotification() @@ -203,7 +203,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenDidShowNewTabSummaryThenFireUniqueDailyAndCountPixels() { + fun `didShowNewTabSummary - fire unique daily and count pixels`() { deviceShieldPixels.didShowNewTabSummary() deviceShieldPixels.didShowNewTabSummary() @@ -214,7 +214,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenDidPressNewTabSummaryThenFireDailyAndCountPixels() { + fun `didPressNewTabSummary - fire daily and count pixels`() { deviceShieldPixels.didPressNewTabSummary() deviceShieldPixels.didPressNewTabSummary() @@ -224,7 +224,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenDidShowSummaryTrackerActivityThenFireUniqueDailyAndCountPixels() { + fun `didShowSummaryTrackerActivity - fire unique daily and count pixels`() { deviceShieldPixels.didShowSummaryTrackerActivity() deviceShieldPixels.didShowSummaryTrackerActivity() @@ -235,7 +235,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenDidShowDetailedTrackerActivityThenFireUniqueDailyAndCountPixels() { + fun `didShowDetailedTrackerActivity - fire unique daily and count pixels`() { deviceShieldPixels.didShowDetailedTrackerActivity() deviceShieldPixels.didShowDetailedTrackerActivity() @@ -246,7 +246,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenStartErrorThenFireDailyAndCountPixels() { + fun `startError - fire daily and count pixels`() { deviceShieldPixels.startError() deviceShieldPixels.startError() @@ -257,7 +257,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenAutomaticRestartThenFireDailyAndCountPixels() { + fun `automaticRestart - fire daily and count pixels`() { deviceShieldPixels.automaticRestart() deviceShieldPixels.automaticRestart() @@ -267,7 +267,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenSuddenKillBySystemThenFireDailyAndCountPixels() { + fun `whenSuddenKillBySystem - fire daily and count pixels`() { deviceShieldPixels.suddenKillBySystem() deviceShieldPixels.suddenKillBySystem() @@ -278,7 +278,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenSuddenKillByVpnRevokedThenFireDailyAndCountPixels() { + fun `whenSuddenKillByVpnRevoked - fire daily and count pixels`() { deviceShieldPixels.suddenKillByVpnRevoked() deviceShieldPixels.suddenKillByVpnRevoked() @@ -289,7 +289,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenPrivacyReportArticleDisplayedThenFireCountPixel() { + fun `whenPrivacyReportArticleDisplayed - fire count pixel`() { deviceShieldPixels.privacyReportArticleDisplayed() deviceShieldPixels.privacyReportArticleDisplayed() @@ -299,7 +299,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenReportUnprotectedAppsBucketCalledThenFirePixels() { + fun `reportUnprotectedAppsBucket - fire pixels`() { val bucketSize = 20 deviceShieldPixels.reportUnprotectedAppsBucket(bucketSize) diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/RestartReceiverTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/RestartReceiverTest.kt index 23590a281847..f67f5b6bae1d 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/RestartReceiverTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/RestartReceiverTest.kt @@ -50,7 +50,7 @@ class RestartReceiverTest { } @Test - fun whenInternalBuildThenRegisterReceiverOnStartVpn() { + fun `whenInternalBuild - register receiver on start vpn`() { whenever(appBuildConfig.flavor).thenReturn(BuildFlavor.INTERNAL) receiver.onVpnStarted(coroutineRule.testScope) @@ -60,7 +60,7 @@ class RestartReceiverTest { } @Test - fun whenNotInternalBuildThenRegisterReceiverOnStartVpn() { + fun `whenNotInternalBuildThenRegisterReceiverOnStartVpn - register receiver on start vpn`() { whenever(appBuildConfig.flavor).thenReturn(BuildFlavor.PLAY) receiver.onVpnStarted(coroutineRule.testScope) @@ -70,7 +70,7 @@ class RestartReceiverTest { } @Test - fun whenInternalBuildThenUnregisterReceiverOnStopVpn() { + fun `onVpnStopped - internal build - unregister receiver on stop vpn`() { whenever(appBuildConfig.flavor).thenReturn(BuildFlavor.INTERNAL) receiver.onVpnStopped(coroutineRule.testScope, VpnStateMonitor.VpnStopReason.SELF_STOP()) @@ -80,7 +80,7 @@ class RestartReceiverTest { } @Test - fun whenNotInternalBuildThenUnregisterReceiverOnStopVpn() { + fun `whenNotInternalBuildThenUnregisterReceiverOnStopVpn - receiver unregistered`() { whenever(appBuildConfig.flavor).thenReturn(BuildFlavor.PLAY) receiver.onVpnStopped(coroutineRule.testScope, VpnStateMonitor.VpnStopReason.SELF_STOP()) diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/VpnEnabledNotificationContentPluginPointKtTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/VpnEnabledNotificationContentPluginPointKtTest.kt index aaf8b72c9030..84b9bb690f20 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/VpnEnabledNotificationContentPluginPointKtTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/VpnEnabledNotificationContentPluginPointKtTest.kt @@ -23,12 +23,12 @@ import org.junit.Test class VpnEnabledNotificationContentPluginPointKtTest { @Test - fun whenEmptyPluginPointThenReturnNull() { + fun `createPluginPoint - empty plugin point - returns null`() { assertNull(createPluginPoint(emptyList()).getHighestPriorityPlugin()) } @Test - fun whenInactivePluginsThenReturnNull() { + fun `createPluginPoint - inactive plugins - return null`() { assertNull( createPluginPoint( listOf( @@ -40,7 +40,7 @@ class VpnEnabledNotificationContentPluginPointKtTest { } @Test - fun whenActivePluginsThenReturnThemInPriorityOrder() { + fun `whenActivePluginsThenReturnThemInPriorityOrder - return active plugins in priority order - high`() { val plugin = createPluginPoint( listOf( FakeVpnEnabledNotificationContentPlugin(isActive = true, VpnEnabledNotificationContentPlugin.VpnEnabledNotificationPriority.NORMAL), diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/VpnRoutesTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/VpnRoutesTest.kt index 5f029528b4b7..0ab5518840d0 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/VpnRoutesTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/VpnRoutesTest.kt @@ -25,7 +25,7 @@ import org.junit.Test class VpnRoutesTest { @Test - fun `all t-mobile wifi calling addresses are excluded from VPN`() { + fun `findRoutes - all t-mobile wifi calling addresses are excluded from VPN - no routes found`() { assertNoRoutes(findRoutes("66.94.2.0", "66.94.2.255")) assertNoRoutes(findRoutes("66.94.6.0", "66.94.7.255")) assertNoRoutes(findRoutes("66.94.8.0", "66.94.11.255")) @@ -33,7 +33,7 @@ class VpnRoutesTest { } @Test - fun `all verizon wifi calling addresses are excluded from VPN`() { + fun `findRoutes - all verizon wifi calling addresses are excluded from VPN - no routes found`() { assertNoRoutes(findRoutes("66.174.0.0", "66.174.255.255")) assertNoRoutes(findRoutes("69.82.0.0", "69.83.255.255")) assertNoRoutes(findRoutes("69.96.0.0", "69.103.255.255")) @@ -46,7 +46,7 @@ class VpnRoutesTest { } @Test - fun `all local IP addresses are excluded from VPN`() { + fun `findRoutes - all local IP addresses excluded from VPN - no routes found`() { assertNoRoutes(findRoutes("10.0.0.0", "10.255.255.255")) assertNoRoutes(findRoutes("169.254.0.0", "169.254.255.255")) assertNoRoutes(findRoutes("172.16.0.0", "172.31.255.255")) @@ -54,33 +54,33 @@ class VpnRoutesTest { } @Test - fun `all CGNAT IP addresses are excluded from VPN`() { + fun `findRoutes - all cgnat ip addresses excluded from vpn - no routes found`() { assertNoRoutes(findRoutes("100.64.0.0", "100.127.255.255")) } @Test - fun `all multicast addresses between 224·0·0·0 and 239·255·255·255 are excluded from VPN`() { + fun `findRoutes - all multicast addresses between 224·0·0·0 and 239·255·255·255 are excluded from VPN`() { val fromRange = "224.0.0.0" val toRange = "239.255.255.255" assertNoRoutes(findRoutes(fromRange, toRange)) } @Test - fun `loopback IP addresses are excluded form VPN`() { + fun `findRoutes - loopback IP addresses excluded from VPN - no routes found`() { val fromRange = "127.0.0.0" val toRange = "127.255.255.255" assertNoRoutes(findRoutes(fromRange, toRange)) } @Test - fun `class D IP address 240·0·0·0 to 255·255·255·255 are excluded from VPN`() { + fun `findRoutes - class D IP address 240·0·0·0 to 255·255·255·255 are excluded from VPN`() { val fromRange = "240.0.0.0" val toRange = "255.255.255.255" assertNoRoutes(findRoutes(fromRange, toRange)) } @Test - fun `all addresses between 0·0·0·0 and 9·255·255·255 range go through VPN`() { + fun `findRoutes - all addresses between 0·0·0·0 and 9·255·255·255 range go through VPN`() { val fromRange = "0.0.0.0" val toRange = "9.255.255.255" val routes = findRoutes(fromRange, toRange) @@ -90,7 +90,7 @@ class VpnRoutesTest { } @Test - fun `all addresses between 10·0·0·0 and 66·94·1·255 range go through VPN`() { + fun `findRoutes - all addresses between 10·0·0·0 and 66·94·1·255 range go through VPN`() { val fromRange = "11.0.0.0" val toRange = "66.94.1.255" val routes = findRoutes(fromRange, toRange) @@ -100,7 +100,7 @@ class VpnRoutesTest { } @Test - fun `all addresses between 66·94·3·0 range and 66·94·5·255 range go through VPN`() { + fun `findRoutes - all addresses between range go through VPN`() { val fromRange = "66.94.3.0" val toRange = "66.94.5.255" val routes = findRoutes(fromRange, toRange) @@ -130,7 +130,7 @@ class VpnRoutesTest { } @Test - fun `all addresses between 69·84·0·0 range and 69·95·255·255 range go through VPN`() { + fun `findRoutes - all addresses between 69·84·0·0 and 69·95·255·255 range go through VPN`() { val fromRange = "69.84.0.0" val toRange = "69.95.255.255" val routes = findRoutes(fromRange, toRange) @@ -140,7 +140,7 @@ class VpnRoutesTest { } @Test - fun `all addresses between 69·104·0·0 range and 70·191·255·255 range go through VPN`() { + fun `findRoutes - all addresses between 69·104·0·0 and 70·191·255·255 range go through VPN`() { val fromRange = "69.104.0.0" val toRange = "70.191.255.255" val routes = findRoutes(fromRange, toRange) @@ -150,7 +150,7 @@ class VpnRoutesTest { } @Test - fun `all addresses between 70·224·0·0 range and 71·255·255·255 range go through VPN`() { + fun `findRoutes - all addresses between 70·224·0·0 and 71·255·255·255 range go through VPN`() { val fromRange = "70.224.0.0" val toRange = "71.255.255.255" val routes = findRoutes(fromRange, toRange) @@ -160,7 +160,7 @@ class VpnRoutesTest { } @Test - fun `all addresses between 72·128·0·0 range and 75·127·255·255 range go through VPN`() { + fun `findRoutes - all addresses between 72-128-0-0 and 75-127-255-255 range go through VPN`() { val fromRange = "72.128.0.0" val toRange = "75.127.255.255" val routes = findRoutes(fromRange, toRange) @@ -170,7 +170,7 @@ class VpnRoutesTest { } @Test - fun `all addresses between 76·0·0·0 range and 96·255·255·255 range go through VPN`() { + fun `findRoutes - all addresses between 76·0·0·0 and 96·255·255·255 range go through VPN`() { val fromRange = "76.0.0.0" val toRange = "96.255.255.255" val routes = findRoutes(fromRange, toRange) @@ -180,7 +180,7 @@ class VpnRoutesTest { } @Test - fun `all addresses between 97·64·0·0 range and 97·127·255·255 range go through VPN`() { + fun `findRoutes - all addresses between 97·64·0·0 and 97·127·255·255 range go through VPN`() { val fromRange = "97.64.0.0" val toRange = "97.127.255.255" val routes = findRoutes(fromRange, toRange) @@ -190,7 +190,7 @@ class VpnRoutesTest { } @Test - fun `all addresses between 98·0·0·0 range and 100·63·255·255 range go through VPN`() { + fun `findRoutes - all addresses between 98·0·0·0 range and 100·63·255·255 range go through VPN`() { val fromRange = "98.0.0.0" val toRange = "100.63.255.255" val routes = findRoutes(fromRange, toRange) @@ -200,7 +200,7 @@ class VpnRoutesTest { } @Test - fun `all addresses between 100·128·0·0 range and 126·255·255·255 range go through VPN`() { + fun `findRoutes - all addresses between 100·128·0·0 and 126·255·255·255 range go through VPN`() { val fromRange = "100.128.0.0" val toRange = "126.255.255.255" val routes = findRoutes(fromRange, toRange) @@ -210,7 +210,7 @@ class VpnRoutesTest { } @Test - fun `all addresses between 128·0·0·0 range and 169·253·255·255 range go through VPN`() { + fun `findRoutes - all addresses between 128·0·0·0 range and 169·253·255·255 range go through VPN`() { val fromRange = "128.0.0.0" val toRange = "169.253.255.255" val routes = findRoutes(fromRange, toRange) @@ -220,7 +220,7 @@ class VpnRoutesTest { } @Test - fun `all addresses between 169·255·0·0 range and 172·15·255·255 range go through VPN`() { + fun `findRoutes - all addresses between 169·255·0·0 range and 172·15·255·255 range go through VPN`() { val fromRange = "169.255.0.0" val toRange = "172.15.255.255" val routes = findRoutes(fromRange, toRange) @@ -230,7 +230,7 @@ class VpnRoutesTest { } @Test - fun `all addresses between 172·32·0·0 range and 174·191·255·255 range go through VPN`() { + fun `findRoutes - all addresses between range and range go through VPN`() { val fromRange = "172.32.0.0" val toRange = "174.191.255.255" val routes = findRoutes(fromRange, toRange) @@ -240,7 +240,7 @@ class VpnRoutesTest { } @Test - fun `all addresses between 175·0·0·0 range and 192·167·255·255 range go through VPN`() { + fun `findRoutes - all addresses between 175·0·0·0 range and 192·167·255·255 range go through VPN`() { val fromRange = "175.0.0.0" val toRange = "192.167.255.255" val routes = findRoutes(fromRange, toRange) @@ -260,7 +260,7 @@ class VpnRoutesTest { } @Test - fun `all addresses between 208·55·0·0 range and multicast range go through VPN`() { + fun `findRoutes - all addresses between 208·55·0·0 range and multicast range go through VPN`() { val fromRange = "208.55.0.0" val toRange = "223.255.255.255" val routes = findRoutes(fromRange, toRange) @@ -270,7 +270,7 @@ class VpnRoutesTest { } @Test - fun `increment IP address`() { + fun `increment IP address - state - expected outcome`() { assertEquals("0.0.0.1", "0.0.0.0".incrementIpAddress()) assertEquals("0.0.0.255", "0.0.0.254".incrementIpAddress()) assertEquals("0.0.2.0", "0.0.1.255".incrementIpAddress()) diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/notification/AppTPAndNetPEnabledNotificationContentPluginTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/notification/AppTPAndNetPEnabledNotificationContentPluginTest.kt index f2f4c9d1b171..4d86067742fb 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/notification/AppTPAndNetPEnabledNotificationContentPluginTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/notification/AppTPAndNetPEnabledNotificationContentPluginTest.kt @@ -95,7 +95,7 @@ class AppTPAndNetPEnabledNotificationContentPluginTest { } @Test - fun getInitialContentNoServerLocationThenReturnsCorrectNotificationContent() = runTest { + fun `getInitialContent - no server location - returns correct notification content`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(true) whenever(networkProtectionState.isEnabled()).thenReturn(true) whenever(networkProtectionState.serverLocation()).thenReturn(null) @@ -107,7 +107,7 @@ class AppTPAndNetPEnabledNotificationContentPluginTest { } @Test - fun getInitialContentWithServerLocationThenReturnsCorrectNotificationContent() = runTest { + fun `getInitialContent - server location - returns correct notification content`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(true) whenever(networkProtectionState.isEnabled()).thenReturn(true) whenever(networkProtectionState.serverLocation()).thenReturn("Stockholm, SE") @@ -119,7 +119,7 @@ class AppTPAndNetPEnabledNotificationContentPluginTest { } @Test - fun getInitialContentAppTpNotEnabledThenReturnsCorrectNotificationContent() = runTest { + fun `getInitialContent - app tp not enabled - returns correct notification content`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(false) whenever(networkProtectionState.isEnabled()).thenReturn(true) @@ -127,7 +127,7 @@ class AppTPAndNetPEnabledNotificationContentPluginTest { } @Test - fun getInitialContentNetPNotEnabledThenReturnsCorrectNotificationContent() = runTest { + fun `getInitialContent - net p not enabled - returns correct notification content`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(true) whenever(networkProtectionState.isEnabled()).thenReturn(false) @@ -135,7 +135,7 @@ class AppTPAndNetPEnabledNotificationContentPluginTest { } @Test - fun getUpdateContentThenReturnsCorrectInitialUpdatedNotificationContent() = runTest { + fun `getUpdateContent - returns correct initial updated notification content`() = runTest { whenever(networkProtectionState.serverLocation()).thenReturn("Stockholm, SE") plugin.getUpdatedContent().test { @@ -149,7 +149,7 @@ class AppTPAndNetPEnabledNotificationContentPluginTest { } @Test - fun getUpdateContentOneCompanyThenReturnsCorrectUpdatedNotificationContent() = runTest { + fun `getUpdateContent - one company - returns correct updated notification content`() = runTest { whenever(networkProtectionState.serverLocation()).thenReturn("Stockholm, SE") plugin.getUpdatedContent().test { @@ -167,7 +167,7 @@ class AppTPAndNetPEnabledNotificationContentPluginTest { } @Test - fun getUpdateContentMultipleDifferentAppsThenReturnsCorrectUpdatedNotificationContent() = runTest { + fun `getUpdateContent - multiple different apps - returns correct updated notification content`() = runTest { whenever(networkProtectionState.serverLocation()).thenReturn("Stockholm, SE") plugin.getUpdatedContent().test { @@ -191,7 +191,7 @@ class AppTPAndNetPEnabledNotificationContentPluginTest { } @Test - fun getUpdateContentMultipleDifferentAppsNoLocationThenReturnsCorrectUpdatedNotificationContent() = runTest { + fun `getUpdateContent - multiple different apps no location - returns correct updated notification content`() = runTest { whenever(networkProtectionState.serverLocation()).thenReturn(null) plugin.getUpdatedContent().test { @@ -215,7 +215,7 @@ class AppTPAndNetPEnabledNotificationContentPluginTest { } @Test - fun getUpdateContentTrackersWithoutEntityThenReturnsCorrectUpdatedNotificationContent() = runTest { + fun `getUpdatedContent - without entity - returns correct updated notification content`() = runTest { whenever(networkProtectionState.serverLocation()).thenReturn("Stockholm, SE") plugin.getUpdatedContent().test { @@ -230,7 +230,7 @@ class AppTPAndNetPEnabledNotificationContentPluginTest { } @Test - fun getUpdateContentTrackersWithoutEntityNoLocationThenReturnsCorrectUpdatedNotificationContent() = runTest { + fun `getUpdateContentTrackers - no location - returns correct updated notification content`() = runTest { whenever(networkProtectionState.serverLocation()).thenReturn(null) plugin.getUpdatedContent().test { @@ -245,7 +245,7 @@ class AppTPAndNetPEnabledNotificationContentPluginTest { } @Test - fun getUpdateContentMultipleSameThenReturnsCorrectUpdatedNotificationContent() = runTest { + fun `getUpdateContent - multiple same - returns correct updated notification content`() = runTest { whenever(networkProtectionState.serverLocation()).thenReturn("Stockholm, SE") plugin.getUpdatedContent().test { @@ -263,7 +263,7 @@ class AppTPAndNetPEnabledNotificationContentPluginTest { } @Test - fun getUpdateContentMultipleSameNoLocationThenReturnsCorrectUpdatedNotificationContent() = runTest { + fun `getUpdateContent - multiple same no location - returns correct updated notification content`() = runTest { whenever(networkProtectionState.serverLocation()).thenReturn(null) plugin.getUpdatedContent().test { @@ -281,14 +281,14 @@ class AppTPAndNetPEnabledNotificationContentPluginTest { } @Test - fun isActiveWhenAppTpAndNetPEnabledThenReturnsTrue() = runTest { + fun `isActive - app tp and net p enabled - returns true`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(true) whenever(networkProtectionState.isEnabled()).thenReturn(true) assertTrue(plugin.isActive()) } @Test - fun isActiveWhenAppTpAndNetPNotEnabledThenReturnsFalse() = runTest { + fun `isActive - app tp and net p not enabled - returns false`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(false) whenever(networkProtectionState.isEnabled()).thenReturn(false) @@ -296,7 +296,7 @@ class AppTPAndNetPEnabledNotificationContentPluginTest { } @Test - fun isActiveWhenAppTpOnlyEnabledThenReturnsFalse() = runTest { + fun `isEnabled - app tracking protection only enabled - returns false`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(true) whenever(networkProtectionState.isEnabled()).thenReturn(false) @@ -304,7 +304,7 @@ class AppTPAndNetPEnabledNotificationContentPluginTest { } @Test - fun isActiveWhenNetPOnlyEnabledThenReturnsFalse() = runTest { + fun `isEnabled - net p only enabled - returns false`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(false) whenever(networkProtectionState.isEnabled()).thenReturn(true) diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/notification/AppTpEnabledNotificationContentPluginTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/notification/AppTpEnabledNotificationContentPluginTest.kt index 96ca650cdc9a..919bee020533 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/notification/AppTpEnabledNotificationContentPluginTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/notification/AppTpEnabledNotificationContentPluginTest.kt @@ -97,7 +97,7 @@ class AppTpEnabledNotificationContentPluginTest { } @Test - fun getInitialContentThenReturnsCorrectNotificationContent() = runTest { + fun `getInitialContent - initial content returned - correct notification content`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(true) whenever(networkProtectionState.isEnabled()).thenReturn(false) @@ -108,13 +108,13 @@ class AppTpEnabledNotificationContentPluginTest { } @Test - fun getInitialContentAppTpNotEnabledThenReturnsCorrectNotificationContent() = runTest { + fun `getInitialContent - app tracking protection not enabled - returns correct notification content`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(false) assertNull(plugin.getInitialContent()) } @Test - fun getUpdateContentThenReturnsCorrectInitialUpdatedNotificationContent() = runTest { + fun `getUpdateContent - returns correct initial updated notification content`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(true) whenever(networkProtectionState.isEnabled()).thenReturn(false) @@ -130,7 +130,7 @@ class AppTpEnabledNotificationContentPluginTest { } @Test - fun getUpdateContentAppTpNotEnabledThenReturnsCorrectInitialUpdatedNotificationContent() = runTest { + fun `getUpdateContent - app tracking protection not enabled - returns correct initial updated notification content`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(false) plugin.getUpdatedContent().test { @@ -143,7 +143,7 @@ class AppTpEnabledNotificationContentPluginTest { } @Test - fun getUpdateContentOneCompanyThenReturnsCorrectUpdatedNotificationContent() = runTest { + fun `getUpdateContent - one company - returns correct updated notification content`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(true) whenever(networkProtectionState.isEnabled()).thenReturn(false) @@ -162,7 +162,7 @@ class AppTpEnabledNotificationContentPluginTest { } @Test - fun getUpdateContentOneCompanyAppTpNotEnabledThenReturnsCorrectUpdatedNotificationContent() = runTest { + fun `getUpdateContent - app tracking protection not enabled - returns correct updated notification content`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(false) plugin.getUpdatedContent().test { @@ -180,7 +180,7 @@ class AppTpEnabledNotificationContentPluginTest { } @Test - fun getUpdateContentMultipleDifferentAppsThenReturnsCorrectUpdatedNotificationContent() = runTest { + fun `getUpdateContent - multiple different apps - returns correct updated notification content`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(true) whenever(networkProtectionState.isEnabled()).thenReturn(false) @@ -230,7 +230,7 @@ class AppTpEnabledNotificationContentPluginTest { } @Test - fun getUpdateContentTrackersWithoutEntityThenReturnsCorrectUpdatedNotificationContent() = runTest { + fun `getUpdateContentTrackers - without entity - returns correct updated notification content`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(true) whenever(networkProtectionState.isEnabled()).thenReturn(false) @@ -246,7 +246,7 @@ class AppTpEnabledNotificationContentPluginTest { } @Test - fun getUpdateContentMultipleSameThenReturnsCorrectUpdatedNotificationContent() = runTest { + fun `getUpdateContent - multiple same trackers - returns correct updated notification content`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(true) whenever(networkProtectionState.isEnabled()).thenReturn(false) @@ -265,7 +265,7 @@ class AppTpEnabledNotificationContentPluginTest { } @Test - fun getUpdateContentMultipleSameAppTpNotEnabledThenReturnsCorrectUpdatedNotificationContent() = runTest { + fun `getUpdateContent - multiple same app tp not enabled - returns correct updated notification content`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(false) plugin.getUpdatedContent().test { appTrackerBlockingStatsRepository.insert(listOf(aTrackerAndCompany(), aTrackerAndCompany())) @@ -279,14 +279,14 @@ class AppTpEnabledNotificationContentPluginTest { } @Test - fun isActiveWhenAppTpEnabledThenReturnsTrue() = runTest { + fun `isEnabled - app tp enabled - returns true`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(true) whenever(networkProtectionState.isEnabled()).thenReturn(false) assertTrue(plugin.isActive()) } @Test - fun isActiveWhenAppTpNotEnabledThenReturnsFalse() = runTest { + fun `isEnabled - app tracking protection not enabled - returns false`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(false) whenever(networkProtectionState.isEnabled()).thenReturn(false) @@ -294,7 +294,7 @@ class AppTpEnabledNotificationContentPluginTest { } @Test - fun isActiveWhenAppTpAndNetPEnabledThenReturnsFalse() = runTest { + fun `isActive - app tp and net p enabled - returns false`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(true) whenever(networkProtectionState.isEnabled()).thenReturn(true) diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/notification/VpnReminderNotificationContentPluginKtTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/notification/VpnReminderNotificationContentPluginKtTest.kt index f39cdf0b0128..44432564c443 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/notification/VpnReminderNotificationContentPluginKtTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/notification/VpnReminderNotificationContentPluginKtTest.kt @@ -30,12 +30,12 @@ import org.junit.Test class VpnReminderNotificationContentPluginKtTest { @Test - fun whenEmptyPluginPointThenReturnNull() { + fun `createPluginPoint - empty plugin point - returns null`() { assertNull(createPluginPoint(emptyList()).getHighestPriorityPluginForType(REVOKED)) } @Test - fun whenPluginForTypeAvailableThenReturnPLugin() { + fun `getHighestPriorityPluginForType - available - returns plugin`() { val plugin = createPluginPoint( listOf( FakeVpnReminderNotificationContentPlugin(type = DISABLED, NORMAL), @@ -46,7 +46,7 @@ class VpnReminderNotificationContentPluginKtTest { } @Test - fun whenNoPluginsForTypeThenReturnNull() { + fun `getHighestPriorityPluginForType - no plugins for type - return null`() { val plugin = createPluginPoint( listOf( FakeVpnReminderNotificationContentPlugin(type = REVOKED, NORMAL), @@ -57,7 +57,7 @@ class VpnReminderNotificationContentPluginKtTest { } @Test - fun whenMultiplePluginsForTypeThenReturnHighestPriority() { + fun `whenMultiplePluginsForTypeThenReturnHighestPriority - return highest priority`() { val plugin = createPluginPoint( listOf( FakeVpnReminderNotificationContentPlugin(type = DISABLED, NORMAL), diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/state/RealVpnStateMonitorTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/state/RealVpnStateMonitorTest.kt index 82cda0d36685..dab93179fef0 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/state/RealVpnStateMonitorTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/service/state/RealVpnStateMonitorTest.kt @@ -61,12 +61,12 @@ class RealVpnStateMonitorTest { } @Test - fun whenIsAllaysOnEnabledThenReturnDefaultValueFalse() = runTest { + fun `isAlwaysOnEnabled - always on enabled - false`() = runTest { Assert.assertFalse(testee.isAlwaysOnEnabled()) } @Test - fun whenVpnLastDisabledByAndroidAndVpnKilledBySystemThenReturnTrue() = runTest { + fun `vpnLastDisabledByAndroid - vpn killed by system - returns true`() = runTest { whenever(vpnServiceStateDao.getLastStateStats()).thenReturn(null) whenever(vpnHeartBeatDao.hearBeats()).thenReturn(listOf(HeartBeatEntity(type = VpnServiceHeartbeatMonitor.DATA_HEART_BEAT_TYPE_ALIVE))) whenever(vpnFeaturesRegistry.isAnyFeatureRunning()).thenReturn(false) @@ -75,7 +75,7 @@ class RealVpnStateMonitorTest { } @Test - fun whenVpnLastDisabledByAndroidAndVpnUnexpectedlyDisabledThenReturnTrue() = runTest { + fun `vpnLastDisabledByAndroid - unexpected disable - returns true`() = runTest { whenever(vpnServiceStateDao.getLastStateStats()).thenReturn( VpnServiceStateStats(state = DISABLED), ) @@ -84,7 +84,7 @@ class RealVpnStateMonitorTest { } @Test - fun whenVpnLastDisabledByAndroidAndVpnDisabledByUserThenReturnFalse() = runTest { + fun `vpnLastDisabledByAndroid - disabled by user - returns false`() = runTest { whenever(vpnServiceStateDao.getLastStateStats()).thenReturn( VpnServiceStateStats(state = DISABLED, stopReason = SELF_STOP), ) @@ -93,7 +93,7 @@ class RealVpnStateMonitorTest { } @Test - fun whenVpnLastDisabledByAndroidAndVpnEnabledThenReturnFalse() = runTest { + fun `vpnLastDisabledByAndroid - enabled - returns false`() = runTest { whenever(vpnServiceStateDao.getLastStateStats()).thenReturn( VpnServiceStateStats(state = ENABLED), ) diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/PrivacyReportViewModelTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/PrivacyReportViewModelTest.kt index af1273a83448..dc285d2242c8 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/PrivacyReportViewModelTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/PrivacyReportViewModelTest.kt @@ -85,7 +85,7 @@ class PrivacyReportViewModelTest { } @Test - fun whenTrackersBlockedThenReportHasTrackers() = runBlocking { + fun `getReport - trackers blocked - report has trackers`() = runBlocking { trackerFound("dax.com") trackerFound("dax.com") trackerFound("dax.com") @@ -98,7 +98,7 @@ class PrivacyReportViewModelTest { } @Test - fun whenTrackersBlockedOutsideTimeWindowThenReturnEmpty() = runBlocking { + fun `getReport - trackers blocked outside time window - return empty`() = runBlocking { trackerFoundYesterday("dax.com") trackerFoundYesterday("dax.com") trackerFoundYesterday("dax.com") @@ -111,7 +111,7 @@ class PrivacyReportViewModelTest { } @Test - fun whenNoTrackersBlockedThenReportIsEmpty() = runBlocking { + fun `getReport - no trackers blocked - report is empty`() = runBlocking { testee.getReport().test { val result = awaitItem() assertEquals(0, result.trackers) diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/notification/AppTPReminderNotificationSchedulerTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/notification/AppTPReminderNotificationSchedulerTest.kt index 602609642f99..d29b899321f6 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/notification/AppTPReminderNotificationSchedulerTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/notification/AppTPReminderNotificationSchedulerTest.kt @@ -101,7 +101,7 @@ class AppTPReminderNotificationSchedulerTest { } @Test - fun whenAppTPEnabledVPNStartsThenUndesiredReminderIsEnqueued() = runTest { + fun `onVpnStarted - app TP enabled - undesired reminder enqueued`() = runTest { assertWorkersAreNotEnqueued(VpnReminderNotificationWorker.WORKER_VPN_REMINDER_UNDESIRED_TAG) whenever(appTrackingProtection.isEnabled()).thenReturn(true) @@ -111,7 +111,7 @@ class AppTPReminderNotificationSchedulerTest { } @Test - fun whenAppTPDisabledVPNStartsThenEnqueueNothing() = runTest { + fun `onVpnStarted - app TP disabled - enqueues nothing`() = runTest { assertWorkersAreNotEnqueued(VpnReminderNotificationWorker.WORKER_VPN_REMINDER_UNDESIRED_TAG) whenever(appTrackingProtection.isEnabled()).thenReturn(false) @@ -121,7 +121,7 @@ class AppTPReminderNotificationSchedulerTest { } @Test - fun whenVPNStartsThenDailyReminderIsNotEnqueued() = runTest { + fun `onVpnStarted - daily reminder is not enqueued`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(true) testee.onVpnStarted(coroutinesTestRule.testScope) @@ -130,7 +130,7 @@ class AppTPReminderNotificationSchedulerTest { } @Test - fun whenVPNStartsAndDailyReminderWasEnqueuedThenDailyReminderIsNotEnqueued() = runTest { + fun `onVpnStarted - daily reminder not enqueued`() = runTest { enqueueDailyReminderNotificationWorker() assertWorkersAreEnqueued(VpnReminderNotificationWorker.WORKER_VPN_REMINDER_DAILY_TAG) whenever(appTrackingProtection.isEnabled()).thenReturn(true) @@ -141,7 +141,7 @@ class AppTPReminderNotificationSchedulerTest { } @Test - fun whenVPNManuallyStopsDueToSnoozeThenDailyReminderIsNotEnqueued() = runTest { + fun `onVpnStopped - daily reminder not enqueued`() = runTest { whenever(vpnFeatureRemover.isFeatureRemoved()).thenReturn(false) assertWorkersAreNotEnqueued(VpnReminderNotificationWorker.WORKER_VPN_REMINDER_DAILY_TAG) whenever(appTrackingProtection.isEnabled()).thenReturn(true) @@ -156,7 +156,7 @@ class AppTPReminderNotificationSchedulerTest { } @Test - fun whenVPNManuallyStopsThenDailyReminderIsEnqueued() = runTest { + fun `onVpnStopped - daily reminder is enqueued`() = runTest { whenever(vpnFeatureRemover.isFeatureRemoved()).thenReturn(false) assertWorkersAreNotEnqueued(VpnReminderNotificationWorker.WORKER_VPN_REMINDER_DAILY_TAG) whenever(appTrackingProtection.isEnabled()).thenReturn(true) @@ -171,7 +171,7 @@ class AppTPReminderNotificationSchedulerTest { } @Test - fun whenVPNStoppedButAppTPDisabledWasRemovedThenNothingIsEnqueued() = runTest { + fun `onVpnStopped - app TP disabled was removed - nothing is enqueued`() = runTest { whenever(vpnFeatureRemover.isFeatureRemoved()).thenReturn(false) whenever(appTrackingProtection.isEnabled()).thenReturn(false) whenever(appTrackingProtection.isOnboarded()).thenReturn(true) @@ -184,7 +184,7 @@ class AppTPReminderNotificationSchedulerTest { } @Test - fun whenVPNStoppedBecauseFeatureWasRemovedThenNothingIsEnqueued() = runTest { + fun `onVpnStopped - vpn stopped because feature was removed - nothing is enqueued`() = runTest { whenever(vpnFeatureRemover.isFeatureRemoved()).thenReturn(true) assertWorkersAreNotEnqueued(VpnReminderNotificationWorker.WORKER_VPN_REMINDER_DAILY_TAG) @@ -195,7 +195,7 @@ class AppTPReminderNotificationSchedulerTest { } @Test - fun whenVPNManuallyStopsAndDailyReminderWasEnqueuedThenDailyReminderIsStillEnqueued() = runTest { + fun `onVpnStopped - daily reminder still enqueued`() = runTest { whenever(vpnFeatureRemover.isFeatureRemoved()).thenReturn(false) enqueueDailyReminderNotificationWorker() assertWorkersAreEnqueued(VpnReminderNotificationWorker.WORKER_VPN_REMINDER_DAILY_TAG) @@ -206,7 +206,7 @@ class AppTPReminderNotificationSchedulerTest { } @Test - fun whenVPNManuallyStopsThenUndesiredReminderIsNotScheduled() = runTest { + fun `onVpnStopped - undesired reminder not scheduled`() = runTest { whenever(vpnFeatureRemover.isFeatureRemoved()).thenReturn(false) testee.onVpnStopped(coroutinesTestRule.testScope, SELF_STOP()) @@ -214,7 +214,7 @@ class AppTPReminderNotificationSchedulerTest { } @Test - fun whenVPNManuallyStopsAndUndesiredReminderWasScheduledThenUndesiredReminderIsNoLongerScheduled() = runTest { + fun `onVpnStopped - undesired reminder is no longer scheduled`() = runTest { whenever(vpnFeatureRemover.isFeatureRemoved()).thenReturn(false) enqueueUndesiredReminderNotificationWorker() assertWorkersAreEnqueued(VpnReminderNotificationWorker.WORKER_VPN_REMINDER_UNDESIRED_TAG) @@ -230,7 +230,7 @@ class AppTPReminderNotificationSchedulerTest { } @Test - fun whenVPNManuallyStopsAndNoContentPluginForDisabledThenNoImmediateNotificationShouldBeShown() = runTest { + fun `onVpnStopped - no content plugin for disabled - no immediate notification`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(true) whenever(vpnFeatureRemover.isFeatureRemoved()).thenReturn(false) whenever(mockPluginPoint.getHighestPriorityPluginForType(DISABLED)).thenReturn(null) @@ -241,7 +241,7 @@ class AppTPReminderNotificationSchedulerTest { } @Test - fun whenUserHasOnboardedAndVPNManuallyStopsAndWithContentPluginForDisabledThenImmediateNotificationShouldBeShown() = runTest { + fun `onVpnStopped - user has onboarded and VPN manually stops with content plugin for disabled - immediate notification should be shown`() = runTest { whenever(mockPluginPoint.getPlugins()).thenReturn(listOf(fakeRevokedPlugin, fakeDisabledPlugin)) whenever(vpnFeatureRemover.isFeatureRemoved()).thenReturn(false) whenever(appTrackingProtection.isEnabled()).thenReturn(true) @@ -254,7 +254,7 @@ class AppTPReminderNotificationSchedulerTest { } @Test - fun whenUserHasNotOnboardedAndVPNManuallyStopsAndWithContentPluginForDisabledThenNoImmediateNotificationShouldBeShown() = runTest { + fun `onVpnStarted - user has not onboarded and VPN manually stops with content plugin for disabled - no immediate notification should be shown`() = runTest { whenever(mockPluginPoint.getPlugins()).thenReturn(listOf(fakeRevokedPlugin, fakeDisabledPlugin)) whenever(vpnFeatureRemover.isFeatureRemoved()).thenReturn(false) whenever(appTrackingProtection.isEnabled()).thenReturn(true) @@ -267,7 +267,7 @@ class AppTPReminderNotificationSchedulerTest { } @Test - fun whenVpnRevokedAndNoContentPluginForRevokedThenNoImmediateNotificationShouldBeShown() = runTest { + fun `onVpnStopped - vpn revoked and no content plugin for revoked - no immediate notification should be shown`() = runTest { whenever(vpnFeatureRemover.isFeatureRemoved()).thenReturn(false) whenever(mockPluginPoint.getHighestPriorityPluginForType(Type.REVOKED)).thenReturn(null) whenever(appTrackingProtection.isEnabled()).thenReturn(true) @@ -279,7 +279,7 @@ class AppTPReminderNotificationSchedulerTest { } @Test - fun whenAppTPEnabledAndOnboardedVpnRevokedAndWithContentPluginForRevokedThenImmediateNotificationShouldBeShown() = runTest { + fun `onVpnStarted - app TP enabled and onboarded VPN revoked with content plugin for revoked - immediate notification shown`() = runTest { whenever(mockPluginPoint.getPlugins()).thenReturn(listOf(fakeRevokedPlugin, fakeDisabledPlugin)) whenever(appTrackingProtection.isEnabled()).thenReturn(true) whenever(appTrackingProtection.isOnboarded()).thenReturn(true) @@ -291,7 +291,7 @@ class AppTPReminderNotificationSchedulerTest { } @Test - fun whenAppTPDisabledVpnRevokedAndWithContentPluginForRevokedThenNoImmediateNotificationShouldBeShown() = runTest { + fun `onVpnStarted - app TP disabled - no immediate notification shown`() = runTest { whenever(mockPluginPoint.getPlugins()).thenReturn(listOf(fakeRevokedPlugin, fakeDisabledPlugin)) whenever(appTrackingProtection.isEnabled()).thenReturn(false) whenever(appTrackingProtection.isOnboarded()).thenReturn(true) @@ -303,7 +303,7 @@ class AppTPReminderNotificationSchedulerTest { } @Test - fun whenAppTPNotOnboardedVpnRevokedAndWithContentPluginForRevokedThenNoImmediateNotificationShouldBeShown() = runTest { + fun `onVpnStarted - app TP not onboarded VPN revoked - no immediate notification`() = runTest { whenever(mockPluginPoint.getPlugins()).thenReturn(listOf(fakeRevokedPlugin, fakeDisabledPlugin)) whenever(appTrackingProtection.isEnabled()).thenReturn(false) whenever(appTrackingProtection.isOnboarded()).thenReturn(false) @@ -315,14 +315,14 @@ class AppTPReminderNotificationSchedulerTest { } @Test - fun whenVPNIsKilledThenUndesiredReminderIsEnqueued() { + fun `onVpnStopped - undesired reminder enqueued`() { testee.onVpnStopped(coroutinesTestRule.testScope, REVOKED) assertWorkersAreNotEnqueued(VpnReminderNotificationWorker.WORKER_VPN_REMINDER_UNDESIRED_TAG) } @Test - fun whenVPNIsKilledAndReminderWasScheduledThenUndesiredReminderIsNoLongerScheduled() = runTest { + fun `onVpnStopped - reminder scheduled - no longer scheduled`() = runTest { enqueueUndesiredReminderNotificationWorker() assertWorkersAreEnqueued(VpnReminderNotificationWorker.WORKER_VPN_REMINDER_UNDESIRED_TAG) whenever(appTrackingProtection.isOnboarded()).thenReturn(true) @@ -336,7 +336,7 @@ class AppTPReminderNotificationSchedulerTest { } @Test - fun whenUserEnabledAppTPAndDisabledItOnVPNReconfigureThenImmediateNotificationShouldBeShow() = runTest { + fun `onVpnReconfigured - app tracking protection enabled and disabled - immediate notification should be shown`() = runTest { whenever(mockPluginPoint.getPlugins()).thenReturn(listOf(fakeRevokedPlugin, fakeDisabledPlugin)) whenever(appTrackingProtection.isOnboarded()).thenReturn(true) whenever(appTrackingProtection.isEnabled()).thenReturn(true) @@ -349,7 +349,7 @@ class AppTPReminderNotificationSchedulerTest { } @Test - fun whenAppTPDisabledOnVPNReconfigureThenNoImmediateNotificationShouldBeShow() = runTest { + fun `onVpnReconfigured - app TP disabled on VPN reconfigure - no immediate notification should be shown`() = runTest { whenever(mockPluginPoint.getPlugins()).thenReturn(listOf(fakeRevokedPlugin, fakeDisabledPlugin)) whenever(appTrackingProtection.isEnabled()).thenReturn(false) testee.onVpnStarted(coroutinesTestRule.testScope) @@ -359,7 +359,7 @@ class AppTPReminderNotificationSchedulerTest { } @Test - fun whenUserEnabledAppTPOnVPNReconfigureThenNoImmediateNotificationShouldBeShow() = runTest { + fun `onVpnReconfigured - no immediate notification should be shown`() = runTest { whenever(mockPluginPoint.getPlugins()).thenReturn(listOf(fakeRevokedPlugin, fakeDisabledPlugin)) whenever(appTrackingProtection.isEnabled()).thenReturn(false) testee.onVpnStarted(coroutinesTestRule.testScope) diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/notification/DeviceShieldDailyNotificationFactoryTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/notification/DeviceShieldDailyNotificationFactoryTest.kt index 295b323ec6cd..5a67cea6358b 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/notification/DeviceShieldDailyNotificationFactoryTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/notification/DeviceShieldDailyNotificationFactoryTest.kt @@ -65,7 +65,7 @@ class DeviceShieldDailyNotificationFactoryTest { } @Test - fun createsTotalTrackersNotificationWhenTrackersFoundInOneApp() = runBlocking { + fun `createsTotalTrackersNotification - trackers found in one app - total trackers notification`() = runBlocking { val trackerDomain = "example.com" trackerFound(trackerDomain) @@ -76,7 +76,7 @@ class DeviceShieldDailyNotificationFactoryTest { } @Test - fun createsTotalTrackersNotificationWhenTrackersFoundInTwoApps() = runBlocking { + fun `createsTotalTrackersNotification - trackers found in two apps - total trackers notification`() = runBlocking { val trackerDomain = "example.com" trackerFound(trackerDomain, appContainingTracker = trackingApp1()) trackerFound( @@ -92,13 +92,13 @@ class DeviceShieldDailyNotificationFactoryTest { } @Test - fun createsHiddenTotalTrackersNotificationWhenNoTrackersFound() = runBlocking { + fun `createDailyDeviceShieldNotification - no trackers found - hidden`() = runBlocking { val notification = factory.dailyNotificationFactory.createDailyDeviceShieldNotification(0) assertTrue(notification.hidden) } @Test - fun createsTopTrackerCompanyNotificationWhenTrackersFoundInOneApp() = runBlocking { + fun `createsTopTrackerCompanyNotification - trackers found in one app - top tracker company notification`() = runBlocking { val trackerDomain = "example.com" trackerFound(trackerDomain) @@ -109,7 +109,7 @@ class DeviceShieldDailyNotificationFactoryTest { } @Test - fun createsTopTrackerCompanyNotificationWhenTrackersFoundInTwoApps() = runBlocking { + fun `createsTopTrackerCompanyNotification - trackers found in two apps - notification created`() = runBlocking { val trackerDomain = "example.com" trackerFound(trackerDomain, appContainingTracker = TrackingApp("foo", "An app")) trackerFound(trackerDomain, appContainingTracker = TrackingApp("bar", "Another app")) @@ -121,20 +121,20 @@ class DeviceShieldDailyNotificationFactoryTest { } @Test - fun doesNotCreateTopTrackerCompanyNotificationWhenTrackersFoundInZeroApps() = runBlocking { + fun `doesNotCreateTopTracker - company notification not created when trackers found in zero apps - hidden`() = runBlocking { val notification = factory.dailyNotificationFactory.createDailyDeviceShieldNotification(1) assertTrue(notification.hidden) } @Test - fun createsHiddenTopTrackerCompanyNotificationWhenNoTrackersFound() = runBlocking { + fun `createsDailyDeviceShieldNotification - no trackers found - hidden`() = runBlocking { val notification = factory.dailyNotificationFactory.createDailyDeviceShieldNotification(1) assertTrue(notification.hidden) } @Test - fun createsTopTrackerAppNumbersNotificationWhenTrackersFound() = runBlocking { + fun `createsTopTrackerAppNumbersNotification - trackers found - notification created`() = runBlocking { val trackerDomain = "example.com" trackerFound(trackerDomain, appContainingTracker = trackingApp1()) trackerFound(trackerDomain, appContainingTracker = trackingApp2()) @@ -156,7 +156,7 @@ class DeviceShieldDailyNotificationFactoryTest { } @Test - fun createsLastCompanyAttemptNotificationWhenTrackersFoundInOneApp() = runBlocking { + fun `createsLastCompanyAttemptNotification - trackers found in one app - last company attempt notification`() = runBlocking { val trackerDomain = "example.com" trackerFound(trackerDomain) @@ -167,7 +167,7 @@ class DeviceShieldDailyNotificationFactoryTest { } @Test - fun createsLastCompanyAttemptNotificationWhenTrackersFoundInTwoApps() = runBlocking { + fun `createsLastCompanyAttemptNotification - trackers found in two apps - last company attempt notification created`() = runBlocking { val trackerDomain = "example.com" trackerFound(trackerDomain, appContainingTracker = trackingApp1()) trackerFound( @@ -183,7 +183,7 @@ class DeviceShieldDailyNotificationFactoryTest { } @Test - fun createsLastCompanyAttemptNotificationWhenTrackersFoundInThreeApps() = runBlocking { + fun `createsLastCompanyAttemptNotification - trackers found in three apps - last company attempt notification`() = runBlocking { val trackerDomain = "example.com" trackerFound(trackerDomain, appContainingTracker = trackingApp1()) trackerFound("google.com", trackerCompanyId = 1, company = "Google", appContainingTracker = trackingApp1()) diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/notification/DeviceShieldWeeklyNotificationFactoryTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/notification/DeviceShieldWeeklyNotificationFactoryTest.kt index 1dcf73f2e2e7..f09bbd55acbc 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/notification/DeviceShieldWeeklyNotificationFactoryTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/notification/DeviceShieldWeeklyNotificationFactoryTest.kt @@ -65,7 +65,7 @@ class DeviceShieldWeeklyNotificationFactoryTest { } @Test - fun createsWeeklyReportNotificationWhenTrackersFoundInOneApp() = runBlocking { + fun `createsWeeklyReportNotification - trackers found in one app - weekly report notification`() = runBlocking { val trackerDomain = "example.com" trackerFound(trackerDomain) @@ -75,7 +75,7 @@ class DeviceShieldWeeklyNotificationFactoryTest { } @Test - fun createsWeeklyReportNotificationWhenTrackersFoundInTwoApps() = runBlocking { + fun `createsWeeklyReportNotification - trackers found in two apps - weekly report notification created`() = runBlocking { val trackerDomain = "example.com" trackerFound(trackerDomain, appContainingTracker = trackingApp1()) trackerFound( @@ -90,7 +90,7 @@ class DeviceShieldWeeklyNotificationFactoryTest { } @Test - fun createsWeeklyReportNotificationWhenTrackersFoundInMoreThanTwoApps() = runBlocking { + fun `createsWeeklyReportNotification - trackers found in more than two apps - weekly report notification`() = runBlocking { val trackerDomain = "example.com" trackerFound(trackerDomain, appContainingTracker = trackingApp1()) trackerFound(trackerDomain, appContainingTracker = trackingApp2()) @@ -106,7 +106,7 @@ class DeviceShieldWeeklyNotificationFactoryTest { } @Test - fun createsWeeklyReportNotificationWithCorrectSortOrder() = runBlocking { + fun `createsWeeklyReportNotification - correct sort order - weekly report notification created`() = runBlocking { val trackerDomain = "example.com" trackerFound(trackerDomain, appContainingTracker = trackingApp1()) trackerFound(trackerDomain, appContainingTracker = trackingApp2()) @@ -125,13 +125,13 @@ class DeviceShieldWeeklyNotificationFactoryTest { } @Test - fun createsHiddenWeeklyReportNotificationWhenNoTrackersFound() = runBlocking { + fun `createsWeeklyReportNotification - no trackers found - hidden`() = runBlocking { val notification = factory.weeklyNotificationFactory.createWeeklyDeviceShieldNotification(0) assertTrue(notification.hidden) } @Test - fun createsWeeklyTopTrackerCompanyNotificationWhenTrackersFoundInOneApp() = runBlocking { + fun `createsWeeklyTopTrackerCompanyNotification - trackers found in one app - weekly top tracker company notification`() = runBlocking { val trackerDomain = "example.com" trackerFound(trackerDomain) @@ -141,7 +141,7 @@ class DeviceShieldWeeklyNotificationFactoryTest { } @Test - fun createsWeeklyTopTrackerCompanyNotificationWhenTrackersFoundInTwoApps() = runBlocking { + fun `createsWeeklyTopTrackerCompanyNotification - trackers found in two apps - weekly device shield notification created`() = runBlocking { val trackerDomain = "example.com" trackerFound("google.com", company = "Google", appContainingTracker = trackingApp1()) @@ -164,7 +164,7 @@ class DeviceShieldWeeklyNotificationFactoryTest { } @Test - fun createsHiddenWeeklyTopTrackerCompanyNotificationWhenNoTrackersFound() = runBlocking { + fun `createsHiddenWeeklyTopTrackerCompanyNotification - no trackers found - hidden`() = runBlocking { val notification = factory.weeklyNotificationFactory.createWeeklyDeviceShieldNotification(1) assertTrue(notification.hidden) } diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/onboarding/SharedPreferencesVpnStoreTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/onboarding/SharedPreferencesVpnStoreTest.kt index 7bcf94a97533..32d5d9ee0c2d 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/onboarding/SharedPreferencesVpnStoreTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/onboarding/SharedPreferencesVpnStoreTest.kt @@ -47,7 +47,7 @@ class SharedPreferencesVpnStoreTest { } @Test - fun whenOnboardingDidShowThenSetPreferenceValueToTrue() { + fun `onboardingDidShow - set preference value to true`() { assertFalse(sharedPreferencesVpnStore.didShowOnboarding()) sharedPreferencesVpnStore.onboardingDidShow() @@ -56,7 +56,7 @@ class SharedPreferencesVpnStoreTest { } @Test - fun whenOnboardingDidNotShowThenSetPreferenceValueToFalse() { + fun `onboardingDidNotShow - set preference value to false`() { sharedPreferencesVpnStore.onboardingDidShow() assertTrue(sharedPreferencesVpnStore.didShowOnboarding()) @@ -67,7 +67,7 @@ class SharedPreferencesVpnStoreTest { } @Test - fun whenAppTpEnabledCtaDidShowThenSetPreferenceValueToTrue() { + fun `appTpEnabledCta - did show - set preference value to true`() { assertFalse(sharedPreferencesVpnStore.didShowAppTpEnabledCta()) sharedPreferencesVpnStore.appTpEnabledCtaDidShow() @@ -76,7 +76,7 @@ class SharedPreferencesVpnStoreTest { } @Test - fun whenIsOnboardingSessionCalledWithoutBeingSetThenReturnFalse() { + fun `getAndSetOnboardingSession - not set - returns false`() { assertTrue(sharedPreferencesVpnStore.getAndSetOnboardingSession()) assertNotEquals(-1, preferences.getLong("KEY_APP_TP_ONBOARDING_BANNER_EXPIRY_TIMESTAMP", -1)) assertTrue(sharedPreferencesVpnStore.getAndSetOnboardingSession()) diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/tracker_activity/AppTPCompanyTrackersViewModelTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/tracker_activity/AppTPCompanyTrackersViewModelTest.kt index 48b6303d6b67..049f98141e45 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/tracker_activity/AppTPCompanyTrackersViewModelTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/tracker_activity/AppTPCompanyTrackersViewModelTest.kt @@ -73,7 +73,7 @@ class AppTPCompanyTrackersViewModelTest { @Ignore @Test - fun whenLoadsDataReturnsTrackersForAppFromDate() = runBlocking { + fun `loadData - state - returns trackers for app from date`() = runBlocking { val date = "2020-10-21" val packageName = "com.duckduckgo.android" @@ -88,7 +88,7 @@ class AppTPCompanyTrackersViewModelTest { } @Test - fun whenAppIsUnprotectedThroughNetpThenReturnViewStateWithtoggleUncheckedDisabledAndShowCorrectBanner() = runTest { + fun `loadData - view state with toggle unchecked disabled and show correct banner`() = runTest { val date = "2020-10-21" val packageName = "com.duckduckgo.android" @@ -113,7 +113,7 @@ class AppTPCompanyTrackersViewModelTest { } @Test - fun whenAppIsProtectedThenReturnViewStateWithtoggleCheckedEnabledAndShowCorrectBanner() = runTest { + fun `loadData - app protected - view state with toggle checked enabled and show correct banner`() = runTest { val date = "2020-10-21" val packageName = "com.duckduckgo.android" @@ -138,7 +138,7 @@ class AppTPCompanyTrackersViewModelTest { } @Test - fun whenAppIsUnProtectedThenReturnViewStateWithtoggleUnCheckedEnabledAndShowCorrectBanner() = runTest { + fun `loadData - app unprotected - show correct banner`() = runTest { val date = "2020-10-21" val packageName = "com.duckduckgo.android" diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/tracker_activity/DeviceShieldActivityFeedViewModelTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/tracker_activity/DeviceShieldActivityFeedViewModelTest.kt index ced5d7140883..97d77d5bfb0d 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/tracker_activity/DeviceShieldActivityFeedViewModelTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/tracker_activity/DeviceShieldActivityFeedViewModelTest.kt @@ -95,7 +95,7 @@ class DeviceShieldActivityFeedViewModelTest { } @Test - fun whenGetMostRecentTrackersCalledStartWithSkeleton() = runBlocking { + fun `getMostRecentTrackers - start with skeleton`() = runBlocking { viewModel.getMostRecentTrackers(timeWindow, config).test { assertEquals(TrackerFeedViewState(listOf(TrackerLoadingSkeleton), VpnState(DISABLED, ERROR)), awaitItem()) cancelAndConsumeRemainingEvents() @@ -103,7 +103,7 @@ class DeviceShieldActivityFeedViewModelTest { } @Test - fun whenGetMostRecentTrackersIsNotEmptyThenStartWithSkeletonThenEmit() = runBlocking { + fun `getMostRecentTrackers - is not empty - start with skeleton then emit`() = runBlocking { repository.insert(listOf(dummyTrackers[0], dummyTrackers[1], dummyTrackers[2])) db.vpnAppTrackerBlockingDao().insertTrackerEntities(dummySignals) @@ -128,7 +128,7 @@ class DeviceShieldActivityFeedViewModelTest { } @Test - fun whenGetMostRecentTrackersIsNotEmptyAndOutsideTimeWindowThenEmitLoadingSkeleton() = runBlocking { + fun `getMostRecentTrackers - is not empty and outside time window - emit loading skeleton`() = runBlocking { repository.insert(listOf(dummyTrackers[3])) viewModel.getMostRecentTrackers(timeWindow, config).test { @@ -145,7 +145,7 @@ class DeviceShieldActivityFeedViewModelTest { } @Test - fun whenGetMostRecentTrackersIsEmptyAndVpnEnabledAndBoundedConfigThenEmitDescriptionAndAppsProtectionState() = runBlocking { + fun `getMostRecentTrackers - empty and vpn enabled and bounded config - emit description and apps protection state`() = runBlocking { mockVpnEnabled() whenever(mockExcludedApps.getAppsAndProtectionInfo()).thenReturn(flowOf(listOf(app, excludedApp))) val boundedConfig = config.copy(maxRows = 5) @@ -181,7 +181,7 @@ class DeviceShieldActivityFeedViewModelTest { } @Test - fun whenGetMostRecentTrackersIsEmptyAndVpnDisabledAndFiveRowsThenEmitDescription() = runBlocking { + fun `getMostRecentTrackers - empty and vpn disabled - emit description`() = runBlocking { mockVpnDisabled() whenever(mockExcludedApps.getAppsAndProtectionInfo()).thenReturn(flowOf(listOf(app, excludedApp))) val boundedConfig = config.copy(maxRows = 5) @@ -203,7 +203,7 @@ class DeviceShieldActivityFeedViewModelTest { } @Test - fun whenGetMostRecentTrackersReturnsLessTrackersThanMaxRowsAndVpnEnabledThenEmitOnlyTrackerFeedDataItems() = runBlocking { + fun `getMostRecentTrackers - vpn enabled - emit only tracker feed data items`() = runBlocking { repository.insert(listOf(dummyTrackers[0], dummyTrackers[1], dummyTrackers[2])) db.vpnAppTrackerBlockingDao().insertTrackerEntities(dummySignals) diff --git a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/tracker_activity/DeviceShieldTrackerActivityViewModelTest.kt b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/tracker_activity/DeviceShieldTrackerActivityViewModelTest.kt index 7335d5eea355..88e3b2ff6b9c 100644 --- a/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/tracker_activity/DeviceShieldTrackerActivityViewModelTest.kt +++ b/app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/ui/tracker_activity/DeviceShieldTrackerActivityViewModelTest.kt @@ -78,7 +78,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenGetRunningStateThenReturnRunningState() = runTest { + fun `getRunningState - when get running state then return running state`() = runTest { whenever(vpnStateMonitor.getStateFlow(AppTpVpnFeature.APPTP_VPN)).thenReturn( flow { emit(VpnStateMonitor.VpnState(VpnStateMonitor.VpnRunningState.ENABLED)) }, ) @@ -90,7 +90,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenLaunchAppTrackersViewEventThenCommandIsLaunchAppTrackers() = runBlocking { + fun `onViewEvent - launch app trackers - launch app trackers faq`() = runBlocking { viewModel.commands().test { viewModel.onViewEvent(ViewEvent.LaunchAppTrackersFAQ) @@ -101,7 +101,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenLaunchDeviceShieldFAQViewEventThenCommandIsLaunchDeviceShieldFAQ() = runBlocking { + fun `onViewEvent - launch device shield FAQ - launch device shield FAQ`() = runBlocking { viewModel.commands().test { viewModel.onViewEvent(ViewEvent.LaunchDeviceShieldFAQ) @@ -112,7 +112,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenLaunchExcludedAppsViewEventThenCommandIsLaunchExcludedApps() = runBlocking { + fun `onViewEvent - launch excluded apps view event - launch manage apps protection`() = runBlocking { viewModel.commands().test { viewModel.onViewEvent(ViewEvent.LaunchExcludedApps) @@ -123,7 +123,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenLaunchMostRecentActivityViewEventThenCommandIsLaunchMostRecentActivity() = runBlocking { + fun `onViewEvent - launch most recent activity - launch most recent activity`() = runBlocking { viewModel.commands().test { viewModel.onViewEvent(ViewEvent.LaunchMostRecentActivity) @@ -134,7 +134,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenToggleIsSwitchedOnAndOtherVPNIsDisabledThenTrackingProtectionIsEnabled() = runBlocking { + fun `onAppTPToggleSwitched - tracking protection enabled`() = runBlocking { whenever(vpnDetector.isExternalVpnDetected()).thenReturn(false) viewModel.commands().test { viewModel.onAppTPToggleSwitched(true) @@ -144,7 +144,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenToggleIsSwitchedOffAndOtherVPNIsDisabledThenConfirmationDialogIsShown() = runBlocking { + fun `onAppTPToggleSwitched - confirmation dialog shown`() = runBlocking { whenever(vpnDetector.isExternalVpnDetected()).thenReturn(false) viewModel.commands().test { viewModel.onAppTPToggleSwitched(false) @@ -154,7 +154,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenVpnPermissionIsNeededThenVpnPermissionRequestIsLaunched() = runBlocking { + fun `onVPNPermissionNeeded - vpn permission request launched`() = runBlocking { viewModel.commands().test { val permissionIntent = Intent() viewModel.onVPNPermissionNeeded(permissionIntent) @@ -164,7 +164,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenVpnPermissionResultIsOKThenVpnIsLaunched() = runBlocking { + fun `onVPNPermissionResult - vpn launched`() = runBlocking { viewModel.commands().test { viewModel.onVPNPermissionResult(AppCompatActivity.RESULT_OK) assertEquals(DeviceShieldTrackerActivityViewModel.Command.LaunchVPN, awaitItem()) @@ -173,7 +173,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenVpnLaunchedAlwaysOnDisabledAndSystemKilledAppTpThenShowAlwaysOnPromotion() = runBlocking { + fun `onVPNPermissionResult - always on disabled and system killed app tp - show always on promotion dialog`() = runBlocking { whenever(vpnStateMonitor.isAlwaysOnEnabled()).thenReturn(false) whenever(vpnStateMonitor.vpnLastDisabledByAndroid()).thenReturn(true) @@ -187,7 +187,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenVpnLaunchedAlwaysOnDisabledAndSystemDidNotKilledAppTpThenDoNotShowAlwaysOnPromotion() = runBlocking { + fun `onVPNPermissionResult - always on disabled and system did not kill app tp - do not show always on promotion`() = runBlocking { whenever(vpnStateMonitor.isAlwaysOnEnabled()).thenReturn(false) whenever(vpnStateMonitor.vpnLastDisabledByAndroid()).thenReturn(false) @@ -199,7 +199,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenVPNInAlwaysOnModeThenShowPromoteAlwaysOnDialogCommandIsNotSent() = runBlocking { + fun `onVPNPermissionResult - vpn in always on mode - show promote always on dialog command is not sent`() = runBlocking { whenever(vpnStateMonitor.isAlwaysOnEnabled()).thenReturn(true) whenever(vpnStateMonitor.vpnLastDisabledByAndroid()).thenReturn(true) @@ -211,7 +211,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenVpnPermissionResultIsDeniedAndRequestTimeWasSmallerThanNeededThenVpnConflictDialogIsShown() = runBlocking { + fun `onVPNPermissionNeeded - vpn permission result denied and request time was smaller than needed - show vpn always on conflict dialog`() = runBlocking { viewModel.commands().test { val permissionIntent = Intent() viewModel.onVPNPermissionNeeded(permissionIntent) @@ -224,7 +224,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenVpnPermissionResultIsDeniedAndRequestTimeWasHigherThanNeededThenVpnIsStopped() = runBlocking { + fun `onVPNPermissionNeeded - vpn permission result denied and request time was higher than needed - vpn is stopped`() = runBlocking { viewModel.commands().test { val permissionIntent = Intent() viewModel.onVPNPermissionNeeded(permissionIntent) @@ -238,7 +238,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenToggleIsSwitchedOnAndOtherVPNIsEnabledThenVpnConflictDialogIsShown() = runBlocking { + fun `onAppTPToggleSwitched - vpn conflict dialog shown`() = runBlocking { whenever(vpnDetector.isExternalVpnDetected()).thenReturn(true) viewModel.commands().test { viewModel.onAppTPToggleSwitched(true) @@ -248,7 +248,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenAppTPIsManuallyDisabledThenTrackingProtectionIsStopped() = runBlocking { + fun `onAppTpManuallyDisabled - tracking protection stopped`() = runBlocking { viewModel.commands().test { viewModel.onAppTpManuallyDisabled() @@ -260,7 +260,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenUserWantsToRemoveFeatureThenDalogIsShown() = runBlocking { + fun `whenUserWantsToRemoveFeatureThenDalogIsShown - show remove feature confirmation dialog`() = runBlocking { viewModel.commands().test { viewModel.onViewEvent(ViewEvent.AskToRemoveFeature) @@ -271,7 +271,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenUserAcceptsToRemoveFeatureThenFeatureIsRemovedAndVpnAndScreenClosed() = runBlocking { + fun `whenUserAcceptsToRemoveFeature - feature removed and vpn and screen closed`() = runBlocking { viewModel.commands().test { viewModel.onViewEvent(ViewEvent.RemoveFeature) @@ -285,7 +285,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenPromoteAlwaysOnOpenSettingsSelectedThenCommandIsSent() = runBlocking { + fun `commands - promote always on open settings selected - command sent`() = runBlocking { viewModel.commands().test { viewModel.onViewEvent(ViewEvent.PromoteAlwaysOnOpenSettings) @@ -297,7 +297,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenAppTpEnabledCtaShownAndListShownThenNoCommandSent() = runBlocking { + fun `showAppTpEnabledCtaIfNeeded - app tp enabled cta shown and list shown - no command sent`() = runBlocking { whenever(vpnStore.didShowAppTpEnabledCta()).thenReturn(true) viewModel.commands().test { @@ -309,7 +309,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenAppTpEnabledCtaNotAlreadyShownAndListShownThenCommandSent() = runBlocking { + fun `showAppTpEnabledCtaIfNeeded - app tp enabled cta not already shown and list shown - command sent`() = runBlocking { whenever(vpnStore.didShowAppTpEnabledCta()).thenReturn(false) viewModel.commands().test { @@ -322,7 +322,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenBannerStateCalledOutsideOnboardingSessionThenReturnNextSessionBanner() { + fun `bannerState - outside onboarding session - next session banner`() { whenever(vpnStore.getAndSetOnboardingSession()).thenReturn(false) val bannerState = viewModel.bannerState() @@ -331,7 +331,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenBannerStateCalledDuringOnboardingSessionThenReturnOnboardingBanner() { + fun `bannerState - onboarding session - onboarding banner`() { whenever(vpnStore.getAndSetOnboardingSession()).thenReturn(true) val bannerState = viewModel.bannerState() diff --git a/app-tracking-protection/vpn-store/src/test/java/com/duckduckgo/mobile/android/vpn/stats/AppTrackerBlockingStatsRepositoryTest.kt b/app-tracking-protection/vpn-store/src/test/java/com/duckduckgo/mobile/android/vpn/stats/AppTrackerBlockingStatsRepositoryTest.kt index 5a4da8a8c5eb..c8b2226b6a90 100644 --- a/app-tracking-protection/vpn-store/src/test/java/com/duckduckgo/mobile/android/vpn/stats/AppTrackerBlockingStatsRepositoryTest.kt +++ b/app-tracking-protection/vpn-store/src/test/java/com/duckduckgo/mobile/android/vpn/stats/AppTrackerBlockingStatsRepositoryTest.kt @@ -63,7 +63,7 @@ class AppTrackerBlockingStatsRepositoryTest { } @Test - fun whenSingleTrackerEntryAddedButNoRelatedEntityThenReturnNoTracker() = runBlocking { + fun `addTracker - no related entity - return no tracker`() = runBlocking { val trackerDomain = "example.com" addTrackerAndReturn(trackerDomain) val vpnTrackers = repository.getVpnTrackers({ dateOfPreviousMidnightAsString() }).firstOrNull() @@ -71,7 +71,7 @@ class AppTrackerBlockingStatsRepositoryTest { } @Test - fun whenSingleTrackerEntryAddedForTodayBucketThenBlockerReturned() = runBlocking { + fun `getVpnTrackers - single tracker entry added for today bucket - blocker returned`() = runBlocking { val trackerDomain = "example.com" val entity = addTrackerAndReturn(trackerDomain).asEntity() db.vpnAppTrackerBlockingDao().insertTrackerEntities(listOf(entity)) @@ -81,7 +81,7 @@ class AppTrackerBlockingStatsRepositoryTest { } @Test - fun whenSameTrackerFoundMultipleTimesTodayThenAllInstancesOfBlockerReturned() = runBlocking { + fun `whenSameTrackerFoundMultipleTimesTodayThenAllInstancesOfBlockerReturned - all instances of blocker returned`() = runBlocking { val trackerDomain = "example.com" addTrackerAndReturn(trackerDomain) val entity = addTrackerAndReturn(trackerDomain).asEntity() @@ -92,19 +92,19 @@ class AppTrackerBlockingStatsRepositoryTest { } @Test - fun whenTrackerFoundBeforeTodayThenNotReturned() = runBlocking { + fun `getVpnTrackers - tracker found before today - not returned`() = runBlocking { trackerFoundYesterday() val vpnTrackers = repository.getVpnTrackers({ dateOfPreviousMidnightAsString() }).firstOrNull() assertNoTrackers(vpnTrackers) } @Test - fun whenContainsVpnTrackersAndDbTableEmptyThenReturnFalse() = runTest { + fun `containsVpnTrackers - db table empty - return false`() = runTest { assertFalse(repository.containsVpnTrackers()) } @Test - fun whenContainsVpnTrackersAndDbTableNotEmptyThenReturnTrue() = runTest { + fun `containsVpnTrackers - db table not empty - true`() = runTest { addTrackerAndReturn() assertTrue(repository.containsVpnTrackers()) diff --git a/app-tracking-protection/vpn-store/src/test/java/com/duckduckgo/mobile/android/vpn/store/VpnDatabaseTest.kt b/app-tracking-protection/vpn-store/src/test/java/com/duckduckgo/mobile/android/vpn/store/VpnDatabaseTest.kt index 4aac4971161b..92d5b333a4f3 100644 --- a/app-tracking-protection/vpn-store/src/test/java/com/duckduckgo/mobile/android/vpn/store/VpnDatabaseTest.kt +++ b/app-tracking-protection/vpn-store/src/test/java/com/duckduckgo/mobile/android/vpn/store/VpnDatabaseTest.kt @@ -37,7 +37,7 @@ class VpnDatabaseTest { MigrationTestHelper(InstrumentationRegistry.getInstrumentation(), VpnDatabase::class.qualifiedName!!, FrameworkSQLiteOpenHelperFactory()) @Test - fun whenTestingAllMigrationsThenSucceeds() { + fun `whenTestingAllMigrations - succeeds`() { createDatabase(18) Room.databaseBuilder( diff --git a/app-tracking-protection/vpn-store/src/test/java/com/duckduckgo/mobile/android/vpn/trackers/AppTrackerJsonParserTest.kt b/app-tracking-protection/vpn-store/src/test/java/com/duckduckgo/mobile/android/vpn/trackers/AppTrackerJsonParserTest.kt index a25748bd5535..c28acfe64f40 100644 --- a/app-tracking-protection/vpn-store/src/test/java/com/duckduckgo/mobile/android/vpn/trackers/AppTrackerJsonParserTest.kt +++ b/app-tracking-protection/vpn-store/src/test/java/com/duckduckgo/mobile/android/vpn/trackers/AppTrackerJsonParserTest.kt @@ -26,7 +26,7 @@ class AppTrackerJsonParserTest { private val moshi = Moshi.Builder().build() @Test - fun whenJsonIsValidThenBlocklistIsParsed() { + fun `parseAppTrackerJson - json is valid - blocklist parsed`() { val json = loadText(javaClass.classLoader!!, "full_app_trackers_blocklist.json") val blocklist = AppTrackerJsonParser.parseAppTrackerJson(moshi, json) diff --git a/app-tracking-protection/vpn-store/src/test/java/com/duckduckgo/mobile/android/vpn/trackers/AppTrackerRepositoryTest.kt b/app-tracking-protection/vpn-store/src/test/java/com/duckduckgo/mobile/android/vpn/trackers/AppTrackerRepositoryTest.kt index 4d2578fd2940..c6d918284265 100644 --- a/app-tracking-protection/vpn-store/src/test/java/com/duckduckgo/mobile/android/vpn/trackers/AppTrackerRepositoryTest.kt +++ b/app-tracking-protection/vpn-store/src/test/java/com/duckduckgo/mobile/android/vpn/trackers/AppTrackerRepositoryTest.kt @@ -51,17 +51,17 @@ class AppTrackerRepositoryTest { } @Test - fun whenHostnameIsTrackerThenReturnTracker() { + fun `findTracker - hostname is tracker - return tracker`() { assertTrackerTypeFound(appTrackerRepository.findTracker("g.doubleclick.net", "")) } @Test - fun whenSubdomainIsTrackerThenReturnTracker() { + fun `findTracker - subdomain is tracker - return tracker`() { assertTrackerTypeFound(appTrackerRepository.findTracker("foo.g.doubleclick.net", "")) } @Test - fun whenHostnameIsNotTrackerThenReturnNull() { + fun `findTracker - hostname not tracker - return null`() { assertNotTrackerType(appTrackerRepository.findTracker("not.tracker.net", "")) } diff --git a/app/src/test/java/com/duckduckgo/app/about/AboutDuckDuckGoViewModelTest.kt b/app/src/test/java/com/duckduckgo/app/about/AboutDuckDuckGoViewModelTest.kt index 35016c68e8f2..3c454c3b415d 100644 --- a/app/src/test/java/com/duckduckgo/app/about/AboutDuckDuckGoViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/about/AboutDuckDuckGoViewModelTest.kt @@ -67,7 +67,7 @@ internal class AboutDuckDuckGoViewModelTest { } @Test - fun whenInitialisedThenViewStateEmittedWithDefaultValues() = runTest { + fun `initialise - view state emitted with default values`() = runTest { testee.viewState().test { val value = awaitItem() @@ -78,7 +78,7 @@ internal class AboutDuckDuckGoViewModelTest { } @Test - fun whenOnLearnMoreLinkClickedThenCommandLaunchBrowserWithLearnMoreUrlIsSentAndPixelFired() = runTest { + fun `onLearnMoreLinkClicked - command launch browser with learn more url is sent and pixel fired`() = runTest { testee.commands().test { testee.onLearnMoreLinkClicked() @@ -90,7 +90,7 @@ internal class AboutDuckDuckGoViewModelTest { } @Test - fun whenOnPrivacyPolicyClickedThenCommandLaunchWebViewWithPrivacyPolicyUrlIsSentAndPixelFired() = runTest { + fun `onPrivacyPolicyClicked - command launch web view with privacy policy url is sent and pixel fired`() = runTest { testee.commands().test { testee.onPrivacyPolicyClicked() @@ -102,7 +102,7 @@ internal class AboutDuckDuckGoViewModelTest { } @Test - fun whenVersionClickedAndNetPWaitlistStateIsOtherThanNotUnlockedThenNoCommandIsSentAndPixelNotSent() = runTest { + fun `onVersionClicked - netPWaitlistState other than not unlocked - no command sent and pixel not sent`() = runTest { testee.commands().test { testee.onVersionClicked() verify(mockPixel, never()).fire(AppPixelName.SETTINGS_ABOUT_DDG_VERSION_EASTER_EGG_PRESSED) @@ -112,7 +112,7 @@ internal class AboutDuckDuckGoViewModelTest { } @Test - fun whenVersionClickedLessThanMaxTimesAndNetPWaitlistStateIsNotUnlockedThenNoCommandIsSentAndPixelNotSent() = runTest { + fun `onVersionClicked - net p waitlist state not unlocked - no command sent and pixel not sent`() = runTest { testee.commands().test { testee.onVersionClicked() verify(mockPixel, never()).fire(AppPixelName.SETTINGS_ABOUT_DDG_VERSION_EASTER_EGG_PRESSED) @@ -122,7 +122,7 @@ internal class AboutDuckDuckGoViewModelTest { } @Test - fun whenVersionClickedMaxTimesCounterResetAndPixelSent() = runTest { + fun `onVersionClicked - max times counter reset and pixel sent`() = runTest { testee.commands().test { for (i in 1..MAX_EASTER_EGG_COUNT) { testee.onVersionClicked() @@ -136,7 +136,7 @@ internal class AboutDuckDuckGoViewModelTest { } @Test - fun whenOnProvideFeedbackClickedThenCommandLaunchFeedbackIsSent() = runTest { + fun `onProvideFeedbackClicked - command launch feedback is sent`() = runTest { testee.commands().test { testee.onProvideFeedbackClicked() @@ -148,7 +148,7 @@ internal class AboutDuckDuckGoViewModelTest { } @Test - fun whenResetNetPEasterEggCounterIsCalledThenEasterEggCounterIsZero() = runTest { + fun `resetEasterEggCounter - easter egg counter reset`() = runTest { testee.onVersionClicked() assertFalse(testee.hasResetEasterEggCounter()) diff --git a/app/src/test/java/com/duckduckgo/app/accessibility/AccessibilitySettingsViewModelTest.kt b/app/src/test/java/com/duckduckgo/app/accessibility/AccessibilitySettingsViewModelTest.kt index d41d51ec7b51..689c4c0a8e5d 100644 --- a/app/src/test/java/com/duckduckgo/app/accessibility/AccessibilitySettingsViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/accessibility/AccessibilitySettingsViewModelTest.kt @@ -45,7 +45,7 @@ class AccessibilitySettingsViewModelTest { private val testee = AccessibilitySettingsViewModel(accessibilitySettings, voiceSearchAvailability, voiceSearchRepository, pixel) @Test - fun whenViewModelCreatedThenDefaultViewStateEmitted() = runTest { + fun `viewState - default view state emitted`() = runTest { val viewState = AccessibilitySettingsViewModel.ViewState( overrideSystemFontSize = false, appFontSize = 100f, @@ -60,7 +60,7 @@ class AccessibilitySettingsViewModelTest { } @Test - fun whenViewModelStartedThenViewStateEmitted() = runTest { + fun `start - view state emitted`() = runTest { val viewState = AccessibilitySettingsViewModel.ViewState( overrideSystemFontSize = true, appFontSize = 150f, @@ -83,7 +83,7 @@ class AccessibilitySettingsViewModelTest { } @Test - fun whenForceZoomEnabledThenViewStateEmitted() = runTest { + fun `onForceZoomChanged - view state emitted`() = runTest { val viewState = defaultViewState() whenever(accessibilitySettings.forceZoom).thenReturn(true) @@ -96,7 +96,7 @@ class AccessibilitySettingsViewModelTest { } @Test - fun whenForceZoomEnabledThenSettingsUpdated() = runTest { + fun `onForceZoomChanged - settings updated`() = runTest { whenever(accessibilitySettings.forceZoom).thenReturn(true) testee.onForceZoomChanged(true) @@ -106,7 +106,7 @@ class AccessibilitySettingsViewModelTest { } @Test - fun whenOverrideSystemFontSizeEnabledThenViewStateEmitted() = runTest { + fun `onSystemFontSizeChanged - view state emitted`() = runTest { val viewState = defaultViewState() whenever(accessibilitySettings.overrideSystemFontSize).thenReturn(true) @@ -119,7 +119,7 @@ class AccessibilitySettingsViewModelTest { } @Test - fun whenOverrideSystemFontSizeEnabledThenSettingsUpdated() = runTest { + fun `onSystemFontSizeChanged - settings updated`() = runTest { whenever(accessibilitySettings.overrideSystemFontSize).thenReturn(true) testee.onSystemFontSizeChanged(true) @@ -129,7 +129,7 @@ class AccessibilitySettingsViewModelTest { } @Test - fun whenFontSizeChangedThenViewStateEmitted() = runTest { + fun `onFontSizeChanged - view state emitted`() = runTest { val viewState = defaultViewState() whenever(accessibilitySettings.appFontSize).thenReturn(150f) @@ -142,7 +142,7 @@ class AccessibilitySettingsViewModelTest { } @Test - fun whenFontSizeChangedThenSettingsUpdated() = runTest { + fun `onFontSizeChanged - settings updated`() = runTest { whenever(accessibilitySettings.appFontSize).thenReturn(150f) testee.onFontSizeChanged(150f) @@ -152,7 +152,7 @@ class AccessibilitySettingsViewModelTest { } @Test - fun whenVoiceSearchEnabledThenViewStateEmitted() = runTest { + fun `onVoiceSearchChanged - view state emitted`() = runTest { val viewState = defaultViewState() whenever(voiceSearchAvailability.isVoiceSearchAvailable).thenReturn(true) @@ -165,25 +165,25 @@ class AccessibilitySettingsViewModelTest { } @Test - fun whenVoiceSearchEnabledThenSettingsUpdated() = runTest { + fun `onVoiceSearchChanged - settings updated`() = runTest { testee.onVoiceSearchChanged(true) verify(voiceSearchRepository).setVoiceSearchUserEnabled(true) } @Test - fun whenVoiceSearchDisabledThenSettingsUpdated() = runTest { + fun `onVoiceSearchChanged - settings updated - voice search disabled`() = runTest { testee.onVoiceSearchChanged(false) verify(voiceSearchRepository).setVoiceSearchUserEnabled(false) } @Test - fun whenVoiceSearchEnabledThenFirePixel() = runTest { + fun `onVoiceSearchChanged - fire pixel`() = runTest { testee.onVoiceSearchChanged(true) verify(pixel).fire(VoiceSearchPixelNames.VOICE_SEARCH_ON) } @Test - fun whenVoiceSearchDisabledThenFirePixel() = runTest { + fun `onVoiceSearchChanged - voice search disabled - fire pixel`() = runTest { testee.onVoiceSearchChanged(false) verify(pixel).fire(VoiceSearchPixelNames.VOICE_SEARCH_OFF) } diff --git a/app/src/test/java/com/duckduckgo/app/appearance/AppearanceViewModelTest.kt b/app/src/test/java/com/duckduckgo/app/appearance/AppearanceViewModelTest.kt index 25e224c60a29..f942db56ade8 100644 --- a/app/src/test/java/com/duckduckgo/app/appearance/AppearanceViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/appearance/AppearanceViewModelTest.kt @@ -73,7 +73,7 @@ internal class AppearanceViewModelTest { } @Test - fun whenInitialisedThenViewStateEmittedWithDefaultValues() = runTest { + fun `initialise - view state emitted with default values`() = runTest { testee.viewState().test { val value = awaitItem() @@ -85,13 +85,13 @@ internal class AppearanceViewModelTest { } @Test - fun whenThemeSettingsClickedThenPixelSent() { + fun `whenThemeSettingsClicked - pixel sent`() { testee.userRequestedToChangeTheme() verify(mockPixel).fire(AppPixelName.SETTINGS_THEME_OPENED) } @Test - fun whenThemeSettingsClickedThenCommandIsLaunchThemeSettingsIsSent() = runTest { + fun `commands - theme settings clicked - launch theme settings is sent`() = runTest { testee.commands().test { testee.userRequestedToChangeTheme() @@ -102,7 +102,7 @@ internal class AppearanceViewModelTest { } @Test - fun whenChangeIconRequestedThenCommandIsChangeIconAndPixelSent() = runTest { + fun `userRequestedToChangeIcon - command is change icon and pixel sent`() = runTest { testee.commands().test { testee.userRequestedToChangeIcon() @@ -114,7 +114,7 @@ internal class AppearanceViewModelTest { } @Test - fun whenThemeChangedThenDataStoreIsUpdatedAndUpdateThemeCommandIsSent() = runTest { + fun `onThemeSelected - data store updated - update theme command sent`() = runTest { testee.commands().test { givenThemeSelected(DuckDuckGoTheme.LIGHT) testee.onThemeSelected(DuckDuckGoTheme.DARK) @@ -128,28 +128,28 @@ internal class AppearanceViewModelTest { } @Test - fun whenThemeChangedToLightThenLightThemePixelIsSent() { + fun `onThemeSelected - theme changed to light - light theme pixel is sent`() { givenThemeSelected(DuckDuckGoTheme.DARK) testee.onThemeSelected(DuckDuckGoTheme.LIGHT) verify(mockPixel).fire(AppPixelName.SETTINGS_THEME_TOGGLED_LIGHT) } @Test - fun whenThemeChangedToDarkThenDarkThemePixelIsSent() { + fun `onThemeSelected - theme changed to dark - dark theme pixel is sent`() { givenThemeSelected(DuckDuckGoTheme.LIGHT) testee.onThemeSelected(DuckDuckGoTheme.DARK) verify(mockPixel).fire(AppPixelName.SETTINGS_THEME_TOGGLED_DARK) } @Test - fun whenThemeChangedToSystemDefaultThenSystemDefaultThemePixelIsSent() { + fun `onThemeSelected - theme changed to system default - system default theme pixel is sent`() { givenThemeSelected(DuckDuckGoTheme.LIGHT) testee.onThemeSelected(DuckDuckGoTheme.SYSTEM_DEFAULT) verify(mockPixel).fire(AppPixelName.SETTINGS_THEME_TOGGLED_SYSTEM_DEFAULT) } @Test - fun whenThemeChangedButThemeWasAlreadySetThenDoNothing() = runTest { + fun `onThemeSelected - theme already set - do nothing`() = runTest { testee.commands().test { givenThemeSelected(DuckDuckGoTheme.LIGHT) testee.onThemeSelected(DuckDuckGoTheme.LIGHT) diff --git a/app/src/test/java/com/duckduckgo/app/autocomplete/api/AutoCompleteApiTest.kt b/app/src/test/java/com/duckduckgo/app/autocomplete/api/AutoCompleteApiTest.kt index 315537169066..320b2892dd06 100644 --- a/app/src/test/java/com/duckduckgo/app/autocomplete/api/AutoCompleteApiTest.kt +++ b/app/src/test/java/com/duckduckgo/app/autocomplete/api/AutoCompleteApiTest.kt @@ -55,7 +55,7 @@ class AutoCompleteApiTest { } @Test - fun whenQueryIsBlankThenReturnAnEmptyList() { + fun `autoComplete - query is blank - return empty list`() { val result = testee.autoComplete("").test() val value = result.values()[0] as AutoCompleteResult @@ -63,7 +63,7 @@ class AutoCompleteApiTest { } @Test - fun whenReturnBookmarkSuggestionsThenPhraseIsURLBaseHost() { + fun `autoComplete - return bookmark suggestions - phrase is URL base host`() { whenever(mockAutoCompleteService.autoComplete("title")).thenReturn(Observable.just(emptyList())) whenever(mockSavedSitesRepository.getBookmarksObservable()).thenReturn(Single.just(bookmarks())) whenever(mockSavedSitesRepository.getFavoritesObservable()).thenReturn(Single.just(emptyList())) @@ -75,7 +75,7 @@ class AutoCompleteApiTest { } @Test - fun whenAutoCompleteDoesNotMatchAnySavedSiteReturnEmptySavedSiteList() { + fun `autoComplete - does not match any saved site - empty saved site list`() { whenever(mockAutoCompleteService.autoComplete("wrong")).thenReturn(Observable.just(emptyList())) whenever(mockSavedSitesRepository.getBookmarksObservable()).thenReturn( @@ -97,7 +97,7 @@ class AutoCompleteApiTest { } @Test - fun whenAutoCompleteReturnsMultipleBookmarkHitsThenLimitToMaxOfTwo() { + fun `autoComplete - returns multiple bookmark hits - limit to max of two`() { whenever(mockAutoCompleteService.autoComplete("title")).thenReturn(Observable.just(emptyList())) whenever(mockSavedSitesRepository.getBookmarksObservable()).thenReturn( Single.just( @@ -124,7 +124,7 @@ class AutoCompleteApiTest { } @Test - fun whenAutoCompleteReturnsMultipleSavedSitesHitsThenLimitToMaxOfTwoFavoritesFirst() { + fun `autoComplete - returns multiple saved sites hits - limit to max of two favorites first`() { whenever(mockAutoCompleteService.autoComplete("title")).thenReturn(Observable.just(emptyList())) whenever(mockSavedSitesRepository.getBookmarksObservable()).thenReturn( Single.just( @@ -160,7 +160,7 @@ class AutoCompleteApiTest { } @Test - fun whenAutoCompleteReturnsDuplicatedItemsThenDedup() { + fun `autoComplete - deduplication`() { whenever(mockAutoCompleteService.autoComplete("title")).thenReturn( Observable.just( listOf( @@ -212,7 +212,7 @@ class AutoCompleteApiTest { } @Test - fun whenReturnOneBookmarkAndOneFavoriteSuggestionsThenShowBothFavoriteFirst() { + fun `autoComplete - return one bookmark and one favorite suggestions - show both favorites first`() { whenever(mockAutoCompleteService.autoComplete("title")).thenReturn(Observable.just(emptyList())) whenever(mockSavedSitesRepository.getBookmarksObservable()).thenReturn( Single.just( @@ -248,7 +248,7 @@ class AutoCompleteApiTest { } @Test - fun whenAutoCompleteReturnsDuplicatedItemsThenDedupConsideringQueryParams() { + fun `autoComplete - duplicated items - dedup considering query params`() { whenever(mockAutoCompleteService.autoComplete("title")).thenReturn( Observable.just( listOf( @@ -290,7 +290,7 @@ class AutoCompleteApiTest { } @Test - fun whenBookmarkTitleStartsWithQueryThenScoresHigher() { + fun `autoComplete - when bookmark title starts with query then scores higher - higher score`() { whenever(mockAutoCompleteService.autoComplete("title")).thenReturn(Observable.just(listOf())) whenever(mockSavedSitesRepository.getBookmarksObservable()).thenReturn( Single.just( @@ -321,7 +321,7 @@ class AutoCompleteApiTest { } @Test - fun whenSingleTokenQueryAndBookmarkDomainStartsWithItThenScoreHigher() { + fun `autoComplete - single token query and bookmark domain starts with it - score higher`() { whenever(mockAutoCompleteService.autoComplete("foo")).thenReturn(Observable.just(listOf())) whenever(mockSavedSitesRepository.getBookmarksObservable()).thenReturn( Single.just( @@ -347,7 +347,7 @@ class AutoCompleteApiTest { } @Test - fun whenSingleTokenQueryAndBookmarkReturnsDuplicatedItemsThenDedup() { + fun `whenSingleTokenQueryAndBookmarkReturnsDuplicatedItemsThenDedup - state - deduplicates bookmark suggestions`() { whenever(mockAutoCompleteService.autoComplete("cnn")).thenReturn(Observable.just(listOf())) whenever(mockSavedSitesRepository.getBookmarksObservable()).thenReturn( Single.just( @@ -377,7 +377,7 @@ class AutoCompleteApiTest { } @Test - fun whenSingleTokenQueryEndsWithSlashThenIgnoreItWhileMatching() { + fun `autoComplete - single token query ends with slash - ignores it while matching`() { whenever(mockAutoCompleteService.autoComplete("reddit.com/")).thenReturn(Observable.just(listOf())) whenever(mockSavedSitesRepository.getBookmarksObservable()).thenReturn( Single.just( @@ -406,7 +406,7 @@ class AutoCompleteApiTest { } @Test - fun whenSingleTokenQueryEndsWithMultipleSlashThenIgnoreThemWhileMatching() { + fun `autoComplete - single token query ends with multiple slash - ignores them while matching`() { whenever(mockAutoCompleteService.autoComplete("reddit.com///")).thenReturn(Observable.just(listOf())) whenever(mockSavedSitesRepository.getBookmarksObservable()).thenReturn( Single.just( @@ -435,7 +435,7 @@ class AutoCompleteApiTest { } @Test - fun whenSingleTokenQueryContainsMultipleSlashThenIgnoreThemWhileMatching() { + fun `autoComplete - single token query contains multiple slash - ignore them while matching`() { whenever(mockAutoCompleteService.autoComplete("reddit.com/r//")).thenReturn(Observable.just(listOf())) whenever(mockSavedSitesRepository.getBookmarksObservable()).thenReturn( Single.just( @@ -463,7 +463,7 @@ class AutoCompleteApiTest { } @Test - fun whenSingleTokenQueryDomainContainsWwwThenResultMathUrl() { + fun `autoComplete - single token query domain contains www - result matches url`() { whenever(mockAutoCompleteService.autoComplete("reddit")).thenReturn(Observable.just(listOf())) whenever(mockSavedSitesRepository.getBookmarksObservable()).thenReturn( Single.just( @@ -492,7 +492,7 @@ class AutoCompleteApiTest { } @Test - fun whenMultipleTokenQueryAndNoTokenMatchThenReturnEmpty() { + fun `autoComplete - multiple token query and no token match - return empty`() { val query = "example title foo" whenever(mockAutoCompleteService.autoComplete(query)).thenReturn(Observable.just(listOf())) whenever(mockSavedSitesRepository.getBookmarksObservable()).thenReturn( @@ -514,7 +514,7 @@ class AutoCompleteApiTest { } @Test - fun whenMultipleTokenQueryAndMultipleMatchesThenReturnCorrectScore() { + fun `autoComplete - multiple token query and multiple matches - return correct score`() { val query = "title foo" whenever(mockAutoCompleteService.autoComplete(query)).thenReturn(Observable.just(listOf())) whenever(mockSavedSitesRepository.getBookmarksObservable()).thenReturn( diff --git a/app/src/test/java/com/duckduckgo/app/bookmarks/mapper/migration/BookmarksMigrationTest.kt b/app/src/test/java/com/duckduckgo/app/bookmarks/mapper/migration/BookmarksMigrationTest.kt index 92524f29b0f2..25bd08db33f8 100644 --- a/app/src/test/java/com/duckduckgo/app/bookmarks/mapper/migration/BookmarksMigrationTest.kt +++ b/app/src/test/java/com/duckduckgo/app/bookmarks/mapper/migration/BookmarksMigrationTest.kt @@ -80,7 +80,7 @@ class BookmarksMigrationTest { } @Test - fun whenMigrationRunsThenAllFormFactorFavoriteFoldersCreated() { + fun `whenMigrationRuns - all form factor favorite folders created`() { whenMigrationApplied() val allFolders = appDatabase.syncEntitiesDao().allEntitiesByTypeSync(EntityType.FOLDER) @@ -91,7 +91,7 @@ class BookmarksMigrationTest { } @Test - fun whenFavoritesExistThenMigrationIsSuccessful() = runTest { + fun `whenFavoritesExist - migration successful - favorites exist`() = runTest { val totalFavorites = 10 givenSomeFavorites(totalFavorites) whenMigrationApplied() @@ -104,7 +104,7 @@ class BookmarksMigrationTest { } @Test - fun whenBookmarksWithoutFoldersExistThenMigrationIsSuccessful() = runTest { + fun `whenBookmarksWithoutFoldersExist - migration is successful`() = runTest { val totalBookmarks = 10 givenSomeBookmarks(totalBookmarks, SavedSitesNames.BOOMARKS_ROOT_ID) @@ -124,7 +124,7 @@ class BookmarksMigrationTest { } @Test - fun whenBookmarksWithFoldersExistThenMigrationIsSuccessful() = runTest { + fun `whenBookmarksWithFoldersExist - migration is successful`() = runTest { val totalFolder = 10 val bookmarksPerFolder = 5 createFoldersTree(totalFolder, bookmarksPerFolder) @@ -145,7 +145,7 @@ class BookmarksMigrationTest { } @Test - fun whenBookmarksWithFoldersAndFavoritesExistThenMigrationIsSuccessful() = runTest { + fun `whenBookmarksWithFoldersAndFavoritesExistThenMigrationIsSuccessful - migration is successful`() = runTest { val totalFolder = 10 val bookmarksPerFolder = 5 createFoldersTree(totalFolder, bookmarksPerFolder) @@ -166,7 +166,7 @@ class BookmarksMigrationTest { } @Test - fun whenBookmarkAndFavoriteHaveSameUrlThenBookmarkAlsoMigratedAsFavorite() { + fun `whenBookmarkAndFavoriteHaveSameUrlThenBookmarkAlsoMigratedAsFavorite - when migration applied - bookmark and favorite migrated`() { bookmarksDao.insert(BookmarkEntity(1, "bookmark1", "http://test.com", 0)) favoritesDao.insert(FavoriteEntity(2, "favorite1", "http://test.com", 0)) @@ -189,7 +189,7 @@ class BookmarksMigrationTest { } @Test - fun whenBookmarkAndFavoriteHaveDifferentUrlThenBothAreMigrated() { + fun `whenBookmarkAndFavoriteHaveDifferentUrlThenBothAreMigrated - both are migrated`() { bookmarksDao.insert(BookmarkEntity(1, "Bookmark1", "http://test.com", 0)) favoritesDao.insert(FavoriteEntity(2, "Favorite1", "http://testee.com", 0)) @@ -215,7 +215,7 @@ class BookmarksMigrationTest { } @Test - fun whenDataIsMigratedThenOldTablesAreDeleted() { + fun `whenDataIsMigrated - old tables deleted`() { givenSomeFavorites(10) givenSomeBookmarks(5, SavedSitesNames.BOOMARKS_ROOT_ID) whenMigrationApplied() @@ -226,7 +226,7 @@ class BookmarksMigrationTest { } @Test - fun whenNeedsFormFactorMigrationThenFavoritesAreCopiedIntoFormFactorFavoriteFolder() { + fun `whenNeedsFormFactorMigrationThenFavoritesAreCopiedIntoFormFactorFavoriteFolder - favorites copied into form factor favorite folder`() { givenSomeFavoritesSavedSites(10) whenMigrationApplied() @@ -238,7 +238,7 @@ class BookmarksMigrationTest { } @Test - fun whenNeedsFormFactorMigrationThenFormFactorFolderLastModifiedUdpated() { + fun `whenNeedsFormFactorMigration - form factor folder last modified updated`() { givenSomeFavoritesSavedSites(10) whenMigrationApplied() @@ -247,7 +247,7 @@ class BookmarksMigrationTest { } @Test - fun whenAnyFavoriteRootFolderHasRelationWithBookmarksRootThenRemoveRelation() = runTest { + fun `whenAnyFavoriteRootFolderHasRelationWithBookmarksRootThenRemoveRelation - remove relation`() = runTest { givenFormFactorFolderExist() givenSomeFavoritesSavedSitesIn( total = 10, diff --git a/app/src/test/java/com/duckduckgo/app/bookmarks/model/SavedSitesParserTest.kt b/app/src/test/java/com/duckduckgo/app/bookmarks/model/SavedSitesParserTest.kt index fa553f4509cd..d84225158b76 100644 --- a/app/src/test/java/com/duckduckgo/app/bookmarks/model/SavedSitesParserTest.kt +++ b/app/src/test/java/com/duckduckgo/app/bookmarks/model/SavedSitesParserTest.kt @@ -106,7 +106,7 @@ class SavedSitesParserTest { } @Test - fun whenSomeBookmarksExistThenHtmlIsGenerated() = runTest { + fun `generateHtml - some bookmarks exist - html generated`() = runTest { val bookmark = Bookmark( id = "bookmark1", title = "example", @@ -142,7 +142,7 @@ class SavedSitesParserTest { } @Test - fun whenNoSavedSitesExistThenNothingIsGenerated() = runTest { + fun `generateHtml - no saved sites exist - nothing is generated`() = runTest { val node = TreeNode(FolderTreeItem(SavedSitesNames.BOOKMARKS_ROOT, RealSavedSitesParser.BOOKMARKS_FOLDER, "", null, 0)) val result = parser.generateHtml(node, emptyList()) @@ -152,7 +152,7 @@ class SavedSitesParserTest { } @Test - fun doesNotImportAnythingWhenFileIsNotProperlyFormatted() = runTest { + fun `parseHtml - file not properly formatted - does not import anything`() = runTest { val inputStream = FileUtilities.loadResource(javaClass.classLoader!!, "bookmarks/bookmarks_invalid.html") val document = Jsoup.parse(inputStream, Charsets.UTF_8.name(), "duckduckgo.com") @@ -162,7 +162,7 @@ class SavedSitesParserTest { } @Test - fun canImportFromFirefox() = runTest { + fun `canImportFromFirefox - import from firefox - 17 bookmarks`() = runTest { val inputStream = FileUtilities.loadResource(javaClass.classLoader!!, "bookmarks/bookmarks_firefox.html") val document = Jsoup.parse(inputStream, Charsets.UTF_8.name(), "duckduckgo.com") @@ -181,7 +181,7 @@ class SavedSitesParserTest { } @Test - fun canImportFromBrave() = runTest { + fun `canImportFromBrave - import from brave - 12 bookmarks`() = runTest { val inputStream = FileUtilities.loadResource(javaClass.classLoader!!, "bookmarks/bookmarks_brave.html") val document = Jsoup.parse(inputStream, Charsets.UTF_8.name(), "duckduckgo.com") @@ -202,7 +202,7 @@ class SavedSitesParserTest { } @Test - fun canImportFromChrome() = runTest { + fun `canImportFromChrome - import from chrome - 12 bookmarks imported`() = runTest { val inputStream = FileUtilities.loadResource(javaClass.classLoader!!, "bookmarks/bookmarks_chrome.html") val document = Jsoup.parse(inputStream, Charsets.UTF_8.name(), "duckduckgo.com") @@ -224,7 +224,7 @@ class SavedSitesParserTest { } @Test - fun canImportBookmarksFromDDGAndroid() = runTest { + fun `canImportBookmarksFromDDGAndroid - bookmarks parsed - 13 bookmarks expected`() = runTest { val inputStream = FileUtilities.loadResource(javaClass.classLoader!!, "bookmarks/bookmarks_ddg_android.html") val document = Jsoup.parse(inputStream, Charsets.UTF_8.name(), "duckduckgo.com") @@ -246,7 +246,7 @@ class SavedSitesParserTest { } @Test - fun canImportBookmarksFromDDGMacOS() = runTest { + fun `canImportBookmarksFromDDGMacOS - parse html - 13 bookmarks imported`() = runTest { val inputStream = FileUtilities.loadResource(javaClass.classLoader!!, "bookmarks/bookmarks_ddg_macos.html") val document = Jsoup.parse(inputStream, Charsets.UTF_8.name(), "duckduckgo.com") @@ -269,7 +269,7 @@ class SavedSitesParserTest { } @Test - fun canImportBookmarksFromSafari() = runTest { + fun `canImportBookmarksFromSafari - state - 14 bookmarks imported`() = runTest { val inputStream = FileUtilities.loadResource(javaClass.classLoader!!, "bookmarks/bookmarks_safari.html") val document = Jsoup.parse(inputStream, Charsets.UTF_8.name(), "duckduckgo.com") @@ -291,7 +291,7 @@ class SavedSitesParserTest { } @Test - fun canImportBookmarksAndFavoritesFromDDG() = runTest { + fun `canImportBookmarksAndFavoritesFromDDG - can import bookmarks and favorites from DDG - 12 sites imported`() = runTest { val inputStream = FileUtilities.loadResource(javaClass.classLoader!!, "bookmarks/bookmarks_favorites_ddg.html") val document = Jsoup.parse(inputStream, Charsets.UTF_8.name(), "duckduckgo.com") @@ -306,7 +306,7 @@ class SavedSitesParserTest { } @Test - fun parsesBookmarksAndFavorites() { + fun `parsesBookmarksAndFavorites - bookmarks and favorites parsed`() { val inputStream = FileUtilities.loadResource(javaClass.classLoader!!, "bookmarks/bookmarks_favorites_ddg.html") val document = Jsoup.parse(inputStream, Charsets.UTF_8.name(), "duckduckgo.com") diff --git a/app/src/test/java/com/duckduckgo/app/bookmarks/model/SavedSitesRepositoryTest.kt b/app/src/test/java/com/duckduckgo/app/bookmarks/model/SavedSitesRepositoryTest.kt index d6a59a2bc065..d9c2aa91dd5b 100644 --- a/app/src/test/java/com/duckduckgo/app/bookmarks/model/SavedSitesRepositoryTest.kt +++ b/app/src/test/java/com/duckduckgo/app/bookmarks/model/SavedSitesRepositoryTest.kt @@ -100,12 +100,12 @@ class SavedSitesRepositoryTest { } @Test - fun whenNoDataThenFolderContentisEmpty() = runTest { + fun `getFolderTreeItems - no data - empty`() = runTest { assert(repository.getFolderTreeItems(SavedSitesNames.BOOKMARKS_ROOT).isEmpty()) } @Test - fun whenRootFolderHasOnlyBookmarksThenDataIsRetrieved() = runTest { + fun `getFolderTreeItems - root folder has only bookmarks - data retrieved`() = runTest { val totalBookmarks = 10 val entities = givenSomeBookmarks(totalBookmarks) savedSitesEntitiesDao.insertList(entities) @@ -117,7 +117,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenRootFolderHasBookmarksAndFoldersThenDataIsRetrieved() = runTest { + fun `getFolderTreeItems - root folder has bookmarks and folders - data retrieved`() = runTest { val totalBookmarks = 10 val totalFolders = 3 @@ -138,7 +138,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenRequestingDataFromEmptyFolderThenNothingIsRetrieved() = runTest { + fun `getFolderTreeItems - empty folder - nothing is retrieved`() = runTest { val totalBookmarks = 10 val totalFolders = 3 @@ -155,7 +155,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenFavoriteIsAddedThenBookmarkIsAlsoAdded() { + fun `insertFavorite - bookmark added`() { givenEmptyDBState() repository.insertFavorite("favourite1", "https://favorite.com", "favorite", "timestamp") @@ -165,7 +165,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenBookmarkIsAddedThenFavoriteIsNotAdded() { + fun `insertBookmark - favorite not added - bookmark and favorite different`() { givenEmptyDBState() repository.insertBookmark("https://favorite.com", "favorite") @@ -175,7 +175,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenFavoriteIsAddedAndThenRemovedThenBookmarkStillExists() { + fun `getFavorite - favorite added and removed - bookmark still exists`() { givenEmptyDBState() val favorite = repository.insertFavorite("favourite1", "https://favorite.com", "favorite", "timestamp") @@ -189,7 +189,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenFavoriteIsAddedAndThenRemovedAndDeleteBookmarkIsTrueThenNothingIsRetrieved() { + fun `getFavorite - favorite added and removed - nothing retrieved`() { givenEmptyDBState() val favorite = repository.insertFavorite("favourite1", "https://favorite.com", "favorite", "timestamp") @@ -203,7 +203,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenBookmarkIsAddedAndThenRemovedThenNothingIsRetrieved() { + fun `insertAndDeleteBookmark - db state empty - nothing retrieved`() { givenEmptyDBState() val bookmark = repository.insertBookmark("https://favorite.com", "favorite") @@ -215,7 +215,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenInsertFavoriteThenReturnSavedSite() { + fun `insertFavorite - return saved site`() { givenNoFavoritesStored() val savedSite = repository.insertFavorite(title = "title", url = "http://example.com", lastModified = "timestamp") @@ -226,7 +226,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenInsertFavoriteWithoutTitleThenSavedSiteUsesUrlAsTitle() { + fun `insertFavorite - no title provided - uses url as title`() { givenNoFavoritesStored() val savedSite = repository.insertFavorite(title = "", url = "http://example.com", lastModified = "timestamp") @@ -237,7 +237,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenUserHasFavoritesAndInsertFavoriteThenSavedSiteUsesNextPosition() { + fun `insertFavorite - user has favorites - uses next position`() { givenSomeFavoritesStored() val savedSite = repository.insertFavorite(title = "Favorite", url = "http://favexample.com", lastModified = "timestamp") @@ -248,7 +248,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenFavoriteNameUpdatedThenDataIsUpdated() { + fun `updateFavourite - data is updated`() { val favoriteone = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) val favoritetwo = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 1) val favoritethree = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 2) @@ -268,7 +268,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenBookmarkFavoriteMovedToAnotherFolderThenBookmarkIsStillFavorite() { + fun `whenBookmarkFavoriteMovedToAnotherFolder - bookmark is still favorite`() { val favoriteone = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) givenFavoriteStored(favoriteone) @@ -308,7 +308,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenListReceivedThenUpdateItemsWithNewPositionInDatabase() { + fun `updateItems - list received - update items with new position in database`() { val favorite = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) val favorite2 = Favorite("favorite2", "Favorite2", "http://favexample2.com", "timestamp", 1) @@ -321,7 +321,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenFavoriteDeletedThenDatabaseUpdated() = runTest { + fun `deleteFavorite - database updated - null returned`() = runTest { val favorite = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 1) givenFavoriteStored(favorite) @@ -331,7 +331,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenUserHasFavoritesThenReturnTrue() = runTest { + fun `hasFavorites - user has favorites - true`() = runTest { val favorite = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 1) givenFavoriteStored(favorite) @@ -340,7 +340,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenFavoriteByUrlRequestedAndAvailableThenReturnFavorite() = runTest { + fun `getFavoriteByUrl - favorite available - return favorite`() = runTest { givenNoFavoritesStored() val favorite = @@ -361,7 +361,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenFavoriteByUrlRequestedAndNotAvailableThenReturnNull() = runTest { + fun `getFavoriteByUrl - not available - null`() = runTest { givenNoFavoritesStored() repository.insert(Favorite(id = "favorite1", title = "title", url = "www.website.com", lastModified = "timestamp", position = 1)) @@ -373,14 +373,14 @@ class SavedSitesRepositoryTest { } @Test - fun whenFavoriteByUrlRequestedAndNoFavoritesAvailableThenReturnNull() = runTest { + fun `getFavorite - no favorites available - null`() = runTest { val result = repository.getFavorite("www.test.com") Assert.assertNull(result) } @Test - fun whenAllFavoritesDeletedThenDeleteAllFavorites() = runTest { + fun `deleteAll - all favorites deleted`() = runTest { val favorite = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 1) val favorite2 = Favorite("favorite2", "Favorite2", "http://favexample2.com", "timestamp", 2) @@ -393,7 +393,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenInsertBookmarkThenPopulateDB() = runTest { + fun `insert - populate db`() = runTest { givenNoBookmarksStored() val bookmark = repository.insert( @@ -426,7 +426,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenUpdateBookmarkUrlThenUpdateBookmarkInDB() = runTest { + fun `updateBookmark - update bookmark in db`() = runTest { givenNoBookmarksStored() val bookmark = repository.insert( @@ -454,7 +454,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenUpdateBookmarkFolderThenUpdateBookmarkInDB() = runTest { + fun `updateBookmarkFolder - update bookmark in db`() = runTest { givenNoBookmarksStored() val bookmark = repository.insert( @@ -475,7 +475,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenDeleteBookmarkThenRemoveBookmarkFromDB() = runTest { + fun `deleteBookmark - remove bookmark from DB`() = runTest { givenNoBookmarksStored() val bookmark = repository.insert( @@ -493,7 +493,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenBookmarkAddedToRootThenGetFolderReturnsRootFolder() = runTest { + fun `getFolder - bookmark added to root - returns root folder`() = runTest { val bookmark = repository.insertBookmark(title = "name", url = "foo.com") repository.getFolderTreeItems(bookmark.parentId).let { result -> Assert.assertTrue(result.size == 1) @@ -502,7 +502,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenGetBookmarkFoldersByParentIdThenReturnBookmarkFoldersForParentId() = runTest { + fun `getBookmarkFoldersByParentId - return bookmark folders for parent id`() = runTest { val folder = repository.insert(BookmarkFolder(id = "folder1", name = "name", lastModified = "timestamp", parentId = "folder2")) val folderInserted = repository.getFolder(folder.id) @@ -510,7 +510,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenBookmarkFolderInsertedButWrongIdThenNothingIsRetrieved() = runTest { + fun `getFolder - wrong id - null`() = runTest { repository.insert(BookmarkFolder(id = "folder1", name = "name", lastModified = "timestamp", parentId = "folder2")) val folderInserted = repository.getFolder("folder2") @@ -518,7 +518,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenGetBookmarkFoldersByNameThenReturnBookmarkFolder() = runTest { + fun `getBookmarkFoldersByName - return bookmark folder`() = runTest { val folder = repository.insert(BookmarkFolder(id = "folder1", name = "name", lastModified = "timestamp", parentId = "folder2")) val folderInserted = repository.getFolderByName(folder.name) @@ -526,7 +526,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenBookmarkAddedToFolderThenGetFolderReturnsFolder() = runTest { + fun `getFolder - when bookmark added to folder then returns folder`() = runTest { givenNoBookmarksStored() repository.insertBookmark(title = "root", url = "foo.com") @@ -545,7 +545,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenBookmarkAndFolderAddedToFolderThenGetFolderReturnsFolder() = runTest { + fun `getFolder - folder added to folder - returns folder`() = runTest { givenNoBookmarksStored() repository.insertBookmark(title = "root", url = "foo.com") @@ -569,7 +569,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenBookmarkIsMovedToAnotherFolderThenRootBookmarksReturnsEmpty() = runTest { + fun `getFolderTreeItems - root bookmarks returns empty`() = runTest { givenNoBookmarksStored() val bookmark = repository.insertBookmark(title = "bookmark1", url = "foo.com") @@ -584,7 +584,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenBookmarkIsMovedToAnotherFolderThenFolderReturnsBookmark() = runTest { + fun `getFolder - when bookmark is moved to another folder then folder returns bookmark`() = runTest { givenNoBookmarksStored() val bookmark = repository.insertBookmark(title = "bookmark1", url = "foo.com") @@ -603,7 +603,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenFolderIsMovedToAnotherFolderThenParentFolderIsUpdated() = runTest { + fun `whenFolderIsMovedToAnotherFolderThenParentFolderIsUpdated - parent folder updated`() = runTest { givenNoBookmarksStored() repository.insert(BookmarkFolder(id = SavedSitesNames.BOOKMARKS_ROOT, name = "Bookmarks", lastModified = "timestamp", parentId = "")) @@ -641,7 +641,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenFolderNameUpdatedThenRepositoryReturnsUpdatedFolder() = runTest { + fun `getFolder - when folder name updated - returns updated folder`() = runTest { val folder = repository.insert(BookmarkFolder(id = "folder", name = "folder", lastModified = "timestamp", parentId = SavedSitesNames.BOOKMARKS_ROOT)) assertEquals(repository.getFolder(folder.id), folder) @@ -654,7 +654,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenFolderParentUpdatedThenRepositoryReturnsUpdatedFolder() = runTest { + fun `getFolder - folder parent updated - returns updated folder`() = runTest { val folderRoot = repository.insert(BookmarkFolder(id = SavedSitesNames.BOOKMARKS_ROOT, name = "folder", lastModified = "timestamp", parentId = "")) val folderTwo = repository.insert(BookmarkFolder(id = "folder2", name = "folder two", lastModified = "timestamp", parentId = folderRoot.id)) @@ -671,7 +671,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenInsertBranchFolderThenAllEntitiesAreInsertedCorrectly() = runTest { + fun `insertFolderBranch - all entities inserted correctly`() = runTest { val parentFolder = BookmarkFolder("folder1", "Parent Folder", SavedSitesNames.BOOKMARKS_ROOT, numFolders = 1, numBookmarks = 1, lastModified = "timestamp") val childFolder = BookmarkFolder("folder2", "Parent Folder", "folder1", numFolders = 0, numBookmarks = 0, lastModified = "timestamp") @@ -686,7 +686,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenChildFolderWithBookmarkThenGetFolderBranchReturnsFolderBranch() = runTest { + fun `getFolderBranch - when child folder with bookmark - returns folder branch`() = runTest { val parentFolder = BookmarkFolder("folder1", "Parent Folder", SavedSitesNames.BOOKMARKS_ROOT, 0, 0, "timestamp") val childFolder = BookmarkFolder("folder2", "Parent Folder", "folder1", 1, 0, "timestamp") val childBookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", "timestamp") @@ -701,7 +701,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenChildFoldersWithBookmarksThenGetFolderBranchReturnsFolderBranch() = runTest { + fun `getFolderBranch - when child folders with bookmarks then returns folder branch`() = runTest { val parentFolder = BookmarkFolder("folder1", "Parent Folder", SavedSitesNames.BOOKMARKS_ROOT, 0, 0, "timestamp") val parentBookmark = Bookmark("bookmark1", "title1", "www.example1.com", "folder1", "timestamp") val childFolder = BookmarkFolder("folder2", "Parent Folder", "folder1", 1, 1, "timestamp") @@ -725,7 +725,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenChildFoldersWithBookmarksInRootThenGetFolderBranchReturnsFolderBranch() = runTest { + fun `getFolderBranch - when child folders with bookmarks in root - returns folder branch`() = runTest { val parentFolder = BookmarkFolder("folder1", "Parent Folder", SavedSitesNames.BOOKMARKS_ROOT, 0, 0, "timestamp") val parentBookmark = Bookmark("bookmark1", "title1", "www.example1.com", SavedSitesNames.BOOKMARKS_ROOT, "timestamp") val childFolder = BookmarkFolder("folder2", "Parent Folder", "folder1", 1, 1, "timestamp") @@ -749,7 +749,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenBranchFolderDeletedThenNothingIsRetrieved() = runTest { + fun `deleteFolderBranch - nothing is retrieved`() = runTest { val parentFolder = BookmarkFolder("folder1", "Parent Folder", SavedSitesNames.BOOKMARKS_ROOT, numBookmarks = 0, numFolders = 1, lastModified = "timestamp") val childFolder = BookmarkFolder("folder2", "Parent Folder", "folder1", numBookmarks = 1, numFolders = 0, lastModified = "timestamp") @@ -770,7 +770,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenBuildFlatStructureThenReturnFolderListWithDepth() = runTest { + fun `getFolderTree - build flat structure - return folder list with depth`() = runTest { val rootFolder = BookmarkFolder(id = SavedSitesNames.BOOKMARKS_ROOT, name = "root", lastModified = "timestamp", parentId = "") val parentFolder = BookmarkFolder( id = "folder1", @@ -800,7 +800,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenBuildFlatStructureThenReturnFolderListWithDepthWithoutCurrentFolderBranch() = runTest { + fun `getFolderTree - build flat structure - return folder list with depth without current folder branch`() = runTest { val rootFolder = BookmarkFolder(id = SavedSitesNames.BOOKMARKS_ROOT, name = "root", lastModified = "timestamp", parentId = "") val parentFolder = BookmarkFolder(id = "folder1", name = "name", lastModified = "timestamp", parentId = SavedSitesNames.BOOKMARKS_ROOT) val childFolder = BookmarkFolder(id = "folder2", name = "another name", lastModified = "timestamp", parentId = parentFolder.id) @@ -822,7 +822,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenFolderIsDeletedThenRemovedFromDb() { + fun `deleteFolder - removed from db`() { val rootFolder = BookmarkFolder(id = SavedSitesNames.BOOKMARKS_ROOT, name = "root", lastModified = "timestamp", parentId = "") repository.insert(rootFolder) @@ -833,7 +833,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenRootFolderHasBookmarksAndFoldersThenDataWithNumbersIsRetrieved() = runTest { + fun `whenRootFolderHasBookmarksAndFoldersThenDataWithNumbersIsRetrieved - data retrieved`() = runTest { val totalBookmarks = 10 val totalFolders = 3 @@ -855,7 +855,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenUserHasBookmarksAndFavoritesThenGetSavedSitesReturnsEverything() = runTest { + fun `getSavedSites - user has bookmarks and favorites - returns everything`() = runTest { val favorite = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) val favorite2 = Favorite("favorite2", "Favorite2", "http://favexample2.com", "timestamp", 1) givenFavoriteStored(favorite, favorite2) @@ -875,7 +875,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenUserHasBookmarksAndFavoritesThenGetSavedSitesFromASubFolderReturnsSubFolder() = runTest { + fun `getSavedSites - sub folder - returns sub folder`() = runTest { val favorite = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) val favorite2 = Favorite("favorite2", "Favorite2", "http://favexample2.com", "timestamp", 1) givenFavoriteStored(favorite, favorite2) @@ -909,7 +909,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenUserHasBookmarksThenBookmarksTreeReturnsSavedSites() = runTest { + fun `getBookmarksTree - user has bookmarks - returns saved sites`() = runTest { val rootFolder = BookmarkFolder(id = SavedSitesNames.BOOKMARKS_ROOT, name = "root", lastModified = "timestamp", parentId = "") repository.insert(rootFolder) @@ -927,7 +927,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenDeleteBookmarkIsUndoneThenFolderStillHasBookmark() = runTest { + fun `deleteBookmark - is undone - folder still has bookmark`() = runTest { val rootFolder = BookmarkFolder(id = SavedSitesNames.BOOKMARKS_ROOT, name = "root", lastModified = "timestamp", parentId = "") repository.insert(rootFolder) @@ -955,7 +955,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenBookmarkIsUpdatedThenLastModifiedIsAlsoUpdated() { + fun `updateBookmark - last modified also updated`() { givenNoBookmarksStored() val bookmark = repository.insert( @@ -976,7 +976,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenFavouritesDuplicatedThenLocalDataIsReplaced() = runTest { + fun `givenFavorites - duplicated - local data replaced`() = runTest { val favoriteone = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) val favoritetwo = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 1) val favoritethree = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 2) @@ -987,7 +987,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenSubFolderIsReplacedThenLocalDataIsUpdated() = runTest { + fun `replaceFolderContent - local data updated`() = runTest { val rootFolder = BookmarkFolder(id = SavedSitesNames.BOOKMARKS_ROOT, name = "root", lastModified = "timestamp", parentId = "") val folderOne = BookmarkFolder(id = "folder1", name = "name", lastModified = "timestamp", parentId = SavedSitesNames.BOOKMARKS_ROOT) val folderTwo = BookmarkFolder(id = "folder2", name = "name", lastModified = "timestamp", parentId = SavedSitesNames.BOOKMARKS_ROOT) @@ -1052,7 +1052,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenFolderParentIsUpdatedThenReplacingItUpdatesData() = runTest { + fun `replaceFolderContent - folder parent updated - data updated`() = runTest { val rootFolder = BookmarkFolder(id = SavedSitesNames.BOOKMARKS_ROOT, name = "root", lastModified = "timestamp", parentId = "") val secondFolder = BookmarkFolder(id = "secondFolder", name = "name", lastModified = "timestamp", parentId = SavedSitesNames.BOOKMARKS_ROOT) val thirdFolder = BookmarkFolder(id = "thirdFolder", name = "name", lastModified = "timestamp", parentId = SavedSitesNames.BOOKMARKS_ROOT) @@ -1069,7 +1069,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenPruningDeletedBookmarkFolderDataIsPermanentlyDeleted() { + fun `pruneDeleted - permanently deleted bookmark folder data`() { givenEmptyDBState() val bookmark = repository.insertBookmark("https://favorite.com", "Bookmark") @@ -1089,7 +1089,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenPruningDeletedBookmarkDataIsPermanentlyDeleted() { + fun `pruneDeleted - bookmark data permanently deleted`() { givenEmptyDBState() val bookmark = repository.insertBookmark("https://favorite.com", "Bookmark") @@ -1104,7 +1104,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenPruningDeletedFavouriteDataIsNotPermanentlyDeleted() { + fun `pruneDeleted - favourite data not permanently deleted`() { givenEmptyDBState() val favorite = repository.insertFavorite("favourite1", "https://favorite.com", "favorite", "timestamp") @@ -1119,7 +1119,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenDeletingAFolderWithFavouriteThenDataIsDeleted() { + fun `deleteAFolderWithFavourite - data is deleted`() { val twoHoursAgo = DatabaseDateFormatter.iso8601(OffsetDateTime.now(ZoneOffset.UTC).minusHours(2)) givenEmptyDBState() @@ -1139,7 +1139,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenDeletingAFolderBranchWithFavouriteThenDataIsDeleted() { + fun `deleteFolderBranch - data deleted`() { val twoHoursAgo = DatabaseDateFormatter.iso8601(OffsetDateTime.now(ZoneOffset.UTC).minusHours(2)) givenEmptyDBState() @@ -1205,7 +1205,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenReplaceBookmarkFolderCalledThenFolderRelationsAreUpdatedCorrectly() = runTest { + fun `replaceBookmarkFolder - folder relations updated correctly`() = runTest { val folderId = "folderId" val initialEntities = listOf("123", "345") val updatedEntities = listOf("567", "789") @@ -1225,7 +1225,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenUpdateBookmarkWithUpdateFavoriteTrueAndBookmarkIsFavoriteThenFavoriteIsInserted() = runTest { + fun `updateBookmark - bookmark is favorite - favorite inserted`() = runTest { givenEmptyDBState() val bookmark = Bookmark("bookmark1", "title", "www.example.com", "timestamp", SavedSitesNames.BOOKMARKS_ROOT, isFavorite = true) @@ -1237,7 +1237,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenUpdateBookmarkWithUpdateFavoriteTrueAndBookmarkIsNotFavoriteThenFavoriteIsDeleted() = runTest { + fun `updateBookmark - bookmark is not favorite - favorite deleted`() = runTest { givenEmptyDBState() val bookmark = Bookmark("bookmark1", "title", "www.example.com", "timestamp", SavedSitesNames.BOOKMARKS_ROOT, isFavorite = false) diff --git a/app/src/test/java/com/duckduckgo/app/bookmarks/model/SyncSavedSitesRepositoryTest.kt b/app/src/test/java/com/duckduckgo/app/bookmarks/model/SyncSavedSitesRepositoryTest.kt index 75ba9f230a5d..5b9cfaff79b7 100644 --- a/app/src/test/java/com/duckduckgo/app/bookmarks/model/SyncSavedSitesRepositoryTest.kt +++ b/app/src/test/java/com/duckduckgo/app/bookmarks/model/SyncSavedSitesRepositoryTest.kt @@ -164,7 +164,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenFolderMetadataNotPresentThenAllChildrenInCurrentAndInsertField() = runTest { + fun `getFolderDiff - no metadata present - all children in current and insert field`() = runTest { givenSomeContentIn(folderId = folder.id, children = 5, saveMetadata = false) val folderChildren = repository.getFolderDiff(folder.id) @@ -174,7 +174,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenFolderMetadataNotPresentThenDeletedChildrenNotPresentInDeletedField() = runTest { + fun `getFolderDiff - folder metadata not present - deleted children not present in deleted field`() = runTest { val entities = BookmarkTestUtils.givenSomeBookmarks(5) savedSitesEntitiesDao.insertList(entities) @@ -195,7 +195,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenFolderMetadataPresentAndSameContentThenAllChildrenInCurrentAndInsertEmpty() = runTest { + fun `getFolderDiff - same content - all children in current and insert empty`() = runTest { givenSomeContentIn(folderId = folder.id, children = 5, saveMetadata = true, metadataRequest = false) val folderChildren = repository.getFolderDiff(folder.id) @@ -205,7 +205,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenFolderMetadataPresentAndLocalContentHasItemAddedThenFolderDiffContainsInsertedItem() = runTest { + fun `getFolderDiff - folder metadata present and local content has item added - contains inserted item`() = runTest { val entities = BookmarkTestUtils.givenSomeBookmarks(5) savedSitesEntitiesDao.insertList(entities) @@ -230,7 +230,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenFolderMetadataPresentAndLocalContentHasItemRemovedThenFolderDiffContainsDeletedItem() = runTest { + fun `getFolderDiff - folder metadata present and local content has item removed - contains deleted item`() = runTest { val entities = BookmarkTestUtils.givenSomeBookmarks(5) val entityRemoved = Entity(title = "entity6", url = "https://testUrl6", type = BOOKMARK, lastModified = DatabaseDateFormatter.iso8601(), deleted = true) @@ -257,7 +257,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenFolderMetadataPresentAndLocalContentHasMissingRelationsThenFolderDiffDoesNotContainDeletedItem() = runTest { + fun `getFolderDiff - folder metadata present and local content has missing relations - does not contain deleted item`() = runTest { val entities = BookmarkTestUtils.givenSomeBookmarks(5) savedSitesEntitiesDao.insertList(entities.dropLast(1)) @@ -278,7 +278,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenFolderIsReplacedThenChildrenAreUpdated() { + fun `whenFolderIsReplacedThenChildrenAreUpdated - folder children updated`() { val bookmarks = BookmarkTestUtils.givenSomeBookmarks(10) savedSitesEntitiesDao.insertList(bookmarks) @@ -297,7 +297,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenFolderIsReplacedThenOrphanedChildrenAreRemoved() { + fun `replaceBookmarkFolder - orphaned children removed`() { val bookmarks = BookmarkTestUtils.givenSomeBookmarks(10) savedSitesEntitiesDao.insertList(bookmarks) @@ -312,7 +312,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenRemoteFolderDoesNotContainLocallyStoredChildThenOrphanIsCreated() { + fun `replaceBookmarkFolder - remote folder does not contain locally stored child - orphan is created`() { val bookmarks = BookmarkTestUtils.givenSomeBookmarks(10) savedSitesEntitiesDao.insertList(bookmarks) @@ -330,7 +330,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenRemoteFolderContainsAddedChildrenThenOrphansAreNotCreated() { + fun `replaceBookmarkFolder - when remote folder contains added children - orphans not created`() { val bookmarks = BookmarkTestUtils.givenSomeBookmarks(10) savedSitesEntitiesDao.insertList(bookmarks) @@ -346,7 +346,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenOrphansPresentThenOrphansAttachedToBookmarksRoot() { + fun `fixOrphans - orphans present - orphans attached to bookmarks root`() { // given a root folder that contains a subfolder val subfolder = Entity(folder.id, "Folder", "", FOLDER, "", false) savedSitesEntitiesDao.insert(subfolder) @@ -377,7 +377,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenFolderContentIsReplacedThenRelationsAreNotDuplicated() { + fun `replaceBookmarkFolder - folder content replaced - relations not duplicated`() { val remoteChildren = BookmarkTestUtils.givenSomeBookmarks(5) savedSitesEntitiesDao.insertList(remoteChildren) val folderRelation = BookmarkTestUtils.givenFolderWithContent(bookmarksRoot.entityId, remoteChildren) @@ -390,7 +390,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun fixingOrphansDoesNotAffectFavourites() { + fun `fixOrphans - bookmarks root updated`() { // given a root folder that contains a subfolder savedSitesRelationsDao.insert(Relation(folderId = bookmarksRoot.entityId, entityId = folder.id)) @@ -433,7 +433,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenPruningDeletedEntityThenAllRelatedDataIsDeleted() { + fun `pruneDeleted - when pruning deleted entity then all related data is deleted`() { // given a root folder that contains a subfolder val subfolder = Entity(folder.id, "Folder", "", FOLDER, "", false) savedSitesEntitiesDao.insert(subfolder) @@ -456,7 +456,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenGeneratingLocalChangesThenMetadataRequestIsUpdated() { + fun `whenGeneratingLocalChanges - metadata request is updated`() { val expectedContent = listOf( getRequestEntryFromBookmarkFolder(favoritesFolder, listOf(bookmark1).map { it.id }), getRequestEntryFromSavedSite(bookmark1), @@ -475,13 +475,13 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenGeneratingLocalChangesAreEmptyThenMetadataRequestIsNotUpdated() { + fun `addRequestMetadata - metadata request not updated - is empty`() { repository.addRequestMetadata(emptyList()) assertTrue(savedSitesMetadataDao.all().isEmpty()) } @Test - fun whenMetadataResponseExistedAddingRequestKeepsPreviousResponse() { + fun `addRequestMetadata - metadata response existed - keeps previous response`() { val storedMetadata = SavedSitesSyncMetadataEntity(favoritesFolder.id, "previousResponse", null) savedSitesMetadataDao.addOrUpdate(storedMetadata) @@ -501,13 +501,13 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenResponseHasNoEntitiesThenMetadataIsNotUpdated() { + fun `addResponseMetadata - no entities - metadata not updated`() { repository.addResponseMetadata(emptyList()) assertTrue(savedSitesMetadataDao.all().isEmpty()) } @Test - fun whenResponseHasNoEntitiesAfterAPatchRequestThenMetadataIsCopiedAsResponse() { + fun `whenResponseHasNoEntitiesAfterAPatchRequestThenMetadataIsCopiedAsResponse - metadata copied as response`() { givenSomeContentIn(folderId = bookmarksRootFolder.id, children = 5) assertTrue(savedSitesMetadataDao.get(bookmarksRootFolder.id) != null) assertTrue(savedSitesMetadataDao.get(bookmarksRootFolder.id)!!.childrenRequest != null) @@ -521,7 +521,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenResponseHasEntitiesThenMetadataIsUpdated() { + fun `whenResponseHasEntities - metadata updated`() { val responseEntries = listOf( getResponseEntryFromSavedSite(bookmark), getResponseEntryFromBookmarkFolder(folder, listOf(bookmark.id)), @@ -538,7 +538,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenDiscardRequestMetadataThenMetadataRequestIsRemoved() { + fun `discardRequestMetadata - metadata request removed`() { val requestContent = listOf( getRequestEntryFromSavedSite(bookmark1), getRequestEntryFromSavedSite(bookmark3), @@ -555,7 +555,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenDiscardRequestMetadataAndStoreResponseMetadataThenMetadataStatusOnlyReflectsResponse() { + fun `discardRequestMetadata - store response metadata - only reflects response`() { val requestContent = listOf( getRequestEntryFromBookmarkFolder(favoritesFolder, listOf(bookmark1).map { it.id }), getRequestEntryFromSavedSite(bookmark1), @@ -587,7 +587,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenResponseHasEntitiesAndOnlyContainsBookmarksThenMetadataIsNotUpdated() { + fun `addResponseMetadata - only contains bookmarks - metadata not updated`() { val responseEntries = listOf( getResponseEntryFromSavedSite(bookmark), ) @@ -598,7 +598,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenResponseHasNoFoldersAfterAPatchRequestThenMetadataIsCopiedAsResponse() { + fun `whenResponseHasNoFoldersAfterAPatchRequestThenMetadataIsCopiedAsResponse - metadata copied as response`() { givenSomeContentIn(folderId = bookmarksRootFolder.id, children = 5) assertTrue(savedSitesMetadataDao.get(bookmarksRootFolder.id) != null) assertTrue(savedSitesMetadataDao.get(bookmarksRootFolder.id)!!.childrenRequest != null) @@ -616,7 +616,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenResponseHasDeletedFoldersThenMetadataIsDeleted() { + fun `addResponseMetadata - response has deleted folders - metadata is deleted`() { givenSomeContentIn(folderId = bookmarksRootFolder.id, children = 5) assertTrue(savedSitesMetadataDao.get(bookmarksRootFolder.id) != null) @@ -627,7 +627,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenUpdatingModifiedSinceThenDatesAreProperlyUpdated() { + fun `updateModified - when updating modified since - dates are properly updated`() { val oneHourAgo = DatabaseDateFormatter.iso8601(OffsetDateTime.now(ZoneOffset.UTC).minusHours(1)) givenSomeContentIn(folderId = bookmarksRootFolder.id, children = 5) @@ -638,7 +638,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenEntitiesPresentBeforeDeduplicationThenTheirTimestampIsUpdated() { + fun `setLocalEntitiesForNextSync - entities present before deduplication - timestamp updated`() { givenSomeContentIn(bookmarksRootFolder.id, 5) val oneHourAgo = DatabaseDateFormatter.iso8601(OffsetDateTime.now(ZoneOffset.UTC).minusHours(1)) @@ -648,7 +648,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenDeduplicatingBookmarkThenRemoteBookmarkReplacesLocal() { + fun `replaceBookmark - remote bookmark replaces local - remote bookmark replaces local`() { // given a local bookmark repository.insert(bookmark1, favouritesRoot.entityId) @@ -662,7 +662,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenBookmarkIsReplacedWithDifferentIdThenDataIsUpdated() { + fun `replaceBookmark - data updated`() { val rootFolder = BookmarkFolder(id = SavedSitesNames.BOOKMARKS_ROOT, name = "root", lastModified = "timestamp", parentId = "") savedSitesRepository.insert(rootFolder) @@ -688,7 +688,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenBookmarkIsReplacedWithSameIdThenDataIsUpdated() { + fun `replaceBookmark - data is updated`() { val rootFolder = BookmarkFolder(id = SavedSitesNames.BOOKMARKS_ROOT, name = "root", lastModified = "timestamp", parentId = "") savedSitesRepository.insert(rootFolder) @@ -770,7 +770,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenMovingBookmarkToAnotherFolderThenBookmarkOnlyHasOnlyBelongsToOneFolder() { + fun `replaceBookmarkFolder - bookmark only has one folder relation`() { val rootFolder = BookmarkFolder(id = SavedSitesNames.BOOKMARKS_ROOT, name = "root", lastModified = "timestamp", parentId = "") val subFolder = BookmarkFolder(id = "folder", name = "Folder", lastModified = "timestamp", parentId = rootFolder.id) savedSitesRepository.insert(rootFolder) @@ -794,7 +794,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenMovingFavouriteToAnotherFolderThenBookmarkBelongsToFavouritesAndFolder() { + fun `replaceBookmarkFolder - bookmark belongs to new folder and favourites root - true`() { val rootFolder = BookmarkFolder(id = SavedSitesNames.BOOKMARKS_ROOT, name = "root", lastModified = "timestamp", parentId = "") val subFolder = BookmarkFolder(id = "folder", name = "Folder", lastModified = "timestamp", parentId = rootFolder.id) savedSitesRepository.insert(rootFolder) @@ -822,7 +822,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenBookmarkModifiedAfterThresholdThenGetModifiedSinceHasBookmarks() { + fun `getBookmarksModifiedSince - when bookmark modified after threshold - has bookmarks`() { val since = OffsetDateTime.now(ZoneOffset.UTC).minusHours(1) val twoHoursAgo = OffsetDateTime.now(ZoneOffset.UTC).minusHours(2) @@ -840,7 +840,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenBookmarkModifiedBeforeThresholdThenGetModifiedSinceIsEmpty() { + fun `getBookmarksModifiedSince - before threshold - get modified since is empty`() { val since = OffsetDateTime.now(ZoneOffset.UTC).minusHours(1) val twoHoursAgo = OffsetDateTime.now(ZoneOffset.UTC).minusHours(2) @@ -855,7 +855,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenReplacingFavouritesFolderThenOnlyCurrentChildrenAreKept() { + fun `replaceFavouriteFolder - state - only new children are kept`() { // given a root folder that contains a subfolder savedSitesRelationsDao.insert(Relation(folderId = bookmarksRoot.entityId, entityId = folder.id)) @@ -883,7 +883,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenAddingToFavouritesFolderThenPreviousFavouritesAreKept() { + fun `addToFavouriteFolder - previous favourites kept - all favourites present`() { // given some favourites val firstBatch = BookmarkTestUtils.givenSomeBookmarks(10) savedSitesRelationsDao.insertList(BookmarkTestUtils.givenFolderWithContent(bookmarksRoot.entityId, firstBatch)) @@ -903,7 +903,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenMarkSavedSitesIdsAsInvalidThenIdsStored() = runTest { + fun `markSavedSitesAsInvalid - ids stored`() = runTest { val ids = listOf("id1", "id2", "id3") repository.markSavedSitesAsInvalid(ids) val invalidIds = store.invalidEntitiesIds @@ -913,7 +913,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenGetInvalidSavedSitesThenExpectedSavedSitesReturned() = runTest { + fun `getInvalidSavedSites - saved sites marked as invalid - expected saved sites returned`() = runTest { val bookmarks = BookmarkTestUtils.givenSomeBookmarks(10) savedSitesEntitiesDao.insertList(bookmarks) val ids = bookmarks.map { it.entityId } diff --git a/app/src/test/java/com/duckduckgo/app/bookmarks/service/SavedSitesExporterTest.kt b/app/src/test/java/com/duckduckgo/app/bookmarks/service/SavedSitesExporterTest.kt index 332ebed70e76..879e35190d01 100644 --- a/app/src/test/java/com/duckduckgo/app/bookmarks/service/SavedSitesExporterTest.kt +++ b/app/src/test/java/com/duckduckgo/app/bookmarks/service/SavedSitesExporterTest.kt @@ -107,7 +107,7 @@ class SavedSitesExporterTest { } @Test - fun whenSomeBookmarksExistThenExportingSucceeds() = runTest { + fun `export - some bookmarks exist - succeeds`() = runTest { val root = BookmarkFolder(SavedSitesNames.BOOKMARKS_ROOT, "DuckDuckGo Bookmarks", "", 0, 0, "timestamp") val parentFolder = BookmarkFolder("folder1", "Folder One", SavedSitesNames.BOOKMARKS_ROOT, 0, 0, "timestamp") val childFolder = BookmarkFolder("folder2", "Folder Two", "folder1", 0, 0, "timestamp") @@ -128,7 +128,7 @@ class SavedSitesExporterTest { } @Test - fun whenFileDoesNotExistThenExportingFails() = runTest { + fun `export - file does not exist - exporting fails`() = runTest { savedSitesRepository.insertBookmark("www.example.com", "example") val localUri = Uri.parse("uridoesnotexist") @@ -139,14 +139,14 @@ class SavedSitesExporterTest { } @Test - fun whenNoSavedSitesExistThenNothingIsExported() = runTest { + fun `export - no saved sites exist - nothing exported`() = runTest { val localUri = Uri.parse("whatever") val result = exporter.export(localUri) assertTrue(result is ExportSavedSitesResult.NoSavedSitesExported) } @Test - fun whenSomeFavoritesExistThenExportingSucceeds() = runTest { + fun `export - some favorites exist - succeeds`() = runTest { val favorite = SavedSite.Favorite(id = "favorite1", title = "example", url = "www.example.com", position = 0, lastModified = "timestamp") savedSitesRepository.insert(favorite) @@ -160,7 +160,7 @@ class SavedSitesExporterTest { } @Test - fun whenGetTreeStructureThenReturnTraversableTree() = runTest { + fun `getTreeFolderStructure - returns traversable tree`() = runTest { val root = BookmarkFolder(SavedSitesNames.BOOKMARKS_ROOT, "DuckDuckGo Bookmarks", "", 0, 0, "timestamp") val parentFolder = BookmarkFolder("folder1", "Folder One", SavedSitesNames.BOOKMARKS_ROOT, 0, 0, "timestamp") val childFolder = BookmarkFolder("folder2", "Folder Two", "folder1", 0, 0, "timestamp") diff --git a/app/src/test/java/com/duckduckgo/app/bookmarks/ui/BookmarksViewModelTest.kt b/app/src/test/java/com/duckduckgo/app/bookmarks/ui/BookmarksViewModelTest.kt index 89124674cbd8..58f499a459db 100644 --- a/app/src/test/java/com/duckduckgo/app/bookmarks/ui/BookmarksViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/bookmarks/ui/BookmarksViewModelTest.kt @@ -124,7 +124,7 @@ class BookmarksViewModelTest { } @Test - fun whenBookmarkDeleteUndoThenRepositoryNotUpdated() = runTest { + fun `onDeleteSaveSiteRequested - bookmark delete undo - repository not updated`() = runTest { testee.onDeleteSavedSiteRequested(bookmark) testee.undoDelete(bookmark) @@ -133,7 +133,7 @@ class BookmarksViewModelTest { } @Test - fun whenBookmarkDeleteThenRepositoryUpdated() = runTest { + fun `onDeleteSavedSite - repository updated`() = runTest { testee.onDeleteSavedSiteRequested(bookmark) testee.onDeleteSavedSiteSnackbarDismissed(bookmark) @@ -142,7 +142,7 @@ class BookmarksViewModelTest { } @Test - fun whenBookmarkDeleteRequestedThenConfirmCommandSent() = runTest { + fun `onDeleteSavedSiteRequested - confirm command sent`() = runTest { testee.onDeleteSavedSiteRequested(bookmark) verify(commandObserver).onChanged(commandCaptor.capture()) @@ -151,7 +151,7 @@ class BookmarksViewModelTest { } @Test - fun whenFavoriteDeleteUndoThenRepositoryNotUpdated() = runTest { + fun `onDeleteSaveSiteRequested - undo - repository not updated`() = runTest { testee.onDeleteSavedSiteRequested(favorite) testee.undoDelete(favorite) @@ -178,21 +178,21 @@ class BookmarksViewModelTest { } @Test - fun whenBookmarkEditedThenDaoUpdated() = runTest { + fun `onBookmarkEdited - dao updated`() = runTest { testee.onBookmarkEdited(bookmark, "folder1", true) verify(savedSitesRepository).updateBookmark(bookmark, "folder1", true) } @Test - fun whenFavoriteEditedThenRepositoryUpdated() = runTest { + fun `onFavouriteEdited - repository updated`() = runTest { testee.onFavouriteEdited(favorite) verify(savedSitesRepository).updateFavourite(favorite) } @Test - fun whenSavedSiteSelectedThenOpenCommand() { + fun `onSelected - saved site selected - open command`() { testee.onSelected(bookmark) verify(commandObserver).onChanged(commandCaptor.capture()) @@ -201,14 +201,14 @@ class BookmarksViewModelTest { } @Test - fun whenFavoriteSelectedThenPixelSent() { + fun `onSelected - favorite selected - pixel sent`() { testee.onSelected(favorite) verify(pixel).fire(AppPixelName.FAVORITE_BOOKMARKS_ITEM_PRESSED) } @Test - fun whenDeleteRequestedThenConfirmCommand() { + fun `onDeleteRequested - confirm command`() { testee.onDeleteSavedSiteRequested(bookmark) verify(commandObserver).onChanged(commandCaptor.capture()) @@ -217,7 +217,7 @@ class BookmarksViewModelTest { } @Test - fun whenBookmarkFolderSelectedThenIssueOpenBookmarkFolderCommand() { + fun `onBookmarkFolderSelected - issue open bookmark folder command`() { testee.onBookmarkFolderSelected(bookmarkFolder) verify(commandObserver).onChanged(commandCaptor.capture()) @@ -225,7 +225,7 @@ class BookmarksViewModelTest { } @Test - fun whenFetchBookmarksAndFoldersThenUpdateStateWithCollectedBookmarksAndFolders() = runTest { + fun `fetchBookmarksAndFolders - state updated with collected bookmarks and folders`() = runTest { val parentId = "folder1" testee.fetchBookmarksAndFolders(parentId = parentId) @@ -246,7 +246,7 @@ class BookmarksViewModelTest { } @Test - fun whenFetchEverythingThenUpdateStateWithData() = runTest { + fun `fetchEverything - update state with data`() = runTest { whenever(savedSitesRepository.getFavoritesSync()).thenReturn(listOf(favorite)) whenever(savedSitesRepository.getBookmarksTree()).thenReturn(listOf(bookmark, bookmark, bookmark)) whenever(savedSitesRepository.getFolderTree(SavedSitesNames.BOOKMARKS_ROOT, null)).thenReturn(listOf(bookmarkFolderItem, bookmarkFolderItem)) @@ -272,14 +272,14 @@ class BookmarksViewModelTest { } @Test - fun whenBookmarkFolderAddedThenCallInsertOnRepository() = runTest { + fun `onBookmarkFolderAdded - repository inserted`() = runTest { testee.onBookmarkFolderAdded(bookmarkFolder) verify(savedSitesRepository).insert(bookmarkFolder) } @Test - fun whenEditBookmarkFolderThenIssueShowEditBookmarkFolderCommand() { + fun `onEditBookmarkFolderRequested - issue show edit bookmark folder command`() { testee.onEditBookmarkFolderRequested(bookmarkFolder) verify(commandObserver).onChanged(commandCaptor.capture()) @@ -287,14 +287,14 @@ class BookmarksViewModelTest { } @Test - fun whenBookmarkFolderUpdatedThenCallUpdateOnRepository() = runTest { + fun `onBookmarkFolderUpdated - repository updated`() = runTest { testee.onBookmarkFolderUpdated(bookmarkFolder) verify(savedSitesRepository).update(bookmarkFolder) } @Test - fun whenDeleteEmptyFolderRequestedThenCommandIssued() = runTest { + fun `onDeleteBookmarkFolderRequested - command issued`() = runTest { testee.onDeleteBookmarkFolderRequested(bookmarkFolder) verify(commandObserver).onChanged(commandCaptor.capture()) assertEquals(bookmarkFolder, (commandCaptor.value as BookmarksViewModel.Command.ConfirmDeleteBookmarkFolder).bookmarkFolder) @@ -310,7 +310,7 @@ class BookmarksViewModelTest { } @Test - fun whenDeleteBookmarkFolderUndoThenRepositoryNotUpdated() = runTest { + fun `onDeleteBookmarkFolderRequested - undo - repository not updated`() = runTest { val parentFolder = BookmarkFolder("folder1", "Parent Folder", SavedSitesNames.BOOKMARKS_ROOT, 0, 0, "timestamp") val childFolder = BookmarkFolder("folder2", "Parent Folder", "folder1", 0, 0, "timestamp") val childBookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", "timestamp") @@ -325,7 +325,7 @@ class BookmarksViewModelTest { } @Test - fun whenDeleteBookmarkFolderConfirmedThenDeleteFolderAndIssueConfirmDeleteBookmarkFolderCommand() = runTest { + fun `onDeleteBookmarkFolderConfirmed - when delete bookmark folder confirmed then issue confirm delete bookmark folder command`() = runTest { val parentFolder = BookmarkFolder("folder1", "Parent Folder", SavedSitesNames.BOOKMARKS_ROOT, 0, 0, "timestamp") val childFolder = BookmarkFolder("folder2", "Parent Folder", "folder1", 0, 0, "timestamp") val childBookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", "timestamp") @@ -343,7 +343,7 @@ class BookmarksViewModelTest { } @Test - fun whenDeleteBookmarkFolderRequestedThenIssueDeleteBookmarkFolderCommand() = runTest { + fun `onDeleteBookmarkFolderRequested - issue delete bookmark folder command`() = runTest { val parentFolder = BookmarkFolder("folder1", "Parent Folder", SavedSitesNames.BOOKMARKS_ROOT, 0, 0, "timestamp") val childFolder = BookmarkFolder("folder2", "Parent Folder", "folder1", 0, 0, "timestamp") val childBookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", "timestamp") @@ -359,7 +359,7 @@ class BookmarksViewModelTest { } @Test - fun whenOnBookmarkFoldersActivityResultCalledThenOpenSavedSiteCommandSent() { + fun `onBookmarkFoldersActivityResult - command observer open saved site - open saved site`() { val savedSiteUrl = "https://www.example.com" testee.onBookmarkFoldersActivityResult(savedSiteUrl) @@ -369,7 +369,7 @@ class BookmarksViewModelTest { } @Test - fun whenUpdateBookmarksCalledThenUpdateFolderRelation() { + fun `updateBookmarks - update folder relation`() { val parentId = "folderId" val bookmarksAndFolders = listOf("bookmark1", "folder1") @@ -379,14 +379,14 @@ class BookmarksViewModelTest { } @Test - fun whenAddFavoriteCalledThenInsertFavorite() { + fun `addFavorite - insert favorite`() { testee.addFavorite(bookmark) verify(savedSitesRepository).insertFavorite(bookmark.id, bookmark.url, bookmark.title) } @Test - fun whenRemoveFavoriteCalledThenDeleteFavorite() { + fun `removeFavorite - delete favorite`() { testee.removeFavorite(bookmark) verify(savedSitesRepository).delete( diff --git a/app/src/test/java/com/duckduckgo/app/bookmarks/ui/bookmarkfolders/BookmarkFoldersViewModelTest.kt b/app/src/test/java/com/duckduckgo/app/bookmarks/ui/bookmarkfolders/BookmarkFoldersViewModelTest.kt index 2f9b5c355346..924959fa3297 100644 --- a/app/src/test/java/com/duckduckgo/app/bookmarks/ui/bookmarkfolders/BookmarkFoldersViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/bookmarks/ui/bookmarkfolders/BookmarkFoldersViewModelTest.kt @@ -75,7 +75,7 @@ class BookmarkFoldersViewModelTest { } @Test - fun whenFetchBookmarkFoldersThenCallRepoAndUpdateViewState() = runTest { + fun `fetchBookmarkFolders - state - call repo and update view state`() = runTest { val selectedFolderId = SavedSitesNames.BOOKMARKS_ROOT val rootFolderName = "Bookmarks" val folder = BookmarkFolder("folder2", "a folder", "folder1", 0, 0, "timestamp") @@ -90,7 +90,7 @@ class BookmarkFoldersViewModelTest { } @Test - fun whenItemSelectedThenIssueSelectFolderCommand() = runTest { + fun `onItemSelected - issue select folder command`() = runTest { val folder = BookmarkFolder("folder2", "a folder", "folder1", 0, 0, "timestamp") testee.onItemSelected(folder) @@ -101,7 +101,7 @@ class BookmarkFoldersViewModelTest { } @Test - fun newFolderAddedThenCallRepoAndUpdateViewState() = runTest { + fun `newFolderAdded - then call repo and update view state`() = runTest { val newFolder = BookmarkFolder("folder3", "new folder", "folder1", 0, 0, "timestamp") val selectedFolderId = SavedSitesNames.BOOKMARKS_ROOT diff --git a/app/src/test/java/com/duckduckgo/app/brokensite/BrokenSiteDataTest.kt b/app/src/test/java/com/duckduckgo/app/brokensite/BrokenSiteDataTest.kt index 0b3ff0418dbb..05e6d700c7c6 100644 --- a/app/src/test/java/com/duckduckgo/app/brokensite/BrokenSiteDataTest.kt +++ b/app/src/test/java/com/duckduckgo/app/brokensite/BrokenSiteDataTest.kt @@ -47,7 +47,7 @@ class BrokenSiteDataTest { private val mockBypassedSSLCertificatesRepository: BypassedSSLCertificatesRepository = mock() @Test - fun whenSiteIsNullThenDataIsEmptyAndUpgradedIsFalse() { + fun `whenSiteIsNull - data empty and upgraded is false`() { val data = BrokenSiteData.fromSite(null, reportFlow = MENU) assertTrue(data.url.isEmpty()) assertTrue(data.blockedTrackers.isEmpty()) @@ -56,28 +56,28 @@ class BrokenSiteDataTest { } @Test - fun whenSiteExistsThenDataContainsUrl() { + fun `fromSite - site exists - contains url`() { val site = buildSite(SITE_URL) val data = BrokenSiteData.fromSite(site, reportFlow = MENU) assertEquals(SITE_URL, data.url) } @Test - fun whenSiteUpgradedThenHttpsUpgradedIsTrue() { + fun `whenSiteUpgraded - site data upgraded to https - true`() { val site = buildSite(SITE_URL, httpsUpgraded = true) val data = BrokenSiteData.fromSite(site, reportFlow = MENU) assertTrue(data.upgradedToHttps) } @Test - fun whenSiteNotUpgradedThenHttpsUpgradedIsFalse() { + fun `whenSiteNotUpgraded - site not upgraded - https upgraded is false`() { val site = buildSite(SITE_URL, httpsUpgraded = false) val data = BrokenSiteData.fromSite(site, reportFlow = MENU) assertFalse(data.upgradedToHttps) } @Test - fun whenUrlParametersRemovedThenUrlParametersRemovedIsTrue() { + fun `whenUrlParametersRemoved - url parameters removed is true`() { val site = buildSite(SITE_URL) site.urlParametersRemoved = true val data = BrokenSiteData.fromSite(site, reportFlow = MENU) @@ -85,21 +85,21 @@ class BrokenSiteDataTest { } @Test - fun whenUrlParametersNotRemovedThenUrlParametersRemovedIsFalse() { + fun `whenUrlParametersNotRemovedThenUrlParametersRemovedIsFalse - url parameters not removed - is false`() { val site = buildSite(SITE_URL) val data = BrokenSiteData.fromSite(site, reportFlow = MENU) assertFalse(data.urlParametersRemoved) } @Test - fun whenSiteHasNoTrackersThenBlockedTrackersIsEmpty() { + fun `whenSiteHasNoTrackers - blocked trackers empty`() { val site = buildSite(SITE_URL) val data = BrokenSiteData.fromSite(site, reportFlow = MENU) assertTrue(data.blockedTrackers.isEmpty()) } @Test - fun whenSiteHasBlockedTrackersThenBlockedTrackersExist() { + fun `whenSiteHasBlockedTrackersThenBlockedTrackersExist - site has blocked trackers - tracker·com exists`() { val site = buildSite(SITE_URL) val event = TrackingEvent( documentUrl = "http://www.example.com", @@ -125,7 +125,7 @@ class BrokenSiteDataTest { } @Test - fun whenSiteHasSameHostBlockedTrackersThenOnlyUniqueTrackersIncludedInData() { + fun `whenSiteHasSameHostBlockedTrackers - only unique trackers included in data`() { val site = buildSite(SITE_URL) val event = TrackingEvent( documentUrl = "http://www.example.com", @@ -151,7 +151,7 @@ class BrokenSiteDataTest { } @Test - fun whenSiteHasBlockedCnamedTrackersThenBlockedTrackersExist() { + fun `whenSiteHasBlockedCnamedTrackersThenBlockedTrackersExist - blocked trackers exist`() { val site = buildSite(SITE_URL) val event = TrackingEvent( documentUrl = "http://www.example.com", @@ -167,14 +167,14 @@ class BrokenSiteDataTest { } @Test - fun whenSiteHasNoSurrogatesThenSurrogatesIsEmpty() { + fun `whenSiteHasNoSurrogates - surrogates empty`() { val site = buildSite(SITE_URL) val data = BrokenSiteData.fromSite(site, reportFlow = MENU) assertTrue(data.surrogates.isEmpty()) } @Test - fun whenSiteHasSurrogatesThenSurrogatesExist() { + fun `whenSiteHasSurrogatesThenSurrogatesExist - site has surrogates - exist`() { val surrogate = SurrogateResponse("test.js", true, "surrogate.com/test.js", "", "") val anotherSurrogate = SurrogateResponse("test.js", true, "anothersurrogate.com/test.js", "", "") val site = buildSite(SITE_URL) @@ -184,7 +184,7 @@ class BrokenSiteDataTest { } @Test - fun whenSiteHasSameHostSurrogatesThenOnlyUniqueSurrogateIncludedInData() { + fun `whenSiteHasSameHostSurrogatesThenOnlyUniqueSurrogateIncludedInData - site data - only unique surrogate included`() { val surrogate = SurrogateResponse("test.js", true, "surrogate.com/test.js", "", "") val anotherSurrogate = SurrogateResponse("test.js", true, "surrogate.com/test2.js", "", "") val site = buildSite(SITE_URL) diff --git a/app/src/test/java/com/duckduckgo/app/brokensite/api/BrokenSiteSubmitterTest.kt b/app/src/test/java/com/duckduckgo/app/brokensite/api/BrokenSiteSubmitterTest.kt index 9b88d114d19c..f92c349211be 100644 --- a/app/src/test/java/com/duckduckgo/app/brokensite/api/BrokenSiteSubmitterTest.kt +++ b/app/src/test/java/com/duckduckgo/app/brokensite/api/BrokenSiteSubmitterTest.kt @@ -114,7 +114,7 @@ class BrokenSiteSubmitterTest { } @Test - fun whenVpnDisabledReportFalse() = runTest { + fun `whenVpnDisabledReport - vpn disabled - false`() = runTest { whenever(networkProtectionState.isRunning()).thenReturn(false) val brokenSite = getBrokenSite() @@ -129,7 +129,7 @@ class BrokenSiteSubmitterTest { } @Test - fun whenVpnEnabledReportTrue() = runTest { + fun `whenVpnEnabledReport - report true - vpn on`() = runTest { whenever(networkProtectionState.isRunning()).thenReturn(true) val brokenSite = getBrokenSite() @@ -144,7 +144,7 @@ class BrokenSiteSubmitterTest { } @Test - fun whenSiteInUnprotectedTemporaryThenProtectionsAreOff() { + fun `submitBrokenSiteFeedback - site in unprotected temporary - protections are off`() { whenever(mockContentBlocking.isAnException(any())).thenReturn(false) whenever(mockUserAllowListRepository.isDomainInUserAllowList(any())).thenReturn(false) whenever(mockUnprotectedTemporary.isAnException(any())).thenReturn(true) @@ -161,7 +161,7 @@ class BrokenSiteSubmitterTest { } @Test - fun whenSiteInUserAllowListThenProtectionsAreOff() { + fun `submitBrokenSiteFeedback - site in user allow list - protections are off`() { whenever(mockContentBlocking.isAnException(any())).thenReturn(false) whenever(mockUserAllowListRepository.isDomainInUserAllowList(any())).thenReturn(true) whenever(mockUnprotectedTemporary.isAnException(any())).thenReturn(false) @@ -178,7 +178,7 @@ class BrokenSiteSubmitterTest { } @Test - fun whenSiteInContentBlockingThenProtectionsAreOff() { + fun `submitBrokenSiteFeedback - site in content blocking - protections are off`() { whenever(mockContentBlocking.isAnException(any())).thenReturn(true) whenever(mockUserAllowListRepository.isDomainInUserAllowList(any())).thenReturn(false) whenever(mockUnprotectedTemporary.isAnException(any())).thenReturn(false) @@ -195,7 +195,7 @@ class BrokenSiteSubmitterTest { } @Test - fun whenSiteInContentBlockingDisabledThenProtectionsAreOff() { + fun `whenSiteInContentBlockingDisabledThenProtectionsAreOff - site in content blocking disabled - protections are off`() { whenever(mockFeatureToggle.isFeatureEnabled(PrivacyFeatureName.ContentBlockingFeatureName.value, true)).thenReturn(false) whenever(mockContentBlocking.isAnException(any())).thenReturn(true) @@ -214,7 +214,7 @@ class BrokenSiteSubmitterTest { } @Test - fun whenSiteAllowedThenProtectionsAreOn() { + fun `whenSiteAllowedThenProtectionsAreOn - site allowed - protections on`() { whenever(mockContentBlocking.isAnException(any())).thenReturn(false) whenever(mockUserAllowListRepository.isDomainInUserAllowList(any())).thenReturn(false) whenever(mockUnprotectedTemporary.isAnException(any())).thenReturn(false) @@ -231,7 +231,7 @@ class BrokenSiteSubmitterTest { } @Test - fun whenBrokenSiteFeedbackIsSuccessfullySubmittedThenParamSentAndSetLastSentDayIsCalledForThatDomain() = runTest { + fun `submitBrokenSiteFeedback - when successfully submitted then param sent and set last sent day is called for that domain`() = runTest { val lastSentDay = "2023-11-01" whenever(mockBrokenSiteLastSentReport.getLastSentDay(any())).thenReturn(lastSentDay) val brokenSite = getBrokenSite() @@ -248,7 +248,7 @@ class BrokenSiteSubmitterTest { } @Test - fun whenDeviceIsEnglishThenIncludeLoginSite() { + fun `whenDeviceIsEnglish - include login site - empty login site`() { whenever(mockAppBuildConfig.deviceLocale).thenReturn(Locale.ENGLISH) whenever(mockContentBlocking.isAnException(any())).thenReturn(false) whenever(mockUserAllowListRepository.isDomainInUserAllowList(any())).thenReturn(false) @@ -266,7 +266,7 @@ class BrokenSiteSubmitterTest { } @Test - fun whenDeviceIsNotEnglishThenDoNotIncludeLoginSite() { + fun `whenDeviceIsNotEnglish - do not include login site - does not contain login site`() { whenever(mockAppBuildConfig.deviceLocale).thenReturn(Locale.FRANCE) whenever(mockContentBlocking.isAnException(any())).thenReturn(false) whenever(mockUserAllowListRepository.isDomainInUserAllowList(any())).thenReturn(false) @@ -284,7 +284,7 @@ class BrokenSiteSubmitterTest { } @Test - fun whenReportFlowIsMenuThenIncludeParam() { + fun `submitBrokenSiteFeedback - report flow menu - include param`() { val brokenSite = getBrokenSite() .copy(reportFlow = MENU) @@ -298,7 +298,7 @@ class BrokenSiteSubmitterTest { } @Test - fun whenReportFlowIsDashboardThenIncludeParam() { + fun `submitBrokenSiteFeedback - report flow is dashboard - include param`() { val brokenSite = getBrokenSite() .copy(reportFlow = DASHBOARD) @@ -312,7 +312,7 @@ class BrokenSiteSubmitterTest { } @Test - fun whenReportFlowIsNullThenDoNotIncludeParam() { + fun `submitBrokenSiteFeedback - report flow null - do not include param`() { val brokenSite = getBrokenSite() .copy(reportFlow = null) @@ -326,7 +326,7 @@ class BrokenSiteSubmitterTest { } @Test - fun whenPrivacyProtectionsPopupExperimentParamsArePresentThenTheyAreIncludedInPixel() = runTest { + fun `submitBrokenSiteFeedback - privacy protections popup experiment params present - includes in pixel`() = runTest { val params = mapOf("test_key" to "test_value") whenever(privacyProtectionsPopupExperimentExternalPixels.getPixelParams()).thenReturn(params) diff --git a/app/src/test/java/com/duckduckgo/app/browser/BrowserViewModelTest.kt b/app/src/test/java/com/duckduckgo/app/browser/BrowserViewModelTest.kt index 6102ba377763..8762a2046815 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/BrowserViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/BrowserViewModelTest.kt @@ -117,21 +117,21 @@ class BrowserViewModelTest { } @Test - fun whenNewTabRequestedThenTabAddedToRepository() = runTest { + fun `onNewTabRequested - tab repository added`() = runTest { whenever(mockTabRepository.liveSelectedTab).doReturn(MutableLiveData()) testee.onNewTabRequested() verify(mockTabRepository).add() } @Test - fun whenNewTabRequestedFromSourceTabThenTabAddedToRepositoryWithSourceTabId() = runTest { + fun `onNewTabRequested - tab added to repository with source tab id`() = runTest { whenever(mockTabRepository.liveSelectedTab).doReturn(MutableLiveData()) testee.onNewTabRequested("sourceTabId") verify(mockTabRepository).addFromSourceTab(sourceTabId = "sourceTabId") } @Test - fun whenOpenInNewTabRequestedThenTabAddedToRepository() = runTest { + fun `onOpenInNewTabRequested - tab repository added`() = runTest { val url = "http://example.com" whenever(mockOmnibarEntryConverter.convertQueryToUrl(url)).thenReturn(url) whenever(mockTabRepository.liveSelectedTab).doReturn(MutableLiveData()) @@ -140,7 +140,7 @@ class BrowserViewModelTest { } @Test - fun whenOpenInNewTabRequestedWithSourceTabIdThenTabAddedToRepositoryWithSourceTabId() = runTest { + fun `onOpenInNewTabRequested - tab repository added with source tab id`() = runTest { val url = "http://example.com" whenever(mockOmnibarEntryConverter.convertQueryToUrl(url)).thenReturn(url) whenever(mockTabRepository.liveSelectedTab).doReturn(MutableLiveData()) @@ -149,38 +149,38 @@ class BrowserViewModelTest { } @Test - fun whenTabsUpdatedAndNoTabsThenDefaultTabAddedToRepository() = runTest { + fun `onTabsUpdated - no tabs - default tab added to repository`() = runTest { testee.onTabsUpdated(ArrayList()) verify(mockTabRepository).addDefaultTab() } @Test - fun whenTabsUpdatedWithTabsThenNewTabNotLaunched() = runTest { + fun `onTabsUpdated - tabs updated - new tab not launched`() = runTest { testee.onTabsUpdated(listOf(TabEntity(TAB_ID, "", "", skipHome = false, viewed = true, position = 0))) verify(mockCommandObserver, never()).onChanged(any()) } @Test - fun whenUserSelectedToRateAppThenPlayStoreCommandTriggered() { + fun `onUserSelectedToRateApp - play store command triggered`() { testee.onUserSelectedToRateApp(PromptCount.first()) verify(mockCommandObserver).onChanged(commandCaptor.capture()) assertEquals(Command.LaunchPlayStore, commandCaptor.lastValue) } @Test - fun whenUserSelectedToGiveFeedbackThenFeedbackCommandTriggered() { + fun `onUserSelectedToGiveFeedback - feedback command triggered`() { testee.onUserSelectedToGiveFeedback(PromptCount.first()) verify(mockCommandObserver).onChanged(commandCaptor.capture()) assertEquals(Command.LaunchFeedbackView, commandCaptor.lastValue) } @Test - fun whenViewStateCreatedThenWebViewContentShouldBeHidden() { + fun `whenViewStateCreated - view state created - web content should be hidden`() { assertTrue(testee.viewState.value!!.hideWebContent) } @Test - fun whenOpenShortcutThenSelectByUrlOrNewTab() = runTest { + fun `onOpenShortcut - select by url or new tab`() = runTest { val url = "example.com" whenever(mockOmnibarEntryConverter.convertQueryToUrl(url)).thenReturn(url) testee.onOpenShortcut(url) @@ -188,7 +188,7 @@ class BrowserViewModelTest { } @Test - fun whenOpenShortcutThenFirePixel() { + fun `onOpenShortcut - fire pixel`() { val url = "example.com" whenever(mockOmnibarEntryConverter.convertQueryToUrl(url)).thenReturn(url) testee.onOpenShortcut(url) @@ -196,7 +196,7 @@ class BrowserViewModelTest { } @Test - fun whenOpenFavoriteThenSelectByUrlOrNewTab() = runTest { + fun `onOpenFavorite - select by url or new tab`() = runTest { val url = "example.com" whenever(mockOmnibarEntryConverter.convertQueryToUrl(url)).thenReturn(url) testee.onOpenFavoriteFromWidget(url) @@ -204,7 +204,7 @@ class BrowserViewModelTest { } @Test - fun whenOpenFavoriteFromWidgetThenFirePixel() = runTest { + fun `onOpenFavoriteFromWidget - fire pixel`() = runTest { val url = "example.com" whenever(mockOmnibarEntryConverter.convertQueryToUrl(url)).thenReturn(url) testee.onOpenFavoriteFromWidget(url) @@ -212,7 +212,7 @@ class BrowserViewModelTest { } @Test - fun whenOpenFromThirdPartyAndNotDefaultBrowserThenFirePixel() = runTest { + fun `launchFromThirdParty - not default browser - fire pixel`() = runTest { whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(false) testee.launchFromThirdParty() verify(mockPixel).fire( @@ -222,7 +222,7 @@ class BrowserViewModelTest { } @Test - fun whenOpenFromThirdPartyAndDefaultBrowserThenFirePixel() = runTest { + fun `launchFromThirdParty - default browser - fire pixel`() = runTest { whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(true) testee.launchFromThirdParty() verify(mockPixel).fire( @@ -232,7 +232,7 @@ class BrowserViewModelTest { } @Test - fun whenOnLaunchedFromNotificationCalledWithPixelNameThePixelFired() { + fun `onLaunchedFromNotification - pixel fired`() { val pixelName = "pixel_name" testee.onLaunchedFromNotification(pixelName) @@ -240,7 +240,7 @@ class BrowserViewModelTest { } @Test - fun whenOnBookmarksActivityResultCalledThenOpenSavedSiteCommandTriggered() { + fun `onBookmarksActivityResult - on changed - open saved site command triggered`() { val bookmarkUrl = "https://www.example.com" testee.onBookmarksActivityResult(bookmarkUrl) diff --git a/app/src/test/java/com/duckduckgo/app/browser/DosDetectorTest.kt b/app/src/test/java/com/duckduckgo/app/browser/DosDetectorTest.kt index 790b61e9970b..5eb20aa902d0 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/DosDetectorTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/DosDetectorTest.kt @@ -33,14 +33,14 @@ class DosDetectorTest { val testee: DosDetector = DosDetector() @Test - fun whenLessThanMaxRequestsCountCallsWithSameUrlThenReturnFalse() { + fun `isUrlGeneratingDos - same url - return false`() { for (i in 0 until MAX_REQUESTS_COUNT) { assertFalse(testee.isUrlGeneratingDos(Uri.parse("http://example.com"))) } } @Test - fun whenMoreThanMaxRequestsCountCallsWithSameUrlThenLastCallReturnsTrue() { + fun `isUrlGeneratingDos - more than max requests count calls with same url - returns true`() { for (i in 0..MAX_REQUESTS_COUNT) { assertFalse(testee.isUrlGeneratingDos(Uri.parse("http://example.com"))) } @@ -48,7 +48,7 @@ class DosDetectorTest { } @Test - fun whenMoreThanMaxRequestsCountCallsWithSameUrlAndDelayGreaterThanLimitThenReturnFalse() { + fun `isUrlGeneratingDos - more than max requests count calls with same url and delay greater than limit - return false`() { runBlocking { for (i in 0..MAX_REQUESTS_COUNT) { assertFalse(testee.isUrlGeneratingDos(Uri.parse("http://example.com"))) @@ -59,7 +59,7 @@ class DosDetectorTest { } @Test - fun whenMoreThanMaxRequestsCountCallsWithSameUrlAndDelayGreaterThanLimitThenCountIsResetSoNextAndSubsequentRequestsReturnFalse() { + fun `whenMoreThanMaxRequestsCountCallsWithSameUrlAndDelayGreaterThanLimitThenCountIsResetSoNextAndSubsequentRequestsReturnFalse - isUrlGeneratingDos reset`() { runBlocking { for (i in 0..MAX_REQUESTS_COUNT) { assertFalse(testee.isUrlGeneratingDos(Uri.parse("http://example.com"))) @@ -71,7 +71,7 @@ class DosDetectorTest { } @Test - fun whenMultipleRequestsFromDifferentUrlsThenReturnFalse() { + fun `isUrlGeneratingDos - multiple requests from different urls - returns false`() { for (i in 0 until MAX_REQUESTS_COUNT * 2) { if (i % 2 == 0) { assertFalse(testee.isUrlGeneratingDos(Uri.parse("http://example.com"))) @@ -82,7 +82,7 @@ class DosDetectorTest { } @Test - fun whenMaxRequestsReceivedConsecutivelyFromDifferentUrlsThenReturnFalse() { + fun `isUrlGeneratingDos - max requests received consecutively from different urls - return false`() { for (i in 0 until MAX_REQUESTS_COUNT) { assertFalse(testee.isUrlGeneratingDos(Uri.parse("http://example.com"))) } diff --git a/app/src/test/java/com/duckduckgo/app/browser/DuckDuckGoRequestRewriterTest.kt b/app/src/test/java/com/duckduckgo/app/browser/DuckDuckGoRequestRewriterTest.kt index 3c68c199cd5f..e092cf1614ea 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/DuckDuckGoRequestRewriterTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/DuckDuckGoRequestRewriterTest.kt @@ -55,7 +55,7 @@ class DuckDuckGoRequestRewriterTest { } @Test - fun whenAddingCustomParamsSourceParameterIsAdded() { + fun `addCustomQueryParams - source parameter added`() { testee.addCustomQueryParams(builder) val uri = builder.build() assertTrue(uri.queryParameterNames.contains(ParamKey.SOURCE)) @@ -63,7 +63,7 @@ class DuckDuckGoRequestRewriterTest { } @Test - fun whenAddingCustomParamsAndUserSourcedFromEuAuctionThenEuSourceParameterIsAdded() { + fun `addCustomQueryParams - user sourced from eu auction - eu source parameter added`() { whenever(mockAppReferrerDataStore.installedFromEuAuction).thenReturn(true) testee.addCustomQueryParams(builder) val uri = builder.build() @@ -72,7 +72,7 @@ class DuckDuckGoRequestRewriterTest { } @Test - fun whenAddingCustomParamsIfStoreContainsAtbIsAdded() { + fun `addCustomQueryParams - store contains atb is added`() { whenever(mockStatisticsStore.atb).thenReturn(Atb("v105-2ma")) testee.addCustomQueryParams(builder) val uri = builder.build() @@ -81,7 +81,7 @@ class DuckDuckGoRequestRewriterTest { } @Test - fun whenAddingCustomParamsIfIsStoreMissingAtbThenAtbIsNotAdded() { + fun `addCustomQueryParams - is store missing atb - atb not added`() { whenever(mockStatisticsStore.atb).thenReturn(null) testee.addCustomQueryParams(builder) @@ -90,7 +90,7 @@ class DuckDuckGoRequestRewriterTest { } @Test - fun whenSerpRemovalFeatureIsActiveThenHideParamIsAddedToSerpUrl() { + fun `addCustomQueryParams - serp removal feature active - hide param added to serp url`() { testee.addCustomQueryParams(builder) val uri = builder.build() @@ -98,19 +98,19 @@ class DuckDuckGoRequestRewriterTest { } @Test - fun whenShouldRewriteRequestAndUrlIsSerpQueryThenReturnTrue() { + fun `shouldRewriteRequest - serp query - returns true`() { val uri = "http://duckduckgo.com/?q=weather".toUri() assertTrue(testee.shouldRewriteRequest(uri)) } @Test - fun whenShouldRewriteRequestAndUrlIsSerpQueryWithSourceAndAtbThenReturnFalse() { + fun `shouldRewriteRequest - serp query with source and atb - return false`() { val uri = "http://duckduckgo.com/?q=weather&atb=test&t=test".toUri() assertFalse(testee.shouldRewriteRequest(uri)) } @Test - fun whenShouldRewriteRequestAndUrlIsADuckDuckGoStaticUrlThenReturnTrue() { + fun `shouldRewriteRequest - url is a duckduckgo static url - returns true`() { val uri = "http://duckduckgo.com/settings".toUri() assertTrue(testee.shouldRewriteRequest(uri)) @@ -119,7 +119,7 @@ class DuckDuckGoRequestRewriterTest { } @Test - fun whenShouldRewriteRequestAndUrlIsDuckDuckGoEmailThenReturnFalse() { + fun `shouldRewriteRequest - url is duckduckgo email - return false`() { val uri = "http://duckduckgo.com/email".toUri() assertFalse(testee.shouldRewriteRequest(uri)) } diff --git a/app/src/test/java/com/duckduckgo/app/browser/DuckDuckGoUrlDetectorTest.kt b/app/src/test/java/com/duckduckgo/app/browser/DuckDuckGoUrlDetectorTest.kt index b989cb1e22a8..52d421ab1c72 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/DuckDuckGoUrlDetectorTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/DuckDuckGoUrlDetectorTest.kt @@ -33,126 +33,126 @@ class DuckDuckGoUrlDetectorTest { } @Test - fun whenCheckingSearchTermThenIdentifiedAsNotDDGUrl() { + fun `isDuckDuckGoUrl - search term checked - not DDG url`() { assertFalse(testee.isDuckDuckGoUrl("foo")) } @Test - fun whenCheckingNonDDGUrlThenIdentifiedAsNotDDGUrl() { + fun `isDuckDuckGoUrl - non DDG URL - not DDG URL`() { assertFalse(testee.isDuckDuckGoUrl("example.com")) } @Test - fun whenCheckingFullDDGUrlThenIdentifiedAsDDGUrl() { + fun `isDuckDuckGoUrl - checking full DDG URL - identified as DDG URL`() { assertTrue(testee.isDuckDuckGoUrl("https://duckduckgo.com/?q=test%20search&tappv=android_0_2_0&t=ddg_android")) } @Test - fun whenCheckingSubdomainAndETLDisDDGThenReturnTrue() { + fun `isDuckDuckGoUrl - checking subdomain and ETL dis DDC - returns true`() { assertTrue(testee.isDuckDuckGoUrl("https://test.duckduckgo.com")) } @Test - fun whenCheckingSubdomainAndETLDisNotDDGThenReturnFalse() { + fun `isDuckDuckGoUrl - checking subdomain and ETL dis not DDG - returns false`() { assertFalse(testee.isDuckDuckGoUrl("https://test.duckduckgo.test.com")) } @Test - fun whenDDGUrlContainsQueryThenQueryCanBeExtracted() { + fun `extractQuery - DDG url contains query - query extracted`() { val query = testee.extractQuery("https://duckduckgo.com?q=test%20search") assertEquals("test search", query) } @Test - fun whenDDGUrlDoesNotContainsQueryThenQueryIsNull() { + fun `extractQuery - DDG url does not contain query - null`() { val query = testee.extractQuery("https://duckduckgo.com") assertNull(query) } @Test - fun whenDDGUrlContainsQueryThenQueryDetected() { + fun `isDuckDuckGoQueryUrl - contains query - query detected`() { assertTrue(testee.isDuckDuckGoQueryUrl("https://duckduckgo.com?q=test%20search")) } @Test - fun whenDDGUrlDoesNotContainsQueryThenQueryIsNotDetected() { + fun `isDuckDuckGoQueryUrl - does not contain query - is not detected`() { assertFalse(testee.isDuckDuckGoQueryUrl("https://duckduckgo.com")) } @Test - fun whenNonDDGUrlContainsQueryThenQueryIsNotDetected() { + fun `isDuckDuckGoQueryUrl - non DDG URL contains query - not detected`() { assertFalse(testee.isDuckDuckGoQueryUrl("https://example.com?q=test%20search")) } @Test - fun whenDDGUrlContainsVerticalThenVerticalCanBeExtracted() { + fun `extractVertical - DDG URL contains vertical - images`() { val vertical = testee.extractVertical("https://duckduckgo.com/?q=new+zealand+images&t=ffab&atb=v218-6&iar=images&iax=images&ia=images") assertEquals("images", vertical) } @Test - fun whenDDGUrlDoesNotContainVerticalThenVerticalIsNull() { + fun `extractVertical - DDG URL does not contain vertical - null`() { val vertical = testee.extractVertical("https://duckduckgo.com") assertNull(vertical) } @Test - fun whenDDGUrlContainsVerticalThenVerticalUrlDetected() { + fun `isDuckDuckGoVerticalUrl - contains vertical - detected`() { assertTrue(testee.isDuckDuckGoVerticalUrl("https://duckduckgo.com?ia=images")) } @Test - fun whenDDGUrlDoesNotContainsVerticalThenVerticalUrlIsNotDetected() { + fun `isDuckDuckGoVerticalUrl - does not contain vertical - is not detected`() { assertFalse(testee.isDuckDuckGoVerticalUrl("https://duckduckgo.com")) } @Test - fun whenCheckingNonDDGUrThenVerticalUrlIsNotDetected() { + fun `isDuckDuckGoVerticalUrl - non DDG URL - not detected`() { assertFalse(testee.isDuckDuckGoVerticalUrl("https://example.com?ia=images")) } @Test - fun whenDDGIsSettingsPageThenStaticPageIsDetected() { + fun `isDuckDuckGoStaticUrl - settings page - static page detected`() { assertTrue(testee.isDuckDuckGoStaticUrl("https://duckduckgo.com/settings")) } @Test - fun whenDDGIsParamsPageThenStaticPageIsDetected() { + fun `isDuckDuckGoStaticUrl - params page - static page detected`() { assertTrue(testee.isDuckDuckGoStaticUrl("https://duckduckgo.com/params")) } @Test - fun whenDDGIsNotStaticPageThenStaticPageIsNotDetected() { + fun `isDuckDuckGoStatic - not static page - is not detected`() { assertFalse(testee.isDuckDuckGoStaticUrl("https://duckduckgo.com/something")) } @Test - fun whenNonDDGThenStaticPageIsDetected() { + fun `isDuckDuckGoStatic - non DDG - not detected`() { assertFalse(testee.isDuckDuckGoStaticUrl("https://example.com/settings")) } @Test - fun whenIsNotDuckDuckGoEmailUrlThenReturnFalse() { + fun `isDuckDuckGoEmailUrl - is not DuckDuckGo email URL - returns false`() { assertFalse(testee.isDuckDuckGoEmailUrl("https://example.com")) } @Test - fun whenIsDuckDuckEmailUrlGoThenReturnTrue() { + fun `isDuckDuckGoEmailUrl - returns true`() { assertTrue(testee.isDuckDuckGoEmailUrl("https://duckduckgo.com/email")) } @Test - fun whenUrlContainsSubdomainAndIsETLDForDuckDuckGoEmailUrlThenReturnTrue() { + fun `isDuckDuckGoEmailUrl - url contains subdomain and is ETLD for DuckDuckGo email URL - returns true`() { assertTrue(testee.isDuckDuckGoEmailUrl("https://test.duckduckgo.com/email")) } @Test - fun whenUrlContainsSubdomainAndIsNotETLDForDuckDuckGoEmailUrlThenReturnTrue() { + fun `isDuckDuckGoEmailUrl - url contains subdomain and is not ETLD for DuckDuckGo email URL - returns true`() { assertFalse(testee.isDuckDuckGoEmailUrl("https://test.duckduckgo.test.com/email")) } @Test - fun whenUrlHasNoSchemeAndIsFromDuckDuckGoUrlThenReturnsFalse() { + fun `isDuckDuckGoEmailUrl - no scheme and from duckduckgo url - returns false`() { assertFalse(testee.isDuckDuckGoEmailUrl("duckduckgo.com/email")) } } diff --git a/app/src/test/java/com/duckduckgo/app/browser/EmptyNavigationStateTest.kt b/app/src/test/java/com/duckduckgo/app/browser/EmptyNavigationStateTest.kt index 9b8315abffb7..cae93e0ca8bf 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/EmptyNavigationStateTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/EmptyNavigationStateTest.kt @@ -23,7 +23,7 @@ import org.junit.Test class EmptyNavigationStateTest { @Test - fun whenEmptyNavigationStateFromNavigationStateThenBrowserPropertiesAreTheSame() { + fun `whenEmptyNavigationStateFromNavigationStateThenBrowserPropertiesAreTheSame - browser properties same`() { val previousState = buildState("originalUrl", "currentUrl", "titlle") val emptyNavigationState = EmptyNavigationState(previousState) @@ -33,7 +33,7 @@ class EmptyNavigationStateTest { } @Test - fun whenEmptyNavigationStateFromNavigationStateThenNavigationPropertiesAreCleared() { + fun `whenEmptyNavigationStateFromNavigationStateThenNavigationPropertiesAreCleared - navigation properties cleared`() { val emptyNavigationState = EmptyNavigationState(buildState("originalUrl", "currentUrl", "titlle")) assertEquals(emptyNavigationState.stepsToPreviousPage, 0) diff --git a/app/src/test/java/com/duckduckgo/app/browser/MajorWebViewVersionProviderTest.kt b/app/src/test/java/com/duckduckgo/app/browser/MajorWebViewVersionProviderTest.kt index 742312e33e04..ca1025510e51 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/MajorWebViewVersionProviderTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/MajorWebViewVersionProviderTest.kt @@ -31,70 +31,70 @@ class MajorWebViewVersionProviderTest { ) @Test - fun whenWebViewVersionIsEmptyThenReturnUnknownFullVersion() { + fun `getFullVersion - web view version empty - unknown`() { whenever(webViewVersionSource.get()).thenReturn("") assertEquals("unknown", testee.getFullVersion()) } @Test - fun whenWebViewVersionIsAvailableThenReturnFullVersion() { + fun `getFullVersion - web view version available - full version`() { whenever(webViewVersionSource.get()).thenReturn("91.1.12.1234.423") assertEquals("91.1.12.1234.423", testee.getFullVersion()) } @Test - fun whenWebViewVersionIsBlankThenReturnFullVersion() { + fun `getFullVersion - web view version blank - return full version`() { whenever(webViewVersionSource.get()).thenReturn(" ") assertEquals("unknown", testee.getFullVersion()) } @Test - fun whenWebViewVersionIsEmptyThenReturnUnknownMajorVersion() { + fun `getMajorVersion - web view version empty - unknown`() { whenever(webViewVersionSource.get()).thenReturn("") assertEquals("unknown", testee.getMajorVersion()) } @Test - fun whenWebViewVersionAvailableThenReturnMajorVersionOnly() { + fun `getMajorVersion - web view version available - major version only`() { whenever(webViewVersionSource.get()).thenReturn("91.1.12.1234.423") assertEquals("91", testee.getMajorVersion()) } @Test - fun whenWebViewVersionHasNonNumericValuesThenReturnMajorVersionOnly() { + fun `getMajorVersion - web view version non numeric values - major version only`() { whenever(webViewVersionSource.get()).thenReturn("59.amazon-webview-v59-3071.3071.125.462") assertEquals("59", testee.getMajorVersion()) } @Test - fun whenWebViewVersionHasNoValidDelimiterThenReturnUnknownMajorVersion() { + fun `getMajorVersion - web view version has no valid delimiter - unknown`() { whenever(webViewVersionSource.get()).thenReturn("37%20%281448693564-arm%29") assertEquals("unknown", testee.getMajorVersion()) } @Test - fun whenWebViewVersionHasNonNumericMajorThenReturnUnknownMajorVersion() { + fun `getMajorVersion - web view version non numeric major - unknown`() { whenever(webViewVersionSource.get()).thenReturn("37%20%28eng.jenkinswh-arm64%29") assertEquals("unknown", testee.getMajorVersion()) } @Test - fun whenWebViewVersionStartsWithDelimiterThenReturnUnknownMajorVersion() { + fun `getMajorVersion - web view version starts with delimiter - return unknown major version`() { whenever(webViewVersionSource.get()).thenReturn(".91.1.12.1234.423") assertEquals("unknown", testee.getMajorVersion()) } @Test - fun whenWebViewVersionIsBlankThenReturnUnknownMajorVersion() { + fun `getMajorVersion - web view version blank - unknown major version`() { whenever(webViewVersionSource.get()).thenReturn(" ") assertEquals("unknown", testee.getMajorVersion()) diff --git a/app/src/test/java/com/duckduckgo/app/browser/QueryUrlConverterTest.kt b/app/src/test/java/com/duckduckgo/app/browser/QueryUrlConverterTest.kt index b2c532697dbc..fe934726673a 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/QueryUrlConverterTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/QueryUrlConverterTest.kt @@ -50,14 +50,14 @@ class QueryUrlConverterTest { } @Test - fun whenSingleWordThenSearchQueryBuilt() { + fun `convertQueryToUrl - single word - search query built`() { val input = "foo" val result = testee.convertQueryToUrl(input) assertDuckDuckGoSearchQuery("foo", result) } @Test - fun whenWebUrlCalledWithInvalidURLThenEncodedSearchQueryBuilt() { + fun `convertQueryToUrl - web url called with invalid url - encoded search query built`() { val input = "http://test .com" val expected = "http%3A%2F%2Ftest%20.com" val result = testee.convertQueryToUrl(input) @@ -65,7 +65,7 @@ class QueryUrlConverterTest { } @Test - fun whenEncodingQueryWithSymbolsThenQueryProperlyEncoded() { + fun `convertQueryToUrl - encoding query with symbols - properly encoded`() { val input = "test \"%-.<>\\^_`{|~" val expected = "test%20%22%25-.%3C%3E%5C%5E_%60%7B%7C~" val result = testee.convertQueryToUrl(input) @@ -73,7 +73,7 @@ class QueryUrlConverterTest { } @Test - fun whenParamHasInvalidCharactersThenAddingParamAppendsEncodedVersion() { + fun `convertQueryToUrl - param has invalid characters - appends encoded version`() { val input = "43 + 5" val expected = "43%20%2B%205" val result = testee.convertQueryToUrl(input) @@ -81,7 +81,7 @@ class QueryUrlConverterTest { } @Test - fun whenIsWebUrlMissingSchemeThenHttpWillBeAddedUponConversion() { + fun `convertQueryToUrl - is web url missing scheme - http will be added upon conversion`() { val input = "example.com" val expected = "http://$input" val result = testee.convertQueryToUrl(input) @@ -89,42 +89,42 @@ class QueryUrlConverterTest { } @Test - fun whenQueryOriginIsFromUserAndIsQueryThenSearchQueryBuilt() { + fun `convertQueryToUrl - from user is query - search query built`() { val input = "foo" val result = testee.convertQueryToUrl(input, queryOrigin = QueryOrigin.FromUser) assertDuckDuckGoSearchQuery("foo", result) } @Test - fun whenQueryOriginIsFromUserAndIsUrlThenUrlReturned() { + fun `convertQueryToUrl - from user and is url - url returned`() { val input = "http://example.com" val result = testee.convertQueryToUrl(input, queryOrigin = QueryOrigin.FromUser) assertEquals(input, result) } @Test - fun whenQueryOriginIsFromAutocompleteAndIsNavIsFalseThenSearchQueryBuilt() { + fun `convertQueryToUrl - from autocomplete and is nav false - search query built`() { val input = "example.com" val result = testee.convertQueryToUrl(input, queryOrigin = QueryOrigin.FromAutocomplete(isNav = false)) assertDuckDuckGoSearchQuery("example.com", result) } @Test - fun whenQueryOriginIsFromAutocompleteAndIsNavIsTrueThenUrlReturned() { + fun `convertQueryToUrl - from autocomplete and is nav true - url returned`() { val input = "http://example.com" val result = testee.convertQueryToUrl(input, queryOrigin = QueryOrigin.FromAutocomplete(isNav = true)) assertEquals(input, result) } @Test - fun whenQueryOriginIsFromAutocompleteAndIsNavIsNullAndIsNotUrlThenSearchQueryBuilt() { + fun `convertQueryToUrl - from autocomplete and is nav null and is not url - search query built`() { val input = "foo" val result = testee.convertQueryToUrl(input, queryOrigin = QueryOrigin.FromAutocomplete(isNav = null)) assertDuckDuckGoSearchQuery("foo", result) } @Test - fun whenConvertQueryToUrlContainsAMajorVerticalThenVerticalAddedToUrl() { + fun `convertQueryToUrl - contains major vertical - vertical added to url`() { val input = "foo" val vertical = QueryUrlConverter.majorVerticals.random() val result = testee.convertQueryToUrl(input, vertical = vertical, queryOrigin = QueryOrigin.FromUser) @@ -132,7 +132,7 @@ class QueryUrlConverterTest { } @Test - fun whenConvertQueryToUrlContainsANonMajorVerticalThenVerticalNotAddedToUrl() { + fun `convertQueryToUrl - contains non major vertical - does not add to url`() { val input = "foo" val vertical = "nonMajor" val result = testee.convertQueryToUrl(input, vertical = vertical, queryOrigin = QueryOrigin.FromUser) diff --git a/app/src/test/java/com/duckduckgo/app/browser/SpecialUrlDetectorImplTest.kt b/app/src/test/java/com/duckduckgo/app/browser/SpecialUrlDetectorImplTest.kt index 4a2f2d0edeae..f2747ce82b81 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/SpecialUrlDetectorImplTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/SpecialUrlDetectorImplTest.kt @@ -73,47 +73,47 @@ class SpecialUrlDetectorImplTest { } @Test - fun whenUrlIsHttpThenWebTypeDetected() { + fun `determineType - url is http - web type detected`() { val expected = Web::class val actual = testee.determineType("http://example.com") assertEquals(expected, actual::class) } @Test - fun whenUrlIsHttpThenWebAddressInData() { + fun `determineType - http url - web address in data`() { val type: Web = testee.determineType("http://example.com") as Web assertEquals("http://example.com", type.webAddress) } @Test - fun whenUrlIsHttpsThenWebTypeDetected() { + fun `determineType - https - web type detected`() { val expected = Web::class val actual = testee.determineType("https://example.com") assertEquals(expected, actual::class) } @Test - fun whenUrlIsHttpsThenSchemePreserved() { + fun `determineType - url is https - scheme preserved`() { val type = testee.determineType("https://example.com") as Web assertEquals("https://example.com", type.webAddress) } @Test - fun whenNoNonBrowserActivitiesFoundThenReturnWebType() { + fun `determineType - no non-browser activities found - return web type`() { whenever(mockPackageManager.queryIntentActivities(any(), anyInt())).thenReturn(listOf(buildBrowserResolveInfo())) val type = testee.determineType("https://example.com") assertTrue(type is Web) } @Test - fun whenAppLinkThrowsURISyntaxExceptionThenReturnWebType() { + fun `determineType - app link throws URI syntax exception - returns web type`() { given(mockPackageManager.queryIntentActivities(any(), anyInt())).willAnswer { throw URISyntaxException("", "") } val type = testee.determineType("https://example.com") assertTrue(type is Web) } @Test - fun whenDefaultNonBrowserActivityFoundThenReturnAppLinkWithIntent() { + fun `determineType - default non browser activity found - return app link with intent`() { whenever(mockPackageManager.resolveActivity(any(), eq(PackageManager.MATCH_DEFAULT_ONLY))).thenReturn(buildAppResolveInfo()) whenever(mockPackageManager.queryIntentActivities(any(), anyInt())).thenReturn( listOf( @@ -135,7 +135,7 @@ class SpecialUrlDetectorImplTest { } @Test - fun whenFirstNonBrowserActivityFoundThenReturnAppLinkWithIntent() { + fun `determineType - first non browser activity found - return app link with intent`() { whenever(mockPackageManager.resolveActivity(any(), eq(PackageManager.MATCH_DEFAULT_ONLY))).thenReturn(null) whenever(mockPackageManager.queryIntentActivities(any(), anyInt())).thenReturn( listOf( @@ -157,7 +157,7 @@ class SpecialUrlDetectorImplTest { } @Test - fun whenNoNonBrowserActivityFoundThenReturnWebType() { + fun `determineType - no non-browser activity found - return web type`() { whenever(mockPackageManager.resolveActivity(any(), eq(PackageManager.MATCH_DEFAULT_ONLY))).thenReturn(null) whenever(mockPackageManager.queryIntentActivities(any(), anyInt())).thenReturn( listOf( @@ -175,198 +175,198 @@ class SpecialUrlDetectorImplTest { } @Test - fun whenUrlIsTelWithDashesThenTelephoneTypeDetected() { + fun `determineType - url is tel with dashes - telephone type detected`() { val expected = Telephone::class val actual = testee.determineType("tel:+123-555-12323") assertEquals(expected, actual::class) } @Test - fun whenUrlIsTelThenTelephoneTypeDetected() { + fun `determineType - url is tel - telephone type detected`() { val expected = Telephone::class val actual = testee.determineType("tel:12355512323") assertEquals(expected, actual::class) } @Test - fun whenUrlIsTelThenSchemeRemoved() { + fun `determineType - url is tel - scheme removed`() { val type = testee.determineType("tel:+123-555-12323") as Telephone assertEquals("+123-555-12323", type.telephoneNumber) } @Test - fun whenUrlIsTelpromptThenTelephoneTypeDetected() { + fun `determineType - url is telprompt - telephone type detected`() { val expected = Telephone::class val actual = testee.determineType("telprompt:12355512323") assertEquals(expected, actual::class) } @Test - fun whenUrlIsTelpromptThenSchemeRemoved() { + fun `determineType - url is telprompt - scheme removed`() { val type = testee.determineType("telprompt:123-555-12323") as Telephone assertEquals("123-555-12323", type.telephoneNumber) } @Test - fun whenUrlIsMailtoThenEmailTypeDetected() { + fun `determineType - url is mailto - email type detected`() { val expected = Email::class val actual = testee.determineType("mailto:foo@example.com") assertEquals(expected, actual::class) } @Test - fun whenUrlIsMailtoThenSchemePreserved() { + fun `determineType - url is mailto - scheme preserved`() { val type = testee.determineType("mailto:foo@example.com") as Email assertEquals("mailto:foo@example.com", type.emailAddress) } @Test - fun whenUrlIsSmsThenSmsTypeDetected() { + fun `determineType - url is sms - sms type detected`() { val expected = Sms::class val actual = testee.determineType("sms:123-555-13245") assertEquals(expected, actual::class) } @Test - fun whenUrlIsSmsToThenSmsTypeDetected() { + fun `determineType - url is sms to - sms type detected`() { val expected = Sms::class val actual = testee.determineType("smsto:123-555-13245") assertEquals(expected, actual::class) } @Test - fun whenUrlIsSmsThenSchemeRemoved() { + fun `determineType - url is sms - scheme removed`() { val type = testee.determineType("sms:123-555-12323") as Sms assertEquals("123-555-12323", type.telephoneNumber) } @Test - fun whenUrlIsSmsToThenSchemeRemoved() { + fun `determineType - url is sms to - scheme removed`() { val type = testee.determineType("smsto:123-555-12323") as Sms assertEquals("123-555-12323", type.telephoneNumber) } @Test - fun whenUrlIsCustomUriSchemeThenNonHttpAppLinkTypeDetected() { + fun `determineType - url is custom uri scheme - non http app link detected`() { val type = testee.determineType("myapp:foo bar") as NonHttpAppLink assertEquals("myapp:foo bar", type.uriString) } @Test - fun whenUrlIsNotPrivacyProThenQueryTypeDetected() { + fun `determineType - url not privacy pro - query type detected`() { whenever(subscriptions.shouldLaunchPrivacyProForUrl(any())).thenReturn(false) val result = testee.determineType("duckduckgo.com") assertTrue(result is SearchQuery) } @Test - fun whenUrlIsPrivacyProThenPrivacyProTypeDetected() { + fun `determineType - url is privacy pro - should launch privacy pro link`() { whenever(subscriptions.shouldLaunchPrivacyProForUrl(any())).thenReturn(true) val result = testee.determineType("duckduckgo.com") assertTrue(result is ShouldLaunchPrivacyProLink) } @Test - fun whenUrlIsParametrizedQueryThenSearchQueryTypeDetected() { + fun `determineType - url is parameterized query - search query detected`() { val type = testee.determineType("foo site:duckduckgo.com") as SearchQuery assertEquals("foo site:duckduckgo.com", type.query) } @Test - fun whenUrlIsJavascriptSchemeThenWebSearchTypeDetected() { + fun `determineType - url is javascript scheme - web search type detected`() { val expected = SearchQuery::class val actual = testee.determineType("javascript:alert(0)") assertEquals(expected, actual::class) } @Test - fun whenUrlIsJavascriptSchemeThenFullQueryRetained() { + fun `determineType - url is javascript scheme - full query retained`() { val type = testee.determineType("javascript:alert(0)") as SearchQuery assertEquals("javascript:alert(0)", type.query) } @Test - fun whenUrlIsAboutSchemeThenWebSearchTypeDetected() { + fun `determineType - about scheme - web search type detected`() { val expected = SearchQuery::class val actual = testee.determineType("about:blank") assertEquals(expected, actual::class) } @Test - fun whenUrlIsAboutSchemeThenFullQueryRetained() { + fun `determineType - url is about scheme - full query retained`() { val type = testee.determineType("about:blank") as SearchQuery assertEquals("about:blank", type.query) } @Test - fun whenUrlIsFileSchemeThenWebSearchTypeDetected() { + fun `determineType - url is file scheme - web search type detected`() { val expected = SearchQuery::class val actual = testee.determineType("file:///sdcard/") assertEquals(expected, actual::class) } @Test - fun whenUrlIsFileSchemeThenFullQueryRetained() { + fun `determineType - url is file scheme - full query retained`() { val type = testee.determineType("file:///sdcard/") as SearchQuery assertEquals("file:///sdcard/", type.query) } @Test - fun whenUrlIsSiteSchemeThenWebSearchTypeDetected() { + fun `determineType - url is site scheme - web search type detected`() { val expected = SearchQuery::class val actual = testee.determineType("site:example.com") assertEquals(expected, actual::class) } @Test - fun whenUrlIsSiteSchemeThenFullQueryRetained() { + fun `determineType - url is site scheme - full query retained`() { val type = testee.determineType("site:example.com") as SearchQuery assertEquals("site:example.com", type.query) } @Test - fun whenUrlIsBlobSchemeThenFullQueryRetained() { + fun `determineType - url is blob scheme - full query retained`() { val type = testee.determineType("blob:example.com") as SearchQuery assertEquals("blob:example.com", type.query) } @Test - fun whenSmsContentIsLongerThanMaxAllowedThenTruncateToMax() { + fun `determineType - sms content longer than max allowed - truncated to max`() { val longSms = randomString(SMS_MAX_LENGTH + 1) val type = testee.determineType("sms:$longSms") as Sms assertEquals(longSms.substring(0, SMS_MAX_LENGTH), type.telephoneNumber) } @Test - fun whenSmsToContentIsLongerThanMaxAllowedThenTruncateToMax() { + fun `determineType - sms to content longer than max allowed - truncated to max`() { val longSms = randomString(SMS_MAX_LENGTH + 1) val type = testee.determineType("smsto:$longSms") as Sms assertEquals(longSms.substring(0, SMS_MAX_LENGTH), type.telephoneNumber) } @Test - fun whenEmailContentIsLongerThanMaxAllowedThenTruncateToMax() { + fun `determineType - email content longer than max allowed - truncated to max`() { val longEmail = "mailto:${randomString(EMAIL_MAX_LENGTH + 1)}" val type = testee.determineType(longEmail) as Email assertEquals(longEmail.substring(0, EMAIL_MAX_LENGTH), type.emailAddress) } @Test - fun whenTelephoneContentIsLongerThanMaxAllowedThenTruncateToMax() { + fun `determineType - telephone content longer than max allowed - truncated to max`() { val longTelephone = randomString(PHONE_MAX_LENGTH + 1) val type = testee.determineType("tel:$longTelephone") as Telephone assertEquals(longTelephone.substring(0, PHONE_MAX_LENGTH), type.telephoneNumber) } @Test - fun whenTelephonePromptContentIsLongerThanMaxAllowedThenTruncateToMax() { + fun `determineType - telephone prompt content longer than max allowed - truncated to max`() { val longTelephone = randomString(PHONE_MAX_LENGTH + 1) val type = testee.determineType("telprompt:$longTelephone") as Telephone assertEquals(longTelephone.substring(0, PHONE_MAX_LENGTH), type.telephoneNumber) } @Test - fun whenUrlIsAmpLinkThenExtractedAmpLinkTypeDetected() { + fun `determineType - url is amp link - extracted amp link detected`() { whenever(mockAmpLinks.extractCanonicalFromAmpLink(anyString())) .thenReturn(AmpLinkType.ExtractedAmpLink(extractedUrl = "https://www.example.com")) val expected = ExtractedAmpLink::class @@ -376,7 +376,7 @@ class SpecialUrlDetectorImplTest { } @Test - fun whenUrlIsCloakedAmpLinkThenCloakedAmpLinkTypeDetected() { + fun `determineType - url is cloaked amp link - cloaked amp link type detected`() { whenever(mockAmpLinks.extractCanonicalFromAmpLink(anyString())) .thenReturn(AmpLinkType.CloakedAmpLink(ampUrl = "https://www.example.com/amp")) val expected = CloakedAmpLink::class @@ -386,7 +386,7 @@ class SpecialUrlDetectorImplTest { } @Test - fun whenUrlIsTrackingParameterLinkThenTrackingParameterLinkTypeDetected() { + fun `determineType - url is tracking parameter link - tracking parameter link type detected`() { whenever(mockTrackingParameters.cleanTrackingParameters(initiatingUrl = anyString(), url = anyString())) .thenReturn("https://www.example.com/query.html") val expected = TrackingParameterLink::class @@ -397,7 +397,7 @@ class SpecialUrlDetectorImplTest { } @Test - fun whenUrlIsPrivacyProThenPrivacyProLinkDetected() { + fun `determineType - privacy pro link detected - should launch privacy pro link`() { whenever(subscriptions.shouldLaunchPrivacyProForUrl(any())).thenReturn(true) val actual = diff --git a/app/src/test/java/com/duckduckgo/app/browser/WebNavigationStateComparisonTest.kt b/app/src/test/java/com/duckduckgo/app/browser/WebNavigationStateComparisonTest.kt index 49f4e567b189..e7f72122fc6b 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/WebNavigationStateComparisonTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/WebNavigationStateComparisonTest.kt @@ -31,76 +31,76 @@ import org.junit.runner.RunWith class WebNavigationStateComparisonTest { @Test - fun whenPreviousStateAndLatestStateSameThenCompareReturnsUnchanged() { + fun `compare - previous and latest states same - unchanged`() { val state = buildState("http://foo.com", "http://subdomain.foo.com") assertEquals(Unchanged, state.compare(state)) } @Test - fun whenPreviousStateAndLatestStateEqualThenCompareReturnsUnchanged() { + fun `compare - previous state and latest state equal - unchanged`() { val previousState = buildState("http://foo.com", "http://subdomain.foo.com") val latestState = buildState("http://foo.com", "http://subdomain.foo.com") assertEquals(Unchanged, latestState.compare(previousState)) } @Test - fun whenPreviousStateIsNullAndLatestContainsAnOriginalUrlACurrentUrlAndTitleThenCompareReturnsNewPageWithTitle() { + fun `compare - previous state is null - new page with title`() { val previousState = null val latestState = buildState("http://latest.com", "http://subdomain.latest.com", "Title") assertEquals(NewPage("http://subdomain.latest.com", "Title"), latestState.compare(previousState)) } @Test - fun whenPreviousStateIsNullAndLatestContainsAnOriginalUrlACurrentUrlAndNoTitleThenCompareReturnsNewPageWithoutTitle() { + fun `compare - previous state is null - new page without title`() { val previousState = null val latestState = buildState("http://latest.com", "http://subdomain.latest.com") assertEquals(NewPage("http://subdomain.latest.com", null), latestState.compare(previousState)) } @Test - fun whenPreviousContainsNoOriginalOrCurrentUrlAndLatestContainsAnOriginalAndCurrentUrlThenCompareReturnsNewPage() { + fun `compare - previous contains no original or current url and latest contains an original and current url - new page`() { val previousState = buildState(null, null) val latestState = buildState("http://latest.com", "http://subdomain.latest.com") assertEquals(NewPage("http://subdomain.latest.com", null), latestState.compare(previousState)) } @Test - fun whenPreviousContainsNoOriginalUrlAndACurrentUrlAndLatestContainsAnOriginalAndCurrentUrlThenCompareReturnsNewPage() { + fun `compare - previous contains no original url and current url and latest contains an original and current url - new page`() { val previousState = buildState(null, "http://subdomain.previous.com") val latestState = buildState("http://latest.com", "http://subdomain.latest.com") assertEquals(NewPage("http://subdomain.latest.com", null), latestState.compare(previousState)) } @Test - fun whenPreviousContainsAnOriginalUrlAndNoCurrentUrlAndLatestContainsAnOriginalAndCurrentUrlThenCompareReturnsNewPage() { + fun `compare - previous contains original url and no current url and latest contains original and current url - new page`() { val previousState = buildState("http://previous.com", null) val latestState = buildState("http://latest.com", "http://subdomain.latest.com") assertEquals(NewPage("http://subdomain.latest.com", null), latestState.compare(previousState)) } @Test - fun whenPreviousContainsAnOriginalUrlAndCurrentUrlAndLatestContainsADifferentOriginalUrlThenCompareReturnsNewPage() { + fun `compare - previous and latest states different - new page`() { val previousState = buildState("http://previous.com", "http://subdomain.previous.com") val latestState = buildState("http://latest.com", "http://subdomain.latest.com") assertEquals(NewPage("http://subdomain.latest.com", null), latestState.compare(previousState)) } @Test - fun whenPreviousContainsAnOriginalUrlAndCurrentUrlAndLatestContainsSameOriginalUrlAndDifferentCurrentUrlDomainThenCompareReturnsNewPage() { + fun `compare - previous contains original url and current url, latest contains same original url and different current url domain - new page`() { val previousState = buildState("http://same.com", "http://subdomain.previous.com") val latestState = buildState("http://same.com", "http://subdomain.latest.com") assertEquals(NewPage("http://subdomain.latest.com", null), latestState.compare(previousState)) } @Test - fun whenPrevContainsAnOriginalUrlAndCurrentUrlAndLatestContainsSameOriginalUrlAndDifferentCurrentUrlWithSameHostThenCompareReturnsUrlUpdated() { + fun `compare - previous and latest states with same host - url updated`() { val previousState = buildState("http://same.com", "http://same.com/previous") val latestState = buildState("http://same.com", "http://same.com/latest") assertEquals(UrlUpdated("http://same.com/latest"), latestState.compare(previousState)) } @Test - fun whenPreviousContainsAnOriginalUrlAndCurrentUrlAndLatestStateContainsNoOriginalUrlAndNoCurrentUrlThenCompareReturnsPageCleared() { + fun `compare - previous contains original url and current url - page cleared`() { val previousState = buildState("http://previous.com", "http://subdomain.previous.com") val latestState = buildState(null, null) assertEquals(PageCleared, latestState.compare(previousState)) @@ -114,21 +114,21 @@ class WebNavigationStateComparisonTest { } @Test - fun whenLatestStateIsEmptyNavigationCompareReturnsPageNavigationCleared() { + fun `compare - latest state empty - page navigation cleared`() { val previousState = buildState("http://previous.com", "http://subdomain.previous.com") val latestState = EmptyNavigationState(previousState) assertEquals(PageNavigationCleared, latestState.compare(previousState)) } @Test - fun whenPreviousContainsAnOriginalUrlAndCurrentUrlAndLatestContainsSameOriginalUrlAndNoCurrentUrlThenCompareReturnsOther() { + fun `compare - previous contains original url and current url, latest contains same original url and no current url - returns other`() { val previousState = buildState("http://same.com", "http://subdomain.previous.com") val latestState = buildState("http://same.com", null) assertEquals(Other, latestState.compare(previousState)) } @Test - fun whenPreviousContainsAnOriginalUrlAndCurrentUrlAndLatestStateContainsDifferentOriginalUrlAndNoCurrentUrlThenCompareReturnsOther() { + fun `compare - different original url and no current url - other`() { val previousState = buildState("http://previous.com", "http://subdomain.previous.com") val latestState = buildState("http://latest.com", null) assertEquals(Other, latestState.compare(previousState)) diff --git a/app/src/test/java/com/duckduckgo/app/browser/WebViewLongPressHandlerTest.kt b/app/src/test/java/com/duckduckgo/app/browser/WebViewLongPressHandlerTest.kt index 993d5a58eb1e..3ddd2b523998 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/WebViewLongPressHandlerTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/WebViewLongPressHandlerTest.kt @@ -69,37 +69,37 @@ class WebViewLongPressHandlerTest { } @Test - fun whenUserLongPressesWithImageTypeThenPixelFired() { + fun `handleLongPress - image type - pixel fired`() { testee.handleLongPress(HitTestResult.IMAGE_TYPE, HTTPS_IMAGE_URL, mockMenu) verify(mockPixel).fire(AppPixelName.LONG_PRESS) } @Test - fun whenUserLongPressesWithAnchorImageTypeThenPixelFired() { + fun `handleLongPress - anchor image type - pixel fired`() { testee.handleLongPress(HitTestResult.SRC_IMAGE_ANCHOR_TYPE, HTTPS_IMAGE_URL, mockMenu) verify(mockPixel).fire(AppPixelName.LONG_PRESS) } @Test - fun whenUserLongPressesWithUnknownTypeThenPixelNotFired() { + fun `handleLongPress - unknown type - pixel not fired`() { testee.handleLongPress(HitTestResult.UNKNOWN_TYPE, HTTPS_IMAGE_URL, mockMenu) verify(mockPixel, never()).fire(AppPixelName.LONG_PRESS) } @Test - fun whenUserLongPressesWithImageTypeThenUrlHeaderAddedToMenu() { + fun `handleLongPress - image type - url header added to menu`() { testee.handleLongPress(HitTestResult.IMAGE_TYPE, HTTPS_IMAGE_URL, mockMenu) verify(mockMenu).setHeaderTitle(HTTPS_IMAGE_URL) } @Test - fun whenUserLongPressesWithAnchorImageTypeThenUrlHeaderAddedToMenu() { + fun `handleLongPress - anchor image type - url header added to menu`() { testee.handleLongPress(HitTestResult.SRC_IMAGE_ANCHOR_TYPE, HTTPS_IMAGE_URL, mockMenu) verify(mockMenu).setHeaderTitle(HTTPS_IMAGE_URL) } @Test - fun whenUserLongPressesWithImageTypeAndHttpsThenCorrectOptionsAddedToMenu() { + fun `handleLongPress - image type and https - correct options added to menu`() { testee.handleLongPress(HitTestResult.IMAGE_TYPE, HTTPS_IMAGE_URL, mockMenu) // Show "Download Image" and "Open Image in Background Tab" verifyDownloadImageMenuOptionsAdded() @@ -110,7 +110,7 @@ class WebViewLongPressHandlerTest { } @Test - fun whenUserLongPressesWithImageTypeAndDataUrlThenCorrectOptionsAddedToMenu() { + fun `handleLongPress - image type and data url - correct options added to menu`() { testee.handleLongPress(HitTestResult.IMAGE_TYPE, DATA_URI_IMAGE_URL, mockMenu) // Show "Download Image" verifyDownloadImageMenuOptionsAdded() @@ -121,7 +121,7 @@ class WebViewLongPressHandlerTest { } @Test - fun whenInCustomTabAndUserLongPressesWithImageTypeAndHttpsThenCorrectOptionsAddedToMenu() { + fun `handleLongPress - custom tab and https - correct options added to menu`() { whenever(mockCustomTabDetector.isCustomTab()).thenReturn(true) testee.handleLongPress(HitTestResult.IMAGE_TYPE, HTTPS_IMAGE_URL, mockMenu) // Show "Download Image" @@ -133,7 +133,7 @@ class WebViewLongPressHandlerTest { } @Test - fun whenUserLongPressesWithAnchorImageTypeAndHttpsThenCorrectOptionsAddedToMenu() { + fun `handleLongPress - anchor image type and https - correct options added to menu`() { testee.handleLongPress(HitTestResult.SRC_IMAGE_ANCHOR_TYPE, HTTPS_IMAGE_URL, mockMenu) // Show "Download Image", "Open Image in Background Tab", "Open In New Tab", "Open in Background Tab", // "Copy Link Address", "Share Link" @@ -144,7 +144,7 @@ class WebViewLongPressHandlerTest { } @Test - fun whenUserLongPressesWithAnchorImageTypeAndDataUrlThenCorrectOptionsAddedToMenu() { + fun `handleLongPress - anchor image type and data url - correct options added to menu`() { testee.handleLongPress(HitTestResult.SRC_IMAGE_ANCHOR_TYPE, DATA_URI_IMAGE_URL, mockMenu) // Show "Download Image" verifyDownloadImageMenuOptionsAdded() @@ -155,7 +155,7 @@ class WebViewLongPressHandlerTest { } @Test - fun whenInCustomTabAndUserLongPressesWithAnchorImageTypeAndHttpsThenCorrectOptionsAddedToMenu() { + fun `handleLongPress - custom tab - long press with anchor image type and https - correct options added to menu`() { testee.handleLongPress(HitTestResult.SRC_IMAGE_ANCHOR_TYPE, DATA_URI_IMAGE_URL, mockMenu) // Show "Download Image" verifyDownloadImageMenuOptionsAdded() @@ -166,7 +166,7 @@ class WebViewLongPressHandlerTest { } @Test - fun whenUserLongPressesWithAnchorTypeAndHttpsThenCorrectOptionsAddedToMenu() { + fun `handleLongPress - anchor type and https - correct options added to menu`() { testee.handleLongPress(HitTestResult.SRC_ANCHOR_TYPE, HTTPS_IMAGE_URL, mockMenu) // Show "Open In New Tab", "Open in Background Tab", "Copy Link Address", "Share Link" verifyLinkMenuOpenInTabOptionsAdded() @@ -177,7 +177,7 @@ class WebViewLongPressHandlerTest { } @Test - fun whenUserLongPressesWithAnchorTypeAndDataUrlThenCorrectOptionsAddedToMenu() { + fun `handleLongPress - anchor type and data url - correct options added to menu`() { testee.handleLongPress(HitTestResult.SRC_ANCHOR_TYPE, DATA_URI_IMAGE_URL, mockMenu) // Show "Open In New Tab", "Open in Background Tab", "Copy Link Address", "Share Link" verifyLinkMenuOpenInTabOptionsAdded() @@ -200,13 +200,13 @@ class WebViewLongPressHandlerTest { } @Test - fun whenUserLongPressesWithOtherImageTypeThenMenuNotAltered() { + fun `handleLongPress - other image type - menu not altered`() { testee.handleLongPress(HitTestResult.UNKNOWN_TYPE, HTTPS_IMAGE_URL, mockMenu) verifyMenuNotAltered() } @Test - fun whenUserSelectsDownloadImageOptionThenActionIsDownloadFileActionRequired() { + fun `userSelectsDownloadImageOption - action download file required`() { whenever(mockMenuItem.itemId).thenReturn(WebViewLongPressHandler.CONTEXT_MENU_ID_DOWNLOAD_IMAGE) val longPressTarget = LongPressTarget(url = "example.com", imageUrl = "example.com/foo.jpg", type = HitTestResult.SRC_ANCHOR_TYPE) val action = testee.userSelectedMenuItem(longPressTarget, mockMenuItem) @@ -214,7 +214,7 @@ class WebViewLongPressHandlerTest { } @Test - fun whenUserSelectsDownloadImageOptionButNoImageUrlAvailableThenNoActionRequired() { + fun `userSelectsDownloadImageOption - no image url available - no action required`() { whenever(mockMenuItem.itemId).thenReturn(WebViewLongPressHandler.CONTEXT_MENU_ID_DOWNLOAD_IMAGE) val longPressTarget = LongPressTarget(url = "example.com", imageUrl = null, type = HitTestResult.SRC_ANCHOR_TYPE) val action = testee.userSelectedMenuItem(longPressTarget, mockMenuItem) @@ -222,7 +222,7 @@ class WebViewLongPressHandlerTest { } @Test - fun whenUserSelectsDownloadImageOptionThenDownloadFileWithCorrectUrlReturned() { + fun `userSelectsDownloadImageOption - download file with correct url returned`() { whenever(mockMenuItem.itemId).thenReturn(WebViewLongPressHandler.CONTEXT_MENU_ID_DOWNLOAD_IMAGE) val longPressTarget = LongPressTarget(url = "example.com", imageUrl = "example.com/foo.jpg", type = HitTestResult.SRC_ANCHOR_TYPE) val action = testee.userSelectedMenuItem(longPressTarget, mockMenuItem) as LongPressHandler.RequiredAction.DownloadFile @@ -230,7 +230,7 @@ class WebViewLongPressHandlerTest { } @Test - fun whenUserSelectsUnknownOptionThenNoActionRequiredReturned() { + fun `userSelectsUnknownOption - no action required returned`() { val unknownMenuId = 123 whenever(mockMenuItem.itemId).thenReturn(unknownMenuId) val longPressTarget = LongPressTarget(url = "example.com", type = HitTestResult.SRC_ANCHOR_TYPE) diff --git a/app/src/test/java/com/duckduckgo/app/browser/WebViewNavigationStateTest.kt b/app/src/test/java/com/duckduckgo/app/browser/WebViewNavigationStateTest.kt index cd6feb518718..748764eecc38 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/WebViewNavigationStateTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/WebViewNavigationStateTest.kt @@ -27,13 +27,13 @@ class WebViewNavigationStateTest { private val stack: TestBackForwardList = TestBackForwardList() @Test - fun whenWebHistoryIsEmptyThenNavigationHistoryIsEmpty() { + fun `webViewState - navigation history empty - is empty`() { val stack = webViewState(stack).navigationHistory assertEquals(0, stack.size) } @Test - fun whenWebHistoryHasSinglePageThenNavigationHistoryRetrieved() { + fun `whenWebHistoryHasSinglePageThenNavigationHistoryRetrieved - navigation history retrieved`() { stack.addPageToHistory("example.com".toHistoryItem()) val stack = webViewState(stack).navigationHistory assertEquals(1, stack.size) @@ -41,7 +41,7 @@ class WebViewNavigationStateTest { } @Test - fun whenWebHistoryHasMultiplePagesThenNavigationHistoryRetrievedInCorrectOrder() { + fun `whenWebHistoryHasMultiplePages - navigation history retrieved in correct order`() { stack.addPageToHistory("a".toHistoryItem()) stack.addPageToHistory("b".toHistoryItem()) stack.addPageToHistory("c".toHistoryItem()) diff --git a/app/src/test/java/com/duckduckgo/app/browser/applinks/DuckDuckGoAppLinksHandlerTest.kt b/app/src/test/java/com/duckduckgo/app/browser/applinks/DuckDuckGoAppLinksHandlerTest.kt index 385ab16234e8..2d14091ea4b3 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/applinks/DuckDuckGoAppLinksHandlerTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/applinks/DuckDuckGoAppLinksHandlerTest.kt @@ -41,7 +41,7 @@ class DuckDuckGoAppLinksHandlerTest { } @Test - fun whenAppLinkHandledAndIsSameOrSubdomainThenReturnFalse() { + fun `handleAppLink - same or subdomain - returns false`() { assertFalse( testee.handleAppLink( isForMainFrame = true, @@ -54,7 +54,7 @@ class DuckDuckGoAppLinksHandlerTest { } @Test - fun whenAppLinkHandledAndIsNotSameOrSubdomainThenReturnFalseAndLaunchAppLink() { + fun `handleAppLink - not same or subdomain - return false and launch app link`() { assertFalse( testee.handleAppLink( isForMainFrame = true, @@ -68,7 +68,7 @@ class DuckDuckGoAppLinksHandlerTest { } @Test - fun whenAppLinkHandledAndIsNotForMainFrameThenReturnFalse() { + fun `handleAppLink - not for main frame - returns false`() { assertFalse( testee.handleAppLink( isForMainFrame = false, @@ -82,7 +82,7 @@ class DuckDuckGoAppLinksHandlerTest { } @Test - fun whenAppLinkHandledOnApiLessThan24ThenReturnFalse() { + fun `handleAppLink - api less than 24 - returns false`() { assertFalse( testee.handleAppLink( isForMainFrame = false, @@ -96,20 +96,20 @@ class DuckDuckGoAppLinksHandlerTest { } @Test - fun whenPreviousUrlUpdatedThenUpdatePreviousUrl() { + fun `updatePreviousUrl - previous url updated - foo·com`() { testee.updatePreviousUrl("foo.com") assertEquals("foo.com", testee.previousUrl) } @Test - fun whenPreviousUrlUpdatedAndIsNullThenResetTriggerState() { + fun `updatePreviousUrl - is null - reset trigger state`() { testee.hasTriggeredForDomain = true testee.updatePreviousUrl(null) assertFalse(testee.hasTriggeredForDomain) } @Test - fun whenPreviousUrlUpdatedAndPreviousUrlIsNullThenDoNotResetTriggerState() { + fun `updatePreviousUrl - previous url updated and is null - do not reset trigger state`() { testee.previousUrl = null testee.hasTriggeredForDomain = true testee.updatePreviousUrl("example.com") @@ -117,7 +117,7 @@ class DuckDuckGoAppLinksHandlerTest { } @Test - fun whenPreviousUrlUpdatedAndIsNotSameOrSubdomainThenResetTriggerState() { + fun `updatePreviousUrl - previous url updated and is not same or subdomain - reset trigger state`() { testee.hasTriggeredForDomain = true testee.previousUrl = "example.com" testee.updatePreviousUrl("foo.com") @@ -125,7 +125,7 @@ class DuckDuckGoAppLinksHandlerTest { } @Test - fun whenPreviousUrlUpdatedAndIsSameOrSubdomainThenDoNotResetTriggerState() { + fun `updatePreviousUrl - same or subdomain - do not reset trigger state`() { testee.hasTriggeredForDomain = true testee.previousUrl = "example.com" testee.updatePreviousUrl("app.example.com") @@ -133,7 +133,7 @@ class DuckDuckGoAppLinksHandlerTest { } @Test - fun whenAppLinksDisabledThenReturnFalse() { + fun `handleAppLink - app links disabled - returns false`() { assertFalse( testee.handleAppLink( isForMainFrame = true, @@ -146,7 +146,7 @@ class DuckDuckGoAppLinksHandlerTest { } @Test - fun whenPreviousUrlIsSameThenReturnFalse() { + fun `handleAppLink - previous url same - return false`() { testee.previousUrl = "example.com" assertFalse( testee.handleAppLink( @@ -160,7 +160,7 @@ class DuckDuckGoAppLinksHandlerTest { } @Test - fun whenPreviousUrlIsSubdomainThenReturnFalse() { + fun `handleAppLink - previous url subdomain - return false`() { testee.previousUrl = "foo.example.com" assertFalse( testee.handleAppLink( @@ -174,7 +174,7 @@ class DuckDuckGoAppLinksHandlerTest { } @Test - fun whenNextUrlIsSubdomainThenReturnFalse() { + fun `handleAppLink - previous url set - returns false`() { testee.previousUrl = "example.com" assertFalse( testee.handleAppLink( @@ -188,7 +188,7 @@ class DuckDuckGoAppLinksHandlerTest { } @Test - fun whenAppLinkIsSameOrSubdomainAndIsUserQueryThenReturnFalseAndSetPreviousUrlAndLaunchAppLink() { + fun `handleAppLink - same or subdomain and is user query - return false set previous url and launch app link`() { testee.isAUserQuery = true testee.hasTriggeredForDomain = false testee.previousUrl = "example.com/something" @@ -207,7 +207,7 @@ class DuckDuckGoAppLinksHandlerTest { } @Test - fun whenAppLinkIsSameOrSubdomainAndHasNotTriggeredForDomainThenReturnFalseAndSetPreviousUrlAndLaunchAppLink() { + fun `handleAppLink - same or subdomain and has not triggered for domain - return false set previous url and launch app link`() { testee.isAUserQuery = false testee.hasTriggeredForDomain = false testee.previousUrl = "example.com/something" @@ -226,7 +226,7 @@ class DuckDuckGoAppLinksHandlerTest { } @Test - fun whenAppLinkIsSameOrSubdomainAndIsInAlwaysTriggerListThenReturnFalseAndSetPreviousUrlAndLaunchAppLink() { + fun `handleAppLink - same or subdomain and in always trigger list - return false and set previous url and launch app link`() { testee.isAUserQuery = false testee.hasTriggeredForDomain = true testee.previousUrl = "digid.nl/something" @@ -245,7 +245,7 @@ class DuckDuckGoAppLinksHandlerTest { } @Test - fun whenAppLinkIsSameOrSubdomainAndIsNotUserQueryAndHasTriggeredForDomainAndIsNotInAlwaysTriggerListThenReturnFalse() { + fun `handleAppLink - same or subdomain and not user query and has triggered for domain and is not in always trigger list - returns false`() { testee.hasTriggeredForDomain = true testee.isAUserQuery = false testee.previousUrl = "foo.example.com" @@ -264,7 +264,7 @@ class DuckDuckGoAppLinksHandlerTest { } @Test - fun whenShouldHaltWebNavigationThenReturnTrueAndSetPreviousUrlAndLaunchAppLink() { + fun `handleAppLink - should halt web navigation - return true and set previous url and launch app link`() { testee.previousUrl = "foo.com" assertTrue( testee.handleAppLink( @@ -280,7 +280,7 @@ class DuckDuckGoAppLinksHandlerTest { } @Test - fun whenShouldNotHaltWebNavigationThenReturnFalseAndSetPreviousUrlAndLaunchAppLink() { + fun `handleAppLink - should not halt web navigation - return false and set previous url and launch app link`() { testee.previousUrl = "foo.com" assertFalse( testee.handleAppLink( diff --git a/app/src/test/java/com/duckduckgo/app/browser/autofill/RealAutofillFireproofDialogSuppressorTest.kt b/app/src/test/java/com/duckduckgo/app/browser/autofill/RealAutofillFireproofDialogSuppressorTest.kt index 7cb027f4749d..58e53efec10b 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/autofill/RealAutofillFireproofDialogSuppressorTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/autofill/RealAutofillFireproofDialogSuppressorTest.kt @@ -35,18 +35,18 @@ class RealAutofillFireproofDialogSuppressorTest { } @Test - fun whenNoInteractionsThenNotPreventingPrompts() { + fun `isAutofillPreventingFireproofPrompts - no interactions - not preventing prompts`() { assertFalse(testee.isAutofillPreventingFireproofPrompts()) } @Test - fun whenSaveOrUpdateDialogVisibleThenPreventingPrompts() { + fun `autofillSaveOrUpdateDialogVisibilityChanged - preventing prompts`() { testee.autofillSaveOrUpdateDialogVisibilityChanged(true) assertTrue(testee.isAutofillPreventingFireproofPrompts()) } @Test - fun whenSaveOrUpdateDialogDismissedRecentlyThenPreventingPrompts() { + fun `saveOrUpdateDialogDismissed - preventing prompts`() { testee.autofillSaveOrUpdateDialogVisibilityChanged(true) testee.autofillSaveOrUpdateDialogVisibilityChanged(false) assertTrue(testee.isAutofillPreventingFireproofPrompts()) diff --git a/app/src/test/java/com/duckduckgo/app/browser/customtabs/CustomTabViewModelTest.kt b/app/src/test/java/com/duckduckgo/app/browser/customtabs/CustomTabViewModelTest.kt index f664f51ceaa8..9669c64e8c65 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/customtabs/CustomTabViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/customtabs/CustomTabViewModelTest.kt @@ -30,7 +30,7 @@ class CustomTabViewModelTest { } @Test - fun whenCustomTabCreatedThenPixelFired() = runTest { + fun `onCustomTabCreated - viewState updated - pixel fired`() = runTest { testee.onCustomTabCreated("url", 100) testee.viewState.test { @@ -44,14 +44,14 @@ class CustomTabViewModelTest { } @Test - fun whenCustomTabShownThenCustomTabDetectorSetToTrue() { + fun `onShowCustomTab - custom tab detector set to true`() { testee.onShowCustomTab() verify(mockCustomTabDetector).setCustomTab(true) } @Test - fun whenCustomTabClosedThenCustomTabDetectorSetToFalse() { + fun `onCloseCustomTab - custom tab detector set to false`() { testee.onCloseCustomTab() verify(mockCustomTabDetector).setCustomTab(false) diff --git a/app/src/test/java/com/duckduckgo/app/browser/customtabs/IntentDispatcherViewModelTest.kt b/app/src/test/java/com/duckduckgo/app/browser/customtabs/IntentDispatcherViewModelTest.kt index c6bd30f1c207..bcc62838d610 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/customtabs/IntentDispatcherViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/customtabs/IntentDispatcherViewModelTest.kt @@ -38,7 +38,7 @@ class IntentDispatcherViewModelTest { } @Test - fun whenIntentReceivedWithSessionThenCustomTabIsRequested() = runTest { + fun `onIntentReceived - with session - custom tab requested`() = runTest { val text = "url" val toolbarColor = 100 configureHasSession(true) @@ -56,7 +56,7 @@ class IntentDispatcherViewModelTest { } @Test - fun whenIntentReceivedWithoutSessionThenCustomTabIsNotRequested() = runTest { + fun `onIntentReceived - no session - custom tab not requested`() = runTest { val text = "url" configureHasSession(false) whenever(mockIntent.intentText).thenReturn(text) @@ -72,7 +72,7 @@ class IntentDispatcherViewModelTest { } @Test - fun whenIntentReceivedWithSessionAndLinkIsEmailProtectionVerificationThenCustomTabIsNotRequested() = runTest { + fun `onIntentReceived - viewState - custom tab not requested`() = runTest { configureHasSession(true) configureIsEmailProtectionLink(true) @@ -85,7 +85,7 @@ class IntentDispatcherViewModelTest { } @Test - fun whenIntentReceivedWithSessionAndLinkIsNotEmailProtectionVerificationThenCustomTabIsRequested() = runTest { + fun `onIntentReceived - session and link not email protection verification - custom tab requested`() = runTest { configureHasSession(true) configureIsEmailProtectionLink(false) @@ -98,7 +98,7 @@ class IntentDispatcherViewModelTest { } @Test - fun whenIntentReceivedWithSessionAndUrlContainingSpacesThenSpacesAreReplacedAndCustomTabIsRequested() = runTest { + fun `onIntentReceived - intent received with session and url containing spaces - custom tab requested`() = runTest { val urlWithSpaces = """ https://mastodon.social/oauth/authorize?client_id=AcfPDZlcKUjwIatVtMt8B8cmdW-w1CSOR6_rYS_6Kxs&scope=read write push&redirect_uri=mastify://oauth&response_type=code @@ -120,7 +120,7 @@ class IntentDispatcherViewModelTest { } @Test - fun whenIntentReceivedWithNoSessionAndIntentTextContainingSpacesAndNotStartingWithHttpSchemaThenNoChangesAreMadeToTheIntent() = runTest { + fun `onIntentReceived - no session - intent text containing spaces and not starting with http schema - no changes made to the intent`() = runTest { val intentTextWithSpaces = """ Voyager 1 is still bringing us surprises from the very edge of our solar system https://www.independent.co.uk/space/voyager-1-nasa-latest-solar-system-b2535462.html @@ -139,7 +139,7 @@ class IntentDispatcherViewModelTest { } @Test - fun whenIntentReceivedWithSessionAndIntentTextContainingSpacesAndNotStartingWithHttpSchemaThenNoChangesAreMadeToTheIntent() = runTest { + fun `onIntentReceived - intent received with session and intent text containing spaces and not starting with http schema - no changes made to the intent`() = runTest { val intentTextWithSpaces = """ Voyager 1 is still bringing us surprises from the very edge of our solar system https://www.independent.co.uk/space/voyager-1-nasa-latest-solar-system-b2535462.html diff --git a/app/src/test/java/com/duckduckgo/app/browser/defaultbrowsing/DefaultBrowserObserverTest.kt b/app/src/test/java/com/duckduckgo/app/browser/defaultbrowsing/DefaultBrowserObserverTest.kt index c158c8165db4..068e0bdf3023 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/defaultbrowsing/DefaultBrowserObserverTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/defaultbrowsing/DefaultBrowserObserverTest.kt @@ -49,7 +49,7 @@ class DefaultBrowserObserverTest { } @Test - fun whenDDGIsDefaultBrowserIfItWasNotBeforeThenFireSetPixel() { + fun `onResume - DDG is default browser if not before - fire set pixel`() { whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(true) whenever(mockAppInstallStore.defaultBrowser).thenReturn(false) val params = mapOf( @@ -62,7 +62,7 @@ class DefaultBrowserObserverTest { } @Test - fun whenDDGIsNotDefaultBrowserIfItWasNotBeforeThenDoNotFireSetPixel() { + fun `onResume - DDG not default browser if it was not before - do not fire set pixel`() { whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(false) whenever(mockAppInstallStore.defaultBrowser).thenReturn(false) @@ -72,7 +72,7 @@ class DefaultBrowserObserverTest { } @Test - fun whenDDGIsDefaultBrowserIfItWasBeforeThenDoNotFireSetPixel() { + fun `isDefaultBrowser - default browser set - does not fire set pixel`() { whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(true) whenever(mockAppInstallStore.defaultBrowser).thenReturn(true) @@ -82,7 +82,7 @@ class DefaultBrowserObserverTest { } @Test - fun whenDDGIsNotDefaultBrowserIfItWasBeforeThenFireUnsetPixel() { + fun `onResume - DDG not default browser if it was before - fire unset pixel`() { whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(false) whenever(mockAppInstallStore.defaultBrowser).thenReturn(true) diff --git a/app/src/test/java/com/duckduckgo/app/browser/downloader/BlobConverterJavascriptInterfaceTest.kt b/app/src/test/java/com/duckduckgo/app/browser/downloader/BlobConverterJavascriptInterfaceTest.kt index 0a53db5aeaa7..51f4c126a874 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/downloader/BlobConverterJavascriptInterfaceTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/downloader/BlobConverterJavascriptInterfaceTest.kt @@ -31,7 +31,7 @@ class BlobConverterJavascriptInterfaceTest { } @Test - fun whenConvertToBlobDataUriThenLambdaCalled() { + fun `convertBlobToDataUri - lambda called - data uri generated`() { testee.convertBlobToDataUri("first", "second") assertEquals("firstsecond", result) diff --git a/app/src/test/java/com/duckduckgo/app/browser/filechooser/FileChooserIntentBuilderTest.kt b/app/src/test/java/com/duckduckgo/app/browser/filechooser/FileChooserIntentBuilderTest.kt index 975b4f1ab5c2..4b6a243fd43c 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/filechooser/FileChooserIntentBuilderTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/filechooser/FileChooserIntentBuilderTest.kt @@ -40,43 +40,43 @@ class FileChooserIntentBuilderTest { } @Test - fun whenIntentBuiltThenReadUriPermissionFlagSet() { + fun `intent - built - read uri permission flag set`() { val output = testee.intent(emptyArray()) assertTrue("Intent.FLAG_GRANT_READ_URI_PERMISSION flag not set on intent", output.hasFlagSet(Intent.FLAG_GRANT_READ_URI_PERMISSION)) } @Test - fun whenIntentBuiltThenAcceptTypeSetToAll() { + fun `intent - built - accept type set to all`() { val output = testee.intent(emptyArray()) assertEquals("*/*", output.type) } @Test - fun whenMultipleModeDisabledThenIntentExtraReturnsFalse() { + fun `intent - multiple mode disabled - returns false`() { val output = testee.intent(emptyArray(), canChooseMultiple = false) assertFalse(output.getBooleanExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)) } @Test - fun whenRequestedTypesAreMissingThenShouldNotAddMimeTypeExtra() { + fun `intent - requested types missing - does not add mime type extra`() { val output = testee.intent(emptyArray()) assertFalse(output.hasExtra(Intent.EXTRA_MIME_TYPES)) } @Test - fun whenRequestedTypesArePresentThenShouldAddMimeTypeExtra() { + fun `intent - requested types present - adds mime type extra`() { val output = testee.intent(arrayOf("image/png", "image/gif")) assertTrue(output.hasExtra(Intent.EXTRA_MIME_TYPES)) } @Test - fun whenUpperCaseTypesGivenThenNormalisedToLowercase() { + fun `whenIntentCalledWithUpperCaseTypesThenNormalizedToLowercase - intent output normalized`() { val output = testee.intent(arrayOf("ImAgE/PnG")) assertEquals("image/png", output.getStringArrayExtra(Intent.EXTRA_MIME_TYPES)!![0]) } @Test - fun whenEmptyTypesGivenThenNotIncludedInOutput() { + fun `intent - empty types given - not included in output`() { val output = testee.intent(arrayOf("image/png", "", " ", "image/gif")) val mimeTypes = output.getStringArrayExtra(Intent.EXTRA_MIME_TYPES) assertEquals(2, mimeTypes!!.size) @@ -85,13 +85,13 @@ class FileChooserIntentBuilderTest { } @Test - fun whenMultipleModeEnabledThenIntentExtraReturnsTrue() { + fun `intent - multiple mode enabled - returns true`() { val output = testee.intent(emptyArray(), canChooseMultiple = true) assertTrue(output.getBooleanExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)) } @Test - fun whenExtractingSingleUriEmptyClipThenSingleUriReturned() { + fun `extractSelectedFileUris - single uri empty clip - single uri returned`() { val intent = buildIntent("a") val extractedUris = testee.extractSelectedFileUris(intent) @@ -100,7 +100,7 @@ class FileChooserIntentBuilderTest { } @Test - fun whenExtractingSingleUriNonEmptyClipThenUriReturnedFromClip() { + fun `extractSelectedFileUris - non-empty clip - uri returned from clip`() { val intent = buildIntent("a", listOf("b")) val extractedUris = testee.extractSelectedFileUris(intent) @@ -109,7 +109,7 @@ class FileChooserIntentBuilderTest { } @Test - fun whenExtractingMultipleClipItemsThenCorrectUrisReturnedFromClip() { + fun `extractSelectedFileUris - multiple clip items - correct uris returned from clip`() { val intent = buildIntent("a", listOf("b", "c")) val extractedUris = testee.extractSelectedFileUris(intent) @@ -119,7 +119,7 @@ class FileChooserIntentBuilderTest { } @Test - fun whenExtractingSingleUriMissingButClipDataAvailableThenUriReturnedFromClip() { + fun `extractSelectedFileUris - clip data available - uri returned from clip`() { val intent = buildIntent(clipData = listOf("b")) val extractedUris = testee.extractSelectedFileUris(intent) @@ -128,7 +128,7 @@ class FileChooserIntentBuilderTest { } @Test - fun whenNoDataOrClipDataThenNullUriReturned() { + fun `extractSelectedFileUris - no data or clip data - null uri returned`() { val intent = buildIntent(data = null, clipData = null) val extractedUris = testee.extractSelectedFileUris(intent) diff --git a/app/src/test/java/com/duckduckgo/app/browser/logindetection/LoginDetectionJavascriptInterfaceTest.kt b/app/src/test/java/com/duckduckgo/app/browser/logindetection/LoginDetectionJavascriptInterfaceTest.kt index c72202b2c512..873a8fed6210 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/logindetection/LoginDetectionJavascriptInterfaceTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/logindetection/LoginDetectionJavascriptInterfaceTest.kt @@ -23,7 +23,7 @@ import org.mockito.kotlin.verify class LoginDetectionJavascriptInterfaceTest { @Test - fun whenLoginDetectedThenNotifyCallback() { + fun `loginDetection - login detected - notify callback`() { val loginDetected = mock<() -> Unit>() val loginDetectionInterface = LoginDetectionJavascriptInterface(loginDetected) diff --git a/app/src/test/java/com/duckduckgo/app/browser/logindetection/NextPageLoginDetectionTest.kt b/app/src/test/java/com/duckduckgo/app/browser/logindetection/NextPageLoginDetectionTest.kt index f974f3c448fa..6ce0e98647c5 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/logindetection/NextPageLoginDetectionTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/logindetection/NextPageLoginDetectionTest.kt @@ -57,7 +57,7 @@ class NextPageLoginDetectionTest { } @Test - fun whenLoginAttemptedAndUserForwardedToNewPageThenLoginDetected() = runTest { + fun `onLoginAttempted - login detected`() = runTest { givenLoginDetector(enabled = true) loginDetector.onEvent(NavigationEvent.LoginAttempt("http://example.com/login")) @@ -68,7 +68,7 @@ class NextPageLoginDetectionTest { } @Test - fun whenLoginAttemptedInsideOAuthFlowThenLoginDetectedWhenUserForwardedToDifferentDomain() = runTest { + fun `whenLoginAttemptedInsideOAuthFlow - login detected when user forwarded to different domain`() = runTest { givenLoginDetector(enabled = true) redirectTo("https://accounts.google.com/o/oauth2/v2/auth") giveLoginDetectorChanceToExecute() @@ -88,7 +88,7 @@ class NextPageLoginDetectionTest { } @Test - fun whenLoginAttemptedInsideSSOFlowThenLoginDetectedWhenUserForwardedToDifferentDomain() = runTest { + fun `whenLoginAttemptedInsideSSOFlow - login detected when user forwarded to different domain - login detected`() = runTest { givenLoginDetector(enabled = true) fullyLoadSite("https://app.asana.com/-/login") giveLoginDetectorChanceToExecute() @@ -108,7 +108,7 @@ class NextPageLoginDetectionTest { } @Test - fun whenLoginAttemptedSkip2FAUrlsThenLoginDetectedForLatestOne() = runTest { + fun `onEvent - login detected for latest one`() = runTest { givenLoginDetector(enabled = true) fullyLoadSite("https://accounts.google.com/ServiceLogin") giveLoginDetectorChanceToExecute() @@ -126,7 +126,7 @@ class NextPageLoginDetectionTest { } @Test - fun whenLoginAttemptedAndUserForwardedToMultipleNewPagesThenLoginDetectedForLatestOne() = runTest { + fun `onLoginAttempt - login detected for latest one`() = runTest { givenLoginDetector(enabled = true) loginDetector.onEvent(NavigationEvent.LoginAttempt("http://example.com/login")) @@ -141,7 +141,7 @@ class NextPageLoginDetectionTest { } @Test - fun whenLoginAttemptedAndUserForwardedToSamePageThenLoginNotDetected() = runTest { + fun `onEvent - login attempted and user forwarded to same page - login not detected`() = runTest { givenLoginDetector(enabled = true) loginDetector.onEvent(NavigationEvent.LoginAttempt("http://example.com/login")) @@ -152,7 +152,7 @@ class NextPageLoginDetectionTest { } @Test - fun whenNotDetectedLoginAttemptAndForwardedToNewPageThenLoginNotDetected() = runTest { + fun `whenNotDetectedLoginAttemptAndForwardedToNewPageThenLoginNotDetected - login not detected`() = runTest { givenLoginDetector(enabled = true) fullyLoadSite("http://example.com") giveLoginDetectorChanceToExecute() @@ -173,7 +173,7 @@ class NextPageLoginDetectionTest { } @Test - fun whenLoginAttemptedAndUserForwardedToSameUrlThenLoginNotDetected() = runTest { + fun `onEvent - login attempted and user forwarded to same url - login not detected`() = runTest { givenLoginDetector(enabled = true) loginDetector.onEvent(NavigationEvent.LoginAttempt("http://example.com/login")) @@ -185,7 +185,7 @@ class NextPageLoginDetectionTest { } @Test - fun whenNotDetectedLoginAttemptAndForwardedToNewUrlThenLoginNotDetected() = runTest { + fun `whenNotDetectedLoginAttemptAndForwardedToNewUrlThenLoginNotDetected - login not detected`() = runTest { givenLoginDetector(enabled = true) loginDetector.onEvent(NavigationEvent.WebNavigationEvent(WebNavigationStateChange.UrlUpdated(url = "http://example.com"))) loginDetector.onEvent(NavigationEvent.PageFinished) @@ -195,7 +195,7 @@ class NextPageLoginDetectionTest { } @Test - fun whenLoginAttemptedAndNextPageFinishedThenLoadingNewPageDoesNotDetectLogin() = runTest { + fun `onLoginAttempted - loading new page does not detect login - no login detected`() = runTest { givenLoginDetector(enabled = true) loginDetector.onEvent(NavigationEvent.LoginAttempt("http://example.com/login")) loginDetector.onEvent(NavigationEvent.PageFinished) @@ -208,7 +208,7 @@ class NextPageLoginDetectionTest { } @Test - fun whenLoginAttemptedAndUserNavigatesBackThenNewPageDoesNotDetectLogin() = runTest { + fun `onLoginAttempted - navigation back - no login detected`() = runTest { givenLoginDetector(enabled = true) loginDetector.onEvent(NavigationEvent.LoginAttempt("http://example.com/login")) loginDetector.onEvent(NavigationEvent.UserAction.NavigateBack) @@ -220,7 +220,7 @@ class NextPageLoginDetectionTest { } @Test - fun whenLoginAttemptedAndUserNavigatesForwardThenNewPageDoesNotDetectLogin() = runTest { + fun `onLoginAttempted - navigation forward - no login detected`() = runTest { givenLoginDetector(enabled = true) loginDetector.onEvent(NavigationEvent.LoginAttempt("http://example.com/login")) loginDetector.onEvent(NavigationEvent.UserAction.NavigateForward) @@ -232,7 +232,7 @@ class NextPageLoginDetectionTest { } @Test - fun whenLoginAttemptedAndUserReloadsWebsiteThenNewPageDoesNotDetectLogin() = runTest { + fun `onRefresh - login detector - no login detected`() = runTest { givenLoginDetector(enabled = true) loginDetector.onEvent(NavigationEvent.LoginAttempt("http://example.com/login")) loginDetector.onEvent(NavigationEvent.UserAction.Refresh) @@ -244,7 +244,7 @@ class NextPageLoginDetectionTest { } @Test - fun whenLoginAttemptedAndUserSubmitsNewQueryThenNewPageDoesNotDetectLogin() = runTest { + fun `onNewQuerySubmitted - login detector does not detect login`() = runTest { givenLoginDetector(enabled = true) loginDetector.onEvent(NavigationEvent.LoginAttempt("http://example.com/login")) loginDetector.onEvent(NavigationEvent.UserAction.NewQuerySubmitted) @@ -256,7 +256,7 @@ class NextPageLoginDetectionTest { } @Test - fun whenLoginAttemptedHasInvalidURLThenNewPageDoesNotDetectLogin() = runTest { + fun `onLoginAttempted - invalid URL - new page does not detect login`() = runTest { givenLoginDetector(enabled = true) loginDetector.onEvent(NavigationEvent.LoginAttempt("")) @@ -267,7 +267,7 @@ class NextPageLoginDetectionTest { } @Test - fun whenLoginAttemptedAndUserForwardedToInvalidNewPageThenLoginDetected() = runTest { + fun `onLoginAttempted - login detected - no event issued`() = runTest { givenLoginDetector(enabled = true) loginDetector.onEvent(NavigationEvent.LoginAttempt("http://example.com/login")) diff --git a/app/src/test/java/com/duckduckgo/app/browser/logindetection/UriAuthExtensionKtTest.kt b/app/src/test/java/com/duckduckgo/app/browser/logindetection/UriAuthExtensionKtTest.kt index b14e9fe673ce..f02f306fa5cb 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/logindetection/UriAuthExtensionKtTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/logindetection/UriAuthExtensionKtTest.kt @@ -29,7 +29,7 @@ import org.junit.runner.RunWith class UriAuthExtensionKtTest { @Test - fun whenAuthUrlThenReturnTrue() { + fun `getValidUrl - returns true for oAuth urls`() { assertTrue(getValidUrl("https://accounts.google.com/o/oauth2/v2/auth?client_id=283002&scope=openid").isOAuthUrl()) assertTrue(getValidUrl("https://appleid.apple.com/auth/authorize?client_id=com.spotify.accounts").isOAuthUrl()) assertTrue(getValidUrl("https://www.amazon.com/ap/oa?client_id=amzn1.application-oa2-client&scope=profile").isOAuthUrl()) @@ -44,14 +44,14 @@ class UriAuthExtensionKtTest { } @Test - fun when2FAUrlThenReturnTrue() { + fun `getValidUrl - is 2fa url - returns true`() { assertTrue(getValidUrl("https://accounts.google.com/signin/v2/challenge/az?client_id").is2FAUrl()) assertTrue(getValidUrl(" https://sso.duckduckgo.com/module.php/duosecurity/getduo.php").is2FAUrl()) assertTrue(getValidUrl(" https://www.amazon.com/ap/cvf/approval").is2FAUrl()) } @Test - fun whenSSOUrlThenReturnTrue() { + fun `getValidUrl - sso url - returns true`() { assertTrue(getValidUrl("https://sso.host.com/saml2/idp/SSOService.php").isSSOUrl()) } diff --git a/app/src/test/java/com/duckduckgo/app/browser/mediaplayback/store/RealMediaPlaybackRepositoryTest.kt b/app/src/test/java/com/duckduckgo/app/browser/mediaplayback/store/RealMediaPlaybackRepositoryTest.kt index ef75ef8172bc..7bdb35c600c9 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/mediaplayback/store/RealMediaPlaybackRepositoryTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/mediaplayback/store/RealMediaPlaybackRepositoryTest.kt @@ -29,7 +29,7 @@ class RealMediaPlaybackRepositoryTest { } @Test - fun whenRepositoryIsCreatedThenValuesLoadedIntoMemory() { + fun `initRepository - repository created - values loaded into memory`() { givenMediaPlaybackDaoContainsEntities() initRepository() @@ -38,7 +38,7 @@ class RealMediaPlaybackRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = runTest { + fun `updateAll - update all called`() = runTest { initRepository() testee.updateAll(listOf()) @@ -47,7 +47,7 @@ class RealMediaPlaybackRepositoryTest { } @Test - fun whenUpdateAllThenPreviousValuesAreClearedAndNewValuesUpdated() = runTest { + fun `updateAll - previous values cleared and new values updated`() = runTest { givenMediaPlaybackDaoContainsEntities() initRepository() diff --git a/app/src/test/java/com/duckduckgo/app/browser/serviceworker/BrowserServiceWorkerClientTest.kt b/app/src/test/java/com/duckduckgo/app/browser/serviceworker/BrowserServiceWorkerClientTest.kt index 12fa45d30078..9e7047cb3491 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/serviceworker/BrowserServiceWorkerClientTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/serviceworker/BrowserServiceWorkerClientTest.kt @@ -45,7 +45,7 @@ class BrowserServiceWorkerClientTest { } @Test - fun whenShouldInterceptRequestAndOriginHeaderExistThenSendItToInterceptor() = runTest { + fun `shouldInterceptRequest - origin header exists - send to interceptor`() = runTest { val webResourceRequest: WebResourceRequest = mock() whenever(webResourceRequest.requestHeaders).thenReturn(mapOf("Origin" to "example.com")) @@ -55,7 +55,7 @@ class BrowserServiceWorkerClientTest { } @Test - fun whenShouldInterceptRequestAndOriginHeaderDoesNotExistButRefererExistThenSendItToInterceptor() = runTest { + fun `shouldInterceptRequest - origin header does not exist but referer exists - send it to interceptor`() = runTest { val webResourceRequest: WebResourceRequest = mock() whenever(webResourceRequest.requestHeaders).thenReturn(mapOf("Referer" to "example.com")) @@ -65,7 +65,7 @@ class BrowserServiceWorkerClientTest { } @Test - fun whenShouldInterceptRequestAndNoOriginOrRefererHeadersExistThenSendNullToInterceptor() = runTest { + fun `shouldInterceptRequest - no origin or referer headers exist - send null to interceptor`() = runTest { val webResourceRequest: WebResourceRequest = mock() whenever(webResourceRequest.requestHeaders).thenReturn(mapOf()) diff --git a/app/src/test/java/com/duckduckgo/app/browser/state/BrowserApplicationStateInfoTest.kt b/app/src/test/java/com/duckduckgo/app/browser/state/BrowserApplicationStateInfoTest.kt index d0fde85ec935..caf54f6bb0cf 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/state/BrowserApplicationStateInfoTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/state/BrowserApplicationStateInfoTest.kt @@ -46,14 +46,14 @@ class BrowserApplicationStateInfoTest { } @Test - fun whenActivityCreatedThenNoop() { + fun `onActivityCreated - noop`() { browserApplicationStateInfo.onActivityCreated(activity, null) verifyNoInteractions(observer) } @Test - fun whenFirstActivityCreatedAndStartedThenNotifyFreshAppLaunch() { + fun `onActivityCreated - started - notify fresh app launch`() { browserApplicationStateInfo.onActivityCreated(activity, null) browserApplicationStateInfo.onActivityStarted(activity) @@ -62,7 +62,7 @@ class BrowserApplicationStateInfoTest { } @Test - fun whenAllActivitiesStopAndRestartThenNotifyAppOpen() { + fun `whenAllActivitiesStopAndRestartThenNotifyAppOpen - state - notify app open`() { browserApplicationStateInfo.onActivityCreated(activity, null) browserApplicationStateInfo.onActivityCreated(activity, null) @@ -82,7 +82,7 @@ class BrowserApplicationStateInfoTest { } @Test - fun whenAllActivitiesAreDestroyedAndRecreatedThenNotifyFreshAppLaunch() { + fun `whenAllActivitiesAreDestroyedAndRecreatedThenNotifyFreshAppLaunch - observer notified`() { browserApplicationStateInfo.onActivityCreated(activity, null) browserApplicationStateInfo.onActivityCreated(activity, null) @@ -106,7 +106,7 @@ class BrowserApplicationStateInfoTest { } @Test - fun whenAllActivitiesAreDestroyedByBackPressAndRecreatedThenDoNotNotifyFreshAppLaunch() { + fun `whenAllActivitiesAreDestroyedByBackPressAndRecreated - do not notify fresh app launch - observer on close`() { activity.destroyedByBackPress = true browserApplicationStateInfo.onActivityCreated(activity, null) @@ -132,7 +132,7 @@ class BrowserApplicationStateInfoTest { } @Test - fun whenAllActivitiesAreDestroyedByConfigChangeAndRecreatedThenDoNotNotifyFreshAppLaunch() { + fun `whenAllActivitiesAreDestroyedByConfigChangeAndRecreatedThenDoNotNotifyFreshAppLaunch - do not notify fresh app launch`() { activity.isConfigChange = true browserApplicationStateInfo.onActivityCreated(activity, null) diff --git a/app/src/test/java/com/duckduckgo/app/browser/urlextraction/UrlExtractionJavascriptInterfaceTest.kt b/app/src/test/java/com/duckduckgo/app/browser/urlextraction/UrlExtractionJavascriptInterfaceTest.kt index ed1ed34a3a43..adfa276f3050 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/urlextraction/UrlExtractionJavascriptInterfaceTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/urlextraction/UrlExtractionJavascriptInterfaceTest.kt @@ -23,7 +23,7 @@ import org.mockito.kotlin.verify class UrlExtractionJavascriptInterfaceTest { @Test - fun whenUrlExtractedThenInvokeCallbackWithUrl() { + fun `urlExtracted - invoke callback with url`() { val onUrlExtracted = mock<(extractedUrl: String?) -> Unit>() val urlExtractionInterface = UrlExtractionJavascriptInterface(onUrlExtracted) @@ -33,7 +33,7 @@ class UrlExtractionJavascriptInterfaceTest { } @Test - fun whenUrlIsUndefinedThenInvokeCallbackWithNull() { + fun `urlExtracted - undefined - invoke callback with null`() { val onUrlExtracted = mock<(extractedUrl: String?) -> Unit>() val urlExtractionInterface = UrlExtractionJavascriptInterface(onUrlExtracted) diff --git a/app/src/test/java/com/duckduckgo/app/browser/webshare/WebShareChooserTest.kt b/app/src/test/java/com/duckduckgo/app/browser/webshare/WebShareChooserTest.kt index 5b8af86d1c04..d53e9b079a93 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/webshare/WebShareChooserTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/webshare/WebShareChooserTest.kt @@ -18,7 +18,7 @@ class WebShareChooserTest { private val webShareChooser = WebShareChooser() @Test - fun whenTitleAndUrlAndTextEmptyThenParseCorrectData() { + fun `whenTitleAndUrlAndTextEmptyThenParseCorrectData - parse correct data`() { val data = JsCallbackData( params = JSONObject("""{"title":"Sample title","url":"https://example.com/", "text":""}"""), featureName = "featureName", @@ -37,7 +37,7 @@ class WebShareChooserTest { } @Test - fun whenTitleAndUrlAndTextNullThenParseCorrectData() { + fun `whenTitleAndUrlAndTextNullThenParseCorrectData - parse correct data`() { val data = JsCallbackData( params = JSONObject("""{"title":"Sample title","url":"https://example.com/"}"""), featureName = "featureName", @@ -56,7 +56,7 @@ class WebShareChooserTest { } @Test - fun whenTitleEmptyAndUrlThenParseCorrectData() { + fun `whenTitleEmptyAndUrlThenParseCorrectData - extras parsed correctly`() { val data = JsCallbackData( params = JSONObject("""{"title":"","url":"https://example.com/"}"""), featureName = "featureName", @@ -75,7 +75,7 @@ class WebShareChooserTest { } @Test - fun whenTitleAndUrlAndTextThenParseCorrectData() { + fun `whenTitleAndUrlAndTextThenParseCorrectData - parse correct data`() { val data = JsCallbackData( params = JSONObject("""{"title":"Sample title","url":"https://example.com/", "text":"Test"}"""), featureName = "featureName", @@ -94,7 +94,7 @@ class WebShareChooserTest { } @Test - fun whenTitleAndTextAndUrlEmptyThenParseCorrectData() { + fun `whenTitleAndTextAndUrlEmptyThenParseCorrectData - parse correct data`() { val data = JsCallbackData( params = JSONObject("""{"title":"Sample title","url":"", "text":"Test"}"""), featureName = "featureName", @@ -113,7 +113,7 @@ class WebShareChooserTest { } @Test - fun whenTitleAndTextAndUrlNullThenParseCorrectData() { + fun `whenTitleAndTextAndUrlNullThenParseCorrectData - parse correct data`() { val data = JsCallbackData( params = JSONObject("""{"title":"Sample title", "text":"Test"}"""), featureName = "featureName", @@ -132,7 +132,7 @@ class WebShareChooserTest { } @Test - fun whenParseResultIsOkAndDataNotInitializedThenReturnDataError() { + fun `parseResult - ok and data not initialized - return data error`() { val data = webShareChooser.parseResult(Activity.RESULT_OK, null) assertEquals(WebShareChooser.DATA_ERROR, data.params.toString()) @@ -142,7 +142,7 @@ class WebShareChooserTest { } @Test - fun whenParseResultIsOkThenReturnSuccess() { + fun `parseResult - ok - return success`() { val data = JsCallbackData( params = JSONObject("""{"title":"Sample title", "text":"Test"}"""), featureName = "featureName", @@ -160,7 +160,7 @@ class WebShareChooserTest { } @Test - fun whenParseResultIsCanceledThenReturnAbort() { + fun `parseResult - is canceled - return abort`() { val data = JsCallbackData( params = JSONObject("""{"title":"Sample title", "text":"Test"}"""), featureName = "featureName", @@ -178,7 +178,7 @@ class WebShareChooserTest { } @Test - fun whenParseResultIsOtherThenReturnDataError() { + fun `parseResult - is other - return data error`() { val data = JsCallbackData( params = JSONObject("""{"title":"Sample title", "text":"Test"}"""), featureName = "featureName", diff --git a/app/src/test/java/com/duckduckgo/app/cta/ui/CtaTest.kt b/app/src/test/java/com/duckduckgo/app/cta/ui/CtaTest.kt index 35f49ba9c451..233233853cd5 100644 --- a/app/src/test/java/com/duckduckgo/app/cta/ui/CtaTest.kt +++ b/app/src/test/java/com/duckduckgo/app/cta/ui/CtaTest.kt @@ -65,61 +65,61 @@ class CtaTest { } @Test - fun whenCtaIsSurveyReturnEmptyOkParameters() { + fun `pixelOkParameters - cta is survey return empty ok parameters`() { val testee = HomePanelCta.Survey(Survey("abc", "http://example.com", 1, Survey.Status.SCHEDULED)) assertTrue(testee.pixelOkParameters().isEmpty()) } @Test - fun whenCtaIsSurveyReturnEmptyCancelParameters() { + fun `pixelCancelParameters - cta is survey return empty - returns empty`() { val testee = HomePanelCta.Survey(Survey("abc", "http://example.com", 1, Survey.Status.SCHEDULED)) assertTrue(testee.pixelCancelParameters().isEmpty()) } @Test - fun whenCtaIsSurveyReturnEmptyShownParameters() { + fun `pixelShownParameters - cta is survey return empty shown parameters`() { val testee = HomePanelCta.Survey(Survey("abc", "http://example.com", 1, Survey.Status.SCHEDULED)) assertTrue(testee.pixelShownParameters().isEmpty()) } @Test - fun whenCtaIsAddWidgetAutoReturnEmptyOkParameters() { + fun `pixelOkParameters - auto return empty`() { val testee = HomePanelCta.AddWidgetAuto assertTrue(testee.pixelOkParameters().isEmpty()) } @Test - fun whenCtaIsAddWidgetAutoReturnEmptyCancelParameters() { + fun `pixelCancelParameters - auto return empty`() { val testee = HomePanelCta.AddWidgetAuto assertTrue(testee.pixelCancelParameters().isEmpty()) } @Test - fun whenCtaIsAddWidgetAutoReturnEmptyShownParameters() { + fun `pixelShownParameters - auto return empty - is empty`() { val testee = HomePanelCta.AddWidgetAuto assertTrue(testee.pixelShownParameters().isEmpty()) } @Test - fun whenCtaIsAddWidgetInstructionsReturnEmptyOkParameters() { + fun `pixelOkParameters - empty ok parameters`() { val testee = HomePanelCta.AddWidgetInstructions assertTrue(testee.pixelOkParameters().isEmpty()) } @Test - fun whenCtaIsAddWidgetInstructionsReturnEmptyCancelParameters() { + fun `pixelCancelParameters - add widget instructions return empty - empty`() { val testee = HomePanelCta.AddWidgetInstructions assertTrue(testee.pixelCancelParameters().isEmpty()) } @Test - fun whenCtaIsAddWidgetInstructionsReturnEmptyShownParameters() { + fun `pixelShownParameters - empty shown parameters`() { val testee = HomePanelCta.AddWidgetInstructions assertTrue(testee.pixelShownParameters().isEmpty()) } @Test - fun whenCtaIsBubbleTypeReturnCorrectCancelParameters() { + fun `pixelCancelParameters - cta is bubble type - correct cancel parameters`() { val testee = DaxBubbleCta.DaxIntroCta(mockOnboardingStore, mockAppInstallStore) val value = testee.pixelCancelParameters() @@ -129,7 +129,7 @@ class CtaTest { } @Test - fun whenCtaIsBubbleTypeReturnCorrectOkParameters() { + fun `pixelOkParameters - cta is bubble type - correct ok parameters`() { val testee = DaxBubbleCta.DaxIntroCta(mockOnboardingStore, mockAppInstallStore) val value = testee.pixelOkParameters() @@ -139,7 +139,7 @@ class CtaTest { } @Test - fun whenCtaIsBubbleTypeReturnCorrectShownParameters() { + fun `pixelShownParameters - cta is bubble type - correct shown parameters`() { whenever(mockOnboardingStore.onboardingDialogJourney).thenReturn(null) whenever(mockAppInstallStore.installTimestamp).thenReturn(System.currentTimeMillis()) @@ -153,7 +153,7 @@ class CtaTest { } @Test - fun whenAddCtaToHistoryThenReturnCorrectValue() { + fun `addCtaToHistory - return correct value`() { whenever(mockOnboardingStore.onboardingDialogJourney).thenReturn(null) whenever(mockAppInstallStore.installTimestamp).thenReturn(System.currentTimeMillis()) @@ -163,7 +163,7 @@ class CtaTest { } @Test - fun whenAddCtaToHistoryOnDay3ThenReturnCorrectValue() { + fun `addCtaToHistory - day 3 - returns correct value`() { whenever(mockOnboardingStore.onboardingDialogJourney).thenReturn(null) whenever(mockAppInstallStore.installTimestamp).thenReturn(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(3)) @@ -173,7 +173,7 @@ class CtaTest { } @Test - fun whenAddCtaToHistoryOnDay4ThenReturn3AsDayValue() { + fun `addCtaToHistory - day 4 - return 3 as day value`() { whenever(mockOnboardingStore.onboardingDialogJourney).thenReturn(null) whenever(mockAppInstallStore.installTimestamp).thenReturn(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(4)) @@ -183,7 +183,7 @@ class CtaTest { } @Test - fun whenAddCtaToHistoryContainsHistoryThenConcatenateNewValue() { + fun `addCtaToHistory - contains history - concatenate new value`() { val ctaHistory = "s:0-t:1" whenever(mockOnboardingStore.onboardingDialogJourney).thenReturn(ctaHistory) whenever(mockAppInstallStore.installTimestamp).thenReturn(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1)) @@ -196,7 +196,7 @@ class CtaTest { } @Test - fun whenCtaIsBubbleTypeThenConcatenateJourneyStoredValueInPixel() { + fun `pixelShownParameters - cta is bubble type - concatenate journey stored value in pixel`() { val existingJourney = "s:0-t:1" whenever(mockOnboardingStore.onboardingDialogJourney).thenReturn(existingJourney) whenever(mockAppInstallStore.installTimestamp).thenReturn(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1)) @@ -208,21 +208,21 @@ class CtaTest { } @Test - fun whenCanSendPixelAndCtaNotPartOfHistoryThenReturnTrue() { + fun `canSendPixel - onboarding dialog journey s·0 - returns true`() { whenever(mockOnboardingStore.onboardingDialogJourney).thenReturn("s:0") val testee = DaxBubbleCta.DaxEndCta(mockOnboardingStore, mockAppInstallStore) assertTrue(testee.canSendShownPixel()) } @Test - fun whenCanSendPixelAndCtaNotPartOfHistoryButIsASubstringThenReturnTrue() { + fun `canSend - onboarding dialog journey substring - returns true`() { whenever(mockOnboardingStore.onboardingDialogJourney).thenReturn("s:0-te:0") val testee = DaxBubbleCta.DaxEndCta(mockOnboardingStore, mockAppInstallStore) assertTrue(testee.canSendShownPixel()) } @Test - fun whenCanSendPixelAndCtaIsPartOfHistoryThenReturnFalse() { + fun `canSendShownPixel - onboarding dialog journey - returns false`() { whenever(mockOnboardingStore.onboardingDialogJourney).thenReturn("i:0-e:0-s:0") val testee = DaxBubbleCta.DaxEndCta(mockOnboardingStore, mockAppInstallStore) @@ -230,7 +230,7 @@ class CtaTest { } @Test - fun whenCtaIsDialogTypeReturnCorrectCancelParameters() { + fun `pixelCancelParameters - cta is dialog type - correct cancel parameters`() { val testee = DaxDialogCta.DaxSerpCta(mockOnboardingStore, mockAppInstallStore) val value = testee.pixelCancelParameters() @@ -240,7 +240,7 @@ class CtaTest { } @Test - fun whenCtaIsDialogTypeReturnCorrectOkParameters() { + fun `pixelOkParameters - cta is dialog type - correct ok parameters`() { val testee = DaxDialogCta.DaxSerpCta(mockOnboardingStore, mockAppInstallStore) val value = testee.pixelOkParameters() @@ -250,7 +250,7 @@ class CtaTest { } @Test - fun whenCtaIsDialogTypeReturnCorrectShownParameters() { + fun `pixelShownParameters - cta is dialog type - correct shown parameters`() { whenever(mockOnboardingStore.onboardingDialogJourney).thenReturn(null) whenever(mockAppInstallStore.installTimestamp).thenReturn(System.currentTimeMillis()) val testee = DaxDialogCta.DaxSerpCta(mockOnboardingStore, mockAppInstallStore) @@ -263,7 +263,7 @@ class CtaTest { } @Test - fun whenCtaIsDialogTypeThenConcatenateJourneyStoredValueInPixel() { + fun `pixelShownParameters - cta is dialog type - concatenates journey stored value in pixel`() { val existingJourney = "s:0-t:1" whenever(mockOnboardingStore.onboardingDialogJourney).thenReturn(existingJourney) whenever(mockAppInstallStore.installTimestamp).thenReturn(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1)) @@ -275,7 +275,7 @@ class CtaTest { } @Test - fun whenMoreThanTwoTrackersBlockedReturnFirstTwoWithMultipleString() { + fun `getDaxText - more than two trackers blocked - first two with multiple string`() { val trackers = listOf( TestingEntity("Facebook", "Facebook", 9.0), TestingEntity("Other", "Other", 9.0), @@ -289,7 +289,7 @@ class CtaTest { } @Test - fun whenTwoTrackersBlockedReturnThemWithZeroString() { + fun `getDaxText - two trackers blocked - with zero string`() { val trackers = listOf( TestingEntity("Facebook", "Facebook", 9.0), TestingEntity("Other", "Other", 9.0), @@ -302,7 +302,7 @@ class CtaTest { } @Test - fun whenTrackersBlockedReturnThemSortingByPrevalence() { + fun `getDaxText - trackers blocked - returns them sorting by prevalence`() { val trackers = listOf( TrackingEvent( documentUrl = "facebook.com", @@ -338,7 +338,7 @@ class CtaTest { } @Test - fun whenTrackersBlockedReturnOnlyTrackersWithDisplayName() { + fun `getDaxText - trackers blocked - only display name`() { val trackers = listOf( TrackingEvent( documentUrl = "facebook.com", @@ -373,7 +373,7 @@ class CtaTest { } @Test - fun whenTrackersBlockedReturnOnlyTrackersBlocked() { + fun `getDaxText - trackers blocked - only trackers blocked`() { val trackers = listOf( TrackingEvent( documentUrl = "facebook.com", @@ -408,7 +408,7 @@ class CtaTest { } @Test - fun whenMultipleTrackersFromSameNetworkBlockedReturnOnlyOneWithZeroString() { + fun `getDaxText - multiple trackers from same network blocked - returns one with zero string`() { val trackers = listOf( TestingEntity("Facebook", "Facebook", 9.0), TestingEntity("Facebook", "Facebook", 9.0), @@ -422,7 +422,7 @@ class CtaTest { } @Test - fun whenTryClearDataCtaShownThenConcatenateJourneyStoredValueInPixel() { + fun `pixelShown - try clear data cta shown - concatenate journey stored value in pixel`() { val existingJourney = "s:0-t:1" whenever(mockOnboardingStore.onboardingDialogJourney).thenReturn(existingJourney) whenever(mockAppInstallStore.installTimestamp).thenReturn(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1)) diff --git a/app/src/test/java/com/duckduckgo/app/downloads/DownloadsViewModelTest.kt b/app/src/test/java/com/duckduckgo/app/downloads/DownloadsViewModelTest.kt index b3892a74851e..137e16511cc7 100644 --- a/app/src/test/java/com/duckduckgo/app/downloads/DownloadsViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/downloads/DownloadsViewModelTest.kt @@ -72,7 +72,7 @@ class DownloadsViewModelTest { } @Test - fun whenNoDownloadsAndVisibilityChangedCalledWithValueFalseThenViewStateEmittedWithEmptyItem() = runTest { + fun `onItemVisibilityChanged - view state emitted with empty item`() = runTest { val visible = false val list = emptyList() whenever(mockDownloadsRepository.getDownloadsAsFlow()).thenReturn(flowOf(list)) @@ -86,7 +86,7 @@ class DownloadsViewModelTest { } @Test - fun whenNoDownloadsAndVisibilityChangedCalledWithValueTrueThenViewStateEmittedWithNotifyMeAndEmptyItems() = runTest { + fun `onItemVisibilityChanged - view state emitted with notify me and empty items`() = runTest { val visible = true val list = emptyList() whenever(mockDownloadsRepository.getDownloadsAsFlow()).thenReturn(flowOf(list)) @@ -101,7 +101,7 @@ class DownloadsViewModelTest { } @Test - fun whenOneDownloadAndVisibilityChangedCalledWithValueFalseThenViewStateEmittedWithHeaderAndOneItem() = runTest { + fun `onItemVisibilityChanged - value false - view state emitted with header and one item`() = runTest { val visible = false val list = listOf(oneItem()) whenever(mockDownloadsRepository.getDownloadsAsFlow()).thenReturn(flowOf(list)) @@ -117,7 +117,7 @@ class DownloadsViewModelTest { } @Test - fun whenOneDownloadAndVisibilityChangedCalledWithValueTrueThenViewStateEmittedWithNotifyMeAndHeaderAndOneItem() = runTest { + fun `onItemVisibilityChanged - value true - view state emitted with notify me and header and one item`() = runTest { val visible = true val list = listOf(oneItem()) whenever(mockDownloadsRepository.getDownloadsAsFlow()).thenReturn(flowOf(list)) @@ -134,7 +134,7 @@ class DownloadsViewModelTest { } @Test - fun whenMultipleDownloadsAndVisibilityChangedCalledWithValueFalseThenViewStateEmittedWithMultipleItemsAndHeaders() = runTest { + fun `onItemVisibilityChanged - multiple downloads and visibility changed - view state emitted with multiple items and headers`() = runTest { val visible = false val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss") val today = LocalDateTime.parse(TODAY, formatter) @@ -198,7 +198,7 @@ class DownloadsViewModelTest { } @Test - fun whenDeleteAllCalledThenRepositoryDeleteAllCalledAndMessageCommandSent() = runTest { + fun `deleteAll - repository delete all called and message command sent`() = runTest { val itemsToDelete = listOf(oneItem()) whenever(mockDownloadsRepository.getDownloads()).thenReturn(itemsToDelete) @@ -214,7 +214,7 @@ class DownloadsViewModelTest { } @Test - fun whenDeleteCalledThenRepositoryDeleteCalledAndMessageCommandSent() = runTest { + fun `delete - repository delete called and message command sent`() = runTest { val item = oneItem() testee.delete(item) @@ -229,7 +229,7 @@ class DownloadsViewModelTest { } @Test - fun whenInsertCalledThenRepositoryInsertAllCalled() = runTest { + fun `insert - repository insert all called`() = runTest { val firstItem = oneItem() val secondItem = otherItem() @@ -239,7 +239,7 @@ class DownloadsViewModelTest { } @Test - fun whenOnQueryTextChangeThenViewStateEmittedWithTwoFilteredItems() = runTest { + fun `onQueryTextChange - view state emitted with two filtered items`() = runTest { val list = listOf(oneItem(), otherItem()) whenever(mockDownloadsRepository.getDownloadsAsFlow()).thenReturn(flowOf(list)) testee.onItemVisibilityChanged(false) @@ -257,7 +257,7 @@ class DownloadsViewModelTest { } @Test - fun whenOnQueryTextChangeThenViewStateEmittedWithZeroFilteredItems() = runTest { + fun `onQueryTextChange - view state emitted with zero filtered items`() = runTest { val list = listOf(oneItem(), otherItem()) whenever(mockDownloadsRepository.getDownloadsAsFlow()).thenReturn(flowOf(list)) testee.onItemVisibilityChanged(false) @@ -273,7 +273,7 @@ class DownloadsViewModelTest { } @Test - fun whenItemClickedThenOpenFileCommandSent() = runTest { + fun `onItemClicked - commands sent - open file command`() = runTest { val item = oneItem() testee.onItemClicked(item) @@ -287,7 +287,7 @@ class DownloadsViewModelTest { } @Test - fun whenItemShareClickedThenShareFileCommandSent() = runTest { + fun `onShareItemClicked - share file command sent`() = runTest { val item = oneItem() testee.onShareItemClicked(item) @@ -301,7 +301,7 @@ class DownloadsViewModelTest { } @Test - fun whenDeleteItemClickedThenItemDeletedAndMessageCommandSent() = runTest { + fun `onDeleteItemClicked - item deleted and message command sent`() = runTest { val item = oneItem() testee.onDeleteItemClicked(item) @@ -320,7 +320,7 @@ class DownloadsViewModelTest { } @Test - fun whenCancelItemClickedThenItemDeletedAndCancelDownloadCommandSent() = runTest { + fun `onCancelItemClicked - item deleted and cancel download command sent`() = runTest { val item = oneItem() testee.onCancelItemClicked(item) @@ -335,7 +335,7 @@ class DownloadsViewModelTest { } @Test - fun whenRemoveFromDownloadManagerThenRemoveIt() = runTest { + fun `removeFromDownloadManager - remove from downloads repository`() = runTest { val downloadId = 1L testee.removeFromDownloadManager(downloadId) diff --git a/app/src/test/java/com/duckduckgo/app/email/AppEmailManagerTest.kt b/app/src/test/java/com/duckduckgo/app/email/AppEmailManagerTest.kt index 2e6ddbd71098..423960368eb9 100644 --- a/app/src/test/java/com/duckduckgo/app/email/AppEmailManagerTest.kt +++ b/app/src/test/java/com/duckduckgo/app/email/AppEmailManagerTest.kt @@ -75,7 +75,7 @@ class AppEmailManagerTest { } @Test - fun whenFetchAliasFromServiceThenStoreAliasAddingDuckDomain() = runTest { + fun `getAlias - store alias adding duck domain`() = runTest { mockEmailDataStore.emailToken = "token" whenever(mockEmailService.newAlias(any())).thenReturn(EmailAlias("test")) testee.getAlias() @@ -84,7 +84,7 @@ class AppEmailManagerTest { } @Test - fun whenFetchAliasFromServiceAndTokenDoesNotExistThenDoNothing() = runTest { + fun `getAlias - token does not exist - do nothing`() = runTest { mockEmailDataStore.emailToken = null testee.getAlias() @@ -92,7 +92,7 @@ class AppEmailManagerTest { } @Test - fun whenFetchAliasFromServiceAndAddressIsBlankThenStoreNull() = runTest { + fun `getAlias - address is blank - store null`() = runTest { mockEmailDataStore.emailToken = "token" whenever(mockEmailService.newAlias(any())).thenReturn(EmailAlias("")) testee.getAlias() @@ -101,26 +101,26 @@ class AppEmailManagerTest { } @Test - fun whenGetAliasThenReturnNextAlias() = runTest { + fun `getAlias - next alias exists - "alias"`() = runTest { givenNextAliasExists() assertEquals("alias", testee.getAlias()) } @Test - fun whenGetAliasIfNextAliasDoesNotExistThenReturnNull() { + fun `getAlias - no next alias exists - null`() { assertNull(testee.getAlias()) } @Test - fun whenGetAliasThenClearNextAlias() { + fun `getAlias - clear next alias`() { testee.getAlias() assertNull(mockEmailDataStore.nextAlias) } @Test - fun whenIsSignedInAndTokenDoesNotExistThenReturnFalse() { + fun `isSignedIn - is signed in and token does not exist - false`() { mockEmailDataStore.emailUsername = "username" mockEmailDataStore.nextAlias = "alias" @@ -128,7 +128,7 @@ class AppEmailManagerTest { } @Test - fun whenIsSignedInAndUsernameDoesNotExistThenReturnFalse() { + fun `isSignedIn - is signed in and username does not exist - returns false`() { mockEmailDataStore.emailToken = "token" mockEmailDataStore.nextAlias = "alias" @@ -136,7 +136,7 @@ class AppEmailManagerTest { } @Test - fun whenIsSignedInAndTokenAndUsernameExistThenReturnTrue() { + fun `isSignedIn - signed in and token and username exist - true`() { mockEmailDataStore.emailToken = "token" mockEmailDataStore.emailUsername = "username" @@ -144,7 +144,7 @@ class AppEmailManagerTest { } @Test - fun whenStoreCredentialsThenGenerateNewAlias() = runTest { + fun `storeCredentials - store credentials then generate new alias`() = runTest { mockEmailDataStore.emailToken = "token" whenever(mockEmailService.newAlias(any())).thenReturn(EmailAlias("")) @@ -154,7 +154,7 @@ class AppEmailManagerTest { } @Test - fun whenStoreCredentialsThenNotifySyncableSetting() = runTest { + fun `storeCredentials - store credentials then notify syncable setting`() = runTest { mockEmailDataStore.emailToken = "token" whenever(mockEmailService.newAlias(any())).thenReturn(EmailAlias("")) @@ -164,7 +164,7 @@ class AppEmailManagerTest { } @Test - fun whenStoreCredentialsThenSendPixel() = runTest { + fun `storeCredentials - email store credentials then send pixel`() = runTest { mockEmailDataStore.emailToken = "token" whenever(mockEmailService.newAlias(any())).thenReturn(EmailAlias("")) @@ -174,7 +174,7 @@ class AppEmailManagerTest { } @Test - fun whenStoreCredentialsThenCredentialsAreStoredInDataStore() { + fun `storeCredentials - data store updated`() { testee.storeCredentials("token", "username", "cohort") assertEquals("username", mockEmailDataStore.emailUsername) @@ -183,21 +183,21 @@ class AppEmailManagerTest { } @Test - fun whenStoreCredentialsIfCredentialsWereCorrectlyStoredThenIsSignedInChannelSendsTrue() = runTest { + fun `storeCredentials - is signed in channel sends true`() = runTest { testee.storeCredentials("token", "username", "cohort") assertTrue(testee.signedInFlow().first()) } @Test - fun whenStoreCredentialsIfCredentialsAreBlankThenIsSignedInChannelSendsFalse() = runTest { + fun `storeCredentials - credentials are blank - is signed in channel sends false`() = runTest { testee.storeCredentials("", "", "cohort") assertFalse(testee.signedInFlow().first()) } @Test - fun whenSignedOutThenClearEmailDataAndAliasIsNull() { + fun `signOut - clear email data and alias is null`() { testee.signOut() assertNull(mockEmailDataStore.emailUsername) @@ -208,81 +208,81 @@ class AppEmailManagerTest { } @Test - fun whenSignedOutThenNotifySyncableSetting() { + fun `signOut - notify syncable setting`() { testee.signOut() verify(mockSyncSettingsListener).onSettingChanged(emailSyncableSetting.key) } @Test - fun whenSignedOutThenSendPixel() { + fun `signOut - send pixel`() { testee.signOut() verify(mockPixel).fire(EMAIL_DISABLED) } @Test - fun whenSignedOutThenIsSignedInChannelSendsFalse() = runTest { + fun `signOut - is signed in channel sends false`() = runTest { testee.signOut() assertFalse(testee.signedInFlow().first()) } @Test - fun whenGetEmailAddressThenDuckEmailDomainIsAppended() { + fun `getEmailAddress - email domain appended - username$DUCK_EMAIL_DOMAIN`() { mockEmailDataStore.emailUsername = "username" assertEquals("username$DUCK_EMAIL_DOMAIN", testee.getEmailAddress()) } @Test - fun whenGetCohortThenReturnCohort() { + fun `getCohort - cohort returned`() { mockEmailDataStore.cohort = "cohort" assertEquals("cohort", testee.getCohort()) } @Test - fun whenGetCohortIfCohortIsNullThenReturnUnknown() { + fun `getCohort - cohort is null - return unknown`() { mockEmailDataStore.cohort = null assertEquals(UNKNOWN_COHORT, testee.getCohort()) } @Test - fun whenGetCohortIfCohortIsEmtpyThenReturnUnknown() { + fun `getCohort - cohort is empty - unknown`() { mockEmailDataStore.cohort = "" assertEquals(UNKNOWN_COHORT, testee.getCohort()) } @Test - fun whenIsEmailFeatureSupportedAndEncryptionCanBeUsedThenReturnTrue() { + fun `isEmailFeatureSupported - email feature supported and encryption can be used - returns true`() { (mockEmailDataStore as FakeEmailDataStore).canUseEncryption = true assertTrue(testee.isEmailFeatureSupported()) } @Test - fun whenGetLastUsedDateIfNullThenReturnEmpty() { + fun `getLastUsedDate - null - empty`() { assertEquals("", testee.getLastUsedDate()) } @Test - fun whenGetLastUsedDateIfNotNullThenReturnValueFromStore() { + fun `getLastUsedDate - last used date not null - return value from store`() { mockEmailDataStore.lastUsedDate = "2021-01-01" assertEquals("2021-01-01", testee.getLastUsedDate()) } @Test - fun whenIsEmailFeatureSupportedAndEncryptionCannotBeUsedThenReturnFalse() { + fun `isEmailFeatureSupported - email data store cannot use encryption - returns false`() { (mockEmailDataStore as FakeEmailDataStore).canUseEncryption = false assertFalse(testee.isEmailFeatureSupported()) } @Test - fun whenGetUserDataThenDataReceivedCorrectly() { + fun `getUserData - data received correctly`() { val expected = JSONObject().apply { put(AppEmailManager.TOKEN, "token") put(AppEmailManager.USERNAME, "user") @@ -297,7 +297,7 @@ class AppEmailManagerTest { } @Test - fun whenSyncableSettingNotifiesChangeThenRefreshEmailState() = runTest { + fun `syncableSetting notifies change - refresh email state`() = runTest { testee.signedInFlow().test { assertFalse(awaitItem()) emailSyncableSetting.save("{\"username\":\"email\",\"personal_access_token\":\"token\"}") diff --git a/app/src/test/java/com/duckduckgo/app/email/EmailJavascriptInterfaceTest.kt b/app/src/test/java/com/duckduckgo/app/email/EmailJavascriptInterfaceTest.kt index d5ca5b1ea56c..34aaf284a76f 100644 --- a/app/src/test/java/com/duckduckgo/app/email/EmailJavascriptInterfaceTest.kt +++ b/app/src/test/java/com/duckduckgo/app/email/EmailJavascriptInterfaceTest.kt @@ -66,7 +66,7 @@ class EmailJavascriptInterfaceTest { } @Test - fun whenIsSignedInAndUrlIsDuckDuckGoEmailThenIsSignedInCalled() { + fun `isSignedIn - is signed in and url is duckduckgo email - is signed in called`() { whenever(mockWebView.url).thenReturn(DUCKDUCKGO_EMAIL_URL) testee.isSignedIn() @@ -75,7 +75,7 @@ class EmailJavascriptInterfaceTest { } @Test - fun whenIsSignedInAndUrlIsNotDuckDuckGoEmailThenIsSignedInNotCalled() { + fun `isSignedIn - is signed in and url not duckduckgo email - is signed in not called`() { whenever(mockWebView.url).thenReturn(NON_EMAIL_URL) testee.isSignedIn() @@ -84,7 +84,7 @@ class EmailJavascriptInterfaceTest { } @Test - fun whenStoreCredentialsAndUrlIsDuckDuckGoEmailThenStoreCredentialsCalledWithCorrectParameters() { + fun `storeCredentials - store credentials called with correct parameters`() { whenever(mockWebView.url).thenReturn(DUCKDUCKGO_EMAIL_URL) testee.storeCredentials("token", "username", "cohort") @@ -93,7 +93,7 @@ class EmailJavascriptInterfaceTest { } @Test - fun whenStoreCredentialsAndUrlIsNotDuckDuckGoEmailThenStoreCredentialsNotCalled() { + fun `storeCredentials - url is not duckduckgo email - store credentials not called`() { whenever(mockWebView.url).thenReturn(NON_EMAIL_URL) testee.storeCredentials("token", "username", "cohort") @@ -102,7 +102,7 @@ class EmailJavascriptInterfaceTest { } @Test - fun whenGetUserDataAndUrlIsDuckDuckGoEmailThenGetUserDataCalled() { + fun `getUserData - url is duckduckgo email - get user data called`() { whenever(mockWebView.url).thenReturn(DUCKDUCKGO_EMAIL_URL) testee.getUserData() @@ -111,7 +111,7 @@ class EmailJavascriptInterfaceTest { } @Test - fun whenGetUserDataAndUrlIsNotDuckDuckGoEmailThenGetUserDataIsNotCalled() { + fun `getUserData - url is not duckduckgo email - get user data is not called`() { whenever(mockWebView.url).thenReturn(NON_EMAIL_URL) testee.getUserData() @@ -120,7 +120,7 @@ class EmailJavascriptInterfaceTest { } @Test - fun whenShowTooltipThenLambdaCalled() { + fun `showTooltip - lambda called`() { whenever(mockWebView.url).thenReturn(NON_EMAIL_URL) testee.showTooltip() @@ -129,7 +129,7 @@ class EmailJavascriptInterfaceTest { } @Test - fun whenShowTooltipAndFeatureDisabledThenLambdaNotCalled() { + fun `showTooltip - feature disabled - lambda not called`() { whenever(mockWebView.url).thenReturn(NON_EMAIL_URL) autofillFeature.self().setEnabled(Toggle.State(enable = false)) @@ -139,7 +139,7 @@ class EmailJavascriptInterfaceTest { } @Test - fun whenShowTooltipAndUrlIsAnExceptionThenLambdaNotCalled() { + fun `showTooltip - url is an exception - lambda not called`() { whenever(mockWebView.url).thenReturn(NON_EMAIL_URL) whenever(mockAutofill.isAnException(any())).thenReturn(true) @@ -149,14 +149,14 @@ class EmailJavascriptInterfaceTest { } @Test - fun whenGetDeviceCapabilitiesAndUrlIsDuckDuckGoEmailThenReturnNonEmptyString() { + fun `getDeviceCapabilities - url is duckduckgo email - return non empty string`() { whenever(mockWebView.url).thenReturn(DUCKDUCKGO_EMAIL_URL) assert(testee.getDeviceCapabilities().isNotBlank()) } @Test - fun whenGetDeviceCapabilitiesAndUrlIsNotDuckDuckGoEmailThenReturnEmptyString() { + fun `getDeviceCapabilities - url is not duckduckgo email - empty string`() { whenever(mockWebView.url).thenReturn(NON_EMAIL_URL) assert(testee.getDeviceCapabilities().isBlank()) diff --git a/app/src/test/java/com/duckduckgo/app/email/EmailSyncTest.kt b/app/src/test/java/com/duckduckgo/app/email/EmailSyncTest.kt index 366e1f493a6c..f84ec2d6c3c5 100644 --- a/app/src/test/java/com/duckduckgo/app/email/EmailSyncTest.kt +++ b/app/src/test/java/com/duckduckgo/app/email/EmailSyncTest.kt @@ -21,7 +21,7 @@ class EmailSyncTest { private val testee = EmailSync(emailDataStoreMock, syncSettingsListenerMock, pixelMock) @Test - fun whenUserSignedInThenReturnAccountInfo() { + fun `getValue - user signed in - account info returned`() { whenever(emailDataStoreMock.emailUsername).thenReturn("username") whenever(emailDataStoreMock.emailToken).thenReturn("token") @@ -34,7 +34,7 @@ class EmailSyncTest { } @Test - fun whenUserSignedOutThenReturnNull() { + fun `getValue - user signed out - null`() { whenever(emailDataStoreMock.emailUsername).thenReturn(null) whenever(emailDataStoreMock.emailToken).thenReturn(null) @@ -44,7 +44,7 @@ class EmailSyncTest { } @Test - fun whenSaveValueThenStoreCredentials() { + fun `save - store credentials - email and token stored`() { testee.save("{\"username\":\"email\",\"personal_access_token\":\"token\"}") verify(emailDataStoreMock).emailUsername = "email" @@ -52,7 +52,7 @@ class EmailSyncTest { } @Test - fun whenSaveNullThenLogoutUser() { + fun `save - null - logout user`() { testee.save(null) verify(emailDataStoreMock).emailUsername = "" @@ -60,7 +60,7 @@ class EmailSyncTest { } @Test - fun whenDeduplicateRemoteAddressWithSameLocalAddressThenDoNothing() { + fun `deduplicate - same local address - do nothing`() { whenever(emailDataStoreMock.emailUsername).thenReturn("username") whenever(emailDataStoreMock.emailToken).thenReturn("token") @@ -71,7 +71,7 @@ class EmailSyncTest { } @Test - fun whenDeduplicateRemoteAddressWithDifferentLocalAddressThenRemoteWins() { + fun `deduplicate - different local address - remote wins`() { whenever(emailDataStoreMock.emailUsername).thenReturn("username2") whenever(emailDataStoreMock.emailToken).thenReturn("token2") @@ -82,7 +82,7 @@ class EmailSyncTest { } @Test - fun whenDeduplicateRemoteAddressWithDifferentLocalAddressThenPixelEvent() { + fun `deduplicate - different local address - pixel event`() { whenever(emailDataStoreMock.emailUsername).thenReturn("username2") whenever(emailDataStoreMock.emailToken).thenReturn("token2") @@ -92,7 +92,7 @@ class EmailSyncTest { } @Test - fun whenDeduplicateRemoteAddressWithNoLocalAccountThenStoreRemote() { + fun `deduplicate - no local account - store remote`() { whenever(emailDataStoreMock.emailUsername).thenReturn(null) whenever(emailDataStoreMock.emailToken).thenReturn(null) @@ -103,7 +103,7 @@ class EmailSyncTest { } @Test - fun whenDeduplicateNullAddresThenDoNothing() { + fun `deduplicate - null address - do nothing`() { whenever(emailDataStoreMock.emailUsername).thenReturn("username") whenever(emailDataStoreMock.emailToken).thenReturn("token") diff --git a/app/src/test/java/com/duckduckgo/app/feedback/BrokenSiteViewModelTest.kt b/app/src/test/java/com/duckduckgo/app/feedback/BrokenSiteViewModelTest.kt index a34603af2838..a1f526237a86 100644 --- a/app/src/test/java/com/duckduckgo/app/feedback/BrokenSiteViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/feedback/BrokenSiteViewModelTest.kt @@ -122,18 +122,18 @@ class BrokenSiteViewModelTest { } @Test - fun whenInitializedThenCanSubmit() { + fun `initialized - view state submit allowed`() { assertTrue(viewState.submitAllowed) } @Test - fun whenNoCategorySelectedThenCanSubmit() { + fun `selectAndAcceptCategory - no category selected - can submit`() { selectAndAcceptCategory(-1) assertTrue(viewState.submitAllowed) } @Test - fun whenCategorySelectedButNotChangedThenReturnOldCategory() { + fun `onCategoryIndexChanged - category not changed - return old category`() { testee.onCategoryIndexChanged(0) testee.onCategoryAccepted() testee.onCategoryIndexChanged(1) @@ -141,13 +141,13 @@ class BrokenSiteViewModelTest { } @Test - fun whenCategoryAcceptedAndIncorrectIndexThenReturnNullCategory() { + fun `selectAndAcceptCategory - category accepted and incorrect index - return null category`() { selectAndAcceptCategory(-1) assertNull(viewState.categorySelected) } @Test - fun whenCategoryAcceptedAndCorrectIndexThenReturnCategory() { + fun `selectAndAcceptCategory - category accepted and correct index - return category`() { val indexSelected = 0 selectAndAcceptCategory(indexSelected) @@ -156,7 +156,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenCanSubmitBrokenSiteAndUrlNotNullAndSubmitPressedThenReportAndPixelSubmitted() { + fun `whenCanSubmitBrokenSiteAndUrlNotNullAndSubmitPressedThenReportAndPixelSubmitted - set initial broken site and submit pressed - report and pixel submitted`() { testee.setInitialBrokenSite( url = url, blockedTrackers = "", @@ -199,7 +199,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenCanSubmitBrokenSiteAndUrlIsEmptyAndSubmitPressedThenDoNotSubmit() { + fun `setInitialBrokenSite - do not submit - does not fire pixel and send feedback`() { val nullUrl = "" testee.setInitialBrokenSite( url = nullUrl, @@ -243,7 +243,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenCanSubmitBrokenSiteAndLastAmpLinkIsNullAndSubmitPressedThenReportUrlAndPixelSubmitted() { + fun `setInitialBrokenSite - reportUrl and pixel submitted`() { whenever(mockAmpLinks.lastAmpLinkInfo).thenReturn(null) testee.setInitialBrokenSite( @@ -288,7 +288,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenCanSubmitBrokenSiteAndUrlHasAssociatedAmpLinkAndSubmitPressedThenAmpLinkReportedAndPixelSubmitted() { + fun `whenCanSubmitBrokenSiteAndUrlHasAssociatedAmpLinkAndSubmitPressed - amp link reported and pixel submitted`() { whenever(mockAmpLinks.lastAmpLinkInfo).thenReturn(AmpLinkInfo(trackingUrl, url)) testee.setInitialBrokenSite( @@ -333,7 +333,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenCanSubmitBrokenSiteAndUrlNotNullAndSubmitPressedThenReportAndPixelSubmittedWithParams() { + fun `setInitialBrokenSite - can submit broken site and url not null and submit pressed - report and pixel submitted with params`() { whenever(mockAmpLinks.lastAmpLinkInfo).thenReturn(AmpLinkInfo(trackingUrl, url)) testee.setInitialBrokenSite( @@ -362,7 +362,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenIsDesktopModeTrueThenSendDesktopParameter() { + fun `setInitialBrokenSite - isDesktopMode true - send desktop parameter`() { testee.setInitialBrokenSite( url = url, blockedTrackers = "", @@ -384,7 +384,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenDesktopModeIsFalseThenSendMobileParameter() { + fun `whenIsDesktopModeFalseThenSendMobileParameter - send mobile parameter`() { testee.setInitialBrokenSite( url = url, blockedTrackers = "", @@ -406,7 +406,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenGetBrokenSiteThenReturnCorrectCategory() { + fun `whenGetBrokenSiteThenReturnCorrectCategory - set initial broken site - correct category`() { val url = "http://m.example.com" val categoryIndex = 0 testee.setInitialBrokenSite( @@ -431,7 +431,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenCancelSelectionThenAssignOldIndexValue() { + fun `onCategorySelectionCancelled - assign old index value`() { testee.setInitialBrokenSite( url = "", blockedTrackers = "", @@ -454,7 +454,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenCancelSelectionAndNoPreviousValueThenAssignMinusOne() { + fun `onCategorySelectionCancelled - no previous value - assign minus one`() { testee.setInitialBrokenSite( url = "", blockedTrackers = "", @@ -476,7 +476,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenCategoryLoginsThenUseLoginSite() { + fun `whenCategoryLoginsThenUseLoginSite - set initial broken site - submit pressed`() { val categoryIndex = testee.shuffledCategories.indexOfFirst { it.key == BrokenSiteCategory.LOGIN_CATEGORY_KEY } testee.setInitialBrokenSite( @@ -521,7 +521,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenCategoryIsNotLoginsThenDoNotUseLoginSite() { + fun `whenCategoryIsNotLoginsThenDoNotUseLoginSite - do not use login site`() { val categoryIndex = testee.shuffledCategories.indexOfFirst { it.key == BrokenSiteCategory.COMMENTS_CATEGORY_KEY } testee.setInitialBrokenSite( @@ -566,7 +566,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenSiteProtectionsToggledAllowlistIsUpdated() = runTest { + fun `onProtectionsToggled - allowlist updated`() = runTest { val url = "https://stuff.example.com" testee.setInitialBrokenSite( @@ -598,7 +598,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenContentBlockingIsDisabledThenSiteProtectionsAreDisabled() { + fun `whenContentBlockingIsDisabledThenSiteProtectionsAreDisabled - site protections disabled`() { whenever(mockFeatureToggle.isFeatureEnabled(PrivacyFeatureName.ContentBlockingFeatureName.value)) .thenReturn(false) @@ -621,7 +621,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenUrlIsInUnprotectedTemporaryExceptionsThenSiteProtectionsAreDisabled() { + fun `whenUrlIsInUnprotectedTemporaryExceptionsThenSiteProtectionsAreDisabled - view state disabled by remote config`() { whenever(mockFeatureToggle.isFeatureEnabled(PrivacyFeatureName.ContentBlockingFeatureName.value)) .thenReturn(true) @@ -647,7 +647,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenUrlIsInContentBlockingExceptionsThenSiteProtectionsAreDisabled() { + fun `whenUrlIsInContentBlockingExceptionsThenSiteProtectionsAreDisabled - view state protections disabled`() { whenever(mockFeatureToggle.isFeatureEnabled(PrivacyFeatureName.ContentBlockingFeatureName.value)) .thenReturn(true) @@ -673,7 +673,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenUrlIsInUserAllowlistThenSiteProtectionsAreDisabled() { + fun `whenUrlIsInUserAllowlistThenSiteProtectionsAreDisabled - view state protections disabled`() { whenever(mockFeatureToggle.isFeatureEnabled(PrivacyFeatureName.ContentBlockingFeatureName.value)) .thenReturn(true) @@ -698,7 +698,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenUrlIsNotInUserAllowlistThenSiteProtectionsAreEnabled() { + fun `whenUrlIsNotInUserAllowlistThenSiteProtectionsAreEnabled - view state enabled`() { whenever(mockFeatureToggle.isFeatureEnabled(PrivacyFeatureName.ContentBlockingFeatureName.value)) .thenReturn(true) @@ -723,7 +723,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenUrlIsAddedToUserAllowlistThenPixelIsFired() = runTest { + fun `setInitialBrokenSite - pixel fired`() = runTest { testee.setInitialBrokenSite( url = url, blockedTrackers = "", @@ -765,7 +765,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenProtectionsAreToggledThenPrivacyProtectionsPopupListenerIsInvoked() = runTest { + fun `onProtectionsToggled - privacy protections popup listener invoked`() = runTest { testee.setInitialBrokenSite( url = url, blockedTrackers = "", @@ -788,7 +788,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenPrivacyProtectionsAreToggledThenCorrectPixelsAreSent() = runTest { + fun `onProtectionsToggled - privacy protections toggled - correct pixels sent`() = runTest { val params = mapOf("test_key" to "test_value") whenever(privacyProtectionsPopupExperimentExternalPixels.getPixelParams()).thenReturn(params) testee.setInitialBrokenSite( diff --git a/app/src/test/java/com/duckduckgo/app/feedback/ui/common/FeedbackViewModelTest.kt b/app/src/test/java/com/duckduckgo/app/feedback/ui/common/FeedbackViewModelTest.kt index 3600bc9f2519..84230fb5cf8a 100644 --- a/app/src/test/java/com/duckduckgo/app/feedback/ui/common/FeedbackViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/feedback/ui/common/FeedbackViewModelTest.kt @@ -83,12 +83,12 @@ class FeedbackViewModelTest { } @Test - fun whenInitialisedThenFragmentStateIsForFirstStep() { + fun `initialise - fragment state for first step`() { assertTrue(updateViewCommand is InitialAppEnjoymentClarifier) } @Test - fun whenCanRateAppAndUserSelectsInitialHappyFaceThenFragmentStateIsFirstStepOfHappyFlow() { + fun `userSelectsInitialHappyFace - fragment state first step of happy flow`() { configureRatingCanBeGiven() testee.userSelectedPositiveFeedback() assertTrue(updateViewCommand is FragmentState.PositiveFeedbackFirstStep) @@ -96,7 +96,7 @@ class FeedbackViewModelTest { } @Test - fun whenCannotRateAppAndUserSelectsInitialHappyFaceThenFragmentStateSkipsStraightToSharingFeedback() { + fun `userSelectsInitialHappyFace - fragment state skips straight to sharing feedback`() { configureRatingCannotBeGiven() testee.userSelectedPositiveFeedback() assertTrue(updateViewCommand is FragmentState.PositiveShareFeedback) @@ -104,7 +104,7 @@ class FeedbackViewModelTest { } @Test - fun whenCanRateAppAndUserNavigatesBackFromPositiveInitialFragmentThenFragmentStateIsInitialFragment() { + fun `whenCanRateAppAndUserNavigatesBackFromPositiveInitialFragment - fragment state initial fragment`() { configureRatingCanBeGiven() testee.userSelectedPositiveFeedback() testee.onBackPressed() @@ -114,7 +114,7 @@ class FeedbackViewModelTest { } @Test - fun whenCannotRateAppAndUserNavigatesBackFromPositiveInitialFragmentThenFragmentStateIsInitialFragment() { + fun `whenCannotRateAppAndUserNavigatesBackFromPositiveInitialFragment - fragment state initial fragment`() { configureRatingCannotBeGiven() testee.userSelectedPositiveFeedback() testee.onBackPressed() @@ -123,14 +123,14 @@ class FeedbackViewModelTest { } @Test - fun whenUserChoosesNotToProvideFurtherDetailsForPositiveFeedbackThenSubmitted() = runTest { + fun `userGavePositiveFeedbackNoDetails - feedback submitted`() = runTest { testee.userGavePositiveFeedbackNoDetails() verify(feedbackSubmitter).sendPositiveFeedback(null) } @Test - fun whenUserChoosesNotToProvideFurtherDetailsForPositiveFeedbackThenExitCommandIssued() = runTest { + fun `userGavePositiveFeedback - exit command issued`() = runTest { testee.userGavePositiveFeedbackNoDetails() val command = captureCommand() as Command.Exit @@ -138,14 +138,14 @@ class FeedbackViewModelTest { } @Test - fun whenUserProvidesFurtherDetailsForPositiveFeedbackThenFeedbackSubmitted() = runTest { + fun `userProvidesFurtherDetails - feedback submitted`() = runTest { testee.userProvidedPositiveOpenEndedFeedback("foo") verify(feedbackSubmitter).sendPositiveFeedback("foo") } @Test - fun whenUserProvidesFurtherDetailsForPositiveFeedbackThenExitCommandIssued() = runTest { + fun `userProvidesFurtherDetails - positive feedback - exit command issued`() = runTest { testee.userProvidedPositiveOpenEndedFeedback("foo") val command = captureCommand() as Command.Exit @@ -153,39 +153,39 @@ class FeedbackViewModelTest { } @Test - fun whenUserProvidesNegativeFeedbackThenFeedbackSubmitted() = runTest { + fun `userProvidesNegativeFeedback - feedback submitted`() = runTest { testee.userProvidedNegativeOpenEndedFeedback(MISSING_BROWSING_FEATURES, TAB_MANAGEMENT, "foo") verify(feedbackSubmitter).sendNegativeFeedback(MISSING_BROWSING_FEATURES, TAB_MANAGEMENT, "foo") } @Test - fun whenUserProvidesNegativeFeedbackNoSubReasonThenFeedbackSubmitted() = runTest { + fun `userProvidesNegativeFeedback - no sub reason - feedback submitted`() = runTest { testee.userProvidedNegativeOpenEndedFeedback(MISSING_BROWSING_FEATURES, null, "foo") verify(feedbackSubmitter).sendNegativeFeedback(MISSING_BROWSING_FEATURES, null, "foo") } @Test - fun whenUserProvidesNegativeFeedbackEmptyOpenEndedFeedbackThenFeedbackSubmitted() = runTest { + fun `userProvidesNegativeFeedback - empty open-ended feedback - feedback submitted`() = runTest { testee.userProvidedNegativeOpenEndedFeedback(MISSING_BROWSING_FEATURES, null, "") verify(feedbackSubmitter).sendNegativeFeedback(MISSING_BROWSING_FEATURES, null, "") } @Test - fun whenUserCancelsThenExitCommandIssued() { + fun `userWantsToCancel - exit command issued - feedback not submitted`() { testee.userWantsToCancel() val command = captureCommand() as Command.Exit assertFalse(command.feedbackSubmitted) } @Test - fun whenUserSelectsInitialSadFaceThenFragmentStateIsFirstStepOfUnhappyFlow() { + fun `userSelectsInitialSadFace - fragment state first step unhappy flow`() { testee.userSelectedNegativeFeedback() assertTrue(updateViewCommand is NegativeFeedbackMainReason) verifyForwardsNavigation(updateViewCommand) } @Test - fun whenUserNavigatesBackFromNegativeMainReasonFragmentThenFragmentStateIsInitialFragment() { + fun `onBackPressed - fragment state initial - initial fragment`() { testee.userSelectedNegativeFeedback() testee.onBackPressed() assertTrue(updateViewCommand is InitialAppEnjoymentClarifier) @@ -193,56 +193,56 @@ class FeedbackViewModelTest { } @Test - fun whenUserSelectsMainNegativeReasonMissingBrowserFeaturesThenFragmentStateIsSubReasonSelection() { + fun `userSelectsMainNegativeReasonMissingBrowserFeatures - fragment state is sub reason selection`() { testee.userSelectedNegativeFeedbackMainReason(MISSING_BROWSING_FEATURES) assertTrue(updateViewCommand is NegativeFeedbackSubReason) verifyForwardsNavigation(updateViewCommand) } @Test - fun whenUserSelectsMainNegativeReasonNotEnoughCustomizationsThenFragmentStateIsSubReasonSelection() { + fun `userSelectsMainNegativeReason - not enough customizations - fragment state sub reason selection`() { testee.userSelectedNegativeFeedbackMainReason(NOT_ENOUGH_CUSTOMIZATIONS) assertTrue(updateViewCommand is NegativeFeedbackSubReason) verifyForwardsNavigation(updateViewCommand) } @Test - fun whenUserSelectsMainNegativeReasonSearchNotGoodEnoughThenFragmentStateIsSubReasonSelection() { + fun `userSelectsMainNegativeReason - fragment state sub reason selection`() { testee.userSelectedNegativeFeedbackMainReason(SEARCH_NOT_GOOD_ENOUGH) assertTrue(updateViewCommand is NegativeFeedbackSubReason) verifyForwardsNavigation(updateViewCommand) } @Test - fun whenUserSelectsMainNegativeReasonAppIsSlowOrBuggyThenFragmentStateIsSubReasonSelection() { + fun `userSelectsMainNegativeReasonAppIsSlowOrBuggy - fragment state is sub reason selection`() { testee.userSelectedNegativeFeedbackMainReason(APP_IS_SLOW_OR_BUGGY) assertTrue(updateViewCommand is NegativeFeedbackSubReason) verifyForwardsNavigation(updateViewCommand) } @Test - fun whenUserSelectsMainNegativeReasonOtherThenFragmentStateIsOpenEndedFeedback() { + fun `userSelectsMainNegativeReason - fragment state open ended feedback`() { testee.userSelectedNegativeFeedbackMainReason(OTHER) assertTrue(updateViewCommand is NegativeOpenEndedFeedback) verifyForwardsNavigation(updateViewCommand) } @Test - fun whenUserSelectsMainNegativeReasonBrokenSiteThenFragmentStateIsSubReasonSelection() { + fun `userSelectsMainNegativeReason - fragment state is sub reason selection`() { testee.userSelectedNegativeFeedbackMainReason(WEBSITES_NOT_LOADING) assertTrue(updateViewCommand is NegativeWebSitesBrokenFeedback) verifyForwardsNavigation(updateViewCommand) } @Test - fun whenUserSelectsSubNegativeReasonThenFragmentStateIsOpenEndedFeedback() { + fun `userSelectsSubNegativeReason - fragment state open ended feedback`() { testee.userSelectedSubReasonMissingBrowserFeatures(MISSING_BROWSING_FEATURES, TAB_MANAGEMENT) assertTrue(updateViewCommand is NegativeOpenEndedFeedback) verifyForwardsNavigation(updateViewCommand) } @Test - fun whenUserNavigatesBackFromSubReasonSelectionThenFragmentStateIsMainReasonSelection() { + fun `onBackPressed - fragment state updated - main reason selection`() { testee.userSelectedNegativeFeedbackMainReason(MISSING_BROWSING_FEATURES) testee.onBackPressed() assertTrue(updateViewCommand is NegativeFeedbackMainReason) @@ -250,7 +250,7 @@ class FeedbackViewModelTest { } @Test - fun whenUserNavigatesBackFromOpenEndedFeedbackAndSubReasonIsValidStepThenFragmentStateIsSubReasonSelection() { + fun `onBackPressed - fragment state is sub reason selection`() { testee.userSelectedNegativeFeedbackMainReason(MISSING_BROWSING_FEATURES) testee.userSelectedSubReasonMissingBrowserFeatures(MISSING_BROWSING_FEATURES, TAB_MANAGEMENT) testee.onBackPressed() @@ -259,7 +259,7 @@ class FeedbackViewModelTest { } @Test - fun whenUserNavigatesBackFromOpenEndedFeedbackAndSubReasonNotAValidStepThenFragmentStateIsMainReasonSelection() { + fun `onBackPressed - fragment state is main reason selection`() { testee.userSelectedNegativeFeedbackMainReason(OTHER) testee.onBackPressed() assertTrue(updateViewCommand is NegativeFeedbackMainReason) @@ -267,7 +267,7 @@ class FeedbackViewModelTest { } @Test - fun whenUserNavigatesBackFromOpenEndedFeedbackThenFragmentStateIsSubReasonSelection() { + fun `onBackPressed - fragment state is sub reason selection - negative feedback sub reason`() { testee.userSelectedNegativeFeedbackMainReason(MISSING_BROWSING_FEATURES) testee.userSelectedSubReasonMissingBrowserFeatures(MISSING_BROWSING_FEATURES, TAB_MANAGEMENT) testee.onBackPressed() diff --git a/app/src/test/java/com/duckduckgo/app/fire/fireproofwebsite/data/FireproofWebsiteEntityKtTest.kt b/app/src/test/java/com/duckduckgo/app/fire/fireproofwebsite/data/FireproofWebsiteEntityKtTest.kt index d961ca9e6279..3761a216e0b0 100644 --- a/app/src/test/java/com/duckduckgo/app/fire/fireproofwebsite/data/FireproofWebsiteEntityKtTest.kt +++ b/app/src/test/java/com/duckduckgo/app/fire/fireproofwebsite/data/FireproofWebsiteEntityKtTest.kt @@ -22,21 +22,21 @@ import org.junit.Test class FireproofWebsiteEntityKtTest { @Test - fun whenDomainStartsWithWWWThenDropPrefix() { + fun `website - domain starts with www - drops prefix`() { val fireproofWebsiteEntity = FireproofWebsiteEntity("www.example.com") val website = fireproofWebsiteEntity.website() assertEquals("example.com", website) } @Test - fun whenDomainStartsWithWWWUppercaseThenDropPrefix() { + fun `whenDomainStartsWithWWWThenDropPrefix - domain starts with www uppercase - drops prefix`() { val fireproofWebsiteEntity = FireproofWebsiteEntity("WWW.example.com") val website = fireproofWebsiteEntity.website() assertEquals("example.com", website) } @Test - fun whenDomainDoesNotStartWithWWWThenDomainUnchanged() { + fun `website - domain does not start with www - unchanged`() { val fireproofWebsiteEntity = FireproofWebsiteEntity("mobile.example.com") val website = fireproofWebsiteEntity.website() assertEquals("mobile.example.com", website) diff --git a/app/src/test/java/com/duckduckgo/app/firebutton/FireButtonViewModelTest.kt b/app/src/test/java/com/duckduckgo/app/firebutton/FireButtonViewModelTest.kt index 7d09e6152b3c..6771426dddc4 100644 --- a/app/src/test/java/com/duckduckgo/app/firebutton/FireButtonViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/firebutton/FireButtonViewModelTest.kt @@ -75,7 +75,7 @@ internal class FireButtonViewModelTest { } @Test - fun whenInitialisedThenViewStateEmittedWithDefaultValues() = runTest { + fun `whenInitialised - view state emitted with default values`() = runTest { whenever(mockAppSettingsDataStore.selectedFireAnimation).thenReturn(FireAnimation.HeroFire) val expectedClearData = FireButtonViewModel.AutomaticallyClearData( clearWhatOption = ClearWhatOption.CLEAR_NONE, @@ -94,7 +94,7 @@ internal class FireButtonViewModelTest { } @Test - fun whenOnFireproofWebsitesClickedThenEmitCommandLaunchFireproofWebsitesAndPixelFired() = runTest { + fun `onFireproofWebsitesClicked - emit command launch fireproof websites and pixel fired`() = runTest { testee.commands().test { testee.onFireproofWebsitesClicked() @@ -106,7 +106,7 @@ internal class FireButtonViewModelTest { } @Test - fun whenOnAutomaticallyClearWhatClickedEmitCommandShowClearWhatDialogAndPixelFired() = runTest { + fun `onAutomaticallyClearWhatClicked - emit command show clear what dialog and pixel fired`() = runTest { testee.commands().test { testee.onAutomaticallyClearWhatClicked() @@ -118,7 +118,7 @@ internal class FireButtonViewModelTest { } @Test - fun whenOnAutomaticallyClearWhenClickedEmitCommandShowClearWhenDialogAndPixelFired() = runTest { + fun `onAutomaticallyClearWhenClicked - emit command show clear when dialog and pixel fired`() = runTest { testee.commands().test { testee.onAutomaticallyClearWhenClicked() @@ -130,7 +130,7 @@ internal class FireButtonViewModelTest { } @Test - fun whenOnAutomaticallyWhatOptionSelectedWithNewOptionThenDataStoreIsUpdatedAndPixelSent() = runTest { + fun `onAutomaticallyWhatOptionSelected - data store updated and pixel sent`() = runTest { whenever(mockAppSettingsDataStore.isCurrentlySelected(ClearWhatOption.CLEAR_TABS_AND_DATA)).thenReturn(false) testee.commands().test { @@ -142,7 +142,7 @@ internal class FireButtonViewModelTest { } @Test - fun whenOnAutomaticallyWhatOptionSelectedWithSameOptionThenDataStoreIsNotUpdatedAndPixelNotSent() = runTest { + fun `onAutomaticallyWhatOptionSelected - same option selected - data store not updated and pixel not sent`() = runTest { whenever(mockAppSettingsDataStore.isCurrentlySelected(ClearWhatOption.CLEAR_NONE)).thenReturn(true) testee.commands().test { @@ -154,7 +154,7 @@ internal class FireButtonViewModelTest { } @Test - fun whenOnAutomaticallyWhenOptionSelectedWithNewOptionThenDataStoreIsUpdatedAndPixelSent() = runTest { + fun `onAutomaticallyWhenOptionSelected - data store updated and pixel sent`() = runTest { whenever(mockAppSettingsDataStore.isCurrentlySelected(ClearWhenOption.APP_EXIT_ONLY)).thenReturn(false) testee.commands().test { @@ -166,7 +166,7 @@ internal class FireButtonViewModelTest { } @Test - fun whenOnAutomaticallyWhenOptionSelectedWithSameOptionThenDataStoreIsNotUpdatedAndPixelNotSent() = runTest { + fun `onAutomaticallyWhenOptionSelected - same option selected - data store not updated and pixel not sent`() = runTest { whenever(mockAppSettingsDataStore.isCurrentlySelected(ClearWhenOption.APP_EXIT_ONLY)).thenReturn(true) testee.commands().test { @@ -178,7 +178,7 @@ internal class FireButtonViewModelTest { } @Test - fun whenFireAnimationSettingClickedThenCommandIsLaunchFireAnimationSettings() = runTest { + fun `commands - fire animation setting clicked - launch fire animation settings`() = runTest { testee.commands().test { testee.userRequestedToChangeFireAnimation() @@ -189,14 +189,14 @@ internal class FireButtonViewModelTest { } @Test - fun whenFireAnimationSettingClickedThenPixelSent() { + fun `whenFireAnimationSettingClicked - pixel sent`() { testee.userRequestedToChangeFireAnimation() verify(mockPixel).fire(AppPixelName.FIRE_ANIMATION_SETTINGS_OPENED) } @Test - fun whenNewFireAnimationSelectedThenUpdateViewState() = runTest { + fun `onFireAnimationSelected - view state updated`() = runTest { val expectedAnimation = FireAnimation.HeroWater testee.viewState().test { @@ -211,21 +211,21 @@ internal class FireButtonViewModelTest { } @Test - fun whenNewFireAnimationSelectedThenStoreNewSelectedAnimation() { + fun `onFireAnimationSelected - store new selected animation`() { testee.onFireAnimationSelected(FireAnimation.HeroWater) verify(mockAppSettingsDataStore).selectedFireAnimation = FireAnimation.HeroWater } @Test - fun whenNewFireAnimationSelectedThenPreLoadAnimation() { + fun `onFireAnimationSelected - preload selected animation`() { testee.onFireAnimationSelected(FireAnimation.HeroWater) verify(mockFireAnimationLoader).preloadSelectedAnimation() } @Test - fun whenNewFireAnimationSelectedThenPixelSent() { + fun `onFireAnimationSelected - pixel sent`() { testee.onFireAnimationSelected(FireAnimation.HeroWater) verify(mockPixel).fire( @@ -235,7 +235,7 @@ internal class FireButtonViewModelTest { } @Test - fun whenSameFireAnimationSelectedThenDoNotSendPixel() { + fun `onFireAnimationSelected - same fire animation selected - do not send pixel`() { givenSelectedFireAnimation(FireAnimation.HeroFire) testee.onFireAnimationSelected(FireAnimation.HeroFire) diff --git a/app/src/test/java/com/duckduckgo/app/global/HashUtilitiesTest.kt b/app/src/test/java/com/duckduckgo/app/global/HashUtilitiesTest.kt index 456ccdf80014..2c2f91c86ac0 100644 --- a/app/src/test/java/com/duckduckgo/app/global/HashUtilitiesTest.kt +++ b/app/src/test/java/com/duckduckgo/app/global/HashUtilitiesTest.kt @@ -25,30 +25,30 @@ import org.junit.Test class HashUtilitiesTest { @Test - fun whenSha1HashCalledOnStringThenResultIsCorrect() { + fun `sha1 - string input - correct result`() { val result = helloWorldText.sha1 assertEquals(helloWorldSha1, result) } @Test - fun whenSha256HashCalledOnBytesThenResultIsCorrect() { + fun `when Sha256Hash called on bytes - result is correct`() { val result = helloWorldText.toByteArray().sha256 assertEquals(helloWorldSha256, result) } @Test - fun whenSha256HashCalledOnStringThenResultIsCorrect() { + fun `when Sha256Hash called on string - result is correct`() { val result = helloWorldText.sha256 assertEquals(helloWorldSha256, result) } @Test - fun whenCorrectSha256HashUsedThenVerifyIsTrue() { + fun `verifySha256 - correct sha256 hash used - true`() { assertTrue(helloWorldText.toByteArray().verifySha256(helloWorldSha256)) } @Test - fun whenIncorrectByteSha256HashUsedThenVerifyIsFalse() { + fun `whenIncorrectByteSha256HashUsedThenVerifyIsFalse - verify is false`() { assertFalse(helloWorldText.toByteArray().verifySha256(otherSha256)) } diff --git a/app/src/test/java/com/duckduckgo/app/global/UriExtensionTest.kt b/app/src/test/java/com/duckduckgo/app/global/UriExtensionTest.kt index 129e620d64da..6dfe1cbb333f 100644 --- a/app/src/test/java/com/duckduckgo/app/global/UriExtensionTest.kt +++ b/app/src/test/java/com/duckduckgo/app/global/UriExtensionTest.kt @@ -40,237 +40,237 @@ import org.junit.runner.RunWith class UriExtensionTest { @Test - fun whenUriDoesNotHaveASchemeThenWithSchemeAppendsHttp() { + fun `withScheme - no scheme - with http scheme`() { val url = "someurl" assertEquals("http://$url", Uri.parse(url).withScheme().toString()) } @Test - fun whenUriHasASchemeThenWithSchemeHasNoEffect() { + fun `parse - uri has scheme - with scheme has no effect`() { val url = "http://someurl" assertEquals(url, Uri.parse(url).withScheme().toString()) } @Test - fun whenUriBeginsWithWwwThenBaseHostReturnsWithoutWww() { + fun `parse - uri begins with www - base host returns without www`() { val url = "http://www.example.com" assertEquals("example.com", Uri.parse(url).baseHost) } @Test - fun whenUriDoesNotBeginWithWwwThenBaseHosReturnsWithSameHost() { + fun `parse - uri does not begin with www - same host`() { val url = "http://example.com" assertEquals("example.com", Uri.parse(url).baseHost) } @Test - fun whenUriDoesNotHaveASchemeThenBaseHostStillResolvesHost() { + fun `parseUri - no scheme - base host still resolves host`() { val url = "www.example.com" assertEquals("example.com", Uri.parse(url).baseHost) } @Test - fun whenUriContainsInvalidHostThenBaseHostIsNull() { + fun `parse - uri contains invalid host - base host is null`() { val url = "about:blank" assertNull(Uri.parse(url).baseHost) } @Test - fun whenUriIsHttpIrrespectiveOfCaseThenIsHttpIsTrue() { + fun `parseUri - http uri - is http true`() { assertTrue(Uri.parse("http://example.com").isHttp) assertTrue(Uri.parse("HTTP://example.com").isHttp) } @Test - fun whenUriIsHttpsThenIsHttpIsFalse() { + fun `parseUri - https - is http false`() { assertFalse(Uri.parse("https://example.com").isHttp) } @Test - fun whenUriIsMalformedThenIsHttpIsFalse() { + fun `parseUri - malformed uri - is http false`() { assertFalse(Uri.parse("[example com]").isHttp) } @Test - fun whenUriIsHttpsIrrespectiveOfCaseThenIsHttpsIsTrue() { + fun `parseUri - https - is true`() { assertTrue(Uri.parse("https://example.com").isHttps) assertTrue(Uri.parse("HTTPS://example.com").isHttps) } @Test - fun whenUriIsHttpThenIsHttpsIsFalse() { + fun `parseUri - http uri - is https false`() { assertFalse(Uri.parse("http://example.com").isHttps) } @Test - fun whenUriIsHttpsAndOtherIsHttpButOtherwiseIdenticalThenIsHttpsVersionOfOtherIsTrue() { + fun `isHttpsVersionOf - identical uris - is https version true`() { val uri = Uri.parse("https://example.com") val other = Uri.parse("http://example.com") assertTrue(uri.isHttpsVersionOfUri(other)) } @Test - fun whenUriIsHttpsAndOtherIsHttpButNotOtherwiseIdenticalThenIsHttpsVersionOfOtherIsFalse() { + fun `isHttpsVersionOfUri - not identical - is false`() { val uri = Uri.parse("https://example.com") val other = Uri.parse("http://example.com/path") assertFalse(uri.isHttpsVersionOfUri(other)) } @Test - fun whenUriIsHttpThenIsHttpsVersionOfOtherIsFalse() { + fun `isHttpsVersionOfUri - http - is false`() { val uri = Uri.parse("http://example.com") val other = Uri.parse("http://example.com") assertFalse(uri.isHttpsVersionOfUri(other)) } @Test - fun whenUriIsHttpsAndOtherIsHttpsThenIsHttpsVersionOfOtherIsFalse() { + fun `isHttpsVersionOfUri - same protocol - is false`() { val uri = Uri.parse("https://example.com") val other = Uri.parse("https://example.com") assertFalse(uri.isHttpsVersionOfUri(other)) } @Test - fun whenUriIsMalformedThenIsHtpsIsFalse() { + fun `parseUri - malformed uri - is https false`() { assertFalse(Uri.parse("[example com]").isHttps) } @Test - fun whenIpUriThenHasIpHostIsTrue() { + fun `whenUriHasIpHost - has ip host is true`() { assertTrue(Uri.parse("https://54.229.105.203/something").hasIpHost) assertTrue(Uri.parse("54.229.105.203/something").hasIpHost) } @Test - fun whenIpWithPortUriThenHasIpHostIsTrue() { + fun `whenUriHasPortThenHasIpHostIsTrue - has ip host`() { assertTrue(Uri.parse("https://54.229.105.203:999/something").hasIpHost) assertTrue(Uri.parse("54.229.105.203:999/something").hasIpHost) } @Test - fun whenIpWithPortUriThenPortNumberParsedSuccessfully() { + fun `parseUri - port number parsed successfully`() { assertEquals(999, Uri.parse("https://54.229.105.203:999/something").port) } @Test - fun whenValidIpAddressWithPortParsedWithSchemeThenPortNumberParsedSuccessfully() { + fun `parse - valid ip address with port parsed with scheme - port number parsed successfully`() { assertEquals(999, Uri.parse("121.33.2.11:999").withScheme().port) } @Test - fun whenStandardUriThenHasIpHostIsFalse() { + fun `whenStandardUriThenHasIpHostIsFalse - standard uri - has ip host is false`() { assertFalse(Uri.parse("http://example.com").hasIpHost) } @Test - fun whenUrlStartsMDotThenIdentifiedAsMobileSite() { + fun `parseUri - url starts with m dot - identified as mobile site`() { assertTrue(Uri.parse("https://m.example.com").isMobileSite) } @Test - fun whenUrlStartsMobileDotThenIdentifiedAsMobileSite() { + fun `parseUri - url starts mobile dot - identified as mobile site`() { assertTrue(Uri.parse("https://mobile.example.com").isMobileSite) } @Test - fun whenUrlSubdomainEndsWithMThenNotIdentifiedAsMobileSite() { + fun `parseUri - subdomain ends with M - not mobile site`() { assertFalse(Uri.parse("https://adam.example.com").isMobileSite) } @Test - fun whenUrlDoesNotStartWithMDotThenNotIdentifiedAsMobileSite() { + fun `parseUri - does not start with M dot - not identified as mobile site`() { assertFalse(Uri.parse("https://example.com").isMobileSite) } @Test - fun whenConvertingMobileSiteToDesktopSiteThenShortMobilePrefixStripped() { + fun `toDesktopUri - short mobile prefix stripped`() { val converted = Uri.parse("https://m.example.com").toDesktopUri() assertEquals("https://example.com", converted.toString()) } @Test - fun whenConvertingMobileSiteToDesktopSiteThenLongMobilePrefixStripped() { + fun `toDesktopUri - long mobile prefix stripped`() { val converted = Uri.parse("https://mobile.example.com").toDesktopUri() assertEquals("https://example.com", converted.toString()) } @Test - fun whenConvertingMobileSiteToDesktopSiteThenMultipleMobilePrefixesStripped() { + fun `toDesktopUri - multiple mobile prefixes stripped`() { val converted = Uri.parse("https://mobile.m.example.com").toDesktopUri() assertEquals("https://example.com", converted.toString()) } @Test - fun whenConvertingDesktopSiteToDesktopSiteThenUrlUnchanged() { + fun `toDesktopUri - url unchanged`() { val converted = Uri.parse("https://example.com").toDesktopUri() assertEquals("https://example.com", converted.toString()) } @Test - fun whenGettingAbsoluteStringThenDoNotReturnQueryParameters() { + fun `getAbsoluteString - no query parameters - https·//example·com/test`() { val absoluteString = Uri.parse("https://example.com/test?q=example/#1/anotherrandomcode").absoluteString assertEquals("https://example.com/test", absoluteString) } @Test - fun whenNullUrlThenNullFaviconUrl() { + fun `toUri - null url - null favicon url`() { assertNull("".toUri().faviconLocation()) } @Test - fun whenHttpRequestThenFaviconLocationAlsoHttp() { + fun `whenHttpRequest - favicon location also http - is http`() { val favicon = "http://example.com".toUri().faviconLocation() assertTrue(favicon!!.isHttp) } @Test - fun whenHttpsRequestThenFaviconLocationAlsoHttps() { + fun `whenHttpsRequestThenFaviconLocationAlsoHttps - favicon location also https`() { val favicon = "https://example.com".toUri().faviconLocation() assertTrue(favicon!!.isHttps) } @Test - fun whenUrlContainsASubdomainThenSubdomainReturnedInFavicon() { + fun `whenUrlContainsASubdomain - favicon returned - subdomain favicon`() { val favicon = "https://sub.example.com".toUri().faviconLocation() assertEquals("https://sub.example.com/favicon.ico", favicon.toString()) } @Test - fun whenUrlIsIpAddressThenIpReturnedInFaviconUrl() { + fun `toUri - url is ip address - ip returned in favicon url`() { val favicon = "https://192.168.1.0".toUri().faviconLocation() assertEquals("https://192.168.1.0/favicon.ico", favicon.toString()) } @Test - fun whenUrlDoesNotHaveSchemeReturnNull() { + fun `toUri - no scheme - returns null`() { assertNull("www.example.com".toUri().domain()) } @Test - fun whenUrlHasSchemeReturnDomain() { + fun `toUri - has scheme - returns domain`() { assertEquals("www.example.com", "http://www.example.com".toUri().domain()) } @Test - fun whenUriHasResourceNameThenDropSchemeReturnResourceName() { + fun `toUri - has resource name - drops scheme`() { assertEquals("www.foo.com", "https://www.foo.com".toUri().toStringDropScheme()) assertEquals("www.foo.com", "http://www.foo.com".toUri().toStringDropScheme()) } @Test - fun whenUriHasResourceNameAndPathThenDropSchemeReturnResourceNameAndPath() { + fun `toUri - has resource name and path - drops scheme`() { assertEquals("www.foo.com/path/to/foo", "https://www.foo.com/path/to/foo".toUri().toStringDropScheme()) assertEquals("www.foo.com/path/to/foo", "http://www.foo.com/path/to/foo".toUri().toStringDropScheme()) } @Test - fun whenUriHasResourceNamePathAndParamsThenDropSchemeReturnResourceNamePathAndParams() { + fun `toUri - has resource name path and params - drop scheme return resource name path and params`() { assertEquals("www.foo.com/path/to/foo?key=value", "https://www.foo.com/path/to/foo?key=value".toUri().toStringDropScheme()) assertEquals("www.foo.com/path/to/foo?key=value", "http://www.foo.com/path/to/foo?key=value".toUri().toStringDropScheme()) } @Test - fun whenUriExtractDomainThenReturnDomainOnly() { + fun `extractDomain - when Uri extract domain then return domain only`() { assertEquals("www.foo.com", "https://www.foo.com/path/to/foo?key=value".extractDomain()) assertEquals("www.foo.com", "www.foo.com/path/to/foo?key=value".extractDomain()) assertEquals("foo.com", "foo.com/path/to/foo?key=value".extractDomain()) diff --git a/app/src/test/java/com/duckduckgo/app/global/UriStringTest.kt b/app/src/test/java/com/duckduckgo/app/global/UriStringTest.kt index 7f03fb5f0f4e..12946d72ae47 100644 --- a/app/src/test/java/com/duckduckgo/app/global/UriStringTest.kt +++ b/app/src/test/java/com/duckduckgo/app/global/UriStringTest.kt @@ -29,7 +29,7 @@ import org.junit.runner.RunWith class UriStringTest { @Test - fun whenUrlsHaveSameDomainThenSameOrSubdomainIsTrue() { + fun `sameOrSubdomain - same domain - true`() { assertTrue(sameOrSubdomain("http://example.com/index.html", "http://example.com/home.html")) } @@ -39,7 +39,7 @@ class UriStringTest { } @Test - fun whenUrlIsSubdomainThenSameOrSubdomainIsTrue() { + fun `sameOrSubdomain - url is subdomain - true`() { assertTrue(sameOrSubdomain("http://subdomain.example.com/index.html", "http://example.com/home.html")) } @@ -49,32 +49,32 @@ class UriStringTest { } @Test - fun whenUrlIsAParentDomainThenSameOrSubdomainIsFalse() { + fun `sameOrSubdomain - url is a parent domain - false`() { assertFalse(sameOrSubdomain("http://example.com/index.html", "http://parent.example.com/home.html")) } @Test - fun whenUrlIsAParentDomainThenSameOrSubdomainIsFalse2() { + fun `whenUrlIsAParentDomainThenSameOrSubdomainIsFalse - same or subdomain - false`() { assertFalse(sameOrSubdomain("http://example.com/index.html".toUri(), "http://parent.example.com/home.html")) } @Test - fun whenChildUrlIsMalformedThenSameOrSubdomainIsFalse() { + fun `whenChildUrlIsMalformed - same or subdomain - false`() { assertFalse(sameOrSubdomain("??.example.com/index.html", "http://example.com/home.html")) } @Test - fun whenChildUrlIsMalformedThenSameOrSubdomainIsFalse2() { + fun `whenChildUrlIsMalformedThenSameOrSubdomainIsFalse - same or subdomain is false`() { assertFalse(sameOrSubdomain("??.example.com/index.html".toUri(), "http://example.com/home.html")) } @Test - fun whenParentUrlIsMalformedThenSameOrSubdomainIsFalse() { + fun `whenParentUrlIsMalformedThenSameOrSubdomainIsFalse - same or subdomain - false`() { assertFalse(sameOrSubdomain("http://example.com/index.html", "??.example.com/home.html")) } @Test - fun whenParentUrlIsMalformedThenSameOrSubdomainIsFalse2() { + fun `whenParentUrlIsMalformedThenSameOrSubdomainIsFalse - same or subdomain is false`() { assertFalse(sameOrSubdomain("http://example.com/index.html".toUri(), "??.example.com/home.html")) } @@ -109,289 +109,289 @@ class UriStringTest { } @Test - fun whenChildUrlIsMalformedThenSafeSameOrSubdomainIsFalse() { + fun `sameOrSubdomain - child url is malformed - false`() { assertFalse(sameOrSubdomain("??.example.com/index.html", "http://example.com/home.html")) } @Test - fun whenChildUrlIsMalformedThenSafeSameOrSubdomainIsFalse2() { + fun `whenChildUrlIsMalformedThenSafeSameOrSubdomainIsFalse - same or subdomain - false`() { assertFalse(sameOrSubdomain("??.example.com/index.html".toUri(), "http://example.com/home.html")) } @Test - fun whenParentUrlIsMalformedThenSafeSameOrSubdomainIsFalse() { + fun `whenParentUrlIsMalformedThenSafeSameOrSubdomainIsFalse - same or subdomain - false`() { assertFalse(sameOrSubdomain("http://example.com/index.html", "??.example.com/home.html")) } @Test - fun whenParentUrlIsMalformedThenSafeSameOrSubdomainIsFalse2() { + fun `whenParentUrlIsMalformedThenSafeSameOrSubdomainIsFalse - same or subdomain is false`() { assertFalse(sameOrSubdomain("http://example.com/index.html".toUri(), "??.example.com/home.html")) } @Test - fun whenUserIsPresentThenIsWebUrlIsFalse() { + fun `isWebUrl - user is present - is false`() { val input = "http://example.com@sample.com" assertFalse(isWebUrl(input)) } @Test - fun whenGivenLongWellFormedUrlThenIsWebUrlIsTrue() { + fun `isWebUrl - given long well-formed URL - is true`() { val input = "http://www.veganchic.com/products/Camo-High-Top-Sneaker-by-The-Critical-Slide-Societ+80758-0180.html" assertTrue(isWebUrl(input)) } @Test - fun whenHostIsValidThenIsWebUrlIsTrue() { + fun `isWebUrl - host valid - is web url true`() { assertTrue(isWebUrl("test.com")) } @Test - fun whenHostIsValidIpAddressThenIsWebUrlIsTrue() { + fun `isWebUrl - host valid ip address - is true`() { assertTrue(isWebUrl("121.33.2.11")) } @Test - fun whenHostIsValidIpAddressWithPortThenIsWebUrlIsTrue() { + fun `isWebUrl - host valid ip address with port - is true`() { assertTrue(isWebUrl("121.33.2.11:999")) } @Test - fun whenHostIsLocalhostThenIsWebUrlIsTrue() { + fun `isWebUrl - host is localhost - true`() { assertTrue(isWebUrl("localhost")) } @Test - fun whenHostIsInvalidContainsSpaceThenIsWebUrlIsFalse() { + fun `isWebUrl - host is invalid contains space - is false`() { assertFalse(isWebUrl("t est.com")) } @Test - fun whenHostIsInvalidContainsExclamationMarkThenIsWebUrlIsFalse() { + fun `isWebUrl - host is invalid contains exclamation mark - is false`() { assertFalse(isWebUrl("test!com.com")) } @Test - fun whenHostIsInvalidIpThenIsWebUrlIsFalse() { + fun `isWebUrl - host is invalid IP - is false`() { assertFalse(isWebUrl("121.33.33.")) } @Test - fun whenHostIsInvalidMisspelledLocalhostContainsSpaceThenIsWebUrlIsFalse() { + fun `isWebUrl - host is invalid misspelled localhost contains space - is false`() { assertFalse(isWebUrl("localhostt")) } @Test - fun whenSchemeIsValidNormalUrlThenIsWebUrlIsTrue() { + fun `isWebUrl - scheme is valid normal url - is web url true`() { assertTrue(isWebUrl("http://test.com")) } @Test - fun whenSchemeIsValidIpAddressThenIsWebUrlIsTrue() { + fun `isWebUrl - scheme is valid ip address - true`() { assertTrue(isWebUrl("http://121.33.2.11")) } @Test - fun whenSchemeIsValidIpAddressWithPortThenIsWebUrlIsTrue() { + fun `isWebUrl - scheme is valid ip address with port - true`() { assertTrue(isWebUrl("http://121.33.2.11:999")) } @Test - fun whenSchemeIsValidLocalhostUrlThenIsWebUrlIsTrue() { + fun `isWebUrl - scheme is valid localhost url - is true`() { assertTrue(isWebUrl("http://localhost")) } @Test - fun whenSchemeIsInvalidNormalUrlThenIsWebUrlIsFalse() { + fun `isWebUrl - scheme is invalid normal url - is false`() { assertFalse(isWebUrl("asdas://test.com")) } @Test - fun whenSchemeIsInvalidIpAddressThenIsWebUrlIsFalse() { + fun `isWebUrl - scheme is invalid ip address - is false`() { assertFalse(isWebUrl("asdas://121.33.2.11")) } @Test - fun whenSchemeIsInvalidLocalhostThenIsWebUrlIsFalse() { + fun `isWebUrl - scheme is invalid localhost - is false`() { assertFalse(isWebUrl("asdas://localhost")) } @Test - fun whenTextIsIncompleteHttpSchemeLettersOnlyThenIsWebUrlIsFalse() { + fun `isWebUrl - text is incomplete http scheme letters only - is false`() { assertFalse(isWebUrl("http")) } @Test - fun whenTextIsIncompleteHttpSchemeMissingBothSlashesThenIsWebUrlIsFalse() { + fun `isWebUrl - text is incomplete http scheme missing both slashes - is false`() { assertFalse(isWebUrl("http:")) } @Test - fun whenTextIsIncompleteHttpSchemeMissingOneSlashThenIsWebUrlIsFalse() { + fun `isWebUrl - text is incomplete http scheme missing one slash - is false`() { assertFalse(isWebUrl("http:/")) } @Test - fun whenTextIsIncompleteHttpsSchemeLettersOnlyThenIsWebUrlIsFalse() { + fun `isWebUrl - text is incomplete https scheme letters only - is false`() { assertFalse(isWebUrl("https")) } @Test - fun whenTextIsIncompleteHttpsSchemeMissingBothSlashesThenIsWebUrlIsFalse() { + fun `isWebUrl - text is incomplete https scheme missing both slashes - is false`() { assertFalse(isWebUrl("https:")) } @Test - fun whenTextIsIncompleteHttpsSchemeMissingOneSlashThenIsWebUrlIsFalse() { + fun `isWebUrl - text is incomplete https scheme missing one slash - is false`() { assertFalse(isWebUrl("https:/")) } @Test - fun whenPathIsValidNormalUrlThenIsWebUrlIsTrue() { + fun `isWebUrl - path valid normal url - is true`() { assertTrue(isWebUrl("http://test.com/path")) } @Test - fun whenPathIsValidIpAddressThenIsWebUrlIsTrue() { + fun `isWebUrl - path is valid ip address - is web url true`() { assertTrue(isWebUrl("http://121.33.2.11/path")) } @Test - fun whenPathIsValidIpAddressWithPortThenIsWebUrlIsTrue() { + fun `isWebUrl - path is valid ip address with port - is true`() { assertTrue(isWebUrl("http://121.33.2.11:999/path")) } @Test - fun whenPathIsValidLocalhostThenIsWebUrlIsTrue() { + fun `isWebUrl - path is valid localhost - is web url true`() { assertTrue(isWebUrl("http://localhost/path")) } @Test - fun whenPathIsValidMissingSchemeNormalUrlThenIsWebUrlIsTrue() { + fun `isWebUrl - path valid missing scheme normal url - is true`() { assertTrue(isWebUrl("test.com/path")) } @Test - fun whenPathIsValidMissingSchemeIpAddressThenIsWebUrlIsTrue() { + fun `isWebUrl - path valid missing scheme ip address - is true`() { assertTrue(isWebUrl("121.33.2.11/path")) } @Test - fun whenPathIsValidMissingSchemeLocalhostThenIsWebUrlIsTrue() { + fun `isWebUrl - path valid missing scheme localhost - is true`() { assertTrue(isWebUrl("localhost/path")) } @Test - fun whenPathIsInvalidContainsSpaceNormalUrlThenIsWebUrlIsFalse() { + fun `isWebUrl - path contains space normal url - is false`() { assertFalse(isWebUrl("http://test.com/pa th")) } @Test - fun whenPathIsInvalidContainsSpaceIpAddressThenIsWebUrlIsFalse() { + fun `isWebUrl - path is invalid contains space ip address - is false`() { assertFalse(isWebUrl("http://121.33.2.11/pa th")) } @Test - fun whenPathIsInvalidContainsSpaceLocalhostThenIsWebUrlIsFalse() { + fun `isWebUrl - path is invalid contains space localhost - is false`() { assertFalse(isWebUrl("http://localhost/pa th")) } @Test - fun whenPathIsInvalidContainsSpaceMissingSchemeNormalUrlThenIsWebUrlIsFalse() { + fun `isWebUrl - path contains space missing scheme normal url - is false`() { assertFalse(isWebUrl("test.com/pa th")) } @Test - fun whenPathIsInvalidContainsSpaceMissingSchemeIpAddressThenIsWebUrlIsFalse() { + fun `isWebUrl - path is invalid contains space missing scheme ip address - is false`() { assertFalse(isWebUrl("121.33.2.11/pa th")) } @Test - fun whenPathIsInvalidContainsSpaceMissingSchemeLocalhostThenIsWebUrlIsFalse() { + fun `isWebUrl - path is invalid contains space missing scheme localhost - is false`() { assertFalse(isWebUrl("localhost/pa th")) } @Test - fun whenPathIsValidContainsEncodedSpaceNormalUrlThenIsWebUrlIsTrue() { + fun `isWebUrl - path is valid contains encoded space normal url - is true`() { assertTrue(isWebUrl("http://www.example.com/pa%20th")) } @Test - fun whenParamsAreValidNormalUrlThenIsWebUrlIsTrue() { + fun `isWebUrl - params are valid normal URL - is true`() { assertTrue(isWebUrl("http://test.com?s=dafas&d=342")) } @Test - fun whenParamsAreValidIpAddressThenIsWebUrlIsTrue() { + fun `isWebUrl - params are valid ip address - is web url true`() { assertTrue(isWebUrl("http://121.33.2.11?s=dafas&d=342")) } @Test - fun whenParamsAreValidLocalhostThenIsWebUrlIsTrue() { + fun `isWebUrl - params are valid localhost - is web url true`() { assertTrue(isWebUrl("http://localhost?s=dafas&d=342")) } @Test - fun whenParamsAreValidNormalUrlMissingSchemeThenIsWebUrlIsTrue() { + fun `isWebUrl - params are valid normal url missing scheme - is true`() { assertTrue(isWebUrl("test.com?s=dafas&d=342")) } @Test - fun whenParamsAreValidIpAddressMissingSchemeThenIsWebUrlIsTrue() { + fun `isWebUrl - params are valid ip address missing scheme - is true`() { assertTrue(isWebUrl("121.33.2.11?s=dafas&d=342")) } @Test - fun whenParamsAreValidLocalhostMissingSchemeThenIsWebUrlIsTrue() { + fun `isWebUrl - params are valid localhost missing scheme - is true`() { assertTrue(isWebUrl("localhost?s=dafas&d=342")) } @Test - fun whenParamsAreValidContainsEncodedUriThenIsWebUrlIsTrue() { + fun `isWebUrl - params are valid contains encoded uri - is true`() { assertTrue(isWebUrl("https://m.facebook.com/?refsrc=https%3A%2F%2Fwww.facebook.com%2F&_rdr")) } @Test - fun whenGivenSimpleStringThenIsWebUrlIsFalse() { + fun `isWebUrl - given simple string - is false`() { assertFalse(isWebUrl("randomtext")) } @Test - fun whenGivenStringWithDotPrefixThenIsWebUrlIsFalse() { + fun `isWebUrl - given string with dot prefix - is false`() { assertFalse(isWebUrl(".randomtext")) } @Test - fun whenGivenStringWithDotSuffixThenIsWebUrlIsFalse() { + fun `isWebUrl - given string with dot suffix - is false`() { assertFalse(isWebUrl("randomtext.")) } @Test - fun whenGivenNumberThenIsWebUrlIsFalse() { + fun `isWebUrl - given number - is false`() { assertFalse(isWebUrl("33")) } @Test - fun whenNamedLocalMachineWithSchemeAndPortThenIsTrue() { + fun `isWebUrl - named local machine with scheme and port - is true`() { assertTrue(isWebUrl("http://raspberrypi:8080")) } @Test - fun whenNamedLocalMachineWithNoSchemeAndPortThenIsFalse() { + fun `isWebUrl - named local machine with no scheme and port - is false`() { assertFalse(isWebUrl("raspberrypi:8080")) } @Test - fun whenNamedLocalMachineWithSchemeNoPortThenIsTrue() { + fun `isWebUrl - named local machine with scheme no port - is true`() { assertTrue(isWebUrl("http://raspberrypi")) } @Test - fun whenStartsWithSiteSpecificSearchThenIsFalse() { + fun `isWebUrl - starts with site specific search - is false`() { assertFalse(isWebUrl("site:example.com")) } @Test - fun whenSchemeIsValidFtpButNotHttpThenNot() { + fun `isWebUrl - scheme is valid ftp but not http - not`() { assertFalse(isWebUrl("ftp://example.com")) } } diff --git a/app/src/test/java/com/duckduckgo/app/global/api/PixelParamRemovalInterceptorTest.kt b/app/src/test/java/com/duckduckgo/app/global/api/PixelParamRemovalInterceptorTest.kt index bfc5ccbd3909..05c448a9378e 100644 --- a/app/src/test/java/com/duckduckgo/app/global/api/PixelParamRemovalInterceptorTest.kt +++ b/app/src/test/java/com/duckduckgo/app/global/api/PixelParamRemovalInterceptorTest.kt @@ -46,7 +46,7 @@ class PixelParamRemovalInterceptorTest { } @Test - fun whenSendPixelRedactAppVersion() { + fun `sendPixel - redact app version - url query parameter`() { testPixels.filter { it.second == PixelParameter.removeVersion() }.map { it.first }.forEach { pixelName -> val pixelUrl = String.format(PIXEL_TEMPLATE, pixelName) val interceptedUrl = pixelRemovalInterceptor.intercept(FakeChain(pixelUrl)).request.url @@ -56,7 +56,7 @@ class PixelParamRemovalInterceptorTest { } @Test - fun whenSendPixelRedactAtb() { + fun `sendPixelRedactAtb - pixel removal interceptor - atb removed`() { testPixels.filter { it.second == PixelParameter.removeAtb() }.map { it.first }.forEach { pixelName -> val pixelUrl = String.format(PIXEL_TEMPLATE, pixelName) val interceptedUrl = pixelRemovalInterceptor.intercept(FakeChain(pixelUrl)).request.url @@ -66,7 +66,7 @@ class PixelParamRemovalInterceptorTest { } @Test - fun whenSendPixelRedactOSVersion() { + fun `sendPixel - redact OS version - atb and appVersion present, os_version absent`() { testPixels.filter { it.second == PixelParameter.removeOSVersion() }.map { it.first }.forEach { pixelName -> val pixelUrl = String.format(PIXEL_TEMPLATE, pixelName) val interceptedUrl = pixelRemovalInterceptor.intercept(FakeChain(pixelUrl)).request.url @@ -77,7 +77,7 @@ class PixelParamRemovalInterceptorTest { } @Test - fun whenSendPixelRedactAtbAndAppAndOSVersion() { + fun `sendPixelRedact - atb and app and os version - null`() { testPixels.filter { it.second.containsAll(PixelParameter.removeAll()) } .map { it.first } .forEach { pixelName -> diff --git a/app/src/test/java/com/duckduckgo/app/global/api/PixelReQueryInterceptorTest.kt b/app/src/test/java/com/duckduckgo/app/global/api/PixelReQueryInterceptorTest.kt index 1800b87ea93a..9f1d5b3c394f 100644 --- a/app/src/test/java/com/duckduckgo/app/global/api/PixelReQueryInterceptorTest.kt +++ b/app/src/test/java/com/duckduckgo/app/global/api/PixelReQueryInterceptorTest.kt @@ -32,7 +32,7 @@ class PixelReQueryInterceptorTest { } @Test - fun whenRq0PixelIsSendThenRemoveDeviceAndFormFactor() { + fun `intercept - Rq0PixelIsSend - remove device and form factor`() { assertEquals( EXPECTED_RQ_0_URL.toHttpUrl(), pixelReQueryInterceptor.intercept(FakeChain(RQ_0_PHONE_URL)).request.url, @@ -45,7 +45,7 @@ class PixelReQueryInterceptorTest { } @Test - fun whenRq1PixelIsSendThenRemoveDeviceAndFormFactor() { + fun `intercept - Rq1PixelIsSend - remove device and form factor`() { assertEquals( EXPECTED_RQ_1_URL.toHttpUrl(), pixelReQueryInterceptor.intercept(FakeChain(RQ_1_PHONE_URL)).request.url, @@ -58,7 +58,7 @@ class PixelReQueryInterceptorTest { } @Test - fun whenPixelOtherThanRqIsSendThenDoNotModify() { + fun `intercept - other pixel phone and tablet urls - does not modify`() { assertEquals( EXPECTED_OTHER_PIXEL_PHONE_URL.toHttpUrl(), pixelReQueryInterceptor.intercept(FakeChain(OTHER_PIXEL_PHONE_URL)).request.url, diff --git a/app/src/test/java/com/duckduckgo/app/global/install/AppInstallStoreTest.kt b/app/src/test/java/com/duckduckgo/app/global/install/AppInstallStoreTest.kt index b890346db9cf..b66a111a90a1 100644 --- a/app/src/test/java/com/duckduckgo/app/global/install/AppInstallStoreTest.kt +++ b/app/src/test/java/com/duckduckgo/app/global/install/AppInstallStoreTest.kt @@ -27,20 +27,20 @@ class AppInstallStoreTest { var testee: AppInstallStore = mock() @Test - fun whenInstallationTodayThenDayInstalledIsZero() { + fun `install - today - zero days installed`() { whenever(testee.installTimestamp).thenReturn(System.currentTimeMillis()) assertEquals(0, testee.daysInstalled()) } @Test - fun whenDayAfterInstallationThenDayInstalledIsOne() { + fun `install - day after installation - one`() { val timeSinceInstallation = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1) whenever(testee.installTimestamp).thenReturn(timeSinceInstallation) assertEquals(1, testee.daysInstalled()) } @Test - fun whenAWeekAfterInstallationThenDayInstalledIsSeven() { + fun `install - days installed seven`() { val timeSinceInstallation = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7) whenever(testee.installTimestamp).thenReturn(timeSinceInstallation) assertEquals(7, testee.daysInstalled()) diff --git a/app/src/test/java/com/duckduckgo/app/global/migrations/GpcMigrationPluginTest.kt b/app/src/test/java/com/duckduckgo/app/global/migrations/GpcMigrationPluginTest.kt index c1f150c423b6..5faa6d92a6d2 100644 --- a/app/src/test/java/com/duckduckgo/app/global/migrations/GpcMigrationPluginTest.kt +++ b/app/src/test/java/com/duckduckgo/app/global/migrations/GpcMigrationPluginTest.kt @@ -37,14 +37,14 @@ class GpcMigrationPluginTest { } @Test - fun whenRunIfPreviousSettingWasEnabledThenEnableGpc() { + fun `run - previous setting enabled - enable gpc`() { whenever(mockSettingsDataStore.globalPrivacyControlEnabled).thenReturn(true) testee.run() verify(mockGpc).enableGpc() } @Test - fun whenRunIfPreviousSettingWasDisabledThenDisableGpc() { + fun `run - previous setting disabled - disable gpc`() { whenever(mockSettingsDataStore.globalPrivacyControlEnabled).thenReturn(false) testee.run() verify(mockGpc).disableGpc() diff --git a/app/src/test/java/com/duckduckgo/app/global/migrations/MigrationLifecycleObserverTest.kt b/app/src/test/java/com/duckduckgo/app/global/migrations/MigrationLifecycleObserverTest.kt index 57179b1f2932..dc66f966d051 100644 --- a/app/src/test/java/com/duckduckgo/app/global/migrations/MigrationLifecycleObserverTest.kt +++ b/app/src/test/java/com/duckduckgo/app/global/migrations/MigrationLifecycleObserverTest.kt @@ -41,7 +41,7 @@ class MigrationLifecycleObserverTest { } @Test - fun whenMigrateIfStoredVersionIsLowerThanCurrentThenRunMigrations() { + fun `migrateIfStoredVersionIsLowerThanCurrent - run migrations`() { whenever(mockMigrationStore.version).thenReturn(CURRENT_VERSION - 1) testee.onCreate(mockOwner) @@ -51,7 +51,7 @@ class MigrationLifecycleObserverTest { } @Test - fun whenMigrateIfStoredVersionIsLowerThanCurrentThenStoreCurrentVersion() { + fun `migrateIfStoredVersionIsLowerThanCurrent - store current version`() { whenever(mockMigrationStore.version).thenReturn(CURRENT_VERSION - 1) testee.onCreate(mockOwner) @@ -60,7 +60,7 @@ class MigrationLifecycleObserverTest { } @Test - fun whenMigrateIfStoredVersionIsHigherThanCurrentThenDoNotRunMigrations() { + fun `onCreate - migrate if stored version is higher than current - do not run migrations`() { whenever(mockMigrationStore.version).thenReturn(CURRENT_VERSION + 1) testee.onCreate(mockOwner) @@ -70,7 +70,7 @@ class MigrationLifecycleObserverTest { } @Test - fun whenMigrateIfStoredVersionIsEqualsThanCurrentThenDoNotRunMigrations() { + fun `onCreate - stored version equals current - do not run migrations`() { whenever(mockMigrationStore.version).thenReturn(CURRENT_VERSION) testee.onCreate(mockOwner) diff --git a/app/src/test/java/com/duckduckgo/app/global/model/SiteMonitorTest.kt b/app/src/test/java/com/duckduckgo/app/global/model/SiteMonitorTest.kt index 90ca48438205..3223458ec27d 100644 --- a/app/src/test/java/com/duckduckgo/app/global/model/SiteMonitorTest.kt +++ b/app/src/test/java/com/duckduckgo/app/global/model/SiteMonitorTest.kt @@ -71,7 +71,7 @@ class SiteMonitorTest { private val mockBypassedSSLCertificatesRepository: BypassedSSLCertificatesRepository = mock() @Test - fun whenUrlIsHttpsThenHttpsStatusIsSecure() { + fun `whenUrlIsHttpsThenHttpsStatusIsSecure - https status secure`() { val testee = SiteMonitor( url = httpsDocument, title = null, @@ -85,7 +85,7 @@ class SiteMonitorTest { } @Test - fun whenUrlIsHttpThenHttpsStatusIsNone() { + fun `whenUrlIsHttpThenHttpsStatusIsNone - https status none`() { val testee = SiteMonitor( url = httpDocument, title = null, @@ -99,7 +99,7 @@ class SiteMonitorTest { } @Test - fun whenUrlIsHttpsWithHttpResourcesThenHttpsStatusIsMixed() { + fun `whenUrlIsHttpsWithHttpResourcesThenHttpsStatusIsMixed - has http resources - mixed`() { val testee = SiteMonitor( url = httpsDocument, title = null, @@ -114,7 +114,7 @@ class SiteMonitorTest { } @Test - fun whenUrlIsMalformedThenHttpsStatusIsNone() { + fun `whenUrlIsMalformedThenHttpsStatusIsNone - https status none`() { val testee = SiteMonitor( url = malformedDocument, title = null, @@ -128,7 +128,7 @@ class SiteMonitorTest { } @Test - fun whenSiteMonitorCreatedThenUrlIsCorrect() { + fun `SiteMonitor - url is correct`() { val testee = SiteMonitor( url = document, title = null, @@ -142,7 +142,7 @@ class SiteMonitorTest { } @Test - fun whenSiteMonitorCreatedThenTrackerCountIsZero() { + fun `whenSiteMonitorCreated - tracker count is zero`() { val testee = SiteMonitor( url = document, title = null, @@ -156,7 +156,7 @@ class SiteMonitorTest { } @Test - fun whenTrackersBlockedOrAllowedByUserAreDetectedThenTrackerCountIsIncremented() { + fun `trackerDetected - tracker count incremented`() { val testee = SiteMonitor( url = document, title = null, @@ -203,7 +203,7 @@ class SiteMonitorTest { } @Test - fun whenNoTrackersAllowedByUserAreDetectedThenAllTrackersBlockedIsTrue() { + fun `trackerDetected - all trackers blocked - true`() { val testee = SiteMonitor( url = document, title = null, @@ -250,7 +250,7 @@ class SiteMonitorTest { } @Test - fun whenAtLeastOneTrackersAllowedByUserIsDetectedThenAllTrackersBlockedIsFalse() { + fun `trackerDetected - at least one tracker allowed by user - all trackers blocked is false`() { val testee = SiteMonitor( url = document, title = null, @@ -297,7 +297,7 @@ class SiteMonitorTest { } @Test - fun whenNonMajorNetworkTrackerIsDetectedThenMajorNetworkCountIsZero() { + fun `trackerDetected - major network count zero`() { val testee = SiteMonitor( url = document, title = null, @@ -322,7 +322,7 @@ class SiteMonitorTest { } @Test - fun whenMajorNetworkTrackerIsDetectedThenMajorNetworkCountIsOne() { + fun `trackerDetected - major network tracker detected - one`() { val testee = SiteMonitor( url = document, title = null, @@ -347,7 +347,7 @@ class SiteMonitorTest { } @Test - fun whenDuplicateMajorNetworkIsDetectedThenMajorNetworkCountIsStillOne() { + fun `trackerDetected - duplicate major network detected - still one`() { val testee = SiteMonitor( url = document, title = null, @@ -383,7 +383,7 @@ class SiteMonitorTest { } @Test - fun whenSiteCreatedThenUpgradedHttpsIsFalse() { + fun `whenSiteCreated - site monitor upgraded https is false`() { val testee = SiteMonitor( url = document, title = null, @@ -397,7 +397,7 @@ class SiteMonitorTest { } @Test - fun whenSiteCreatedThenSurrogatesSizeIsZero() { + fun `whenSiteCreatedThenSurrogatesSizeIsZero - site created - size is zero`() { val testee = SiteMonitor( url = document, title = null, @@ -411,7 +411,7 @@ class SiteMonitorTest { } @Test - fun whenSurrogatesAreDetectedThenSurrogatesListIsIncremented() { + fun `surrogateDetected - surrogates list incremented`() { val testee = SiteMonitor( url = document, title = null, @@ -426,7 +426,7 @@ class SiteMonitorTest { } @Test - fun whenOtherDomainsAreLoadedThenOtherDomainsLoadedCountIsIncremented() { + fun `trackerDetected - other domains loaded count incremented`() { val testee = SiteMonitor( url = document, title = null, @@ -473,7 +473,7 @@ class SiteMonitorTest { } @Test - fun whenSpecialDomainsAreLoadedThenSpecialDomainsLoadedCountIsIncremented() { + fun `trackerDetected - special domains loaded count incremented`() { val testee = SiteMonitor( url = document, title = null, @@ -553,7 +553,7 @@ class SiteMonitorTest { } @Test - fun whenSiteBelongsToUserAllowListThenPrivacyShieldIsUnprotected() { + fun `whenSiteBelongsToUserAllowList - privacy shield unprotected`() { val testee = givenASiteMonitor(url = document) whenever(mockAllowListRepository.isDomainInUserAllowList(document)).thenReturn(true) @@ -561,21 +561,21 @@ class SiteMonitorTest { } @Test - fun whenSiteIsHttptThenPrivacyShieldIsUnprotected() { + fun `givenASiteMonitor - site is httpt - privacy shield unprotected`() { val testee = givenASiteMonitor(url = httpDocument) assertEquals(UNPROTECTED, testee.privacyProtection()) } @Test - fun whenSiteIsNotExceptionOrHttpButFullDetailsNotAvailableThenReturnUnkown() { + fun `whenSiteIsNotExceptionOrHttpButFullDetailsNotAvailableThenReturnUnknown - privacy protection unknown`() { val testee = givenASiteMonitor(url = httpsDocument) assertEquals(UNKNOWN, testee.privacyProtection()) } @Test - fun whenSiteIsMajorNetworkThenPrivacyShieldIsProtected() { + fun `updatePrivacyData - site is major network - privacy shield protected`() { val testee = givenASiteMonitor(url = httpsDocument) testee.updatePrivacyData(givenSitePrivacyData(entity = majorNetwork)) @@ -584,7 +584,7 @@ class SiteMonitorTest { } @Test - fun whenPrivacyIssuesNotFoundThenPrivacyShieldIsProtected() { + fun `updatePrivacyData - privacy issues not found - privacy shield protected`() { val testee = givenASiteMonitor(url = httpsDocument) testee.updatePrivacyData(givenSitePrivacyData(entity = network)) @@ -593,7 +593,7 @@ class SiteMonitorTest { } @Test - fun whenUserBypassedSslCertificateThenPrivacyShieldIsUnprotected() { + fun `whenUserBypassedSslCertificate - privacy shield unprotected`() { val testee = givenASiteMonitor(url = document) whenever(mockBypassedSSLCertificatesRepository.contains(document)).thenReturn(false) diff --git a/app/src/test/java/com/duckduckgo/app/global/rating/InitialPromptDeciderTest.kt b/app/src/test/java/com/duckduckgo/app/global/rating/InitialPromptDeciderTest.kt index d4b150ffd356..23f7601211fb 100644 --- a/app/src/test/java/com/duckduckgo/app/global/rating/InitialPromptDeciderTest.kt +++ b/app/src/test/java/com/duckduckgo/app/global/rating/InitialPromptDeciderTest.kt @@ -49,42 +49,42 @@ class InitialPromptDeciderTest { } @Test - fun whenUserHasNotSeenPromptBeforeAndNotUsedTheAppEnoughThenShouldNotSeePrompt() = runTest { + fun `shouldShowPrompt - user has not seen prompt before and not used the app enough - should not see prompt`() = runTest { whenever(mockAppDaysUsedRepository.getNumberOfDaysAppUsed()).thenReturn(NOT_ENOUGH_DAYS) whenever(mockAppEnjoymentRepository.canUserBeShownFirstPrompt()).thenReturn(true) assertFalse(testee.shouldShowPrompt()) } @Test - fun whenUserHasNotSeenPromptBeforeAndUsedTheAppExactEnoughDaysThenShouldSeePrompt() = runTest { + fun `shouldShowPrompt - user has not seen prompt before and used app exact enough days - should see prompt`() = runTest { whenever(mockAppDaysUsedRepository.getNumberOfDaysAppUsed()).thenReturn(EXACT_NUMBER_OF_DAYS) whenever(mockAppEnjoymentRepository.canUserBeShownFirstPrompt()).thenReturn(true) assertTrue(testee.shouldShowPrompt()) } @Test - fun whenUserHasNotSeenPromptBeforeAndUsedTheAppMoreThanEnoughDaysThenShouldSeePrompt() = runTest { + fun `shouldShowPrompt - user has not seen prompt before and used app more than enough days - should see prompt`() = runTest { whenever(mockAppDaysUsedRepository.getNumberOfDaysAppUsed()).thenReturn(MORE_THAN_ENOUGH_DAYS) whenever(mockAppEnjoymentRepository.canUserBeShownFirstPrompt()).thenReturn(true) assertTrue(testee.shouldShowPrompt()) } @Test - fun whenUserHasSeenPromptBeforeAndNotUsedTheAppEnoughThenShouldNotSeePrompt() = runTest { + fun `shouldShowPrompt - user has seen prompt before and not used app enough - should not see prompt`() = runTest { whenever(mockAppDaysUsedRepository.getNumberOfDaysAppUsed()).thenReturn(NOT_ENOUGH_DAYS) whenever(mockAppEnjoymentRepository.canUserBeShownFirstPrompt()).thenReturn(false) assertFalse(testee.shouldShowPrompt()) } @Test - fun whenUserHasSeenPromptBeforeAndUsedTheAppExactEnoughDaysThenShouldNotSeePrompt() = runTest { + fun `shouldShowPrompt - user has seen prompt before and used app exact enough days - should not see prompt`() = runTest { whenever(mockAppDaysUsedRepository.getNumberOfDaysAppUsed()).thenReturn(EXACT_NUMBER_OF_DAYS) whenever(mockAppEnjoymentRepository.canUserBeShownFirstPrompt()).thenReturn(false) assertFalse(testee.shouldShowPrompt()) } @Test - fun whenUserHasSeenPromptBeforeAndUsedTheAppMoreThanEnoughDaysThenShouldNotSeePrompt() = runTest { + fun `shouldShowPrompt - user has seen prompt before and used app more than enough days - should not see prompt`() = runTest { whenever(mockAppDaysUsedRepository.getNumberOfDaysAppUsed()).thenReturn(MORE_THAN_ENOUGH_DAYS) whenever(mockAppEnjoymentRepository.canUserBeShownFirstPrompt()).thenReturn(false) assertFalse(testee.shouldShowPrompt()) diff --git a/app/src/test/java/com/duckduckgo/app/global/rating/InitialPromptTypeDeciderTest.kt b/app/src/test/java/com/duckduckgo/app/global/rating/InitialPromptTypeDeciderTest.kt index 9d70779c9d17..29f856657adb 100644 --- a/app/src/test/java/com/duckduckgo/app/global/rating/InitialPromptTypeDeciderTest.kt +++ b/app/src/test/java/com/duckduckgo/app/global/rating/InitialPromptTypeDeciderTest.kt @@ -61,19 +61,19 @@ class InitialPromptTypeDeciderTest { } @Test - fun whenPlayNotInstalledThenNoPromptShown() = runTest { + fun `determineInitialPromptType - play not installed - no prompt shown`() = runTest { whenever(mockPlayStoreUtils.isPlayStoreInstalled()).thenReturn(false) assertPromptNotShown(testee.determineInitialPromptType()) } @Test - fun whenNotEnoughSearchesMadeThenNoPromptShown() = runTest { + fun `determineInitialPromptType - not enough searches made - no prompt shown`() = runTest { whenever(mockSearchCountDao.getSearchesMade()).thenReturn(0) assertPromptNotShown(testee.determineInitialPromptType()) } @Test - fun whenEnoughSearchesMadeAndFirstPromptNotShownBeforeThenShouldShowFirstPrompt() = runTest { + fun `determineInitialPromptType - enough searches made and first prompt not shown before - show first prompt`() = runTest { whenever(mockInitialPromptDecider.shouldShowPrompt()).thenReturn(true) whenever(mockSearchCountDao.getSearchesMade()).thenReturn(Long.MAX_VALUE) val type = testee.determineInitialPromptType() as AppEnjoymentPromptOptions.ShowEnjoymentPrompt diff --git a/app/src/test/java/com/duckduckgo/app/global/rating/SecondaryPromptDeciderTest.kt b/app/src/test/java/com/duckduckgo/app/global/rating/SecondaryPromptDeciderTest.kt index efd37903c63d..139ee7d714f9 100644 --- a/app/src/test/java/com/duckduckgo/app/global/rating/SecondaryPromptDeciderTest.kt +++ b/app/src/test/java/com/duckduckgo/app/global/rating/SecondaryPromptDeciderTest.kt @@ -49,20 +49,20 @@ class SecondaryPromptDeciderTest { } @Test - fun whenUserHasUsedTheAppForAWhileSinceSeeingFirstPromptThenTheySeeSecondPrompt() = runTest { + fun `shouldShowPrompt - user has used app for a while since seeing first prompt - sees second prompt`() = runTest { configureLotsOfAppUsage() assertTrue(testee.shouldShowPrompt()) } @Test - fun whenUserHasNotUsedTheAppMuchSinceSeeingFirstPromptThenTheyDoNotSeeSecondPrompt() = runTest { + fun `shouldShowPrompt - user has not used the app much since seeing first prompt - does not see second prompt`() = runTest { whenever(mockAppEnjoymentRepository.canUserBeShownSecondPrompt()).thenReturn(true) configureNotALotOfAppUsage() assertFalse(testee.shouldShowPrompt()) } @Test - fun whenUserHasAlreadyRatedOrGaveFeedbackThenTheyDoNoSeeASecondPromptEvenAfterALotOfUsage() = runTest { + fun `canUserBeShownSecondPrompt - user has already rated or given feedback - should not show prompt`() = runTest { whenever(mockAppEnjoymentRepository.canUserBeShownSecondPrompt()).thenReturn(false) configureLotsOfAppUsage() assertFalse(testee.shouldShowPrompt()) diff --git a/app/src/test/java/com/duckduckgo/app/global/uri/UriSubdomainRemoverTest.kt b/app/src/test/java/com/duckduckgo/app/global/uri/UriSubdomainRemoverTest.kt index 4e0ee1f69bbc..3a9d4e1f24e5 100644 --- a/app/src/test/java/com/duckduckgo/app/global/uri/UriSubdomainRemoverTest.kt +++ b/app/src/test/java/com/duckduckgo/app/global/uri/UriSubdomainRemoverTest.kt @@ -28,19 +28,19 @@ import org.junit.runner.RunWith class UriSubdomainRemoverTest { @Test - fun whenRemovingASubdomainWhenTwoAvailableThenOneIsReturned() { + fun `removeSubdomain - two available subdomains - one returned`() { val converted = Uri.parse("https://a.example.com").removeSubdomain() assertEquals("https://example.com", converted) } @Test - fun whenRemovingASubdomainWhenFiveAvailableThenFourAreReturned() { + fun `removeSubdomain - five available - four returned`() { val converted = Uri.parse("https://a.b.c.d.example.com").removeSubdomain() assertEquals("https://b.c.d.example.com", converted) } @Test - fun whenRemovingMultipleSubdomainCanKeepCalling() { + fun `removeSubdomain - multiple subdomains removed - keeps calling`() { val converted = Uri.parse("https://a.b.c.d.example.com") .removeSubdomain()!! .toUri().removeSubdomain()!! @@ -49,43 +49,43 @@ class UriSubdomainRemoverTest { } @Test - fun whenRemovingASubdomainWhenOnlyOneExistsThenReturnsNull() { + fun `removeSubdomain - only one subdomain exists - returns null`() { val converted = Uri.parse("https://example.com").removeSubdomain() assertNull(converted) } @Test - fun whenRemovingASubdomainWhenOnlyOneExistsButHasMultipartTldCoUkThenReturnsNull() { + fun `removeSubdomain - only one subdomain exists but has multipart TLD co·uk - returns null`() { val converted = Uri.parse("https://co.uk").removeSubdomain() assertNull(converted) } @Test - fun whenRemovingASubdomainWhenOnlyOneExistsButHasMultipartTldCoNzThenReturnsMultipartTld() { + fun `removeSubdomain - only one exists but has multipart TLD - returns multipart TLD`() { val converted = Uri.parse("https://co.za").removeSubdomain() assertNull(converted) } @Test - fun whenRemovingASubdomainWhenOnlyOneExistsButHasRecentTldThenReturnsNull() { + fun `removeSubdomain - recent TLD - returns null`() { val converted = Uri.parse("https://example.dev").removeSubdomain() assertNull(converted) } @Test - fun whenRemovingASubdomainWhenOnlyOneExistsButHasUnknownTldThenReturnsNull() { + fun `removeSubdomain - unknown TLD - returns null`() { val converted = Uri.parse("https://example.nonexistent").removeSubdomain() assertNull(converted) } @Test - fun whenRemovingASubdomainWhenUnknownTldThenReturnsNonExistentTld() { + fun `removeSubdomain - unknown TLD - returns non-existent TLD`() { val converted = Uri.parse("https://foo.example.nonexistent").removeSubdomain() assertEquals("https://example.nonexistent", converted) } @Test - fun whenRemovingSubdomainWhenUriIpAddressThenReturnsNull() { + fun `parse - uri ip address removed - returns null`() { val converted = Uri.parse("127.0.0.1").removeSubdomain() assertNull(converted) } diff --git a/app/src/test/java/com/duckduckgo/app/globalprivacycontrol/ui/GlobalPrivacyControlViewModelTest.kt b/app/src/test/java/com/duckduckgo/app/globalprivacycontrol/ui/GlobalPrivacyControlViewModelTest.kt index 398b273894b3..711c0386eb14 100644 --- a/app/src/test/java/com/duckduckgo/app/globalprivacycontrol/ui/GlobalPrivacyControlViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/globalprivacycontrol/ui/GlobalPrivacyControlViewModelTest.kt @@ -65,19 +65,19 @@ class GlobalPrivacyControlViewModelTest { } @Test - fun whenViewModelCreateThenInitialisedWithDefaultViewState() { + fun `whenViewModelCreate - initialised with default view state`() { val defaultViewState = GlobalPrivacyControlViewModel.ViewState() verify(mockViewStateObserver, atLeastOnce()).onChanged(viewStateCaptor.capture()) assertEquals(defaultViewState, viewStateCaptor.value) } @Test - fun whenViewModelCreateThenPixelSent() { + fun `viewModelCreate - pixel sent - settings do not sell shown`() { verify(mockPixel).fire(AppPixelName.SETTINGS_DO_NOT_SELL_SHOWN) } @Test - fun whenOnLearnMoreSelectedThenOpenLearnMoreCommandIssuedWithCorrectUrl() { + fun `onLearnMoreSelected - command observer issued with open learn more`() { testee.onLearnMoreSelected() verify(mockCommandObserver, atLeastOnce()).onChanged(commandCaptor.capture()) @@ -85,35 +85,35 @@ class GlobalPrivacyControlViewModelTest { } @Test - fun whenOnUserToggleGlobalPrivacyControlThenDoNotSellOnPixelSent() { + fun `onUserToggleGlobalPrivacyControl - do not sell on pixel sent`() { testee.onUserToggleGlobalPrivacyControl(true) verify(mockPixel).fire(AppPixelName.SETTINGS_DO_NOT_SELL_ON) } @Test - fun whenOnUserToggleGlobalPrivacyControlThenDoNotSellOffPixelSent() { + fun `onUserToggleGlobalPrivacyControl - do not sell off pixel sent`() { testee.onUserToggleGlobalPrivacyControl(false) verify(mockPixel).fire(AppPixelName.SETTINGS_DO_NOT_SELL_OFF) } @Test - fun whenOnUserToggleGlobalPrivacyControlSwitchedOnThenValueStoredInSettings() { + fun `onUserToggleGlobalPrivacyControl - gpc enabled - value stored in settings`() { testee.onUserToggleGlobalPrivacyControl(true) verify(mockGpc).enableGpc() } @Test - fun whenOnUserToggleGlobalPrivacyControlSwitchedOffThenValueStoredInSettings() { + fun `onUserToggleGlobalPrivacyControl - gpc disabled - value stored in settings`() { testee.onUserToggleGlobalPrivacyControl(false) verify(mockGpc).disableGpc() } @Test - fun whenOnUserToggleGlobalPrivacyControlSwitchedOnThenViewStateUpdatedToTrue() { + fun `onUserToggleGlobalPrivacyControl - view state updated - true`() { testee.onUserToggleGlobalPrivacyControl(true) verify(mockViewStateObserver, atLeastOnce()).onChanged(viewStateCaptor.capture()) @@ -121,7 +121,7 @@ class GlobalPrivacyControlViewModelTest { } @Test - fun whenOnUserToggleGlobalPrivacyControlSwitchedOnThenViewStateUpdatedToFalse() { + fun `onUserToggleGlobalPrivacyControl - view state updated - false`() { testee.onUserToggleGlobalPrivacyControl(false) verify(mockViewStateObserver, atLeastOnce()).onChanged(viewStateCaptor.capture()) diff --git a/app/src/test/java/com/duckduckgo/app/job/WorkSchedulerTest.kt b/app/src/test/java/com/duckduckgo/app/job/WorkSchedulerTest.kt index 1ea27c92d142..4820f080c637 100644 --- a/app/src/test/java/com/duckduckgo/app/job/WorkSchedulerTest.kt +++ b/app/src/test/java/com/duckduckgo/app/job/WorkSchedulerTest.kt @@ -44,7 +44,7 @@ class WorkSchedulerTest { } @Test - fun schedulesNextNotificationAndCleansDeprecatedJobs() = runTest { + fun `schedulesNextNotification - cleans deprecated jobs`() = runTest { testee.onResume(mockOwner) verify(notificationScheduler).scheduleNextNotification() diff --git a/app/src/test/java/com/duckduckgo/app/launch/LaunchViewModelTest.kt b/app/src/test/java/com/duckduckgo/app/launch/LaunchViewModelTest.kt index 595361186e68..3ee422c5deaf 100644 --- a/app/src/test/java/com/duckduckgo/app/launch/LaunchViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/launch/LaunchViewModelTest.kt @@ -55,7 +55,7 @@ class LaunchViewModelTest { } @Test - fun whenOnboardingShouldShowAndReferrerDataReturnsQuicklyThenCommandIsOnboarding() = runTest { + fun `determineViewToShow - onboarding should show and referrer data returns quickly - command is onboarding`() = runTest { testee = LaunchViewModel( userStageStore, StubAppReferrerFoundStateListener("xx"), @@ -70,7 +70,7 @@ class LaunchViewModelTest { } @Test - fun whenOnboardingShouldShowAndReferrerDataReturnsButNotInstantlyThenCommandIsOnboarding() = runTest { + fun `determineViewToShow - onboarding should show and referrer data returns but not instantly - command is onboarding`() = runTest { testee = LaunchViewModel( userStageStore, StubAppReferrerFoundStateListener("xx", mockDelayMs = 1_000), @@ -85,7 +85,7 @@ class LaunchViewModelTest { } @Test - fun whenOnboardingShouldShowAndReferrerDataTimesOutThenCommandIsOnboarding() = runTest { + fun `determineViewToShow - onboarding should show and referrer data times out - command is onboarding`() = runTest { testee = LaunchViewModel( userStageStore, StubAppReferrerFoundStateListener("xx", mockDelayMs = Long.MAX_VALUE), @@ -100,7 +100,7 @@ class LaunchViewModelTest { } @Test - fun whenOnboardingShouldNotShowAndReferrerDataReturnsQuicklyThenCommandIsHome() = runTest { + fun `determineViewToShow - onboarding should not show and referrer data returns quickly - command is home`() = runTest { testee = LaunchViewModel(userStageStore, StubAppReferrerFoundStateListener("xx"), mockExtendedOnboardingExperimentVariantManager) whenever(userStageStore.getUserAppStage()).thenReturn(AppStage.DAX_ONBOARDING) testee.command.observeForever(mockCommandObserver) @@ -109,7 +109,7 @@ class LaunchViewModelTest { } @Test - fun whenOnboardingShouldNotShowAndReferrerDataReturnsButNotInstantlyThenCommandIsHome() = runTest { + fun `determineViewToShow - onboarding should not show and referrer data returns but not instantly - command is home`() = runTest { testee = LaunchViewModel( userStageStore, StubAppReferrerFoundStateListener("xx", mockDelayMs = 1_000), @@ -122,7 +122,7 @@ class LaunchViewModelTest { } @Test - fun whenOnboardingShouldNotShowAndReferrerDataTimesOutThenCommandIsHome() = runTest { + fun `determineViewToShow - onboarding times out - command is home`() = runTest { testee = LaunchViewModel( userStageStore, StubAppReferrerFoundStateListener("xx", mockDelayMs = Long.MAX_VALUE), diff --git a/app/src/test/java/com/duckduckgo/app/location/data/LocationPermissionEntityTest.kt b/app/src/test/java/com/duckduckgo/app/location/data/LocationPermissionEntityTest.kt index 9705b0a62b75..20faecf692fb 100644 --- a/app/src/test/java/com/duckduckgo/app/location/data/LocationPermissionEntityTest.kt +++ b/app/src/test/java/com/duckduckgo/app/location/data/LocationPermissionEntityTest.kt @@ -23,28 +23,28 @@ import org.junit.Test class LocationPermissionEntityTest { @Test - fun whenDomainStartsWithHttpsThenDropPrefix() { + fun `whenDomainStartsWithHttpsThenDropPrefix - for fireproofing - www example com`() { val locationPermissionEntity = LocationPermissionEntity("https://www.example.com/", LocationPermissionType.ALLOW_ONCE) val host = locationPermissionEntity.forFireproofing() Assert.assertEquals("www.example.com", host) } @Test - fun whenDomainStartsWithHttpsUppercaseThenDropPrefix() { + fun `whenDomainStartsWithHttpsUppercaseThenDropPrefix - for fireproofing - www example com`() { val locationPermissionEntity = LocationPermissionEntity("HTTPS://www.example.com/", LocationPermissionType.ALLOW_ONCE) val host = locationPermissionEntity.forFireproofing() Assert.assertEquals("www.example.com", host) } @Test - fun whenDomainDoesNotStartWithHttpsThenDomainUnchanged() { + fun `whenDomainDoesNotStartWithHttpsThenDomainUnchanged - for fireproofing - unchanged`() { val locationPermissionEntity = LocationPermissionEntity("mobile.example.com/", LocationPermissionType.ALLOW_ONCE) val host = locationPermissionEntity.forFireproofing() Assert.assertEquals("mobile.example.com/", host) } @Test - fun whenDomainIsReturnedAsPermissionOriginThenDomainMatches() { + fun `asLocationPermissionOrigin - domain matches`() { val domain = "www.example.com" val host = domain.asLocationPermissionOrigin() Assert.assertEquals("https://www.example.com/", host) diff --git a/app/src/test/java/com/duckduckgo/app/notification/AndroidSchedulerNotificationTest.kt b/app/src/test/java/com/duckduckgo/app/notification/AndroidSchedulerNotificationTest.kt index 3517962a5c1e..122ff871e09f 100644 --- a/app/src/test/java/com/duckduckgo/app/notification/AndroidSchedulerNotificationTest.kt +++ b/app/src/test/java/com/duckduckgo/app/notification/AndroidSchedulerNotificationTest.kt @@ -92,7 +92,7 @@ class AndroidNotificationSchedulerTest { } @Test - fun whenPrivacyNotificationClearDataCanShowThenPrivacyNotificationIsScheduled() = runTest { + fun `scheduleNextNotification - privacy notification clear data can show - is scheduled`() = runTest { whenever(mockPrivacyNotification.canShow()).thenReturn(true) whenever(mockClearNotification.canShow()).thenReturn(true) @@ -102,7 +102,7 @@ class AndroidNotificationSchedulerTest { } @Test - fun whenPrivacyNotificationCanShowButClearDataCannotThenPrivacyNotificationIsScheduled() = runTest { + fun `scheduleNextNotification - privacy notification can show but clear data cannot - is scheduled`() = runTest { whenever(mockPrivacyNotification.canShow()).thenReturn(true) whenever(mockClearNotification.canShow()).thenReturn(false) @@ -112,7 +112,7 @@ class AndroidNotificationSchedulerTest { } @Test - fun whenPrivacyNotificationCannotShowAndClearNotificationCanShowThenClearNotificationIsScheduled() = runTest { + fun `scheduleNextNotification - privacy notification cannot show and clear notification can show - clear notification is scheduled`() = runTest { whenever(mockPrivacyNotification.canShow()).thenReturn(false) whenever(mockClearNotification.canShow()).thenReturn(true) @@ -122,7 +122,7 @@ class AndroidNotificationSchedulerTest { } @Test - fun whenPrivacyNotificationAndClearNotificationCannotShowThenNoNotificationScheduled() = runTest { + fun `scheduleNextNotification - privacy and clear notifications cannot show - no notification scheduled`() = runTest { whenever(mockPrivacyNotification.canShow()).thenReturn(false) whenever(mockClearNotification.canShow()).thenReturn(false) diff --git a/app/src/test/java/com/duckduckgo/app/onboarding/store/AppUserStageStoreTest.kt b/app/src/test/java/com/duckduckgo/app/onboarding/store/AppUserStageStoreTest.kt index 4348155fdd73..7cacc174eff5 100644 --- a/app/src/test/java/com/duckduckgo/app/onboarding/store/AppUserStageStoreTest.kt +++ b/app/src/test/java/com/duckduckgo/app/onboarding/store/AppUserStageStoreTest.kt @@ -34,7 +34,7 @@ class AppUserStageStoreTest { private val testee = AppUserStageStore(userStageDao, coroutineRule.testDispatcherProvider) @Test - fun whenGetUserAppStageThenReturnCurrentStage() = runTest { + fun `getUserAppStage - get current stage - returns Dax Onboarding`() = runTest { givenCurrentStage(AppStage.DAX_ONBOARDING) val userAppStage = testee.getUserAppStage() @@ -43,7 +43,7 @@ class AppUserStageStoreTest { } @Test - fun whenStageNewCompletedThenStageDaxOnboardingReturned() = runTest { + fun `stageCompleted - stage new completed - stage Dax onboarding returned`() = runTest { givenCurrentStage(AppStage.NEW) val nextStage = testee.stageCompleted(AppStage.NEW) @@ -52,7 +52,7 @@ class AppUserStageStoreTest { } @Test - fun whenStageDaxOnboardingCompletedThenStageEstablishedReturned() = runTest { + fun `stageCompleted - stage Dax onboarding completed - established returned`() = runTest { givenCurrentStage(AppStage.DAX_ONBOARDING) val nextStage = testee.stageCompleted(AppStage.DAX_ONBOARDING) @@ -61,7 +61,7 @@ class AppUserStageStoreTest { } @Test - fun whenStageEstablishedCompletedThenStageEstablishedReturned() = runTest { + fun `stageCompleted - stage established completed - stage established returned`() = runTest { givenCurrentStage(AppStage.ESTABLISHED) val nextStage = testee.stageCompleted(AppStage.ESTABLISHED) @@ -70,7 +70,7 @@ class AppUserStageStoreTest { } @Test - fun whenMoveToStageThenUpdateUserStageInDao() = runTest { + fun `moveToStage - update user stage in dao`() = runTest { testee.moveToStage(AppStage.DAX_ONBOARDING) verify(userStageDao).updateUserStage(AppStage.DAX_ONBOARDING) } diff --git a/app/src/test/java/com/duckduckgo/app/onboarding/ui/OnboardingPageManagerTest.kt b/app/src/test/java/com/duckduckgo/app/onboarding/ui/OnboardingPageManagerTest.kt index f0e497f1f418..62405b199b5d 100644 --- a/app/src/test/java/com/duckduckgo/app/onboarding/ui/OnboardingPageManagerTest.kt +++ b/app/src/test/java/com/duckduckgo/app/onboarding/ui/OnboardingPageManagerTest.kt @@ -45,7 +45,7 @@ class OnboardingPageManagerTest { } @Test - fun whenDDGIsNotDefaultBrowserThenExpectedOnboardingPagesAreTwo() { + fun `buildPageBlueprints - DDG not default browser - expected onboarding pages are two`() { configureDeviceSupportsDefaultBrowser() whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(false) whenever(defaultRoleBrowserDialog.shouldShowDialog()).thenReturn(false) @@ -56,7 +56,7 @@ class OnboardingPageManagerTest { } @Test - fun whenDDGIsNotDefaultBrowserAndShouldShowBrowserDialogThenExpectedOnboardingPagesAre1() { + fun `buildPageBlueprints - DDG not default browser and should show browser dialog - expected onboarding pages are 1`() { configureDeviceSupportsDefaultBrowser() whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(false) whenever(defaultRoleBrowserDialog.shouldShowDialog()).thenReturn(true) @@ -67,7 +67,7 @@ class OnboardingPageManagerTest { } @Test - fun whenDDGAsDefaultBrowserThenSinglePageOnBoarding() { + fun `buildPageBlueprints - default browser - single page onboarding`() { configureDeviceSupportsDefaultBrowser() whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(true) whenever(defaultRoleBrowserDialog.shouldShowDialog()).thenReturn(false) @@ -78,7 +78,7 @@ class OnboardingPageManagerTest { } @Test - fun whenDDGAsDefaultBrowserAndShouldShowBrowserDialogThenSinglePageOnBoarding() { + fun `buildPageBlueprints - default browser and dialog - single page onboarding`() { configureDeviceSupportsDefaultBrowser() whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(true) whenever(defaultRoleBrowserDialog.shouldShowDialog()).thenReturn(true) @@ -89,7 +89,7 @@ class OnboardingPageManagerTest { } @Test - fun whenDeviceDoesNotSupportDefaultBrowserThenSinglePageOnBoarding() { + fun `buildPageBlueprints - device does not support default browser - single page onboarding`() { configureDeviceDoesNotSupportDefaultBrowser() whenever(defaultRoleBrowserDialog.shouldShowDialog()).thenReturn(false) @@ -99,7 +99,7 @@ class OnboardingPageManagerTest { } @Test - fun whenDeviceDoesNotSupportDefaultBrowserAndShouldShowBrowserDialogThenSinglePageOnBoarding() { + fun `buildPageBlueprints - device does not support default browser and should show browser dialog - single page onboarding`() { configureDeviceDoesNotSupportDefaultBrowser() whenever(defaultRoleBrowserDialog.shouldShowDialog()).thenReturn(true) diff --git a/app/src/test/java/com/duckduckgo/app/onboarding/ui/OnboardingViewModelTest.kt b/app/src/test/java/com/duckduckgo/app/onboarding/ui/OnboardingViewModelTest.kt index 263e655c3fb7..2569c7b9ffbb 100644 --- a/app/src/test/java/com/duckduckgo/app/onboarding/ui/OnboardingViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/onboarding/ui/OnboardingViewModelTest.kt @@ -45,7 +45,7 @@ class OnboardingViewModelTest { } @Test - fun whenOnboardingDoneThenCompleteStage() = runTest { + fun `onOnboardingDone - user stage store completed - new stage`() = runTest { testee.onOnboardingDone() verify(userStageStore).stageCompleted(AppStage.NEW) } diff --git a/app/src/test/java/com/duckduckgo/app/onboarding/ui/page/DefaultBrowserPageViewModelTest.kt b/app/src/test/java/com/duckduckgo/app/onboarding/ui/page/DefaultBrowserPageViewModelTest.kt index a2aad34587be..934af9dbbbe1 100644 --- a/app/src/test/java/com/duckduckgo/app/onboarding/ui/page/DefaultBrowserPageViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/onboarding/ui/page/DefaultBrowserPageViewModelTest.kt @@ -75,7 +75,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenInitializingIfThereIsADefaultBrowserThenShowSettingsUI() { + fun `whenInitializingIfThereIsADefaultBrowserThenShowSettingsUI - view state set to default browser settings UI`() { whenever(mockDefaultBrowserDetector.hasDefaultBrowser()).thenReturn(true) testee = DefaultBrowserPageViewModel(mockDefaultBrowserDetector, mockPixel, mockInstallStore) @@ -84,7 +84,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenInitializingIfThereIsNotADefaultBrowserThenShowDialogUI() { + fun `initialize - no default browser - show dialog UI`() { whenever(mockDefaultBrowserDetector.hasDefaultBrowser()).thenReturn(false) testee = DefaultBrowserPageViewModel(mockDefaultBrowserDetector, mockPixel, mockInstallStore) @@ -93,7 +93,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenLoadUiThenShowSettingsUiIfDefaultBrowserIsTrue() { + fun `loadUI - show settings UI if default browser true`() { whenever(mockDefaultBrowserDetector.hasDefaultBrowser()).thenReturn(true) testee.loadUI() @@ -102,7 +102,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenLoadUiThenShowDialogUiIfDefaultBrowserIsFalse() { + fun `loadUI - default browser false - show dialog ui`() { whenever(mockDefaultBrowserDetector.hasDefaultBrowser()).thenReturn(false) testee.loadUI() @@ -111,7 +111,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenLoadUIAfterDefaultButtonClickedThenSameState() { + fun `loadUI - same state`() { whenever(mockDefaultBrowserDetector.hasDefaultBrowser()).thenReturn(false) testee.loadUI() testee.onDefaultBrowserClicked() @@ -123,7 +123,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenContinueButtonClickedWithoutTryingToSetDDGAsDefaultThenSendPixelAndExecuteContinueToBrowserCommand() { + fun `onContinueToBrowser - no default browser set - send pixel and execute continue to browser command`() { whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(false) testee.loadUI() @@ -133,7 +133,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenDefaultButtonClickedWithDefaultBrowserThenExecuteOpenSettingsCommandAndFireDefaultBrowserLaunchedPixel() { + fun `onDefaultBrowserClicked - default browser launched - open settings command executed`() { whenever(mockDefaultBrowserDetector.hasDefaultBrowser()).thenReturn(true) val params = mapOf( Pixel.PixelParameter.DEFAULT_BROWSER_BEHAVIOUR_TRIGGERED to DEFAULT_BROWSER_SETTINGS, @@ -146,7 +146,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenDefaultButtonClickedWithoutDefaultBrowserThenExecuteOpenDialogCommandAndShowInstructionsCard() { + fun `onDefaultButtonClicked - without default browser - execute open dialog command and show instructions card`() { whenever(mockDefaultBrowserDetector.hasDefaultBrowser()).thenReturn(false) testee.loadUI() @@ -157,7 +157,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenUserSetDDGAsDefaultFromDialogThenContinueToBrowserAndFirePixel() { + fun `loadUI - default browser set from dialog - continue to browser and fire pixel`() { val params = mapOf( Pixel.PixelParameter.DEFAULT_BROWSER_SET_FROM_ONBOARDING to true.toString(), Pixel.PixelParameter.DEFAULT_BROWSER_SET_ORIGIN to DEFAULT_BROWSER_DIALOG, @@ -173,7 +173,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenUserSetDDGAsJustOnceForFirstTimeThenShowInstructionsAgainOpenDialogAndFirePixel() { + fun `whenUserSetDDGAsJustOnceForFirstTime - show instructions again open dialog and fire pixel - show default browser dialog and fire pixel`() { whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(false) testee.loadUI() testee.onDefaultBrowserClicked() @@ -186,7 +186,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenUserSetDDGAsJustOnceTheMaxAllowedTimesThenTakeUserToBrowser() { + fun `whenUserSetDDGAsJustOnceTheMaxAllowedTimesThenTakeUserToBrowser - handle result - take user to browser`() { whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(false) val params = mapOf( Pixel.PixelParameter.DEFAULT_BROWSER_SET_ORIGIN to Pixel.PixelValues.DEFAULT_BROWSER_JUST_ONCE_MAX, @@ -202,7 +202,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenUserDismissedDialogThenShowDialogUIAndFirePixel() { + fun `whenUserDismissedDialog - show dialog UI and fire pixel`() { whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(false) whenever(mockDefaultBrowserDetector.hasDefaultBrowser()).thenReturn(false) val params = mapOf( @@ -218,7 +218,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenUserSetAnotherBrowserAsDefaultThenShowSettingsUI() { + fun `onDefaultBrowserClicked - show settings UI`() { val params = mapOf( Pixel.PixelParameter.DEFAULT_BROWSER_SET_ORIGIN to Pixel.PixelValues.DEFAULT_BROWSER_EXTERNAL, ) @@ -234,7 +234,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenUserSetDDGAsDefaultThenContinueToBrowser() { + fun `whenUserSetDDGAsDefaultThenContinueToBrowser - continue to browser`() { val params = mapOf( Pixel.PixelParameter.DEFAULT_BROWSER_SET_FROM_ONBOARDING to true.toString(), Pixel.PixelParameter.DEFAULT_BROWSER_SET_ORIGIN to Pixel.PixelValues.DEFAULT_BROWSER_EXTERNAL, @@ -251,7 +251,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenUserWasTakenToSettingsAndSelectedDDGAsDefaultThenContinueToBrowser() { + fun `loadUI - settings selected DDG as default - continue to browser`() { whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(false) whenever(mockDefaultBrowserDetector.hasDefaultBrowser()).thenReturn(true) testee.loadUI() @@ -264,7 +264,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenUserWasTakenToSettingsAndDidNotSelectDDGAsDefaultThenShowSettingsUI() { + fun `loadUI - settings UI shown`() { whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(false) whenever(mockDefaultBrowserDetector.hasDefaultBrowser()).thenReturn(true) testee.loadUI() @@ -276,7 +276,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenUserSelectedDDGAsDefaultInSettingsScreenThenFirePixel() { + fun `loadUI - settings screen - fire pixel`() { whenever(mockDefaultBrowserDetector.hasDefaultBrowser()).thenReturn(true) val params = mapOf( Pixel.PixelParameter.DEFAULT_BROWSER_SET_FROM_ONBOARDING to true.toString(), @@ -292,7 +292,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenUserDoesNotSelectedDDGAsDefaultInSettingsThenFirePixel() { + fun `loadUI - default browser not set - fire pixel`() { whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(false) whenever(mockDefaultBrowserDetector.hasDefaultBrowser()).thenReturn(true) val params = mapOf( @@ -307,7 +307,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenOriginReceivedIsSettingsThenResetTimesPressedJustOnce() { + fun `handleResult - origin received is settings - reset times pressed just once`() { testee.loadUI() testee.timesPressedJustOnce = 1 @@ -317,7 +317,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenOriginReceivedIsDialogDismissedThenResetTimesPressedJustOnce() { + fun `handleResult - origin received is dialog dismissed - reset times pressed just once`() { testee.loadUI() testee.timesPressedJustOnce = 1 @@ -327,7 +327,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenOriginReceivedIsExternalBrowserThenResetTimesPressedJustOnce() { + fun `handleResult - origin received is external browser - reset times pressed just once`() { testee.timesPressedJustOnce = 1 testee.handleResult(Origin.ExternalBrowser) @@ -336,7 +336,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenOriginReceivedIsInternalBrowserAndDDGIsTheDefaultBrowserThenResetTimesPressedJustOnce() { + fun `handleResult - origin received is internal browser and default browser - reset times pressed just once`() { whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(true) testee.timesPressedJustOnce = 1 @@ -346,7 +346,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenOriginReceivedIsInternalBrowserAndDDGIsNotTheDefaultBrowserThenIncreaseTimesPressedJustOnceIfIsLessThanTheMaxNumberOfAttempts() { + fun `handleResult - origin received is internal browser and DDG is not the default browser - increase times pressed just once if less than max number of attempts`() { whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(false) testee.timesPressedJustOnce = 1 @@ -356,7 +356,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenOriginReceivedIsInternalBrowserAndDDGIsNotTheDefaultBrowserThenResetTimesPressedJustOnceIfIsGreaterOrEqualThanTheMaxNumberOfAttempts() { + fun `handleResult - origin received is internal browser and DDG is not default browser - reset times pressed just once if greater or equal to max number of attempts`() { whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(false) testee.timesPressedJustOnce = MAX_DIALOG_ATTEMPTS diff --git a/app/src/test/java/com/duckduckgo/app/onboarding/ui/page/WelcomePageViewModelTest.kt b/app/src/test/java/com/duckduckgo/app/onboarding/ui/page/WelcomePageViewModelTest.kt index 5e2f08c9067f..f4bc47722a13 100644 --- a/app/src/test/java/com/duckduckgo/app/onboarding/ui/page/WelcomePageViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/onboarding/ui/page/WelcomePageViewModelTest.kt @@ -81,7 +81,7 @@ class WelcomePageViewModelTest { } @Test - fun whenOnPrimaryCtaClickedAndShouldNotShowDialogThenFireAndFinish() = runTest { + fun `onPrimaryCtaClicked - should not show dialog - fire and finish`() = runTest { whenever(defaultRoleBrowserDialog.shouldShowDialog()).thenReturn(false) events.emit(WelcomePageView.Event.OnPrimaryCtaClicked) @@ -92,7 +92,7 @@ class WelcomePageViewModelTest { } @Test - fun whenOnPrimaryCtaClickedAndShouldShowDialogAndShowThenFireAndEmitShowDialog() = runTest { + fun `onPrimaryCtaClicked - should show dialog and show - fire and emit show dialog`() = runTest { whenever(defaultRoleBrowserDialog.shouldShowDialog()).thenReturn(true) val intent = Intent() whenever(defaultRoleBrowserDialog.createIntent(any())).thenReturn(intent) @@ -105,7 +105,7 @@ class WelcomePageViewModelTest { } @Test - fun whenOnPrimaryCtaClickedAndShouldShowDialogNullIntentThenFireAndFinish() = runTest { + fun `onPrimaryCtaClicked - should show dialog null intent - fire and finish`() = runTest { whenever(defaultRoleBrowserDialog.shouldShowDialog()).thenReturn(true) whenever(defaultRoleBrowserDialog.createIntent(any())).thenReturn(null) @@ -118,7 +118,7 @@ class WelcomePageViewModelTest { } @Test - fun whenOnDefaultBrowserSetThenCallDialogShownFireAndFinish() = runTest { + fun `onDefaultBrowserSet - call dialog shown fire and finish`() = runTest { events.emit(WelcomePageView.Event.OnDefaultBrowserSet) viewEvents.test { @@ -134,7 +134,7 @@ class WelcomePageViewModelTest { } @Test - fun whenOnDefaultBrowserNotSetThenCallDialogShownFireAndFinish() = runTest { + fun `onDefaultBrowserNotSet - call dialog shown fire and finish`() = runTest { events.emit(WelcomePageView.Event.OnDefaultBrowserNotSet) viewEvents.test { diff --git a/app/src/test/java/com/duckduckgo/app/permissions/PermissionsViewModelTest.kt b/app/src/test/java/com/duckduckgo/app/permissions/PermissionsViewModelTest.kt index 54dc6b06a23c..4ce15d023b19 100644 --- a/app/src/test/java/com/duckduckgo/app/permissions/PermissionsViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/permissions/PermissionsViewModelTest.kt @@ -63,7 +63,7 @@ class PermissionsViewModelTest { } @Test - fun whenStartNotCalledYetThenViewStateInitialisedDefaultValues() = runTest { + fun `viewState - initialises default values`() = runTest { testee.viewState().test { val value = awaitItem() assertTrue(value.autoCompleteSuggestionsEnabled) @@ -73,7 +73,7 @@ class PermissionsViewModelTest { } @Test - fun whenStartCalledWithNotificationsEnabledThenNotificationsSettingSubtitleSetCorrectlyAsEnabled() = runTest { + fun `start - notifications setting subtitle set correctly as enabled`() = runTest { testee.start(notificationsEnabled = true) testee.viewState().test { @@ -86,7 +86,7 @@ class PermissionsViewModelTest { } @Test - fun whenStartCalledWithNotificationsDisabledThenNotificationsSettingSubtitleSetCorrectlyAsDisabled() = runTest { + fun `start - notifications disabled - notifications setting subtitle set correctly as disabled`() = runTest { testee.start(notificationsEnabled = false) testee.viewState().test { @@ -99,7 +99,7 @@ class PermissionsViewModelTest { } @Test - fun whenAppLinksSetToAskEverytimeThenDataStoreIsUpdatedAndPixelIsSent() { + fun `onAppLinksSettingChanged - data store updated and pixel sent`() { testee.onAppLinksSettingChanged(AppLinkSettingType.ASK_EVERYTIME) verify(mockAppSettingsDataStore).appLinksEnabled = true @@ -126,7 +126,7 @@ class PermissionsViewModelTest { } @Test - fun whenOnSitePermissionsClickedThenEmitCommandLaunchLocationAndPixelFired() = runTest { + fun `onSitePermissionsClicked - emit command launch location and pixel fired`() = runTest { testee.commands().test { testee.onSitePermissionsClicked() @@ -138,7 +138,7 @@ class PermissionsViewModelTest { } @Test - fun whenUserRequestedToChangeNotificationsSettingThenEmitCommandLaunchNotificationsSettingsAndSendPixel() = runTest { + fun `userRequestedToChangeNotificationsSetting - emit command launch notifications settings and send pixel`() = runTest { testee.commands().test { testee.userRequestedToChangeNotificationsSetting() @@ -150,7 +150,7 @@ class PermissionsViewModelTest { } @Test - fun whenUserRequestedToChangeAppLinkSettingThenEmitCommandLaunchAppLinkSettings() = runTest { + fun `userRequestedToChangeAppLinkSetting - emit command launch app link settings`() = runTest { testee.commands().test { testee.userRequestedToChangeAppLinkSetting() diff --git a/app/src/test/java/com/duckduckgo/app/pixels/EnqueuedPixelWorkerTest.kt b/app/src/test/java/com/duckduckgo/app/pixels/EnqueuedPixelWorkerTest.kt index 2adfdc88ad77..b2798c54c30d 100644 --- a/app/src/test/java/com/duckduckgo/app/pixels/EnqueuedPixelWorkerTest.kt +++ b/app/src/test/java/com/duckduckgo/app/pixels/EnqueuedPixelWorkerTest.kt @@ -69,7 +69,7 @@ class EnqueuedPixelWorkerTest { } @Test - fun whenOnCreateAndPendingPixelCountClearDataThenScheduleWorkerToFireMf() { + fun `onCreate - pending pixel count clear data - schedule worker to fire MF`() { whenever(unsentForgetAllPixelStore.pendingPixelCountClearData).thenReturn(2) enqueuedPixelWorker.onCreate(lifecycleOwner) @@ -81,7 +81,7 @@ class EnqueuedPixelWorkerTest { } @Test - fun whenOnCreateAndPendingPixelCountClearDataIsZeroThenDoNotFireMf() { + fun `onCreate - pending pixel count clear data zero - do not fire mf`() { whenever(unsentForgetAllPixelStore.pendingPixelCountClearData).thenReturn(0) enqueuedPixelWorker.onCreate(lifecycleOwner) @@ -89,7 +89,7 @@ class EnqueuedPixelWorkerTest { } @Test - fun whenOnStartAndLaunchByFireActionThenDoNotSendAppLaunchPixel() { + fun `onStart - launch by fire action - do not send app launch pixel`() { whenever(unsentForgetAllPixelStore.pendingPixelCountClearData).thenReturn(1) whenever(unsentForgetAllPixelStore.lastClearTimestamp).thenReturn(System.currentTimeMillis()) @@ -100,7 +100,7 @@ class EnqueuedPixelWorkerTest { } @Test - fun whenOnStartAndAppLaunchThenSendAppLaunchPixel() { + fun `onStart - app launch - send app launch pixel`() { whenever(unsentForgetAllPixelStore.pendingPixelCountClearData).thenReturn(1) whenever(webViewVersionProvider.getMajorVersion()).thenReturn("91") whenever(defaultBrowserDetector.isDefaultBrowser()).thenReturn(false) @@ -118,7 +118,7 @@ class EnqueuedPixelWorkerTest { } @Test - fun whenOnStartAndInCustomTabAndAppLaunchThenDoNotSendAppLaunchPixel() { + fun `onStart - in custom tab and app launch - do not send app launch pixel`() { whenever(customTabDetector.isCustomTab()).thenReturn(true) whenever(unsentForgetAllPixelStore.pendingPixelCountClearData).thenReturn(1) whenever(webViewVersionProvider.getMajorVersion()).thenReturn("91") @@ -137,7 +137,7 @@ class EnqueuedPixelWorkerTest { } @Test - fun whenOnStartAndAppLaunchAndShouldCollectOnAppLaunchIsTrueThenSendAppLaunchPixelWithFullWebViewVersion() { + fun `onStart - should collect on app launch is true - send app launch pixel with full web view version`() { whenever(unsentForgetAllPixelStore.pendingPixelCountClearData).thenReturn(1) whenever(webViewVersionProvider.getMajorVersion()).thenReturn("91") whenever(webViewVersionProvider.getFullVersion()).thenReturn("91.0.4472.101") @@ -158,7 +158,7 @@ class EnqueuedPixelWorkerTest { } @Test - fun whenOnStartAndAppLaunchAndShouldCollectOnAppLaunchIsFalseThenNeverSendAppLaunchPixelWithFullWebViewVersion() { + fun `onStart - should collect on app launch is false - never send app launch pixel with full web view version`() { whenever(unsentForgetAllPixelStore.pendingPixelCountClearData).thenReturn(1) whenever(webViewVersionProvider.getMajorVersion()).thenReturn("91") whenever(webViewVersionProvider.getFullVersion()).thenReturn("91.0.4472.101") @@ -179,7 +179,7 @@ class EnqueuedPixelWorkerTest { } @Test - fun whenOnStartAndLaunchByFireActionFollowedByAppLaunchThenSendOneAppLaunchPixel() { + fun `onStart - launch by fire action followed by app launch - send one app launch pixel`() { whenever(unsentForgetAllPixelStore.pendingPixelCountClearData).thenReturn(1) whenever(unsentForgetAllPixelStore.lastClearTimestamp).thenReturn(System.currentTimeMillis()) whenever(webViewVersionProvider.getMajorVersion()).thenReturn("91") @@ -199,7 +199,7 @@ class EnqueuedPixelWorkerTest { } @Test - fun whenSendingAppLaunchPixelThenIncludePrivacyProtectionsPopupExperimentParams() { + fun `whenSendingAppLaunchPixel - include privacy protections popup experiment params`() { whenever(unsentForgetAllPixelStore.pendingPixelCountClearData).thenReturn(1) whenever(webViewVersionProvider.getMajorVersion()).thenReturn("91") whenever(defaultBrowserDetector.isDefaultBrowser()).thenReturn(false) diff --git a/app/src/test/java/com/duckduckgo/app/privacy/db/UserAllowListRepositoryTest.kt b/app/src/test/java/com/duckduckgo/app/privacy/db/UserAllowListRepositoryTest.kt index 08241cf8cfd0..de46470bc927 100644 --- a/app/src/test/java/com/duckduckgo/app/privacy/db/UserAllowListRepositoryTest.kt +++ b/app/src/test/java/com/duckduckgo/app/privacy/db/UserAllowListRepositoryTest.kt @@ -66,7 +66,7 @@ class UserAllowListRepositoryTest { } @Test - fun whenDbContainsUserAllowListedDomainsThenUpdateUserAllowList() { + fun `whenDbContainsUserAllowListedDomains - update user allow list`() { assertEquals(0, repository.domainsInUserAllowList().size) dao.insert("example.com") assertEquals(1, repository.domainsInUserAllowList().size) @@ -74,26 +74,26 @@ class UserAllowListRepositoryTest { } @Test - fun whenDbContainsUserAllowListedDomainThenIsUrlInAllowListReturnsTrue() { + fun `isUrlInUserAllowList - db contains user allow listed domain - returns true`() { dao.insert("example.com") assertTrue(repository.isUrlInUserAllowList("https://example.com")) } @Test - fun whenDbDoesNotContainUserAllowListedDomainThenIsUrlInAllowListReturnsFalse() { + fun `isUrlInUserAllowList - db does not contain user - returns false`() { dao.insert("example.com") assertFalse(repository.isUrlInUserAllowList("https://foo.com")) } @Test - fun whenDomainIsAddedToUserAllowListThenItGetsInsertedIntoDb() = runTest { + fun `addDomainToUserAllowList - db contains`() = runTest { assertFalse(dao.contains("example.com")) repository.addDomainToUserAllowList("example.com") assertTrue(dao.contains("example.com")) } @Test - fun whenDomainIsRemovedFromUserAllowListThenItGetsDeletedFromDb() = runTest { + fun `removeDomainFromUserAllowList - domain removed from db`() = runTest { dao.insert("example.com") assertTrue(dao.contains("example.com")) repository.removeDomainFromUserAllowList("example.com") @@ -101,7 +101,7 @@ class UserAllowListRepositoryTest { } @Test - fun whenAllowlistIsModifiedThenFlowEmitsEvent() = runTest { + fun `domainsInUserAllowList - modified - emits event`() = runTest { repository.domainsInUserAllowListFlow() .test { assertEquals(emptyList(), awaitItem()) diff --git a/app/src/test/java/com/duckduckgo/app/privacy/model/EntityTest.kt b/app/src/test/java/com/duckduckgo/app/privacy/model/EntityTest.kt index d8afe46ed190..7396483ca2ca 100644 --- a/app/src/test/java/com/duckduckgo/app/privacy/model/EntityTest.kt +++ b/app/src/test/java/com/duckduckgo/app/privacy/model/EntityTest.kt @@ -25,12 +25,12 @@ import org.junit.Test class EntityTest { @Test - fun whenEntityPrevalenceIsGreaterThanMajorNetworkPrevalenceThenIsMajorIsTrue() { + fun `whenEntityPrevalenceIsGreaterThanMajorNetworkPrevalence - is major true`() { assertTrue(TdsEntity("", "", MAJOR_NETWORK_PREVALENCE + 1).isMajor) } @Test - fun whenEntityPrevalenceLessOrEqualThanMajorNetworkPrevalenceThenIsMajorIsFalse() { + fun `whenEntityPrevalenceLessOrEqualThanMajorNetworkPrevalence - is major false`() { assertFalse(TdsEntity("", "", MAJOR_NETWORK_PREVALENCE).isMajor) } } diff --git a/app/src/test/java/com/duckduckgo/app/privacy/model/TrustedSitesTest.kt b/app/src/test/java/com/duckduckgo/app/privacy/model/TrustedSitesTest.kt index a841b229fef5..13a671f1ed82 100644 --- a/app/src/test/java/com/duckduckgo/app/privacy/model/TrustedSitesTest.kt +++ b/app/src/test/java/com/duckduckgo/app/privacy/model/TrustedSitesTest.kt @@ -26,12 +26,12 @@ import org.junit.runner.RunWith class TrustedSitesTest { @Test - fun whenSiteIsInTrustedListThenIsTrustedIsTrue() { + fun `isTrusted - site in trusted list - is true`() { assertTrue(TrustedSites.isTrusted("https://www.duckduckgo.com")) } @Test - fun whenSiteIsNotInTrustedListThenIsTrustedIsFalse() { + fun `isTrusted - site not in trusted list - is false`() { assertFalse(TrustedSites.isTrusted("https://www.example.com")) } } diff --git a/app/src/test/java/com/duckduckgo/app/privatesearch/PrivateSearchViewModelTest.kt b/app/src/test/java/com/duckduckgo/app/privatesearch/PrivateSearchViewModelTest.kt index 5d6e1c2d93ef..675d1daa46d5 100644 --- a/app/src/test/java/com/duckduckgo/app/privatesearch/PrivateSearchViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/privatesearch/PrivateSearchViewModelTest.kt @@ -60,7 +60,7 @@ internal class PrivateSearchViewModelTest { } @Test - fun whenAutocompleteSwitchedOnThenDataStoreIsUpdated() { + fun `onAutocompleteSettingChanged - data store updated`() { testee.onAutocompleteSettingChanged(true) verify(mockAppSettingsDataStore).autoCompleteSuggestionsEnabled = true @@ -74,7 +74,7 @@ internal class PrivateSearchViewModelTest { } @Test - fun whenMoreSearchSettingsClickedThenCommandLaunchCustomizeSearchWebPageAndPixelIsSent() = runTest { + fun `onPrivateSearchMoreSearchSettingsClicked - command launch customize search webpage and pixel sent`() = runTest { testee.commands().test { testee.onPrivateSearchMoreSearchSettingsClicked() diff --git a/app/src/test/java/com/duckduckgo/app/referral/QueryParamReferrerParserTest.kt b/app/src/test/java/com/duckduckgo/app/referral/QueryParamReferrerParserTest.kt index 4a722b09f759..b7954a054798 100644 --- a/app/src/test/java/com/duckduckgo/app/referral/QueryParamReferrerParserTest.kt +++ b/app/src/test/java/com/duckduckgo/app/referral/QueryParamReferrerParserTest.kt @@ -28,88 +28,88 @@ class QueryParamReferrerParserTest { private val testee: QueryParamReferrerParser = QueryParamReferrerParser() @Test - fun whenReferrerDoesNotContainTargetThenNoReferrerFound() { + fun `parse - referrer does not contain target - no referrer found`() { verifyReferrerNotFound(testee.parse("ABC")) } @Test - fun whenReferrerContainsTargetAndLongSuffixThenShortenedReferrerFound() { + fun `parse - referrer contains target and long suffix - shortened referrer found`() { val result = testee.parse("DDGRAABC") verifyCampaignReferrerFound("AB", result) } @Test - fun whenReferrerContainsTargetAndTwoCharSuffixThenReferrerFound() { + fun `parse - referrer contains target and two char suffix - referrer found`() { val result = testee.parse("DDGRAXY") verifyCampaignReferrerFound("XY", result) } @Test - fun whenReferrerContainsTargetAndOneCharSuffixThenNoReferrerFound() { + fun `parse - referrer contains target and one char suffix - no referrer found`() { val result = testee.parse("DDGRAX") verifyReferrerNotFound(result) } @Test - fun whenReferrerContainsTargetButNoSuffixThenNoReferrerFound() { + fun `parse - referrer contains target but no suffix - no referrer found`() { val result = testee.parse("DDGRAX") verifyReferrerNotFound(result) } @Test - fun whenReferrerIsEmptyThenNoReferrerFound() { + fun `parse - referrer empty - no referrer found`() { verifyReferrerNotFound(testee.parse("")) } @Test - fun whenReferrerContainsTargetAsFirstParamThenReferrerFound() { + fun `parse - referrer contains target as first param - referrer found`() { val result = testee.parse("key1=DDGRAAB&key2=foo&key3=bar") verifyCampaignReferrerFound("AB", result) } @Test - fun whenReferrerContainsTargetAsLastParamThenReferrerFound() { + fun `parse - referrer contains target as last param - referrer found`() { val result = testee.parse("key1=foo&key2=bar&key3=DDGRAAB") verifyCampaignReferrerFound("AB", result) } @Test - fun whenReferrerContainsTargetWithDifferentCaseThenNoReferrerFound() { + fun `parse - referrer contains target with different case - no referrer found`() { verifyReferrerNotFound(testee.parse("ddgraAB")) } @Test - fun whenReferrerContainsEuAuctionSearchChoiceDataThenEuActionReferrerFound() { + fun `parse - referrer contains eu auction search choice data - eu action referrer found`() { val result = testee.parse("$INSTALLATION_SOURCE_KEY=$INSTALLATION_SOURCE_EU_SEARCH_CHOICE_AUCTION_VALUE") assertTrue(result is EuAuctionSearchChoiceReferrerFound) } @Test - fun whenReferrerContainsBothEuAuctionSearchChoiceAndCampaignReferrerDataThenEuActionReferrerFound() { + fun `parse - referrer contains eu auction search choice and campaign referrer data - eu action referrer found`() { val result = testee.parse("key1=DDGRAAB&key2=foo&key3=bar&$INSTALLATION_SOURCE_KEY=$INSTALLATION_SOURCE_EU_SEARCH_CHOICE_AUCTION_VALUE") assertTrue(result is EuAuctionSearchChoiceReferrerFound) } @Test - fun whenReferrerContainsInstallationSourceKeyButNotMatchingValueThenNoReferrerFound() { + fun `parse - referrer contains installation source key but not matching value - no referrer found`() { val result = testee.parse("$INSTALLATION_SOURCE_KEY=bar") verifyReferrerNotFound(result) } @Test - fun whenReferrerContainsInstallationSourceKeyAndNoEuAuctionValueButHasCampaignReferrerDataThenCampaignReferrerFound() { + fun `parse - referrer contains installation source key and no eu auction value but has campaign referrer data - campaign referrer found`() { val result = testee.parse("key1=DDGRAAB&key2=foo&key3=bar&$INSTALLATION_SOURCE_KEY=bar") verifyCampaignReferrerFound("AB", result) } @Test - fun whenReferrerContainsEuAuctionBrowserChoiceDataThenEuActionReferrerFound() { + fun `parse - referrer contains eu auction browser choice data - eu action referrer found`() { val result = testee.parse("$INSTALLATION_SOURCE_KEY=$INSTALLATION_SOURCE_EU_BROWSER_CHOICE_AUCTION_VALUE") assertTrue(result is EuAuctionBrowserChoiceReferrerFound) } @Test - fun whenReferrerContainsBothEuAuctionBrowserChoiceAndCampaignReferrerDataThenEuActionReferrerFound() { + fun `parse - referrer contains eu auction browser choice and campaign referrer data - eu action referrer found`() { val result = testee.parse("key1=DDGRAAB&key2=foo&key3=bar&$INSTALLATION_SOURCE_KEY=$INSTALLATION_SOURCE_EU_BROWSER_CHOICE_AUCTION_VALUE") assertTrue(result is EuAuctionBrowserChoiceReferrerFound) } diff --git a/app/src/test/java/com/duckduckgo/app/settings/SettingsViewModelTest.kt b/app/src/test/java/com/duckduckgo/app/settings/SettingsViewModelTest.kt index 7b3a7836b453..278b869f3d62 100644 --- a/app/src/test/java/com/duckduckgo/app/settings/SettingsViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/settings/SettingsViewModelTest.kt @@ -106,13 +106,13 @@ class SettingsViewModelTest { } @Test - fun whenViewModelInitialisedThenPixelIsFired() { + fun `init - viewmodel initialized - pixel fired`() { testee // init verify(mockPixel).fire(AppPixelName.SETTINGS_OPENED) } @Test - fun whenStartCalledThenEmailAddressSetCorrectly() = runTest { + fun `start - view state set correctly`() = runTest { whenever(mockEmailManager.getEmailAddress()).thenReturn("email") testee.start() testee.viewState().test { @@ -125,7 +125,7 @@ class SettingsViewModelTest { } @Test - fun whenOnDefaultBrowserSettingClickedAndAlreadyDefaultBrowserThenLaunchDefaultBrowserCommandIsSentAndPixelFired() = runTest { + fun `onDefaultBrowserSettingClicked - already default browser - launch default browser command sent and pixel fired`() = runTest { testee.commands().test { whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(true) testee.onDefaultBrowserSettingClicked() @@ -138,7 +138,7 @@ class SettingsViewModelTest { } @Test - fun whenOnDefaultBrowserSettingClickedAndNotDefaultBrowserThenLaunchDefaultBrowserCommandIsSentAndPixelFired() = runTest { + fun `onDefaultBrowserSettingClicked - not default browser - launch default browser command sent and pixel fired`() = runTest { testee.commands().test { whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(false) testee.onDefaultBrowserSettingClicked() @@ -151,7 +151,7 @@ class SettingsViewModelTest { } @Test - fun whenDefaultBrowserAppAlreadySetToOursThenIsDefaultBrowserFlagIsTrue() = runTest { + fun `start - view state is default browser flag true`() = runTest { whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(true) testee.start() @@ -163,7 +163,7 @@ class SettingsViewModelTest { } @Test - fun whenDefaultBrowserAppNotSetToOursThenIsDefaultBrowserFlagIsFalse() = runTest { + fun `start - default browser not set - is default browser flag is false`() = runTest { testee.viewState().test { whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(false) testee.start() @@ -175,7 +175,7 @@ class SettingsViewModelTest { } @Test - fun whenBrowserDetectorIndicatesDefaultCannotBeSetThenFlagToShowSettingIsFalse() = runTest { + fun `start - browser detector indicates default cannot be set - flag to show setting is false`() = runTest { testee.viewState().test { whenever(mockDefaultBrowserDetector.deviceSupportsDefaultBrowserConfiguration()).thenReturn(false) testee.start() @@ -187,7 +187,7 @@ class SettingsViewModelTest { } @Test - fun whenBrowserDetectorIndicatesDefaultCanBeSetThenFlagToShowSettingIsTrue() = runTest { + fun `start - browser detector indicates default can be set - flag to show setting is true`() = runTest { whenever(mockDefaultBrowserDetector.deviceSupportsDefaultBrowserConfiguration()).thenReturn(true) testee.start() testee.viewState().test { @@ -198,7 +198,7 @@ class SettingsViewModelTest { } @Test - fun whenOnEmailProtectionSettingClickedAndEmailIsSupportedThenEmitCommandLaunchEmailProtectionAndPixelFired() = runTest { + fun `onEmailProtectionSettingClicked - email is supported - emit command launch email protection and pixel fired`() = runTest { whenever(mockEmailManager.isEmailFeatureSupported()).thenReturn(true) testee.commands().test { testee.onEmailProtectionSettingClicked() @@ -211,7 +211,7 @@ class SettingsViewModelTest { } @Test - fun whenOnEmailProtectionSettingClickedAndEmailIsNotSupportedThenEmitCommandLaunchEmailProtectionNotSupportedAndPixelFired() = runTest { + fun `onEmailProtectionSettingClicked - email not supported - emit command and pixel fired`() = runTest { whenever(mockEmailManager.isEmailFeatureSupported()).thenReturn(false) testee.commands().test { testee.onEmailProtectionSettingClicked() @@ -224,7 +224,7 @@ class SettingsViewModelTest { } @Test - fun whenHomeScreenWidgetSettingClickedThenEmitCommandLaunchAddHomeScreenWidget() = runTest { + fun `whenHomeScreenWidgetSettingClicked - emit command launch add home screen widget`() = runTest { testee.commands().test { testee.userRequestedToAddHomeScreenWidget() @@ -235,7 +235,7 @@ class SettingsViewModelTest { } @Test - fun whenOnMacOsSettingClickedThenEmitCommandLaunchMacOsAndPixelFired() = runTest { + fun `onMacOsSettingClicked - emit command launch macos and pixel fired`() = runTest { testee.commands().test { testee.onMacOsSettingClicked() @@ -247,7 +247,7 @@ class SettingsViewModelTest { } @Test - fun whenAutofillIsAvailableTheShowAutofillTrue() = runTest { + fun `start - autofill available - show autofill true`() = runTest { whenever(autofillCapabilityChecker.canAccessCredentialManagementScreen()).thenReturn(true) testee.start() @@ -257,7 +257,7 @@ class SettingsViewModelTest { } @Test - fun whenAutofillIsNotAvailableTheShowAutofillFalse() = runTest { + fun `start - autofill not available - show autofill false`() = runTest { whenever(autofillCapabilityChecker.canAccessCredentialManagementScreen()).thenReturn(false) testee.start() @@ -267,7 +267,7 @@ class SettingsViewModelTest { } @Test - fun whenAppTPOnboardingNotShownThenViewStateIsCorrect() = runTest { + fun `start - app TP onboarding not shown - view state is correct`() = runTest { whenever(appTrackingProtection.isOnboarded()).thenReturn(false) testee.start() @@ -277,7 +277,7 @@ class SettingsViewModelTest { } @Test - fun whenAppTPOnboardingShownThenViewStateIsCorrect() = runTest { + fun `start - app tracking protection onboarding shown - correct view state`() = runTest { whenever(appTrackingProtection.isOnboarded()).thenReturn(true) testee.start() @@ -287,7 +287,7 @@ class SettingsViewModelTest { } @Test - fun whenWindowsSettingClickedThenEmitCommandLaunchWindows() = runTest { + fun `windowsSettingClicked - emit command launch windows`() = runTest { testee.commands().test { testee.windowsSettingClicked() @@ -298,7 +298,7 @@ class SettingsViewModelTest { } @Test - fun whenSyncFeatureDisabledThenViewStateIsCorrect() = runTest { + fun `start - view state correct - feature disabled`() = runTest { whenever(deviceSyncState.isFeatureEnabled()).thenReturn(false) testee.start() @@ -309,7 +309,7 @@ class SettingsViewModelTest { } @Test - fun whenSyncFeatureEnabledAndUserSignedInOnDeviceThenSettingVisible() = runTest { + fun `start - sync feature enabled and user signed in on device - setting visible`() = runTest { whenever(deviceSyncState.isFeatureEnabled()).thenReturn(true) whenever(deviceSyncState.isUserSignedInOnDevice()).thenReturn(true) testee.start() @@ -322,7 +322,7 @@ class SettingsViewModelTest { } @Test - fun whenOnLaunchedFromNotificationCalledWithPixelNameThePixelFired() { + fun `onLaunchedFromNotification - pixel fired`() { val pixelName = "pixel_name" testee.onLaunchedFromNotification(pixelName) @@ -330,7 +330,7 @@ class SettingsViewModelTest { } @Test - fun whenPrivateSearchSettingClickedThenEmitCommandLaunchPrivateSearchWebPageAndPixelFired() = runTest { + fun `onPrivateSearchSettingClicked - emit command launch private search webpage and pixel fired`() = runTest { testee.commands().test { testee.onPrivateSearchSettingClicked() @@ -342,7 +342,7 @@ class SettingsViewModelTest { } @Test - fun whenWebTrackingProtectionSettingClickedThenEmitCommandLaunchWebTrackingProtectionWebPageAndPixelFired() = runTest { + fun `onWebTrackingProtectionSettingClicked - emit command launch web tracking protection webpage and pixel fired`() = runTest { testee.commands().test { testee.onWebTrackingProtectionSettingClicked() @@ -354,7 +354,7 @@ class SettingsViewModelTest { } @Test - fun whenAutofillSettingsClickThenEmitCommandLaunchAutofillSettings() = runTest { + fun `onAutofillSettingsClick - emit command launch autofill settings`() = runTest { testee.commands().test { testee.onAutofillSettingsClick() @@ -365,7 +365,7 @@ class SettingsViewModelTest { } @Test - fun whenAppTPSettingClickedAndAppTpOnboardedThenEmitCommandLaunchAppTPTrackersScreenAndPixelFierd() = runTest { + fun `onAppTPSettingClicked - app TP on boarded - emit command launch App TP trackers screen and pixel fired`() = runTest { whenever(appTrackingProtection.isOnboarded()).thenReturn(true) testee.commands().test { testee.onAppTPSettingClicked() @@ -378,7 +378,7 @@ class SettingsViewModelTest { } @Test - fun whenAppTPSettingClickedAndAppTpNotOnboardedThenEmitCommandLaunchAppTPOnboardingAndPixelFired() = runTest { + fun `onAppTPSettingClicked - app TP not onboarded - emit command launch app TP onboarding and pixel fired`() = runTest { whenever(appTrackingProtection.isOnboarded()).thenReturn(false) testee.commands().test { testee.onAppTPSettingClicked() @@ -391,7 +391,7 @@ class SettingsViewModelTest { } @Test - fun whenSyncSettingClickedThenEmitCommandLaunchSyncSettingsAndPixelFired() = runTest { + fun `onSyncSettingClicked - emit command launch sync settings and pixel fired`() = runTest { testee.commands().test { testee.onSyncSettingClicked() @@ -403,7 +403,7 @@ class SettingsViewModelTest { } @Test - fun whenAccessibilitySettingClickedThenEmitCommandLaunchAccessibilitySettingsAndPixelFired() = runTest { + fun `onAccessibilitySettingClicked - emit command launch accessibility settings and pixel fired`() = runTest { testee.commands().test { testee.onAccessibilitySettingClicked() @@ -415,7 +415,7 @@ class SettingsViewModelTest { } @Test - fun whenPermissionsSettingClickedThenEmitCommandLaunchPermissionsScreenAndPixelFired() = runTest { + fun `onPermissionsSettingClicked - emit command launch permissions screen and pixel fired`() = runTest { testee.commands().test { testee.onPermissionsSettingClicked() @@ -427,7 +427,7 @@ class SettingsViewModelTest { } @Test - fun whenAboutSettingClickedThenEmitCommandLaunchAboutScreenAndPixelFired() = runTest { + fun `onAboutSettingClicked - emit command launch about screen and pixel fired`() = runTest { testee.commands().test { testee.onAboutSettingClicked() @@ -439,7 +439,7 @@ class SettingsViewModelTest { } @Test - fun whenAppearanceSettingClickedThenEmitCommandLaunchAppearanceScreenAndPixelFired() = runTest { + fun `onAppearanceSettingClicked - emit command launch appearance screen and pixel fired`() = runTest { testee.commands().test { testee.onAppearanceSettingClicked() @@ -451,7 +451,7 @@ class SettingsViewModelTest { } @Test - fun whenOnAutoconsentClickedThenEmitCommandLaunchAutoconsentAndPixelFired() = runTest { + fun `onCookiePopupProtectionSettingClicked - emit command launch autoconsent and pixel fired`() = runTest { testee.commands().test { testee.onCookiePopupProtectionSettingClicked() @@ -463,7 +463,7 @@ class SettingsViewModelTest { } @Test - fun whenAutoconsentEnabledThenAutoconsentEnabledIsTrue() = runTest { + fun `start - view state auto consent enabled - is true`() = runTest { whenever(mockAutoconsent.isSettingEnabled()).thenReturn(true) testee.start() @@ -474,7 +474,7 @@ class SettingsViewModelTest { } @Test - fun whenAutoconsentDisabledThenAutoconsentEnabledIsFalse() = runTest { + fun `start - auto consent disabled - is auto consent enabled false`() = runTest { whenever(mockAutoconsent.isSettingEnabled()).thenReturn(false) testee.start() diff --git a/app/src/test/java/com/duckduckgo/app/sitepermissions/PermissionsPerWebsiteViewModelTest.kt b/app/src/test/java/com/duckduckgo/app/sitepermissions/PermissionsPerWebsiteViewModelTest.kt index d744f3881010..a05b69f174d0 100644 --- a/app/src/test/java/com/duckduckgo/app/sitepermissions/PermissionsPerWebsiteViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/sitepermissions/PermissionsPerWebsiteViewModelTest.kt @@ -59,7 +59,7 @@ class PermissionsPerWebsiteViewModelTest { private val domain = "domain.com" @Test - fun whenPermissionsSettingsAreLoadedThenViewStateEmittedSettings() = runTest { + fun `loadWebsitePermissions - view state emitted settings`() = runTest { loadAskForPermissionsPrefs() loadWebsitePermissionsSettings() @@ -72,7 +72,7 @@ class PermissionsPerWebsiteViewModelTest { } @Test - fun whenSitePermissionIsAllowAlwaysThenShowSettingAsAllow() = runTest { + fun `loadWebsitePermissions - site permission is allow always - show setting as allow`() = runTest { loadAskForPermissionsPrefs() loadWebsitePermissionsSettings(cameraSetting = SitePermissionAskSettingType.ALLOW_ALWAYS.name) @@ -85,7 +85,7 @@ class PermissionsPerWebsiteViewModelTest { } @Test - fun whenSitePermissionIsAskEveryTimeThenShowSettingAsAsk() = runTest { + fun `loadWebsitePermissions - site permission ask every time - show setting as ask`() = runTest { loadAskForPermissionsPrefs() loadWebsitePermissionsSettings(cameraSetting = SitePermissionAskSettingType.ASK_EVERY_TIME.name) @@ -98,7 +98,7 @@ class PermissionsPerWebsiteViewModelTest { } @Test - fun whenSitePermissionIsDenyAlwaysTimeThenShowSettingAsDeny() = runTest { + fun `loadWebsitePermissions - site permission is deny always time - show setting as deny`() = runTest { loadAskForPermissionsPrefs() loadWebsitePermissionsSettings(cameraSetting = SitePermissionAskSettingType.DENY_ALWAYS.name) @@ -111,7 +111,7 @@ class PermissionsPerWebsiteViewModelTest { } @Test - fun whenAskForSitePermissionPrefsIsDisabledAndSettingIsAskThenShowSettingAsAskDisabled() = runTest { + fun `loadAskForSitePermissionPrefs - view state updated - ask disabled`() = runTest { loadAskForPermissionsPrefs(cameraEnabled = false) loadWebsitePermissionsSettings() @@ -124,7 +124,7 @@ class PermissionsPerWebsiteViewModelTest { } @Test - fun whenAskForSitePermissionPrefsIsDisabledAndSettingIsDenyThenShowSettingAsDeny() = runTest { + fun `loadAskForSitePermissionPrefs - prefs disabled and setting deny - show setting as deny`() = runTest { loadAskForPermissionsPrefs(cameraEnabled = false) loadWebsitePermissionsSettings(cameraSetting = SitePermissionAskSettingType.DENY_ALWAYS.name) @@ -137,7 +137,7 @@ class PermissionsPerWebsiteViewModelTest { } @Test - fun whenAskForSitePermissionPrefsIsDisabledAndSettingIsAllowThenShowSettingAsAllow() = runTest { + fun `loadAskForSitePermissionPrefs - website permission settings - show setting as allow`() = runTest { loadAskForPermissionsPrefs(cameraEnabled = false) loadWebsitePermissionsSettings(cameraSetting = SitePermissionAskSettingType.ALLOW_ALWAYS.name) @@ -150,7 +150,7 @@ class PermissionsPerWebsiteViewModelTest { } @Test - fun whenPermissionIsTappedThenShowSettingsSelectionDialog() = runTest { + fun `whenPermissionIsTapped - show settings selection dialog`() = runTest { loadAskForPermissionsPrefs() loadWebsitePermissionsSettings() @@ -165,7 +165,7 @@ class PermissionsPerWebsiteViewModelTest { } @Test - fun whenPermissionSettingIsChangedThenSave() = runTest { + fun `onPermissionSettingSelected - save permission setting`() = runTest { loadAskForPermissionsPrefs() loadWebsitePermissionsSettings() @@ -184,7 +184,7 @@ class PermissionsPerWebsiteViewModelTest { } @Test - fun whenWebsitePermissionsAreRemovedThenDeleteFromDB() = runTest { + fun `websitePermissionsAreRemoved - delete from DB`() = runTest { loadAskForPermissionsPrefs() loadWebsitePermissionsSettings() @@ -195,7 +195,7 @@ class PermissionsPerWebsiteViewModelTest { } @Test - fun whenWebsitePermissionsAreRemovedThenNavigateBackToSitePermissionsScreen() = runTest { + fun `whenRemoveWebsitePermissionsThenNavigateBack - website permissions removed - navigate back to site permissions screen`() = runTest { loadAskForPermissionsPrefs() loadWebsitePermissionsSettings() diff --git a/app/src/test/java/com/duckduckgo/app/sitepermissions/SitePermissionsViewModelTest.kt b/app/src/test/java/com/duckduckgo/app/sitepermissions/SitePermissionsViewModelTest.kt index 9287b8a746d1..b2aa37a91d15 100644 --- a/app/src/test/java/com/duckduckgo/app/sitepermissions/SitePermissionsViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/sitepermissions/SitePermissionsViewModelTest.kt @@ -66,7 +66,7 @@ class SitePermissionsViewModelTest { } @Test - fun whenAllowedSitesLoadedThenViewStateEmittedWebsites() = runTest { + fun `whenAllowedSitesLoaded - view state emitted websites`() = runTest { viewModel.viewState.test { val sitePermissions = awaitItem().sitesPermissionsAllowed assertEquals(2, sitePermissions.size) @@ -74,7 +74,7 @@ class SitePermissionsViewModelTest { } @Test - fun whenAllowedSitesLoadedThenViewStateEmittedLocationWebsites() = runTest { + fun `whenAllowedSitesLoaded - viewState emitted location websites`() = runTest { viewModel.viewState.test { val sitePermissions = awaitItem().locationPermissionsAllowed assertEquals(1, sitePermissions.size) @@ -82,21 +82,21 @@ class SitePermissionsViewModelTest { } @Test - fun whenRemoveAllWebsitesThenClearAllLocationWebsitesIsCalled() = runTest { + fun `removeAllSites - clear all location websites is called`() = runTest { viewModel.removeAllSitesSelected() verify(mockGeoLocationPermissions).clearAll() } @Test - fun whenRemoveAllWebsitesThenDeleteAllSitePermissionsIsCalled() = runTest { + fun `removeAllSites - delete all site permissions called`() = runTest { viewModel.removeAllSitesSelected() verify(mockSitePermissionsRepository).deleteAll() } @Test - fun whenRemoveAllWebsitesThenShowRemoveAllSnackBar() = runTest { + fun `removeAll - show remove all snackbar`() = runTest { viewModel.removeAllSitesSelected() viewModel.commands.test { @@ -105,7 +105,7 @@ class SitePermissionsViewModelTest { } @Test - fun whenPermissionsSettingsAreLoadedThenViewStateEmittedForAskLocationEnabled() = runTest { + fun `loadPermissionsSettings - view state emitted for ask location enabled - not enabled`() = runTest { loadPermissionsSettings(locationEnabled = false) viewModel.viewState.test { val askLocationEnabled = awaitItem().askLocationEnabled @@ -114,7 +114,7 @@ class SitePermissionsViewModelTest { } @Test - fun whenPermissionsSettingsAreLoadedThenViewStateEmittedForAskCameraEnabled() = runTest { + fun `loadPermissionsSettings - view state emitted for ask camera enabled - not enabled`() = runTest { loadPermissionsSettings(cameraEnabled = false) viewModel.viewState.test { @@ -124,7 +124,7 @@ class SitePermissionsViewModelTest { } @Test - fun whenPermissionsSettingsAreLoadedThenViewStateEmittedForAskMicEnabled() = runTest { + fun `loadPermissionsSettings - view state emitted for ask mic enabled - not asked`() = runTest { loadPermissionsSettings(micEnabled = false) viewModel.viewState.test { @@ -134,7 +134,7 @@ class SitePermissionsViewModelTest { } @Test - fun whenToggleOffAskForLocationThenViewStateEmitted() = runTest { + fun `toggleOffAskForLocation - view state emitted`() = runTest { viewModel.permissionToggleSelected(false, R.string.sitePermissionsSettingsLocation) viewModel.viewState.test { @@ -144,7 +144,7 @@ class SitePermissionsViewModelTest { } @Test - fun whenToggleOffAskForCameraThenViewStateEmitted() = runTest { + fun `toggleOffAskForCamera - view state emitted`() = runTest { viewModel.permissionToggleSelected(false, R.string.sitePermissionsSettingsCamera) viewModel.viewState.test { @@ -154,7 +154,7 @@ class SitePermissionsViewModelTest { } @Test - fun whenToggleOffAskForMicThenViewStateEmitted() = runTest { + fun `toggleOffAskForMic - view state emitted`() = runTest { viewModel.permissionToggleSelected(false, R.string.sitePermissionsSettingsMicrophone) viewModel.viewState.test { @@ -164,7 +164,7 @@ class SitePermissionsViewModelTest { } @Test - fun whenWebsiteIsTappedThenNavigateToPermissionsPerWebsiteScreen() = runTest { + fun `whenWebsiteIsTapped - navigate to permissions per website screen`() = runTest { val testDomain = "website1.com" viewModel.allowedSiteSelected(testDomain) diff --git a/app/src/test/java/com/duckduckgo/app/statistics/pixels/PixelNameTest.kt b/app/src/test/java/com/duckduckgo/app/statistics/pixels/PixelNameTest.kt index 3ff05d05aed8..c80c6b0f0e5f 100644 --- a/app/src/test/java/com/duckduckgo/app/statistics/pixels/PixelNameTest.kt +++ b/app/src/test/java/com/duckduckgo/app/statistics/pixels/PixelNameTest.kt @@ -26,7 +26,7 @@ import org.junit.Test class PixelNameTest { @Test - fun verifyNoDuplicatePixelNames() { + fun `verifyNoDuplicatePixelNames - no duplicates found`() { val existingNames = mutableSetOf() AppPixelName.values().forEach { if (!existingNames.add(it.pixelName)) { diff --git a/app/src/test/java/com/duckduckgo/app/surrogates/ResourceSurrogatesTest.kt b/app/src/test/java/com/duckduckgo/app/surrogates/ResourceSurrogatesTest.kt index d0dffbf83e1b..850d60629a17 100644 --- a/app/src/test/java/com/duckduckgo/app/surrogates/ResourceSurrogatesTest.kt +++ b/app/src/test/java/com/duckduckgo/app/surrogates/ResourceSurrogatesTest.kt @@ -30,26 +30,26 @@ class ResourceSurrogatesTest { } @Test - fun whenInitialisedThenHasNoSurrogatesLoaded() { + fun `initialise - has no surrogates loaded`() { assertEquals(0, testee.getAll().size) } @Test - fun whenOneSurrogateLoadedThenOneReturnedFromFullList() { + fun `loadSurrogates - one surrogate loaded - one returned from full list`() { val surrogate = SurrogateResponse() testee.loadSurrogates(listOf(surrogate)) assertEquals(1, testee.getAll().size) } @Test - fun whenMultipleSurrogatesLoadedThenAllReturnedFromFullList() { + fun `loadSurrogates - all returned from full list`() { val surrogate = SurrogateResponse() testee.loadSurrogates(listOf(surrogate, surrogate, surrogate)) assertEquals(3, testee.getAll().size) } @Test - fun whenSearchingForExactMatchingExistingSurrogateThenCanFindByScriptId() { + fun `loadSurrogates - searching for exact matching existing surrogate - can find by script id`() { val surrogate = SurrogateResponse(scriptId = "fooId", name = "foo") testee.loadSurrogates(listOf(surrogate)) val retrieved = testee.get("fooId") @@ -57,7 +57,7 @@ class ResourceSurrogatesTest { } @Test - fun whenSearchingByNonExistentScriptIdThenResponseUnavailableSurrogateResultReturned() { + fun `loadSurrogates - searching by non-existent script id - response unavailable surrogate result returned`() { val surrogate = SurrogateResponse(scriptId = "fooId", name = "foo") testee.loadSurrogates(listOf(surrogate)) val retrieved = testee.get("bar") diff --git a/app/src/test/java/com/duckduckgo/app/survey/api/SurveyDownloaderTest.kt b/app/src/test/java/com/duckduckgo/app/survey/api/SurveyDownloaderTest.kt index f244954e5c08..512e7acbdc40 100644 --- a/app/src/test/java/com/duckduckgo/app/survey/api/SurveyDownloaderTest.kt +++ b/app/src/test/java/com/duckduckgo/app/survey/api/SurveyDownloaderTest.kt @@ -64,7 +64,7 @@ class SurveyDownloaderTest { } @Test - fun whenNewSurveyAllocatedThenSavedAsScheduledAndUnusedSurveysDeleted() { + fun `download - new survey allocated - saved as scheduled and unused surveys deleted`() { whenever(mockCall.execute()).thenReturn(Response.success(surveyWithAllocation("abc"))) whenever(mockService.survey()).thenReturn(mockCall) testee.download().blockingAwait() @@ -73,7 +73,7 @@ class SurveyDownloaderTest { } @Test - fun whenNewSurveyNotAllocatedThenSavedAsUnallocatedAndUnusedSurveysDeleted() { + fun `download - new survey not allocated - saved as unallocated and unused surveys deleted`() { val surveyNotAllocated = Survey("abc", null, null, NOT_ALLOCATED) whenever(mockSurveyRepository.isUserEligibleForSurvey(surveyNotAllocated)).thenReturn(true) whenever(mockCall.execute()).thenReturn(Response.success(surveyNoAllocation("abc"))) @@ -84,7 +84,7 @@ class SurveyDownloaderTest { } @Test - fun whenSurveyAlreadyExistsThenNotSavedAndUnusedSurveysNotDeleted() { + fun `download - survey already exists - not saved and unused surveys not deleted`() { whenever(mockSurveyRepository.surveyExists(any())).thenReturn(true) whenever(mockCall.execute()).thenReturn(Response.success(surveyWithAllocation("abc"))) whenever(mockService.survey()).thenReturn(mockCall) @@ -94,7 +94,7 @@ class SurveyDownloaderTest { } @Test - fun whenSuccessfulRequestReturnsNoSurveysThenUnusedSurveysDeleted() { + fun `download - successful request returns no surveys - unused surveys deleted`() { whenever(mockCall.execute()).thenReturn(Response.success(null)) whenever(mockService.survey()).thenReturn(mockCall) testee.download().blockingAwait() @@ -102,14 +102,14 @@ class SurveyDownloaderTest { } @Test(expected = RuntimeException::class) - fun whenRequestUnsuccessfulThenExceptionThrown() { + fun `download - request unsuccessful - exception thrown`() { whenever(mockCall.execute()).thenReturn(Response.error(500, ResponseBody.create(null, ""))) whenever(mockService.survey()).thenReturn(mockCall) testee.download().blockingAwait() } @Test - fun whenSurveyForEmailReceivedAndUserIsSignedInThenCreateSurveyWithCorrectCohort() { + fun `whenSurveyForEmailReceivedAndUserIsSignedIn - create survey with correct cohort`() { val surveyWithCohort = Survey("abc", SURVEY_URL_WITH_COHORT, -1, SCHEDULED) whenever(mockSurveyRepository.isUserEligibleForSurvey(surveyWithCohort)).thenReturn(true) whenever(mockEmailManager.isSignedIn()).thenReturn(true) @@ -121,7 +121,7 @@ class SurveyDownloaderTest { } @Test - fun whenSurveyForEmailReceivedAndUserIsNotSignedInThenDoNotCreateSurvey() { + fun `download - survey for email received and user is not signed in - do not create survey`() { whenever(mockEmailManager.isSignedIn()).thenReturn(false) whenever(mockEmailManager.getCohort()).thenReturn("cohort") whenever(mockCall.execute()).thenReturn(Response.success(surveyWithAllocationForEmail("abc"))) @@ -131,7 +131,7 @@ class SurveyDownloaderTest { } @Test - fun whenNewSurveyAllocatedAndUserIsEligibleThenSavedAsScheduled() = runTest { + fun `download - new survey allocated and user is eligible - saved as scheduled`() = runTest { whenever(mockCall.execute()).thenReturn(Response.success(surveyWithAllocation("abc"))) whenever(mockService.survey()).thenReturn(mockCall) testee.download().blockingAwait() @@ -140,7 +140,7 @@ class SurveyDownloaderTest { } @Test - fun whenNewSurveyAllocatedAndUserIsNotEligibleThenSavedAsScheduled() = runTest { + fun `download - new survey allocated and user is not eligible - saved as scheduled`() = runTest { whenever(mockSurveyRepository.isUserEligibleForSurvey(testSurvey)).thenReturn(false) whenever(mockCall.execute()).thenReturn(Response.success(surveyWithAllocation("abc"))) whenever(mockService.survey()).thenReturn(mockCall) diff --git a/app/src/test/java/com/duckduckgo/app/survey/api/SurveyRepositoryTest.kt b/app/src/test/java/com/duckduckgo/app/survey/api/SurveyRepositoryTest.kt index 9c091b6a7de4..bbff4db2b53d 100644 --- a/app/src/test/java/com/duckduckgo/app/survey/api/SurveyRepositoryTest.kt +++ b/app/src/test/java/com/duckduckgo/app/survey/api/SurveyRepositoryTest.kt @@ -37,7 +37,7 @@ class SurveyRepositoryTest { } @Test - fun whenSurveyUrlIsNullThenSurveyIsNotEligible() { + fun `isUserEligibleForSurvey - survey url is null - not eligible`() { val survey = Survey( surveyId = "id", status = Survey.Status.SCHEDULED, @@ -49,7 +49,7 @@ class SurveyRepositoryTest { } @Test - fun whenLocaleIsNotAllowedThenSurveyIsNotEligible() { + fun `isUserEligibleForSurvey - locale not allowed - not eligible`() { whenever(appBuildConfig.deviceLocale).thenReturn(Locale.JAPAN) val survey = Survey( surveyId = "id", @@ -62,7 +62,7 @@ class SurveyRepositoryTest { } @Test - fun whenRequiredDaysInstalledNullThenSurveyIsNotEligible() { + fun `isUserEligibleForSurvey - required days installed null - not eligible`() { val survey = Survey( surveyId = "id", status = Survey.Status.SCHEDULED, @@ -74,7 +74,7 @@ class SurveyRepositoryTest { } @Test - fun whenRequiredDaysInstalledMinusOneThenSurveyIsEligible() { + fun `isUserEligibleForSurvey - required days installed minus one - eligible`() { whenever(userBrowserProperties.daysSinceInstalled()).thenReturn(0) val survey = Survey( surveyId = "id", @@ -87,7 +87,7 @@ class SurveyRepositoryTest { } @Test - fun whenRetentionDayBellowRequiredDaysThenUserIsEligibleForSurvey() { + fun `isUserEligibleForSurvey - retention day below required days - eligible for survey`() { whenever(userBrowserProperties.daysSinceInstalled()).thenReturn(0) val survey = Survey( surveyId = "id", @@ -100,7 +100,7 @@ class SurveyRepositoryTest { } @Test - fun whenLocaleIsNotAllowedAndRequiredDaysInstalledMetThenSurveyIsNotEligible() { + fun `isUserEligibleForSurvey - locale not allowed and required days installed met - not eligible`() { whenever(appBuildConfig.deviceLocale).thenReturn(Locale.JAPAN) whenever(userBrowserProperties.daysSinceInstalled()).thenReturn(0) val survey = Survey( @@ -114,7 +114,7 @@ class SurveyRepositoryTest { } @Test - fun whenLocaleIsCanadaAndRequiredDaysInstalledMetThenSurveyIsEligible() { + fun `whenLocaleIsCanadaAndRequiredDaysInstalledMetThenSurveyIsEligible - survey repository is eligible`() { whenever(appBuildConfig.deviceLocale).thenReturn(Locale.CANADA) whenever(userBrowserProperties.daysSinceInstalled()).thenReturn(0) val survey = Survey( @@ -128,7 +128,7 @@ class SurveyRepositoryTest { } @Test - fun whenLocaleIsUKAndRequiredDaysInstalledMetThenSurveyIsEligible() { + fun `whenLocaleIsUKAndRequiredDaysInstalledMetThenSurveyIsEligible - survey repository is eligible`() { whenever(appBuildConfig.deviceLocale).thenReturn(Locale.UK) whenever(userBrowserProperties.daysSinceInstalled()).thenReturn(0) val survey = Survey( @@ -142,7 +142,7 @@ class SurveyRepositoryTest { } @Test - fun whenRequiredDaysInstalledIsNullAndRetentionDaysBelowDefaultDaysThenReturnMinus1() { + fun `whenRequiredDaysInstalledIsNullAndRetentionDaysBelowDefaultDaysThenReturnMinus1 - remaining days for showing survey - minus 1`() { whenever(userBrowserProperties.daysSinceInstalled()).thenReturn(4) val survey = Survey( surveyId = "id", @@ -156,7 +156,7 @@ class SurveyRepositoryTest { } @Test - fun whenRequiredDaysInstalledIsNullAndRetentionDaysAboveDefaultDaysThenReturn0() { + fun `whenRequiredDaysInstalledIsNullAndRetentionDaysAboveDefaultDaysThenReturn0 - remaining days for showing survey - 0`() { whenever(userBrowserProperties.daysSinceInstalled()).thenReturn(31) val survey = Survey( surveyId = "id", @@ -170,7 +170,7 @@ class SurveyRepositoryTest { } @Test - fun whenRequiredDaysInstalledIsMinus1AndNotFirstDayThenRemainingDaysToSurveyIsZero() { + fun `whenRequiredDaysInstalledIsMinus1AndNotFirstDayThenRemainingDaysToSurveyIsZero - remaining days to survey is zero`() { whenever(userBrowserProperties.daysSinceInstalled()).thenReturn(4) val survey = Survey( surveyId = "id", @@ -184,7 +184,7 @@ class SurveyRepositoryTest { } @Test - fun whenRequiredDaysInstalledAndDaysInstallNotEnoughThenShouldNotShowSurvey() { + fun `whenRequiredDaysInstalledAndDaysInstallNotEnoughThenShouldNotShowSurvey - should not show survey`() { whenever(userBrowserProperties.daysSinceInstalled()).thenReturn(2) val survey = Survey( surveyId = "id", @@ -198,7 +198,7 @@ class SurveyRepositoryTest { } @Test - fun whenRetentionDaysIsAboveRequiredDaysInstalledThenShouldNotShowSurvey() { + fun `whenRetentionDaysIsAboveRequiredDaysInstalled - should not show survey`() { whenever(userBrowserProperties.daysSinceInstalled()).thenReturn(4) val survey = Survey( surveyId = "id", @@ -212,7 +212,7 @@ class SurveyRepositoryTest { } @Test - fun whenSurveyStatusIsDoneThenShouldNotShowSurvey() { + fun `shouldShowSurvey - survey status done - should not show survey`() { whenever(userBrowserProperties.daysSinceInstalled()).thenReturn(4) val survey = Survey( surveyId = "id", @@ -225,7 +225,7 @@ class SurveyRepositoryTest { } @Test - fun getScheduledSurveyReturnsLastSurvey() { + fun `getScheduledSurvey - returns last scheduled survey`() { val survey = Survey( surveyId = "1", status = Survey.Status.SCHEDULED, @@ -242,7 +242,7 @@ class SurveyRepositoryTest { } @Test - fun givenExistingSurveyWhenCheckingIfSurveyExistThenReturnTrue() { + fun `givenExistingSurvey - survey exists - true`() { val survey = Survey( surveyId = "id", status = Survey.Status.SCHEDULED, @@ -255,7 +255,7 @@ class SurveyRepositoryTest { } @Test - fun givenNonExistingSurveyWhenCheckingIfSurveyExistThenReturnFalse() { + fun `givenNonExistingSurvey - survey repository - returns false`() { assertFalse(surveyRepository.surveyExists("id")) } } diff --git a/app/src/test/java/com/duckduckgo/app/survey/rmf/SurveyActionMapperTest.kt b/app/src/test/java/com/duckduckgo/app/survey/rmf/SurveyActionMapperTest.kt index 123a7fd1857b..1ee86e59e232 100644 --- a/app/src/test/java/com/duckduckgo/app/survey/rmf/SurveyActionMapperTest.kt +++ b/app/src/test/java/com/duckduckgo/app/survey/rmf/SurveyActionMapperTest.kt @@ -54,7 +54,7 @@ class SurveyActionMapperTest { ) @Test - fun whenEvaluateAndTypeIsSurveyThenReturnActionSurvey() { + fun `evaluate - type survey - return action survey`() { val jsonMessageAction = JsonMessageAction( type = "survey", value = "http://example.com", @@ -65,7 +65,7 @@ class SurveyActionMapperTest { } @Test - fun whenEvaluateAndTypeIsSurveyAndNoParamsThenReturnActionSurvey() { + fun `evaluate - type survey and no params - return action survey`() { val jsonMessageAction = JsonMessageAction( type = "survey", value = "http://example.com", @@ -76,7 +76,7 @@ class SurveyActionMapperTest { } @Test - fun whenEvaluateAndTypeIsSurveyButUnknownParamsThenReturnNull() { + fun `evaluate - survey unknown params - return null`() { val jsonMessageAction = JsonMessageAction( type = "survey", value = "value", @@ -87,7 +87,7 @@ class SurveyActionMapperTest { } @Test - fun whenEvaluateAndQueryParamsInPayloadThenReturnActionSurveyWithQueryParams() = runTest { + fun `evaluate - and query params in payload - return action survey with query params`() = runTest { whenever(mockStatisticsStore.atb).thenReturn(Atb("123")) whenever(mockStatisticsStore.variant).thenReturn("abc") whenever(mockAppInstallStore.installTimestamp).thenReturn(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(2)) @@ -115,7 +115,7 @@ class SurveyActionMapperTest { } @Test - fun whenEvaluateAndTypeIsNotSurveyThenReturnNull() { + fun `evaluate - not survey - return null`() { val jsonMessageAction = JsonMessageAction( type = "notSurvey", value = "value", diff --git a/app/src/test/java/com/duckduckgo/app/survey/ui/SurveyViewModelTest.kt b/app/src/test/java/com/duckduckgo/app/survey/ui/SurveyViewModelTest.kt index ac2f04670731..b537f99cecae 100644 --- a/app/src/test/java/com/duckduckgo/app/survey/ui/SurveyViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/survey/ui/SurveyViewModelTest.kt @@ -95,7 +95,7 @@ class SurveyViewModelTest { } @Test - fun whenViewStartedThenSurveyLoaded() { + fun `start - view started - survey loaded`() { val url = "https://survey.com" val captor = argumentCaptor() @@ -105,7 +105,7 @@ class SurveyViewModelTest { } @Test - fun whenSurveyStartedThenParametersAddedToUrl() { + fun `start - survey started - parameters added to url`() { whenever(mockStatisticsStore.atb).thenReturn(Atb("123")) whenever(mockStatisticsStore.variant).thenReturn("abc") whenever(mockAppInstallStore.installTimestamp).thenReturn(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(2)) @@ -128,7 +128,7 @@ class SurveyViewModelTest { } @Test - fun whenSurveyStartedFromNotificationThenSourceIsPushAndDayActiveIsYesterday() = runTest { + fun `start - survey started from notification - source is push and day active is yesterday`() = runTest { whenever(mockStatisticsStore.atb).thenReturn(Atb("123")) whenever(mockStatisticsStore.variant).thenReturn("abc") whenever(mockAppInstallStore.installTimestamp).thenReturn(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(2)) @@ -152,7 +152,7 @@ class SurveyViewModelTest { } @Test - fun whenSurveyStartedAndInAppTpRetentionStudyThenParametersAddedToUrl() { + fun `start - survey started and in app tp retention study - parameters added to url`() { whenever(mockStatisticsStore.atb).thenReturn(Atb("123")) whenever(mockStatisticsStore.variant).thenReturn("abc") whenever(mockAppInstallStore.installTimestamp).thenReturn(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(2)) @@ -175,19 +175,19 @@ class SurveyViewModelTest { } @Test - fun whenSurveyFailsToLoadThenErrorShown() { + fun `onSurveyFailedToLoad - error shown`() { testee.onSurveyFailedToLoad() verify(mockCommandObserver).onChanged(Command.ShowError) } @Test - fun whenSurveyLoadedThenSurveyIsShown() { + fun `onSurveyLoaded - survey shown`() { testee.onSurveyLoaded() verify(mockCommandObserver).onChanged(Command.ShowSurvey) } @Test - fun whenSurveyCompletedThenViewIsClosedAndRecordIsUpdatedAnd() { + fun `start - survey completed - view closed and record updated`() { testee.start(Survey("", "https://survey.com", null, SCHEDULED), testSource) testee.onSurveyCompleted() verify(mockSurveyRepository).updateSurvey(Survey("", "https://survey.com", null, DONE)) @@ -195,14 +195,14 @@ class SurveyViewModelTest { } @Test - fun whenSurveyCompletedThenSurveyNotificationIsCleared() { + fun `start - survey completed - survey notification cleared`() { testee.start(Survey("", "https://survey.com", null, SCHEDULED), testSource) testee.onSurveyCompleted() verify(mockSurveyRepository).clearSurveyNotification() } @Test - fun whenSurveyDismissedThenViewIsClosedAndRecordIsNotUpdated() { + fun `start - survey dismissed - view closed and record not updated`() { testee.start(Survey("", "https://survey.com", null, SCHEDULED), testSource) testee.onSurveyDismissed() verify(mockSurveyRepository, never()).updateSurvey(any()) diff --git a/app/src/test/java/com/duckduckgo/app/sync/RealSavedSitesFormFactorSyncMigrationTest.kt b/app/src/test/java/com/duckduckgo/app/sync/RealSavedSitesFormFactorSyncMigrationTest.kt index afdfaa9d01c2..ebec9916df43 100644 --- a/app/src/test/java/com/duckduckgo/app/sync/RealSavedSitesFormFactorSyncMigrationTest.kt +++ b/app/src/test/java/com/duckduckgo/app/sync/RealSavedSitesFormFactorSyncMigrationTest.kt @@ -78,7 +78,7 @@ class RealSavedSitesFormFactorSyncMigrationTest { } @Test - fun whenSyncEnabledThenFormFactorFavoriteFoldersCreated() { + fun `onFormFactorFavouritesEnabled - form factor favorite folders created`() { testee.onFormFactorFavouritesEnabled() assertNotNull(savedSitesEntitiesDao.entityById(SavedSitesNames.FAVORITES_ROOT)) @@ -87,7 +87,7 @@ class RealSavedSitesFormFactorSyncMigrationTest { } @Test - fun whenSyncEnabledThenAllFavoritesCopiedToNativeFolder() = runTest { + fun `onFormFactorFavouritesEnabled - all favorites copied to native folder`() = runTest { val entities = givenEntitiesWithIds("Entity1", "Entity2", "Entity3") givenEntitiesStoredIn(entities, SavedSitesNames.FAVORITES_ROOT) @@ -101,7 +101,7 @@ class RealSavedSitesFormFactorSyncMigrationTest { } @Test - fun whenDisplayModeNativeAndFavoritesInAllFormFactorFolderThenCopyNativeFavoritesInRoot() = runTest { + fun `onFormFactorFavourites - display mode native - copy native favorites in root`() = runTest { val desktopEntities = givenEntitiesWithIds("Entity1", "Entity2", "Entity3") givenEntitiesStoredIn(desktopEntities, SavedSitesNames.FAVORITES_DESKTOP_ROOT) val nativeEntities = givenEntitiesWithIds("Entity4", "Entity5", "Entity6") @@ -121,7 +121,7 @@ class RealSavedSitesFormFactorSyncMigrationTest { } @Test - fun whenDisplayModeUnifiedAndFavoritesInAllFormFactorFolderThenRemoveContentFromFormFactorFolders() = runTest { + fun `onFormFactorFavouritesDisabled - remove content from form factor folders`() = runTest { val desktopEntities = givenEntitiesWithIds("Entity1", "Entity2", "Entity3") givenEntitiesStoredIn(desktopEntities, SavedSitesNames.FAVORITES_DESKTOP_ROOT) val nativeEntities = givenEntitiesWithIds("Entity4", "Entity5", "Entity6") @@ -141,7 +141,7 @@ class RealSavedSitesFormFactorSyncMigrationTest { } @Test - fun whenSyncDisabledAndDisplayModeUnifiedThenNewDisplayModeIsNative() { + fun `onFormFactorFavouritesDisabled - favorites display mode unified - native`() { savedSiteSettingsRepository.favoritesDisplayMode = FavoritesDisplayMode.UNIFIED testee.onFormFactorFavouritesDisabled() @@ -150,7 +150,7 @@ class RealSavedSitesFormFactorSyncMigrationTest { } @Test - fun whenSyncDisabledAndDisplayModeNativeThenNewDisplayModeIsNative() { + fun `onFormFactorFavouritesDisabled - display mode native - native`() { savedSiteSettingsRepository.favoritesDisplayMode = FavoritesDisplayMode.NATIVE testee.onFormFactorFavouritesDisabled() @@ -159,7 +159,7 @@ class RealSavedSitesFormFactorSyncMigrationTest { } @Test - fun whenSyncDisabledThenOnlyFavoritesRootFolderExist() { + fun `onFormFactorFavouritesDisabled - state - only favorites root folder exists`() { savedSitesEntitiesDao.insert( Entity(entityId = SavedSitesNames.FAVORITES_ROOT, url = "", title = SavedSitesNames.FAVORITES_NAME, type = FOLDER), ) diff --git a/app/src/test/java/com/duckduckgo/app/sync/SavedSitesSyncDataProviderTest.kt b/app/src/test/java/com/duckduckgo/app/sync/SavedSitesSyncDataProviderTest.kt index 277761bddc27..521e7986b843 100644 --- a/app/src/test/java/com/duckduckgo/app/sync/SavedSitesSyncDataProviderTest.kt +++ b/app/src/test/java/com/duckduckgo/app/sync/SavedSitesSyncDataProviderTest.kt @@ -176,13 +176,13 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenGettingAllContentAndUserHasNoBookmarksThenChangesAreEmpty() { + fun `allContent - no bookmarks - changes are empty`() { val syncChanges = parser.allContent() assertTrue(syncChanges.isEmpty()) } @Test - fun whenGettingAllContentAndUsersHasFavoritesThenChangesAreNotEmpty() { + fun `whenGettingAllContentAndUsersHasFavorites - changes are not empty - not empty`() { repository.insert(favourite1) repository.insert(bookmark1) repository.insert(bookmark3) @@ -201,7 +201,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenFirstSyncAndUsersHasFavoritesThenFormFactorFolderPresent() { + fun `whenFirstSyncAndUsersHasFavoritesThenFormFactorFolderPresent - form factor folder present`() { repository.insert(favourite1) repository.insert(bookmark3) repository.insert(bookmark4) @@ -221,7 +221,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenNewBookmarksSinceLastSyncThenChangesContainData() { + fun `getChanges - new bookmarks since last sync - changes contain data`() { repository.insert(bookmark3) repository.insert(bookmark4) @@ -235,7 +235,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenOnFirstSyncBookmarkIsInvalidThenChangesDoesNotContainInvalidEntity() { + fun `getChanges - on first sync bookmark is invalid - does not contain invalid entity`() { repository.insert(invalidBookmark) val syncChanges = parser.getChanges() @@ -247,7 +247,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenOnFirstSyncFolderIsInvalidThenChangesContainDataFixed() { + fun `getChanges - on first sync folder is invalid - changes contain data fixed`() { repository.insert(invalidBookmark) repository.insert(invalidFolder) @@ -262,7 +262,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenNewBookmarkIsInvalidThenChangesDoesNotContainInvalidEntity() { + fun `getChanges - new bookmark invalid - does not contain invalid entity`() { setLastSyncTime(DatabaseDateFormatter.iso8601(twoHoursAgo)) repository.insert(invalidBookmark.copy(lastModified = DatabaseDateFormatter.iso8601(oneHourAgo))) @@ -275,7 +275,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenNewFolderIsInvalidThenChangesContainDataFixed() { + fun `getChanges - new folder is invalid - changes contain data fixed`() { setLastSyncTime(DatabaseDateFormatter.iso8601(twoHoursAgo)) repository.insert(invalidBookmark.copy(lastModified = DatabaseDateFormatter.iso8601(oneHourAgo))) repository.insert(invalidFolder.copy(lastModified = DatabaseDateFormatter.iso8601(oneHourAgo))) @@ -289,7 +289,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenInvalidBookmarkPresentAndValidBookmarkAddedThenOnlyValidBookmarkIncluded() { + fun `whenInvalidBookmarkPresentAndValidBookmarkAddedThenOnlyValidBookmarkIncluded - repository updated - only valid bookmark included`() { repository.insert(invalidBookmark) syncRepository.markSavedSitesAsInvalid(listOf(invalidBookmark.id)) setLastSyncTime(DatabaseDateFormatter.iso8601(twoHoursAgo)) @@ -306,7 +306,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenNewFoldersAndBookmarksAndFavouritesSinceLastSyncThenChangesContainData() { + fun `whenNewFoldersAndBookmarksAndFavouritesSinceLastSyncThenChangesContainData - changes contain data`() { val modificationTimestamp = DatabaseDateFormatter.iso8601() val lastSyncTimestamp = DatabaseDateFormatter.iso8601(twoHoursAgo) setLastSyncTime(lastSyncTimestamp) @@ -335,7 +335,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenNewFavouritesSinceLastSyncThenChangesContainData() { + fun `whenNewFavouritesSinceLastSync - changes contain data`() { val modificationTimestamp = DatabaseDateFormatter.iso8601() val lastServerSyncTimestamp = DatabaseDateFormatter.iso8601(twoHoursAgo) setLastSyncTime(lastServerSyncTimestamp, modificationTimestamp) @@ -365,7 +365,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenNoChangesAfterLastSyncThenChangesAreEmpty() { + fun `getChanges - no changes after last sync - empty`() { val modificationTimestamp = DatabaseDateFormatter.iso8601(twoHoursAgo) val lastSyncTimestamp = DatabaseDateFormatter.iso8601() setLastSyncTime(lastSyncTimestamp) @@ -379,7 +379,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenBookmarkDeletedAfterLastSyncThenChangesContainData() { + fun `whenBookmarkDeletedAfterLastSyncThenChangesContainData - changes contain data`() { val modificationTimestamp = DatabaseDateFormatter.iso8601() val lastSyncTimestamp = DatabaseDateFormatter.iso8601(twoHoursAgo) setLastSyncTime(lastSyncTimestamp) @@ -403,7 +403,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenFolderDeletedAfterLastSyncThenChangesContainData() { + fun `whenFolderDeletedAfterLastSyncThenChangesContainData - changes contain data`() { val lastSyncTimestamp = DatabaseDateFormatter.iso8601(twoHoursAgo) setLastSyncTime(lastSyncTimestamp) @@ -429,7 +429,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenFavouriteDeletedAfterLastSyncThenChangesContainData() { + fun `whenFavouriteDeletedAfterLastSyncThenChangesContainData - changes contain data`() { val lastSyncTimestamp = DatabaseDateFormatter.iso8601(twoHoursAgo) setLastSyncTime(lastSyncTimestamp) @@ -445,7 +445,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenFavouritesAndBookmarksDeletedAfterLastSyncThenChangesContainData() { + fun `whenFavouritesAndBookmarksDeletedAfterLastSync - changes contain data`() { val lastSyncTimestamp = DatabaseDateFormatter.iso8601(twoHoursAgo) setLastSyncTime(lastSyncTimestamp) @@ -466,7 +466,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenFolderMovedToAnotherFolderAfterLastSyncThenChangesContainData() { + fun `whenFolderMovedToAnotherFolderAfterLastSyncThenChangesContainData - changes contain data`() { val beforeLastSyncTimestamp = DatabaseDateFormatter.iso8601(threeHoursAgo) val modificationTimestamp = DatabaseDateFormatter.iso8601(oneHourAgo) val lastSyncTimestamp = DatabaseDateFormatter.iso8601(twoHoursAgo) @@ -488,7 +488,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenNoChangesNeedSyncThenChildrenRequestIsNotAddedToMetadata() { + fun `whenNoChangesNeedSyncThenChildrenRequestIsNotAddedToMetadata - metadata not updated`() { val syncChanges = parser.allContent() assertTrue(syncChanges.isEmpty()) @@ -496,7 +496,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenChangesNeedSyncThenChildrenRequestIsAddedToMetadata() { + fun `getChanges - changes need sync - children request is added to metadata`() { repository.insert(bookmark3) repository.insert(bookmark4) diff --git a/app/src/test/java/com/duckduckgo/app/sync/algorithm/SavedSitesDeduplicationPersisterTest.kt b/app/src/test/java/com/duckduckgo/app/sync/algorithm/SavedSitesDeduplicationPersisterTest.kt index 0c05b382aeb8..b69bc2264c3a 100644 --- a/app/src/test/java/com/duckduckgo/app/sync/algorithm/SavedSitesDeduplicationPersisterTest.kt +++ b/app/src/test/java/com/duckduckgo/app/sync/algorithm/SavedSitesDeduplicationPersisterTest.kt @@ -112,7 +112,7 @@ class SavedSitesDeduplicationPersisterTest { } @Test - fun whenProcessingBookmarkNotPresentLocallyThenBookmarkIsInserted() { + fun `processBookmark - bookmark not present locally - inserted`() { val bookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", "timestamp") assertTrue(repository.getBookmarkById(bookmark.id) == null) @@ -122,7 +122,7 @@ class SavedSitesDeduplicationPersisterTest { } @Test - fun whenProcessingDeletedBookmarkNotPresentLocallyThenBookmarkIsNotInserted() { + fun `processBookmark - bookmark not present locally - not inserted`() { val bookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", "timestamp", deleted = "1") assertTrue(repository.getBookmarkById(bookmark.id) == null) @@ -132,7 +132,7 @@ class SavedSitesDeduplicationPersisterTest { } @Test - fun whenProcessingBookmarkDuplicateThenBookmarkIdIsReplaced() { + fun `processBookmark - duplicate bookmark - replaces bookmark id`() { val bookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", "timestamp") repository.insert(bookmark) @@ -149,7 +149,7 @@ class SavedSitesDeduplicationPersisterTest { } @Test - fun whenProcessingEmptyFavouriteFoldersThenFavouritesAreAdded() { + fun `processFavouritesFolder - empty favourite folders - favourites are added`() { // given some favourites val firstBatch = BookmarkTestUtils.givenSomeBookmarks(10) savedSitesEntitiesDao.insertList(firstBatch) @@ -164,7 +164,7 @@ class SavedSitesDeduplicationPersisterTest { } @Test - fun whenProcessingNotEmptyFavouriteFoldersThenFavouritesAreAdded() { + fun `processFavouritesFolder - state - all favourites are added`() { // given some favourites val firstBatch = BookmarkTestUtils.givenSomeBookmarks(10) savedSitesEntitiesDao.insertList(firstBatch) @@ -185,7 +185,7 @@ class SavedSitesDeduplicationPersisterTest { } @Test - fun whenProcessingFolderNotPresentLocallyThenFolderIsInserted() { + fun `processBookmarkFolder - folder not present locally - folder inserted`() { val folder = BookmarkFolder("folder1", "title", SavedSitesNames.BOOKMARKS_ROOT, 0, 0) assertTrue(repository.getFolder(folder.id) == null) @@ -195,7 +195,7 @@ class SavedSitesDeduplicationPersisterTest { } @Test - fun whenProcessingDeletedFolderNotPresentLocallyThenFolderIsNotInserted() { + fun `processBookmarkFolder - folder not present locally - folder not inserted`() { val folder = BookmarkFolder("folder1", "title", SavedSitesNames.BOOKMARKS_ROOT, 0, 0, deleted = "1") assertTrue(repository.getFolder(folder.id) == null) @@ -205,7 +205,7 @@ class SavedSitesDeduplicationPersisterTest { } @Test - fun whenProcessingFolderPresentLocallyThenFolderIsReplaced() { + fun `processBookmarkFolder - processing folder present locally - folder replaced`() { val folder = BookmarkFolder("folder1", "title", SavedSitesNames.BOOKMARKS_ROOT, 0, 0) repository.insert(folder) assertTrue(repository.getFolder(folder.id) != null) @@ -218,7 +218,7 @@ class SavedSitesDeduplicationPersisterTest { } @Test - fun whenProcessingRemoteDeletedFolderPresentLocallyThenFolderIsDeleted() { + fun `processBookmarkFolder - remote deleted folder present locally - folder is deleted`() { val folder = BookmarkFolder("folder1", "title", SavedSitesNames.BOOKMARKS_ROOT, 0, 0) repository.insert(folder) assertTrue(repository.getFolder(folder.id) != null) diff --git a/app/src/test/java/com/duckduckgo/app/sync/algorithm/SavedSitesDuplicateFinderTest.kt b/app/src/test/java/com/duckduckgo/app/sync/algorithm/SavedSitesDuplicateFinderTest.kt index fa7ef2a9a3b6..bcbd010d6dd8 100644 --- a/app/src/test/java/com/duckduckgo/app/sync/algorithm/SavedSitesDuplicateFinderTest.kt +++ b/app/src/test/java/com/duckduckgo/app/sync/algorithm/SavedSitesDuplicateFinderTest.kt @@ -109,7 +109,7 @@ class SavedSitesDuplicateFinderTest { } @Test - fun whenBookmarkAlreadyExistsThenDuplicateIsFound() { + fun `findBookmark - bookmark already exists - duplicate found`() { val bookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", "timestamp") repository.insert(bookmark) @@ -119,7 +119,7 @@ class SavedSitesDuplicateFinderTest { } @Test - fun whenBookmarkAlreadyExistsWithDifferentIdsAndUrlsThenDuplicateIsNotFound() { + fun `findBookmarkDuplicate - bookmark already exists with different ids and urls - not duplicate`() { val bookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", "timestamp") val updatedBookmark = Bookmark("bookmark2", "title", "www.examples.com", "folder2", "timestamp") repository.insert(bookmark) @@ -130,7 +130,7 @@ class SavedSitesDuplicateFinderTest { } @Test - fun whenBookmarkAlreadyExistsWithDifferentIdsAndSameUrlsThenDuplicateIsFound() { + fun `findBookmarkDuplicate - bookmark already exists with different ids and same urls - duplicate found`() { val bookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", "timestamp") val updatedBookmark = Bookmark("bookmark2", "title", "www.example.com", "folder2", "timestamp") repository.insert(bookmark) @@ -141,7 +141,7 @@ class SavedSitesDuplicateFinderTest { } @Test - fun whenBookmarkAlreadyExistsWithDifferentUrlThenDuplicateIsNotFound() { + fun `findBookmark - bookmark already exists with different url - not duplicate`() { val bookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", "timestamp") val updatedBookmark = Bookmark("bookmark1", "title", "www.examples.com", "folder2", "timestamp") repository.insert(bookmark) @@ -152,7 +152,7 @@ class SavedSitesDuplicateFinderTest { } @Test - fun whenBookmarkAlreadyExistsWithDifferentTitleThenDuplicateIsNotFound() { + fun `findBookmarkDuplicate - bookmark already exists with different title - not duplicate`() { val bookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", "timestamp") val updatedBookmark = Bookmark("bookmark1", "title1", "www.example.com", "folder2", "timestamp") repository.insert(bookmark) @@ -162,7 +162,7 @@ class SavedSitesDuplicateFinderTest { } @Test - fun whenBookmarkAlreadyExistsWithDifferentTitleAndIdsThenDuplicateIsNotFound() { + fun `findBookmarkDuplicate - bookmark already exists with different title and ids - not duplicate`() { val bookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", "timestamp") val updatedBookmark = Bookmark("bookmark2", "title1", "www.example.com", "folder2", "timestamp") repository.insert(bookmark) @@ -173,7 +173,7 @@ class SavedSitesDuplicateFinderTest { } @Test - fun whenBookmarkAlreadyExistsWithDifferentParentIdThenDuplicateIsNotFound() { + fun `findBookmarkDuplicate - bookmark already exists with different parent id - not duplicate`() { val bookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", "timestamp") val updatedBookmark = Bookmark("bookmark1", "title", "www.example.com", "folder3", "timestamp") repository.insert(bookmark) @@ -184,7 +184,7 @@ class SavedSitesDuplicateFinderTest { } @Test - fun whenBookmarkAlreadyExistsWithDifferentParentIdAndIdsThenDuplicateIsNotFound() { + fun `findBookmarkDuplicate - bookmark already exists with different parent id and ids - not duplicate`() { val bookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", "timestamp") val updatedBookmark = Bookmark("bookmark2", "title", "www.example.com", "folder3", "timestamp") repository.insert(bookmark) @@ -195,7 +195,7 @@ class SavedSitesDuplicateFinderTest { } @Test - fun whenBookmarkNotPresentThenDuplicateIsNotFound() { + fun `findBookmark - bookmark not present - not duplicate`() { val bookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", "timestamp") val result = duplicateFinder.findBookmarkDuplicate(bookmark) @@ -204,7 +204,7 @@ class SavedSitesDuplicateFinderTest { } @Test - fun whenFolderNotPresentThenDuplicateIsNotFound() { + fun `findFolder - not present - not found`() { val folder = BookmarkFolder("folder", "Folder", SavedSitesNames.BOOKMARKS_ROOT, 0, 0, "timestamp") val result = duplicateFinder.findFolderDuplicate(folder) @@ -213,7 +213,7 @@ class SavedSitesDuplicateFinderTest { } @Test - fun whenFolderPresentWithSameParentIdThenDuplicateIsFound() { + fun `findFolderDuplicate - folder present with same parent id - duplicate found`() { val folder = BookmarkFolder("folder1", "Folder", SavedSitesNames.BOOKMARKS_ROOT, 0, 0, "timestamp") val folder1 = BookmarkFolder("folder1", "Folder", SavedSitesNames.BOOKMARKS_ROOT, 0, 0, "timestamp") repository.insert(folder) @@ -224,7 +224,7 @@ class SavedSitesDuplicateFinderTest { } @Test - fun whenFolderPresentWithDifferentParentIdThenDuplicateIsNotFound() { + fun `findFolderDuplicate - folder present with different parent id - not duplicate`() { val folder = BookmarkFolder("folder1", "Folder", SavedSitesNames.BOOKMARKS_ROOT, 0, 0, "timestamp") val folder1 = BookmarkFolder("folder2", "Folder", folder.id, 2, 1, "timestamp") repository.insert(folder) @@ -235,7 +235,7 @@ class SavedSitesDuplicateFinderTest { } @Test - fun whenFolderPresentWithSameTitleDifferentParentIdThenDuplicateIsNotFound() { + fun `findFolderDuplicate - folder present with same title different parent id - not duplicate`() { val folder = BookmarkFolder("folder1", "Folder", SavedSitesNames.BOOKMARKS_ROOT, 0, 0, "timestamp") val folder1 = BookmarkFolder("folder2", "Folder", folder.id, 2, 1, "timestamp") repository.insert(folder) @@ -246,7 +246,7 @@ class SavedSitesDuplicateFinderTest { } @Test - fun whenFolderPresentWithSameTitleAndParentIdThenDuplicateIsNotFound() { + fun `findFolderDuplicate - folder present with same title and parent id - duplicate found`() { val folder = BookmarkFolder("folder1", "Folder", SavedSitesNames.BOOKMARKS_ROOT, 0, 0, "timestamp") val folder1 = BookmarkFolder("folder2", "Folder", SavedSitesNames.BOOKMARKS_ROOT, 0, 0, "timestamp") repository.insert(folder) diff --git a/app/src/test/java/com/duckduckgo/app/sync/algorithm/SavedSitesLocalWinsPersisterTest.kt b/app/src/test/java/com/duckduckgo/app/sync/algorithm/SavedSitesLocalWinsPersisterTest.kt index ede12b43f90c..ee6315e3747a 100644 --- a/app/src/test/java/com/duckduckgo/app/sync/algorithm/SavedSitesLocalWinsPersisterTest.kt +++ b/app/src/test/java/com/duckduckgo/app/sync/algorithm/SavedSitesLocalWinsPersisterTest.kt @@ -109,7 +109,7 @@ class SavedSitesLocalWinsPersisterTest { } @Test - fun whenProcessingBookmarkNotPresentLocallyThenBookmarkIsInserted() { + fun `processBookmark - bookmark not present locally - inserted`() { val bookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", twoHoursAgo) assertTrue(repository.getBookmarkById(bookmark.id) == null) @@ -119,7 +119,7 @@ class SavedSitesLocalWinsPersisterTest { } @Test - fun whenProcessingDeletedBookmarkNotPresentLocallyThenBookmarkIsNotInserted() { + fun `processBookmark - bookmark not present locally - not inserted`() { val bookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", twoHoursAgo, deleted = "1") assertTrue(repository.getBookmarkById(bookmark.id) == null) @@ -129,7 +129,7 @@ class SavedSitesLocalWinsPersisterTest { } @Test - fun whenProcessingRemoteBookmarkPresentLocallyThenBookmarkIsNotReplaced() { + fun `processBookmark - processing remote bookmark present locally - not replaced`() { val bookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", twoHoursAgo) repository.insert(bookmark) @@ -144,7 +144,7 @@ class SavedSitesLocalWinsPersisterTest { } @Test - fun whenProcessingDeletedRemoteBookmarkThenBookmarkIsDeleted() { + fun `processBookmark - processing deleted remote bookmark - bookmark is deleted`() { val bookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", twoHoursAgo) repository.insert(bookmark) @@ -158,7 +158,7 @@ class SavedSitesLocalWinsPersisterTest { } @Test - fun whenProcessingEmptyFavouriteFoldersThenFavouritesAreAdded() { + fun `processFavouritesFolder - empty favourite folders - favourites are added`() { // given some bookmarks val firstBatch = BookmarkTestUtils.givenSomeBookmarks(10) savedSitesEntitiesDao.insertList(firstBatch) @@ -173,7 +173,7 @@ class SavedSitesLocalWinsPersisterTest { } @Test - fun whenProcessingNotEmptyFavouriteFoldersThenFavouritesAreReplaced() { + fun `processFavouritesFolder - state - favourites replaced`() { // given some favourites val firstBatch = BookmarkTestUtils.givenSomeBookmarks(10) savedSitesEntitiesDao.insertList(firstBatch) @@ -194,7 +194,7 @@ class SavedSitesLocalWinsPersisterTest { } @Test - fun whenProcessingFolderNotPresentLocallyThenFolderIsInserted() { + fun `processBookmarkFolder - folder not present locally - folder inserted`() { val folder = BookmarkFolder("folder1", "title", SavedSitesNames.BOOKMARKS_ROOT, 0, 0) assertTrue(repository.getFolder(folder.id) == null) @@ -204,7 +204,7 @@ class SavedSitesLocalWinsPersisterTest { } @Test - fun whenProcessingDeletedFolderPresentLocallyThenFolderIsDeleted() { + fun `processBookmarkFolder - processing deleted folder present locally - folder is deleted`() { val folder = BookmarkFolder("folder1", "title", SavedSitesNames.BOOKMARKS_ROOT, 0, 0) repository.insert(folder) assertTrue(repository.getFolder(folder.id) != null) @@ -216,7 +216,7 @@ class SavedSitesLocalWinsPersisterTest { } @Test - fun whenProcessingFolderThenFolderIsNotReplaced() { + fun `processBookmarkFolder - folder not replaced`() { val folder = BookmarkFolder("folder1", "title", SavedSitesNames.BOOKMARKS_ROOT, 0, 0, lastModified = twoHoursAgo) repository.insert(folder) assertTrue(repository.getFolder(folder.id) != null) diff --git a/app/src/test/java/com/duckduckgo/app/sync/algorithm/SavedSitesRemoteWinsPersisterTest.kt b/app/src/test/java/com/duckduckgo/app/sync/algorithm/SavedSitesRemoteWinsPersisterTest.kt index 410ea278cc1a..429f183d5325 100644 --- a/app/src/test/java/com/duckduckgo/app/sync/algorithm/SavedSitesRemoteWinsPersisterTest.kt +++ b/app/src/test/java/com/duckduckgo/app/sync/algorithm/SavedSitesRemoteWinsPersisterTest.kt @@ -108,7 +108,7 @@ class SavedSitesRemoteWinsPersisterTest { } @Test - fun whenProcessingBookmarkNotPresentLocallyThenBookmarkIsInserted() { + fun `processBookmark - bookmark not present locally - inserted`() { val bookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", twoHoursAgo) assertTrue(repository.getBookmarkById(bookmark.id) == null) @@ -118,7 +118,7 @@ class SavedSitesRemoteWinsPersisterTest { } @Test - fun whenProcessingDeletedBookmarkNotPresentLocallyThenBookmarkIsNotInserted() { + fun `processBookmark - bookmark not present locally - not inserted`() { val bookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", twoHoursAgo, deleted = "1") assertTrue(repository.getBookmarkById(bookmark.id) == null) @@ -128,7 +128,7 @@ class SavedSitesRemoteWinsPersisterTest { } @Test - fun whenProcessingRemoteBookmarkPresentLocallyThenBookmarkIsReplaced() { + fun `processBookmark - processing remote bookmark present locally - bookmark is replaced`() { val bookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", twoHoursAgo) repository.insert(bookmark) @@ -143,7 +143,7 @@ class SavedSitesRemoteWinsPersisterTest { } @Test - fun whenProcessingDeletedRemoteBookmarkThenBookmarkIsDeleted() { + fun `processBookmark - processing deleted remote bookmark - bookmark is deleted`() { val bookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", twoHoursAgo) repository.insert(bookmark) @@ -157,7 +157,7 @@ class SavedSitesRemoteWinsPersisterTest { } @Test - fun whenProcessingEmptyFavouriteFoldersThenFavouritesAreAdded() { + fun `processFavouritesFolder - empty favourite folders - favourites are added`() { // given some bookmarks val firstBatch = BookmarkTestUtils.givenSomeBookmarks(10) savedSitesEntitiesDao.insertList(firstBatch) @@ -172,7 +172,7 @@ class SavedSitesRemoteWinsPersisterTest { } @Test - fun whenProcessingNotEmptyFavouriteFoldersThenFavouritesAreReplaced() { + fun `processFavouritesFolder - state - favourites replaced`() { // given some favourites val firstBatch = BookmarkTestUtils.givenSomeBookmarks(10) savedSitesEntitiesDao.insertList(firstBatch) @@ -193,7 +193,7 @@ class SavedSitesRemoteWinsPersisterTest { } @Test - fun whenProcessingFolderNotPresentLocallyThenFolderIsInserted() { + fun `processBookmarkFolder - folder not present locally - folder inserted`() { val folder = BookmarkFolder("folder1", "title", SavedSitesNames.BOOKMARKS_ROOT, 0, 0) assertTrue(repository.getFolder(folder.id) == null) @@ -203,7 +203,7 @@ class SavedSitesRemoteWinsPersisterTest { } @Test - fun whenProcessingDeletedFolderPresentLocallyThenFolderIsDeleted() { + fun `processBookmarkFolder - processing deleted folder present locally - folder is deleted`() { val folder = BookmarkFolder("folder1", "title", SavedSitesNames.BOOKMARKS_ROOT, 0, 0) repository.insert(folder) assertTrue(repository.getFolder(folder.id) != null) @@ -215,7 +215,7 @@ class SavedSitesRemoteWinsPersisterTest { } @Test - fun whenProcessingFolderThenFolderIsReplaced() { + fun `processBookmarkFolder - folder replaced`() { val folder = BookmarkFolder("folder1", "title", SavedSitesNames.BOOKMARKS_ROOT, 0, 0, lastModified = twoHoursAgo) repository.insert(folder) assertTrue(repository.getFolder(folder.id) != null) diff --git a/app/src/test/java/com/duckduckgo/app/sync/algorithm/SavedSitesTimestampPersisterTest.kt b/app/src/test/java/com/duckduckgo/app/sync/algorithm/SavedSitesTimestampPersisterTest.kt index 246a2d34539e..d2396becff00 100644 --- a/app/src/test/java/com/duckduckgo/app/sync/algorithm/SavedSitesTimestampPersisterTest.kt +++ b/app/src/test/java/com/duckduckgo/app/sync/algorithm/SavedSitesTimestampPersisterTest.kt @@ -111,7 +111,7 @@ class SavedSitesTimestampPersisterTest { } @Test - fun whenProcessingBookmarkNotPresentLocallyThenBookmarkIsInserted() { + fun `processBookmark - bookmark not present locally - inserted`() { val bookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", threeHoursAgo) assertTrue(repository.getBookmarkById(bookmark.id) == null) @@ -121,7 +121,7 @@ class SavedSitesTimestampPersisterTest { } @Test - fun whenProcessingDeletedBookmarkNotPresentLocallyThenBookmarkIsNotInserted() { + fun `processBookmark - bookmark not present locally - not inserted`() { val bookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", threeHoursAgo, deleted = "1") assertTrue(repository.getBookmarkById(bookmark.id) == null) @@ -131,7 +131,7 @@ class SavedSitesTimestampPersisterTest { } @Test - fun whenProcessingRemoteBookmarkModifiedAfterThenBookmarkIsReplaced() { + fun `processBookmark - bookmark modified after - bookmark is replaced`() { val bookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", threeHoursAgo) repository.insert(bookmark) @@ -146,7 +146,7 @@ class SavedSitesTimestampPersisterTest { } @Test - fun whenProcessingRemoteBookmarkModifiedBeforeThenBookmarkIsNotReplaced() { + fun `processBookmark - remote bookmark modified before - not replaced`() { val bookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", twoHoursAgo) repository.insert(bookmark) @@ -161,7 +161,7 @@ class SavedSitesTimestampPersisterTest { } @Test - fun whenProcessingDeletedRemoteBookmarkThenBookmarkIsDeleted() { + fun `processBookmark - bookmark deleted - bookmark is deleted`() { val bookmark = Bookmark("bookmark1", "title", "www.example.com", "folder2", threeHoursAgo) repository.insert(bookmark) @@ -175,7 +175,7 @@ class SavedSitesTimestampPersisterTest { } @Test - fun whenProcessingEmptyFavouriteFoldersThenFavouritesAreAdded() { + fun `processFavouritesFolder - empty favourite folders - favourites are added`() { // given some bookmarks val firstBatch = BookmarkTestUtils.givenSomeBookmarks(10) savedSitesEntitiesDao.insertList(firstBatch) @@ -190,7 +190,7 @@ class SavedSitesTimestampPersisterTest { } @Test - fun whenProcessingNotEmptyFavouriteFoldersThenFavouritesAreReplaced() { + fun `processFavouritesFolder - state - favourites replaced`() { // given some favourites val firstBatch = BookmarkTestUtils.givenSomeBookmarks(10) savedSitesEntitiesDao.insertList(firstBatch) @@ -211,7 +211,7 @@ class SavedSitesTimestampPersisterTest { } @Test - fun whenProcessingFolderNotPresentLocallyThenFolderIsInserted() { + fun `processBookmarkFolder - folder not present locally - folder inserted`() { val folder = BookmarkFolder("folder1", "title", SavedSitesNames.BOOKMARKS_ROOT, 0, 0) assertTrue(repository.getFolder(folder.id) == null) @@ -221,7 +221,7 @@ class SavedSitesTimestampPersisterTest { } @Test - fun whenProcessingDeletedFolderPresentLocallyThenFolderIsDeleted() { + fun `processBookmarkFolder - processing deleted folder present locally - folder is deleted`() { val folder = BookmarkFolder("folder1", "title", SavedSitesNames.BOOKMARKS_ROOT, 0, 0) repository.insert(folder) assertTrue(repository.getFolder(folder.id) != null) @@ -233,7 +233,7 @@ class SavedSitesTimestampPersisterTest { } @Test - fun whenProcessingFolderModifiedAfterThenFolderIsReplaced() { + fun `processBookmarkFolder - folder modified after - folder replaced`() { val folder = BookmarkFolder("folder1", "title", SavedSitesNames.BOOKMARKS_ROOT, 0, 0, lastModified = threeHoursAgo) repository.insert(folder) assertTrue(repository.getFolder(folder.id) != null) @@ -246,7 +246,7 @@ class SavedSitesTimestampPersisterTest { } @Test - fun whenProcessingFolderModifiedBeforeThenFolderIsNotReplaced() { + fun `processBookmarkFolder - folder modified before - not replaced`() { val folder = BookmarkFolder("folder1", "title", SavedSitesNames.BOOKMARKS_ROOT, 0, 0, lastModified = twoHoursAgo) repository.insert(folder) assertTrue(repository.getFolder(folder.id) != null) @@ -259,7 +259,7 @@ class SavedSitesTimestampPersisterTest { } @Test - fun whenProcessingFolderSameTimestampThenFolderIsReplaced() { + fun `processBookmarkFolder - same timestamp - folder replaced`() { val timestamp = twoHoursAgo val folder = BookmarkFolder("folder1", "title", SavedSitesNames.BOOKMARKS_ROOT, 0, 0, lastModified = timestamp) repository.insert(folder) diff --git a/app/src/test/java/com/duckduckgo/app/systemsearch/DeviceAppLookupTest.kt b/app/src/test/java/com/duckduckgo/app/systemsearch/DeviceAppLookupTest.kt index 485c0a3b2bd2..c56289a15a14 100644 --- a/app/src/test/java/com/duckduckgo/app/systemsearch/DeviceAppLookupTest.kt +++ b/app/src/test/java/com/duckduckgo/app/systemsearch/DeviceAppLookupTest.kt @@ -35,7 +35,7 @@ class DeviceAppLookupTest { private val testee = InstalledDeviceAppLookup(mockAppProvider) @Test - fun whenQueryMatchesWordInShortNameThenMatchesAreReturned() { + fun `query - matches word in short name - matches are returned`() { whenever(mockAppProvider.get()).thenReturn(apps) val result = testee.query("DDG") assertEquals(3, result.size) @@ -45,7 +45,7 @@ class DeviceAppLookupTest { } @Test - fun whenQueryMatchesWordPrefixInShortNameThenMatchesAreReturned() { + fun `query - matches word prefix in short name - matches are returned`() { whenever(mockAppProvider.get()).thenReturn(apps) val result = testee.query("DDG") assertEquals(3, result.size) @@ -55,7 +55,7 @@ class DeviceAppLookupTest { } @Test - fun whenQueryMatchesPastShortNameWordBoundaryToNextPrefixThenMatchesAreReturned() { + fun `query - past short name word boundary to next prefix - matches are returned`() { whenever(mockAppProvider.get()).thenReturn(apps) val result = testee.query("DDG M") assertEquals(2, result.size) @@ -64,7 +64,7 @@ class DeviceAppLookupTest { } @Test - fun whenQueryMatchesWordPrefixInShortNameWithDifferentCaseThenMatchesAreReturned() { + fun `query - matches word prefix in short name with different case - matches are returned`() { whenever(mockAppProvider.get()).thenReturn(apps) val result = testee.query("ddg") assertEquals(3, result.size) @@ -74,35 +74,35 @@ class DeviceAppLookupTest { } @Test - fun whenQueryMatchesMiddleOrSuffixOfAppNameWordThenNoAppsReturned() { + fun `query - query matches middle or suffix of app name word - no apps returned`() { whenever(mockAppProvider.get()).thenReturn(apps) val result = testee.query("DG") assertTrue(result.isEmpty()) } @Test - fun whenQueryDoesNotMatchAnyPartOfAppNameThenNoAppsReturned() { + fun `query - no apps returned - empty`() { whenever(mockAppProvider.get()).thenReturn(apps) val result = testee.query("nonmatching") assertTrue(result.isEmpty()) } @Test - fun whenQueryIsEmptyThenNoAppsReturned() { + fun `query - empty query - no apps returned`() { whenever(mockAppProvider.get()).thenReturn(apps) val result = testee.query("") assertTrue(result.isEmpty()) } @Test - fun whenAppsListIsEmptyThenNoAppsReturned() { + fun `query - apps list empty - no apps returned`() { whenever(mockAppProvider.get()).thenReturn(noApps) val result = testee.query("DDG") assertTrue(result.isEmpty()) } @Test - fun whenQueryMatchesAppNameWithSpecialRegexCharactersThenAppReturnedWithoutCrashing() { + fun `query - app matches app name with special regex characters - app returned without crashing`() { whenever(mockAppProvider.get()).thenReturn(apps) val result = testee.query(APP_WITH_RESERVED_CHARS) assertEquals(1, result.size) diff --git a/app/src/test/java/com/duckduckgo/app/systemsearch/SystemSearchViewModelTest.kt b/app/src/test/java/com/duckduckgo/app/systemsearch/SystemSearchViewModelTest.kt index b8243947fb92..dc1e8c2cf0f3 100644 --- a/app/src/test/java/com/duckduckgo/app/systemsearch/SystemSearchViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/systemsearch/SystemSearchViewModelTest.kt @@ -97,7 +97,7 @@ class SystemSearchViewModelTest { } @Test - fun whenOnboardingShouldNotShowThenViewIsNotVisibleAndUnexpanded() = runTest { + fun `onboardingShouldNotShow - view state not visible and unexpanded`() = runTest { whenever(mockUserStageStore.getUserAppStage()).thenReturn(AppStage.DAX_ONBOARDING) testee.resetViewState() @@ -107,7 +107,7 @@ class SystemSearchViewModelTest { } @Test - fun whenOnboardingShouldShowThenViewIsVisibleAndUnexpanded() = runTest { + fun `onboarding - shows onboarding view - is visible and unexpanded`() = runTest { whenever(mockUserStageStore.getUserAppStage()).thenReturn(AppStage.NEW) testee.resetViewState() @@ -117,14 +117,14 @@ class SystemSearchViewModelTest { } @Test - fun whenOnboardingShownThenPixelSent() = runTest { + fun `resetViewState - onboarding shown - pixel sent`() = runTest { whenever(mockUserStageStore.getUserAppStage()).thenReturn(AppStage.NEW) testee.resetViewState() verify(mockPixel).fire(INTERSTITIAL_ONBOARDING_SHOWN) } @Test - fun whenOnboardingIsUnexpandedAndUserPressesToggleThenItIsExpandedAndPixelSent() = runTest { + fun `onboardingToggle - onboarding expanded and pixel sent`() = runTest { whenOnboardingShowing() testee.userTappedOnboardingToggle() @@ -134,7 +134,7 @@ class SystemSearchViewModelTest { } @Test - fun whenOnboardingIsExpandedAndUserPressesToggleThenItIsUnexpandedAndPixelSent() = runTest { + fun `onboardingIsExpandedAndUserPressesToggle - onboarding unexpanded and pixel sent`() = runTest { whenOnboardingShowing() testee.userTappedOnboardingToggle() // first press to expand testee.userTappedOnboardingToggle() // second press to minimize @@ -145,7 +145,7 @@ class SystemSearchViewModelTest { } @Test - fun whenOnboardingIsDismissedThenViewHiddenPixelSentAndOnboardingStoreNotified() = runTest { + fun `onboardingIsDismissed - view hidden pixel sent and onboarding store notified`() = runTest { whenOnboardingShowing() testee.userDismissedOnboarding() @@ -156,7 +156,7 @@ class SystemSearchViewModelTest { } @Test - fun whenUserUpdatesQueryThenViewStateUpdated() = runTest { + fun `userUpdatedQuery - viewState updated`() = runTest { testee.userUpdatedQuery(QUERY) val newViewState = testee.resultsViewState.value as SystemSearchResultsViewState @@ -166,7 +166,7 @@ class SystemSearchViewModelTest { } @Test - fun whenUserAddsSpaceToQueryThenViewStateMatchesAndSpaceTrimmedFromAutocomplete() = runTest { + fun `userUpdatedQuery - view state matches and space trimmed from autocomplete`() = runTest { testee.userUpdatedQuery(QUERY) testee.userUpdatedQuery("$QUERY ") @@ -177,7 +177,7 @@ class SystemSearchViewModelTest { } @Test - fun whenUsersUpdatesWithAutoCompleteEnabledThenAutoCompleteSuggestionsIsNotEmpty() = runTest { + fun `userUpdated - autoComplete suggestions is not empty`() = runTest { doReturn(true).whenever(mockSettingsStore).autoCompleteSuggestionsEnabled testee.userUpdatedQuery(QUERY) @@ -188,7 +188,7 @@ class SystemSearchViewModelTest { } @Test - fun whenUsersUpdatesWithAutoCompleteDisabledThenViewStateReset() = runTest { + fun `userUpdated - autoComplete disabled - view state reset`() = runTest { doReturn(false).whenever(mockSettingsStore).autoCompleteSuggestionsEnabled testee.userUpdatedQuery(QUERY) @@ -196,7 +196,7 @@ class SystemSearchViewModelTest { } @Test - fun whenUserClearsQueryThenViewStateReset() = runTest { + fun `userClearsQuery - viewState reset`() = runTest { testee.userUpdatedQuery(QUERY) testee.userRequestedClear() @@ -204,7 +204,7 @@ class SystemSearchViewModelTest { } @Test - fun whenUsersUpdatesWithBlankQueryThenViewStateReset() = runTest { + fun `userUpdatedQuery - view state reset`() = runTest { testee.userUpdatedQuery(QUERY) testee.userUpdatedQuery(BLANK_QUERY) @@ -212,7 +212,7 @@ class SystemSearchViewModelTest { } @Test - fun whenUserSubmitsQueryThenBrowserLaunchedWithQueryAndPixelSent() { + fun `userSubmittedQuery - browser launched with query and pixel sent`() { testee.userSubmittedQuery(QUERY) verify(commandObserver, atLeastOnce()).onChanged(commandCaptor.capture()) assertEquals(Command.LaunchBrowser(QUERY), commandCaptor.lastValue) @@ -220,7 +220,7 @@ class SystemSearchViewModelTest { } @Test - fun whenUserSubmitsQueryWithSpaceThenBrowserLaunchedWithTrimmedQueryAndPixelSent() { + fun `userSubmitsQueryWithSpace - browser launched with trimmed query and pixel sent`() { testee.userSubmittedQuery("$QUERY ") verify(commandObserver, atLeastOnce()).onChanged(commandCaptor.capture()) assertEquals(Command.LaunchBrowser(QUERY), commandCaptor.lastValue) @@ -228,20 +228,20 @@ class SystemSearchViewModelTest { } @Test - fun whenUserSubmitsBlankQueryThenIgnored() { + fun `userSubmitsBlankQuery - ignored - does not launch browser`() { testee.userSubmittedQuery(BLANK_QUERY) assertFalse(commandCaptor.allValues.any { it is Command.LaunchBrowser }) verify(mockPixel, never()).fire(INTERSTITIAL_LAUNCH_BROWSER_QUERY) } @Test - fun whenUserSubmitsQueryThenOnboardingCompleted() = runTest { + fun `userSubmittedQuery - onboarding completed - stage completed`() = runTest { testee.userSubmittedQuery(QUERY) verify(mockUserStageStore).stageCompleted(AppStage.NEW) } @Test - fun whenUserSubmitsAutocompleteResultThenBrowserLaunchedAndPixelSent() { + fun `userSubmitsAutocompleteResult - browser launched and pixel sent`() { testee.userSubmittedAutocompleteResult(AUTOCOMPLETE_RESULT) verify(commandObserver, atLeastOnce()).onChanged(commandCaptor.capture()) assertEquals(Command.LaunchBrowser(AUTOCOMPLETE_RESULT), commandCaptor.lastValue) @@ -249,7 +249,7 @@ class SystemSearchViewModelTest { } @Test - fun whenUserSelectsAppResultThenAppLaunchedAndPixelSent() { + fun `userSelectsApp - app launched and pixel sent`() { testee.userSelectedApp(deviceApp) verify(commandObserver, atLeastOnce()).onChanged(commandCaptor.capture()) assertEquals(Command.LaunchDeviceApplication(deviceApp), commandCaptor.lastValue) @@ -257,7 +257,7 @@ class SystemSearchViewModelTest { } @Test - fun whenUserTapsDaxThenAppLaunchedAndPixelSent() { + fun `userTapsDax - app launched and pixel sent`() { testee.userTappedDax() verify(commandObserver, atLeastOnce()).onChanged(commandCaptor.capture()) assertTrue(commandCaptor.lastValue is LaunchDuckDuckGo) @@ -265,18 +265,18 @@ class SystemSearchViewModelTest { } @Test - fun whenUserTapsDaxThenOnboardingCompleted() = runTest { + fun `userTappedDax - onboarding completed - stage completed`() = runTest { testee.userTappedDax() verify(mockUserStageStore).stageCompleted(AppStage.NEW) } @Test - fun whenViewModelCreatedThenAppsRefreshed() = runTest { + fun `whenViewModelCreated - apps refreshed`() = runTest { verify(mockDeviceAppLookup).refreshAppList() } @Test - fun whenUserSelectsAppThatCannotBeFoundThenAppsRefreshedAndUserMessageShown() = runTest { + fun `appNotFound - user selects app that cannot be found - show app not found message`() = runTest { testee.appNotFound(deviceApp) verify(mockDeviceAppLookup, times(2)).refreshAppList() verify(commandObserver, atLeastOnce()).onChanged(commandCaptor.capture()) @@ -284,7 +284,7 @@ class SystemSearchViewModelTest { } @Test - fun whenUserSelectedToUpdateQueryThenEditQueryCommandSent() { + fun `onUserSelectedToEditQuery - edit query command sent`() { val query = "test" testee.onUserSelectedToEditQuery(query) verify(commandObserver, atLeastOnce()).onChanged(commandCaptor.capture()) @@ -292,7 +292,7 @@ class SystemSearchViewModelTest { } @Test - fun whenQuickAccessItemClickedThenLaunchBrowser() { + fun `onQuickAccessItemClicked - launch browser`() { val quickAccessItem = QuickAccessFavorite(Favorite("favorite1", "title", "http://example.com", "timestamp", 0)) testee.onQuickAccessItemClicked(quickAccessItem) @@ -302,7 +302,7 @@ class SystemSearchViewModelTest { } @Test - fun whenQuickAccessItemClickedThenPixelSent() { + fun `onQuickAccessItemClicked - pixel sent`() { val quickAccessItem = QuickAccessFavorite(Favorite("favorite1", "title", "http://example.com", "timestamp", 0)) testee.onQuickAccessItemClicked(quickAccessItem) @@ -311,7 +311,7 @@ class SystemSearchViewModelTest { } @Test - fun whenQuickAccessItemEditRequestedThenLaunchEditDialog() { + fun `onEditQuickAccessItemRequested - launch edit dialog`() { val quickAccessItem = QuickAccessFavorite(Favorite("favorite1", "title", "http://example.com", "timestamp", 0)) testee.onEditQuickAccessItemRequested(quickAccessItem) @@ -321,7 +321,7 @@ class SystemSearchViewModelTest { } @Test - fun whenQuickAccessItemDeleteRequestedThenShowDeleteFavoriteConfirmation() { + fun `onDeleteQuickAccessItemRequested - show delete favorite confirmation`() { val quickAccessItem = QuickAccessFavorite(Favorite("favorite1", "title", "http://example.com", "timestamp", 0)) testee.onDeleteQuickAccessItemRequested(quickAccessItem) @@ -331,7 +331,7 @@ class SystemSearchViewModelTest { } @Test - fun whenSavedSiteDeleteRequestedThenShowDeleteSavedSiteConfirmation() { + fun `onDeleteSavedSiteRequested - show delete saved site confirmation`() { val quickAccessItem = QuickAccessFavorite(Favorite("favorite1", "title", "http://example.com", "timestamp", 0)) testee.onDeleteSavedSiteRequested(quickAccessItem) @@ -341,7 +341,7 @@ class SystemSearchViewModelTest { } @Test - fun whenQuickAccessEditedThenRepositoryUpdated() { + fun `onFavouriteEdited - repository updated`() { val savedSite = Favorite("favorite1", "title", "http://example.com", "timestamp", 0) testee.onFavouriteEdited(savedSite) @@ -350,7 +350,7 @@ class SystemSearchViewModelTest { } @Test - fun whenQuickAccessDeleteRequestedThenFavouriteDeletedFromViewState() = runTest { + fun `onDeleteQuickAccessItemRequested - view state updated`() = runTest { val savedSite = Favorite("favorite1", "title", "http://example.com", "timestamp", 0) whenever(mocksavedSitesRepository.getFavorites()).thenReturn(flowOf(listOf(savedSite))) testee = SystemSearchViewModel( @@ -374,7 +374,7 @@ class SystemSearchViewModelTest { } @Test - fun whenQuickAccessDeleteUndoThenViewStateUpdated() = runTest { + fun `undoDelete - view state updated`() = runTest { val savedSite = Favorite("favorite1", "title", "http://example.com", "timestamp", 0) whenever(mocksavedSitesRepository.getFavorites()).thenReturn(flowOf(listOf(savedSite))) testee = SystemSearchViewModel( @@ -397,7 +397,7 @@ class SystemSearchViewModelTest { } @Test - fun whenQuickAccessDeletedThenRepositoryDeletesFavorite() = runTest { + fun `deleteFavorite - quick access deleted - repository deletes favorite`() = runTest { val savedSite = Favorite("favorite1", "title", "http://example.com", "timestamp", 0) testee.deleteFavoriteSnackbarDismissed(savedSite) @@ -406,7 +406,7 @@ class SystemSearchViewModelTest { } @Test - fun whenAssociatedBookmarkDeletedThenRepositoryDeletesBookmark() = runTest { + fun `deleteSavedSite - repository deletes bookmark`() = runTest { val savedSite = Favorite("favorite1", "title", "http://example.com", "timestamp", 0) testee.deleteSavedSiteSnackbarDismissed(savedSite) @@ -415,7 +415,7 @@ class SystemSearchViewModelTest { } @Test - fun whenQuickAccessListChangedThenRepositoryUpdated() { + fun `onQuickAccessListChanged - repository updated`() { val savedSite = Favorite("favorute1", "title", "http://example.com", "timestamp", 0) val savedSites = listOf(QuickAccessFavorite(savedSite)) @@ -425,7 +425,7 @@ class SystemSearchViewModelTest { } @Test - fun whenUserHasFavoritesThenInitialStateShowsFavorites() { + fun `whenUserHasFavorites - initialState shows favorites`() { val savedSite = Favorite("favorite1", "title", "http://example.com", "timestamp", 0) whenever(mocksavedSitesRepository.getFavorites()).thenReturn(flowOf(listOf(savedSite))) testee = SystemSearchViewModel( @@ -445,7 +445,7 @@ class SystemSearchViewModelTest { } @Test - fun whenVoiceSearchDisabledThenShouldEmitUpdateVoiceSearchCommand() { + fun `voiceSearchDisabled - should emit update voice search command`() { testee.voiceSearchDisabled() verify(commandObserver, atLeastOnce()).onChanged(commandCaptor.capture()) diff --git a/app/src/test/java/com/duckduckgo/app/tabs/ui/TabRendererExtensionTest.kt b/app/src/test/java/com/duckduckgo/app/tabs/ui/TabRendererExtensionTest.kt index 325f009f55cd..2b810af6ae05 100644 --- a/app/src/test/java/com/duckduckgo/app/tabs/ui/TabRendererExtensionTest.kt +++ b/app/src/test/java/com/duckduckgo/app/tabs/ui/TabRendererExtensionTest.kt @@ -32,38 +32,38 @@ class TabRendererExtensionTest { private val context: Context = mock() @Test - fun whenTabIsBlankThenDisplayTitleIsDuckDuckGo() { + fun `getHomeTab - tab is blank - display title is duckduckgo`() { whenever(context.getString(R.string.homeTab)).thenReturn("DuckDuckGo") assertEquals("DuckDuckGo", TabEntity("", position = 0).displayTitle(context)) } @Test - fun whenTabHasTitleThenDisplayTitleIsSame() { + fun `whenTabHasTitle - display title same`() { assertEquals(TITLE, TabEntity("", URL, TITLE, position = 0).displayTitle(context)) } @Test - fun whenTabDoesNotHaveTitleThenDisplayTitleIsUrlHost() { + fun `getDisplayTitle - tab does not have title - url host`() { assertEquals("example.com", TabEntity("", URL, null, position = 0).displayTitle(context)) } @Test - fun whenTabDoesNotHaveTitleAndUrlIsInvalidThenTitleIsBlank() { + fun `displayTitle - tab does not have title and url is invalid - title is blank`() { assertEquals("", TabEntity("", INVALID_URL, null, position = 0).displayTitle(context)) } @Test - fun whenTabIsBlankThenUrlIsDuckDuckGo() { + fun `getDisplayUrl - tab is blank - duckduckgo`() { assertEquals("https://duckduckgo.com", TabEntity("", position = 0).displayUrl()) } @Test - fun whenTabHasUrlThenDisplayUrlIsSame() { + fun `whenTabHasUrl - display url same`() { assertEquals(URL, TabEntity("", URL, TITLE, position = 0).displayUrl()) } @Test - fun whenTabDoesNotHaveAUrlThenDisplayUrlIsBlank() { + fun `getDisplayUrl - tab does not have a url - is blank`() { assertEquals("", TabEntity("", null, TITLE, position = 0).displayUrl()) } diff --git a/app/src/test/java/com/duckduckgo/app/tabs/ui/TabSwitcherViewModelTest.kt b/app/src/test/java/com/duckduckgo/app/tabs/ui/TabSwitcherViewModelTest.kt index ca5e2294beb6..aecf29a94fc9 100644 --- a/app/src/test/java/com/duckduckgo/app/tabs/ui/TabSwitcherViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/tabs/ui/TabSwitcherViewModelTest.kt @@ -96,7 +96,7 @@ class TabSwitcherViewModelTest { } @Test - fun whenNewTabRequestedThenRepositoryNotifiedAndSwitcherClosed() = runTest { + fun `onNewTabRequested - repository notified and switcher closed`() = runTest { testee.onNewTabRequested() verify(mockTabRepository).add() verify(mockCommandObserver).onChanged(commandCaptor.capture()) @@ -104,7 +104,7 @@ class TabSwitcherViewModelTest { } @Test - fun whenTabSelectedThenRepositoryNotifiedAndSwitcherClosed() = runTest { + fun `onTabSelected - repository notified and switcher closed`() = runTest { testee.onTabSelected(TabEntity("abc", "", "", position = 0)) verify(mockTabRepository).select(eq("abc")) verify(mockCommandObserver).onChanged(commandCaptor.capture()) @@ -112,7 +112,7 @@ class TabSwitcherViewModelTest { } @Test - fun whenTabDeletedThenRepositoryNotified() = runTest { + fun `onTabDeleted - repository notified`() = runTest { val entity = TabEntity("abc", "", "", position = 0) testee.onTabDeleted(entity) verify(mockTabRepository).delete(entity) @@ -120,7 +120,7 @@ class TabSwitcherViewModelTest { } @Test - fun whenOnMarkTabAsDeletableThenCallMarkDeletable() = runTest { + fun `onMarkTabAsDeletable - call mark deletable`() = runTest { val entity = TabEntity("abc", "", "", position = 0) testee.onMarkTabAsDeletable(entity) @@ -129,7 +129,7 @@ class TabSwitcherViewModelTest { } @Test - fun whenUndoDeletableTabThenUndoDeletable() = runTest { + fun `undoDeletableTab - undo deletable tab - undo deletable`() = runTest { val entity = TabEntity("abc", "", "", position = 0) testee.undoDeletableTab(entity) @@ -137,14 +137,14 @@ class TabSwitcherViewModelTest { } @Test - fun whenPurgeDeletableTabsThenCallRepositoryPurgeDeletableTabs() = runTest { + fun `purgeDeletableTabs - call repository purge deletable tabs`() = runTest { testee.purgeDeletableTabs() verify(mockTabRepository).purgeDeletableTabs() } @Test - fun whenRepositoryDeletableTabsUpdatesThenDeletableTabsEmits() = runTest { + fun `repoDeletableTabs - updates - emits deletable tabs`() = runTest { val tab = TabEntity("ID", position = 0) val expectedTabs = listOf(listOf(), listOf(tab)) @@ -158,7 +158,7 @@ class TabSwitcherViewModelTest { } @Test - fun whenRepositoryDeletableTabsEmitsSameValueThenDeletableTabsEmitsAll() = runTest { + fun `repoDeletableTabs - emits same value - emits all`() = runTest { val tab = TabEntity("ID", position = 0) testee.deletableTabs.observeForever { @@ -170,7 +170,7 @@ class TabSwitcherViewModelTest { } @Test - fun whenOnCloseAllTabsRequestedThenEmitCommandCloseAllTabsRequest() = runTest { + fun `onCloseAllTabsRequested - emit command close all tabs request`() = runTest { testee.onCloseAllTabsRequested() verify(mockCommandObserver).onChanged(commandCaptor.capture()) @@ -178,7 +178,7 @@ class TabSwitcherViewModelTest { } @Test - fun whenOnCloseAllTabsConfirmedThenTabDeletedAndTabIdClearedAndSessionDeleted() = runTest { + fun `onCloseAllTabsConfirmed - tab deleted and session cleared - tab id cleared`() = runTest { val tab = TabEntity("ID", position = 0) tabs.postValue(listOf(tab)) diff --git a/app/src/test/java/com/duckduckgo/app/trackerdetection/CloakedCnameDetectorImplTest.kt b/app/src/test/java/com/duckduckgo/app/trackerdetection/CloakedCnameDetectorImplTest.kt index 5fd5932bd1c9..226d0c478530 100644 --- a/app/src/test/java/com/duckduckgo/app/trackerdetection/CloakedCnameDetectorImplTest.kt +++ b/app/src/test/java/com/duckduckgo/app/trackerdetection/CloakedCnameDetectorImplTest.kt @@ -44,20 +44,20 @@ class CloakedCnameDetectorImplTest { } @Test - fun whenDetectCnameAndHostIsNullThenReturnNull() { + fun `detectCname - host and cname null - returns null`() { whenever(mockUri.host).thenReturn(null) assertNull(testee.detectCnameCloakedHost("foo.com", mockUri)) } @Test - fun whenDetectCnameAndCnameDetectedThenReturnUncloakedHost() { + fun `detectCname - cname detected - return uncloaked host`() { whenever(mockUri.host).thenReturn("host.com") whenever(mockCnameEntityDao.get(any())).thenReturn(TdsCnameEntity("host.com", "uncloaked-host.com")) assertEquals("http://uncloaked-host.com", testee.detectCnameCloakedHost("foo.com", mockUri)) } @Test - fun whenDetectCnameAndCnameDetectedAndHasSchemeThenReturnUncloakedHostWithScheme() { + fun `detectCname - has scheme - returns uncloaked host with scheme`() { whenever(mockUri.host).thenReturn("host.com") whenever(mockUri.scheme).thenReturn("https") whenever(mockCnameEntityDao.get(any())).thenReturn(TdsCnameEntity("host.com", "uncloaked-host.com")) @@ -65,14 +65,14 @@ class CloakedCnameDetectorImplTest { } @Test - fun whenDetectCnameAndCnameNotDetectedThenReturnNull() { + fun `detectCname - cname not detected - return null`() { whenever(mockUri.host).thenReturn("host.com") whenever(mockCnameEntityDao.get(any())).thenReturn(null) assertEquals(null, testee.detectCnameCloakedHost("foo.com", mockUri)) } @Test - fun whenDetectCnameAndCnameDetectedAndHasPathThenReturnUncloakedHostWithPathAppended() { + fun `detectCname - has path - return uncloaked host with path appended`() { whenever(mockUri.host).thenReturn("host.com") whenever(mockUri.path).thenReturn("/path") whenever(mockCnameEntityDao.get(any())).thenReturn(TdsCnameEntity("host.com", "uncloaked-host.com")) @@ -80,7 +80,7 @@ class CloakedCnameDetectorImplTest { } @Test - fun whenDetectCnameAndCnameDetectedAndHasSchemeAndPathThenReturnUncloakedHostWithSchemeAndPathAppended() { + fun `detectCname - has scheme and path - returns uncloaked host with scheme and path appended`() { whenever(mockUri.host).thenReturn("host.com") whenever(mockUri.path).thenReturn("/path") whenever(mockUri.scheme).thenReturn("https") @@ -89,13 +89,13 @@ class CloakedCnameDetectorImplTest { } @Test - fun whenRequestUrlIsInAllowListThenReturnNull() { + fun `detectCnameCloakedHost - request url in allow list - return null`() { whenever(mockTrackerAllowList.isAnException(anyString(), anyString())).thenReturn(true) assertEquals(null, testee.detectCnameCloakedHost("foo.com", mockUri)) } @Test - fun whenDetectCnameCloakedHostAndUrlIsInUserAllowListThenReturnNull() { + fun `detectCnameCloakedHost - user allow list - return null`() { whenever(mockUserAllowListRepository.isUriInUserAllowList(any())).thenReturn(true) assertNull(testee.detectCnameCloakedHost("foo.com", mockUri)) } diff --git a/app/src/test/java/com/duckduckgo/app/trackerdetection/EntityLookupTest.kt b/app/src/test/java/com/duckduckgo/app/trackerdetection/EntityLookupTest.kt index 53458865c1d0..06ee3ab09f2a 100644 --- a/app/src/test/java/com/duckduckgo/app/trackerdetection/EntityLookupTest.kt +++ b/app/src/test/java/com/duckduckgo/app/trackerdetection/EntityLookupTest.kt @@ -38,7 +38,7 @@ class EntityLookupTest { private var testee = TdsEntityLookup(mockEntityDao, mockDomainEntityDao) @Test - fun whenUrlContainsOneUnmatchedDomainThenNoValueIsReturned() { + fun `entityForUrl - url contains one unmatched domain - no value returned`() { val url = "a.com" whenever(mockDomainEntityDao.get(url)).thenReturn(null) @@ -48,7 +48,7 @@ class EntityLookupTest { } @Test - fun whenUrlContainsOneMatchingDomainThenValueIsReturned() { + fun `entityForUrl - url contains one matching domain - returns value`() { val url = "a.com" whenever(mockDomainEntityDao.get(url)).thenReturn(anEntityDomain()) whenever(mockEntityDao.get(anEntityName())).thenReturn(anEntity()) @@ -57,7 +57,7 @@ class EntityLookupTest { } @Test - fun whenUrlContainsOneMatchingDomainThenDomainIsSearchedFor() { + fun `entityForUrl - url contains one matching domain - search for domain`() { val url = "a.com" testee.entityForUrl("https://$url") verify(mockDomainEntityDao).get("a.com") @@ -65,7 +65,7 @@ class EntityLookupTest { } @Test - fun whenUrlContainsOneUnmatchedSubDomainAndOneMatchingDomainThenValueIsReturned() { + fun `entityForUrl - url contains one unmatched subdomain and one matching domain - returns value`() { val url = "a.b.com" whenever(mockDomainEntityDao.get(url)).thenReturn(anEntityDomain()) whenever(mockEntityDao.get(anEntityName())).thenReturn(anEntity()) @@ -75,7 +75,7 @@ class EntityLookupTest { } @Test - fun whenUrlContainsOneMultipartTldThenTldIsSearchedForInDb() { + fun `entityForUrl - url contains one multipart TLD - search for in DB`() { val url = "a.co.uk" testee.entityForUrl("https://$url") verify(mockDomainEntityDao).get("a.co.uk") @@ -83,7 +83,7 @@ class EntityLookupTest { } @Test - fun whenUrlContainsManyUnmatchedSubdomainsThenAllIntermediateValuesAreSearchedFor() { + fun `entityForUrl - url contains many unmatched subdomains - all intermediate values are searched for`() { val url = "a.b.c.com" whenever(mockDomainEntityDao.get("a.b.c.com")).thenReturn(null) whenever(mockDomainEntityDao.get("b.c.com")).thenReturn(null) @@ -98,7 +98,7 @@ class EntityLookupTest { } @Test - fun whenUrlContainsManyMatchingSubdomainsThenSearchingStopsWhenValueFound() { + fun `entityForUrl - url contains many matching subdomains - stops when value found`() { val url = "a.b.c.com" whenever(mockDomainEntityDao.get("a.b.c.com")).thenReturn(null) whenever(mockDomainEntityDao.get("b.c.com")).thenReturn(anEntityDomain()) diff --git a/app/src/test/java/com/duckduckgo/app/trackerdetection/TdsClientTest.kt b/app/src/test/java/com/duckduckgo/app/trackerdetection/TdsClientTest.kt index cd3e2aae081e..e27ce05c6a40 100644 --- a/app/src/test/java/com/duckduckgo/app/trackerdetection/TdsClientTest.kt +++ b/app/src/test/java/com/duckduckgo/app/trackerdetection/TdsClientTest.kt @@ -49,57 +49,57 @@ class TdsClientTest { private val image = "image" @Test - fun whenUrlHasSameDomainAsTrackerEntryAndDefaultActionBlockThenMatchesIsTrue() { + fun `matches - url has same domain as tracker entry and default action block - is true`() { test(url = "http://tracker.com/script.js", trackerDomain = trackerDomain, action = BLOCK, expected = true) } @Test - fun whenUrlHasSameDomainAsTrackerEntryAndDefaultActionIgnoreThenMatchesIsFalse() { + fun `matches - url has same domain as tracker entry and default action ignore - is false`() { test(url = "http://tracker.com/script.js", trackerDomain = trackerDomain, action = IGNORE, expected = false) } @Test - fun whenUrlIsSubdomainOfTrackerEntryAndDefaultActionBlockThenMatchesIsTrue() { + fun `matches - url is subdomain of tracker entry and default action block - true`() { test(url = "http://subdomian.tracker.com/script.js", trackerDomain = trackerDomain, action = BLOCK, expected = true) } @Test - fun whenUrlIsNotDomainOrSubDomainOfTrackerEntryThenMatchesIsFalse() { + fun `test - url not domain or subdomain of tracker entry - matches is false`() { test(url = "http://nontracker.com/script.js", trackerDomain = trackerDomain, action = BLOCK, expected = false) } @Test - fun whenUrlIsAParentDomainOfATrackerEntryThenMatchesIsFalse() { + fun `matches - url is a parent domain of a tracker entry - matches is false`() { test(url = "http://tracker.com/script.js", trackerDomain = Domain("subdomain.tracker.com"), action = BLOCK, expected = false) } @Test - fun whenUrlContainsButIsNotSubdomainOfATrackerEntryThenMatchesIsFalse() { + fun `matches - url contains but is not subdomain of a tracker entry - matches is false`() { test(url = "http://notsubdomainoftracker.com", trackerDomain = trackerDomain, action = BLOCK, expected = false) } @Test - fun whenUrlMatchesRuleWithNoExceptionsAndRuleActionBlockThenMatchesIsTrue() { + fun `whenUrlMatchesRule - no exceptions and block action - matches is true`() { test(rule = ruleBlockNullExceptions, url = url, trackerDomain = trackerDomain, action = BLOCK, expected = true) } @Test - fun whenUrlMatchesRuleWithNoExceptionsAndRuleActionIgnoreThenMatchesIsFalse() { + fun `test - url matches rule with no exceptions and rule action ignore - matches is false`() { test(rule = ruleIgnoreNullExceptions, url = url, trackerDomain = trackerDomain, action = BLOCK, expected = false) } @Test - fun whenUrlMatchesDomainWithDefaultBlockAndRuleWithNoExceptionsAndNoActionThenMatchesIsTrue() { + fun `test - url matches domain with default block and rule with no exceptions and no action - matches is true`() { test(rule = ruleNullExceptions, url = url, trackerDomain = trackerDomain, action = BLOCK, expected = true) } @Test - fun whenUrlMatchesDomainWithDefaultIgnoreAndRuleWithNoExceptionsAndNoActionThenMatchesIsTrue() { + fun `matches - domain matches with default ignore and no exceptions - is true`() { test(rule = ruleNullExceptions, url = url, trackerDomain = trackerDomain, action = IGNORE, expected = true) } @Test - fun whenUrlMatchesRuleWithExceptionsAndExceptionDomainMatchesDocumentThenMatchesIsFalseIrrespectiveOfAction() { + fun `testUrlMatchesRuleWithExceptionsAndExceptionDomainMatchesDocument - matches is false - irrespective of action`() { val exampleException = RuleExceptions(listOf("example.com"), null) val ruleBlock = Rule(ruleString, BLOCK, exampleException, null, null) @@ -115,7 +115,7 @@ class TdsClientTest { } @Test - fun whenUrlMatchesRuleWithExceptionsAndExceptionDomainDoesNotMatchDocumentThenMatchesBehaviorIsStandard() { + fun `testUrlMatchesRuleWithExceptionsAndExceptionDomainDoesNotMatchDocument - matches behavior is standard`() { val nonMatchingExceptions = RuleExceptions(listOf("nonmatching.com"), null) val ruleBlock = Rule(ruleString, BLOCK, nonMatchingExceptions, null, null) @@ -131,7 +131,7 @@ class TdsClientTest { } @Test - fun whenUrlMatchesRuleWithExceptionsWithNoDomainsAndTypeMatchesExceptionThenMatchesIsFalseIrrespectiveOfAction() { + fun `testMatchesIsFalseIrrespectiveOfAction - matches is false`() { val exceptions = RuleExceptions(null, listOf("something")) val ruleBlock = Rule("api\\.tracker\\.com\\/auth", BLOCK, exceptions, null, null) @@ -149,7 +149,7 @@ class TdsClientTest { } @Test - fun whenUrlMatchesRuleWithSurrogateThenMatchesIsTrueIrrespectiveOfActionExceptIgnore() { + fun `testUrlMatchesRuleWithSurrogate - matches is true - except ignore`() { val exceptions = RuleExceptions(null, null) val ruleBlock = Rule("api\\.tracker\\.com\\/auth", BLOCK, exceptions, "testId", null) @@ -165,7 +165,7 @@ class TdsClientTest { } @Test - fun whenUrlMatchesRuleWithTypeExceptionAndDomainsIsNullThenMatchesIsFalse() { + fun `mapRule - domains is null - matches is false`() { test( mapResult = image, rule = Rule(ruleString, BLOCK, RuleExceptions(null, listOf(image)), null, null), @@ -177,7 +177,7 @@ class TdsClientTest { } @Test - fun whenUrlMatchesRuleWithTypeExceptionAndDomainsIsEmptyThenMatchesIsFalse() { + fun `matches - url matches rule with type exception and domains empty - is false`() { test( mapResult = image, rule = Rule(ruleString, BLOCK, RuleExceptions(emptyList(), listOf(image)), null, null), @@ -189,7 +189,7 @@ class TdsClientTest { } @Test - fun whenUrlMatchesRuleWithDomainExceptionAndTypesIsNullThenMatchesIsFalse() { + fun `mapRule - domain exception and types is null - matches is false`() { test( mapResult = image, rule = Rule(ruleString, BLOCK, RuleExceptions(listOf("example.com"), null), null, null), @@ -201,7 +201,7 @@ class TdsClientTest { } @Test - fun whenUrlMatchesRuleWithDomainExceptionAndTypesIsEmptyThenMatchesIsFalse() { + fun `mapResult - url matches rule with domain exception and types is empty - matches is false`() { test( mapResult = image, rule = Rule( @@ -219,7 +219,7 @@ class TdsClientTest { } @Test - fun whenUrlMatchesRuleWithDomainAndTypeExceptionThenMatchesIsFalse() { + fun `matches - url matches rule with domain and type exception - is false`() { test( mapResult = image, rule = Rule(ruleString, BLOCK, RuleExceptions(listOf("example.com"), listOf(image)), null, null), @@ -231,7 +231,7 @@ class TdsClientTest { } @Test - fun whenUrlMatchesRuleWithDomainExceptionButNotTypeThenMatchesIsTrue() { + fun `mapRule - domain exception but not type - matches is true`() { test( mapResult = image, rule = Rule(ruleString, BLOCK, RuleExceptions(listOf("example.com"), listOf("script")), null, null), @@ -243,7 +243,7 @@ class TdsClientTest { } @Test - fun whenUrlMatchesRuleWithTypeExceptionButNotDomainThenMatchesIsTrue() { + fun `mapRule - type exception but not domain - matches is true`() { test( mapResult = image, rule = Rule(ruleString, BLOCK, RuleExceptions(listOf("foo.com"), listOf(image)), null, null), @@ -255,7 +255,7 @@ class TdsClientTest { } @Test - fun whenUrlMatchesRuleForBlockedTrackerWithMatchingExceptionAndOptionTypeAndEmptyOptionDomainThenMatchesFalse() { + fun `mapResult - rule matches blocked tracker with matching exception and option type and empty option domain - matches false`() { // If option domain is empty and type is matching, should block would be false since exception is matching. test( mapResult = image, @@ -274,7 +274,7 @@ class TdsClientTest { } @Test - fun whenUrlMatchesRuleForBlockedTrackerWithMatchingExceptionAndOptionDomainAndEmptyOptionTypeThenMatchesFalse() { + fun `mapResult - rule matches blocked tracker with matching exception and option domain and empty option type - matches false`() { // If option type is empty and domain is matching, should block would be false since exception is matching. test( mapResult = image, @@ -293,7 +293,7 @@ class TdsClientTest { } @Test - fun whenUrlMatchesRuleForBlockedTrackerWithMatchingExceptionAndOptionDomainButNotOptionTypeThenMatchesTrue() { + fun `mapResult - rule matches blocked tracker with matching exception and option domain but not option type - matches true`() { // If option type is not null and not matching, should block would be true since we will use the tracker's default action. test( mapResult = image, @@ -312,7 +312,7 @@ class TdsClientTest { } @Test - fun whenUrlMatchesRuleForBlockedTrackerWithMatchingExceptionButNotOptionDomainAndOptionTypeThenMatchesTrue() { + fun `matches - rule for blocked tracker with matching exception but not option domain and option type - matches true`() { // If option domain is not null and not matching, should block would be true since we will use the tracker's default action. test( mapResult = image, @@ -331,7 +331,7 @@ class TdsClientTest { } @Test - fun whenHasOptionsButDoesntMatchDomainNorTypeThenMatchesTrue() { + fun `whenHasOptionsButDoesntMatchDomainNorTypeThenMatchesTrue - matches true`() { // If option type and domain are both not null and not matching, should block would be true since we will use the tracker's default action. test( mapResult = image, @@ -376,7 +376,7 @@ class TdsClientTest { } @Test - fun whenUrlMatchesRuleWithSurrogateThenSurrogateScriptIdReturned() { + fun `matches - url matches rule with surrogate - returns script id`() { val rule = Rule("api\\.tracker\\.com\\/auth", BLOCK, null, "script.js", null) val testee = TdsClient(TDS, listOf(TdsTracker(Domain("tracker.com"), BLOCK, OWNER, CATEGORY, listOf(rule))), mockUrlToTypeMapper, false) diff --git a/app/src/test/java/com/duckduckgo/app/trackerdetection/TrackerDataLoaderTest.kt b/app/src/test/java/com/duckduckgo/app/trackerdetection/TrackerDataLoaderTest.kt index 1e7e53f4d6c5..4b26c1141d41 100644 --- a/app/src/test/java/com/duckduckgo/app/trackerdetection/TrackerDataLoaderTest.kt +++ b/app/src/test/java/com/duckduckgo/app/trackerdetection/TrackerDataLoaderTest.kt @@ -90,7 +90,7 @@ class TrackerDataLoaderTest { } @Test - fun whenPersistTdsThenPersistEntities() { + fun `persistTds - when persisting tds then persist entities - persisted`() { val tdsJson = TdsJson() tdsJson.cnames = mapOf(Pair("host.com", "uncloaked-host.com")) diff --git a/app/src/test/java/com/duckduckgo/app/trackerdetection/TrackerDetectorClientTypeTest.kt b/app/src/test/java/com/duckduckgo/app/trackerdetection/TrackerDetectorClientTypeTest.kt index 049a5bfa09f1..b8651c2fcae7 100644 --- a/app/src/test/java/com/duckduckgo/app/trackerdetection/TrackerDetectorClientTypeTest.kt +++ b/app/src/test/java/com/duckduckgo/app/trackerdetection/TrackerDetectorClientTypeTest.kt @@ -68,7 +68,7 @@ class TrackerDetectorClientTypeTest { } @Test - fun whenUrlMatchesOnlyInBlockingClientThenEvaluateReturnsTrackingEvent() { + fun `evaluate - url matches only in blocking client - returns tracking event`() { val url = Url.BLOCKED val expected = TrackingEvent( documentUrl = documentUrl, @@ -83,7 +83,7 @@ class TrackerDetectorClientTypeTest { } @Test - fun whenUrlDoesNotMatchInAnyClientsThenEvaluateReturnsAllowedDomain() { + fun `evaluate - url does not match in any clients - allowed domain`() { val url = Url.UNLISTED val expected = TrackingEvent( documentUrl = documentUrl, diff --git a/app/src/test/java/com/duckduckgo/app/trackerdetection/TrackerDetectorTest.kt b/app/src/test/java/com/duckduckgo/app/trackerdetection/TrackerDetectorTest.kt index 3bdfc83d8bdc..c02c69e5506e 100644 --- a/app/src/test/java/com/duckduckgo/app/trackerdetection/TrackerDetectorTest.kt +++ b/app/src/test/java/com/duckduckgo/app/trackerdetection/TrackerDetectorTest.kt @@ -60,25 +60,25 @@ class TrackerDetectorTest { ) @Test - fun whenThereAreNoClientsThenClientCountIsZero() { + fun `trackerDetector - client count is zero`() { assertEquals(0, trackerDetector.clientCount) } @Test - fun whenClientAddedThenClientCountIsOne() { + fun `addClient - client count is one`() { trackerDetector.addClient(alwaysMatchingClient(CLIENT_A)) assertEquals(1, trackerDetector.clientCount) } @Test - fun whenTwoClientsWithDifferentNamesAddedThenCountIsTwo() { + fun `addClients - client count is two`() { trackerDetector.addClient(alwaysMatchingClient(CLIENT_A)) trackerDetector.addClient(alwaysMatchingClient(CLIENT_B)) assertEquals(2, trackerDetector.clientCount) } @Test - fun whenTwoClientsWithSameNameAddedThenClientIsReplacedAndCountIsStillOne() { + fun `addClient - client replaced and count still one - not changed`() { trackerDetector.addClient(alwaysMatchingClient(CLIENT_A)) assertEquals(1, trackerDetector.clientCount) assertNotNull( @@ -101,7 +101,7 @@ class TrackerDetectorTest { } @Test - fun whenTwoClientsWithSameNameAddedThenClientIsReplacedAndCountIsStillOne2() { + fun `addClient - client replaced and count still one - still one`() { trackerDetector.addClient(alwaysMatchingClient(CLIENT_A)) assertEquals(1, trackerDetector.clientCount) assertNotNull( @@ -124,7 +124,7 @@ class TrackerDetectorTest { } @Test - fun whenThereAreNoClientsAndIsThirdPartyThenEvaluateReturnsNonTrackingEvent() { + fun `evaluate - no clients and third party - non tracking event`() { trackerDetector.addClient(nonMatchingClientNoTracker(CLIENT_A)) val expected = TrackingEvent( documentUrl = "http://example.com/index.com", @@ -145,7 +145,7 @@ class TrackerDetectorTest { } @Test - fun whenThereAreNoClientsAndIsThirdPartyThenEvaluateReturnsNonTrackingEvent2() { + fun `evaluate - no clients and third party - non tracking event 2`() { trackerDetector.addClient(nonMatchingClientNoTracker(CLIENT_A)) val expected = TrackingEvent( documentUrl = "http://example.com/index.com", @@ -166,7 +166,7 @@ class TrackerDetectorTest { } @Test - fun whenThereAreNoClientsAndIsThirdPartyFromSameEntityThenEvaluateReturnsSameEntityNonTrackingEvent() { + fun `evaluate - no clients and third party from same entity - same entity non tracking event`() { val entity = TdsEntity("example", "example", 0.0) whenever(mockEntityLookup.entityForUrl(anyString())).thenReturn(entity) whenever(mockEntityLookup.entityForUrl(any())).thenReturn(entity) @@ -190,7 +190,7 @@ class TrackerDetectorTest { } @Test - fun whenThereAreNoClientsAndIsThirdPartyFromSameEntityThenEvaluateReturnsSameEntityNonTrackingEvent2() { + fun `evaluate - no clients and third party from same entity - same entity non tracking event 2`() { val entity = TdsEntity("example", "example", 0.0) whenever(mockEntityLookup.entityForUrl(anyString())).thenReturn(entity) whenever(mockEntityLookup.entityForUrl(any())).thenReturn(entity) @@ -214,7 +214,7 @@ class TrackerDetectorTest { } @Test - fun whenThereAreClientsAndIsThirdPartyButIgnoredThenEvaluateReturnsNonTrackingEvent() { + fun `evaluate - clients and third party ignored - non tracking event`() { val entity = TdsEntity("example", "example", 0.0) whenever(mockEntityLookup.entityForUrl(anyString())).thenReturn(entity) whenever(mockEntityLookup.entityForUrl(any())).thenReturn(entity) @@ -238,7 +238,7 @@ class TrackerDetectorTest { } @Test - fun whenThereAreClientsAndIsThirdPartyButIgnoredThenEvaluateReturnsNonTrackingEvent2() { + fun `evaluate - clients and third party ignored - non tracking event 2`() { val entity = TdsEntity("example", "example", 0.0) whenever(mockEntityLookup.entityForUrl(anyString())).thenReturn(entity) whenever(mockEntityLookup.entityForUrl(any())).thenReturn(entity) @@ -262,7 +262,7 @@ class TrackerDetectorTest { } @Test - fun whenSiteIsNotUserAllowListedAndAllClientsMatchThenEvaluateReturnsBlockedTrackingEvent() { + fun `evaluate - site not user allow listed and all clients match - blocked tracking event`() { whenever(mockUserAllowListDao.contains("example.com")).thenReturn(false) trackerDetector.addClient(alwaysMatchingClient(CLIENT_A)) trackerDetector.addClient(alwaysMatchingClient(CLIENT_B)) @@ -284,7 +284,7 @@ class TrackerDetectorTest { } @Test - fun whenSiteIsNotUserAllowListedAndAllClientsMatchThenEvaluateReturnsBlockedTrackingEvent2() { + fun `evaluate - site not user allow listed and all clients match - blocked tracking event 2`() { whenever(mockUserAllowListDao.contains("example.com")).thenReturn(false) trackerDetector.addClient(alwaysMatchingClient(CLIENT_A)) trackerDetector.addClient(alwaysMatchingClient(CLIENT_B)) @@ -306,7 +306,7 @@ class TrackerDetectorTest { } @Test - fun whenSiteIsUserAllowListedAndAllClientsMatchThenEvaluateReturnsUnblockedTrackingEvent() { + fun `evaluate - site is user allow listed and all clients match - unblocked tracking event`() { whenever(mockUserAllowListDao.contains("example.com")).thenReturn(true) trackerDetector.addClient(alwaysMatchingClient(CLIENT_A)) trackerDetector.addClient(alwaysMatchingClient(CLIENT_B)) @@ -328,7 +328,7 @@ class TrackerDetectorTest { } @Test - fun whenSiteIsUserAllowListedAndAllClientsMatchThenEvaluateReturnsUnblockedTrackingEvent2() { + fun `evaluate - site is user allow listed and all clients match - unblocked tracking event 2`() { whenever(mockUserAllowListDao.contains("example.com")).thenReturn(true) trackerDetector.addClient(alwaysMatchingClient(CLIENT_A)) trackerDetector.addClient(alwaysMatchingClient(CLIENT_B)) @@ -350,7 +350,7 @@ class TrackerDetectorTest { } @Test - fun whenSiteIsNotUserAllowListedAndSomeClientsMatchThenEvaluateReturnsBlockedTrackingEvent() { + fun `evaluate - site not user allow listed and some clients match - blocked tracking event`() { whenever(mockUserAllowListDao.contains("example.com")).thenReturn(false) trackerDetector.addClient(alwaysMatchingClient(CLIENT_B)) val expected = TrackingEvent( @@ -371,7 +371,7 @@ class TrackerDetectorTest { } @Test - fun whenSiteIsNotUserAllowListedAndSomeClientsMatchThenEvaluateReturnsBlockedTrackingEvent2() { + fun `evaluate - site not user allow listed and some clients match - blocked tracking event 2`() { whenever(mockUserAllowListDao.contains("example.com")).thenReturn(false) trackerDetector.addClient(alwaysMatchingClient(CLIENT_B)) val expected = TrackingEvent( @@ -392,7 +392,7 @@ class TrackerDetectorTest { } @Test - fun whenSiteIsUserAllowListedAndSomeClientsMatchThenEvaluateReturnsUnblockedTrackingEvent() { + fun `evaluate - site is user allow listed and some clients match - unblocked tracking event`() { whenever(mockUserAllowListDao.contains("example.com")).thenReturn(true) trackerDetector.addClient(alwaysMatchingClient(CLIENT_B)) val expected = TrackingEvent( @@ -413,7 +413,7 @@ class TrackerDetectorTest { } @Test - fun whenSiteIsUserAllowListedAndSomeClientsMatchThenEvaluateReturnsUnblockedTrackingEvent2() { + fun `evaluate - site is user allow listed and some clients match - unblocked tracking event 2`() { whenever(mockUserAllowListDao.contains("example.com")).thenReturn(true) trackerDetector.addClient(alwaysMatchingClient(CLIENT_B)) val expected = TrackingEvent( @@ -434,7 +434,7 @@ class TrackerDetectorTest { } @Test - fun whenSiteIsInContentBlockingExceptionsListAndSomeClientsMatchThenEvaluateReturnsUnblockedTrackingEvent() { + fun `evaluate - site in content blocking exceptions list and some clients match - unblocked tracking event`() { whenever(mockContentBlocking.isAnException(anyString())).thenReturn(true) trackerDetector.addClient(alwaysMatchingClient(CLIENT_A)) val expected = TrackingEvent( @@ -455,7 +455,7 @@ class TrackerDetectorTest { } @Test - fun whenSiteIsInContentBlockingExceptionsListAndSomeClientsMatchThenEvaluateReturnsUnblockedTrackingEvent2() { + fun `evaluate - site in content blocking exceptions list and some clients match - unblocked tracking event 2`() { whenever(mockContentBlocking.isAnException(anyString())).thenReturn(true) trackerDetector.addClient(alwaysMatchingClient(CLIENT_A)) val expected = TrackingEvent( @@ -476,7 +476,7 @@ class TrackerDetectorTest { } @Test - fun whenSiteIsNotUserAllowListedAndSomeClientsMatchWithSurrogateThenEvaluateReturnsBlockedTrackingEventWithSurrogate() { + fun `evaluate - site not user allow listed and some clients match with surrogate - blocked tracking event with surrogate`() { whenever(mockUserAllowListDao.contains("example.com")).thenReturn(false) trackerDetector.addClient(alwaysMatchingClientWithSurrogate(CLIENT_A)) val expected = TrackingEvent( @@ -518,7 +518,7 @@ class TrackerDetectorTest { } @Test - fun whenRequestIsInAllowlistAndSomeClientsMatchThenEvaluateReturnsUnblockedTrackingEvent() { + fun `evaluate - in allowlist and some clients match - unblocked tracking event`() { whenever(mockTrackerAllowlist.isAnException(anyString(), anyString())).thenReturn(true) trackerDetector.addClient(alwaysMatchingClient(CLIENT_A)) val expected = TrackingEvent( @@ -539,7 +539,7 @@ class TrackerDetectorTest { } @Test - fun whenRequestIsInAllowlistAndSomeClientsMatchThenEvaluateReturnsUnblockedTrackingEvent2() { + fun `evaluate - in allowlist and some clients match - unblocked tracking event 2`() { whenever(mockTrackerAllowlist.isAnException(anyString(), anyString())).thenReturn(true) trackerDetector.addClient(alwaysMatchingClient(CLIENT_A)) val expected = TrackingEvent( @@ -560,7 +560,7 @@ class TrackerDetectorTest { } @Test - fun whenRequestIsInAdClickAllowListAndSomeClientsMatchThenEvaluateReturnsUnblockedTrackingEvent() { + fun `evaluate - ad click allow list and some clients match - unblocked tracking event`() { whenever(mockAdClickManager.isExemption(anyString(), anyString())).thenReturn(true) trackerDetector.addClient(alwaysMatchingClient(CLIENT_A)) val expected = TrackingEvent( @@ -581,7 +581,7 @@ class TrackerDetectorTest { } @Test - fun whenRequestIsInAdClickAllowListAndSomeClientsMatchThenEvaluateReturnsUnblockedTrackingEvent2() { + fun `evaluate - ad click allow list and some clients match - unblocked tracking event 2`() { whenever(mockAdClickManager.isExemption(anyString(), anyString())).thenReturn(true) trackerDetector.addClient(alwaysMatchingClient(CLIENT_A)) val expected = TrackingEvent( @@ -602,13 +602,13 @@ class TrackerDetectorTest { } @Test - fun whenUrlHasSameDomainAsDocumentThenEvaluateReturnsNull() { + fun `evaluate - url has same domain as document - returns null`() { trackerDetector.addClient(alwaysMatchingClient(CLIENT_A)) assertNull(trackerDetector.evaluate("http://example.com/update.js", "http://example.com/index.com".toUri(), requestHeaders = mapOf())) } @Test - fun whenUrlHasSameDomainAsDocumentThenEvaluateReturnsNull2() { + fun `evaluate - same domain - returns null`() { trackerDetector.addClient(alwaysMatchingClient(CLIENT_A)) assertNull( trackerDetector.evaluate( @@ -620,7 +620,7 @@ class TrackerDetectorTest { } @Test - fun whenUrlIsSubdomainOfDocumentThenEvaluateReturnsNull() { + fun `evaluate - url is subdomain of document - returns null`() { trackerDetector.addClient(alwaysMatchingClient(CLIENT_A)) assertNull( trackerDetector.evaluate( @@ -644,7 +644,7 @@ class TrackerDetectorTest { } @Test - fun whenUrlIsParentOfDocumentThenEvaluateReturnsNull() { + fun `evaluate - url is parent of document - returns null`() { trackerDetector.addClient(alwaysMatchingClient(CLIENT_A)) assertNull( trackerDetector.evaluate( diff --git a/app/src/test/java/com/duckduckgo/app/trackerdetection/api/TdsDomainEntityJsonTest.kt b/app/src/test/java/com/duckduckgo/app/trackerdetection/api/TdsDomainEntityJsonTest.kt index ca48f3490515..86b652959af0 100644 --- a/app/src/test/java/com/duckduckgo/app/trackerdetection/api/TdsDomainEntityJsonTest.kt +++ b/app/src/test/java/com/duckduckgo/app/trackerdetection/api/TdsDomainEntityJsonTest.kt @@ -31,14 +31,14 @@ class TdsDomainEntityJsonTest { private val jsonAdapter: JsonAdapter = moshi.adapter(TdsJson::class.java) @Test - fun whenFormatIsValidThenDomainEntitiesAreCreated() { + fun `formatIsValid - domain entities created`() { val json = loadText(javaClass.classLoader!!, "json/tds_domain_entities.json") val domains = jsonAdapter.fromJson(json)!!.jsonToDomainEntities() assertEquals(3, domains.count()) } @Test - fun whenFormatIsValidThenDomainEntitiesAreConvertedCorrectly() { + fun `formatIsValid - domain entities converted correctly`() { val json = loadText(javaClass.classLoader!!, "json/tds_domain_entities.json") val domains = jsonAdapter.fromJson(json)!!.jsonToDomainEntities() val domain = domains.first() @@ -46,7 +46,7 @@ class TdsDomainEntityJsonTest { } @Test - fun whenValueIsNullThenDomainEntitiesNotCreated() { + fun `fromJson - value is null - domain entities not created`() { val json = loadText(javaClass.classLoader!!, "json/tds_domain_entities_null_value.json") val domains = jsonAdapter.fromJson(json)!!.jsonToDomainEntities() assertEquals(2, domains.count()) diff --git a/app/src/test/java/com/duckduckgo/app/trackerdetection/api/TdsEntityJsonTest.kt b/app/src/test/java/com/duckduckgo/app/trackerdetection/api/TdsEntityJsonTest.kt index bc0c814c1dd3..f6b47c61fbb4 100644 --- a/app/src/test/java/com/duckduckgo/app/trackerdetection/api/TdsEntityJsonTest.kt +++ b/app/src/test/java/com/duckduckgo/app/trackerdetection/api/TdsEntityJsonTest.kt @@ -30,14 +30,14 @@ class TdsEntityJsonTest { private val jsonAdapter: JsonAdapter = moshi.adapter(TdsJson::class.java) @Test - fun whenFormatIsValidThenEntitiesAreCreated() { + fun `formatIsValid - entities created`() { val json = loadText(javaClass.classLoader!!, "json/tds_entities.json") val entities = jsonAdapter.fromJson(json)!!.jsonToEntities() assertEquals(4, entities.count()) } @Test - fun whenFormatIsValidThenBasicElementsAreConvertedCorrectly() { + fun `formatIsValid - basic elements converted correctly`() { val json = loadText(javaClass.classLoader!!, "json/tds_entities.json") val entities = jsonAdapter.fromJson(json)!!.jsonToEntities() val entity = entities.first() @@ -45,7 +45,7 @@ class TdsEntityJsonTest { } @Test - fun whenEntityIsMissingPrevalenceThenPrevalenceIsSetToZero() { + fun `loadJson - entity is missing prevalence - prevalence set to zero`() { val json = loadText(javaClass.classLoader!!, "json/tds_entities.json") val entities = jsonAdapter.fromJson(json)!!.jsonToEntities() val entity = entities[1] @@ -53,7 +53,7 @@ class TdsEntityJsonTest { } @Test - fun whenEntityIsMissingDisplayNameThenDisplayNameIsSameAsName() { + fun `loadJson - entity is missing display name - same as name`() { val json = loadText(javaClass.classLoader!!, "json/tds_entities.json") val entities = jsonAdapter.fromJson(json)!!.jsonToEntities() val entity = entities[2] @@ -61,7 +61,7 @@ class TdsEntityJsonTest { } @Test - fun whenEntityHasBlankDisplayNameThenDisplayNameIsSameAsName() { + fun `loadTdsEntity - has blank display name - same as name`() { val json = loadText(javaClass.classLoader!!, "json/tds_entities.json") val entities = jsonAdapter.fromJson(json)!!.jsonToEntities() val entity = entities.last() diff --git a/app/src/test/java/com/duckduckgo/app/trackerdetection/api/TdsTrackerJsonTest.kt b/app/src/test/java/com/duckduckgo/app/trackerdetection/api/TdsTrackerJsonTest.kt index 2490aef2d846..c10797c2e495 100644 --- a/app/src/test/java/com/duckduckgo/app/trackerdetection/api/TdsTrackerJsonTest.kt +++ b/app/src/test/java/com/duckduckgo/app/trackerdetection/api/TdsTrackerJsonTest.kt @@ -34,14 +34,14 @@ class TdsTrackerJsonTest { private val jsonAdapter: JsonAdapter = moshi.adapter(TdsJson::class.java) @Test - fun whenFormatIsValidThenTrackersAreCreated() { + fun `formatIsValid - track creation`() { val json = loadText(javaClass.classLoader!!, "json/tds_trackers.json") val trackers = jsonAdapter.fromJson(json)!!.jsonToTrackers() assertEquals(3, trackers.count()) } @Test - fun whenFormatIsValidThenBasicElementsAreConvertedCorrectly() { + fun `formatIsValid - basic elements converted correctly`() { val json = loadText(javaClass.classLoader!!, "json/tds_trackers.json") val trackers = jsonAdapter.fromJson(json)!!.jsonToTrackers() val tracker = trackers["1dmp.io"] @@ -49,7 +49,7 @@ class TdsTrackerJsonTest { } @Test - fun whenTrackerHasInvalidDefaultActionThenTrackerConvertedCorrectly() { + fun `whenTrackerHasInvalidDefaultAction - tracker converted correctly`() { val json = loadText(javaClass.classLoader!!, "json/tds_trackers_action_invalid.json") val jsonTrackers = jsonAdapter.fromJson(json)!! val trackers = jsonTrackers.jsonToTrackers() @@ -58,7 +58,7 @@ class TdsTrackerJsonTest { } @Test - fun whenTrackerIsMissingDefaultActionThenTrackerNotCreated() { + fun `whenTrackerIsMissingDefaultActionThenTrackerNotCreated - tracker not created`() { val json = loadText(javaClass.classLoader!!, "json/tds_trackers_action_missing.json") val trackers = jsonAdapter.fromJson(json)!!.jsonToTrackers() assertEquals(2, trackers.count()) diff --git a/app/src/test/java/com/duckduckgo/app/trackerdetection/api/TrackerDataDownloaderKtTest.kt b/app/src/test/java/com/duckduckgo/app/trackerdetection/api/TrackerDataDownloaderKtTest.kt index a70a913954f2..fe33f33b19fe 100644 --- a/app/src/test/java/com/duckduckgo/app/trackerdetection/api/TrackerDataDownloaderKtTest.kt +++ b/app/src/test/java/com/duckduckgo/app/trackerdetection/api/TrackerDataDownloaderKtTest.kt @@ -24,19 +24,19 @@ import org.junit.Test class TrackerDataDownloaderKtTest { @Test - fun whenExtractETagAndContainsPrefixAndQuotesThenReturnETag() { + fun `extractETag - contains prefix and quotes - returns ETag`() { val headers = Headers.headersOf("eTag", "W/\"123456789\"") assertEquals(ETAG, headers.extractETag()) } @Test - fun whenExtractETagAndContainsQuotesThenReturnETag() { + fun `extractETag - contains quotes - returns eTag`() { val headers = Headers.headersOf("eTag", "\"123456789\"") assertEquals(ETAG, headers.extractETag()) } @Test - fun whenExtractETagAndDoesNotContainsQuotesAndPrefixThenReturnETag() { + fun `extractETag - does not contain quotes and prefix - returns ETag`() { val headers = Headers.headersOf("eTag", "123456789") assertEquals(ETAG, headers.extractETag()) } diff --git a/app/src/test/java/com/duckduckgo/app/webtrackingprotection/WebTrackingProtectionViewModelTest.kt b/app/src/test/java/com/duckduckgo/app/webtrackingprotection/WebTrackingProtectionViewModelTest.kt index c153fb160c71..d4b98f04dc12 100644 --- a/app/src/test/java/com/duckduckgo/app/webtrackingprotection/WebTrackingProtectionViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/webtrackingprotection/WebTrackingProtectionViewModelTest.kt @@ -71,7 +71,7 @@ internal class WebTrackingProtectionViewModelTest { } @Test - fun whenInitialisedThenGpgDisabled() = runTest { + fun `initialise - gpg disabled - not enabled`() = runTest { whenever(mockFeatureToggle.isFeatureEnabled(eq(PrivacyFeatureName.GpcFeatureName.value), any())).thenReturn(false) whenever(mockGpc.isEnabled()).thenReturn(true) @@ -83,7 +83,7 @@ internal class WebTrackingProtectionViewModelTest { } @Test - fun whenGpcToggleEnabledAndGpcDisabledThenGpgDisabled() = runTest { + fun `whenGpcToggleEnabledAndGpcDisabledThenGpgDisabled - view state gpg disabled`() = runTest { whenever(mockFeatureToggle.isFeatureEnabled(eq(PrivacyFeatureName.GpcFeatureName.value), any())).thenReturn(true) whenever(mockGpc.isEnabled()).thenReturn(false) @@ -95,7 +95,7 @@ internal class WebTrackingProtectionViewModelTest { } @Test - fun whenGpcToggleEnabledAndGpcEnabledThenGpgEnabled() = runTest { + fun `whenGpcToggleEnabledAndGpcEnabledThenGpgEnabled - view state updated`() = runTest { whenever(mockFeatureToggle.isFeatureEnabled(eq(PrivacyFeatureName.GpcFeatureName.value), any())).thenReturn(true) whenever(mockGpc.isEnabled()).thenReturn(true) @@ -107,7 +107,7 @@ internal class WebTrackingProtectionViewModelTest { } @Test - fun whenOnGlobalPrivacyControlClickedThenCommandIsLaunchGlobalPrivacyControlAndPixelFired() = runTest { + fun `onGlobalPrivacyControlClicked - command is launch global privacy control and pixel fired`() = runTest { testee.commands().test { testee.onGlobalPrivacyControlClicked() @@ -119,7 +119,7 @@ internal class WebTrackingProtectionViewModelTest { } @Test - fun whenOnManageAllowListSelectedThenEmitCommandLaunchAllowListAndSendPixel() = runTest { + fun `onManageAllowListSelected - emit command launch allow list and send pixel`() = runTest { testee.commands().test { testee.onManageAllowListSelected() diff --git a/app/src/test/java/com/duckduckgo/app/widget/AddWidgetCompatLauncherTest.kt b/app/src/test/java/com/duckduckgo/app/widget/AddWidgetCompatLauncherTest.kt index 3c8aa52e7821..6740549ca98e 100644 --- a/app/src/test/java/com/duckduckgo/app/widget/AddWidgetCompatLauncherTest.kt +++ b/app/src/test/java/com/duckduckgo/app/widget/AddWidgetCompatLauncherTest.kt @@ -36,7 +36,7 @@ class AddWidgetCompatLauncherTest { ) @Test - fun whenAutomaticWidgetAddIsNotSupportedThenDelegateToLegacyAddWidgetLauncher() { + fun `launchAddWidget - automatic widget add not supported - delegate to legacy add widget launcher`() { whenever(widgetCapabilities.supportsAutomaticWidgetAdd).thenReturn(false) testee.launchAddWidget(null) @@ -45,7 +45,7 @@ class AddWidgetCompatLauncherTest { } @Test - fun whenAutomaticWidgetAddIsSupportedThenDelegateToAppWidgetManagerAddWidgetLauncher() { + fun `whenAutomaticWidgetAddIsSupportedThenDelegateToAppWidgetManagerAddWidgetLauncher - delegate to add widget launcher`() { whenever(widgetCapabilities.supportsAutomaticWidgetAdd).thenReturn(true) testee.launchAddWidget(null) diff --git a/app/src/test/java/com/duckduckgo/autofill/pixel/AutofillUniquePixelSenderTest.kt b/app/src/test/java/com/duckduckgo/autofill/pixel/AutofillUniquePixelSenderTest.kt index 14e0141e44c5..482f515c13a0 100644 --- a/app/src/test/java/com/duckduckgo/autofill/pixel/AutofillUniquePixelSenderTest.kt +++ b/app/src/test/java/com/duckduckgo/autofill/pixel/AutofillUniquePixelSenderTest.kt @@ -58,37 +58,37 @@ class AutofillUniquePixelSenderTest { } @Test - fun whenSharedPreferencesHasNoValueThenReturnsFalse() = runTest { + fun `hasDeterminedCapabilities - shared preferences has no value - returns false`() = runTest { configureSharePreferencesMissingKey() assertFalse(testee.hasDeterminedCapabilities()) } @Test - fun whenPixelSentThenSharedPreferencesRecordsPixelWasSentBefore() = runTest { + fun `sendCapabilitiesPixel - shared preferences records pixel was sent before`() = runTest { testee.sendCapabilitiesPixel(secureStorageAvailable = true, deviceAuthAvailable = true) assertTrue(testee.hasDeterminedCapabilities()) } @Test - fun whenSecureStorageIsAvailableAndDeviceAuthEnabledThenSendCorrectPixel() { + fun `sendCapabilitiesPixel - secure storage available and device auth enabled - send correct pixel`() { testee.sendCapabilitiesPixel(secureStorageAvailable = true, deviceAuthAvailable = true) verify(mockPixel).fire(AUTOFILL_DEVICE_CAPABILITY_CAPABLE) } @Test - fun whenSecureStorageIsAvailableButDeviceAuthDisabledThenSendCorrectPixel() { + fun `sendCapabilitiesPixel - secure storage available but device auth disabled - send correct pixel`() { testee.sendCapabilitiesPixel(secureStorageAvailable = true, deviceAuthAvailable = false) verify(mockPixel).fire(AUTOFILL_DEVICE_CAPABILITY_DEVICE_AUTH_DISABLED) } @Test - fun whenDeviceAuthEnabledButSecureStorageIsNotAvailableThenSendCorrectPixel() { + fun `sendCapabilitiesPixel - device auth enabled but secure storage is not available - send correct pixel`() { testee.sendCapabilitiesPixel(secureStorageAvailable = false, deviceAuthAvailable = true) verify(mockPixel).fire(AUTOFILL_DEVICE_CAPABILITY_SECURE_STORAGE_UNAVAILABLE) } @Test - fun whenDeviceAuthDisabledAndSecureStorageIsNotAvailableThenSendCorrectPixel() { + fun `sendCapabilitiesPixel - device auth disabled and secure storage not available - send correct pixel`() { testee.sendCapabilitiesPixel(secureStorageAvailable = false, deviceAuthAvailable = false) verify(mockPixel).fire(AUTOFILL_DEVICE_CAPABILITY_SECURE_STORAGE_UNAVAILABLE_AND_DEVICE_AUTH_DISABLED) } diff --git a/app/src/test/java/com/duckduckgo/savedsites/impl/MissingEntitiesRelationReconcilerTest.kt b/app/src/test/java/com/duckduckgo/savedsites/impl/MissingEntitiesRelationReconcilerTest.kt index 9234b8a43888..a7fa4a327b55 100644 --- a/app/src/test/java/com/duckduckgo/savedsites/impl/MissingEntitiesRelationReconcilerTest.kt +++ b/app/src/test/java/com/duckduckgo/savedsites/impl/MissingEntitiesRelationReconcilerTest.kt @@ -43,7 +43,7 @@ class MissingEntitiesRelationReconcilerTest { } @Test - fun whenInvalidEntitiesAreConsecutiveThenResultListKeepsCorrectPositions() = runTest { + fun `reconcileRelations - invalid entities consecutive - result list keeps correct positions`() = runTest { val initialEntities = listOf("A", "Inv1", "Inv2", "B") initialEntities.forEachIndexed { index, entityId -> @@ -58,7 +58,7 @@ class MissingEntitiesRelationReconcilerTest { } @Test - fun whenInvalidEntitiesBetweenValidEntitiesThenResultListKeepsCorrectPositions() = runTest { + fun `reconcileRelations - invalid entities between valid entities - result list keeps correct positions`() = runTest { val initialEntities = listOf("A", "Inv1", "C", "Inv2", "D") initialEntities.forEachIndexed { index, entityId -> @@ -73,7 +73,7 @@ class MissingEntitiesRelationReconcilerTest { } @Test - fun whenInvalidEntitiesBetweenMultipleValidEntitiesThenResultListKeepsCorrectPositions() = runTest { + fun `reconcileRelations - invalid entities between multiple valid entities - result list keeps correct positions`() = runTest { val initialEntities = listOf("A", "B", "Inv1", "C", "D", "Inv2", "E", "F") initialEntities.forEachIndexed { index, entityId -> @@ -88,7 +88,7 @@ class MissingEntitiesRelationReconcilerTest { } @Test - fun whenInvalidEntitiesAndValidItemRemovedThenResultListKeepsCorrectPositions() = runTest { + fun `reconcileRelations - invalid entities and valid item removed - result list keeps correct positions`() = runTest { val initialEntities = listOf("A", "B", "Inv1", "C", "D", "Inv2", "E", "F") initialEntities.forEachIndexed { index, entityId -> @@ -103,7 +103,7 @@ class MissingEntitiesRelationReconcilerTest { } @Test - fun whenInvalidEntitiesAndValidItemAddedAtTheEndOfListThenResultListKeepsCorrectPositions() = runTest { + fun `reconcileRelations - invalid entities and valid item added at the end of list - result list keeps correct positions`() = runTest { val initialEntities = listOf("A", "B", "Inv1", "C", "D", "Inv2", "E", "F") initialEntities.forEachIndexed { index, entityId -> @@ -118,7 +118,7 @@ class MissingEntitiesRelationReconcilerTest { } @Test - fun whenInvalidEntitiesAndValidItemAddedInTheMiddleOfListThenResultListKeepsCorrectPositions() = runTest { + fun `reconcileRelations - invalid entities and valid item added - result list keeps correct positions`() = runTest { val initialEntities = listOf("A", "B", "Inv1", "C", "D", "Inv2", "E", "F") initialEntities.forEachIndexed { index, entityId -> @@ -133,7 +133,7 @@ class MissingEntitiesRelationReconcilerTest { } @Test - fun whenInvalidEntitiesIsFirstItemThenResultListKeepsCorrectPositions() = runTest { + fun `reconcileRelations - invalid entities first item - result list keeps correct positions`() = runTest { val initialEntities = listOf("Inv0", "A", "B", "Inv1", "C", "D", "Inv2", "E", "F") initialEntities.forEachIndexed { index, entityId -> @@ -148,7 +148,7 @@ class MissingEntitiesRelationReconcilerTest { } @Test - fun whenInvalidEntitiesIsFirstItemAndItemsReorderedThenResultListKeepsCorrectPositions() = runTest { + fun `reconcileRelations - invalid entities first item and items reordered - result list keeps correct positions`() = runTest { val initialEntities = listOf("Inv0", "A", "B", "Inv1", "C", "D", "Inv2", "E", "F") initialEntities.forEachIndexed { index, entityId -> @@ -163,7 +163,7 @@ class MissingEntitiesRelationReconcilerTest { } @Test - fun whenInvalidMultipleEntitiesStartListThenResultListKeepsCorrectPositions() = runTest { + fun `reconcileRelations - initial entities valid - result list keeps correct positions`() = runTest { val initialEntities = listOf("Inv0", "Inv1", "Inv2", "A", "B", "C", "D", "E", "F") initialEntities.forEachIndexed { index, entityId -> @@ -178,7 +178,7 @@ class MissingEntitiesRelationReconcilerTest { } @Test - fun whenNoInvalidEntitiesThenReturnSameList() = runTest { + fun `reconcileRelations - no invalid entities - same list`() = runTest { val initialEntities = listOf("A", "B", "C", "D", "E", "F") initialEntities.forEachIndexed { index, entityId -> diff --git a/app/src/test/java/com/duckduckgo/savedsites/impl/RealFavoritesDelegateTest.kt b/app/src/test/java/com/duckduckgo/savedsites/impl/RealFavoritesDelegateTest.kt index e58cef024ece..974369ee6458 100644 --- a/app/src/test/java/com/duckduckgo/savedsites/impl/RealFavoritesDelegateTest.kt +++ b/app/src/test/java/com/duckduckgo/savedsites/impl/RealFavoritesDelegateTest.kt @@ -55,7 +55,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenDefaultThenReturnFavoritesFromRootFolderFlow() = runTest { + fun `getFavorites - default - returns favorites from root folder flow`() = runTest { givenFavoriteDelegate(syncDisabledFavoritesSettings) val favoriteone = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) val favoritetwo = Favorite("favorite2", "Favorite2", "http://favexample.com", "timestamp", 1) @@ -69,7 +69,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenUnifiedModeThenReturnFavoritesFromRootFolderFlow() = runTest { + fun `getFavorites - unified mode - returns favorites from root folder flow`() = runTest { givenFavoriteDelegate(favoritesDisplayModeSettings.apply { favoritesDisplayMode = UNIFIED }) val favoriteone = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) val favoritetwo = Favorite("favorite2", "Favorite2", "http://favexample.com", "timestamp", 1) @@ -83,7 +83,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenNativeModeThenReturnMobileFavoritesFolderFlow() = runTest { + fun `getFavorites - native mode - returns mobile favorites folder flow`() = runTest { givenFavoriteDelegate(favoritesDisplayModeSettings.apply { favoritesDisplayMode = NATIVE }) val favoriteone = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) val favoritetwo = Favorite("favorite2", "Favorite2", "http://favexample.com", "timestamp", 1) @@ -97,7 +97,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenViewModeChangesThenNewFlowEmitted() = runTest { + fun `getFavorites - view mode changes - new flow emitted`() = runTest { givenFavoriteDelegate(favoritesDisplayModeSettings.apply { favoritesDisplayMode = NATIVE }) val favoriteone = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) val favoritetwo = Favorite("favorite2", "Favorite2", "http://favexample.com", "timestamp", 1) @@ -114,7 +114,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenDefaultThenReturnRootFavoritesFolderList() = runTest { + fun `getFavoritesSync - default - returns root favorites folder list`() = runTest { givenFavoriteDelegate(syncDisabledFavoritesSettings) val favoriteone = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) val favoritetwo = Favorite("favorite2", "Favorite2", "http://favexample.com", "timestamp", 1) @@ -126,7 +126,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenUnifiedModeThenReturnRootFavoritesFolderList() = runTest { + fun `getFavoritesSync - unified mode - returns root favorites folder list`() = runTest { givenFavoriteDelegate(favoritesDisplayModeSettings.apply { favoritesDisplayMode = UNIFIED }) val favoriteone = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) val favoritetwo = Favorite("favorite2", "Favorite2", "http://favexample.com", "timestamp", 1) @@ -138,7 +138,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenNativeModeThenReturnMobileFavoritesFolderList() = runTest { + fun `getFavoritesSync - native mode - returns mobile favorites folder list`() = runTest { givenFavoriteDelegate(favoritesDisplayModeSettings.apply { favoritesDisplayMode = NATIVE }) val favoriteone = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) val favoritetwo = Favorite("favorite2", "Favorite2", "http://favexample.com", "timestamp", 1) @@ -150,7 +150,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenGetFavoritesCountByDomainThenOnlyCheckRootFolder() = runTest { + fun `getFavoritesCountByDomain - only check root folder`() = runTest { givenFavoriteDelegate(syncDisabledFavoritesSettings) val favoriteone = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) val favoritetwo = Favorite("favorite2", "Favorite2", "http://favexample.com", "timestamp", 1) @@ -162,7 +162,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenUnifiedModeGetFavoritesCountByDomainThenOnlyCheckRootFolder() = runTest { + fun `getFavoritesCountByDomain - unified mode - only check root folder`() = runTest { givenFavoriteDelegate(favoritesDisplayModeSettings.apply { favoritesDisplayMode = UNIFIED }) val favoriteone = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) val favoritetwo = Favorite("favorite2", "Favorite2", "http://favexample.com", "timestamp", 1) @@ -174,7 +174,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenNativeModeGetFavoritesCountByDomainThenOnlyCheckMobileFolder() = runTest { + fun `getFavoritesCountByDomain - native mode - only check mobile folder`() = runTest { givenFavoriteDelegate(favoritesDisplayModeSettings.apply { favoritesDisplayMode = NATIVE }) val favoriteone = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) val favoritetwo = Favorite("favorite2", "Favorite2", "http://favexample.com", "timestamp", 1) @@ -185,7 +185,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenGetFavoriteByIdThenOnlyCheckRootFolder() = runTest { + fun `getFavoriteById - only check root folder`() = runTest { givenFavoriteDelegate(syncDisabledFavoritesSettings) val favoriteone = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) val favoritetwo = Favorite("favorite2", "Favorite2", "http://favexample.com", "timestamp", 1) @@ -197,7 +197,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenUnifiedModeGetFavoriteByIdThenOnlyCheckRootFolder() = runTest { + fun `getFavoriteById - unified mode - only check root folder`() = runTest { givenFavoriteDelegate(favoritesDisplayModeSettings.apply { favoritesDisplayMode = UNIFIED }) val favoriteone = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) val favoritetwo = Favorite("favorite2", "Favorite2", "http://favexample.com", "timestamp", 1) @@ -209,7 +209,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenNativeModeGetFavoriteByIdThenOnlyCheckMobileFolder() = runTest { + fun `getFavoriteById - native mode - only check mobile folder`() = runTest { givenFavoriteDelegate(favoritesDisplayModeSettings.apply { favoritesDisplayMode = NATIVE }) val favoriteone = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) val favoritetwo = Favorite("favorite2", "Favorite2", "http://favexample.com", "timestamp", 1) @@ -221,7 +221,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenFavoritesCountThenOnlyCheckRootFolder() = runTest { + fun `favoritesCount - only check root folder`() = runTest { givenFavoriteDelegate(syncDisabledFavoritesSettings) val favoriteone = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) val favoritetwo = Favorite("favorite2", "Favorite2", "http://favexample.com", "timestamp", 1) @@ -233,7 +233,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenUnifiedModeFavoritesCountThenOnlyCheckRootFolder() = runTest { + fun `favoritesCount - unified mode favorites count - only check root folder`() = runTest { givenFavoriteDelegate(favoritesDisplayModeSettings.apply { favoritesDisplayMode = UNIFIED }) val favoriteone = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) val favoritetwo = Favorite("favorite2", "Favorite2", "http://favexample.com", "timestamp", 1) @@ -245,7 +245,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenNativeModeFavoritesCountThenOnlyCheckMobileFolder() = runTest { + fun `favoritesCount - native mode favorites count - only check mobile folder`() = runTest { givenFavoriteDelegate(favoritesDisplayModeSettings.apply { favoritesDisplayMode = NATIVE }) val favoriteone = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) val favoritetwo = Favorite("favorite2", "Favorite2", "http://favexample.com", "timestamp", 1) @@ -257,7 +257,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenUpdateWithPositionThenUpdateItemsOnRootFolder() { + fun `updateWithPosition - update items on root folder - entities updated`() { givenFavoriteDelegate(syncDisabledFavoritesSettings) val favoriteone = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) val favoritetwo = Favorite("favorite2", "Favorite2", "http://favexample.com", "timestamp", 1) @@ -278,7 +278,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenUnifiedModeUpdateWithPositionThenUpdateItemsOnRootFolder() = runTest { + fun `updateWithPosition - unified mode update with position - items updated on root folder`() = runTest { givenFavoriteDelegate(favoritesDisplayModeSettings.apply { favoritesDisplayMode = UNIFIED }) val favoriteone = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) val favoritetwo = Favorite("favorite2", "Favorite2", "http://favexample.com", "timestamp", 1) @@ -299,7 +299,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenNativeModeUpdateWithPositionThenUpdateItemsOnRootFolder() = runTest { + fun `updateWithPosition - items on root folder updated`() = runTest { givenFavoriteDelegate(favoritesDisplayModeSettings.apply { favoritesDisplayMode = NATIVE }) val favoriteone = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) val favoritetwo = Favorite("favorite2", "Favorite2", "http://favexample.com", "timestamp", 1) @@ -320,7 +320,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenInsertFavoriteThenUpdateItemsOnRootFolder() { + fun `insertFavorite - update items on root folder - favorites updated`() { givenFavoriteDelegate(syncDisabledFavoritesSettings) testee.insertFavorite("favorite1", "Favorite", "http://favexample.com", "timestamp") @@ -330,7 +330,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenUnifiedModeInsertFavoriteThenUpdateItemsOnRootAndMobileFolder() = runTest { + fun `insertFavorite - unified mode - update items on root and mobile folder`() = runTest { givenFavoriteDelegate(favoritesDisplayModeSettings.apply { favoritesDisplayMode = UNIFIED }) testee.insertFavorite("favorite1", "Favorite", "http://favexample.com", "timestamp") @@ -339,7 +339,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenNativeModeInsertFavoriteThenUpdateItemsOnRootAndMobileFolder() = runTest { + fun `insertFavorite - native mode - update items on root and mobile folder`() = runTest { givenFavoriteDelegate(favoritesDisplayModeSettings.apply { favoritesDisplayMode = NATIVE }) testee.insertFavorite("favorite1", "Favorite", "http://favexample.com", "timestamp") @@ -348,7 +348,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenDeleteFavoriteThenDeleteFromRootFolder() = runTest { + fun `deleteFavorite - state - favorite deleted from root folder`() = runTest { givenFavoriteDelegate(syncDisabledFavoritesSettings) val favoriteone = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) @@ -364,7 +364,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenUnifiedModeDeleteFavoriteThenDeleteFromAllFolders() = runTest { + fun `deleteFavorite - unified mode - delete from all folders`() = runTest { givenFavoriteDelegate(favoritesDisplayModeSettings.apply { favoritesDisplayMode = UNIFIED }) val favoriteone = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) givenFavoriteStored(favoriteone, favoriteFolderId = SavedSitesNames.FAVORITES_ROOT) @@ -379,7 +379,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenNativeModeDeleteNonDesktopFavoriteThenDeleteFromAllFolders() = runTest { + fun `deleteFavorite - native mode delete non desktop favorite - deleted from all folders`() = runTest { givenFavoriteDelegate(favoritesDisplayModeSettings.apply { favoritesDisplayMode = NATIVE }) val favoriteone = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) givenFavoriteStored(favoriteone, favoriteFolderId = SavedSitesNames.FAVORITES_ROOT) @@ -393,7 +393,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenDataSourceChangesThenNewListReceived() { + fun `getFavoritesObservable - data source changes - new list received`() { givenFavoriteDelegate(syncDisabledFavoritesSettings) givenNoFavoritesStored() diff --git a/app/src/test/java/com/duckduckgo/savedsites/impl/RealFavoritesDisplayModeSettingsRepositoryTest.kt b/app/src/test/java/com/duckduckgo/savedsites/impl/RealFavoritesDisplayModeSettingsRepositoryTest.kt index b97a9f5c1549..ec86de5449eb 100644 --- a/app/src/test/java/com/duckduckgo/savedsites/impl/RealFavoritesDisplayModeSettingsRepositoryTest.kt +++ b/app/src/test/java/com/duckduckgo/savedsites/impl/RealFavoritesDisplayModeSettingsRepositoryTest.kt @@ -80,14 +80,14 @@ class RealFavoritesDisplayModeSettingsRepositoryTest { } @Test - fun whenObserverAddedThenCurrentViewStateEmitted() = runTest { + fun `favoritesDisplayModeFlow - current view state emitted`() = runTest { testee.favoritesDisplayModeFlow().test { assertEquals(NATIVE, awaitItem()) } } @Test - fun whenDisplayModeChangedThenViewStateIsUpdated() = runTest { + fun `displayModeChanged - viewState updated`() = runTest { testee.favoritesDisplayModeFlow().test { awaitItem() testee.favoritesDisplayMode = UNIFIED @@ -96,20 +96,20 @@ class RealFavoritesDisplayModeSettingsRepositoryTest { } @Test - fun whenDisplayModeChangedThenNotifySyncableSetting() = runTest { + fun `displayModeChanged - notify syncable setting`() = runTest { testee.favoritesDisplayMode = UNIFIED verify(syncSettingsListener).onSettingChanged(syncableSetting.key) } @Test - fun whenSyncDisabledThenQueryFolderIsFavoritesRoot() = runTest { + fun `getQueryFolder - sync disabled - favorites root`() = runTest { syncStateFlow.value = SyncState.OFF assertEquals(SavedSitesNames.FAVORITES_ROOT, testee.getQueryFolder()) } @Test - fun whenUserEnabledSyncThenEmitNewQueryFolder() = runTest { + fun `getFavoriteFolderFlow - user enabled sync - emit new query folder`() = runTest { syncStateFlow.value = SyncState.OFF testee.getFavoriteFolderFlow().test { assertEquals(SavedSitesNames.FAVORITES_ROOT, awaitItem()) @@ -121,27 +121,27 @@ class RealFavoritesDisplayModeSettingsRepositoryTest { } @Test - fun whenSyncEnabledAndNativeModeThenQueryFolderIsMobileRoot() = runTest { + fun `getQueryFolder - sync enabled and native mode - mobile root`() = runTest { syncStateFlow.value = SyncState.READY savedSitesSettingsStore.favoritesDisplayMode = NATIVE assertEquals(SavedSitesNames.FAVORITES_MOBILE_ROOT, testee.getQueryFolder()) } @Test - fun whenSyncEnabledAndUnifiedModeThenQueryFolderIsMobileRoot() = runTest { + fun `getQueryFolder - sync enabled and unified mode - mobile root`() = runTest { syncStateFlow.value = SyncState.READY savedSitesSettingsStore.favoritesDisplayMode = UNIFIED assertEquals(SavedSitesNames.FAVORITES_ROOT, testee.getQueryFolder()) } @Test - fun whenSyncDisabledThenInsertFolderIsFavoritesRoot() = runTest { + fun `getInsertFolder - sync disabled - favorites root`() = runTest { syncStateFlow.value = SyncState.OFF assertEquals(listOf(SavedSitesNames.FAVORITES_ROOT), testee.getInsertFolder()) } @Test - fun whenSyncEnabledAndNativeModeThenInsertFolderIsMobileAndFavoritesRoot() = runTest { + fun `getInsertFolder - sync enabled and native mode - mobile and favorites root`() = runTest { syncStateFlow.value = SyncState.READY savedSitesSettingsStore.favoritesDisplayMode = NATIVE assertTrue(testee.getInsertFolder().size == 2) @@ -150,7 +150,7 @@ class RealFavoritesDisplayModeSettingsRepositoryTest { } @Test - fun whenSyncEnabledAndUnifiedModeThenInsertFolderIsMobileAndFavoritesRoot() = runTest { + fun `getInsertFolder - sync enabled and unified mode - mobile and favorites root`() = runTest { syncStateFlow.value = SyncState.READY savedSitesSettingsStore.favoritesDisplayMode = UNIFIED assertTrue(testee.getInsertFolder().size == 2) @@ -159,13 +159,13 @@ class RealFavoritesDisplayModeSettingsRepositoryTest { } @Test - fun whenSyncDisabledThenDeleteFolderIsFavoritesRoot() = runTest { + fun `getDeleteFolder - sync disabled - delete folder is favorites root`() = runTest { syncStateFlow.value = SyncState.OFF assertEquals(listOf(SavedSitesNames.FAVORITES_ROOT), testee.getDeleteFolder("entityId")) } @Test - fun whenSyncEnabledAndNativeModeThenDeleteFolderIsMobileAndFavoritesRoot() = runTest { + fun `getDeleteFolder - sync enabled and native mode - mobile and favorites root`() = runTest { syncStateFlow.value = SyncState.READY savedSitesSettingsStore.favoritesDisplayMode = NATIVE assertTrue(testee.getDeleteFolder("entityId").size == 2) @@ -174,7 +174,7 @@ class RealFavoritesDisplayModeSettingsRepositoryTest { } @Test - fun whenSyncEnabledAndNativeModeAndFavoriteIsDesktopThenDeleteFolderIsMobile() = runTest { + fun `getDeleteFolder - sync enabled and native mode and favorite is desktop - delete folder is mobile`() = runTest { savedSitesRelationsDao.insert(Relation(folderId = SavedSitesNames.FAVORITES_DESKTOP_ROOT, entityId = "entityId")) syncStateFlow.value = SyncState.READY savedSitesSettingsStore.favoritesDisplayMode = NATIVE @@ -184,7 +184,7 @@ class RealFavoritesDisplayModeSettingsRepositoryTest { } @Test - fun whenSyncEnabledAndUnifiedModeThenDeleteFolderIsAllFolders() = runTest { + fun `getDeleteFolder - sync enabled and unified mode - all folders`() = runTest { syncStateFlow.value = SyncState.READY savedSitesSettingsStore.favoritesDisplayMode = UNIFIED assertTrue(testee.getDeleteFolder("entityId").size == 3) diff --git a/app/src/test/java/com/duckduckgo/widget/WidgetVoiceSearchStatusListenerTest.kt b/app/src/test/java/com/duckduckgo/widget/WidgetVoiceSearchStatusListenerTest.kt index 4c4753516b26..c5c7bde8204d 100644 --- a/app/src/test/java/com/duckduckgo/widget/WidgetVoiceSearchStatusListenerTest.kt +++ b/app/src/test/java/com/duckduckgo/widget/WidgetVoiceSearchStatusListenerTest.kt @@ -27,7 +27,7 @@ class WidgetVoiceSearchStatusListenerTest { private val testee = WidgetVoiceSearchStatusListener(mock(), widgetUpdater) @Test - fun whenVoiceSearchStatusChangedThenShouldUpdateWidgets() { + fun `voiceSearchStatusChanged - should update widgets`() { testee.voiceSearchStatusChanged() verify(widgetUpdater).updateWidgets(any()) diff --git a/app/src/testInternal/java/com/duckduckgo/app/survey/api/SurveyEndpointInterceptorTest.kt b/app/src/testInternal/java/com/duckduckgo/app/survey/api/SurveyEndpointInterceptorTest.kt index a03ff83f14c8..2e6e68ff29f5 100644 --- a/app/src/testInternal/java/com/duckduckgo/app/survey/api/SurveyEndpointInterceptorTest.kt +++ b/app/src/testInternal/java/com/duckduckgo/app/survey/api/SurveyEndpointInterceptorTest.kt @@ -17,7 +17,7 @@ class SurveyEndpointInterceptorTest { } @Test - fun interceptSurveyUrlWhenEnabled() { + fun `interceptSurveyUrl - enabled - sandbox url`() { surveyEndpointDataStore.useSurveyCustomEnvironmentUrl = true val chain = FakeChain(SURVEY_URL) @@ -27,7 +27,7 @@ class SurveyEndpointInterceptorTest { } @Test - fun doNotInterceptSurveyUrlWhenDisabled() { + fun `intercept - survey url disabled - does not intercept`() { surveyEndpointDataStore.useSurveyCustomEnvironmentUrl = false val chain = FakeChain(SURVEY_URL) @@ -37,7 +37,7 @@ class SurveyEndpointInterceptorTest { } @Test - fun ignoreUnknownUrlWhenEnabled() { + fun `intercept - use custom environment url enabled - unknown url`() { surveyEndpointDataStore.useSurveyCustomEnvironmentUrl = true val chain = FakeChain(UNKNOWN_URL) @@ -47,7 +47,7 @@ class SurveyEndpointInterceptorTest { } @Test - fun ignoreUnknownUrlWhenDisabled() { + fun `intercept - use survey custom environment url disabled - unknown url`() { surveyEndpointDataStore.useSurveyCustomEnvironmentUrl = false val chain = FakeChain(UNKNOWN_URL) diff --git a/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/AutoconsentInterfaceTest.kt b/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/AutoconsentInterfaceTest.kt index e6f72ba39430..406aa1354122 100644 --- a/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/AutoconsentInterfaceTest.kt +++ b/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/AutoconsentInterfaceTest.kt @@ -39,7 +39,7 @@ class AutoconsentInterfaceTest { } @Test - fun whenMessagedParsedIfTypeMatchesThenCallProcess() { + fun `process - message parsed if type matches - call process`() { val message = """{"type":"fake"}""" autoconsentInterface.process(message) @@ -48,7 +48,7 @@ class AutoconsentInterfaceTest { } @Test - fun whenMessagedParsedIfTypeDoesNotMatchThenDoNotCallProcess() { + fun `process - message parsed if type does not match - do not call process`() { val message = """{"type":"noMatchingType"}""" autoconsentInterface.process(message) diff --git a/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/RealAutoconsentTest.kt b/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/RealAutoconsentTest.kt index 07b3cf4f1009..76dd5e5e18bf 100644 --- a/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/RealAutoconsentTest.kt +++ b/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/RealAutoconsentTest.kt @@ -63,7 +63,7 @@ class RealAutoconsentTest { } @Test - fun whenInjectAutoconsentIfNeverHandledThenDoNotCallEvaluate() { + fun `injectAutoconsent - never handled - do not call evaluate`() { settingsRepository.userSetting = false settingsRepository.firstPopupHandled = false @@ -78,7 +78,7 @@ class RealAutoconsentTest { } @Test - fun whenInjectAutoconsentIfPreviouslyHandledAndSettingFalseThenDoNotCallEvaluate() { + fun `injectAutoconsent - previously handled and setting false - do not call evaluate`() { settingsRepository.userSetting = false settingsRepository.firstPopupHandled = true @@ -88,7 +88,7 @@ class RealAutoconsentTest { } @Test - fun whenInjectAutoconsentIfPreviouslyHandledAndSettingTrueThenCallEvaluate() { + fun `injectAutoconsent - previously handled and setting true - call evaluate`() { settingsRepository.userSetting = true settingsRepository.firstPopupHandled = true @@ -98,7 +98,7 @@ class RealAutoconsentTest { } @Test - fun whenChangeSettingChangedThenRepoSetValueChanged() { + fun `changeSetting - repo set value changed`() { autoconsent.changeSetting(false) assertFalse(settingsRepository.userSetting) @@ -107,7 +107,7 @@ class RealAutoconsentTest { } @Test - fun whenSettingEnabledCalledThenReturnValueFromRepo() { + fun `isSettingEnabled - setting enabled called - return value from repo`() { settingsRepository.userSetting = false assertFalse(autoconsent.isSettingEnabled()) @@ -116,7 +116,7 @@ class RealAutoconsentTest { } @Test - fun whenSetAutoconsentOptOutThenEvaluateJavascriptCalled() { + fun `setAutoconsentOptOut - evaluate javascript called`() { val expected = """ javascript:(function() { window.autoconsentMessageCallback({ "type": "optOut" }, window.origin); @@ -128,25 +128,25 @@ class RealAutoconsentTest { } @Test - fun whenSetAutoconsentOptOutThenTrueValueStored() { + fun `setAutoconsentOptOut - settings stored - true value stored`() { autoconsent.setAutoconsentOptOut(webView) assertTrue(settingsRepository.userSetting) } @Test - fun whenSetAutoconsentOptInThenFalseValueStored() { + fun `setAutoconsentOptIn - settings stored - false value stored`() { autoconsent.setAutoconsentOptIn() assertFalse(settingsRepository.userSetting) } @Test - fun whenFirstPopUpHandledThenFalseValueStored() { + fun `firstPopUpHandled - settings stored - false value stored`() { autoconsent.firstPopUpHandled() assertTrue(settingsRepository.firstPopupHandled) } @Test - fun whenInjectAutoconsentIfUrlIsExceptionThenDoNothing() { + fun `injectAutoconsent - url is exception - do nothing`() { givenSettingsRepositoryAllowsInjection() autoconsent.injectAutoconsent(webView, EXCEPTION_URL) @@ -155,7 +155,7 @@ class RealAutoconsentTest { } @Test - fun whenInjectAutoconsentIfUrlContainsDomainThatIsExceptionThenDoNothing() { + fun `injectAutoconsent - url contains exception domain - do nothing`() { givenSettingsRepositoryAllowsInjection() autoconsent.injectAutoconsent(webView, EXCEPTION_SUBDOMAIN_URL) @@ -164,7 +164,7 @@ class RealAutoconsentTest { } @Test - fun whenInjectAutoconsentIfUrlIsInUserAllowListThenDoNothing() { + fun `injectAutoconsent - url in user allow list - do nothing`() { givenSettingsRepositoryAllowsInjection() autoconsent.injectAutoconsent(webView, USER_ALLOWED_URL) @@ -173,7 +173,7 @@ class RealAutoconsentTest { } @Test - fun whenInjectAutoconsentIfUrlIsInUnprotectedListThenDoNothing() { + fun `injectAutoconsent - url in unprotected list - do nothing`() { givenSettingsRepositoryAllowsInjection() autoconsent.injectAutoconsent(webView, UNPROTECTED_URL) @@ -182,7 +182,7 @@ class RealAutoconsentTest { } @Test - fun whenInjectAutoconsentIfFeatureIsDisabledThenDoNothing() { + fun `injectAutoconsent - feature disabled - do nothing`() { givenSettingsRepositoryAllowsInjection() whenever(mockToggle.isEnabled()).thenReturn(false) diff --git a/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/handlers/EvalMessageHandlerPluginTest.kt b/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/handlers/EvalMessageHandlerPluginTest.kt index 3c8692afb2fd..6c70ea74d93f 100644 --- a/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/handlers/EvalMessageHandlerPluginTest.kt +++ b/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/handlers/EvalMessageHandlerPluginTest.kt @@ -46,14 +46,14 @@ class EvalMessageHandlerPluginTest { private val evalMessageHandlerPlugin = EvalMessageHandlerPlugin(TestScope(), coroutineRule.testDispatcherProvider) @Test - fun whenProcessMessageIfTypeNotEvalDoNothing() { + fun `processMessage - if type not eval - do nothing`() { evalMessageHandlerPlugin.process("noMatching", "", webView, mockCallback) assertNull(shadowOf(webView).lastEvaluatedJavascript) } @Test - fun whenProcessMessageIfDoesNotParseDoNothing() { + fun `processMessage - does not parse - do nothing`() { val message = """ {"type":"${evalMessageHandlerPlugin.supportedTypes.first()}", id: "myId", "code": "42==42"} """.trimIndent() @@ -64,7 +64,7 @@ class EvalMessageHandlerPluginTest { } @Test - fun whenProcessMessageThenCallEvaluateWithCorrectCode() { + fun `process - evaluate with correct code - last evaluated javascript`() { val expected = """ javascript:(function() { try { @@ -81,7 +81,7 @@ class EvalMessageHandlerPluginTest { } @Test - fun whenProcessMessageThenAndEvalTrueThenCorrectEvalRespSent() { + fun `process - and eval true - correct eval resp sent`() { evalMessageHandlerPlugin.process(evalMessageHandlerPlugin.supportedTypes.first(), message("42==42"), webView, mockCallback) val shadow = shadowOf(webView) @@ -96,7 +96,7 @@ class EvalMessageHandlerPluginTest { } @Test - fun whenProcessMessageThenAndEvalFalseThenCorrectEvalRespSent() { + fun `process - and eval false - correct eval resp sent`() { evalMessageHandlerPlugin.process(evalMessageHandlerPlugin.supportedTypes.first(), message("41==42"), webView, mockCallback) val shadow = shadowOf(webView) diff --git a/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/handlers/InitMessageHandlerPluginTest.kt b/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/handlers/InitMessageHandlerPluginTest.kt index e307bfbeb99f..4a9fc28734ee 100644 --- a/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/handlers/InitMessageHandlerPluginTest.kt +++ b/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/handlers/InitMessageHandlerPluginTest.kt @@ -55,14 +55,14 @@ class InitMessageHandlerPluginTest { ) @Test - fun whenProcessIfMessageTypeIsNotInitThenDoNothing() { + fun `process - if message type is not init - do nothing`() { initHandlerPlugin.process("noMatching", "", webView, mockCallback) assertNull(shadowOf(webView).lastEvaluatedJavascript) } @Test - fun whenProcessIfCannotParseMessageThenDoNothing() { + fun `processIfCannotParseMessage - do nothing`() { val message = """ {"type":"${initHandlerPlugin.supportedTypes.first()}", url: "http://www.example.com"} """.trimIndent() @@ -73,7 +73,7 @@ class InitMessageHandlerPluginTest { } @Test - fun whenProcessIfNotUrlSchemaThenDoNothing() { + fun `processIfNotUrlSchema - do nothing - null`() { val message = """ {"type":"${initHandlerPlugin.supportedTypes.first()}", "url": "ftp://www.example.com"} """.trimIndent() @@ -84,7 +84,7 @@ class InitMessageHandlerPluginTest { } @Test - fun whenProcessIfAutoconsentIsDisabledAndAlreadyHandledThenDoNothing() { + fun `processIfAutoconsentIsDisabledAndAlreadyHandled - do nothing`() { settingsRepository.userSetting = false settingsRepository.firstPopupHandled = true @@ -94,7 +94,7 @@ class InitMessageHandlerPluginTest { } @Test - fun whenProcessIfAutoconsentIsDisabledAndNotHandledThenDoNotCallEvaluate() { + fun `processIfAutoconsentIsDisabledAndNotHandled - do not call evaluate`() { settingsRepository.userSetting = false settingsRepository.firstPopupHandled = false @@ -104,7 +104,7 @@ class InitMessageHandlerPluginTest { } @Test - fun whenProcessMessageForFirstTimeThenDoNotCallEvaluate() { + fun `processMessageForFirstTime - do not call evaluate - null result`() { whenever(repository.disabledCMPs).thenReturn(CopyOnWriteArrayList().apply { add("MyCmp") }) settingsRepository.userSetting = false settingsRepository.firstPopupHandled = false @@ -117,7 +117,7 @@ class InitMessageHandlerPluginTest { } @Test - fun whenProcessMessageResponseSentIsCorrect() { + fun `processMessageResponseSent - correct response - `() { settingsRepository.userSetting = true settingsRepository.firstPopupHandled = true whenever(repository.disabledCMPs).thenReturn(CopyOnWriteArrayList()) @@ -136,7 +136,7 @@ class InitMessageHandlerPluginTest { } @Test - fun whenProcessMessageThenOnResultReceivedCalled() { + fun `processMessage - on result received called - consent not managed`() { settingsRepository.userSetting = true settingsRepository.firstPopupHandled = true diff --git a/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/handlers/OptOutAndAutoconsentDoneMessageHandlerPluginTest.kt b/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/handlers/OptOutAndAutoconsentDoneMessageHandlerPluginTest.kt index da6bd0553802..b860d7d09c79 100644 --- a/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/handlers/OptOutAndAutoconsentDoneMessageHandlerPluginTest.kt +++ b/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/handlers/OptOutAndAutoconsentDoneMessageHandlerPluginTest.kt @@ -42,7 +42,7 @@ class OptOutAndAutoconsentDoneMessageHandlerPluginTest { private val handler = OptOutAndAutoconsentDoneMessageHandlerPlugin(TestScope(), coroutineRule.testDispatcherProvider) @Test - fun whenProcessIfMessageTypeIsNotIncludedInListThenDoNothing() { + fun `process - if message type is not included in list - do nothing`() { handler.process("noMatching", "", webView, mockCallback) verifyNoInteractions(mockCallback) @@ -50,7 +50,7 @@ class OptOutAndAutoconsentDoneMessageHandlerPluginTest { } @Test - fun whenProcessIfCannotParseMessageThenDoNothing() { + fun `processIfCannotParseMessage - do nothing`() { val message = """ {"type":"${handler.supportedTypes}", url: "http://www.example.com", "cmp: "test"} """.trimIndent() @@ -62,28 +62,28 @@ class OptOutAndAutoconsentDoneMessageHandlerPluginTest { } @Test - fun whenProcessOptOutIfResultIsFailsThenSendResultWithFailure() { + fun `processOptOutIfResultIsFails - send result with failure`() { handler.process(getOptOut(), optOutMessage(result = false, selfTest = false), webView, mockCallback) verify(mockCallback).onResultReceived(consentManaged = true, optOutFailed = true, selfTestFailed = false, isCosmetic = null) } @Test - fun whenProcessAutoconsentDoneIfCosmeticThenResultSentWithCosmeticSetToTrue() { + fun `processAutoconsent - cosmetic - result sent with cosmetic set to true`() { handler.process(getAutoconsentType(), autoconsentDoneMessage(cosmetic = true), webView, mockCallback) verify(mockCallback).onResultReceived(consentManaged = true, optOutFailed = false, selfTestFailed = false, isCosmetic = true) } @Test - fun whenProcessAutoconsentDoneIfNotCosmeticThenResultSentWithCosmeticSetToFalse() { + fun `processAutoconsent - not cosmetic - result sent with cosmetic set to false`() { handler.process(getAutoconsentType(), autoconsentDoneMessage(cosmetic = false), webView, mockCallback) verify(mockCallback).onResultReceived(consentManaged = true, optOutFailed = false, selfTestFailed = false, isCosmetic = false) } @Test - fun whenProcessAutoconsentDoneIfCannotGetHostTHenDoNothing() { + fun `processAutoconsent - done if cannot get host - do nothing`() { handler.process(getAutoconsentType(), autoconsentDoneMessage("noHost"), webView, mockCallback) verifyNoInteractions(mockCallback) @@ -91,7 +91,7 @@ class OptOutAndAutoconsentDoneMessageHandlerPluginTest { } @Test - fun whenProcessOptOutWithSelfTestThenAutoconsentCallsEvaluateJavascript() { + fun `processOptOutWithSelfTest - evaluate javascript - calls auto consent`() { val expected = """ javascript:(function() { window.autoconsentMessageCallback({ "type": "selfTest" }, window.origin); diff --git a/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/handlers/PopUpFoundMessageHandlerPluginTest.kt b/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/handlers/PopUpFoundMessageHandlerPluginTest.kt index 1634026fb86f..c03da54b6ce2 100644 --- a/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/handlers/PopUpFoundMessageHandlerPluginTest.kt +++ b/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/handlers/PopUpFoundMessageHandlerPluginTest.kt @@ -37,14 +37,14 @@ class PopUpFoundMessageHandlerPluginTest { private val popupFoundHandler = PopUpFoundMessageHandlerPlugin(repository) @Test - fun whenProcessIfMessageTypeIsNotPopUpFoundThenDoNothing() { + fun `processIfMessageTypeIsNotPopUp - do nothing - callback not handled`() { popupFoundHandler.process("noMatching", "", webView, mockCallback) verify(mockCallback, never()).onFirstPopUpHandled() } @Test - fun whenProcessIfSettingEnabledThenDoNothing() { + fun `process - if setting enabled - do nothing`() { repository.userSetting = true popupFoundHandler.process(popupFoundHandler.supportedTypes.first(), "", webView, mockCallback) @@ -53,7 +53,7 @@ class PopUpFoundMessageHandlerPluginTest { } @Test - fun whenProcessIfSettingDisabledAndCmpIsNotTopThenCallCallback() { + fun `processIfSettingDisabledAndCmpIsNotTop - callback called`() { repository.userSetting = false popupFoundHandler.process(popupFoundHandler.supportedTypes.first(), message("test"), webView, mockCallback) @@ -62,7 +62,7 @@ class PopUpFoundMessageHandlerPluginTest { } @Test - fun whenProcessIfSettingDisabledAndCmpIsTopThenDoNothing() { + fun `process - setting disabled and cmp is top - do nothing`() { repository.userSetting = false popupFoundHandler.process(popupFoundHandler.supportedTypes.first(), message("test-top"), webView, mockCallback) diff --git a/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/handlers/SelfTestResultMessageHandlerPluginTest.kt b/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/handlers/SelfTestResultMessageHandlerPluginTest.kt index 1ab7f039078d..84aefb4b3240 100644 --- a/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/handlers/SelfTestResultMessageHandlerPluginTest.kt +++ b/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/handlers/SelfTestResultMessageHandlerPluginTest.kt @@ -35,14 +35,14 @@ class SelfTestResultMessageHandlerPluginTest { private val selfTestPlugin = SelfTestResultMessageHandlerPlugin() @Test - fun whenProcessIfMessageTypeIsNotSelfTestThenDoNothing() { + fun `process - if message type is not self test - do nothing`() { selfTestPlugin.process("noMatching", "", webView, mockCallback) verifyNoInteractions(mockCallback) } @Test - fun whenProcessIfCannotParseMessageThenDoNothing() { + fun `processIfCannotParseMessage - do nothing`() { val message = """ {"type":"${selfTestPlugin.supportedTypes.first()}", cmp: "test", "result": true, "url": "http://example.com"} """.trimIndent() @@ -53,7 +53,7 @@ class SelfTestResultMessageHandlerPluginTest { } @Test - fun whenProcessThenCallDashboardWithCorrectParameters() { + fun `process - dashboard with correct parameters - on result received`() { val message = """ {"type":"${selfTestPlugin.supportedTypes.first()}", "cmp": "test", "result": true, "url": "http://example.com"} """.trimIndent() diff --git a/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/remoteconfig/RealAutoconsentExceptionsRepositoryTest.kt b/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/remoteconfig/RealAutoconsentExceptionsRepositoryTest.kt index 976e96ad2f25..44de80070c10 100644 --- a/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/remoteconfig/RealAutoconsentExceptionsRepositoryTest.kt +++ b/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/remoteconfig/RealAutoconsentExceptionsRepositoryTest.kt @@ -49,7 +49,7 @@ class RealAutoconsentExceptionsRepositoryTest { } @Test - fun whenRepositoryIsCreatedThenExceptionsLoadedIntoMemory() { + fun `whenRepositoryIsCreatedThenExceptionsLoadedIntoMemory - exceptions loaded into memory`() { givenDaoContainsExceptions() repository = RealAutoconsentExceptionsRepository(TestScope(), coroutineRule.testDispatcherProvider, mockDatabase, isMainProcess = true) @@ -58,7 +58,7 @@ class RealAutoconsentExceptionsRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = runTest { + fun `insertAll - update all called`() = runTest { repository = RealAutoconsentExceptionsRepository(TestScope(), coroutineRule.testDispatcherProvider, mockDatabase, isMainProcess = true) repository.insertAllExceptions(listOf()) @@ -67,7 +67,7 @@ class RealAutoconsentExceptionsRepositoryTest { } @Test - fun whenUpdateAllThenPreviousExceptionsAreCleared() = runTest { + fun `insertAll - previous exceptions cleared`() = runTest { givenDaoContainsExceptions() repository = RealAutoconsentExceptionsRepository(TestScope(), coroutineRule.testDispatcherProvider, mockDatabase, isMainProcess = true) diff --git a/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/remoteconfig/RealAutoconsentFeatureSettingsRepositoryTest.kt b/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/remoteconfig/RealAutoconsentFeatureSettingsRepositoryTest.kt index f5519819bc02..09c2f12aaed7 100644 --- a/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/remoteconfig/RealAutoconsentFeatureSettingsRepositoryTest.kt +++ b/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/remoteconfig/RealAutoconsentFeatureSettingsRepositoryTest.kt @@ -49,7 +49,7 @@ class RealAutoconsentFeatureSettingsRepositoryTest { } @Test - fun whenRepositoryIsCreatedThenExceptionsLoadedIntoMemory() { + fun `whenRepositoryIsCreatedThenExceptionsLoadedIntoMemory - state - exceptions loaded into memory`() { givenDaoContainsDisabledCmps() repository = RealAutoconsentFeatureSettingsRepository(TestScope(), coroutineRule.testDispatcherProvider, mockDatabase, isMainProcess = true) @@ -58,7 +58,7 @@ class RealAutoconsentFeatureSettingsRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = runTest { + fun `updateAll - update all settings called - update all disabled cmps`() = runTest { repository = RealAutoconsentFeatureSettingsRepository(TestScope(), coroutineRule.testDispatcherProvider, mockDatabase, isMainProcess = true) repository.updateAllSettings(AutoconsentSettings(listOf())) @@ -67,7 +67,7 @@ class RealAutoconsentFeatureSettingsRepositoryTest { } @Test - fun whenUpdateAllThenPreviousExceptionsAreCleared() = runTest { + fun `updateAll - previous exceptions cleared`() = runTest { givenDaoContainsDisabledCmps() repository = RealAutoconsentFeatureSettingsRepository(TestScope(), coroutineRule.testDispatcherProvider, mockDatabase, isMainProcess = true) diff --git a/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/ui/AutoconsentSettingsViewModelTest.kt b/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/ui/AutoconsentSettingsViewModelTest.kt index d3b1ef80866b..2c224c3c56b2 100644 --- a/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/ui/AutoconsentSettingsViewModelTest.kt +++ b/autoconsent/autoconsent-impl/src/test/java/com/duckduckgo/autoconsent/impl/ui/AutoconsentSettingsViewModelTest.kt @@ -36,7 +36,7 @@ class AutoconsentSettingsViewModelTest { private val viewModel = AutoconsentSettingsViewModel(autoconsent) @Test - fun whenViewModelCreatedThenEmitViewState() = runTest { + fun `whenViewModelCreated - view state emitted - auto consent disabled`() = runTest { viewModel.viewState.test { assertFalse(awaitItem().autoconsentEnabled) cancelAndIgnoreRemainingEvents() @@ -44,7 +44,7 @@ class AutoconsentSettingsViewModelTest { } @Test - fun whenOnLearnMoreSelectedCalledThenLaunchLearnMoreWebPageCommandIsSent() = runTest { + fun `onLearnMoreSelected - launch learn more webpage command sent`() = runTest { viewModel.commands().test { viewModel.onLearnMoreSelected() assertEquals(AutoconsentSettingsViewModel.Command.LaunchLearnMoreWebPage(), awaitItem()) @@ -53,7 +53,7 @@ class AutoconsentSettingsViewModelTest { } @Test - fun whenOnUserToggleAutoconsentToTrueThenAutoconsentEnabledIsTrue() = runTest { + fun `onUserToggleAutoconsent - viewState updated - autoconsent enabled is true`() = runTest { viewModel.viewState.test { assertFalse(awaitItem().autoconsentEnabled) viewModel.onUserToggleAutoconsent(true) @@ -64,7 +64,7 @@ class AutoconsentSettingsViewModelTest { } @Test - fun whenOnUserToggleAutoconsentToFalseThenAutoconsentEnabledIsFalse() = runTest { + fun `onUserToggleAutoconsent - view state updated - auto consent enabled is false`() = runTest { viewModel.viewState.test { viewModel.onUserToggleAutoconsent(false) assertFalse(awaitItem().autoconsentEnabled) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/AutofillCapabilityCheckerImplTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/AutofillCapabilityCheckerImplTest.kt index 16354c3f2a8f..f0bc4f5c5f75 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/AutofillCapabilityCheckerImplTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/AutofillCapabilityCheckerImplTest.kt @@ -39,13 +39,13 @@ class AutofillCapabilityCheckerImplTest { private lateinit var testee: AutofillCapabilityCheckerImpl @Test - fun whenTopLevelFeatureDisabledAndDisabledByUserThenCannotAccessAnySubFeatures() = runTest { + fun `setupConfig - top level feature disabled by user - cannot access any sub features`() = runTest { setupConfig(topLevelFeatureEnabled = false, autofillEnabledByUser = false) assertAllSubFeaturesDisabled() } @Test - fun whenTopLevelFeatureDisabledButEnabledByUserThenCannotAccessAnySubFeatures() = runTest { + fun `setupConfig - top level feature disabled but enabled by user - cannot access any sub features`() = runTest { setupConfig(topLevelFeatureEnabled = false, autofillEnabledByUser = true) assertAllSubFeaturesDisabled() } @@ -55,7 +55,7 @@ class AutofillCapabilityCheckerImplTest { */ @Test - fun whenUserHasAutofillEnabledThenCanInjectCredentialsDictatedByConfig() = runTest { + fun `canInjectCredentials - autofill enabled - can inject credentials`() = runTest { setupConfig(topLevelFeatureEnabled = true, autofillEnabledByUser = true, canInjectCredentials = true) assertTrue(testee.canInjectCredentialsToWebView(URL)) @@ -64,7 +64,7 @@ class AutofillCapabilityCheckerImplTest { } @Test - fun whenUserHasAutofillEnabledThenCanSaveCredentialsDictatedByConfig() = runTest { + fun `whenUserHasAutofillEnabledThenCanSaveCredentials - config - can save credentials`() = runTest { setupConfig(topLevelFeatureEnabled = true, autofillEnabledByUser = true, canSaveCredentials = true) assertTrue(testee.canSaveCredentialsFromWebView(URL)) @@ -73,7 +73,7 @@ class AutofillCapabilityCheckerImplTest { } @Test - fun whenUserHasAutofillEnabledThenCanAccessCredentialManagementScreenDictatedByConfig() = runTest { + fun `canAccessCredentialManagementScreen - autofill enabled - can access credential management screen`() = runTest { setupConfig(topLevelFeatureEnabled = true, autofillEnabledByUser = true, canAccessCredentialManagement = true) assertTrue(testee.canAccessCredentialManagementScreen()) @@ -82,7 +82,7 @@ class AutofillCapabilityCheckerImplTest { } @Test - fun whenUserHasAutofillEnabledThenCanGeneratePasswordFromWebViewDictatedByConfig() = runTest { + fun `canGeneratePasswordFromWebView - autofill enabled - can generate password`() = runTest { setupConfig(topLevelFeatureEnabled = true, autofillEnabledByUser = true, canGeneratePassword = true) assertTrue(testee.canGeneratePasswordFromWebView(URL)) @@ -95,25 +95,25 @@ class AutofillCapabilityCheckerImplTest { */ @Test - fun whenUserHasAutofillEnabledButTopLevelFeatureDisabledThenCanInjectCredentialsIsFalse() = runTest { + fun `canInjectCredentials - user has autofill enabled but top level feature disabled - is false`() = runTest { setupConfig(topLevelFeatureEnabled = false, autofillEnabledByUser = true) assertFalse(testee.canInjectCredentialsToWebView(URL)) } @Test - fun whenUserHasAutofillEnabledThenCanSaveCredentialsIsFalse() = runTest { + fun `canSaveCredentials - user has autofill enabled - cannot save credentials`() = runTest { setupConfig(topLevelFeatureEnabled = false, autofillEnabledByUser = true) assertFalse(testee.canSaveCredentialsFromWebView(URL)) } @Test - fun whenUserHasAutofillEnabledThenCanAccessCredentialManagementScreenIsFalse() = runTest { + fun `canAccessCredentialManagementScreen - user has autofill enabled - cannot access credential management screen`() = runTest { setupConfig(topLevelFeatureEnabled = false, autofillEnabledByUser = true) assertFalse(testee.canAccessCredentialManagementScreen()) } @Test - fun whenUserHasAutofillEnabledThenCanGeneratePasswordFromWebViewIsFalse() = runTest { + fun `canGeneratePasswordFromWebView - autofill enabled by user - cannot generate password from web view`() = runTest { setupConfig(topLevelFeatureEnabled = false, autofillEnabledByUser = true) assertFalse(testee.canGeneratePasswordFromWebView(URL)) } diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/AutofillStoredBackJavascriptInterfaceTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/AutofillStoredBackJavascriptInterfaceTest.kt index 172112766201..8a2c28883297 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/AutofillStoredBackJavascriptInterfaceTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/AutofillStoredBackJavascriptInterfaceTest.kt @@ -121,14 +121,14 @@ class AutofillStoredBackJavascriptInterfaceTest { } @Test - fun whenInjectingNoCredentialResponseThenCorrectJsonWriterInvoked() = runTest { + fun `injectNoCredentialResponse - correct json writer invoked`() = runTest { testee.injectNoCredentials() verify(autofillResponseWriter).generateEmptyResponseGetAutofillData() verifyMessageSent() } @Test - fun whenInjectingCredentialResponseThenCorrectJsonWriterInvoked() = runTest { + fun `injectCredentials - correct json writer invoked`() = runTest { val loginCredentials = LoginCredentials(0, "example.com", "username", "password") testee.injectCredentials(loginCredentials) verify(autofillResponseWriter).generateResponseGetAutofillData(any()) @@ -136,7 +136,7 @@ class AutofillStoredBackJavascriptInterfaceTest { } @Test - fun whenGetAutofillDataCalledNoCredentialsAvailableThenNoCredentialsCallbackInvoked() = runTest { + fun `getAutofillData - no credentials available - no credentials callback invoked`() = runTest { setupRequestForSubTypeUsername() whenever(autofillStore.getCredentials(any())).thenReturn(emptyList()) initiateGetAutofillDataRequest() @@ -144,14 +144,14 @@ class AutofillStoredBackJavascriptInterfaceTest { } @Test - fun whenGetAutofillDataCalledWithCredentialsAvailableThenCredentialsAvailableCallbackInvoked() = runTest { + fun `getAutofillData - credentials available - credentials available callback invoked`() = runTest { whenever(autofillStore.getCredentials(any())).thenReturn(listOf(LoginCredentials(0, "example.com", "username", "password"))) initiateGetAutofillDataRequest() assertCredentialsAvailable() } @Test - fun whenGetAutofillDataCalledWithCredentialsAvailableWithNullUsernameUsernameConvertedToEmptyString() = runTest { + fun `getAutofillData - credentials available - username converted to empty string`() = runTest { setupRequestForSubTypePassword() whenever(autofillStore.getCredentials(any())).thenReturn( listOf( @@ -168,7 +168,7 @@ class AutofillStoredBackJavascriptInterfaceTest { } @Test - fun whenRequestSpecifiesSubtypeUsernameAndNoEntriesThenNoCredentialsCallbackInvoked() = runTest { + fun `initiateGetAutofillDataRequest - no credentials callback invoked`() = runTest { setupRequestForSubTypeUsername() whenever(autofillStore.getCredentials(any())).thenReturn(emptyList()) initiateGetAutofillDataRequest() @@ -176,7 +176,7 @@ class AutofillStoredBackJavascriptInterfaceTest { } @Test - fun whenRequestSpecifiesSubtypeUsernameAndNoEntriesWithAUsernameThenNoCredentialsCallbackInvoked() = runTest { + fun `initiateGetAutofillDataRequest - no entries with username - no credentials callback invoked`() = runTest { setupRequestForSubTypeUsername() whenever(autofillStore.getCredentials(any())).thenReturn( listOf( @@ -189,7 +189,7 @@ class AutofillStoredBackJavascriptInterfaceTest { } @Test - fun whenRequestSpecifiesSubtypeUsernameAndSingleEntryWithAUsernameThenCredentialsAvailableCallbackInvoked() = runTest { + fun `initiateGetAutofillDataRequest - credentials available callback invoked - username contains foo`() = runTest { setupRequestForSubTypeUsername() whenever(autofillStore.getCredentials(any())).thenReturn( listOf( @@ -204,7 +204,7 @@ class AutofillStoredBackJavascriptInterfaceTest { } @Test - fun whenRequestSpecifiesSubtypeUsernameAndMultipleEntriesWithAUsernameThenCredentialsAvailableCallbackInvoked() = runTest { + fun `initiateGetAutofillDataRequest - credentials available callback invoked - username and multiple entries with a username`() = runTest { setupRequestForSubTypeUsername() whenever(autofillStore.getCredentials(any())).thenReturn( listOf( @@ -221,7 +221,7 @@ class AutofillStoredBackJavascriptInterfaceTest { } @Test - fun whenRequestSpecifiesSubtypePasswordAndNoEntriesThenNoCredentialsCallbackInvoked() = runTest { + fun `getAutofillData - subtype password and no entries - no credentials callback invoked`() = runTest { setupRequestForSubTypePassword() whenever(autofillStore.getCredentials(any())).thenReturn(emptyList()) initiateGetAutofillDataRequest() @@ -229,7 +229,7 @@ class AutofillStoredBackJavascriptInterfaceTest { } @Test - fun whenRequestSpecifiesSubtypePasswordAndNoEntriesWithAPasswordThenNoCredentialsCallbackInvoked() = runTest { + fun `initiateGetAutofillDataRequest - no entries with a password - no credentials callback invoked`() = runTest { setupRequestForSubTypePassword() whenever(autofillStore.getCredentials(any())).thenReturn( listOf( @@ -242,7 +242,7 @@ class AutofillStoredBackJavascriptInterfaceTest { } @Test - fun whenRequestSpecifiesSubtypePasswordAndSingleEntryWithAPasswordThenCredentialsAvailableCallbackInvoked() = runTest { + fun `initiateGetAutofillDataRequest - request specifies subtype password and single entry with a password - credentials available callback invoked`() = runTest { setupRequestForSubTypePassword() whenever(autofillStore.getCredentials(any())).thenReturn( listOf( @@ -257,7 +257,7 @@ class AutofillStoredBackJavascriptInterfaceTest { } @Test - fun whenRequestSpecifiesSubtypePasswordAndMultipleEntriesWithAPasswordThenCredentialsAvailableCallbackInvoked() = runTest { + fun `initiateGetAutofillDataRequest - credentials available callback invoked - password and multiple entries with a password`() = runTest { setupRequestForSubTypePassword() whenever(autofillStore.getCredentials(any())).thenReturn( listOf( @@ -275,14 +275,14 @@ class AutofillStoredBackJavascriptInterfaceTest { } @Test - fun whenStoreFormDataCalledWithNoUsernameThenCallbackInvoked() = runTest { + fun `storeFormData - no username - callback invoked`() = runTest { configureRequestParserToReturnSaveCredentialRequestType(username = null, password = "password") testee.storeFormData("") assertNotNull(testCallback.credentialsToSave) } @Test - fun whenStoreFormDataCalledWithNoPasswordThenCallbackInvoked() = runTest { + fun `storeFormData - no password - callback invoked`() = runTest { configureRequestParserToReturnSaveCredentialRequestType(username = "dax@duck.com", password = null) testee.storeFormData("") assertNotNull(testCallback.credentialsToSave) @@ -290,14 +290,14 @@ class AutofillStoredBackJavascriptInterfaceTest { } @Test - fun whenStoreFormDataCalledWithNullUsernameAndPasswordThenCallbackNotInvoked() = runTest { + fun `storeFormData - store form data called with null username and password - callback not invoked`() = runTest { configureRequestParserToReturnSaveCredentialRequestType(username = null, password = null) testee.storeFormData("") assertNull(testCallback.credentialsToSave) } @Test - fun whenStoreFormDataCalledWithBlankUsernameThenCallbackInvoked() = runTest { + fun `storeFormData - store form data called with blank username - callback invoked`() = runTest { configureRequestParserToReturnSaveCredentialRequestType(username = " ", password = "password") testee.storeFormData("") assertEquals(" ", testCallback.credentialsToSave!!.username) @@ -305,7 +305,7 @@ class AutofillStoredBackJavascriptInterfaceTest { } @Test - fun whenStoreFormDataCalledWithBlankPasswordThenCallbackInvoked() = runTest { + fun `storeFormData - store form data called with blank password - callback invoked`() = runTest { configureRequestParserToReturnSaveCredentialRequestType(username = "username", password = " ") testee.storeFormData("") assertEquals("username", testCallback.credentialsToSave!!.username) @@ -313,7 +313,7 @@ class AutofillStoredBackJavascriptInterfaceTest { } @Test - fun whenStoreFormDataCalledButSiteInNeverSaveListThenCallbackNotInvoked() = runTest { + fun `storeFormData - site in never save list - callback not invoked`() = runTest { configureRequestParserToReturnSaveCredentialRequestType(username = "username", password = "password") whenever(neverSavedSiteRepository.isInNeverSaveList(any())).thenReturn(true) testee.storeFormData("") @@ -321,14 +321,14 @@ class AutofillStoredBackJavascriptInterfaceTest { } @Test - fun whenStoreFormDataCalledWithBlankUsernameAndBlankPasswordThenCallbackNotInvoked() = runTest { + fun `storeFormData - store form data called with blank username and blank password - callback not invoked`() = runTest { configureRequestParserToReturnSaveCredentialRequestType(username = " ", password = " ") testee.storeFormData("") assertNull(testCallback.credentialsToSave) } @Test - fun whenStoreFormDataCalledAndParsingErrorThenExceptionIsContained() = runTest { + fun `storeFormData - parsing error - exception contained`() = runTest { configureRequestParserToReturnSaveCredentialRequestType(username = "username", password = "password") whenever(requestParser.parseStoreFormDataRequest(any())).thenReturn(Result.failure(RuntimeException("Parsing error"))) testee.storeFormData("") diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/InlineBrowserAutofillTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/InlineBrowserAutofillTest.kt index 0f28994e95a1..a347c3b75622 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/InlineBrowserAutofillTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/InlineBrowserAutofillTest.kt @@ -82,7 +82,7 @@ class InlineBrowserAutofillTest { } @Test - fun whenRemoveJsInterfaceThenRemoveReferenceToWebview() { + fun `removeJsInterface - remove reference to webview`() { testee.addJsInterface(testWebView, testCallback, emailProtectionInContextCallback, emailProtectionInContextSignupFlowCallback, "tabId") assertNotNull(autofillJavascriptInterface.webView) @@ -93,14 +93,14 @@ class InlineBrowserAutofillTest { } @Test - fun whenInjectCredentialsNullThenInterfaceInjectNoCredentials() { + fun `injectCredentials - null - no credentials injected`() { testee.injectCredentials(null) assertEquals(NoCredentialsInjected, autofillJavascriptInterface.lastAction) } @Test - fun whenInjectCredentialsThenInterfaceCredentialsInjected() { + fun `injectCredentials - interface credentials injected`() { val toInject = LoginCredentials( id = 1, domain = "hello.com", diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/RealAutofillTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/RealAutofillTest.kt index 1fffbc36cb3b..9d8eb4e17dec 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/RealAutofillTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/RealAutofillTest.kt @@ -40,28 +40,28 @@ class RealAutofillTest { } @Test - fun whenIsAnExceptionAndDomainIsListedInTheExceptionsListThenReturnTrue() { + fun `isAnException - exception and domain listed in exceptions list - true`() { givenThereAreExceptions() assertTrue(testee.isAnException("http://www.example.com")) } @Test - fun whenIsAnExceptionWithSubdomainAndDomainIsListedInTheExceptionsListThenReturnTrue() { + fun `isAnException - exceptions list contains subdomain and domain - returns true`() { givenThereAreExceptions() assertTrue(testee.isAnException("http://test.example.com")) } @Test - fun whenIsAnExceptionAndDomainIsNotListedInTheExceptionsListThenReturnFalse() { + fun `isAnException - domain not listed in exceptions list - returns false`() { whenever(mockAutofillRepository.exceptions).thenReturn(CopyOnWriteArrayList()) assertFalse(testee.isAnException("http://test.example.com")) } @Test - fun whenIsAnExceptionAndDomainIsListedInTheUnprotectedTemporaryListThenReturnTrue() { + fun `isAnException - is listed in unprotected temporary list - returns true`() { val url = "http://example.com" whenever(mockUnprotectedTemporary.isAnException(url)).thenReturn(true) whenever(mockAutofillRepository.exceptions).thenReturn(CopyOnWriteArrayList()) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/RealDuckAddressLoginCreatorTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/RealDuckAddressLoginCreatorTest.kt index f16fc89e9679..0fee0ca13605 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/RealDuckAddressLoginCreatorTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/RealDuckAddressLoginCreatorTest.kt @@ -47,28 +47,28 @@ class RealDuckAddressLoginCreatorTest { ) @Test - fun whenAutofillCapabilitiesRestrictSavingThenNoLoginCreated() = runTest { + fun `createLogin - autofill capabilities restrict saving - no login created`() = runTest { whenever(autofillCapabilityChecker.canSaveCredentialsFromWebView(URL)).thenReturn(false) testee.createLoginForPrivateDuckAddress(DUCK_ADDRESS, TAB_ID, URL) verifyNotSavedOrUpdated() } @Test - fun whenNoAutoSavedLoginIdThenNewLoginSaved() = runTest { + fun `createLogin - no auto saved login id - new login saved`() = runTest { configureReadyToAutoSave() testee.createLoginForPrivateDuckAddress(DUCK_ADDRESS, TAB_ID, URL) verifyLoginSaved() } @Test - fun whenAutoSavedLoginIdSetButNoMatchingLoginFoundThenNewLoginSaved() = runTest { + fun `createLoginForPrivateDuckAddress - auto saved login id set but no matching login found - new login saved`() = runTest { configureReadyToAutoSave() testee.createLoginForPrivateDuckAddress(DUCK_ADDRESS, TAB_ID, URL) verifyLoginSaved() } @Test - fun whenAutoSavedLoginFoundAndDetailsAlreadyMatchThenNotSavedOrUpdated() = runTest { + fun `createLogin - auto saved login found and details already match - not saved or updated`() = runTest { val existingLogin = aLogin(id = 1, username = DUCK_ADDRESS) configureReadyToAutoSave() whenever(automaticSavedLoginsMonitor.getAutoSavedLoginId(TAB_ID)).thenReturn(1) @@ -79,7 +79,7 @@ class RealDuckAddressLoginCreatorTest { } @Test - fun whenAutoSavedLoginFoundAndUsernameDifferentThenLoginUpdated() = runTest { + fun `createLoginForPrivateDuckAddress - auto saved login found and username different - login updated`() = runTest { val existingLogin = aLogin(id = 1, username = "different-username") whenever(neverSavedSiteRepository.isInNeverSaveList(any())).thenReturn(false) whenever(autofillCapabilityChecker.canSaveCredentialsFromWebView(URL)).thenReturn(true) @@ -91,7 +91,7 @@ class RealDuckAddressLoginCreatorTest { } @Test - fun whenSiteIsInNeverSaveListThenDoNotAutoSaveALogin() = runTest { + fun `createLogin - site in never save list - do not auto save login`() = runTest { configureReadyToAutoSave() whenever(neverSavedSiteRepository.isInNeverSaveList(URL)).thenReturn(true) testee.createLoginForPrivateDuckAddress(DUCK_ADDRESS, TAB_ID, URL) @@ -99,7 +99,7 @@ class RealDuckAddressLoginCreatorTest { } @Test - fun whenSiteIsNotInNeverSaveListThenAutoSaveALogin() = runTest { + fun `createLogin - site not in never save list - auto save a login`() = runTest { configureReadyToAutoSave() whenever(neverSavedSiteRepository.isInNeverSaveList(any())).thenReturn(false) testee.createLoginForPrivateDuckAddress(DUCK_ADDRESS, TAB_ID, URL) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/SecureStoreBackedAutofillStoreTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/SecureStoreBackedAutofillStoreTest.kt index 046401a51808..e40c4ab29f01 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/SecureStoreBackedAutofillStoreTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/SecureStoreBackedAutofillStoreTest.kt @@ -80,14 +80,14 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenAutofillUnavailableAndPrefsAreAllTrueThenReturnTrueForAutofillEnabled() { + fun `canAccessSecureStorage - autofill unavailable and prefs are all true - return true for autofill enabled`() { setupTestee(canAccessSecureStorage = false) assertTrue(testee.autofillEnabled) } @Test - fun whenAutofillAvailableAndPrefsAreAllFalseThenReturnFalseForAutofillEnabled() = runTest { + fun `whenAutofillAvailableAndPrefsAreAllFalse - return false for autofill enabled`() = runTest { setupTesteeWithAutofillAvailable() whenever(autofillPrefsStore.isEnabled).thenReturn(false) @@ -95,19 +95,19 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenSecureStorageAvailableThenReturnAutofillAvailable() = runTest { + fun `setupTestee - secure storage available - autofill available`() = runTest { setupTesteeWithAutofillAvailable() assertTrue(testee.autofillAvailable) } @Test - fun whenSecureStorageNotAvailableThenReturnAutofillAvailableFalse() { + fun `whenSecureStorageNotAvailable - return autofill available false`() { setupTestee(canAccessSecureStorage = false) assertFalse(testee.autofillAvailable) } @Test - fun whenAutofillEnabledButCannotAccessSecureStorageThenGetCredentialsWithDomainReturnsEmpty() = runTest { + fun `getCredentials - autofill enabled but cannot access secure storage - returns empty`() = runTest { setupTestee(canAccessSecureStorage = false) val url = "example.com" storeCredentials(1, url, "username", "password") @@ -116,14 +116,14 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenStoreEmptyThenNoMatch() = runTest { + fun `containsCredentials - store empty - no match`() = runTest { setupTesteeWithAutofillAvailable() val result = testee.containsCredentials("example.com", "username", "password") assertNotMatch(result) } @Test - fun whenStoreContainsMatchingUsernameEntriesButNoneMatchingUrlThenNoMatch() = runTest { + fun `containsCredentials - store contains matching username entries but none matching url - no match`() = runTest { setupTesteeWithAutofillAvailable() storeCredentials(1, "https://example.com", "username", "password") val result = testee.containsCredentials("foo.com", "username", "password") @@ -131,7 +131,7 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenStoreContainsDomainButDifferentCredentialsThenUrlMatch() = runTest { + fun `containsCredentials - store contains domain but different credentials - url match`() = runTest { setupTesteeWithAutofillAvailable() storeCredentials(1, "https://example.com", "username", "password") val result = testee.containsCredentials("example.com", "differentUsername", "differentPassword") @@ -139,7 +139,7 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenPasswordExistsForSiteWithNoUsernameThenReturnUsernameMissing() = runTest { + fun `containsCredentials - password exists for site with no username - return username missing`() = runTest { setupTesteeWithAutofillAvailable() storeCredentials(id = 1, domain = "https://example.com", username = null, password = "password") val result = testee.containsCredentials("example.com", "username", "password") @@ -147,7 +147,7 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenDifferentPasswordExistsForSiteWithNoUsernameThenReturnUrlMatch() = runTest { + fun `containsCredentials - different password exists - return url match`() = runTest { setupTesteeWithAutofillAvailable() storeCredentials(id = 1, domain = "https://example.com", username = null, password = "password") val result = testee.containsCredentials("example.com", "username", "not-the-same-password") @@ -155,7 +155,7 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenStoreContainsDomainAndUsernameButDifferentPassword() = runTest { + fun `containsCredentials - different password - true`() = runTest { setupTesteeWithAutofillAvailable() storeCredentials(1, "https://example.com", "username", "password") val result = testee.containsCredentials("example.com", "username", "differentPassword") @@ -163,7 +163,7 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenStoreContainsMatchingDomainAndUsernameAndPassword() = runTest { + fun `containsCredentials - store contains matching domain and username and password - true`() = runTest { setupTesteeWithAutofillAvailable() storeCredentials(1, "https://example.com", "username", "password") val result = testee.containsCredentials("example.com", "username", "password") @@ -171,7 +171,7 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenNoCredentialsForUrlStoredThenGetCredentialsReturnNothing() = runTest { + fun `getCredentials - no credentials stored for url - returns nothing`() = runTest { setupTesteeWithAutofillAvailable() storeCredentials(1, "url.com", "username1", "password123") @@ -179,13 +179,13 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenNoCredentialsSavedThenGetAllCredentialsReturnNothing() = runTest { + fun `getAllCredentials - no credentials saved - returns nothing`() = runTest { setupTesteeWithAutofillAvailable() assertEquals(0, testee.getAllCredentials().first().size) } @Test - fun whenStoredCredentialMissingUsernameAndStoringACredentialWithNoUsernameThenUrlOnlyMatch() = runTest { + fun `storeCredential - missing username and storing credential with no username - url only match`() = runTest { setupTesteeWithAutofillAvailable() storeCredentials(1, "https://example.com", username = null, password = "password") val result = testee.containsCredentials("example.com", username = null, password = "differentPassword") @@ -193,7 +193,7 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenPasswordIsUpdatedForUrlThenUpdatedOnlyMatchingCredential() = runTest { + fun `updateCredentials - password updated for url - only matching credential updated`() = runTest { setupTesteeWithAutofillAvailable() val url = "https://example.com" storeCredentials(1, url, "username1", "password123") @@ -216,7 +216,7 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenPasswordIsUpdatedThenUpdatedOnlyMatchingCredential() = runTest { + fun `updateCredentials - password updated - only matching credential updated`() = runTest { setupTesteeWithAutofillAvailable() val url = "example.com" storeCredentials(1, url, "username1", "password123") @@ -239,7 +239,7 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenDomainIsUpdatedTheCleanRawUrl() = runTest { + fun `updateDomain - clean raw URL`() = runTest { setupTesteeWithAutofillAvailable() val url = "https://example.com" storeCredentials(1, url, "username1", "password123") @@ -258,7 +258,7 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenUsernameIsUpdatedForUrlThenUpdatedOnlyMatchingCredential() = runTest { + fun `updateUsernameForUrl - credentials updated`() = runTest { setupTesteeWithAutofillAvailable() val url = "example.com" storeCredentials(1, url, null, "password123") @@ -281,7 +281,7 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenUsernameMissingForAnotherUrlThenNoUpdatesMade() = runTest { + fun `updateCredentials - username missing for another url - no updates made`() = runTest { setupTesteeWithAutofillAvailable() val urlStored = "example.com" val newDomain = "test.com" @@ -297,7 +297,7 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenSaveCredentialsThenReturnSavedOnGetCredentials() = runTest { + fun `saveCredentials - get credentials returned`() = runTest { setupTesteeWithAutofillAvailable() val url = "example.com" val credentials = LoginCredentials( @@ -312,7 +312,7 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenPasswordIsDeletedThenRemoveCredentialFromStore() = runTest { + fun `deleteCredentials - remove credential from store`() = runTest { setupTesteeWithAutofillAvailable() val url = "example.com" storeCredentials(1, url, "username1", "password123") @@ -328,7 +328,7 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenCredentialWithIdIsStoredTheReturnCredentialsOnGetCredentialsWithId() = runTest { + fun `getCredentialsWithId - credential with id stored - returns credentials on get credentials with id`() = runTest { setupTesteeWithAutofillAvailable() val url = "example.com" storeCredentials(1, url, "username1", "password123") @@ -348,13 +348,13 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenNoCredentialStoredTheReturnNullOnGetCredentialsWithId() = runTest { + fun `getCredentialsWithId - no credential stored - returns null`() = runTest { setupTesteeWithAutofillAvailable() assertNull(testee.getCredentialsWithId(1)) } @Test - fun whenExactUrlMatchesThenCredentialsReturned() = runTest { + fun `getCredentials - exact url matches - credentials returned`() = runTest { setupTesteeWithAutofillAvailable() val savedUrl = "https://example.com" val visitedSite = "https://example.com" @@ -366,7 +366,7 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenExactSubdomainMatchesThenCredentialsReturned() = runTest { + fun `getCredentials - exact subdomain matches - credentials returned`() = runTest { setupTesteeWithAutofillAvailable() val savedUrl = "https://subdomain.example.com" val visitedSite = "https://subdomain.example.com" @@ -378,7 +378,7 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenExactWwwSubdomainMatchesThenCredentialsReturned() = runTest { + fun `getCredentials - exact www subdomain matches - credentials returned`() = runTest { setupTesteeWithAutofillAvailable() val savedUrl = "https://www.example.com" val visitedSite = "https://www.example.com" @@ -390,7 +390,7 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenSavedCredentialHasSubdomainAndVisitedPageDoesNotThenCredentialMatched() = runTest { + fun `getCredentials - saved credential has subdomain and visited page does not match - no match`() = runTest { setupTesteeWithAutofillAvailable() val savedUrl = "https://test.example.com" val visitedSite = "https://example.com" @@ -401,7 +401,7 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenSavedCredentialHasNoSubdomainAndVisitedPageDoesThenCredentialNotMatched() = runTest { + fun `getCredentials - no subdomain and visited page does not match - credential not matched`() = runTest { setupTesteeWithAutofillAvailable() val savedUrl = "https://example.com" val visitedSite = "https://test.example.com" @@ -412,7 +412,7 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenSavedCredentialHasDifferentSubdomainToVisitedPageSubdomainThenCredentialMatched() = runTest { + fun `getCredentials - saved credential has different subdomain to visited page subdomain - credential matched`() = runTest { setupTesteeWithAutofillAvailable() val savedUrl = "https://test.example.com" val visitedSite = "https://different.example.com" @@ -423,7 +423,7 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenReinsertingLoginCredentialsThenAllFieldsPreserved() = runTest { + fun `reinsertCredentials - all fields preserved`() = runTest { setupTesteeWithAutofillAvailable() val originalCredentials = LoginCredentials( id = 123, @@ -448,7 +448,7 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenUpdatingCredentialsByDefaultLastUpdatedTimestampGetsUpdated() = runTest { + fun `updateCredentials - last updated timestamp gets updated`() = runTest { setupTesteeWithAutofillAvailable() val saved = storeCredentials(id = 1, domain = "example.com", username = "username", password = "password") val updated = testee.updateCredentials(saved)!! @@ -456,7 +456,7 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenUpdatingCredentialsAndSpecifyNotToUpdateLastUpdatedTimestampThenNotUpdated() = runTest { + fun `updateCredentials - not update last updated timestamp - not updated`() = runTest { setupTesteeWithAutofillAvailable() val saved = storeCredentials(id = 1, domain = "example.com", username = "username", password = "password") val updated = testee.updateCredentials(saved, refreshLastUpdatedTimestamp = false)!! diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/configuration/InlineBrowserAutofillConfiguratorTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/configuration/InlineBrowserAutofillConfiguratorTest.kt index 9ac08289d8e8..f9043c919a14 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/configuration/InlineBrowserAutofillConfiguratorTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/configuration/InlineBrowserAutofillConfiguratorTest.kt @@ -56,7 +56,7 @@ class InlineBrowserAutofillConfiguratorTest { } @Test - fun whenFeatureIsNotEnabledThenDoNotInject() = runTest { + fun `configureAutofill - feature not enabled - do not inject`() = runTest { givenFeatureIsDisabled() inlineBrowserAutofillConfigurator.configureAutofillForCurrentPage(webView, "https://example.com") @@ -64,7 +64,7 @@ class InlineBrowserAutofillConfiguratorTest { } @Test - fun whenFeatureIsEnabledThenInject() = runTest { + fun `configureAutofill - feature enabled - inject`() = runTest { givenFeatureIsEnabled() inlineBrowserAutofillConfigurator.configureAutofillForCurrentPage(webView, "https://example.com") diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/configuration/RealAutofillRuntimeConfigProviderTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/configuration/RealAutofillRuntimeConfigProviderTest.kt index 757a04770905..a4f1238a5e97 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/configuration/RealAutofillRuntimeConfigProviderTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/configuration/RealAutofillRuntimeConfigProviderTest.kt @@ -79,14 +79,14 @@ class RealAutofillRuntimeConfigProviderTest { } @Test - fun whenAutofillNotEnabledThenConfigurationUserPrefsCredentialsIsFalse() = runTest { + fun `getRuntimeConfiguration - autofill not enabled - is false`() = runTest { configureAutofillCapabilities(enabled = false) testee.getRuntimeConfiguration("", EXAMPLE_URL) verifyAutofillCredentialsReturnedAs(false) } @Test - fun whenAutofillEnabledThenConfigurationUserPrefsCredentialsIsTrue() = runTest { + fun `getRuntimeConfiguration - autofill enabled - is true`() = runTest { configureAutofillCapabilities(enabled = true) configureNoShareableLogins() testee.getRuntimeConfiguration("", EXAMPLE_URL) @@ -94,7 +94,7 @@ class RealAutofillRuntimeConfigProviderTest { } @Test - fun whenCanAutofillThenConfigSpecifiesShowingKeyIcon() = runTest { + fun `getRuntimeConfiguration - can autofill - shows key icon`() = runTest { configureAutofillCapabilities(enabled = true) configureAutofillAvailableForSite(EXAMPLE_URL) configureNoShareableLogins() @@ -103,7 +103,7 @@ class RealAutofillRuntimeConfigProviderTest { } @Test - fun whenNoCredentialsForUrlThenConfigurationInputTypeCredentialsIsFalse() = runTest { + fun `getRuntimeConfiguration - no credentials for url - configuration input type credentials is false`() = runTest { configureAutofillEnabledWithNoSavedCredentials(EXAMPLE_URL) testee.getRuntimeConfiguration("", EXAMPLE_URL) @@ -115,7 +115,7 @@ class RealAutofillRuntimeConfigProviderTest { } @Test - fun whenWithCredentialsForUrlThenConfigurationInputTypeCredentialsIsTrue() = runTest { + fun `getRuntimeConfiguration - with credentials for url - configuration input type credentials is true`() = runTest { configureAutofillCapabilities(enabled = true) whenever(autofillStore.getCredentials(EXAMPLE_URL)).thenReturn( listOf( @@ -139,7 +139,7 @@ class RealAutofillRuntimeConfigProviderTest { } @Test - fun whenWithShareableCredentialsForUrlThenConfigurationInputTypeCredentialsIsTrue() = runTest { + fun `getRuntimeConfiguration - with shareable credentials for url - configuration input type credentials is true`() = runTest { configureAutofillCapabilities(enabled = true) whenever(autofillStore.getCredentials(EXAMPLE_URL)).thenReturn(emptyList()) whenever(shareableCredentials.shareableCredentials(any())).thenReturn( @@ -163,7 +163,7 @@ class RealAutofillRuntimeConfigProviderTest { } @Test - fun whenWithUsernameOnlyForUrlThenConfigurationInputTypeCredentialsUsernameIsTrue() = runTest { + fun `getRuntimeConfiguration - with username only for url - configuration input type credentials username is true`() = runTest { val url = "example.com" configureAutofillCapabilities(enabled = true) whenever(autofillStore.getCredentials(url)).thenReturn( @@ -188,7 +188,7 @@ class RealAutofillRuntimeConfigProviderTest { } @Test - fun whenWithEmptyUsernameOnlyForUrlThenConfigurationInputTypeCredentialsUsernameIsFalse() = runTest { + fun `getRuntimeConfiguration - with empty username only for url - configuration input type credentials username is false`() = runTest { val url = "example.com" configureAutofillCapabilities(enabled = true) whenever(autofillStore.getCredentials(url)).thenReturn( @@ -213,7 +213,7 @@ class RealAutofillRuntimeConfigProviderTest { } @Test - fun whenWithPasswordOnlyForUrlThenConfigurationInputTypeCredentialsUsernameIsTrue() = runTest { + fun `getRuntimeConfiguration - with password only for url - username is true`() = runTest { val url = "example.com" configureAutofillCapabilities(enabled = true) whenever(autofillStore.getCredentials(url)).thenReturn( @@ -238,7 +238,7 @@ class RealAutofillRuntimeConfigProviderTest { } @Test - fun whenWithEmptyPasswordOnlyForUrlThenConfigurationInputTypeCredentialsUsernameIsTrue() = runTest { + fun `getRuntimeConfiguration - with empty password only for url - configuration input type credentials username is true`() = runTest { val url = "example.com" configureAutofillCapabilities(enabled = true) whenever(autofillStore.getCredentials(url)).thenReturn( @@ -263,7 +263,7 @@ class RealAutofillRuntimeConfigProviderTest { } @Test - fun whenWithCredentialsForUrlButAutofillDisabledThenConfigurationInputTypeCredentialsIsFalse() = runTest { + fun `getRuntimeConfiguration - with credentials for url but autofill disabled - configuration input type credentials is false`() = runTest { val url = "example.com" configureAutofillCapabilities(enabled = false) whenever(autofillStore.getCredentials(url)).thenReturn( @@ -287,7 +287,7 @@ class RealAutofillRuntimeConfigProviderTest { } @Test - fun whenWithCredentialsForUrlButAutofillUnavailableThenConfigurationInputTypeCredentialsIsFalse() = runTest { + fun `getRuntimeConfiguration - with credentials for url but autofill unavailable - configuration input type credentials is false`() = runTest { val url = "example.com" configureAutofillCapabilities(enabled = false) whenever(autofillStore.getCredentials(url)).thenReturn( @@ -311,7 +311,7 @@ class RealAutofillRuntimeConfigProviderTest { } @Test - fun whenEmailIsSignedInThenConfigurationInputTypeEmailIsTrue() = runTest { + fun `getRuntimeConfiguration - email signed in - configuration input type email is true`() = runTest { val url = "example.com" configureAutofillEnabledWithNoSavedCredentials(url) whenever(emailManager.isSignedIn()).thenReturn(true) @@ -325,7 +325,7 @@ class RealAutofillRuntimeConfigProviderTest { } @Test - fun whenEmailIsSignedOutThenConfigurationInputTypeEmailIsFalse() = runTest { + fun `getRuntimeConfiguration - email signed out - configuration input type email is false`() = runTest { val url = "example.com" configureAutofillEnabledWithNoSavedCredentials(url) whenever(emailManager.isSignedIn()).thenReturn(false) @@ -339,7 +339,7 @@ class RealAutofillRuntimeConfigProviderTest { } @Test - fun whenSiteNotInNeverSaveListThenCanSaveCredentials() = runTest { + fun `getRuntimeConfiguration - site not in never save list - can save credentials`() = runTest { val url = "example.com" configureAutofillEnabledWithNoSavedCredentials(url) testee.getRuntimeConfiguration("", url) @@ -347,7 +347,7 @@ class RealAutofillRuntimeConfigProviderTest { } @Test - fun whenSiteInNeverSaveListThenStillTellJsWeCanSaveCredentials() = runTest { + fun `getRuntimeConfiguration - site in never save list - can still save credentials`() = runTest { val url = "example.com" configureAutofillEnabledWithNoSavedCredentials(url) whenever(neverSavedSiteRepository.isInNeverSaveList(url)).thenReturn(true) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/configuration/RealRuntimeConfigurationWriterTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/configuration/RealRuntimeConfigurationWriterTest.kt index d228b54919fe..219ae351e3ae 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/configuration/RealRuntimeConfigurationWriterTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/configuration/RealRuntimeConfigurationWriterTest.kt @@ -25,7 +25,7 @@ class RealRuntimeConfigurationWriterTest { private val testee = RealRuntimeConfigurationWriter(Builder().build()) @Test - fun whenGenerateResponseGetAvailableInputTypesThenReturnAvailableInputTypesJson() { + fun `generateResponse - get available input types - return available input types json`() { val expectedJson = """ { "credentials": { @@ -46,7 +46,7 @@ class RealRuntimeConfigurationWriterTest { } @Test - fun whenGenerateContentScopeTheReturnContentScopeString() { + fun `generateContentScope - returns content scope string`() { val expectedJson = """ contentScope = { "features": { @@ -65,7 +65,7 @@ class RealRuntimeConfigurationWriterTest { } @Test - fun whenGenerateUserUnprotectedDomainsThenReturnUserUnprotectedDomainsString() { + fun `generateUserUnprotectedDomains - returns user unprotected domains string`() { val expectedJson = "userUnprotectedDomains = [];" assertEquals( expectedJson, @@ -74,7 +74,7 @@ class RealRuntimeConfigurationWriterTest { } @Test - fun whenGenerateUserPreferencesThenReturnUserPreferencesString() { + fun `generateUserPreferences - return user preferences string`() { val expectedJson = """ userPreferences = { "debug": false, diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deduper/RealAutofillLoginDeduplicatorTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deduper/RealAutofillLoginDeduplicatorTest.kt index 2e921f478ade..ec9f27be1fa5 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deduper/RealAutofillLoginDeduplicatorTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deduper/RealAutofillLoginDeduplicatorTest.kt @@ -22,13 +22,13 @@ class RealAutofillLoginDeduplicatorTest { ) @Test - fun whenEmptyListInThenEmptyListOut() = runTest { + fun `deduplicate - empty list in - empty list out`() = runTest { val result = testee.deduplicate("example.com", emptyList()) assertTrue(result.isEmpty()) } @Test - fun whenSingleEntryInThenSingleEntryReturned() { + fun `deduplicate - single entry in - single entry returned`() { val inputList = listOf( aLogin("domain", "username", "password"), ) @@ -37,7 +37,7 @@ class RealAutofillLoginDeduplicatorTest { } @Test - fun whenEntriesCompletelyUnrelatedThenNoDeduplication() { + fun `deduplicate - entries completely unrelated - no deduplication`() { val inputList = listOf( aLogin("domain_A", "username_A", "password_A"), aLogin("domain_B", "username_B", "password_B"), @@ -49,7 +49,7 @@ class RealAutofillLoginDeduplicatorTest { } @Test - fun whenEntriesShareUsernameAndPasswordButNotDomainThenDeduped() { + fun `deduplicate - entries share username and password but not domain - deduped`() { val inputList = listOf( aLogin("foo.com", "username", "password"), aLogin("bar.com", "username", "password"), @@ -59,7 +59,7 @@ class RealAutofillLoginDeduplicatorTest { } @Test - fun whenEntriesShareDomainAndUsernameButNotPasswordThenNoDeduplication() { + fun `deduplicate - entries share domain and username but not password - no deduplication`() { val inputList = listOf( aLogin("example.com", "username", "123"), aLogin("example.com", "username", "xyz"), @@ -71,7 +71,7 @@ class RealAutofillLoginDeduplicatorTest { } @Test - fun whenEntriesShareDomainAndPasswordButNotUsernameThenNoDeduplication() { + fun `deduplicate - entries share domain and password but not username - no deduplication`() { val inputList = listOf( aLogin("example.com", "user_A", "password"), aLogin("example.com", "user_B", "password"), @@ -83,7 +83,7 @@ class RealAutofillLoginDeduplicatorTest { } @Test - fun whenEntriesShareMultipleCredentialsWhichArePerfectDomainMatchesThenDeduped() { + fun `deduplicate - entries share multiple credentials which are perfect domain matches - deduped`() { val inputList = listOf( aLogin("example.com", "username", "password"), aLogin("example.com", "username", "password"), @@ -93,7 +93,7 @@ class RealAutofillLoginDeduplicatorTest { } @Test - fun whenEntriesShareMultipleCredentialsWhichArePartialDomainMatchesThenDeduped() { + fun `deduplicate - entries share multiple credentials which are partial domain matches - deduped`() { val inputList = listOf( aLogin("a.example.com", "username", "password"), aLogin("b.example.com", "username", "password"), @@ -103,7 +103,7 @@ class RealAutofillLoginDeduplicatorTest { } @Test - fun whenEntriesShareMultipleCredentialsWhichAreNotDomainMatchesThenDeduped() { + fun `deduplicate - entries share multiple credentials which are not domain matches - deduped`() { val inputList = listOf( aLogin("foo.com", "username", "password"), aLogin("bar.com", "username", "password"), @@ -113,7 +113,7 @@ class RealAutofillLoginDeduplicatorTest { } @Test - fun whenEntriesShareCredentialsAcrossPerfectAndPartialMatchesThenDedupedToPerfectMatch() { + fun `deduplicate - entries share credentials across perfect and partial matches - deduped to perfect match`() { val inputList = listOf( aLogin("example.com", "username", "password"), aLogin("a.example.com", "username", "password"), @@ -124,7 +124,7 @@ class RealAutofillLoginDeduplicatorTest { } @Test - fun whenEntriesShareCredentialsAcrossPerfectAndNonDomainMatchesThenDedupedToPerfectMatch() { + fun `deduplicate - entries share credentials across perfect and non-domain matches - deduped to perfect match`() { val inputList = listOf( aLogin("example.com", "username", "password"), aLogin("bar.com", "username", "password"), @@ -135,7 +135,7 @@ class RealAutofillLoginDeduplicatorTest { } @Test - fun whenEntriesShareCredentialsAcrossPartialAndNonDomainMatchesThenDedupedToPerfectMatch() { + fun `deduplicate - entries share credentials across partial and non-domain matches - deduped to perfect match`() { val inputList = listOf( aLogin("a.example.com", "username", "password"), aLogin("bar.com", "username", "password"), @@ -146,7 +146,7 @@ class RealAutofillLoginDeduplicatorTest { } @Test - fun whenEntriesShareCredentialsAcrossPerfectAndPartialAndNonDomainMatchesThenDedupedToPerfectMatch() { + fun `deduplicate - entries share credentials across perfect and partial and non domain matches - deduped to perfect match`() { val inputList = listOf( aLogin("a.example.com", "username", "password"), aLogin("example.com", "username", "password"), diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deduper/RealAutofillMatchTypeDetectorTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deduper/RealAutofillMatchTypeDetectorTest.kt index 19a35dcb698c..e75703a38d29 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deduper/RealAutofillMatchTypeDetectorTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deduper/RealAutofillMatchTypeDetectorTest.kt @@ -14,31 +14,31 @@ class RealAutofillMatchTypeDetectorTest { private val testee = RealAutofillDeduplicationMatchTypeDetector(AutofillDomainNameUrlMatcher(TestUrlUnicodeNormalizer())) @Test - fun whenExactUrlMatchThenTypeIsPerfectMatch() { + fun `detectMatchType - exact url match - perfect match`() { val result = testee.detectMatchType("example.com", creds("example.com")) result.assertIsPerfectMatch() } @Test - fun whenSubdomainMatchOnSavedSiteThenTypeIsPartialMatch() { + fun `detectMatchType - subdomain match on saved site - partial match`() { val result = testee.detectMatchType("example.com", creds("subdomain.example.com")) result.assertIsPartialMatch() } @Test - fun whenSubdomainMatchOnVisitedSiteThenTypeIsPartialMatch() { + fun `detectMatchType - subdomain match on visited site - partial match`() { val result = testee.detectMatchType("subdomain.example.com", creds("example.com")) result.assertIsPartialMatch() } @Test - fun whenSubdomainMatchOnBothVisitedAndSavedSiteThenTypeIsPerfectMatch() { + fun `detectMatchType - subdomain match on both visited and saved site - perfect match`() { val result = testee.detectMatchType("subdomain.example.com", creds("subdomain.example.com")) result.assertIsPerfectMatch() } @Test - fun whenNoETldPlusOneMatchNotAMatch() { + fun `detectMatchType - no ETLD plus one match not a match - not a match`() { val result = testee.detectMatchType("foo.com", creds("example.com")) result.assertNotAMatch() } diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deduper/RealLoginDeduplicatorBestMatchFinderTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deduper/RealLoginDeduplicatorBestMatchFinderTest.kt index 8d7495c1096b..6ab9b3df6fd8 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deduper/RealLoginDeduplicatorBestMatchFinderTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deduper/RealLoginDeduplicatorBestMatchFinderTest.kt @@ -19,12 +19,12 @@ class RealLoginDeduplicatorBestMatchFinderTest { ) @Test - fun whenEmptyListThenNoBestMatchFound() { + fun `findBestMatch - empty list - no best match found`() { assertNull(testee.findBestMatch("", emptyList())) } @Test - fun whenSinglePerfectMatchThenThatIsReturnedAsBestMatch() { + fun `findBestMatch - single perfect match - that is returned as best match`() { val input = listOf( LoginCredentials(id = 0, domain = "example.com", username = "username", password = "password"), ) @@ -33,7 +33,7 @@ class RealLoginDeduplicatorBestMatchFinderTest { } @Test - fun whenMultiplePerfectMatchesMostRecentlyModifiedIsReturned() { + fun `findBestMatch - multiple perfect matches most recently modified is returned`() { val input = listOf( creds("example.com", 1000), creds("example.com", 2000), @@ -43,7 +43,7 @@ class RealLoginDeduplicatorBestMatchFinderTest { } @Test - fun whenMultiplePartialMatchesWithSameTimestampThenDomainAlphabeticallyFirstReturned() { + fun `findBestMatch - multiple partial matches with same timestamp - domain alphabetically first returned`() { val input = listOf( creds("a.example.com", 2000), creds("b.example.com", 2000), @@ -53,7 +53,7 @@ class RealLoginDeduplicatorBestMatchFinderTest { } @Test - fun whenSingleNonMatchThenReturnedAsBestMatch() { + fun `findBestMatch - single non match - returned as best match`() { val input = listOf( creds("not-a-match.com", 2000), ) @@ -62,7 +62,7 @@ class RealLoginDeduplicatorBestMatchFinderTest { } @Test - fun whenMultipleNonMatchesThenMostRecentlyModifiedIsReturned() { + fun `findBestMatch - multiple non matches - most recently modified is returned`() { val input = listOf( creds("not-a-match.com", 2000), creds("also-not-a-match.com", 1000), @@ -72,7 +72,7 @@ class RealLoginDeduplicatorBestMatchFinderTest { } @Test - fun whenMatchesFromAllTypesThenMatchInPerfectReturnedRegardlessOfTimestamps() { + fun `findBestMatch - matches from all types - match in perfect returned regardless of timestamps`() { val input = listOf( creds("perfect-match.com", 1000), creds("imperfect-match.com", 3000), diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deduper/RealLoginDeduplicatorUsernameAndPasswordMatcherTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deduper/RealLoginDeduplicatorUsernameAndPasswordMatcherTest.kt index 08ec6cf0d8f2..9d4625139f44 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deduper/RealLoginDeduplicatorUsernameAndPasswordMatcherTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deduper/RealLoginDeduplicatorUsernameAndPasswordMatcherTest.kt @@ -8,14 +8,14 @@ class RealLoginDeduplicatorUsernameAndPasswordMatcherTest { private val testee = RealAutofillDeduplicationUsernameAndPasswordMatcher() @Test - fun whenEmptyListInThenEmptyListOut() { + fun `groupDuplicateCredentials - empty list in - empty list out`() { val input = emptyList() val output = testee.groupDuplicateCredentials(input) assertTrue(output.isEmpty()) } @Test - fun whenSingleEntryInThenSingleEntryOut() { + fun `groupDuplicateCredentials - single entry in - single entry out`() { val input = listOf( creds("username", "password"), ) @@ -24,7 +24,7 @@ class RealLoginDeduplicatorUsernameAndPasswordMatcherTest { } @Test - fun whenMultipleEntriesWithNoDuplicationAtAllThenNumberOfGroupsReturnedMatchesNumberOfEntriesInputted() { + fun `groupDuplicateCredentials - no duplication at all - matches number of entries inputted`() { val input = listOf( creds("username_a", "password_x"), creds("username_b", "password_y"), @@ -35,7 +35,7 @@ class RealLoginDeduplicatorUsernameAndPasswordMatcherTest { } @Test - fun whenEntriesMatchOnUsernameButNotPasswordThenNotGrouped() { + fun `groupDuplicateCredentials - entries match on username but not password - not grouped`() { val input = listOf( creds("username", "password_x"), creds("username", "password_y"), @@ -45,7 +45,7 @@ class RealLoginDeduplicatorUsernameAndPasswordMatcherTest { } @Test - fun whenEntriesMatchOnPasswordButNotUsernameThenNotGrouped() { + fun `groupDuplicateCredentials - entries match on password but not username - not grouped`() { val input = listOf( creds("username_a", "password"), creds("username_b", "password"), @@ -55,7 +55,7 @@ class RealLoginDeduplicatorUsernameAndPasswordMatcherTest { } @Test - fun whenEntriesMatchOnUsernameAndPasswordThenGrouped() { + fun `groupDuplicateCredentials - entries match on username and password - grouped`() { val input = listOf( creds("username", "password"), creds("username", "password"), diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deduper/RealLoginSorterForDeduplicationTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deduper/RealLoginSorterForDeduplicationTest.kt index 6d436ade1f48..5b2018a89f1c 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deduper/RealLoginSorterForDeduplicationTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deduper/RealLoginSorterForDeduplicationTest.kt @@ -9,63 +9,63 @@ class RealLoginSorterForDeduplicationTest { private val testee = AutofillDeduplicationLoginComparator() @Test - fun whenFirstLoginIsNewerThenReturnNegative() { + fun `compare - first login newer - return negative`() { val login1 = creds(lastUpdated = 2000, domain = null) val login2 = creds(lastUpdated = 1000, domain = null) assertTrue(testee.compare(login1, login2) < 0) } @Test - fun whenSecondLoginIsNewerThenReturnPositive() { + fun `compare - second login newer - return positive`() { val login1 = creds(lastUpdated = 1000, domain = null) val login2 = creds(lastUpdated = 2000, domain = null) assertTrue(testee.compare(login1, login2) > 0) } @Test - fun whenFirstLoginHasNoLastModifiedTimestampThenReturnsNegative() { + fun `compare - first login has no last modified timestamp - returns negative`() { val login1 = creds(lastUpdated = null, domain = null) val login2 = creds(lastUpdated = 2000, domain = null) assertTrue(testee.compare(login1, login2) < 0) } @Test - fun whenSecondLoginHasNoLastModifiedTimestampThenReturnsPositive() { + fun `compare - second login has no last modified timestamp - returns positive`() { val login1 = creds(lastUpdated = 1000, domain = null) val login2 = creds(lastUpdated = null, domain = null) assertTrue(testee.compare(login1, login2) > 0) } @Test - fun whenLastModifiedTimesEqualAndFirstLoginDomainShouldBeSortedFirstThenReturnsNegative() { + fun `compare - last modified times equal and first login domain should be sorted first then returns negative`() { val login1 = creds(lastUpdated = 1000, domain = "example.com") val login2 = creds(lastUpdated = 1000, domain = "site.com") assertTrue(testee.compare(login1, login2) < 0) } @Test - fun whenLastModifiedTimesEqualAndSecondLoginDomainShouldBeSortedFirstThenReturnsNegative() { + fun `compare - last modified times equal and second login domain should be sorted first - returns negative`() { val login1 = creds(lastUpdated = 1000, domain = "site.com") val login2 = creds(lastUpdated = 1000, domain = "example.com") assertTrue(testee.compare(login1, login2) > 0) } @Test - fun whenLastModifiedTimesEqualAndDomainsEqualThenReturns0() { + fun `compare - last modified times equal and domains equal - returns 0`() { val login1 = creds(lastUpdated = 1000, domain = "example.com") val login2 = creds(lastUpdated = 1000, domain = "example.com") assertEquals(0, testee.compare(login1, login2)) } @Test - fun whenLastModifiedDatesMissingAndDomainMissingThenReturns0() { + fun `compare - last modified dates missing and domain missing - returns 0`() { val login1 = creds(lastUpdated = null, domain = null) val login2 = creds(lastUpdated = null, domain = null) assertEquals(0, testee.compare(login1, login2)) } @Test - fun whenLoginsSameLastUpdatedTimeThenReturn0() { + fun `compare - logins same last updated time - return 0`() { val login1 = creds(lastUpdated = 1000, domain = null) val login2 = creds(lastUpdated = 1000, domain = null) assertEquals(0, testee.compare(login1, login2)) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deviceauth/AutofillTimeBasedAuthorizationGracePeriodTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deviceauth/AutofillTimeBasedAuthorizationGracePeriodTest.kt index acc7c025f9fe..5676c93b861c 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deviceauth/AutofillTimeBasedAuthorizationGracePeriodTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deviceauth/AutofillTimeBasedAuthorizationGracePeriodTest.kt @@ -28,26 +28,26 @@ class AutofillTimeBasedAuthorizationGracePeriodTest { private val testee = AutofillTimeBasedAuthorizationGracePeriod(timeProvider) @Test - fun whenNoInteractionsThenAuthRequired() { + fun `isAuthRequired - no interactions - auth required`() { assertTrue(testee.isAuthRequired()) } @Test - fun whenLastSuccessfulAuthWasBeforeGracePeriodThenAuthRequired() { + fun `isAuthRequired - last successful auth before grace period - auth required`() { recordAuthorizationInDistantPast() timeProvider.reset() assertTrue(testee.isAuthRequired()) } @Test - fun whenLastSuccessfulAuthWasWithinGracePeriodThenAuthNotRequired() { + fun `isAuthRequired - last successful auth within grace period - not required`() { recordAuthorizationWithinGracePeriod() timeProvider.reset() assertFalse(testee.isAuthRequired()) } @Test - fun whenLastSuccessfulAuthWasWithinGracePeriodButInvalidatedThenAuthRequired() { + fun `whenLastSuccessfulAuthWasWithinGracePeriodButInvalidated - auth required`() { recordAuthorizationWithinGracePeriod() timeProvider.reset() testee.invalidate() diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deviceauth/RealDeviceAuthenticatorTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deviceauth/RealDeviceAuthenticatorTest.kt index 5071aea409ce..3e54120aeeef 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deviceauth/RealDeviceAuthenticatorTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/deviceauth/RealDeviceAuthenticatorTest.kt @@ -65,7 +65,7 @@ class RealDeviceAuthenticatorTest { } @Test - fun whenSdkIs28ThenValidAuthenticationShouldCheckLegacy() { + fun `hasValidDeviceAuthentication - sdk 28 - checks legacy authentication`() { whenever(appBuildConfig.sdkInt).thenReturn(28) testee.hasValidDeviceAuthentication() @@ -74,7 +74,7 @@ class RealDeviceAuthenticatorTest { } @Test - fun whenSdkIs29ThenValidAuthenticationShouldCheckLegacy() { + fun `hasValidDeviceAuthentication - sdk 29 - checks legacy authentication`() { whenever(appBuildConfig.sdkInt).thenReturn(29) testee.hasValidDeviceAuthentication() @@ -83,7 +83,7 @@ class RealDeviceAuthenticatorTest { } @Test - fun whenSdkIsNot28Or29ThenValidAuthenticationShouldCheckLegacy() { + fun `hasValidDeviceAuthentication - sdk not 28 or 29 - checks legacy`() { whenever(appBuildConfig.sdkInt).thenReturn(30) testee.hasValidDeviceAuthentication() @@ -92,13 +92,13 @@ class RealDeviceAuthenticatorTest { } @Test - fun whenAuthenticateToAccessCredentialsIsCalledWithFragmentThenLaunchAuthLauncher() { + fun `authenticate - fragment - launch auth launcher`() { testee.authenticate(fragment) {} verifyAuthDialogLaunched() } @Test - fun whenAuthenticateToAccessCredentialsIsCalledWithActivityThenLaunchAuthLauncher() { + fun `authenticate - activity - launch auth launcher`() { testee.authenticate(fragment) {} verifyAuthDialogLaunched() } @@ -113,7 +113,7 @@ class RealDeviceAuthenticatorTest { } @Test - fun whenAuthGracePeriodActiveThenNoDeviceAuthLaunchedWhenAccessingCredentials() { + fun `authenticate - auth grace period active - no device auth launched`() { whenever(autofillAuthorizationGracePeriod.isAuthRequired()).thenReturn(false) testee.authenticate(fragmentActivity) {} verifyAuthNotLaunched() diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/email/EmailProtectionInContextSignupViewModelTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/email/EmailProtectionInContextSignupViewModelTest.kt index 6e0812da7e7d..a5bd2bd6987c 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/email/EmailProtectionInContextSignupViewModelTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/email/EmailProtectionInContextSignupViewModelTest.kt @@ -30,7 +30,7 @@ class EmailProtectionInContextSignupViewModelTest { private val testee = EmailProtectionInContextSignupViewModel(pixel = pixel) @Test - fun whenInitialStateThenCanExitWithoutConfirmation() = runTest { + fun `whenInitialState - view state can exit without confirmation`() = runTest { testee.viewState.test { (awaitItem() as ShowingWebContent).verifyCanExitWithoutConfirmation() cancelAndConsumeRemainingEvents() @@ -38,7 +38,7 @@ class EmailProtectionInContextSignupViewModelTest { } @Test - fun whenInitialStateThenCanNavigateBackwards() = runTest { + fun `whenInitialState - can navigate backwards`() = runTest { testee.viewState.test { assertTrue((awaitItem() as ShowingWebContent).urlActions.backButton == NavigateBack) cancelAndConsumeRemainingEvents() @@ -46,7 +46,7 @@ class EmailProtectionInContextSignupViewModelTest { } @Test - fun whenBackButtonPressedAndWebViewCannotGoBackThenCancelInContextSignUpState() = runTest { + fun `onBackButtonPressed - view state cancelled in context sign up`() = runTest { testee.onBackButtonPressed("", false) testee.viewState.test { awaitItem() as CancellingInContextSignUp @@ -55,7 +55,7 @@ class EmailProtectionInContextSignupViewModelTest { } @Test - fun whenUrlNotKnownAndBackButtonPressedThenDefaultBackActionTaken() = runTest { + fun `onBackButtonPressed - view state updated - default back action taken`() = runTest { testee.onBackButtonPressed("", true) testee.viewState.test { awaitItem() as NavigatingBack @@ -64,7 +64,7 @@ class EmailProtectionInContextSignupViewModelTest { } @Test - fun whenPageFinishedIsUnknownUrlThenDefaultExitActionTaken() = runTest { + fun `onPageFinished - unknown url - default exit action taken`() = runTest { testee.onPageFinished(UNKNOWN_URL) testee.viewState.test { (awaitItem() as ShowingWebContent).verifyCanExitWithoutConfirmation() @@ -73,7 +73,7 @@ class EmailProtectionInContextSignupViewModelTest { } @Test - fun whenBackButtonPressedWebViewCanGoBackAndUrlInAllowableBackListThenNavigateBackState() = runTest { + fun `onBackButtonPressed - webView can go back and url in allowable back list then navigate back state`() = runTest { testee.onBackButtonPressed(URL_IN_ALLOWED_BACK_NAVIGATION_LIST, true) testee.viewState.test { awaitItem() as NavigatingBack @@ -82,7 +82,7 @@ class EmailProtectionInContextSignupViewModelTest { } @Test - fun whenBackNavigationConsumedThenStateReturnsToViewingWebContent() = runTest { + fun `onBackButtonPressed - state returns to viewing web content`() = runTest { testee.onBackButtonPressed(URL_IN_ALLOWED_BACK_NAVIGATION_LIST, true) testee.viewState.test { awaitItem() as NavigatingBack @@ -95,7 +95,7 @@ class EmailProtectionInContextSignupViewModelTest { } @Test - fun whenPageFinishedIsUrlOnAllowedBackListThenCanExitWithoutConfirmation() = runTest { + fun `onPageFinished - view state updated - can exit without confirmation`() = runTest { testee.onPageFinished(URL_IN_ALLOWED_BACK_NAVIGATION_LIST) testee.viewState.test { (awaitItem() as ShowingWebContent).verifyCanExitWithoutConfirmation() @@ -104,7 +104,7 @@ class EmailProtectionInContextSignupViewModelTest { } @Test - fun whenPageFinishedIsUrlThatRequiresExitConfirmationThenConfirmationRequired() = runTest { + fun `onPageFinished - view state updated - confirmation required`() = runTest { testee.onPageFinished(URL_REQUIRES_EXIT_CONFIRMATION) testee.viewState.test { (awaitItem() as ShowingWebContent).verifyCanExitWithConfirmation() @@ -113,7 +113,7 @@ class EmailProtectionInContextSignupViewModelTest { } @Test - fun whenUrlIsLandingPageAndNotSignedInThenDoesNotExit() = runTest { + fun `signedInStateUpdated - not signed in - does not exit`() = runTest { testee.signedInStateUpdated(signedIn = false, url = "https://duckduckgo.com/email/") testee.viewState.test { assertTrue(awaitItem() is ShowingWebContent) @@ -122,25 +122,25 @@ class EmailProtectionInContextSignupViewModelTest { } @Test - fun whenUserCancelsEarlyExitThenPixelFired() { + fun `onUserDecidedNotToCancel - pixel fired`() { testee.onUserDecidedNotToCancelInContextSignUp() verify(pixel).fire(EMAIL_PROTECTION_IN_CONTEXT_MODAL_EXIT_EARLY_CANCEL) } @Test - fun whenUserConfirmsEarlyExitThenPixelFired() { + fun `onUserConfirmedCancellation - pixel fired`() { testee.onUserConfirmedCancellationOfInContextSignUp() verify(pixel).fire(EMAIL_PROTECTION_IN_CONTEXT_MODAL_EXIT_EARLY_CONFIRM) } @Test - fun whenUserCancelsWithoutConfirmationThenPixelFired() { + fun `userCancelledSignup - without confirmation - pixel fired`() { testee.userCancelledSignupWithoutConfirmation() verify(pixel).fire(EMAIL_PROTECTION_IN_CONTEXT_MODAL_DISMISSED) } @Test - fun whenUserCancelsWithoutConfirmationThenCancellationViewStateSent() = runTest { + fun `userCancelledSignup - view state sent - cancellation view state sent`() = runTest { testee.userCancelledSignupWithoutConfirmation() testee.viewState.test { assertTrue(awaitItem() is CancellingInContextSignUp) @@ -149,7 +149,7 @@ class EmailProtectionInContextSignupViewModelTest { } @Test - fun whenLoadedStartingUrlThenPixelFired() { + fun `loadedStartingUrl - pixel fired`() { testee.loadedStartingUrl() verify(pixel).fire(EMAIL_PROTECTION_IN_CONTEXT_MODAL_DISPLAYED) } diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/email/ResultHandlerEmailProtectionChooseEmailTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/email/ResultHandlerEmailProtectionChooseEmailTest.kt index 0215dda1f3db..6babd86250bd 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/email/ResultHandlerEmailProtectionChooseEmailTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/email/ResultHandlerEmailProtectionChooseEmailTest.kt @@ -73,56 +73,56 @@ class ResultHandlerEmailProtectionChooseEmailTest { } @Test - fun whenUserSelectedToUsePersonalAddressThenCorrectCallbackInvoked() = runTest { + fun `processResult - user selected personal address - correct callback invoked`() = runTest { val bundle = bundle(result = UsePersonalEmailAddress) testee.processResult(bundle, context, "tab-id-123", Fragment(), callback) verify(callback).onUseEmailProtectionPersonalAddress(any(), any()) } @Test - fun whenUserSelectedToUsePrivateAliasAddressThenCorrectCallbackInvoked() = runTest { + fun `processResult - user selected private alias address - correct callback invoked`() = runTest { val bundle = bundle(result = UsePrivateAliasAddress) testee.processResult(bundle, context, "tab-id-123", Fragment(), callback) verify(callback).onUseEmailProtectionPrivateAlias(any(), any()) } @Test - fun whenUrlMissingFromBundleThenExceptionThrown() = runTest { + fun `processResult - url missing from bundle - exception thrown`() = runTest { val bundle = bundle(url = null, result = UsePersonalEmailAddress) testee.processResult(bundle, context, "tab-id-123", Fragment(), callback) verifyNoInteractions(callback) } @Test - fun whenResultTypeMissingFromBundleThenExceptionThrown() = runTest { + fun `processResult - result type missing from bundle - exception thrown`() = runTest { val bundle = bundle(result = null) testee.processResult(bundle, context, "tab-id-123", Fragment(), callback) verifyNoInteractions(callback) } @Test - fun whenUserSelectedToUsePrivateAliasAddressThenSetNewLastUsedDateCalled() = runTest { + fun `processResult - user selected private alias address - set new last used date called`() = runTest { val bundle = bundle(result = UsePrivateAliasAddress) testee.processResult(bundle, context, "tab-id-123", Fragment(), callback) verify(emailManager).setNewLastUsedDate() } @Test - fun whenUserSelectedToUsePersonalDuckAddressThenSetNewLastUsedDateCalled() = runTest { + fun `processResult - user selected personal duck address - set new last used date called`() = runTest { val bundle = bundle(result = UsePersonalEmailAddress) testee.processResult(bundle, context, "tab-id-123", Fragment(), callback) verify(emailManager).setNewLastUsedDate() } @Test - fun whenUserSelectedNotToUseEmailProtectionThenPixelSent() = runTest { + fun `processResult - user selected not to use email protection - pixel sent`() = runTest { val bundle = bundle(result = DoNotUseEmailProtection) testee.processResult(bundle, context, "tab-id-123", Fragment(), callback) verify(pixel).enqueueFire(EMAIL_TOOLTIP_DISMISSED, mapOf(COHORT to "cohort")) } @Test - fun whenUserSelectedToUsePersonalDuckAddressThenPixelSent() = runTest { + fun `processResult - user selected personal duck address - pixel sent`() = runTest { val bundle = bundle(result = UsePersonalEmailAddress) testee.processResult(bundle, context, "tab-id-123", Fragment(), callback) verify(pixel).enqueueFire( @@ -132,7 +132,7 @@ class ResultHandlerEmailProtectionChooseEmailTest { } @Test - fun whenUserSelectedToUsePrivateAliasThenPixelSent() = runTest { + fun `processResult - user selected private alias - pixel sent`() = runTest { val bundle = bundle(result = UsePrivateAliasAddress) testee.processResult(bundle, context, "tab-id-123", Fragment(), callback) verify(pixel).enqueueFire( diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/email/incontext/availability/RealEmailProtectionInContextAvailabilityRulesTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/email/incontext/availability/RealEmailProtectionInContextAvailabilityRulesTest.kt index 5829452c0b14..40cb89b639de 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/email/incontext/availability/RealEmailProtectionInContextAvailabilityRulesTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/email/incontext/availability/RealEmailProtectionInContextAvailabilityRulesTest.kt @@ -58,37 +58,37 @@ class RealEmailProtectionInContextAvailabilityRulesTest { } @Test - fun whenLocaleNotEnglishThenNotPermitted() = runTest { + fun `configureNonEnglishLocale - permitted - not permitted`() = runTest { configureNonEnglishLocale() assertFalse(testee.permittedToShow(ALLOWED_URL)) } @Test - fun whenInstalledALongTimeAgoThenNotPermitted() = runTest { + fun `whenInstalledALongTimeAgo - not permitted`() = runTest { configureAsNotRecentInstall() assertFalse(testee.permittedToShow(ALLOWED_URL)) } @Test - fun whenInstalledRecentlyThenPermitted() = runTest { + fun `configureAsRecentInstall - permitted - shows allowed URL`() = runTest { configureAsRecentInstall() assertTrue(testee.permittedToShow(ALLOWED_URL)) } @Test - fun whenSecureAutofillUnavailableThenNotPermitted() = runTest { + fun `isSecureAutofillAvailable - not permitted`() = runTest { whenever(autofillGlobalCapabilityChecker.isSecureAutofillAvailable()).thenReturn(false) assertFalse(testee.permittedToShow(ALLOWED_URL)) } @Test - fun whenFeatureDisabledInRemoteConfigThenNotPermitted() = runTest { + fun `whenFeatureDisabledInRemoteConfigThenNotPermitted - remote config feature disabled - not permitted`() = runTest { emailProtectionInContextSignupFeature.enabled = false assertFalse(testee.permittedToShow(ALLOWED_URL)) } @Test - fun whenUrlOnExceptionListThenNotPermitted() = runTest { + fun `isPermitted - url on exception list - not permitted`() = runTest { assertFalse(testee.permittedToShow(DISALLOWED_URL)) } diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/email/incontext/availability/RealEmailProtectionInContextRecentInstallCheckerTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/email/incontext/availability/RealEmailProtectionInContextRecentInstallCheckerTest.kt index d2a8dbbb9693..d5ce03b69130 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/email/incontext/availability/RealEmailProtectionInContextRecentInstallCheckerTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/email/incontext/availability/RealEmailProtectionInContextRecentInstallCheckerTest.kt @@ -21,25 +21,25 @@ class RealEmailProtectionInContextRecentInstallCheckerTest { private val testee = RealEmailProtectionInContextRecentInstallChecker(userBrowserProperties, dataStore, coroutineTestRule.testDispatcherProvider) @Test - fun whenInstalledForLessTimeThanMaxDaysAllowsIsRecentInstall() = runTest { + fun `isRecentInstall - installed for less time than max days - is recent install`() = runTest { configureInstallationDaysLessThanMaximum() assertTrue(testee.isRecentInstall()) } @Test - fun whenInstalledForSameTimeAsMaxDaysAllowsThenIsRecentInstall() = runTest { + fun `isRecentInstall - installed for same time as max days allows`() = runTest { configureInstallationDayToMatchMaximum() assertTrue(testee.isRecentInstall()) } @Test - fun whenInstalledForMoreTimeThanMaxDaysAllowsThenIsRecentInstall() = runTest { + fun `isRecentInstall - installed for more time than max days allows - not recent install`() = runTest { configureInstallationDaysMoreThanMaximum() assertFalse(testee.isRecentInstall()) } @Test - fun whenInstallRulesMissingThenNotPermitted() = runTest { + fun `isRecentInstall - install rules missing - not permitted`() = runTest { configureMaxInstallDaysRuleNotSet() assertFalse(testee.isRecentInstall()) } diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/email/incontext/prompt/EmailProtectionInContextSignUpPromptViewModelTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/email/incontext/prompt/EmailProtectionInContextSignUpPromptViewModelTest.kt index 18df7e153a0a..f89adf3280e5 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/email/incontext/prompt/EmailProtectionInContextSignUpPromptViewModelTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/email/incontext/prompt/EmailProtectionInContextSignUpPromptViewModelTest.kt @@ -29,13 +29,13 @@ class EmailProtectionInContextSignUpPromptViewModelTest { ) @Test - fun whenUserPressesToProtectEmailThenCorrectPixelSent() { + fun `onProtectEmailButtonPressed - pixel sent`() { testee.onProtectEmailButtonPressed() verify(pixel).fire(EMAIL_PROTECTION_IN_CONTEXT_PROMPT_CONFIRMED) } @Test - fun whenUserPressesToProtectEmailThenCorrectResultTypeReturned() = runTest { + fun `onProtectEmailButtonPressed - commands returned - sign up result`() = runTest { testee.onProtectEmailButtonPressed() testee.commands.test { assertTrue((awaitItem() as FinishWithResult).result is SignUp) @@ -44,13 +44,13 @@ class EmailProtectionInContextSignUpPromptViewModelTest { } @Test - fun whenUserPressesToDismissPromptThenCorrectPixelSent() { + fun `onCloseButtonPressed - pixel sent - email protection in context prompt dismissed`() { testee.onCloseButtonPressed() verify(pixel).fire(EMAIL_PROTECTION_IN_CONTEXT_PROMPT_DISMISSED) } @Test - fun whenUserPressesToDismissPromptThenCorrectResultTypeReturned() = runTest { + fun `onCloseButtonPressed - commands returned - cancel result`() = runTest { testee.onCloseButtonPressed() testee.commands.test { assertTrue((awaitItem() as FinishWithResult).result is Cancel) @@ -59,13 +59,13 @@ class EmailProtectionInContextSignUpPromptViewModelTest { } @Test - fun whenUserPressesToDismissPromptPermanentlyThenCorrectPixelSent() { + fun `onDoNotShowAgainButtonPressed - pixel sent`() { testee.onDoNotShowAgainButtonPressed() verify(pixel).fire(EMAIL_PROTECTION_IN_CONTEXT_PROMPT_NEVER_AGAIN) } @Test - fun whenUserPressesToDismissPromptPermanentlyThenCorrectResultTypeReturned() = runTest { + fun `onDoNotShowAgainButtonPressed - commands returned - do not show again`() = runTest { testee.onDoNotShowAgainButtonPressed() testee.commands.test { assertTrue((awaitItem() as FinishWithResult).result is DoNotShowAgain) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/email/incontext/verifier/RealEmailProtectionLinkVerifierTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/email/incontext/verifier/RealEmailProtectionLinkVerifierTest.kt index 36c0f0ebc151..81c8bd19ab33 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/email/incontext/verifier/RealEmailProtectionLinkVerifierTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/email/incontext/verifier/RealEmailProtectionLinkVerifierTest.kt @@ -7,27 +7,27 @@ class RealEmailProtectionLinkVerifierTest { private val testee = RealEmailProtectionLinkVerifier() @Test - fun whenUrlIsNullThenDoNotConsumeLink() { + fun `testUrl - url is null - do not consume link`() { assertFalse(null.testUrl()) } @Test - fun whenUrlDoesNotContainVerificationLinkThenDoNotConsumeLink() { + fun `testUrl - does not contain verification link - do not consume link`() { assertFalse(NOT_VERIFICATION_URL.testUrl()) } @Test - fun whenUrlBeginsWithVerificationLinkThenConsumeLink() { + fun `testUrl - url begins with verification link - consumes link`() { assertTrue(VERIFICATION_URL.testUrl()) } @Test - fun whenUrlContainsVerificationLinkThenConsumeLink() { + fun `testUrl - contains verification link - consumes link`() { assertTrue(VERIFICATION_PREPENDED_WITH_ANOTHER_DOMAIN.testUrl()) } @Test - fun whenInContextViewNotShowingThenNeverConsumeLink() { + fun `shouldDelegateToInContextView - not showing - never consume link`() { assertFalse(testee.shouldDelegateToInContextView(VERIFICATION_URL, inContextViewAlreadyShowing = false)) assertFalse(testee.shouldDelegateToInContextView(VERIFICATION_PREPENDED_WITH_ANOTHER_DOMAIN, inContextViewAlreadyShowing = false)) assertFalse(testee.shouldDelegateToInContextView(NOT_VERIFICATION_URL, inContextViewAlreadyShowing = false)) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/encoding/UrlUnicodeNormalizerImplTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/encoding/UrlUnicodeNormalizerImplTest.kt index b133cc7c16e6..56a3a4ee5745 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/encoding/UrlUnicodeNormalizerImplTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/encoding/UrlUnicodeNormalizerImplTest.kt @@ -27,22 +27,22 @@ class UrlUnicodeNormalizerImplTest { private val testee = UrlUnicodeNormalizerImpl() @Test - fun whenNormalizingToAsciiAndContainsNonAsciiThenOutputIdnaEncoded() { + fun `normalizeAscii - contains non-ascii - idna encoded`() { assertEquals("xn--7ca.com", testee.normalizeAscii("ç.com")) } @Test - fun whenNormalizingToAsciiAndOnlyContainsAsciiThenThenInputAndOutputIdentical() { + fun `normalizeAscii - ascii only - identical input and output`() { assertEquals("c.com", testee.normalizeAscii("c.com")) } @Test - fun whenNormalizingToUnicodeAndContainsNonAsciiThenOutputContainsNonAscii() { + fun `normalizeUnicode - contains non-ascii - output contains non-ascii`() { assertEquals("ç.com", testee.normalizeUnicode("xn--7ca.com")) } @Test - fun whenNormalizingToUnicodeAndOnlyContainsAsciiThenThenInputAndOutputIdentical() { + fun `normalizeUnicode - only contains ascii - identical`() { assertEquals("c.com", testee.normalizeUnicode("c.com")) } } diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/engagement/EngagementPasswordAddedListenerTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/engagement/EngagementPasswordAddedListenerTest.kt index 360fd1646832..4c0bc5aa78e3 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/engagement/EngagementPasswordAddedListenerTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/engagement/EngagementPasswordAddedListenerTest.kt @@ -28,21 +28,21 @@ class EngagementPasswordAddedListenerTest { ) @Test - fun whenDaysInstalledLessThan7ThenPixelSent() { + fun `onCredentialAdded - days installed less than 7 - pixel sent`() { whenever(userBrowserProperties.daysSinceInstalled()).thenReturn(0) testee.onCredentialAdded(0) verifyPixelSent() } @Test - fun whenDaysInstalledExactly7ThenPixelNotSent() { + fun `onCredentialAdded - days installed exactly 7 - pixel not sent`() { whenever(userBrowserProperties.daysSinceInstalled()).thenReturn(7) testee.onCredentialAdded(0) verifyPixelNotSent() } @Test - fun whenDaysInstalledAbove7ThenPixelNotSent() { + fun `onCredentialAdded - days installed above 7 - pixel not sent`() { whenever(userBrowserProperties.daysSinceInstalled()).thenReturn(10) testee.onCredentialAdded(0) verifyPixelNotSent() diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/engagement/store/DefaultAutofillEngagementBucketingTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/engagement/store/DefaultAutofillEngagementBucketingTest.kt index 5db749d3cae7..31df78658094 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/engagement/store/DefaultAutofillEngagementBucketingTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/engagement/store/DefaultAutofillEngagementBucketingTest.kt @@ -12,31 +12,31 @@ class DefaultAutofillEngagementBucketingTest { private val testee = DefaultAutofillEngagementBucketing() @Test - fun whenZeroSavedPasswordsThenBucketIsNone() { + fun `bucketNumberOfSavedPasswords - zero saved passwords - none`() { assertEquals(NONE, testee.bucketNumberOfSavedPasswords(0)) } @Test - fun whenBetweenOneAndThreeSavedPasswordThenBucketIsFew() { + fun `bucketNumberOfSavedPasswords - between one and three saved password - few`() { assertEquals(FEW, testee.bucketNumberOfSavedPasswords(1)) assertEquals(FEW, testee.bucketNumberOfSavedPasswords(2)) assertEquals(FEW, testee.bucketNumberOfSavedPasswords(3)) } @Test - fun whenBetweenFourAndTenSavedPasswordThenBucketIsSome() { + fun `bucketNumberOfSavedPasswords - between 4 and 10 saved password - some`() { assertEquals(SOME, testee.bucketNumberOfSavedPasswords(4)) assertEquals(SOME, testee.bucketNumberOfSavedPasswords(10)) } @Test - fun whenBetweenElevenAndFortyNineSavedPasswordThenBucketIsMany() { + fun `bucketNumberOfSavedPasswords - between eleven and forty-nine saved password - many`() { assertEquals(MANY, testee.bucketNumberOfSavedPasswords(11)) assertEquals(MANY, testee.bucketNumberOfSavedPasswords(49)) } @Test - fun whenFiftyOrOverThenBucketIsMany() { + fun `bucketNumberOfSavedPasswords - fifty or over - many`() { assertEquals(LOTS, testee.bucketNumberOfSavedPasswords(50)) assertEquals(LOTS, testee.bucketNumberOfSavedPasswords(Int.MAX_VALUE)) } diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/engagement/store/DefaultAutofillEngagementRepositoryTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/engagement/store/DefaultAutofillEngagementRepositoryTest.kt index 293acb9d3379..c00abbb5d956 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/engagement/store/DefaultAutofillEngagementRepositoryTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/engagement/store/DefaultAutofillEngagementRepositoryTest.kt @@ -53,19 +53,19 @@ class DefaultAutofillEngagementRepositoryTest { ) @Test - fun whenAutofilledButNotSearchedThenActiveUserPixelNotSent() = runTest { + fun `recordAutofilled - active user pixel not sent`() = runTest { testee.recordAutofilledToday() AUTOFILL_ENGAGEMENT_ACTIVE_USER.verifyNotSent() } @Test - fun whenSearchedButNotNotAutofilledThenActiveUserPixelNotSent() = runTest { + fun `recordSearchedToday - active user pixel not sent`() = runTest { testee.recordSearchedToday() AUTOFILL_ENGAGEMENT_ACTIVE_USER.verifyNotSent() } @Test - fun whenSearchedAndAutofilledThenActiveUserPixelSent() = runTest { + fun `recordSearchedAndAutofilled - active user pixel sent`() = runTest { testee.recordSearchedToday() testee.recordAutofilledToday() AUTOFILL_ENGAGEMENT_ACTIVE_USER.verifySent() diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/feature/plugin/emailprotection/EmailProtectionInContextRemoteSettingsPersisterTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/feature/plugin/emailprotection/EmailProtectionInContextRemoteSettingsPersisterTest.kt index 5b81750ac250..a5fcbfe5e3e6 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/feature/plugin/emailprotection/EmailProtectionInContextRemoteSettingsPersisterTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/feature/plugin/emailprotection/EmailProtectionInContextRemoteSettingsPersisterTest.kt @@ -28,25 +28,25 @@ class EmailProtectionInContextRemoteSettingsPersisterTest { ) @Test - fun whenInvalidJsonThenNotSaved() = runTest { + fun `store - invalid json - not saved`() = runTest { testee.store("invalid json") verify(dataStore, never()).updateMaximumPermittedDaysSinceInstallation(any()) } @Test - fun whenValidJsonButMissingInstalledDaysFieldThenSavedAsMaxValue() = runTest { + fun `store - valid json missing installed days field - saved as max value`() = runTest { testee.store("{}") verify(dataStore).updateMaximumPermittedDaysSinceInstallation(Int.MAX_VALUE) } @Test - fun whenValidJsonPositiveNumberThenStoredCorrectly() = runTest { + fun `store - valid json positive number - stored correctly`() = runTest { testee.store(validJson(10)) verify(dataStore).updateMaximumPermittedDaysSinceInstallation(10) } @Test - fun whenValidJsonNegativeNumberThenStoredCorrectly() = runTest { + fun `store - valid json negative number - stored correctly`() = runTest { testee.store(validJson(-1)) verify(dataStore).updateMaximumPermittedDaysSinceInstallation(-1) } diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/internal/RealInternalTestUserCheckerTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/internal/RealInternalTestUserCheckerTest.kt index 8081f8a8203f..e92f049c20bb 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/internal/RealInternalTestUserCheckerTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/internal/RealInternalTestUserCheckerTest.kt @@ -47,7 +47,7 @@ class RealInternalTestUserCheckerTest { } @Test - fun whenErrorReceivedForInvalidUrlThenisNotInternalTestUser() { + fun `verifyVerificationErrorReceived - is not internal test user - not internal test user`() { testee.verifyVerificationErrorReceived(INVALID_TEST_URL) testee.verifyVerificationCompleted(INVALID_TEST_URL) @@ -55,14 +55,14 @@ class RealInternalTestUserCheckerTest { } @Test - fun whenCompletedForInvalidUrlThenisNotInternalTestUser() { + fun `verifyVerificationCompleted - is not internal test user - not internal test user`() { testee.verifyVerificationCompleted(INVALID_TEST_URL) assertFalse(testee.isInternalTestUser) } @Test - fun whenErrorForValidButHttpUrlThenisNotInternalTestUser() { + fun `verifyVerificationError - http url - is not internal test user`() { testee.verifyVerificationErrorReceived(VALID_TEST_HTTP_URL) testee.verifyVerificationCompleted(VALID_TEST_HTTPS_URL) @@ -70,7 +70,7 @@ class RealInternalTestUserCheckerTest { } @Test - fun whenErrorReceivedForValidUrlThenisNotInternalTestUser() { + fun `verifyVerificationErrorReceived - is not internal test user`() { testee.verifyVerificationErrorReceived(VALID_TEST_HTTPS_URL) testee.verifyVerificationCompleted(VALID_TEST_HTTPS_URL) @@ -78,28 +78,28 @@ class RealInternalTestUserCheckerTest { } @Test - fun whenCompletedForValidUrlThenisInternalTestUser() { + fun `verifyVerificationCompleted - is internal test user - true`() { testee.verifyVerificationCompleted(VALID_TEST_HTTPS_URL) assertTrue(testee.isInternalTestUser) } @Test - fun whenCompletedForValidButHttpUrlThenisInternalTestUser() { + fun `verifyVerificationCompleted - http url - is internal test user`() { testee.verifyVerificationCompleted(VALID_TEST_HTTP_URL) assertTrue(testee.isInternalTestUser) } @Test - fun whenUserBuildIsInternalNoValidationThenIsInternalTestUser() { + fun `whenUserBuildIsInternalNoValidation - is internal test user`() { whenever(appBuildConfig.flavor).thenReturn(INTERNAL) assertTrue(testee.isInternalTestUser) } @Test - fun whenUserBuildIsInternalAndErrorReceivedWhenValidatingThenIsInternalTestUser() { + fun `verifyVerificationErrorReceived - internal build and error received - is internal test user`() { whenever(appBuildConfig.flavor).thenReturn(INTERNAL) testee.verifyVerificationErrorReceived(VALID_TEST_HTTPS_URL) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/jsbridge/request/AutofillJsonRequestParserTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/jsbridge/request/AutofillJsonRequestParserTest.kt index fe6bb2c47558..369e946a0629 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/jsbridge/request/AutofillJsonRequestParserTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/jsbridge/request/AutofillJsonRequestParserTest.kt @@ -28,61 +28,61 @@ class AutofillJsonRequestParserTest { private val testee = AutofillJsonRequestParser(moshi) @Test - fun whenUsernameAndPasswordBothProvidedThenBothInResponse() = runTest { + fun `parseStoreFormDataJson - username and password both provided - both in response`() = runTest { val parsed = "storeFormData_usernameAndPasswordProvided".parseStoreFormDataJson() assertEquals("dax@duck.com", parsed.credentials!!.username) assertEquals("123456", parsed.credentials!!.password) } @Test - fun whenUsernameAndPasswordBothMissingThenBothAreNull() = runTest { + fun `parseStoreFormDataJson - username and password both missing - null`() = runTest { val parsed = "storeFormData_usernameAndPasswordMissing".parseStoreFormDataJson() assertNull(parsed.credentials!!.username) assertNull(parsed.credentials!!.password) } @Test - fun whenUsernameAndPasswordBothNullThenBothAreNullInParsedObject() = runTest { + fun `parseStoreFormDataJson - username and password both null - both are null in parsed object`() = runTest { val parsed = "storeFormData_usernameAndPasswordNull".parseStoreFormDataJson() assertNull(parsed.credentials!!.username) assertNull(parsed.credentials!!.password) } @Test - fun whenAdditionalUnknownPropertiesInRequestThenStillParses() = runTest { + fun `parseStoreFormDataJson - additional unknown properties in request - still parses`() = runTest { val parsed = "storeFormData_additionalUnknownPropertiesIncluded".parseStoreFormDataJson() assertEquals("dax@duck.com", parsed.credentials!!.username) assertEquals("123456", parsed.credentials!!.password) } @Test - fun whenUsernameMissingThenPasswordPopulated() = runTest { + fun `parseStoreFormDataJson - username missing - password populated`() = runTest { val parsed = "storeFormData_usernameMissing".parseStoreFormDataJson() assertNull(parsed.credentials!!.username) assertEquals("123456", parsed.credentials!!.password) } @Test - fun whenPasswordMissingThenUsernamePopulated() = runTest { + fun `parseStoreFormDataJson - password missing - username populated`() = runTest { val parsed = "storeFormData_passwordMissing".parseStoreFormDataJson() assertEquals("dax@duck.com", parsed.credentials!!.username) assertNull(parsed.credentials!!.password) } @Test - fun whenTopLevelCredentialsObjectMissingThenParsesWithoutError() = runTest { + fun `parseStoreFormDataJson - top level credentials object missing - parses without error`() = runTest { val parsed = "storeFormData_topLevelDataMissing".parseStoreFormDataJson() assertNull(parsed.credentials) } @Test - fun whenStoreFormDataRequestIsEmptyThenExceptionThrown() = runTest { + fun `parseStoreFormDataRequest - empty request - exception thrown`() = runTest { val result = testee.parseStoreFormDataRequest("") assertTrue(result.isFailure) } @Test - fun whenStoreFormDataRequestIsMalformedJSONThenExceptionThrown() = runTest { + fun `parseStoreFormDataRequest - malformed JSON - exception thrown`() = runTest { val result = testee.parseStoreFormDataRequest("invalid json") assertTrue(result.isFailure) } diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/jsbridge/response/AutofillJsonResponseWriterTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/jsbridge/response/AutofillJsonResponseWriterTest.kt index b2adaccdfbbc..b535d56959a5 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/jsbridge/response/AutofillJsonResponseWriterTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/jsbridge/response/AutofillJsonResponseWriterTest.kt @@ -25,7 +25,7 @@ class AutofillJsonResponseWriterTest { private val testee = AutofillJsonResponseWriter(Moshi.Builder().build()) @Test - fun whenGenerateResponseGetAutofillDataTheReturnAutofillDataJson() { + fun `generateResponseGetAutofillData - get autofill data - return autofill data json`() { val expectedJson = "{\n" + " \"success\": {\n" + " \"action\": \"fill\",\n" + @@ -48,7 +48,7 @@ class AutofillJsonResponseWriterTest { } @Test - fun whenGenerateEmptyResponseGetAutofillDataThenReturnEmptyResponseJson() { + fun `generateEmptyResponseGetAutofillData - returns empty response json`() { val expectedJson = "{\n" + " \"success\": {\n" + " \"action\": \"none\"\n" + diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/securestorage/RealL2DataTransformerTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/securestorage/RealL2DataTransformerTest.kt index f0791d21164c..c7cb0f377975 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/securestorage/RealL2DataTransformerTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/securestorage/RealL2DataTransformerTest.kt @@ -46,21 +46,21 @@ class RealL2DataTransformerTest { } @Test - fun whenCanProcessDataThenReturnCanAccessKeyStoreTrue() { + fun `canProcessData - can access key store true`() { whenever(secureStorageKeyProvider.canAccessKeyStore()).thenReturn(true) assertTrue(testee.canProcessData()) } @Test - fun whenCanProcessDataFalseThenReturnCanAccessKeyStoreFalse() { + fun `canProcessData - can access key store false - return can process data false`() { whenever(secureStorageKeyProvider.canAccessKeyStore()).thenReturn(false) assertFalse(testee.canProcessData()) } @Test - fun whenDataIsEncryptedThenDelegateEncryptionToEncryptionHelper() { + fun `encrypt - data encrypted - delegate to encryption helper`() { val result = testee.encrypt("test123") assertEquals(expectedEncryptedData, result.data) @@ -68,7 +68,7 @@ class RealL2DataTransformerTest { } @Test - fun whenDataIsDecryptedThenDelegateDecryptionToEncryptionHelper() { + fun `decrypt - data decrypted - delegate decryption to encryption helper`() { val result = testee.decrypt("test123", "iv") assertEquals(decodedDecryptedData, result) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/securestorage/RealSecureStorageKeyGeneratorTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/securestorage/RealSecureStorageKeyGeneratorTest.kt index 47275c9a38f3..3db80a066d38 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/securestorage/RealSecureStorageKeyGeneratorTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/securestorage/RealSecureStorageKeyGeneratorTest.kt @@ -55,18 +55,18 @@ class RealSecureStorageKeyGeneratorTest { } @Test - fun whenKeyIsGeneratedThenAlgorithmShouldBeAES() { + fun `generateKey - key generated - AES`() { assertEquals("AES", testee.generateKey().algorithm) } @Test - fun whenKeyIsGeneratedFromKeyMaterialThenAlgorithmShouldBeAES() { + fun `generateKeyFromKeyMaterial - algorithm should be AES`() { val keyMaterial = randomBytes assertEquals("AES", testee.generateKeyFromKeyMaterial(keyMaterial).algorithm) } @Test - fun whenKeyIsGeneratedFromPasswordForSDK26MaterialThenUseDerivedKeySecretFactoryAndAlgorithmShouldBeAES() { + fun `generateKeyFromPassword - SDK 26 material - uses AES algorithm`() { whenever(appBuildConfig.sdkInt).thenReturn(26) val result = testee.generateKeyFromPassword("password", randomBytes) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/securestorage/RealSecureStorageKeyProviderTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/securestorage/RealSecureStorageKeyProviderTest.kt index cc1aa84bf32e..dc85e3b1cd54 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/securestorage/RealSecureStorageKeyProviderTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/securestorage/RealSecureStorageKeyProviderTest.kt @@ -53,12 +53,12 @@ class RealSecureStorageKeyProviderTest { } @Test - fun whenCanAccessKeyStoreIsCheckedThenReturnRepositoryCanUseEncryption() { + fun `canAccessKeyStore - checked - return repository can use encryption`() { assertTrue(testee.canAccessKeyStore()) } @Test - fun whenNoL1KeySetThenGenerateAndStoreL1Key() { + fun `getL1Key - no L1 key set - generate and store L1 key`() { whenever(randomBytesGenerator.generateBytes(32)).thenReturn(testRandomBytes) assertNull("Initial state is incorrect since L1key is not null", secureStorageKeyRepository.l1Key) @@ -69,7 +69,7 @@ class RealSecureStorageKeyProviderTest { } @Test - fun whenL1KeySetThenReturnStoredL1Key() { + fun `getl1Key - l1 key set - returns stored l1 key`() { secureStorageKeyRepository.l1Key = testRandomBytes val result = testee.getl1Key() @@ -78,7 +78,7 @@ class RealSecureStorageKeyProviderTest { } @Test - fun whenNoValueStoredInKeyRepositoryThenReturnKeyAndGenerateAndStoreKeyValues() { + fun `getl2Key - no value stored in key repository - return key and generate and store key values`() { whenever(mockKey.encoded).thenReturn(testRandomBytes) whenever(randomBytesGenerator.generateBytes(32)).thenReturn(testRandomBytes) assertNull("Initial state is incorrect since password is not null", secureStorageKeyRepository.password) @@ -96,7 +96,7 @@ class RealSecureStorageKeyProviderTest { } @Test - fun whenAllKeysStoredInKeyRepositoryThenUseKeysWhenConstructingL2Key() { + fun `getL2Key - all keys stored in key repository - uses keys when constructing L2 key`() { secureStorageKeyRepository.password = testRandomBytes secureStorageKeyRepository.passwordSalt = testRandomBytes secureStorageKeyRepository.encryptedL2Key = testRandomBytes diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/securestorage/RealSecureStorageTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/securestorage/RealSecureStorageTest.kt index ff14ce7c3950..874b153b63d7 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/securestorage/RealSecureStorageTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/securestorage/RealSecureStorageTest.kt @@ -93,35 +93,35 @@ class RealSecureStorageTest { } @Test - fun whenCredentialsAddedThenAddEntityToRepositoryWithEncryptedPasswordAndIv() = runTest { + fun `addWebsiteLoginDetails - credentials added - add entity to repository with encrypted password and iv`() = runTest { testee.addWebsiteLoginDetailsWithCredentials(testCredentials) verify(secureStorageRepository).addWebsiteLoginCredential(testEntity) } @Test - fun whenCanAccessSecureStorageThenReturnCanProcessDataValue() { + fun `canAccessSecureStorage - can process data - true`() { whenever(l2DataTransformer.canProcessData()).thenReturn(true) assertTrue(testee.canAccessSecureStorage()) } @Test - fun whenCredentialsDeletedThenDeleteEntityWithIdFromSecureStorageRepository() = runTest { + fun `deleteWebsiteLoginDetailsWithCredentials - secure storage repository delete`() = runTest { testee.deleteWebsiteLoginDetailsWithCredentials(1) verify(secureStorageRepository).deleteWebsiteLoginCredentials(1) } @Test - fun whenCredentialsUpdatedThenUpdateEntityInSecureStorageRepository() = runTest { + fun `updateWebsiteLoginDetails - credentials updated - update entity in secure storage repository`() = runTest { testee.updateWebsiteLoginDetailsWithCredentials(testCredentials) verify(secureStorageRepository).updateWebsiteLoginCredentials(testEntity) } @Test - fun whenGetCredentialsWIthIdThenGetEntityWithIdFromSecureStorageRepository() = runTest { + fun `getWebsiteLoginDetailsWithCredentials - id - gets entity with id from secure storage repository`() = runTest { whenever(secureStorageRepository.getWebsiteLoginCredentialsForId(1)).thenReturn(testEntity) val result = testee.getWebsiteLoginDetailsWithCredentials(1) @@ -130,7 +130,7 @@ class RealSecureStorageTest { } @Test - fun whenAllWebsiteLoginDetailsRequestedThenGetAllEntitiesAndReturnAllDetailsOnly() = runTest { + fun `websiteLoginDetails - all website login details requested - return all details only`() = runTest { whenever(secureStorageRepository.websiteLoginCredentials()).thenReturn( MutableStateFlow(listOf(testEntity)), ) @@ -141,7 +141,7 @@ class RealSecureStorageTest { } @Test - fun whenWebsiteLoginDetailsForDomainRequestedThenGetEntityForDomainAndReturnDetailsOnly() = runTest { + fun `websiteLoginDetailsForDomain - get entity for domain and return details only`() = runTest { whenever(secureStorageRepository.websiteLoginCredentialsForDomain("test.com")).thenReturn( MutableStateFlow(listOf(testEntity)), ) @@ -152,7 +152,7 @@ class RealSecureStorageTest { } @Test - fun whenAllWebsiteLoginCredentialsRequestedThenGetAllEntitiesAndReturnIncludingDecryptedPassword() = runTest { + fun `websiteLoginDetailsWithCredentials - all website login credentials requested - including decrypted password`() = runTest { whenever(secureStorageRepository.websiteLoginCredentials()).thenReturn( MutableStateFlow(listOf(testEntity)), ) @@ -163,7 +163,7 @@ class RealSecureStorageTest { } @Test - fun whenWebsiteLoginCredentialsForDomainRequestedThenGetEntityForDomainAndReturnIncludingDecryptedPassword() = runTest { + fun `websiteLoginDetailsWithCredentials - website login credentials for domain requested - returns entity with decrypted password`() = runTest { whenever(secureStorageRepository.websiteLoginCredentialsForDomain("test.com")).thenReturn( MutableStateFlow(listOf(testEntity)), ) @@ -174,14 +174,14 @@ class RealSecureStorageTest { } @Test - fun whenNoSecureStorageRepositoryThenCanAccessSecureStorageFalse() { + fun `setUpNoSecureStorageRepository - can access secure storage false`() { setUpNoSecureStorageRepository() assertFalse(testee.canAccessSecureStorage()) } @Test - fun whenNoSecureStorageRepositoryAddCredentialsThenDoNothing() = runTest { + fun `addWebsiteLoginDetails - no secure storage repository - do nothing`() = runTest { setUpNoSecureStorageRepository() testee.addWebsiteLoginDetailsWithCredentials(testCredentials) @@ -190,14 +190,14 @@ class RealSecureStorageTest { } @Test - fun whenNoSecureStorageRepositoryGetCredentialsThenReturnNull() = runTest { + fun `getWebsiteLoginDetailsWithCredentials - no secure storage repository - return null`() = runTest { setUpNoSecureStorageRepository() assertNull(testee.getWebsiteLoginDetailsWithCredentials(1)) } @Test - fun whenNoSecureStorageRepositoryUpdateCredentialsThenDoNothing() = runTest { + fun `updateWebsiteLoginDetails - no secure storage repository update credentials - do nothing`() = runTest { setUpNoSecureStorageRepository() testee.updateWebsiteLoginDetailsWithCredentials(testCredentials) @@ -206,7 +206,7 @@ class RealSecureStorageTest { } @Test - fun whenNoSecureStorageRepositoryDeleteCredentialsThenDoNothing() = runTest { + fun `deleteWebsiteLoginDetails - no secure storage repository - do nothing`() = runTest { setUpNoSecureStorageRepository() testee.deleteWebsiteLoginDetailsWithCredentials(1) @@ -215,7 +215,7 @@ class RealSecureStorageTest { } @Test - fun whenNoSecureStorageRepositoryGetWebsiteLoginDetailsForDomainThenFlowReturnsNothing() = runTest { + fun `websiteLoginDetailsForDomain - no secure storage repository - returns nothing`() = runTest { setUpNoSecureStorageRepository() testee.websiteLoginDetailsForDomain("test").test { @@ -224,7 +224,7 @@ class RealSecureStorageTest { } @Test - fun whenNoSecureStorageRepositoryGetWebsiteLoginDetailsThenFlowReturnsNothing() = runTest { + fun `websiteLoginDetails - no secure storage repository - returns nothing`() = runTest { setUpNoSecureStorageRepository() testee.websiteLoginDetails().test { @@ -233,7 +233,7 @@ class RealSecureStorageTest { } @Test - fun whenNoSecureStorageRepositoryGetWebsiteCredentialsForDomainThenFlowReturnsEmptyList() = runTest { + fun `websiteLoginDetails - no secure storage repository - returns empty list`() = runTest { setUpNoSecureStorageRepository() testee.websiteLoginDetailsWithCredentialsForDomain("test").test { @@ -243,7 +243,7 @@ class RealSecureStorageTest { } @Test - fun whenNoSecureStorageRepositoryGetWebsiteCredentialsThenFlowReturnsEmptyList() = runTest { + fun `websiteLoginDetailsWithCredentials - no secure storage repository - returns empty list`() = runTest { setUpNoSecureStorageRepository() testee.websiteLoginDetailsWithCredentials().test { @@ -253,7 +253,7 @@ class RealSecureStorageTest { } @Test - fun whenMassDeletingCredentialsBulkDeletionFunctionOnSecureStorageRepoUsed() = runTest { + fun `deleteWebSiteLoginDetailsWithCredentials - secure storage repo used`() = runTest { val idsToDelete = listOf(1L, 2L, 3L) testee.deleteWebSiteLoginDetailsWithCredentials(idsToDelete) verify(secureStorageRepository).deleteWebsiteLoginCredentials(idsToDelete) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/sharedcreds/AppleShareableCredentialsTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/sharedcreds/AppleShareableCredentialsTest.kt index 6be2f830cd1a..248540b229de 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/sharedcreds/AppleShareableCredentialsTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/sharedcreds/AppleShareableCredentialsTest.kt @@ -37,21 +37,21 @@ class AppleShareableCredentialsTest { ) @Test - fun whenNoMatchingShareableCredentialsFoundThenEmptyListReturned() = runTest { + fun `shareableCredentials - no matching credentials found - empty list returned`() = runTest { configureMatchingLogins(emptyList()) val list = testee.shareableCredentials("example.com") assertTrue(list.isEmpty()) } @Test - fun whenSingleMatchingShareableCredentialFoundThenReturned() = runTest { + fun `shareableCredentials - single matching shareable credential found - returned`() = runTest { configureMatchingLogins(listOf("example.com")) val list = testee.shareableCredentials("example.com") assertEquals(1, list.size) } @Test - fun whenMultipleDifferentMatchingShareableCredentialsFoundThenAllReturned() = runTest { + fun `shareableCredentials - multiple different matching shareable credentials found - all returned`() = runTest { configureMatchingLogins( listOf( "example.com", @@ -64,7 +64,7 @@ class AppleShareableCredentialsTest { } @Test - fun whenSameLoginFoundMultipleTimesThenOnlyIncludedOnce() = runTest { + fun `shareableCredentials - same login found multiple times - only included once`() = runTest { configureMatchingLogins( listOf( "example.com", diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/sharedcreds/AppleSharedCredentialsParserTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/sharedcreds/AppleSharedCredentialsParserTest.kt index 029ddad0ae83..6239154318d1 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/sharedcreds/AppleSharedCredentialsParserTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/sharedcreds/AppleSharedCredentialsParserTest.kt @@ -44,14 +44,14 @@ class AppleSharedCredentialsParserTest { ) @Test - fun whenJsonNotReadThenRulesAreEmpty() = runTest { + fun `read - json not read - rules are empty`() = runTest { whenever(jsonReader.read()).thenReturn(null) val rules = testee.read() rules.assertRulesAreEmpty() } @Test - fun whenJsonIsCorruptNotReadThenRulesAreEmpty() = runTest { + fun `read - json corrupt not read - rules are empty`() = runTest { whenever(jsonReader.read()).thenReturn("not valid json") val rules = testee.read() rules.assertRulesAreEmpty() diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/sharedcreds/RealShareableCredentialsUrlGeneratorTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/sharedcreds/RealShareableCredentialsUrlGeneratorTest.kt index e5ac418fd5ed..1155f8ee8129 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/sharedcreds/RealShareableCredentialsUrlGeneratorTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/sharedcreds/RealShareableCredentialsUrlGeneratorTest.kt @@ -54,7 +54,7 @@ class RealShareableCredentialsUrlGeneratorTest { } @Test - fun whenSiteInOmnidirectionalListThenAllRelatedSitesReturned() = runTest { + fun `generateShareableUrls - site in omnidirectional list - all related sites returned`() = runTest { val config = config( omnidirectionalRules = listOf( omnidirectionalRule(listOf("foo.com", "example.com", "bar.com")), @@ -73,7 +73,7 @@ class RealShareableCredentialsUrlGeneratorTest { } @Test - fun whenSiteInOmnidirectionalListMultipleTimesThenOnlyReturnedOnce() = runTest { + fun `generateShareableUrls - site in omnidirectional list multiple times - only returned once`() = runTest { val config = config( omnidirectionalRules = listOf( omnidirectionalRule(listOf("foo.com", "example.com", "bar.com")), @@ -92,7 +92,7 @@ class RealShareableCredentialsUrlGeneratorTest { } @Test - fun whenSiteInUnidirectionalToRuleThenOfferedFromUrl() = runTest { + fun `generateShareableUrls - site in unidirectional to rule - offered from url`() = runTest { val config = config( unidirectionalRules = listOf( unidirectionalRule( @@ -106,7 +106,7 @@ class RealShareableCredentialsUrlGeneratorTest { } @Test - fun whenSiteInUnidirectionalFromRuleThenNotOfferedToUrl() = runTest { + fun `generateShareableUrls - site in unidirectional rule - not offered to url`() = runTest { val config = config( unidirectionalRules = listOf( unidirectionalRule( @@ -120,7 +120,7 @@ class RealShareableCredentialsUrlGeneratorTest { } @Test - fun whenSiteInMultipleUnidirectionalListThenReturnedOnce() = runTest { + fun `generateShareableUrls - site in multiple unidirectional list - returned once`() = runTest { val config = config( unidirectionalRules = listOf( unidirectionalRule( @@ -139,7 +139,7 @@ class RealShareableCredentialsUrlGeneratorTest { } @Test - fun whenFromUnidirectionalListHasMultipleSitesThenAllReturned() = runTest { + fun `generateShareableUrls - from unidirectional list has multiple sites - all returned`() = runTest { val config = config( unidirectionalRules = listOf( unidirectionalRule( @@ -169,7 +169,7 @@ class RealShareableCredentialsUrlGeneratorTest { } @Test - fun whenMatchesFromOmnidirectionalAndUnidirectionalThenReturnedOnce() = runTest { + fun `generateShareableUrls - omnidirectional and unidirectional matches - returned once`() = runTest { val config = config( omnidirectionalRules = listOf( omnidirectionalRule(listOf("example.com", "expected.com")), @@ -186,14 +186,14 @@ class RealShareableCredentialsUrlGeneratorTest { } @Test - fun whenFullUncleanedUrlGivenThenStillMatches() = runTest { + fun `generateShareableUrls - full uncleaned url given - still matches`() = runTest { val config = config(omnidirectionalRules = listOf(omnidirectionalRule(listOf("example.com", "expected.com")))) val result = testee.generateShareableUrls("https://example.com/hello/world", config) result.assertMatches(listOf("expected.com")) } @Test - fun whenConfigIsEmptyThenNoSitesReturned() = runTest { + fun `generateShareableUrls - config is empty - no sites returned`() = runTest { val config = emptyLists() val result = testee.generateShareableUrls("example.com", config) result.assertMatches(emptyList()) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/store/RealNeverSavedSiteRepositoryTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/store/RealNeverSavedSiteRepositoryTest.kt index 6e3d780afee0..9a52d348472c 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/store/RealNeverSavedSiteRepositoryTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/store/RealNeverSavedSiteRepositoryTest.kt @@ -31,25 +31,25 @@ class RealNeverSavedSiteRepositoryTest { ) @Test - fun whenDomainAddedToNeverSaveListThenETldPlus1IsUsed() = runTest { + fun `addToNeverSaveList - domain added to never save list - etld plus 1 used`() = runTest { testee.addToNeverSaveList("foo.example.com") verify(secureStorage).addToNeverSaveList("example.com") } @Test - fun whenDomainAddedToNeverSaveListContainsQueryParamsThenOnlyETldPlus1IsUsed() = runTest { + fun `addToNeverSaveList - domain added to never save list contains query params - only etld plus 1 used`() = runTest { testee.addToNeverSaveList("https://foo.example.com/?q=123") verify(secureStorage).addToNeverSaveList("example.com") } @Test - fun whenDomainAddedThenQueryingForThatExactDomainReturnsTrue() = runTest { + fun `isInNeverSaveList - domain added - returns true`() = runTest { whenever(secureStorage.isInNeverSaveList("example.com")).thenReturn(true) assertTrue(testee.isInNeverSaveList("example.com")) } @Test - fun whenDomainAddedThenQueryingUsesEtldPlusOne() = runTest { + fun `isInNeverSaveList - domain added - uses etld plus one`() = runTest { whenever(secureStorage.isInNeverSaveList("example.com")).thenReturn(true) assertTrue(testee.isInNeverSaveList("foo.example.com")) } diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/AutofillSettingsViewModelTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/AutofillSettingsViewModelTest.kt index 2a0dc071b92b..31f2545a3d33 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/AutofillSettingsViewModelTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/AutofillSettingsViewModelTest.kt @@ -123,7 +123,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenUserEnablesAutofillThenViewStateUpdatedToReflectChange() = runTest { + fun `onEnableAutofill - view state updated`() = runTest { testee.onEnableAutofill() testee.viewState.test { assertTrue(this.awaitItem().autofillEnabled) @@ -132,7 +132,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenUserDisablesAutofillThenViewStateUpdatedToReflectChange() = runTest { + fun `onDisableAutofill - viewState updated`() = runTest { testee.onDisableAutofill() testee.viewState.test { assertFalse(this.awaitItem().autofillEnabled) @@ -141,19 +141,19 @@ class AutofillSettingsViewModelTest { } @Test - fun whenUserEnablesAutofillThenCorrectPixelFired() { + fun `onEnableAutofill - pixel fired - correct pixel fired`() { testee.onEnableAutofill() verify(pixel).fire(AUTOFILL_ENABLE_AUTOFILL_TOGGLE_MANUALLY_ENABLED) } @Test - fun whenUserDisablesAutofillThenCorrectPixelFired() { + fun `onDisableAutofill - pixel fired`() { testee.onDisableAutofill() verify(pixel).fire(AUTOFILL_ENABLE_AUTOFILL_TOGGLE_MANUALLY_DISABLED) } @Test - fun whenUserCopiesPasswordThenCommandIssuedToShowChange() = runTest { + fun `onCopyPassword - command issued to show change`() = runTest { testee.onCopyPassword("hello") verify(clipboardInteractor).copyToClipboard("hello", isSensitive = true) @@ -164,7 +164,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenUserCopiesUsernameThenCommandIssuedToShowChange() = runTest { + fun `onCopyUsername - command issued to show change`() = runTest { testee.onCopyUsername("username") verify(clipboardInteractor).copyToClipboard("username", isSensitive = false) @@ -175,14 +175,14 @@ class AutofillSettingsViewModelTest { } @Test - fun whenUserDeletesViewedCredentialsThenStoreDeletionCalled() = runTest { + fun `onDeleteCredentials - store deletion called`() = runTest { val credentials = someCredentials() testee.onDeleteCredentials(credentials) verify(mockStore).deleteCredentials(credentials.id!!) } @Test - fun whenUserDeletesViewedCredentialsLaunchedDirectlyThenCredentialsDeleted() = runTest { + fun `onViewCredentials - delete credentials launched directly - credentials deleted`() = runTest { val credentials = someCredentials() testee.onViewCredentials(credentials) testee.onDeleteCredentials(credentials) @@ -190,7 +190,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenOnViewCredentialsCalledFromListThenShowCredentialViewingMode() = runTest { + fun `onViewCredentials - view state updated - show credential viewing mode`() = runTest { val credentials = someCredentials() testee.onViewCredentials(credentials) @@ -205,7 +205,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenOnViewCredentialsCalledFirstThenShowCredentialViewingMode() = runTest { + fun `onViewCredentials - view state updated - shows credential viewing mode`() = runTest { val credentials = someCredentials() testee.onViewCredentials(credentials) @@ -220,7 +220,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenOnViewCredentialsCalledWithWebsiteThenShowLinkButton() = runTest { + fun `onViewCredentials - website - show link button`() = runTest { whenever(webUrlIdentifier.isLikelyAUrl(anyOrNull())).thenReturn(true) val credentials = someCredentials() testee.onViewCredentials(credentials) @@ -236,7 +236,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenOnViewCredentialsCalledWithoutValidWebsiteThenHideLinkButton() = runTest { + fun `onViewCredentials - no valid website - hide link button`() = runTest { whenever(webUrlIdentifier.isLikelyAUrl(anyOrNull())).thenReturn(false) val credentials = someCredentials() testee.onViewCredentials(credentials) @@ -252,7 +252,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenOnEditCredentialsCalledThenShowCredentialEditingMode() = runTest { + fun `onEditCurrentCredentials - view state updated - editing existing credential mode`() = runTest { val credentials = someCredentials() testee.onViewCredentials(credentials) testee.onEditCurrentCredentials() @@ -267,7 +267,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenOnEditCredentialsCalledDirectlyThenShowCredentialEditingMode() = runTest { + fun `onEditCredentials - view state updated - show credential editing mode`() = runTest { val credentials = someCredentials() testee.onEditCredentials(credentials) @@ -281,7 +281,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenOnEditCredentialsCalledNotFromViewThenShowCredentialEditingMode() = runTest { + fun `onEditCredentials - not from view - show credential editing mode`() = runTest { val credentials = someCredentials() testee.onEditCredentials(credentials) @@ -304,7 +304,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenOnCredentialEditModePopulatedThenViewStateUpdated() = runTest { + fun `onCredentialEditModePopulated - view state updated`() = runTest { val credentials = someCredentials() testee.onEditCredentials(credentials) @@ -320,7 +320,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenLockCalledThenShowLockedMode() = runTest { + fun `lock - show locked mode`() = runTest { testee.lock() testee.commands.test { @@ -330,7 +330,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenLockModeCalledMOreThanOnceThenShowLockedModeOnlyOnce() = runTest { + fun `lock - show locked mode only once`() = runTest { testee.lock() testee.commands.test { @@ -341,7 +341,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenUnlockCalledThenExitLockedMode() = runTest { + fun `unlock - exit locked mode`() = runTest { testee.unlock() testee.commands.test { @@ -352,7 +352,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenDisableCalledThenShowDisabledMode() = runTest { + fun `disabled - show disabled mode`() = runTest { testee.disabled() testee.commands.test { @@ -370,7 +370,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenUpdateCredentialsCalledThenUpdateAutofillStore() = runTest { + fun `onEditCredentials - update autofill store`() = runTest { val credentials = someCredentials() testee.onEditCredentials(credentials) @@ -382,7 +382,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenUpdateCredentialsCalledFromManualCreationThenSaveAutofillStore() = runTest { + fun `onCreateNewCredentials - save autofill store`() = runTest { val credentials = someCredentials() testee.onCreateNewCredentials() testee.saveOrUpdateCredentials(credentials) @@ -390,7 +390,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenOnExitEditModeThenUpdateCredentialModeStateToViewing() = runTest { + fun `onCancelEditMode - view state updated - viewing mode`() = runTest { val credentials = someCredentials() testee.onViewCredentials(credentials) testee.onEditCurrentCredentials() @@ -404,7 +404,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenOnExitEditModeButNotFromViewThenExitCredentialMode() = runTest { + fun `onCancelEditMode - exit credential mode`() = runTest { val credentials = someCredentials() testee.onEditCredentials(credentials) @@ -417,7 +417,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenOnExitCredentialModeThenExitCredentialMode() = runTest { + fun `onExitCredentialMode - exit credential mode`() = runTest { testee.onExitCredentialMode() testee.commands.test { @@ -427,7 +427,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenLockingAndUnlockingPreviousViewStateRestoredIfWasListMode() = runTest { + fun `onInitialiseListMode - view state restored - list mode`() = runTest { testee.onInitialiseListMode() testee.lock() testee.unlock() @@ -439,7 +439,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenLockingAndUnlockingPreviousViewStateRestoredIfWasCredentialViewingMode() = runTest { + fun `lock - unlock - previous view state restored if credential viewing mode`() = runTest { testee.onViewCredentials(someCredentials()) testee.lock() testee.unlock() @@ -451,7 +451,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenInEditModeAndChangedToDisabledThenUpdateNotInCredentialModeAndShowDisabledMode() = runTest { + fun `onEditCredentials - in edit mode and changed to disabled - update not in credential mode and show disabled mode`() = runTest { testee.onEditCredentials(someCredentials()) testee.disabled() @@ -466,7 +466,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenAllowSaveInEditModeSetToFalseThenUpdateViewStateToEditingSaveableFalse() = runTest { + fun `onAllowSaveInEditModeSetToFalse - viewState updated - editing saveable false`() = runTest { val credentials = someCredentials() testee.onViewCredentials(credentials) testee.onEditCurrentCredentials() @@ -484,7 +484,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenLaunchDeviceAuthWithDeviceUnsupportedThenEmitUnsupportedModeCommand() = runTest { + fun `launchDeviceAuth - device unsupported - emit unsupported mode command`() = runTest { configureDeviceToBeUnsupported() testee.launchDeviceAuth() @@ -503,7 +503,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenLaunchDeviceAuthThenUpdateStateToIsAuthenticatingAndEmitLaunchDeviceCommand() = runTest { + fun `launchDeviceAuth - state updated - emit launch device command`() = runTest { configureDeviceToBeSupported() configureDeviceToHaveValidAuthentication(true) configureStoreToHaveThisManyCredentialsStored(1) @@ -516,7 +516,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenLaunchDeviceAuthWithNoSavedCredentialsThenIsUnlockedAndAuthNotLaunched() = runTest { + fun `launchDeviceAuth - no saved credentials - is unlocked and auth not launched`() = runTest { configureDeviceToHaveValidAuthentication(true) configureStoreToHaveThisManyCredentialsStored(0) testee.launchDeviceAuth() @@ -530,7 +530,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenLaunchDeviceAuthWithNoValidAuthThenDisabledShown() = runTest { + fun `launchDeviceAuth - no valid auth - disabled shown`() = runTest { configureDeviceToHaveValidAuthentication(false) testee.launchDeviceAuth() @@ -543,7 +543,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenLaunchedDeviceAuthHasEndedAndLaunchedAgainThenEmitLaunchDeviceCommandTwice() = runTest { + fun `launchDeviceAuth - launched device auth has ended and launched again - emit launch device command twice`() = runTest { configureDeviceToBeSupported() configureDeviceToHaveValidAuthentication(true) configureStoreToHaveThisManyCredentialsStored(1) @@ -560,7 +560,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenLaunchDeviceAuthWithNoValidAuthenticationThenShowDisabledViewAndAuthNotLaunched() = runTest { + fun `launchDeviceAuth - no valid authentication - show disabled view and auth not launched`() = runTest { configureDeviceToBeSupported() configureDeviceToHaveValidAuthentication(false) testee.launchDeviceAuth() @@ -573,7 +573,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenObserveCredentialsCalledWithAutofillDisabledThenAutofillEnabledStateIsReturned() = runTest { + fun `observeCredentials - autofill disabled - false`() = runTest { whenever(mockStore.autofillEnabled).thenReturn(false) configureDeviceToHaveValidAuthentication(true) @@ -585,7 +585,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenObserveCredentialsCalledWithAutofillEnabledThenAutofillEnabledStateIsReturned() = runTest { + fun `onViewCreated - view state updated - autofill enabled`() = runTest { whenever(mockStore.autofillEnabled).thenReturn(true) configureDeviceToHaveValidAuthentication(true) @@ -597,7 +597,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenSearchQueryChangesEmptyThenShouldShowEnableToggle() = runTest { + fun `onSearchQueryChanged - view state updated - show enable toggle`() = runTest { testee.onSearchQueryChanged("") testee.onViewCreated() @@ -608,7 +608,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenSearchQueryChangesNonEmptyThenShouldNotShowEnableToggle() = runTest { + fun `onSearchQueryChanged - view state updated - should not show enable toggle`() = runTest { testee.onSearchQueryChanged("foo") testee.onViewCreated() @@ -619,7 +619,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenScreenLaunchedDirectlyIntoCredentialViewThenNoLaunchPixelSent() { + fun `sendLaunchPixel - no launch pixel sent`() { val launchedFromBrowser = false val directLinkToCredentials = true testee.sendLaunchPixel(launchedFromBrowser, directLinkToCredentials) @@ -627,7 +627,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenScreenLaunchedDirectlyIntoCredentialViewAndLaunchedFromBrowserThenNoLaunchPixelSent() { + fun `sendLaunchPixel - launched directly into credential view and launched from browser - no launch pixel sent`() { val launchedFromBrowser = true val directLinkToCredentials = true testee.sendLaunchPixel(launchedFromBrowser, directLinkToCredentials) @@ -635,7 +635,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenScreenLaunchedFromBrowserAndNotDirectLinkThenCorrectLaunchPixelSent() { + fun `sendLaunchPixel - not direct link - correct launch pixel sent`() { val launchedFromBrowser = true val directLinkToCredentials = false testee.sendLaunchPixel(launchedFromBrowser, directLinkToCredentials) @@ -643,7 +643,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenScreenLaunchedNotFromBrowserAndNotDirectLinkThenCorrectLaunchPixelSent() { + fun `sendLaunchPixel - not from browser and not direct link - correct launch pixel sent`() { val launchedFromBrowser = false val directLinkToCredentials = false testee.sendLaunchPixel(launchedFromBrowser, directLinkToCredentials) @@ -651,31 +651,31 @@ class AutofillSettingsViewModelTest { } @Test - fun whenUserFirstChoosesToResetNeverSavedSiteListThenCorrectPixelFired() = runTest { + fun `onResetNeverSavedSites - correct pixel fired`() = runTest { testee.onResetNeverSavedSitesInitialSelection() verify(pixel).fire(AUTOFILL_NEVER_SAVE_FOR_THIS_SITE_CONFIRMATION_PROMPT_DISPLAYED) } @Test - fun whenUserConfirmsTheyWantToResetNeverSavedSiteListThenRepositoryCleared() = runTest { + fun `onUserConfirmationToClearNeverSavedSites - repository cleared`() = runTest { testee.onUserConfirmationToClearNeverSavedSites() verify(neverSavedSiteRepository).clearNeverSaveList() } @Test - fun whenUserConfirmsTheyWantToResetNeverSavedSiteListThenCorrectPixelFired() = runTest { + fun `onUserConfirmationToClearNeverSavedSites - pixel fired - correct pixel fired`() = runTest { testee.onUserConfirmationToClearNeverSavedSites() verify(pixel).fire(AUTOFILL_NEVER_SAVE_FOR_THIS_SITE_CONFIRMATION_PROMPT_CONFIRMED) } @Test - fun whenUserDismissesPromptToResetNeverSavedSiteListThenCorrectPixelFired() = runTest { + fun `onUserCancelledFromClearNeverSavedSitesPrompt - correct pixel fired`() = runTest { testee.onUserCancelledFromClearNeverSavedSitesPrompt() verify(pixel).fire(AUTOFILL_NEVER_SAVE_FOR_THIS_SITE_CONFIRMATION_PROMPT_DISMISSED) } @Test - fun whenDeleteAllFirstCalledWithNoSavedLoginsThenNoCommandSentToShowConfirmationDialog() = runTest { + fun `onDeleteAllPasswordsInitialSelection - no saved logins - no command sent to show confirmation dialog`() = runTest { configureStoreToHaveThisManyCredentialsStored(0) testee.onViewCreated() testee.onDeleteAllPasswordsInitialSelection() @@ -686,7 +686,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenDeleteAllFirstCalledWithOneSavedLoginThenCommandSentToShowConfirmationDialog() = runTest { + fun `onDeleteAll - one saved login - shows confirmation dialog`() = runTest { configureStoreToHaveThisManyCredentialsStored(1) testee.onViewCreated() testee.onDeleteAllPasswordsInitialSelection() @@ -697,7 +697,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenDeleteAllPasswordsConfirmedButNoPasswordsSavedThenDoesNotIssueCommandToShowUndoSnackbar() = runTest { + fun `onDeleteAllPasswordsConfirmed - no passwords saved - does not issue command to show undo snackbar`() = runTest { whenever(mockStore.deleteAllCredentials()).thenReturn(emptyList()) testee.onDeleteAllPasswordsConfirmed() testee.commandsListView.test { @@ -707,7 +707,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenDeleteAllPasswordsConfirmedWithPasswordsSavedThenDoesIssueCommandToShowUndoSnackbar() = runTest { + fun `onDeleteAllPasswordsConfirmed - commands list view updated - shows undo snackbar`() = runTest { testee.onDeleteAllPasswordsConfirmed() testee.commandsListView.test { awaitItem().verifyHasCommandToAuthenticateMassDeletion() @@ -716,7 +716,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenAuthenticationSucceedsToMassDeletePasswordsThenDoesIssueCommandToShowUndoSnackbar() = runTest { + fun `onAuthenticatedToDeleteAllPasswords - does issue command to show undo snackbar`() = runTest { whenever(mockStore.deleteAllCredentials()).thenReturn(listOf(someCredentials())) testee.onAuthenticatedToDeleteAllPasswords() testee.commands.test { @@ -726,7 +726,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenDeleteAllFirstCalledWithManySavedLoginThenCommandSentToShowConfirmationDialog() = runTest { + fun `onDeleteAllPasswords - many saved logins - shows confirmation dialog`() = runTest { configureStoreToHaveThisManyCredentialsStored(100) testee.onViewCreated() testee.onDeleteAllPasswordsInitialSelection() @@ -737,38 +737,38 @@ class AutofillSettingsViewModelTest { } @Test - fun whenNoSurveysAvailableThenNoSurveyInViewState() = runTest { + fun `onViewStarted - view state no survey available - no survey in view state`() = runTest { testee.onViewStarted() verifySurveyNotAvailable() } @Test - fun whenUnusedSurveyAvailableThenSurveyInViewState() = runTest { + fun `onInitialiseListMode - survey in view state`() = runTest { whenever(autofillSurvey.firstUnusedSurvey()).thenReturn(SurveyDetails("surveyId-1", "example.com")) testee.onInitialiseListMode() "surveyId-1".verifySurveyAvailable() } @Test - fun whenSurveyShownThenNoSurveyInViewState() = runTest { + fun `onSurveyShown - view state no survey`() = runTest { testee.onSurveyShown("surveyId-1") verifySurveyNotAvailable() } @Test - fun whenSurveyShownThenSurveyMarkedAsUsed() = runTest { + fun `onSurveyShown - survey marked as used`() = runTest { testee.onSurveyShown("surveyId-1") verify(autofillSurvey).recordSurveyAsUsed("surveyId-1") } @Test - fun whenSurveyPromptDismissedThenNoSurveyInViewState() = runTest { + fun `onSurveyPromptDismissed - view state no survey`() = runTest { testee.onSurveyPromptDismissed("surveyId-1") verifySurveyNotAvailable() } @Test - fun whenSurveyPromptDismissedThenSurveyMarkedAsUsed() = runTest { + fun `onSurveyPromptDismissed - survey marked as used`() = runTest { testee.onSurveyPromptDismissed("surveyId-1") verify(autofillSurvey).recordSurveyAsUsed("surveyId-1") } diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/CredentialGrouperTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/CredentialGrouperTest.kt index 7f081ca6ba34..1176b7fc0d82 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/CredentialGrouperTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/CredentialGrouperTest.kt @@ -43,14 +43,14 @@ class CredentialGrouperTest { ) @Test - fun whenEmptyListInThenEmptyListOut() { + fun `group - empty list in - empty list out`() { val credentials = emptyList() val grouped = testee.group(credentials) assertTrue(grouped.isEmpty()) } @Test - fun whenSingleCredentialThenInitialAdded() { + fun `group - single credential - initial added`() { val credentials = listOf( creds("example.com"), ) @@ -63,7 +63,7 @@ class CredentialGrouperTest { } @Test - fun whenMultipleCredentialsWithSameInitialThenOnlyOneGroupAdded() { + fun `group - multiple credentials with same initial - one group added`() { val credentials = listOf( creds("example.com"), creds("energy.com"), @@ -77,7 +77,7 @@ class CredentialGrouperTest { } @Test - fun whenCredentialsWithDifferentInitialsThenMultipleGroupsAdded() { + fun `group - credentials with different initials - multiple groups added`() { val credentials = listOf( creds("example.com"), creds("foo.com"), @@ -94,7 +94,7 @@ class CredentialGrouperTest { } @Test - fun whenCombinationOfDomainsAndTitlesThenGroupsTakenFromTitlesWhenTheyExist() { + fun `group - combination of domains and titles - groups taken from titles when they exist`() { val credentials = listOf( creds(domain = "energy.com"), creds(domain = "amazon.com", title = "Smile Amazon"), @@ -114,7 +114,7 @@ class CredentialGrouperTest { } @Test - fun whenListContainsAnEntryWithAMissingDomainAndTitleThenGroupedIntoPlaceholder() { + fun `group - list contains missing domain and title - grouped into placeholder`() { val credentials = listOf( creds(domain = "amazon.com", title = "Smile Amazon"), creds(domain = "example.com"), @@ -133,7 +133,7 @@ class CredentialGrouperTest { } @Test - fun whenCharactersCanBeDeconstructedThenTheyDoNotGetTheirOwnGroup() { + fun `group - characters deconstructed - no own group`() { val credentials = listOf( creds(title = "ä"), creds(title = "A"), @@ -151,7 +151,7 @@ class CredentialGrouperTest { } @Test - fun whenNonEnglishAlphabetCharactersThenTheyDoGetTheirOwnGroup() { + fun `group - non-english alphabet characters - get their own group`() { val credentials = listOf( creds(title = "ß"), ) @@ -164,7 +164,7 @@ class CredentialGrouperTest { } @Test - fun whenEmojiThenTheTheyAreInPlaceholder() { + fun `group - emoji in placeholder - is group heading`() { val credentials = listOf( creds(title = "😅"), ) @@ -177,7 +177,7 @@ class CredentialGrouperTest { } @Test - fun whenNumberThenGroupedIntoPlaceholder() { + fun `group - number then grouped into placeholder - grouped correctly`() { val credentials = listOf( creds(title = "8"), creds(title = "5"), @@ -193,7 +193,7 @@ class CredentialGrouperTest { } @Test - fun whenListMixtureOfAccentedCharactersThenAccentedCharactersDoNotGetTheirOwnGroups() { + fun `group - mixture of accented characters - no separate groups for accented characters`() { val credentials = listOf( creds(title = "A"), creds(title = "Ab"), diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/CredentialInitialExtractorTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/CredentialInitialExtractorTest.kt index 35db9de51a3d..62eb4ae99f21 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/CredentialInitialExtractorTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/CredentialInitialExtractorTest.kt @@ -33,76 +33,76 @@ class CredentialInitialExtractorTest { private val testee = CredentialInitialExtractor(autofillUrlMatcher = AutofillDomainNameUrlMatcher(unicodeNormalizer)) @Test - fun whenMissingTitleAndDomainThenPlaceholderChar() { + fun `extractInitial - missing title and domain - is placeholder char`() { val result = testee.extractInitial(creds(title = null, domain = null)) result.assertIsPlaceholder() } @Test - fun whenEmptyStringTitleAndEmptyStringDomainThenPlaceholderChar() { + fun `extractInitial - empty string title and domain - is placeholder char`() { val result = testee.extractInitial(creds(title = "", domain = "")) result.assertIsPlaceholder() } @Test - fun whenMissingTitleThenDomainInitialUsed() { + fun `extractInitial - missing title - uses domain initial`() { val loginCredentials = creds(title = null, domain = "example.com") val result = testee.extractInitial(loginCredentials) assertEquals("E", result) } @Test - fun whenTitleIsPresentThenTitleInitialIsUsedAndDomainIsIgnored() { + fun `extractInitial - title present - title initial used and domain ignored`() { val loginCredentials = creds(title = "A website", domain = "example.com") val result = testee.extractInitial(loginCredentials) assertEquals("A", result) } @Test - fun whenTitleStartsWithANumberThenPlaceholderUsed() { + fun `extractInitial - title starts with a number - uses placeholder`() { val loginCredentials = creds(title = "123 website") testee.extractInitial(loginCredentials).assertIsPlaceholder() } @Test - fun whenTitleStartsWithASpecialCharacterThenPlaceholderUsed() { + fun `extractInitial - title starts with special character - is placeholder`() { val loginCredentials = creds(title = "$123 website") testee.extractInitial(loginCredentials).assertIsPlaceholder() } @Test - fun whenTitleStartsWithANonLatinLetterThatCannotBeDecomposedThenOriginalLetterIsUsed() { + fun `extractInitial - title starts with non-latin letter that cannot be decomposed - original letter is used`() { val loginCredentials = creds(title = "ß website") assertEquals("ß", testee.extractInitial(loginCredentials)) } @Test - fun whenDomainStartsWithANonLatinLetterThatCannotBeDecomposedThenOriginalLetterIsUsed() { + fun `extractInitial - domain starts with non-latin letter that cannot be decomposed - original letter is used`() { val loginCredentials = creds(title = "ß.com") assertEquals("ß", testee.extractInitial(loginCredentials)) } @Test - fun whenTitleStartsWithAnAccentedLetterThenThatBaseLetterIsUsed() { + fun `extractInitial - title starts with accented letter - uses base letter`() { val loginCredentials = creds(title = "Ça va website") assertEquals("C", testee.extractInitial(loginCredentials)) } @Test - fun whenDomainStartsWithAnAccentedLetterThenThatBaseLetterIsUsed() { + fun `extractInitial - domain starts with accented letter - uses base letter`() { unicodeNormalizer.overrides["ça.com"] = "ca.com" val loginCredentials = creds(domain = "ça.com") assertEquals("C", testee.extractInitial(loginCredentials)) } @Test - fun whenTitleStartsWithANonLatinLetterThenThatLetterIsUsed() { + fun `extractInitial - title starts with non-latin letter - that letter is used`() { val loginCredentials = creds(title = "あ") assertEquals("あ", testee.extractInitial(loginCredentials)) } @Test - fun whenSubdomainIsPresentThenNotUsedForInitialExtraction() { + fun `extractInitial - subdomain present - not used for initial extraction`() { val loginCredentials = creds(domain = "a.example.com") assertEquals("E", testee.extractInitial(loginCredentials)) } diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/CredentialListSorterTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/CredentialListSorterTest.kt index 7a02d9339558..35064f670132 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/CredentialListSorterTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/CredentialListSorterTest.kt @@ -36,13 +36,13 @@ class CredentialListSorterTest { private val list = mutableListOf() @Test - fun whenListIsEmptyThenReturnEmptyList() { + fun `sort - list empty - returns empty list`() { val result = testee.sort(emptyList()) assertTrue(result.isEmpty()) } @Test - fun whenComparingTitlesCaseIsIgnored() { + fun `sort - case ignored - title order asserted`() { val sorted = testee.sort( list.also { it.add(credsWithTitle("C")) @@ -54,7 +54,7 @@ class CredentialListSorterTest { } @Test - fun whenComparingDomainsCaseIsIgnored() { + fun `sort - case ignored - domain order asserted`() { val sorted = testee.sort( list.also { it.add(credsWithDomain("C.COM")) @@ -78,7 +78,7 @@ class CredentialListSorterTest { } @Test - fun whenTitleStartsWithANumberThenSortedBeforeLetters() { + fun `sort - title starts with a number - sorted before letters`() { val sorted = testee.sort( list.also { it.add(credsWithTitle("1")) @@ -91,7 +91,7 @@ class CredentialListSorterTest { } @Test - fun whenTitleStartsWithACharacterThenSortedBeforeLetters() { + fun `sort - title starts with a character - sorted before letters`() { val sorted = testee.sort( list.also { it.add(credsWithTitle("1")) @@ -104,7 +104,7 @@ class CredentialListSorterTest { } @Test - fun whenTitleMissingThenSortedBeforeLetters() { + fun `sort - title missing - sorted before letters`() { val sorted = testee.sort( list.also { it.add(credsWithTitle("A")) @@ -117,7 +117,7 @@ class CredentialListSorterTest { } @Test - fun whenTitlesAllMissingThenDomainUsedInstead() { + fun `sort - titles all missing - domain used instead`() { val sorted = testee.sort( list.also { it.add(credsWithDomain("a.com")) @@ -129,7 +129,7 @@ class CredentialListSorterTest { } @Test - fun whenTitlesEqualThenDomainUsedAsSecondarySort() { + fun `sort - titles equal - domain used as secondary sort`() { val sorted = testee.sort( list.also { it.add(creds("a.com", "Website")) @@ -141,7 +141,7 @@ class CredentialListSorterTest { } @Test - fun whenTitlesDifferThenDomainSortingNotUsed() { + fun `sort - titles differ - domain sorting not used`() { val sorted = testee.sort( list.also { it.add(creds("a.com", "2. Website")) @@ -154,7 +154,7 @@ class CredentialListSorterTest { } @Test - fun whenComparingDomainsThenHttpSchemaIgnored() { + fun `sort - comparing domains - http schema ignored`() { val sorted = testee.sort( list.also { it.add(credsWithDomain("http://b.com")) @@ -165,7 +165,7 @@ class CredentialListSorterTest { } @Test - fun whenComparingDomainsThenHttpsSchemaIgnored() { + fun `sort - comparing domains - https schema ignored`() { val sorted = testee.sort( list.also { it.add(credsWithDomain("https://b.com")) @@ -176,7 +176,7 @@ class CredentialListSorterTest { } @Test - fun whenComparingSubdomainsThenWwwNotTreatedAsSpecialForSorting() { + fun `sort - www not treated as special for sorting`() { val sorted = testee.sort( list.also { it.add(credsWithDomain(id = 0, domain = "www.example.com")) @@ -188,7 +188,7 @@ class CredentialListSorterTest { } @Test - fun whenComparingDomainsThenMissingDomainSortedFirst() { + fun `sort - missing domain sorted first`() { val sorted = testee.sort( list.also { it.add(credsWithDomain("http://b.com")) @@ -200,7 +200,7 @@ class CredentialListSorterTest { } @Test - fun whenComparingDomainsThenInvalidDomainInitialUsedForSort() { + fun `sort - comparing domains - uses initial for sort`() { val sorted = testee.sort( list.also { it.add(credsWithDomain("http://b.com")) @@ -213,7 +213,7 @@ class CredentialListSorterTest { } @Test - fun whenCombinationOfDomainsAndTitlesThenTitlesTakePreferenceWhenTheyExist() { + fun `sort - combination of domains and titles - titles take preference when they exist`() { val credentials = listOf( creds(domain = "energy.com"), creds(domain = "amazon.co.uk", title = "Smile Amazon"), @@ -228,7 +228,7 @@ class CredentialListSorterTest { } @Test - fun whenSpecialCharactersInDomainThenSortedAmongLetters() { + fun `sort - special characters in domain - sorted among letters`() { val sorted = testee.sort( list.also { it.add(credsWithDomain("a.com")) @@ -241,7 +241,7 @@ class CredentialListSorterTest { } @Test - fun whenSpecialCharactersInTitleThenSortedAmongLetters() { + fun `sort - special characters in title - sorted among letters`() { val sorted = testee.sort( list.also { it.add(credsWithTitle("a")) @@ -254,7 +254,7 @@ class CredentialListSorterTest { } @Test - fun whenMultipleSimilarCharactersInTitleThenSortingCorrect() { + fun `sort - multiple similar characters in title - sorting correct`() { val sorted = testee.sort( list.also { it.add(credsWithTitle("a")) @@ -269,7 +269,7 @@ class CredentialListSorterTest { } @Test - fun whenMultipleSimilarCharactersInDomainThenSortingCorrect() { + fun `sort - multiple similar characters in domain - sorting correct`() { val sorted = testee.sort( list.also { it.add(credsWithDomain("a")) @@ -284,7 +284,7 @@ class CredentialListSorterTest { } @Test - fun whenComparingSubdomainsWithSitesFromSameDomainWithoutSubdomainThenTopSiteSortedFirst() { + fun `sort - same domain without subdomain - top site sorted first`() { val sorted = testee.sort( list.also { it.add(credsWithDomain(id = 0, domain = "www.example.com")) @@ -296,7 +296,7 @@ class CredentialListSorterTest { } @Test - fun whenComparingMixtureOfTitlesSitesWithSubdomainsAndSomeWithoutThenCorrectOrder() { + fun `sort - mixture of titles and sites with subdomains - correct order`() { val sorted = testee.sort( list.also { it.add(creds(id = 0, domain = "www.exaaaaample.com")) @@ -311,7 +311,7 @@ class CredentialListSorterTest { } @Test - fun whenDomainsStartWithDecomposableLetterThenIsDecomposedInOrdering() { + fun `sort - domains start with decomposable letter - is decomposed in ordering`() { unicodeNormalizer.overrides["ç.com"] = "c.com" val sorted = testee.sort( list.also { diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/RegexBasedUrlIdentifierTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/RegexBasedUrlIdentifierTest.kt index e5fd35e53876..d436ded946ef 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/RegexBasedUrlIdentifierTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/RegexBasedUrlIdentifierTest.kt @@ -27,32 +27,32 @@ class RegexBasedUrlIdentifierTest { private val testee = RegexBasedUrlIdentifier() @Test - fun whenUrlIsNullThenNotClassedAsUrl() { + fun `isLikelyAUrl - url is null - not classed as url`() { assertFalse(testee.isLikelyAUrl(null)) } @Test - fun whenUrlIsEmptyStringThenNotClassedAsUrl() { + fun `isLikelyAUrl - url is empty string - not classified as url`() { assertFalse(testee.isLikelyAUrl("")) } @Test - fun whenUrlIsBlankStringThenNotClassedAsUrl() { + fun `isLikelyAUrl - url is blank string - not classified as url`() { assertFalse(testee.isLikelyAUrl(" ")) } @Test - fun whenUrlIsAnIpAddressThenIsClassedAsUrl() { + fun `isLikelyAUrl - url is an ip address - classified as url`() { assertTrue(testee.isLikelyAUrl("192.168.1.100")) } @Test - fun whenUrlIsSimpleUrlThenIsClassedAsUrl() { + fun `isLikelyAUrl - simple url - is classified as url`() { assertTrue(testee.isLikelyAUrl("example.com")) } @Test - fun whenUrlHasPortThenIsClassedAsUrl() { + fun `isLikelyAUrl - has port - classified as url`() { assertTrue(testee.isLikelyAUrl("example.com:1234")) } } diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/searching/ManagementScreenAutofillCredentialMatcherTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/searching/ManagementScreenAutofillCredentialMatcherTest.kt index 11cb5a862596..64969371921c 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/searching/ManagementScreenAutofillCredentialMatcherTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/searching/ManagementScreenAutofillCredentialMatcherTest.kt @@ -26,12 +26,12 @@ class ManagementScreenAutofillCredentialMatcherTest { private val testee = ManagementScreenAutofillCredentialMatcher() @Test - fun whenEmptyQueryThenMatchesCredential() = runTest { + fun `matches - empty query - matches credential`() = runTest { assertTrue(testee.matches(creds(), "")) } @Test - fun whenQueryMatchesUsernameThenMatchesCredential() { + fun `matches - query matches username - credential matches`() { val creds = creds(username = "username") assertTrue(testee.matches(creds, "username")) assertTrue(EXPECT_PREFIXES, testee.matches(creds, "user")) @@ -41,13 +41,13 @@ class ManagementScreenAutofillCredentialMatcherTest { } @Test - fun whenQueryMatchesPasswordThenNotAMatch() { + fun `matches - query matches password - not a match`() { val creds = creds(password = "password") assertFalse(testee.matches(creds, "password")) } @Test - fun whenQueryMatchesTitleThenMatchesCredential() { + fun `matches - query matches title - matches credential`() { val creds = creds(title = "title") assertTrue(testee.matches(creds, "title")) assertTrue(EXPECT_PREFIXES, testee.matches(creds, "ti")) @@ -57,7 +57,7 @@ class ManagementScreenAutofillCredentialMatcherTest { } @Test - fun whenQueryMatchesNotesThenMatchesCredential() { + fun `matches - query matches notes - matches credential`() { val creds = creds(notes = "notes") assertTrue(testee.matches(creds, "notes")) assertTrue(EXPECT_PREFIXES, testee.matches(creds, "no")) @@ -67,7 +67,7 @@ class ManagementScreenAutofillCredentialMatcherTest { } @Test - fun whenQueryMatchesDomainThenMatchesCredential() { + fun `matches - query matches domain - credential matches`() { val creds = creds(domain = "example.com") assertTrue(testee.matches(creds, "example.com")) assertTrue(EXPECT_PREFIXES, testee.matches(creds, "exa")) @@ -77,7 +77,7 @@ class ManagementScreenAutofillCredentialMatcherTest { } @Test - fun whenQueryMatchesMultipleFieldsThenMatchesCredential() { + fun `matches - query matches multiple fields - matches credential`() { val creds = creds(domain = "example.com", username = "example", title = "example", notes = "example") assertTrue(testee.matches(creds, "example")) } diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/searching/ManagementScreenCredentialListFilterTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/searching/ManagementScreenCredentialListFilterTest.kt index 986e178bfbf6..9b4e25de59fc 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/searching/ManagementScreenCredentialListFilterTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/searching/ManagementScreenCredentialListFilterTest.kt @@ -28,12 +28,12 @@ class ManagementScreenCredentialListFilterTest { private val testee = ManagementScreenCredentialListFilter(matcher) @Test - fun whenEmptyListAndEmptyQueryThenEmptyListReturned() = runTest { + fun `filter - empty list and query - returns empty list`() = runTest { assertTrue(testee.filter(emptyList(), "").isEmpty()) } @Test - fun whenNonEmptyListAndEmptyQueryThenUnfilteredListReturned() = runTest { + fun `filter - non empty list and empty query - unfiltered list returned`() = runTest { val originalList = listOf( creds(), creds(), @@ -43,7 +43,7 @@ class ManagementScreenCredentialListFilterTest { } @Test - fun whenEmptyListWithAQueryThenEmptyListReturned() = runTest { + fun `filter - empty list - empty list returned`() = runTest { assertTrue(testee.filter(emptyList(), "foo").isEmpty()) } diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/suggestion/SuggestionListBuilderTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/suggestion/SuggestionListBuilderTest.kt index e250569be003..bc05e59fc51f 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/suggestion/SuggestionListBuilderTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/suggestion/SuggestionListBuilderTest.kt @@ -38,68 +38,68 @@ class SuggestionListBuilderTest { ) @Test - fun whenNoSuggestionThenEmptyListReturned() { + fun `build - no suggestion - empty list returned`() { assertTrue(testee.build(emptyList(), emptyList()).isEmpty()) } @Test - fun whenOneDirectSuggestionThenDividerAddedLast() { + fun `build - one direct suggestion - divider added last`() { val suggestions = buildSuggestions(1) val list = testee.build(suggestions, emptyList()) assertTrue(list.last() is ListItem.Divider) } @Test - fun whenTwoDirectSuggestionsThenDividerAddedLast() { + fun `build - two direct suggestions - divider added last`() { val suggestions = buildSuggestions(2) val list = testee.build(suggestions, emptyList()) assertTrue(list.last() is ListItem.Divider) } @Test - fun whenOneDirectSuggestionThenCorrectNumberOfListItemsReturned() { + fun `build - one direct suggestion - correct number of list items returned`() { val suggestions = buildSuggestions(1) val list = testee.build(suggestions, emptyList()) assertEquals(NUM_SUGGESTION_HEADERS + NUM_DIVIDERS + suggestions.size, list.size) } @Test - fun whenTwoDirectSuggestionsThenCorrectNumberOfListItemsReturned() { + fun `build - two direct suggestions - correct number of list items returned`() { val suggestions = buildSuggestions(2) val list = testee.build(suggestions, emptyList()) assertEquals(NUM_SUGGESTION_HEADERS + NUM_DIVIDERS + suggestions.size, list.size) } @Test - fun whenTenDirectSuggestionsThenThirteenListItemsReturned() { + fun `build - ten direct suggestions - thirteen list items returned`() { val suggestions = buildSuggestions(10) val list = testee.build(suggestions, emptyList()) assertEquals(NUM_SUGGESTION_HEADERS + NUM_DIVIDERS + suggestions.size, list.size) } @Test - fun whenDirectSuggestionAddedThenGroupNameIsCorrect() { + fun `build - direct suggestion added - group name correct`() { val suggestions = buildSuggestions(1) val heading = testee.build(suggestions, emptyList()).first() assertTrue(heading is ListItem.GroupHeading) } @Test - fun whenNoDirectSuggestionsButOneShareableThenCorrectNumberOfListItemsReturned() { + fun `build - no direct suggestions but one shareable - correct number of list items returned`() { val suggestions = buildSuggestions(1) val list = testee.build(emptyList(), suggestions) assertEquals(NUM_SUGGESTION_HEADERS + NUM_DIVIDERS + suggestions.size, list.size) } @Test - fun whenNoDirectSuggestionsButMultipleShareableThenCorrectNumberOfListItemsReturned() { + fun `build - no direct suggestions but multiple shareable - correct number of list items returned`() { val suggestions = buildSuggestions(10) val list = testee.build(emptyList(), suggestions) assertEquals(NUM_SUGGESTION_HEADERS + NUM_DIVIDERS + suggestions.size, list.size) } @Test - fun whenOneDirectAndOneShareableThenDirectSuggestionsAppearFirst() { + fun `build - one direct and one shareable - direct suggestions appear first`() { val directSuggestions = buildSuggestions(1) val sharableSuggestions = buildSuggestions(1, startingIndex = directSuggestions.size) val list = testee.build(directSuggestions, sharableSuggestions) @@ -110,7 +110,7 @@ class SuggestionListBuilderTest { } @Test - fun whenMultipleDirectAndSomeShareableThenDirectSuggestionsAppearFirst() { + fun `build - multiple direct and some shareable - direct suggestions appear first`() { val directSuggestions = buildSuggestions(10, isShareable = false) val sharableSuggestions = buildSuggestions(1, isShareable = true, startingIndex = directSuggestions.size) val list = testee.build(directSuggestions, sharableSuggestions) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/suggestion/SuggestionMatcherTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/suggestion/SuggestionMatcherTest.kt index 3ab57af5b79d..efcee6b192e0 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/suggestion/SuggestionMatcherTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/suggestion/SuggestionMatcherTest.kt @@ -41,21 +41,21 @@ class SuggestionMatcherTest { ) @Test - fun whenUrlIsNullThenNoSuggestions() = runTest { + fun `getDirectSuggestions - url is null - no suggestions`() = runTest { configureNoShareableCredentials() val suggestions = testee.getDirectSuggestions(null, listOf()) assertTrue(suggestions.isEmpty()) } @Test - fun whenUrlIsNotNullAndNoCredentialsThenNoSuggestions() = runTest { + fun `getDirectSuggestions - url is not null and no credentials - no suggestions`() = runTest { configureNoShareableCredentials() val suggestions = testee.getDirectSuggestions("https://duckduckgo.com", listOf()) assertTrue(suggestions.isEmpty()) } @Test - fun whenCredentialsAvailableButNotAMatchThenNoSuggestions() = runTest { + fun `getDirectSuggestions - credentials available but not a match - no suggestions`() = runTest { configureNoShareableCredentials() val creds = listOf(creds("https://example.com")) val suggestions = testee.getDirectSuggestions("https://duckduckgo.com", creds) @@ -63,7 +63,7 @@ class SuggestionMatcherTest { } @Test - fun whenCredentialsAvailableWithASingleMatchThenOneSuggestion() = runTest { + fun `getDirectSuggestions - credentials available with a single match - one suggestion`() = runTest { configureNoShareableCredentials() val creds = listOf( creds("https://example.com"), @@ -75,7 +75,7 @@ class SuggestionMatcherTest { } @Test - fun whenCredentialsAvailableWithMultipleMatchesThenMultipleSuggestions() = runTest { + fun `getDirectSuggestions - credentials available with multiple matches - multiple suggestions`() = runTest { configureNoShareableCredentials() val creds = listOf( creds("https://example.com"), @@ -88,7 +88,7 @@ class SuggestionMatcherTest { } @Test - fun whenSubdomainIncludedInSavedSiteAndVisitingRootSiteThenSuggestionOffered() = runTest { + fun `getDirectSuggestions - subdomain included in saved site and visiting root site - suggestion offered`() = runTest { configureNoShareableCredentials() val creds = listOf(creds("https://duckduckgo.com")) val suggestions = testee.getDirectSuggestions("https://test.duckduckgo.com", creds) @@ -96,7 +96,7 @@ class SuggestionMatcherTest { } @Test - fun whenPortIncludedInSavedSiteAndNotInVisitedSiteThenNotASuggestion() = runTest { + fun `getDirectSuggestions - port included in saved site and not visited site - not a suggestion`() = runTest { configureNoShareableCredentials() val creds = listOf(creds("example.com:8080")) val suggestions = testee.getDirectSuggestions("example.com", creds) @@ -104,7 +104,7 @@ class SuggestionMatcherTest { } @Test - fun whenPortIncludedInVisitedSiteAndNotInSavedSiteThenNotASuggestion() = runTest { + fun `getDirectSuggestions - port included in visited site and not in saved site - not a suggestion`() = runTest { configureNoShareableCredentials() val creds = listOf(creds("example.com")) val suggestions = testee.getDirectSuggestions("example.com:8080", creds) @@ -112,7 +112,7 @@ class SuggestionMatcherTest { } @Test - fun whenPortIncludedInVisitedSiteDiffersFromPortInSavedSiteThenNotASuggestion() = runTest { + fun `getDirectSuggestions - port included in visited site differs from port in saved site - not a suggestion`() = runTest { configureNoShareableCredentials() val creds = listOf(creds("example.com:9000")) val suggestions = testee.getDirectSuggestions("example.com:8080", creds) @@ -120,7 +120,7 @@ class SuggestionMatcherTest { } @Test - fun whenPortIncludedInVisitedSiteMatchesPortInSavedSiteThenNotASuggestion() = runTest { + fun `getDirectSuggestions - port included in visited site matches port in saved site - not a suggestion`() = runTest { configureNoShareableCredentials() val creds = listOf(creds("example.com:9000")) val suggestions = testee.getDirectSuggestions("example.com:9000", creds) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/survey/AutofillSurveyImplTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/survey/AutofillSurveyImplTest.kt index 06e4fe0147a0..c2affd86e424 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/survey/AutofillSurveyImplTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/survey/AutofillSurveyImplTest.kt @@ -47,33 +47,33 @@ class AutofillSurveyImplTest { } @Test - fun whenSurveyHasNotBeenShownBeforeThenFirstUnusedSurveyReturnsIt() = runTest { + fun `firstUnusedSurvey - has not been shown before - returns first unused survey`() = runTest { whenever(autofillSurveyStore.hasSurveyBeenTaken("autofill-2024-04-26")).thenReturn(false) val survey = testee.firstUnusedSurvey() assertEquals("autofill-2024-04-26", survey!!.id) } @Test - fun whenSurveyHasNotBeenShownBeforeButLocaleNotEnglishThenFirstUnusedSurveyDoesNotReturnIt() = runTest { + fun `firstUnusedSurvey - survey not shown before - does not return it`() = runTest { whenever(appBuildConfig.deviceLocale).thenReturn(Locale("fr")) whenever(autofillSurveyStore.hasSurveyBeenTaken("autofill-2024-04-26")).thenReturn(false) assertNull(testee.firstUnusedSurvey()) } @Test - fun whenSurveyHasBeenShownBeforeThenFirstUnusedSurveyDoesNotReturnIt() = runTest { + fun `firstUnusedSurvey - survey has been shown before - does not return it`() = runTest { whenever(autofillSurveyStore.hasSurveyBeenTaken("autofill-2024-04-26")).thenReturn(true) assertNull(testee.firstUnusedSurvey()) } @Test - fun whenSurveyRecordedAsUsedThenPersisted() = runTest { + fun `recordSurveyAsUsed - persisted`() = runTest { testee.recordSurveyAsUsed("surveyId-1") verify(autofillSurveyStore).recordSurveyWasShown("surveyId-1") } @Test - fun whenSavedPasswordsLowestInNoneBucketThenCorrectQueryParamValueAdded() = runTest { + fun `getAvailableSurvey - saved passwords lowest in none bucket - correct query param value added`() = runTest { configureCredentialCount(0) val survey = getAvailableSurvey() val savedPasswordsBucket = survey.url.toUri().getQueryParameter("saved_passwords") @@ -81,7 +81,7 @@ class AutofillSurveyImplTest { } @Test - fun whenSavedPasswordsHighestInNoneBucketThenCorrectQueryParamValueAdded() = runTest { + fun `getAvailableSurvey - saved passwords highest in none bucket - correct query param value added`() = runTest { configureCredentialCount(2) val survey = getAvailableSurvey() val savedPasswordsBucket = survey.url.toUri().getQueryParameter("saved_passwords") @@ -89,7 +89,7 @@ class AutofillSurveyImplTest { } @Test - fun whenSavedPasswordsLowestInSomeBucketThenCorrectQueryParamValueAdded() = runTest { + fun `getAvailableSurvey - saved passwords lowest in some bucket - correct query param value added`() = runTest { configureCredentialCount(3) val survey = getAvailableSurvey() val savedPasswordsBucket = survey.url.toUri().getQueryParameter("saved_passwords") @@ -97,7 +97,7 @@ class AutofillSurveyImplTest { } @Test - fun whenSavedPasswordsHighestInSomeBucketThenCorrectQueryParamValueAdded() = runTest { + fun `getAvailableSurvey - saved passwords highest in some bucket - correct query param value added`() = runTest { configureCredentialCount(9) val survey = getAvailableSurvey() val savedPasswordsBucket = survey.url.toUri().getQueryParameter("saved_passwords") @@ -105,7 +105,7 @@ class AutofillSurveyImplTest { } @Test - fun whenSavedPasswordsLowestInManyBucketThenCorrectQueryParamValueAdded() = runTest { + fun `getAvailableSurvey - saved passwords lowest in many bucket - correct query param value added`() = runTest { configureCredentialCount(10) val survey = getAvailableSurvey() val savedPasswordsBucket = survey.url.toUri().getQueryParameter("saved_passwords") @@ -113,7 +113,7 @@ class AutofillSurveyImplTest { } @Test - fun whenSavedPasswordsHighestInManyBucketThenCorrectQueryParamValueAdded() = runTest { + fun `getAvailableSurvey - saved passwords highest in many bucket - correct query param value added`() = runTest { configureCredentialCount(49) val survey = getAvailableSurvey() val savedPasswordsBucket = survey.url.toUri().getQueryParameter("saved_passwords") @@ -121,7 +121,7 @@ class AutofillSurveyImplTest { } @Test - fun whenSavedPasswordsLowestInLotsBucketThenCorrectQueryParamValueAdded() = runTest { + fun `getAvailableSurvey - saved passwords lowest in lots bucket - correct query param value added`() = runTest { configureCredentialCount(50) val survey = getAvailableSurvey() val savedPasswordsBucket = survey.url.toUri().getQueryParameter("saved_passwords") @@ -129,7 +129,7 @@ class AutofillSurveyImplTest { } @Test - fun whenSavedPasswordsIsExtremelyLargeThenCorrectQueryParamValueAdded() = runTest { + fun `getAvailableSurvey - saved passwords extremely large - correct query param value added`() = runTest { configureCredentialCount(Int.MAX_VALUE) val survey = getAvailableSurvey() val savedPasswordsBucket = survey.url.toUri().getQueryParameter("saved_passwords") diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/survey/AutofillSurveyStoreImplTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/survey/AutofillSurveyStoreImplTest.kt index bfb93773d756..2a1a0b70650c 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/survey/AutofillSurveyStoreImplTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/survey/AutofillSurveyStoreImplTest.kt @@ -22,24 +22,24 @@ class AutofillSurveyStoreImplTest { ) @Test - fun whenSurveyIdNeverRecordedBeforeThenReturnsFalse() = runTest { + fun `hasSurveyBeenTaken - survey id never recorded before - returns false`() = runTest { assertFalse(testee.hasSurveyBeenTaken("surveyId-1")) } @Test - fun whenAnotherSurveyIdWasRecordedButNotThisOneThenReturnsFalse() = runTest { + fun `recordSurveyWasShown - has survey been taken - returns false`() = runTest { testee.recordSurveyWasShown("surveyId-1") assertFalse(testee.hasSurveyBeenTaken("surveyId-2")) } @Test - fun whenSurveyRecordedBeforeThenReturnsTrue() = runTest { + fun `recordSurvey - has survey been taken - returns true`() = runTest { testee.recordSurveyWasShown("surveyId-1") assertTrue(testee.hasSurveyBeenTaken("surveyId-1")) } @Test - fun whenMultipleSurveysRecordedAndQueriedOneInListThenReturnsTrue() = runTest { + fun `recordSurveys - has survey been taken - returns true`() = runTest { testee.recordSurveyWasShown("surveyId-1") testee.recordSurveyWasShown("surveyId-2") testee.recordSurveyWasShown("surveyId-3") diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/viewing/duckaddress/RealDuckAddressIdentifierTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/viewing/duckaddress/RealDuckAddressIdentifierTest.kt index b93cee1e1404..3b1229a46155 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/viewing/duckaddress/RealDuckAddressIdentifierTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/management/viewing/duckaddress/RealDuckAddressIdentifierTest.kt @@ -23,32 +23,32 @@ class RealDuckAddressIdentifierTest { private val testee = RealDuckAddressIdentifier() @Test - fun whenInputIsOnlySuffixThenNotAPrivateAddress() { + fun `isPrivateDuckAddress - input is only suffix - not a private address`() { assertFalse(testee.isPrivateDuckAddress("@duck.com", MAIN_ADDRESS)) } @Test - fun whenInputMatchesMainAddressThenNotAPrivateAddress() { + fun `isPrivateDuckAddress - input matches main address - not a private address`() { assertFalse(testee.isPrivateDuckAddress(MAIN_ADDRESS, MAIN_ADDRESS)) } @Test - fun whenInputMatchesMainAddressGivenWithSuffixThenNotAPrivateAddress() { + fun `isPrivateDuckAddress - input matches main address given with suffix - not a private address`() { assertFalse(testee.isPrivateDuckAddress(MAIN_ADDRESS, "test@duck.com")) } @Test - fun whenInputDoesNotEndWithSuffixThenNotAPrivateAddress() { + fun `isPrivateDuckAddress - input does not end with suffix - not a private address`() { assertFalse(testee.isPrivateDuckAddress("test@gmail.com", MAIN_ADDRESS)) } @Test - fun whenMatchesMainAddressExceptInputHasFullAddressAndMainAddressMissingSuffixThenNotAPrivateAddress() { + fun `isPrivateDuckAddress - matches main address except input has full address and main address missing suffix - not a private address`() { assertFalse(testee.isPrivateDuckAddress("test@duck.com", MAIN_ADDRESS)) } @Test - fun whenInputHasDifferentDuckAddressFromMainAddressThenIsAPrivateAddress() { + fun `isPrivateDuckAddress - input has different duck address from main address - is a private address`() { assertTrue(testee.isPrivateDuckAddress("foo@duck.com", MAIN_ADDRESS)) } diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/passwordgeneration/InMemoryAutoSavedLoginsMonitorTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/passwordgeneration/InMemoryAutoSavedLoginsMonitorTest.kt index 11e2a2b0d22e..35b19ffb59d0 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/passwordgeneration/InMemoryAutoSavedLoginsMonitorTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/passwordgeneration/InMemoryAutoSavedLoginsMonitorTest.kt @@ -23,7 +23,7 @@ class InMemoryAutoSavedLoginsMonitorTest { private val testee = InMemoryAutoSavedLoginsMonitor() @Test - fun whenValueSetThenReturnedFromGetFunction() { + fun `setAutoSavedLoginId - get auto saved login id returned`() { val loginId: Long = 1 val tabId = "abc" testee.setAutoSavedLoginId(loginId, tabId) @@ -31,7 +31,7 @@ class InMemoryAutoSavedLoginsMonitorTest { } @Test - fun whenValueSetThenClearedThenNotReturnedFromGetFunction() { + fun `setAutoSavedLoginId - cleared - not returned from get function`() { val loginId: Long = 1 val tabId = "abc" testee.setAutoSavedLoginId(loginId, tabId) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/passwordgeneration/PasswordEventResolverTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/passwordgeneration/PasswordEventResolverTest.kt index 7dda1409a146..473898504116 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/passwordgeneration/PasswordEventResolverTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/passwordgeneration/PasswordEventResolverTest.kt @@ -29,21 +29,21 @@ class PasswordEventResolverTest { private val testee = PasswordEventResolver() @Test - fun whenNoAutoSavedLoginAndNotAutogeneratedCredentialsThenPromptUserToSave() { + fun `decideActions - no auto saved login and not autogen credentials - prompt user to save`() { val autoSavedLogin = null val actions = testee.decideActions(autoSavedLogin, autogenerated = false) actions.assertExpectedActions(PromptToSave) } @Test - fun whenNoAutoSavedLoginAndAutogeneratedCredentialsThenPromptToSave() { + fun `decideActions - no auto saved login and autogen credentials - prompt to save`() { val autoSavedLogin = null val actions = testee.decideActions(autoSavedLogin, autogenerated = true) actions.assertExpectedActions(PromptToSave) } @Test - fun whenAutoSavedLoginAndNotAutogeneratedCredentialsThenDeleteAutoLoginAndDiscardAutoLoginIdAndPromptToSave() { + fun `decideActions - auto saved login and not autogen credentials - delete auto login and discard auto login id and prompt to save`() { val autoSavedLogin = loginCreds(id = 1) val actions = testee.decideActions(autoSavedLogin, autogenerated = false) actions.assertExpectedActions( @@ -54,7 +54,7 @@ class PasswordEventResolverTest { } @Test - fun whenAutoSavedLoginAndAutogeneratedCredentialsThenUpdateSavedLogin() { + fun `decideActions - auto saved login and autogenerated credentials - update saved login`() { val autoSavedLogin = loginCreds(id = 1) val actions = testee.decideActions(autoSavedLogin, autogenerated = true) actions.assertExpectedActions(UpdateSavedAutoLogin(1)) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/passwordgeneration/ResultHandlerUseGeneratedPasswordTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/passwordgeneration/ResultHandlerUseGeneratedPasswordTest.kt index 02cdbe160e3d..702055bd37c3 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/passwordgeneration/ResultHandlerUseGeneratedPasswordTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/passwordgeneration/ResultHandlerUseGeneratedPasswordTest.kt @@ -73,14 +73,14 @@ class ResultHandlerUseGeneratedPasswordTest { } @Test - fun whenUserRejectedToUsePasswordThenCorrectCallbackInvoked() { + fun `processResult - user rejected to use password - correct callback invoked`() { val bundle = bundle("example.com", acceptedGeneratedPassword = false) testee.processResult(bundle, context, "tab-id-123", Fragment(), callback) verify(callback).onRejectGeneratedPassword("example.com") } @Test - fun whenUserAcceptedToUsePasswordNoAutoLoginInThenCorrectCallbackInvoked() = runTest { + fun `processResult - user accepted to use password no auto login in - correct callback invoked`() = runTest { whenever(autoSavedLoginsMonitor.getAutoSavedLoginId(any())).thenReturn(null) val bundle = bundle("example.com", acceptedGeneratedPassword = true, password = "pw") testee.processResult(bundle, context, "tab-id-123", Fragment(), callback) @@ -88,7 +88,7 @@ class ResultHandlerUseGeneratedPasswordTest { } @Test - fun whenUserAcceptedToUsePasswordNoAutoLoginInThenCredentialIsSaved() = runTest { + fun `processResult - user accepted to use password no auto login in - credential is saved`() = runTest { whenever(autoSavedLoginsMonitor.getAutoSavedLoginId(any())).thenReturn(null) val bundle = bundle("example.com", acceptedGeneratedPassword = true, password = "pw") testee.processResult(bundle, context, "tab-id-123", Fragment(), callback) @@ -96,7 +96,7 @@ class ResultHandlerUseGeneratedPasswordTest { } @Test - fun whenUserAcceptedToUsePasswordNoAutoLoginInThenAutoLoginIdUpdated() = runTest { + fun `processResult - user accepted to use password no auto login in - auto login id updated`() = runTest { whenever(autoSavedLoginsMonitor.getAutoSavedLoginId(any())).thenReturn(null) whenever(autofillStore.saveCredentials(any(), any())).thenReturn(aLogin(1)) @@ -106,7 +106,7 @@ class ResultHandlerUseGeneratedPasswordTest { } @Test - fun whenUserAcceptedToUsePasswordAutoLoginIdNotFoundThenLoginSaved() = runTest { + fun `processResult - user accepted to use password auto login id not found - login saved`() = runTest { whenever(autoSavedLoginsMonitor.getAutoSavedLoginId(any())).thenReturn(1) whenever(autofillStore.getCredentialsWithId(1)).thenReturn(null) @@ -116,7 +116,7 @@ class ResultHandlerUseGeneratedPasswordTest { } @Test - fun whenUserAcceptedToUsePasswordAutoLoginIdFoundAndAlreadyMatchesThenNothingSavedOrUpdated() = runTest { + fun `processResult - user accepted to use password auto login id found and already matches - nothing saved or updated`() = runTest { val testLogin = aLogin(id = 1) whenever(autoSavedLoginsMonitor.getAutoSavedLoginId(any())).thenReturn(1) whenever(autofillStore.getCredentialsWithId(1)).thenReturn(testLogin) @@ -133,7 +133,7 @@ class ResultHandlerUseGeneratedPasswordTest { } @Test - fun whenUserAcceptedToUsePasswordAutoLoginIdFoundAndDoesNotMatchUsernameThenUpdated() = runTest { + fun `processResult - user accepted password auto login id found and does not match username - updated`() = runTest { val testLogin = aLogin(id = 1) whenever(autoSavedLoginsMonitor.getAutoSavedLoginId(any())).thenReturn(1) whenever(autofillStore.getCredentialsWithId(1)).thenReturn(testLogin) @@ -150,7 +150,7 @@ class ResultHandlerUseGeneratedPasswordTest { } @Test - fun whenUserAcceptedToUsePasswordAutoLoginIdFoundAndDoesNotMatchPasswordThenUpdated() = runTest { + fun `processResult - user accepted password auto login id found and does not match password - updated`() = runTest { val testLogin = aLogin(id = 1) whenever(autoSavedLoginsMonitor.getAutoSavedLoginId(any())).thenReturn(1) whenever(autofillStore.getCredentialsWithId(1)).thenReturn(testLogin) @@ -167,14 +167,14 @@ class ResultHandlerUseGeneratedPasswordTest { } @Test - fun whenUserAcceptedToUsePasswordButPasswordIsNullThenCorrectCallbackNotInvoked() = runTest { + fun `processResult - user accepted to use password but password is null - correct callback not invoked`() = runTest { val bundle = bundle("example.com", acceptedGeneratedPassword = true, password = null) testee.processResult(bundle, context, "tab-id-123", Fragment(), callback) verify(callback, never()).onAcceptGeneratedPassword("example.com") } @Test - fun whenBundleMissingUrlThenCallbackNotInvoked() = runTest { + fun `processResult - bundle missing url - callback not invoked`() = runTest { val bundle = bundle(url = null, acceptedGeneratedPassword = true) testee.processResult(bundle, context, "tab-id-123", Fragment(), callback) verifyNoInteractions(callback) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/repository/RemoteDuckAddressStatusRepositoryTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/repository/RemoteDuckAddressStatusRepositoryTest.kt index 3d48f1e862b5..af0d5513054f 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/repository/RemoteDuckAddressStatusRepositoryTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/repository/RemoteDuckAddressStatusRepositoryTest.kt @@ -45,14 +45,14 @@ class RemoteDuckAddressStatusRepositoryTest { private val testee = RemoteDuckAddressStatusRepository(service, emailManager, coroutineTestRule.testDispatcherProvider) @Test - fun whenNotSignedIntoEmailProtectionThenReturnTypeIsNotSignedIn() = runTest { + fun `getActivationStatus - email protection not signed in - not signed in`() = runTest { configureEmailProtectionNotSignedIn() val status = testee.getActivationStatus("foo@example.com") assertTrue(status is NotSignedIn) } @Test - fun whenStatusIsDeactivatedThenReturnTypeIsDeactivated() = runTest { + fun `getActivationStatus - status deactivated - deactivated`() = runTest { configureEmailProtectionSignedIn() configureNetworkResponseActivatedIsFalse() val status = testee.getActivationStatus("foo@example.com") @@ -60,7 +60,7 @@ class RemoteDuckAddressStatusRepositoryTest { } @Test - fun whenStatusIsActivatedThenReturnTypeIsActivated() = runTest { + fun `getActivationStatus - status activated - activated`() = runTest { configureEmailProtectionSignedIn() configureNetworkResponseActivatedIsTrue() val status = testee.getActivationStatus("foo@example.com") @@ -68,7 +68,7 @@ class RemoteDuckAddressStatusRepositoryTest { } @Test - fun whenStatusRequestFailsGeneralErrorActivatedThenReturnTypeIsError() = runTest { + fun `getActivationStatus - status request fails general error activated - return type is error`() = runTest { configureEmailProtectionSignedIn() configureNetworkResponseActivatedIsGeneralError() val status = testee.getActivationStatus("foo@example.com") @@ -76,7 +76,7 @@ class RemoteDuckAddressStatusRepositoryTest { } @Test - fun whenStatusRequestFails404ActivatedThenReturnTypeIsUnmanageable() = runTest { + fun `getActivationStatus - status request fails 404 activated - unmanageable`() = runTest { configureEmailProtectionSignedIn() configureNetworkResponseDuckAddressUnmanageable() val status = testee.getActivationStatus("foo@example.com") @@ -84,41 +84,41 @@ class RemoteDuckAddressStatusRepositoryTest { } @Test - fun whenNotSignedAndTryingToUpdateStatusThenReturnFalse() = runTest { + fun `setActivationStatus - not signed in - returns false`() = runTest { configureEmailProtectionNotSignedIn() assertFalse(testee.setActivationStatus("foo@example.com", true)) } @Test - fun whenUpdatingStatusToActivatedAndNewUpdateMatchesThenReturnTrue() = runTest { + fun `setActivationStatus - status updated to activated and new update matches - returns true`() = runTest { configureEmailProtectionSignedIn() configureNetworkResponseAfterSettingStatusToBeActivated() assertTrue(testee.setActivationStatus("foo@example.com", true)) } @Test - fun whenUpdatingStatusToActivatedAndNewUpdateDoesNotMatchThenReturnFalse() = runTest { + fun `setActivationStatus - status updated to activated and new update does not match - returns false`() = runTest { configureEmailProtectionSignedIn() configureNetworkResponseAfterSettingStatusToBeDeactivated() assertFalse(testee.setActivationStatus("foo@example.com", true)) } @Test - fun whenUpdatingStatusToDeactivatedAndNewUpdateMatchesThenReturnTrue() = runTest { + fun `setActivationStatus - status updated to deactivated and new update matches - true`() = runTest { configureEmailProtectionSignedIn() configureNetworkResponseAfterSettingStatusToBeDeactivated() assertTrue(testee.setActivationStatus("foo@example.com", false)) } @Test - fun whenUpdatingStatusAndNewUpdateDoesNotMatchThenReturnFalse() = runTest { + fun `setActivationStatus - status update does not match - returns false`() = runTest { configureEmailProtectionSignedIn() configureNetworkResponseAfterSettingStatusToBeActivated() assertFalse(testee.setActivationStatus("foo@example.com", false)) } @Test - fun whenUpdatingStatusErrorsThenReturnFalse() = runTest { + fun `setActivationStatus - updating status errors - return false`() = runTest { configureEmailProtectionSignedIn() configureNetworkResponseToUpdatingSettingsToError() assertFalse(testee.setActivationStatus("foo@example.com", false)) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/saving/AutofillSavingCredentialsViewModelTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/saving/AutofillSavingCredentialsViewModelTest.kt index ed60ef6f455b..6c04c51bf52b 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/saving/AutofillSavingCredentialsViewModelTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/saving/AutofillSavingCredentialsViewModelTest.kt @@ -42,13 +42,13 @@ class AutofillSavingCredentialsViewModelTest { ).also { it.autofillStore = mockStore } @Test - fun whenUserPromptedToSaveThenFlagSet() = runTest { + fun `userPromptedToSave - store has ever been prompted to save login - true`() = runTest { testee.userPromptedToSaveCredentials() verify(mockStore).hasEverBeenPromptedToSaveLogin = true } @Test - fun whenUserSpecifiesNeverToSaveCurrentSiteThenSitePersisted() = runTest { + fun `addSiteToNeverSaveList - site persisted`() = runTest { val url = "https://example.com" testee.addSiteToNeverSaveList(url) verify(neverSavedSiteRepository).addToNeverSaveList(eq(url)) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/saving/AutofillSavingPixelEventNamesTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/saving/AutofillSavingPixelEventNamesTest.kt index 0763a3a00c77..df515bf4d189 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/saving/AutofillSavingPixelEventNamesTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/saving/AutofillSavingPixelEventNamesTest.kt @@ -36,49 +36,49 @@ import org.junit.Test class AutofillSavingPixelEventNamesTest { @Test - fun whenSavingAcceptedWithUsernameAndPasswordThenCorrectPixelUsed() { + fun `whenSavingAcceptedWithUsernameAndPasswordThenCorrectPixelUsed - pixel used`() { assertEquals(pixelNameDialogAccepted(UsernameAndPassword), AUTOFILL_SAVE_LOGIN_PROMPT_SAVED) } @Test - fun whenSavingAcceptedWithPasswordOnlyThenCorrectPixelUsed() { + fun `whenSavingAcceptedWithPasswordOnlyThenCorrectPixelUsed - pixel used`() { assertEquals(pixelNameDialogAccepted(PasswordOnly), AUTOFILL_SAVE_PASSWORD_PROMPT_SAVED) } @Test - fun whenDialogShownWithUsernameAndPasswordThenCorrectPixelUsed() { + fun `dialogShown - username and password - correct pixel used`() { assertEquals(pixelNameDialogShown(UsernameAndPassword), AUTOFILL_SAVE_LOGIN_PROMPT_SHOWN) } @Test - fun whenDialogShownWithPasswordOnlyThenCorrectPixelUsed() { + fun `dialogShown - password only - correct pixel used`() { assertEquals(pixelNameDialogShown(PasswordOnly), AUTOFILL_SAVE_PASSWORD_PROMPT_SHOWN) } @Test - fun whenDialogDismissedWithUsernameAndPasswordThenCorrectPixelUsed() { + fun `dialogDismissed - username and password - correct pixel used`() { assertEquals(pixelNameDialogDismissed(UsernameAndPassword), AUTOFILL_SAVE_LOGIN_PROMPT_DISMISSED) } @Test - fun whenDialogDismissedWithPasswordOnlyThenCorrectPixelUsed() { + fun `dialogDismissed - password only - correct pixel used`() { assertEquals(pixelNameDialogDismissed(PasswordOnly), AUTOFILL_SAVE_PASSWORD_PROMPT_DISMISSED) } @Test - fun whenUsernameAndPasswordProvidedThenSaveTypeIsUsernameAndPassword() { + fun `loginCredentials - username and password provided - username and password`() { val loginCredentials = loginCredentials(username = "username", password = "password") assertEquals(loginCredentials.saveType(), UsernameAndPassword) } @Test - fun whenUsernameOnlyProvidedThenSaveTypeIsUsernameOnly() { + fun `saveType - username only provided - username only`() { val loginCredentials = loginCredentials(username = "username", password = null) assertEquals(loginCredentials.saveType(), UsernameOnly) } @Test - fun whenPassworldOnlyProvidedThenSaveTypeIsUsernameOnly() { + fun `saveType - password only provided - username only`() { val loginCredentials = loginCredentials(username = null, password = "password") assertEquals(loginCredentials.saveType(), PasswordOnly) } diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/saving/ResultHandlerPromptToDisableCredentialSavingTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/saving/ResultHandlerPromptToDisableCredentialSavingTest.kt index cab176a78f7c..16a5d4406070 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/saving/ResultHandlerPromptToDisableCredentialSavingTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/saving/ResultHandlerPromptToDisableCredentialSavingTest.kt @@ -43,32 +43,32 @@ class ResultHandlerPromptToDisableCredentialSavingTest { ) @Test - fun whenResultProcessedThenFireproofNotifiedDialogNotVisible() { + fun `processResult - fireproof notified dialog not visible`() { val result = bundleForAutofillDisablePrompt() testee.processResult(result, context, "tab-id-123", Fragment(), callback) verify(autofillFireproofDialogSuppressor).autofillSaveOrUpdateDialogVisibilityChanged(false) } @Test - fun whenUserChoosesToDisableAutofillThenStoreUpdatedToFalse() { + fun `onDisableAutofill - store updated to false`() { testee.onDisableAutofill(callback) verify(autofillStore).autofillEnabled = false } @Test - fun whenUserChoosesToDisableAutofillThenDeclineCounterDisabled() = runTest { + fun `onDisableAutofill - decline counter disabled`() = runTest { testee.onDisableAutofill(callback) verify(declineCounter).disableDeclineCounter() } @Test - fun whenUserChoosesToDisableAutofillThenPageRefreshRequested() = runTest { + fun `onDisableAutofill - page refresh requested`() = runTest { testee.onDisableAutofill(callback) verify(callback).onAutofillStateChange() } @Test - fun whenUserChoosesToKeepUsingAutofillThenDeclineCounterDisabled() = runTest { + fun `onKeepUsingAutofill - decline counter disabled`() = runTest { testee.onKeepUsingAutofill() verify(declineCounter).disableDeclineCounter() } diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/saving/ResultHandlerSaveLoginCredentialsTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/saving/ResultHandlerSaveLoginCredentialsTest.kt index ac353e319d1b..9d3f52604d28 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/saving/ResultHandlerSaveLoginCredentialsTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/saving/ResultHandlerSaveLoginCredentialsTest.kt @@ -57,7 +57,7 @@ class ResultHandlerSaveLoginCredentialsTest { ) @Test - fun whenSaveBundleMissingUrlThenNoAttemptToSaveMade() = runTest { + fun `processResult - save bundle missing url - no attempt to save made`() = runTest { val bundle = bundle(url = null, credentials = someLoginCredentials()) testee.processResult(bundle, context, "tab-id-123", Fragment(), callback) verifySaveNeverCalled() @@ -65,7 +65,7 @@ class ResultHandlerSaveLoginCredentialsTest { } @Test - fun whenSaveBundleMissingCredentialsThenNoAttemptToSaveMade() = runTest { + fun `processResult - save bundle missing credentials - no attempt to save made`() = runTest { val bundle = bundle(url = "example.com", credentials = null) testee.processResult(bundle, context, "tab-id-123", Fragment(), callback) verifySaveNeverCalled() @@ -73,7 +73,7 @@ class ResultHandlerSaveLoginCredentialsTest { } @Test - fun whenSaveBundleWellFormedThenCredentialsAreSaved() = runTest { + fun `processResult - save bundle well formed - credentials saved`() = runTest { val loginCredentials = LoginCredentials(domain = "example.com", username = "foo", password = "bar") val bundle = bundle("example.com", loginCredentials) whenever(autofillStore.saveCredentials(any(), any())).thenReturn(loginCredentials) @@ -83,7 +83,7 @@ class ResultHandlerSaveLoginCredentialsTest { } @Test - fun whenSaveCredentialsForFirstTimeThenDisableDeclineCountMonitoringFlag() = runTest { + fun `processResult - save credentials for first time - disable decline count monitoring flag`() = runTest { val loginCredentials = LoginCredentials(domain = "example.com", username = "foo", password = "bar") val bundle = bundle("example.com", loginCredentials) whenever(autofillStore.saveCredentials(any(), any())).thenReturn(loginCredentials) @@ -92,7 +92,7 @@ class ResultHandlerSaveLoginCredentialsTest { } @Test - fun whenSaveCredentialsUnsuccessfulThenDoesNotDisableDeclineCountMonitoringFlag() = runTest { + fun `processResult - save credentials unsuccessful - does not disable decline count monitoring flag`() = runTest { val bundle = bundle("example.com", someLoginCredentials()) whenever(autofillStore.saveCredentials(any(), any())).thenReturn(null) testee.processResult(bundle, context, "tab-id-123", Fragment(), callback) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/saving/declines/AutofillDisablingDeclineCounterTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/saving/declines/AutofillDisablingDeclineCounterTest.kt index 39679d8d4652..4db95a4de99b 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/saving/declines/AutofillDisablingDeclineCounterTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/saving/declines/AutofillDisablingDeclineCounterTest.kt @@ -50,13 +50,13 @@ class AutofillDisablingDeclineCounterTest { } @Test - fun whenInitialisedThenNoPreviouslyStoredDomain() = runTest { + fun `initialiseDeclineCounter - no previously stored domain`() = runTest { initialiseDeclineCounter() assertNull(testee.currentSessionPreviousDeclinedDomain) } @Test - fun whenNotMonitoringDeclineCountsThenShouldNotRecordNewDeclines() = runTest { + fun `monitorDeclineCounts - not monitoring decline counts - should not record new declines`() = runTest { whenever(autofillStore.monitorDeclineCounts).thenReturn(false) initialiseDeclineCounter() @@ -65,7 +65,7 @@ class AutofillDisablingDeclineCounterTest { } @Test - fun whenMonitoringDeclineCountsThenShouldRecordNewDeclines() = runTest { + fun `monitorDeclineCounts - should record new declines`() = runTest { whenever(autofillStore.monitorDeclineCounts).thenReturn(true) initialiseDeclineCounter() @@ -74,7 +74,7 @@ class AutofillDisablingDeclineCounterTest { } @Test - fun whenNewDomainMatchesOldDomainThenDeclineNotRecorded() = runTest { + fun `userDeclinedToSaveCredentials - current session previous declined domain matches old domain - decline not recorded`() = runTest { initialiseDeclineCounter() testee.currentSessionPreviousDeclinedDomain = "example.com" testee.userDeclinedToSaveCredentials("example.com") @@ -82,7 +82,7 @@ class AutofillDisablingDeclineCounterTest { } @Test - fun whenNewDomainDoesNotMatchOldDomainThenDeclineRecorded() = runTest { + fun `userDeclinedToSaveCredentials - current session previous declined domain not matched - decline recorded`() = runTest { initialiseDeclineCounter() testee.currentSessionPreviousDeclinedDomain = "foo.com" testee.userDeclinedToSaveCredentials("example.com") @@ -90,7 +90,7 @@ class AutofillDisablingDeclineCounterTest { } @Test - fun whenDeclineOnNewDomainWithNoPreviousDomainThenDomainStored() = runTest { + fun `userDeclinedToSaveCredentials - domain stored`() = runTest { initialiseDeclineCounter() testee.currentSessionPreviousDeclinedDomain = null testee.userDeclinedToSaveCredentials("example.com") @@ -106,7 +106,7 @@ class AutofillDisablingDeclineCounterTest { } @Test - fun whenDeclineTotalCountBelowThresholdThenShouldNotOfferToDisable() = runTest { + fun `whenDeclineTotalCountBelowThreshold - should not offer to disable - does not prompt`() = runTest { initialiseDeclineCounter() whenever(autofillStore.autofillDeclineCount).thenReturn(0) testee.userDeclinedToSaveCredentials("example.com") @@ -114,7 +114,7 @@ class AutofillDisablingDeclineCounterTest { } @Test - fun whenDeclineIncreasesTotalCountAtThresholdThenShouldOfferToDisable() = runTest { + fun `whenDeclineIncreasesTotalCountAtThresholdThenShouldOfferToDisable - should offer to disable`() = runTest { initialiseDeclineCounter() configureGlobalDeclineCountAtThreshold() testee.userDeclinedToSaveCredentials("a.com") @@ -122,7 +122,7 @@ class AutofillDisablingDeclineCounterTest { } @Test - fun whenCounterNotActiveThenShouldNeverPromptToDisableAutofill() = runTest { + fun `isActive - counter not active - should never prompt to disable autofill`() = runTest { initialiseDeclineCounter() testee.isActive = false configureGlobalDeclineCountAtThreshold() @@ -130,14 +130,14 @@ class AutofillDisablingDeclineCounterTest { } @Test - fun whenAutofillNotAvailableThenCounterNotActive() = runTest { + fun `initialiseDeclineCounter - autofill not available - counter not active`() = runTest { whenever(autofillStore.autofillAvailable).thenReturn(false) initialiseDeclineCounter() assertFalse(testee.isActive) } @Test - fun whenAutofillNotEnabledThenCounterNotActive() = runTest { + fun `initialiseDeclineCounter - autofill not enabled - counter not active`() = runTest { whenever(autofillStore.autofillEnabled).thenReturn(false) initialiseDeclineCounter() assertFalse(testee.isActive) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/selecting/CredentialTextExtractorTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/selecting/CredentialTextExtractorTest.kt index 2ffc9f1b4ef9..53e0a910a168 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/selecting/CredentialTextExtractorTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/selecting/CredentialTextExtractorTest.kt @@ -31,13 +31,13 @@ class CredentialTextExtractorTest { private val testee = CredentialTextExtractor(context) @Test - fun whenMissingUsernameWithDomainPresentThenDomainUsedInString() { + fun `usernameOrPlaceholder - missing username with domain present - uses domain in string`() { val result = testee.usernameOrPlaceholder(missingUsername()) assertEquals("Password for example.com", result) } @Test - fun whenMissingUsernameAndMissingDomainThenPlaceholderUsedString() { + fun `usernameOrPlaceholder - missing username and domain - placeholder used string`() { val result = testee.usernameOrPlaceholder(missingUsernameAndDomain()) assertEquals("Password for site", result) } diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/selecting/LastUpdatedCredentialSorterTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/selecting/LastUpdatedCredentialSorterTest.kt index b05ac8a37b93..33e0574e0d3d 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/selecting/LastUpdatedCredentialSorterTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/selecting/LastUpdatedCredentialSorterTest.kt @@ -9,7 +9,7 @@ class LastUpdatedCredentialSorterTest { private val testee = LastUpdatedCredentialSorter() @Test - fun whenTimestampsAreEqualThen0Returned() { + fun `compare - timestamps equal - 0 returned`() { val login1 = aLogin(lastUpdatedTimestamp = 1) val login2 = aLogin(lastUpdatedTimestamp = 1) val result = testee.compare(login1, login2) @@ -17,7 +17,7 @@ class LastUpdatedCredentialSorterTest { } @Test - fun whenTimestampsAreBothNullThen0Returned() { + fun `compare - timestamps both null - 0 returned`() { val login1 = aLogin(lastUpdatedTimestamp = null) val login2 = aLogin(lastUpdatedTimestamp = null) val result = testee.compare(login1, login2) @@ -25,7 +25,7 @@ class LastUpdatedCredentialSorterTest { } @Test - fun whenLogin1TimestampIsLowerThenSortedBeforeOtherLogin() { + fun `compare - login1 timestamp lower - sorted before other login`() { val login1 = aLogin(lastUpdatedTimestamp = 1) val login2 = aLogin(lastUpdatedTimestamp = 2) val result = testee.compare(login1, login2) @@ -33,7 +33,7 @@ class LastUpdatedCredentialSorterTest { } @Test - fun whenLogin1IsMissingATimestampThenSortedBeforeOtherLogin() { + fun `compare - login missing timestamp - sorted before other login`() { val login1 = aLogin(lastUpdatedTimestamp = null) val login2 = aLogin(lastUpdatedTimestamp = 1) val result = testee.compare(login1, login2) @@ -41,7 +41,7 @@ class LastUpdatedCredentialSorterTest { } @Test - fun whenLogin2TimestampIsLowerThenSortedBeforeOtherLogin() { + fun `compare - login timestamp lower - sorted before other login`() { val login1 = aLogin(lastUpdatedTimestamp = 2) val login2 = aLogin(lastUpdatedTimestamp = 1) val result = testee.compare(login1, login2) @@ -57,21 +57,21 @@ class LastUpdatedCredentialSorterTest { } @Test - fun whenLogin1IsNullThenSortedBeforeOtherLogin() { + fun `compare - login 1 is null - sorted before other login`() { val login2 = aLogin(lastUpdatedTimestamp = null) val result = testee.compare(null, login2) assertEquals(-1, result) } @Test - fun whenLogin2IsNullThenSortedBeforeOtherLogin() { + fun `compare - login 2 is null - sorted before other login`() { val login1 = aLogin(lastUpdatedTimestamp = null) val result = testee.compare(login1, null) assertEquals(1, result) } @Test - fun whenBothLoginsAreNullThenTreatedAsEquals() { + fun `compare - both logins null - equals`() { assertEquals(0, testee.compare(null, null)) } diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/selecting/LastUsedCredentialSorterTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/selecting/LastUsedCredentialSorterTest.kt index 07ce4b40b425..975d0407f4ad 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/selecting/LastUsedCredentialSorterTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/selecting/LastUsedCredentialSorterTest.kt @@ -9,7 +9,7 @@ class LastUsedCredentialSorterTest { private val testee = LastUsedCredentialSorter() @Test - fun whenTimestampsAreEqualThen0Returned() { + fun `compare - timestamps equal - 0 returned`() { val login1 = aLogin(lastUsedTimestamp = 1) val login2 = aLogin(lastUsedTimestamp = 1) val result = testee.compare(login1, login2) @@ -17,7 +17,7 @@ class LastUsedCredentialSorterTest { } @Test - fun whenTimestampsAreBothNullThen0Returned() { + fun `compare - timestamps both null - 0 returned`() { val login1 = aLogin(lastUsedTimestamp = null) val login2 = aLogin(lastUsedTimestamp = null) val result = testee.compare(login1, login2) @@ -25,7 +25,7 @@ class LastUsedCredentialSorterTest { } @Test - fun whenLogin1TimestampIsLowerThenSortedBeforeOtherLogin() { + fun `compare - login1 timestamp lower - sorted before other login`() { val login1 = aLogin(lastUsedTimestamp = 1) val login2 = aLogin(lastUsedTimestamp = 2) val result = testee.compare(login1, login2) @@ -33,7 +33,7 @@ class LastUsedCredentialSorterTest { } @Test - fun whenLogin1IsMissingATimestampThenSortedBeforeOtherLogin() { + fun `compare - login missing timestamp - sorted before other login`() { val login1 = aLogin(lastUsedTimestamp = null) val login2 = aLogin(lastUsedTimestamp = 1) val result = testee.compare(login1, login2) @@ -41,7 +41,7 @@ class LastUsedCredentialSorterTest { } @Test - fun whenLogin2TimestampIsLowerThenSortedBeforeOtherLogin() { + fun `compare - login timestamp lower - sorted before other login`() { val login1 = aLogin(lastUsedTimestamp = 2) val login2 = aLogin(lastUsedTimestamp = 1) val result = testee.compare(login1, login2) @@ -57,21 +57,21 @@ class LastUsedCredentialSorterTest { } @Test - fun whenLogin1IsNullThenSortedBeforeOtherLogin() { + fun `compare - login 1 is null - sorted before other login`() { val login2 = aLogin(lastUsedTimestamp = null) val result = testee.compare(null, login2) assertEquals(-1, result) } @Test - fun whenLogin2IsNullThenSortedBeforeOtherLogin() { + fun `compare - login 2 is null - sorted before other login`() { val login1 = aLogin(lastUsedTimestamp = null) val result = testee.compare(login1, null) assertEquals(1, result) } @Test - fun whenBothLoginsAreNullThenTreatedAsEquals() { + fun `compare - both logins null - equals`() { assertEquals(0, testee.compare(null, null)) } diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/selecting/RealAutofillSelectCredentialsGrouperTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/selecting/RealAutofillSelectCredentialsGrouperTest.kt index ea95974f4f59..5109e74ac33d 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/selecting/RealAutofillSelectCredentialsGrouperTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/selecting/RealAutofillSelectCredentialsGrouperTest.kt @@ -42,7 +42,7 @@ class RealAutofillSelectCredentialsGrouperTest { ) @Test - fun whenOnlyOnePerfectMatchThenCorrectlyGroupedIntoPerfectMatch() { + fun `group - only one perfect match - correctly grouped into perfect match`() { val creds = listOf(creds("example.com")) val grouped = testee.group("example.com", unsortedCredentials = creds) grouped.assertNoPartialMatches() @@ -50,7 +50,7 @@ class RealAutofillSelectCredentialsGrouperTest { } @Test - fun whenMultiplePerfectMatchesThenAllCorrectlyGroupedIntoPerfectMatch() { + fun `group - multiple perfect matches - all correctly grouped into perfect match`() { val creds = listOf(creds("example.com"), creds("example.com")) val grouped = testee.group("example.com", unsortedCredentials = creds) grouped.assertNoPartialMatches() @@ -58,7 +58,7 @@ class RealAutofillSelectCredentialsGrouperTest { } @Test - fun whenNotAMatchThenNotIncludedInGroups() { + fun `group - not a match - not included in groups`() { val creds = listOf(creds("differentDomain.com")) val grouped = testee.group("example.com", unsortedCredentials = creds) grouped.assertNoPartialMatches() @@ -66,7 +66,7 @@ class RealAutofillSelectCredentialsGrouperTest { } @Test - fun whenSinglePartialMatchThenGetsItsOwnGroup() { + fun `group - single partial match - gets its own group`() { val creds = listOf(creds("foo.example.com")) val grouped = testee.group("example.com", unsortedCredentials = creds) grouped.assertNoPerfectMatches() @@ -76,7 +76,7 @@ class RealAutofillSelectCredentialsGrouperTest { } @Test - fun whenMultiplePartialMatchesWithSameSubdomainThenAllShareAGroup() { + fun `group - multiple partial matches with same subdomain - all share a group`() { val creds = listOf(creds("foo.example.com"), creds("foo.example.com")) val grouped = testee.group("example.com", unsortedCredentials = creds) grouped.assertNoPerfectMatches() @@ -86,7 +86,7 @@ class RealAutofillSelectCredentialsGrouperTest { } @Test - fun whenMultipleDifferentPartialMatchesThenEachGetsTheirOwnGroup() { + fun `group - multiple different partial matches - each gets their own group`() { val creds = listOf(creds("foo.example.com"), creds("bar.example.com"), creds("bar.example.com")) val grouped = testee.group("example.com", unsortedCredentials = creds) grouped.assertNoPerfectMatches() @@ -104,7 +104,7 @@ class RealAutofillSelectCredentialsGrouperTest { } @Test - fun whenSortingPerfectMatchesWithNoLastUsedThenLastUpdatedSortedFirst() { + fun `group - sorting perfect matches with no last used - last updated sorted first`() { val creds = listOf( creds(lastUpdated = 100, domain = "example.com"), creds(lastUpdated = 300, domain = "example.com"), @@ -117,7 +117,7 @@ class RealAutofillSelectCredentialsGrouperTest { } @Test - fun whenSortingPerfectMatchesThenLastUsedSortedFirst() { + fun `group - sorting perfect matches - last used sorted first`() { val creds = listOf( creds(lastUsed = 100, domain = "example.com"), creds(lastUsed = 300, domain = "example.com"), @@ -130,7 +130,7 @@ class RealAutofillSelectCredentialsGrouperTest { } @Test - fun whenSortingPartialMatchesWithNoLastUsedThenLastUpdatedSortedFirst() { + fun `group - sorting partial matches with no last used - last updated sorted first`() { val creds = listOf( creds(lastUpdated = 100, domain = "foo.example.com"), creds(lastUpdated = 300, domain = "foo.example.com"), @@ -144,7 +144,7 @@ class RealAutofillSelectCredentialsGrouperTest { } @Test - fun whenSortingPartialMatchesThenLastUpdatedSortedFirst() { + fun `group - sorting partial matches - last updated sorted first`() { val creds = listOf( creds(lastUsed = 100, domain = "foo.example.com"), creds(lastUsed = 300, domain = "foo.example.com"), @@ -158,7 +158,7 @@ class RealAutofillSelectCredentialsGrouperTest { } @Test - fun whenSortingOtherMatchesWithNoLastUsedThenLastUpdatedSortedFirst() { + fun `group - sorting other matches with no last used - last updated sorted first`() { val creds = listOf( creds(lastUpdated = 100, domain = "other.site"), creds(lastUpdated = 300, domain = "other.site"), @@ -172,7 +172,7 @@ class RealAutofillSelectCredentialsGrouperTest { } @Test - fun whenSortingOtherMatchesThenLastUsedSortedFirst() { + fun `group - sorting other matches - last used sorted first`() { val creds = listOf( creds(lastUsed = 100, domain = "other.site"), creds(lastUsed = 300, domain = "other.site"), @@ -186,7 +186,7 @@ class RealAutofillSelectCredentialsGrouperTest { } @Test - fun whenThereShareableCredentialsThenTheyAreGroupedByDomainLikePartialMatches() { + fun `group - shareable credentials grouped by domain like partial matches`() { val creds = listOf( creds(domain = "fill.dev"), // sharable credential creds(domain = "fill.dev"), // sharable credential in the same group as the above diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/selecting/RealAutofillSelectCredentialsListBuilderTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/selecting/RealAutofillSelectCredentialsListBuilderTest.kt index 3fe5beb7c3be..6590fa5723b3 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/selecting/RealAutofillSelectCredentialsListBuilderTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/selecting/RealAutofillSelectCredentialsListBuilderTest.kt @@ -35,7 +35,7 @@ class RealAutofillSelectCredentialsListBuilderTest { private val testee = RealAutofillSelectCredentialsListBuilder(context) @Test - fun whenEmptyInputThenEmptyListOut() { + fun `buildFlatList - empty input - empty list out`() { val sortedGroup = Groups( perfectMatches = listOf(), partialMatches = mapOf(), @@ -45,7 +45,7 @@ class RealAutofillSelectCredentialsListBuilderTest { } @Test - fun whenPerfectMatchAndNoPartialMatchThenFromThisWebsiteLabelOmitted() { + fun `buildFlatList - no partial match - from this website label omitted`() { val sortedGroup = Groups( perfectMatches = listOf(creds()), partialMatches = mapOf(), @@ -56,7 +56,7 @@ class RealAutofillSelectCredentialsListBuilderTest { } @Test - fun whenOnePerfectMatchThenButtonIsPrimaryType() { + fun `buildFlatList - one perfect match - primary button`() { val sortedGroup = Groups( perfectMatches = listOf(creds()), partialMatches = mapOf(), @@ -67,7 +67,7 @@ class RealAutofillSelectCredentialsListBuilderTest { } @Test - fun whenMultiplePerfectMatchesThenFirstButtonOnlyIsPrimaryType() { + fun `buildFlatList - multiple perfect matches - first button only is primary type`() { val sortedGroup = Groups( perfectMatches = listOf(creds(), creds(), creds()), partialMatches = mapOf(), @@ -80,7 +80,7 @@ class RealAutofillSelectCredentialsListBuilderTest { } @Test - fun whenNoPerfectMatchesAndOnePartialMatchThenGroupHeaderAdded() { + fun `buildFlatList - no perfect matches and one partial match - group header added`() { val sortedGroup = Groups( perfectMatches = emptyList(), partialMatches = mapOf( @@ -93,7 +93,7 @@ class RealAutofillSelectCredentialsListBuilderTest { } @Test - fun whenNoPerfectMatchesAndOnePartialMatchThenPartialMatchAddedAsPrimaryButton() { + fun `buildFlatList - no perfect matches and one partial match - partial match added as primary button`() { val sortedGroup = Groups( perfectMatches = emptyList(), partialMatches = mapOf( @@ -106,7 +106,7 @@ class RealAutofillSelectCredentialsListBuilderTest { } @Test - fun whenNoPerfectMatchesAndTwoPartialMatchesInSameDomainThenFirstPartialMatchAddedAsPrimaryButton() { + fun `buildFlatList - no perfect matches and two partial matches in same domain - first partial match added as primary button`() { val sortedGroup = Groups( perfectMatches = emptyList(), partialMatches = mapOf( @@ -120,7 +120,7 @@ class RealAutofillSelectCredentialsListBuilderTest { } @Test - fun whenPerfectMatchesAndPartialMatchesThenFromThisWebsiteLabelShown() { + fun `buildFlatList - perfect and partial matches - from this website label shown`() { val sortedGroup = Groups( perfectMatches = listOf(creds()), partialMatches = mapOf( @@ -134,7 +134,7 @@ class RealAutofillSelectCredentialsListBuilderTest { } @Test - fun whenPerfectMatchesAndOnePartialMatchThenPartialMatchAddedAsSecondaryButton() { + fun `buildFlatList - perfect matches and one partial match - partial match added as secondary button`() { val sortedGroup = Groups( perfectMatches = listOf(creds()), partialMatches = mapOf( @@ -147,7 +147,7 @@ class RealAutofillSelectCredentialsListBuilderTest { } @Test - fun whenNoPerfectMatchesAndMultiplePartialMatchesAcrossSitesThenFirstPartialMatchAddedAsPrimaryButton() { + fun `buildFlatList - no perfect matches and multiple partial matches across sites - first partial match added as primary button`() { val sortedGroup = Groups( perfectMatches = emptyList(), partialMatches = mapOf( @@ -164,7 +164,7 @@ class RealAutofillSelectCredentialsListBuilderTest { } @Test - fun whenPerfectMatchesAndMultiplePartialMatchesThenListOutputAsExpected() { + fun `buildFlatList - perfect matches and multiple partial matches - as expected`() { val sortedGroup = Groups( perfectMatches = listOf(creds(), creds()), partialMatches = mapOf( diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/selecting/ResultHandlerCredentialSelectionTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/selecting/ResultHandlerCredentialSelectionTest.kt index 18f29ff7b9f4..f641fb858a40 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/selecting/ResultHandlerCredentialSelectionTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/selecting/ResultHandlerCredentialSelectionTest.kt @@ -65,7 +65,7 @@ class ResultHandlerCredentialSelectionTest { } @Test - fun whenUserRejectedToUseCredentialThenCorrectCallbackInvoked() = runTest { + fun `processResult - user rejected to use credential - correct callback invoked`() = runTest { configureSuccessfulAuth() val bundle = bundleForUserCancelling("example.com") testee.processResult(bundle, context, "tab-id-123", Fragment(), callback) @@ -73,7 +73,7 @@ class ResultHandlerCredentialSelectionTest { } @Test - fun whenUserAcceptedToUseCredentialsAndSuccessfullyAuthenticatedThenCorrectCallbackInvoked() = runTest { + fun `processResult - user accepted to use credentials and successfully authenticated - correct callback invoked`() = runTest { configureSuccessfulAuth() val bundle = bundleForUserAcceptingToAutofill("example.com") testee.processResult(bundle, context, "tab-id-123", Fragment(), callback) @@ -81,7 +81,7 @@ class ResultHandlerCredentialSelectionTest { } @Test - fun whenUserAcceptedToUseCredentialsAndCancelsAuthenticationThenCorrectCallbackInvoked() = runTest { + fun `processResult - user accepted to use credentials and cancels authentication - correct callback invoked`() = runTest { configureCancelledAuth() val bundle = bundleForUserAcceptingToAutofill("example.com") testee.processResult(bundle, context, "tab-id-123", Fragment(), callback) @@ -89,7 +89,7 @@ class ResultHandlerCredentialSelectionTest { } @Test - fun whenUserAcceptedToUseCredentialsAndAuthenticationFailsThenCorrectCallbackInvoked() = runTest { + fun `processResult - user accepted to use credentials and authentication fails - on no credentials chosen for autofill`() = runTest { configureFailedAuth() val bundle = bundleForUserAcceptingToAutofill("example.com") testee.processResult(bundle, context, "tab-id-123", Fragment(), callback) @@ -97,7 +97,7 @@ class ResultHandlerCredentialSelectionTest { } @Test - fun whenUserAcceptedToUseCredentialsButMissingInBundleThenNoCallbackInvoked() = runTest { + fun `processResult - user accepted to use credentials but missing in bundle - no callback invoked`() = runTest { configureSuccessfulAuth() val bundle = bundleMissingCredentials("example.com") testee.processResult(bundle, context, "tab-id-123", Fragment(), callback) @@ -105,7 +105,7 @@ class ResultHandlerCredentialSelectionTest { } @Test - fun whenMissingUrlThenNoCallbackInvoked() = runTest { + fun `processResult - missing url - no callback invoked`() = runTest { configureSuccessfulAuth() val bundle = bundleMissingUrl() testee.processResult(bundle, context, "tab-id-123", Fragment(), callback) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/updating/AutofillUpdatingExistingCredentialViewModelTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/updating/AutofillUpdatingExistingCredentialViewModelTest.kt index 67b5207af4ff..c08215f12863 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/updating/AutofillUpdatingExistingCredentialViewModelTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/updating/AutofillUpdatingExistingCredentialViewModelTest.kt @@ -26,14 +26,14 @@ class AutofillUpdatingExistingCredentialViewModelTest { private val testee = AutofillUpdatingExistingCredentialViewModel() @Test - fun whenUsernameIsShortThenNoEllipsizing() { + fun `ellipsizeIfNecessary - username short - no ellipsizing`() { val result = testee.ellipsizeIfNecessary("foo") result.assertDoesNotEndInEllipsis() assertEquals("foo", result) } @Test - fun whenUsernameIsExactlyOnLimitThenNoEllipsizing() { + fun `ellipsizeIfNecessary - username exactly as long as limit - no ellipsizing`() { val usernameExactlyAsLongAsLimit = "A".repeat(50) val result = testee.ellipsizeIfNecessary(usernameExactlyAsLongAsLimit) result.assertDoesNotEndInEllipsis() @@ -41,7 +41,7 @@ class AutofillUpdatingExistingCredentialViewModelTest { } @Test - fun whenUsernameIsLongerThanLimitThenEllipsizing() { + fun `ellipsizeIfNecessary - username longer than limit - ellipsized`() { val usernameLongerThanLimit = "A".repeat(51) val result = testee.ellipsizeIfNecessary(usernameLongerThanLimit) result.assertEndsInEllipsis() diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/updating/ResultHandlerUpdateLoginCredentialsTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/updating/ResultHandlerUpdateLoginCredentialsTest.kt index 8d9b3c36c206..dd0c6753b5ad 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/updating/ResultHandlerUpdateLoginCredentialsTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/ui/credential/updating/ResultHandlerUpdateLoginCredentialsTest.kt @@ -56,7 +56,7 @@ class ResultHandlerUpdateLoginCredentialsTest { ) @Test - fun whenUpdateBundleMissingUrlThenNoAttemptToUpdateMade() = runTest { + fun `processBundle - update bundle missing URL - no attempt to update made`() = runTest { val bundle = bundleForUpdateDialog( url = null, credentials = someLoginCredentials(), @@ -67,7 +67,7 @@ class ResultHandlerUpdateLoginCredentialsTest { } @Test - fun whenUpdateBundleMissingCredentialsThenNoAttemptToSaveMade() = runTest { + fun `processBundle - update bundle missing credentials - no attempt to save made`() = runTest { val bundle = bundleForUpdateDialog(url = "example.com", credentials = null, Password) testee.processResult(bundle, context, "tab-id-123", Fragment(), callback) @@ -75,7 +75,7 @@ class ResultHandlerUpdateLoginCredentialsTest { } @Test - fun whenUpdateBundleWellFormedThenCredentialsAreUpdated() = runTest { + fun `processResult - update bundle well formed - credentials updated`() = runTest { val loginCredentials = LoginCredentials(domain = "example.com", username = "foo", password = "bar") val bundle = bundleForUpdateDialog("example.com", loginCredentials, Password) testee.processResult(bundle, context, "tab-id-123", Fragment(), callback) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/urlmatcher/AutofillDomainNameUrlMatcherTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/urlmatcher/AutofillDomainNameUrlMatcherTest.kt index fed68f4326ae..4ac9f6112754 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/urlmatcher/AutofillDomainNameUrlMatcherTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/urlmatcher/AutofillDomainNameUrlMatcherTest.kt @@ -32,98 +32,98 @@ class AutofillDomainNameUrlMatcherTest { private val testee = AutofillDomainNameUrlMatcher(TestUrlUnicodeNormalizer()) @Test - fun whenBasicDomainThenSameReturnedForEtldPlus1() { + fun `extractUrlPartsForAutofill - basic domain - same returned for eTLD plus 1`() { val inputUrl = "duckduckgo.com" val result = testee.extractUrlPartsForAutofill(inputUrl) assertEquals(inputUrl, result.eTldPlus1) } @Test - fun whenUrlIsInvalidMissingTldThenEtldPlusOneIsNull() { + fun `extractUrlPartsForAutofill - url is invalid missing tld - etld plus one null`() { val inputUrl = "duckduckgo" val result = testee.extractUrlPartsForAutofill(inputUrl) assertNull(result.eTldPlus1) } @Test - fun whenUrlIsInvalidMissingTldThenSubdomainIsNull() { + fun `extractUrlPartsForAutofill - url is invalid missing tld - subdomain is null`() { val inputUrl = "duckduckgo" val result = testee.extractUrlPartsForAutofill(inputUrl) assertNull(result.subdomain) } @Test - fun whenContainsHttpSchemeThenEtldPlus1Returned() { + fun `extractUrlPartsForAutofill - contains http scheme - etld plus 1 returned`() { val inputUrl = "http://duckduckgo.com" val result = testee.extractUrlPartsForAutofill(inputUrl) assertEquals("duckduckgo.com", result.eTldPlus1) } @Test - fun whenContainsHttpsSchemeThenEtldPlus1Returned() { + fun `extractUrlPartsForAutofill - contains https scheme - eTldPlus1 returned`() { val inputUrl = "https://duckduckgo.com" val result = testee.extractUrlPartsForAutofill(inputUrl) assertEquals("duckduckgo.com", result.eTldPlus1) } @Test - fun whenContainsWwwSubdomainThenEtldPlus1Returned() { + fun `extractUrlPartsForAutofill - contains www subdomain - etld plus 1 returned`() { val inputUrl = "www.duckduckgo.com" val result = testee.extractUrlPartsForAutofill(inputUrl) assertEquals("duckduckgo.com", result.eTldPlus1) } @Test - fun whenContainsAnotherSubdomainThenEtldPlus1Returned() { + fun `extractUrlPartsForAutofill - contains another subdomain - eTLD plus 1 returned`() { val inputUrl = "foo.duckduckgo.com" val result = testee.extractUrlPartsForAutofill(inputUrl) assertEquals("duckduckgo.com", result.eTldPlus1) } @Test - fun whenTwoPartTldWithNoSubdomainThenEtldPlus1Returned() { + fun `extractUrlPartsForAutofill - no subdomain - etld plus 1 returned`() { val inputUrl = "duckduckgo.co.uk" val result = testee.extractUrlPartsForAutofill(inputUrl) assertEquals("duckduckgo.co.uk", result.eTldPlus1) } @Test - fun whenTwoPartTldWithSubdomainThenEtldPlus1Returned() { + fun `extractUrlPartsForAutofill - two part tld with subdomain - etld plus 1 returned`() { val inputUrl = "www.duckduckgo.co.uk" val result = testee.extractUrlPartsForAutofill(inputUrl) assertEquals("duckduckgo.co.uk", result.eTldPlus1) } @Test - fun whenSubdomainIsWwwThenCorrectlyIdentifiedAsSubdomain() { + fun `extractUrlPartsForAutofill - subdomain www - correctly identified as subdomain`() { val inputUrl = "www.duckduckgo.co.uk" val result = testee.extractUrlPartsForAutofill(inputUrl) assertEquals("www", result.subdomain) } @Test - fun whenSubdomainIsPresentButNotWwwThenCorrectlyIdentifiedAsSubdomain() { + fun `extractUrlPartsForAutofill - subdomain present but not www - correctly identified as subdomain`() { val inputUrl = "test.duckduckgo.co.uk" val result = testee.extractUrlPartsForAutofill(inputUrl) assertEquals("test", result.subdomain) } @Test - fun whenSubdomainHasTwoLevelsThenCorrectlyIdentifiedAsSubdomain() { + fun `extractUrlPartsForAutofill - subdomain has two levels - correctly identified as subdomain`() { val inputUrl = "foo.bar.duckduckgo.co.uk" val result = testee.extractUrlPartsForAutofill(inputUrl) assertEquals("foo.bar", result.subdomain) } @Test - fun whenUrlsAreIdenticalThenMatchingForAutofill() { + fun `extractUrlPartsForAutofill - matching for autofill`() { val savedSite = testee.extractUrlPartsForAutofill("https://example.com") val visitedSite = testee.extractUrlPartsForAutofill("https://example.com") assertTrue(testee.matchingForAutofill(visitedSite, savedSite)) } @Test - fun whenUrlsAreIdenticalExceptForUppercaseVisitedSiteThenMatchingForAutofill() { + fun `extractUrlPartsForAutofill - matching for autofill - true`() { val savedSite = testee.extractUrlPartsForAutofill("https://example.com") val visitedSite = testee.extractUrlPartsForAutofill("https://EXAMPLE.com") assertTrue(testee.matchingForAutofill(visitedSite, savedSite)) @@ -179,35 +179,35 @@ class AutofillDomainNameUrlMatcherTest { } @Test - fun whenSavedSiteMatchesVisitedExceptForPortThenNotMatchingForAutofill() { + fun `matchingForAutofill - saved site matches visited except for port - not matching for autofill`() { val savedSite = ExtractedUrlParts(eTldPlus1 = "example.com", userFacingETldPlus1 = "example.com", subdomain = null, port = 8000) val visitedSite = ExtractedUrlParts(eTldPlus1 = "example.com", userFacingETldPlus1 = "example.com", subdomain = null, port = 1000) assertFalse(testee.matchingForAutofill(visitedSite, savedSite)) } @Test - fun whenSavedSiteMatchesVisitedAndEqualPortsThenMatchingForAutofill() { + fun `matchingForAutofill - saved site matches visited and equal ports - matching for autofill`() { val savedSite = ExtractedUrlParts(eTldPlus1 = "example.com", userFacingETldPlus1 = "example.com", subdomain = null, port = 8000) val visitedSite = ExtractedUrlParts(eTldPlus1 = "example.com", userFacingETldPlus1 = "example.com", subdomain = null, port = 8000) assertTrue(testee.matchingForAutofill(visitedSite, savedSite)) } @Test - fun whenSavedSiteMatchesVisitedAndSavedSiteMissingPortThenNotMatchingForAutofill() { + fun `matchingForAutofill - saved site missing port - not matching for autofill`() { val savedSite = ExtractedUrlParts(eTldPlus1 = "example.com", userFacingETldPlus1 = "example.com", subdomain = null, port = null) val visitedSite = ExtractedUrlParts(eTldPlus1 = "example.com", userFacingETldPlus1 = "example.com", subdomain = null, port = 8000) assertFalse(testee.matchingForAutofill(visitedSite, savedSite)) } @Test - fun whenSavedSiteMatchesVisitedAndVisitedSiteMissingPortThenNotMatchingForAutofill() { + fun `matchingForAutofill - saved site matches visited and visited site missing port - not matching for autofill`() { val savedSite = ExtractedUrlParts(eTldPlus1 = "example.com", userFacingETldPlus1 = "example.com", subdomain = null, port = 8000) val visitedSite = ExtractedUrlParts(eTldPlus1 = "example.com", userFacingETldPlus1 = "example.com", subdomain = null, port = null) assertFalse(testee.matchingForAutofill(visitedSite, savedSite)) } @Test - fun whenSavedSiteContainsUppercaseWwwSubdomainAndVisitedSiteDoesNotThenMatchingForAutofill() { + fun `extractUrlPartsForAutofill - site does not match - matching for autofill`() { val savedSite = testee.extractUrlPartsForAutofill("WWW.example.com") val visitedSite = testee.extractUrlPartsForAutofill("example.com") assertTrue(testee.matchingForAutofill(visitedSite, savedSite)) @@ -221,7 +221,7 @@ class AutofillDomainNameUrlMatcherTest { } @Test - fun whenSavedSiteDoesNotContainSubdomainAndVisitedSiteDoesContainUppercaseWwwSubdomainThenMatchingForAutofill() { + fun `extractUrlPartsForAutofill - site does not contain subdomain and site contains uppercase www subdomain - matching for autofill`() { val savedSite = testee.extractUrlPartsForAutofill("example.com") val visitedSite = testee.extractUrlPartsForAutofill("WWW.example.com") assertTrue(testee.matchingForAutofill(visitedSite, savedSite)) @@ -242,21 +242,21 @@ class AutofillDomainNameUrlMatcherTest { } @Test - fun whenSavedSiteHasNoSubdomainAndVisitedMaliciousSitePartiallyContainSavedSiteThenNoMatchingForAutofill() { + fun `extractUrlPartsForAutofill - no matching for autofill`() { val savedSite = testee.extractUrlPartsForAutofill("example.com") val visitedSite = testee.extractUrlPartsForAutofill("example.com.malicious.com") assertFalse(testee.matchingForAutofill(visitedSite, savedSite)) } @Test - fun whenSavedMaliciousSitePartiallyContainsVisitedSiteThenNoMatchingForAutofill() { + fun `extractUrlPartsForAutofill - matching for autofill - no match`() { val savedSite = testee.extractUrlPartsForAutofill("example.com.malicious.com") val visitedSite = testee.extractUrlPartsForAutofill("example.com") assertFalse(testee.matchingForAutofill(visitedSite, savedSite)) } @Test - fun whenCleanRawUrlThenReturnOnlySchemeAndDomain() { + fun `cleanRawUrl - return only scheme and domain`() { assertEquals("www.foo.com", testee.cleanRawUrl("https://www.foo.com/path/to/foo?key=value")) assertEquals("www.fuu.foo.com", testee.cleanRawUrl("https://www.fuu.foo.com/path/to/foo?key=value")) assertEquals("foo.com", testee.cleanRawUrl("http://foo.com/path/to/foo?key=value")) @@ -278,7 +278,7 @@ class AutofillDomainNameUrlMatcherTest { } @Test - fun whenDomainContainsValidNonAsciiCharactersThenETldPlusOnePunycodeEncoded() { + fun `extractUrlPartsForAutofill - domain contains valid non ascii characters - eTLD plus one punycode encoded`() { assertEquals("xn--a-5fa.com", testee.extractUrlPartsForAutofill("ça.com").eTldPlus1) assertEquals("xn--a-5fa.com", testee.extractUrlPartsForAutofill("https://ça.com").eTldPlus1) } diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/store/RealAutofillPrefsStoreTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/store/RealAutofillPrefsStoreTest.kt index 812ce89cdda3..9bfa782d8586 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/store/RealAutofillPrefsStoreTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/store/RealAutofillPrefsStoreTest.kt @@ -26,27 +26,27 @@ class RealAutofillPrefsStoreTest { ) @Test - fun whenAutofillStateNeverSetManuallyThenDefaultStateDeciderUsed() { + fun `isEnabled - autofill state never set manually - default state decider used`() { testee.isEnabled verify(defaultStateDecider).defaultState() } @Test - fun whenAutofillStateWasManuallySetToEnabledThenDefaultStateDeciderNotUsed() { + fun `whenAutofillStateWasManuallySetToEnabled - default state decider not used`() { testee.isEnabled = true testee.isEnabled verify(defaultStateDecider, never()).defaultState() } @Test - fun whenAutofillStateWasManuallySetToDisabledThenDefaultStateDeciderNotUsed() { + fun `whenAutofillStateWasManuallySetToDisabled - default state decider not used`() { testee.isEnabled = false testee.isEnabled verify(defaultStateDecider, never()).defaultState() } @Test - fun whenDeterminedEnabledByDefaultOnceThenNotDecidedAgain() { + fun `whenDeterminedEnabledByDefaultOnceThenNotDecidedAgain - default state decided - enabled`() { // first call will decide default state should be enabled whenever(defaultStateDecider.defaultState()).thenReturn(true) assertTrue(testee.isEnabled) @@ -58,7 +58,7 @@ class RealAutofillPrefsStoreTest { } @Test - fun whenDeterminedNotEnabledByDefaultOnceThenWillCallToDeciderAgain() { + fun `whenDeterminedNotEnabledByDefaultOnce - will call to decider again`() { // first call will decide default state should not be enabled whenever(defaultStateDecider.defaultState()).thenReturn(false) assertFalse(testee.isEnabled) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/store/feature/RealAutofillDefaultStateDeciderTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/store/feature/RealAutofillDefaultStateDeciderTest.kt index 2d9ae1b24003..81fdb1df8108 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/store/feature/RealAutofillDefaultStateDeciderTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/store/feature/RealAutofillDefaultStateDeciderTest.kt @@ -20,7 +20,7 @@ class RealAutofillDefaultStateDeciderTest { ) @Test - fun whenRemoteFeatureDisabledThenNumberOfDaysInstalledIsIrrelevant() { + fun `whenRemoteFeatureDisabled - default state irrelevant`() { configureRemoteFeatureEnabled(false) configureDaysInstalled(0) @@ -31,7 +31,7 @@ class RealAutofillDefaultStateDeciderTest { } @Test - fun whenNumberOfDaysInstalledIsNotZeroThenFeatureFlagIsIrrelevant() { + fun `defaultState - numberOfDaysInstalled not zero - irrelevant feature flag`() { configureDaysInstalled(0) configureRemoteFeatureEnabled(false) @@ -42,7 +42,7 @@ class RealAutofillDefaultStateDeciderTest { } @Test - fun whenInternalTesterThenAlwaysEnabledByDefault() { + fun `configureAsInternalTester - default state always enabled`() { configureDaysInstalled(100) configureRemoteFeatureEnabled(false) configureAsInternalTester() @@ -50,7 +50,7 @@ class RealAutofillDefaultStateDeciderTest { } @Test - fun whenInstalledSameDayAndFeatureFlagEnabledThenEnabledByDefault() { + fun `defaultState - installed same day and feature flag enabled - enabled by default`() { configureDaysInstalled(0) configureRemoteFeatureEnabled(true) assertTrue(testee.defaultState()) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/AppCredentialsSyncFeatureListenerTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/AppCredentialsSyncFeatureListenerTest.kt index 725de4424cf9..e8750fd41a2a 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/AppCredentialsSyncFeatureListenerTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/AppCredentialsSyncFeatureListenerTest.kt @@ -55,12 +55,12 @@ class AppCredentialsSyncFeatureListenerTest { ) @Test - fun whenNoValuesThenIsSyncPausedIsFalse() { + fun `isSyncPaused - no values - is false`() { assertFalse(credentialsSyncStore.isSyncPaused) } @Test - fun whenSyncPausedAndOnSuccessWithChangesThenIsSyncPausedIsFalse() { + fun `onSuccess - is sync paused false`() { credentialsSyncStore.isSyncPaused = true val updatesJSON = FileUtilities.loadText(javaClass.classLoader!!, "json/sync/merger_first_get.json") val validChanges = SyncChangesResponse(CREDENTIALS, updatesJSON) @@ -71,7 +71,7 @@ class AppCredentialsSyncFeatureListenerTest { } @Test - fun whenSyncPausedAndOnSuccessWithoutChangesThenSyncPaused() { + fun `onSuccess - sync paused and no changes - sync paused`() { credentialsSyncStore.isSyncPaused = true val validChanges = SyncChangesResponse.empty(BOOKMARKS) @@ -81,7 +81,7 @@ class AppCredentialsSyncFeatureListenerTest { } @Test - fun whenSyncPausedAndOnErrorThenSyncPaused() { + fun `onError - sync paused - still sync paused`() { credentialsSyncStore.isSyncPaused = true testee.onError(FeatureSyncError.COLLECTION_LIMIT_REACHED) @@ -90,7 +90,7 @@ class AppCredentialsSyncFeatureListenerTest { } @Test - fun whenSyncActiveAndOnErrorThenSyncPaused() { + fun `sync - active and on error - sync paused`() { credentialsSyncStore.isSyncPaused = false testee.onError(FeatureSyncError.COLLECTION_LIMIT_REACHED) @@ -99,7 +99,7 @@ class AppCredentialsSyncFeatureListenerTest { } @Test - fun whenOnSyncDisabledThenSyncPausedFalse() { + fun `onSyncDisabled - sync paused false`() { credentialsSyncStore.isSyncPaused = true testee.onSyncDisabled() diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/CredentialsInvalidItemsViewModelTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/CredentialsInvalidItemsViewModelTest.kt index 04febcb4f57f..5a7d9a827ada 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/CredentialsInvalidItemsViewModelTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/CredentialsInvalidItemsViewModelTest.kt @@ -55,7 +55,7 @@ class CredentialsInvalidItemsViewModelTest { ) @Test - fun whenNoInvalidCredentialsThenWarningNotVisible() = runTest { + fun `viewState - no invalid credentials - warning not visible`() = runTest { viewModel.viewState().test { val awaitItem = awaitItem() assertFalse(awaitItem.warningVisible) @@ -65,7 +65,7 @@ class CredentialsInvalidItemsViewModelTest { } @Test - fun whenInvalidCredentialsThenWarningVisible() = runTest { + fun `getUpdatesSince - view state updated - warning visible`() = runTest { credentialsSync.saveCredential(invalidCredentials, "remote1") credentialsSync.saveCredential(spotifyCredentials, "remote2") credentialsSync.getUpdatesSince("0") // trigger sync so invalid credentials are detected diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/CredentialsRateLimitViewModelTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/CredentialsRateLimitViewModelTest.kt index 306a2f76b64c..eed59d135ddd 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/CredentialsRateLimitViewModelTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/CredentialsRateLimitViewModelTest.kt @@ -41,7 +41,7 @@ class CredentialsRateLimitViewModelTest { ) @Test - fun whenSyncPausedThenWarningVisible() = runTest { + fun `viewState - sync paused - warning visible`() = runTest { credentialsSyncStore.isSyncPaused = true testee.viewState().test { assertTrue(awaitItem().warningVisible) @@ -50,7 +50,7 @@ class CredentialsRateLimitViewModelTest { } @Test - fun whenUserClicksWarningActionThenNavigateToBookmarks() = runTest { + fun `onWarningActionClicked - navigate to bookmarks`() = runTest { testee.commands().test { testee.onWarningActionClicked() assertEquals(NavigateToCredentials, awaitItem()) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/CredentialsSyncDataPersisterTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/CredentialsSyncDataPersisterTest.kt index 6301d7361b70..0e01a4ccc096 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/CredentialsSyncDataPersisterTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/CredentialsSyncDataPersisterTest.kt @@ -82,7 +82,7 @@ internal class CredentialsSyncDataPersisterTest { } @Test - fun whenValidatingCorruptedDataThenResultIsError() { + fun `onSuccess - validating corrupted data - error`() { val updatesJSON = FileUtilities.loadText(javaClass.classLoader!!, "json/sync/merger_invalid_data.json") val corruptedChanges = SyncChangesResponse(CREDENTIALS, updatesJSON) val result = syncPersister.onSuccess(corruptedChanges, TIMESTAMP) @@ -91,7 +91,7 @@ internal class CredentialsSyncDataPersisterTest { } @Test - fun whenValidatingNullEntriesThenResultIsError() { + fun `onSuccess - null entries - error`() { val updatesJSON = FileUtilities.loadText(javaClass.classLoader!!, "json/sync/merger_null_entries.json") val corruptedChanges = SyncChangesResponse(CREDENTIALS, updatesJSON) val result = syncPersister.onSuccess(corruptedChanges, TIMESTAMP) @@ -100,7 +100,7 @@ internal class CredentialsSyncDataPersisterTest { } @Test - fun whenProcessingDataInEmptyDBThenResultIsSuccess() { + fun `onSuccess - empty DB - success`() { val updatesJSON = FileUtilities.loadText(javaClass.classLoader!!, "json/sync/merger_first_get.json") val validChanges = SyncChangesResponse(CREDENTIALS, updatesJSON) val result = syncPersister.onSuccess(validChanges, DEDUPLICATION) @@ -109,7 +109,7 @@ internal class CredentialsSyncDataPersisterTest { } @Test - fun whenMergingEmptyEntriesThenResultIsSuccess() { + fun `onSuccess - merging empty entries - success`() { val updatesJSON = FileUtilities.loadText(javaClass.classLoader!!, "json/sync/merger_empty_entries.json") val corruptedChanges = SyncChangesResponse(CREDENTIALS, updatesJSON) val result = syncPersister.onSuccess(corruptedChanges, TIMESTAMP) @@ -118,7 +118,7 @@ internal class CredentialsSyncDataPersisterTest { } @Test - fun whenMergingWithDeletedDataThenResultIsSuccess() { + fun `onSuccess - merging with deleted data - success`() { val updatesJSON = FileUtilities.loadText(javaClass.classLoader!!, "json/sync/merger_deleted_entries.json") val deletedChanges = SyncChangesResponse(CREDENTIALS, updatesJSON) val result = syncPersister.onSuccess(deletedChanges, TIMESTAMP) @@ -127,7 +127,7 @@ internal class CredentialsSyncDataPersisterTest { } @Test - fun whenPersistWithAnotherTypeThenReturnFalse() { + fun `onSuccess - another type - return false`() { val result = syncPersister.onSuccess( SyncChangesResponse(BOOKMARKS, ""), DEDUPLICATION, @@ -137,7 +137,7 @@ internal class CredentialsSyncDataPersisterTest { } @Test - fun whenPersistFinishesThenPruneLocalDeletedEntities() { + fun `onSuccess - prune local deleted entities`() { autofillStore.startTimeStamp = "2022-08-30T00:01:00Z" dao.insert(CredentialsSyncMetadataEntity("123", 1L, "2022-08-30T00:00:00Z", null)) @@ -150,7 +150,7 @@ internal class CredentialsSyncDataPersisterTest { } @Test - fun whenOnSuccessThenNotifyListener() { + fun `onSuccess - notify listener`() { val updatesJSON = FileUtilities.loadText(javaClass.classLoader!!, "json/sync/merger_first_get.json") val validChanges = SyncChangesResponse(CREDENTIALS, updatesJSON) @@ -160,13 +160,13 @@ internal class CredentialsSyncDataPersisterTest { } @Test - fun whenOnErrorThenNotifyListener() { + fun `syncPersister - on error - notify listener`() { syncPersister.onError(SyncErrorResponse(CREDENTIALS, COLLECTION_LIMIT_REACHED)) verify(credentialsSyncFeatureListener).onError(COLLECTION_LIMIT_REACHED) } @Test - fun whenOnSyncDisabledTheNotifyListener() { + fun `onSyncDisabled - notify listener`() { syncPersister.onSyncDisabled() verify(credentialsSyncFeatureListener).onSyncDisabled() } diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/CredentialsSyncMapperTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/CredentialsSyncMapperTest.kt index 1fe9992278d7..aedcf9a81b51 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/CredentialsSyncMapperTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/CredentialsSyncMapperTest.kt @@ -30,7 +30,7 @@ import org.mockito.kotlin.verify internal class CredentialsSyncMapperTest { @Test - fun whenMapRemoteLoginCredentialThenLoginCredentials() { + fun `mapRemoteLoginCredential - toLoginCredential - login credentials`() { val syncCrypto = FakeCrypto() val credentialsSyncMapper = CredentialsSyncMapper(syncCrypto) val toLoginCredentialEntryResponse = twitterCredentials.toLoginCredentialEntryResponse() @@ -53,7 +53,7 @@ internal class CredentialsSyncMapperTest { } @Test - fun whenMapRemoteLoginCredentialThenEnsureFieldsDecrypted() { + fun `whenMapRemoteLoginCredential - ensure fields decrypted`() { val syncCrypto = mock() val credentialsSyncMapper = CredentialsSyncMapper(syncCrypto) val toLoginCredentialEntryResponse = twitterCredentials.toLoginCredentialEntryResponse() diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/CredentialsSyncMetadataTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/CredentialsSyncMetadataTest.kt index b0d299b3c6a6..5beba439543f 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/CredentialsSyncMetadataTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/CredentialsSyncMetadataTest.kt @@ -49,7 +49,7 @@ internal class CredentialsSyncMetadataTest { } @Test - fun whenAddNewEntityThenEntityInserted() { + fun `addOrUpdate - entity inserted`() { assertNull(dao.getLocalId("syncId")) testee.addOrUpdate(CredentialsSyncMetadataEntity("syncId", 123L, null, null)) @@ -58,7 +58,7 @@ internal class CredentialsSyncMetadataTest { } @Test - fun whenUpdateSyncIdExistingEntityThenEntityUpdated() { + fun `addOrUpdate - update sync id existing entity - entity updated`() { dao.insert(CredentialsSyncMetadataEntity("syncId", 123L, null, null)) testee.addOrUpdate(CredentialsSyncMetadataEntity("syncId", 456L, null, null)) @@ -67,7 +67,7 @@ internal class CredentialsSyncMetadataTest { } @Test - fun whenUpdateExistingEntityByLocalIdThenEntityUpdated() { + fun `addOrUpdate - entity updated`() { dao.insert(CredentialsSyncMetadataEntity("syncId", 123L, null, null)) testee.addOrUpdate(CredentialsSyncMetadataEntity("syncId2", 123L, null, null)) @@ -76,14 +76,14 @@ internal class CredentialsSyncMetadataTest { } @Test - fun whenAutofillIdNotFoundThenReturnNull() { + fun `getSyncMetadata - autofill id not found - return null`() { val syncId = testee.getSyncMetadata(123L) assertNull(syncId) } @Test - fun whenLoginIdExistsThenReturnSyncMetadata() { + fun `getSyncMetadata - login id exists - returns sync metadata`() { val loginId = 123L val syncId = "syncId" dao.insert(CredentialsSyncMetadataEntity(syncId = syncId, localId = loginId, null, null)) @@ -94,14 +94,14 @@ internal class CredentialsSyncMetadataTest { } @Test - fun whenCreateSyncIdForNonExistingIdThenReturnNewSyncId() { + fun `createSyncId - non existing id - returns new sync id`() { val syncId = testee.createSyncId(123L) assertNotNull(syncId) } @Test - fun whenCreateSyncIdForExistingIdThenReturnExistingSyncId() { + fun `createSyncId - existing id - returns existing sync id`() { val loginId = 123L val syncId = "syncId" dao.insert(CredentialsSyncMetadataEntity(syncId = syncId, localId = loginId, null, null)) @@ -113,14 +113,14 @@ internal class CredentialsSyncMetadataTest { } @Test - fun whenLocalIdNotFoundThenReturnNull() { + fun `getLocalId - local id not found - null`() { val localId = testee.getLocalId("syncId") assertNull(localId) } @Test - fun whenLocalIdExistsThenReturnLocalId() { + fun `getLocalId - local id exists - returns local id`() { val localId = 123L val syncId = "syncId" dao.insert(CredentialsSyncMetadataEntity(syncId = syncId, localId = localId, null, null)) @@ -131,7 +131,7 @@ internal class CredentialsSyncMetadataTest { } @Test - fun whenGetRemovedEntitiesThenReturnEntitiesWithDeletedAt() { + fun `getRemovedEntities - deleted at returned`() { val loginId = 123L val syncId = "syncId" dao.insert(CredentialsSyncMetadataEntity(syncId = syncId, localId = loginId, deleted_at = "2023-07-21T20:21:40.552Z", null)) @@ -144,7 +144,7 @@ internal class CredentialsSyncMetadataTest { } @Test - fun whenGetRemovedEntitiesThenDoNotReturnEntitiesPreviousToSince() { + fun `getRemovedEntities - since - does not return entities previous to`() { val loginId = 123L val syncId = "syncId" dao.insert(CredentialsSyncMetadataEntity(syncId = syncId, localId = loginId, deleted_at = "2021-08-30T00:39:00Z", null)) @@ -155,7 +155,7 @@ internal class CredentialsSyncMetadataTest { } @Test - fun whenEntityRemovedThenUpdateDeletedAtIfExists() { + fun `onEntityRemoved - update deleted at if exists`() { val loginId = 123L val syncId = "syncId" dao.insert(CredentialsSyncMetadataEntity(syncId = syncId, localId = loginId, null, null)) @@ -167,7 +167,7 @@ internal class CredentialsSyncMetadataTest { } @Test - fun whenEntitiesRemovedThenUpdateDeletedAtIfExists() { + fun `onEntitiesRemoved - update deleted at if exists`() { val loginId1 = 1L val syncId1 = "syncId_1" dao.insert(CredentialsSyncMetadataEntity(syncId = syncId1, localId = loginId1, null, null)) @@ -183,7 +183,7 @@ internal class CredentialsSyncMetadataTest { } @Test - fun whenRemoveDeletedEntitiesThenDeleteEntitiesBeforeDate() { + fun `removeDeletedEntities - delete entities before date`() { val loginId = 123L val syncId = "syncId" dao.insert(CredentialsSyncMetadataEntity(syncId = syncId, localId = loginId, deleted_at = "2022-08-30T00:00:00Z", null)) @@ -194,7 +194,7 @@ internal class CredentialsSyncMetadataTest { } @Test - fun whenRemoveDeletedEntitiesThenKeepEntitiesAfterDate() { + fun `removeDeletedEntities - keep entities after date - null and not null`() { val syncId = "syncId" dao.insert(CredentialsSyncMetadataEntity(syncId = syncId, localId = 123L, deleted_at = "2022-08-30T00:00:00Z", null)) dao.insert(CredentialsSyncMetadataEntity(syncId = syncId, localId = 345L, deleted_at = "2022-09-30T00:00:00Z", null)) @@ -206,7 +206,7 @@ internal class CredentialsSyncMetadataTest { } @Test - fun whenRemoveEntityWithLocalIdThenRemoveEntity() { + fun `removeEntityWith - remove entity`() { val loginId = 123L dao.insert(CredentialsSyncMetadataEntity(syncId = "syncId", localId = loginId, null, null)) @@ -216,7 +216,7 @@ internal class CredentialsSyncMetadataTest { } @Test - fun whenRemoveEntityWithSyncIdThenRemoveEntity() { + fun `removeEntityWith - remove entity with sync id`() { val syncId = "syncId" dao.insert(CredentialsSyncMetadataEntity(syncId = syncId, localId = 123L, null, null)) @@ -226,7 +226,7 @@ internal class CredentialsSyncMetadataTest { } @Test - fun whenEntityChangedThenUpdateModifiedAt() { + fun `onEntityChanged - update modified at`() { val loginId = 123L val syncId = "syncId" dao.insert(CredentialsSyncMetadataEntity(syncId = syncId, localId = loginId, null, null)) @@ -238,7 +238,7 @@ internal class CredentialsSyncMetadataTest { } @Test - fun whenEntityChangedInAListThenUpdateModifiedAt() { + fun `onEntitiesChanged - update modified at`() { val loginId = 123L val syncId = "syncId" dao.insert(CredentialsSyncMetadataEntity(syncId = syncId, localId = loginId, null, null)) @@ -250,7 +250,7 @@ internal class CredentialsSyncMetadataTest { } @Test - fun whenEntityChangedDoesNotExistThenInsertedWithModifiedAt() { + fun `onEntityChanged - does not exist - inserted with modified at`() { val loginId = 123L testee.onEntityChanged(loginId) @@ -260,7 +260,7 @@ internal class CredentialsSyncMetadataTest { } @Test - fun whenEntityChangedInAListDoesNotExistThenInsertedWithModifiedAt() { + fun `onEntitiesChanged - entity does not exist - inserted with modified at`() { val loginId = 123L testee.onEntitiesChanged(listOf(loginId)) @@ -270,7 +270,7 @@ internal class CredentialsSyncMetadataTest { } @Test - fun whenGetChangesSinceThenReturnChanges() { + fun `getChangesSince - return changes`() { val loginId = 123L val syncId = "syncId" dao.insert(CredentialsSyncMetadataEntity(syncId = syncId, localId = loginId, null, "2022-08-30T00:40:00Z")) @@ -282,7 +282,7 @@ internal class CredentialsSyncMetadataTest { } @Test - fun whenGetAllThenReturnAll() { + fun `getAll - return all credentials`() { val loginId = 123L val syncId = "syncId" dao.insert(CredentialsSyncMetadataEntity(syncId = syncId, localId = loginId, null, null)) @@ -294,7 +294,7 @@ internal class CredentialsSyncMetadataTest { } @Test - fun whenClearAllThenRemoveAll() { + fun `clearAll - remove all`() { val loginId = 123L val syncId = "syncId" dao.insert(CredentialsSyncMetadataEntity(syncId = syncId, localId = loginId, null, null)) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/CredentialsSyncTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/CredentialsSyncTest.kt index 6e6a0f44a21a..88d20cfd1201 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/CredentialsSyncTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/CredentialsSyncTest.kt @@ -59,7 +59,7 @@ internal class CredentialsSyncTest { } @Test - fun whenInitMetadataThenSetServerModifiedSinceToZero() = runTest { + fun `initMetadata - set server modified since to zero`() = runTest { credentialsSync.initMetadata() assertEquals("0", credentialsSyncStore.serverModifiedSince) @@ -67,7 +67,7 @@ internal class CredentialsSyncTest { } @Test - fun whenInitMetadataThenCreateMetadataForAllEntitiesWithModifiedSince() = runTest { + fun `initMetadata - create metadata for all entities with modified since`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -82,14 +82,14 @@ internal class CredentialsSyncTest { } @Test - fun whenGetUpdatesThenStartTimeUpdates() = runTest { + fun `getUpdates - start time updates`() = runTest { credentialsSync.getUpdatesSince("0") assertNotNull(credentialsSyncStore.startTimeStamp) } @Test - fun whenGetUpdatesSinceZeroTimeThenReturnAllContent() = runTest { + fun `getUpdatesSince - get all content - return all content`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -108,7 +108,7 @@ internal class CredentialsSyncTest { } @Test - fun whenGetUpdatesSinceDateThenReturnRecentUpdates() = runTest { + fun `getUpdatesSince - return recent updates`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials.copy(lastUpdatedMillis = 1689592358516), @@ -124,7 +124,7 @@ internal class CredentialsSyncTest { } @Test - fun whenGetUpdatesSinceDateThenEntitiesWithModifiedAtNullNotReturned() = runTest { + fun `getUpdatesSince - get updates since date - entities with modified at null not returned`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -136,7 +136,7 @@ internal class CredentialsSyncTest { } @Test - fun whenUpdatesContainDeletedItemsThenReturnIncludeDeletedItemsInUpdate() = runTest { + fun `getUpdates - contains deleted items in update`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials.copy(lastUpdatedMillis = 1689592358516), @@ -155,7 +155,7 @@ internal class CredentialsSyncTest { } @Test - fun whenOnFirstWithInvalidCredentialsThenChangesDoesNotContainInvalidEntities() = runTest { + fun `getUpdatesSince - on first with invalid credentials - does not contain invalid entities`() = runTest { givenLocalCredentials( invalidCredentials, ) @@ -167,7 +167,7 @@ internal class CredentialsSyncTest { } @Test - fun whenNewCredentialsIsInvalidThenChangesDoesNotContainInvalidEntity() = runTest { + fun `getUpdatesSince - new credentials invalid - does not contain invalid entity`() = runTest { givenLocalCredentials( spotifyCredentials, invalidCredentials.copy(lastUpdatedMillis = 1689592358516), @@ -180,7 +180,7 @@ internal class CredentialsSyncTest { } @Test - fun whenInvalidCredentialsPresentThenAlwaysRetryItemsAndUpdateInvalidList() = runTest { + fun `whenInvalidCredentialsPresent - always retry items and update invalid list`() = runTest { givenLocalCredentials( invalidCredentials, spotifyCredentials.copy(lastUpdatedMillis = 1689592358516), @@ -195,7 +195,7 @@ internal class CredentialsSyncTest { } @Test - fun whenInvalidCredentialsThenReturnInvalidCredentials() = runTest { + fun `getInvalidCredentials - given local credentials and return invalid credentials`() = runTest { givenLocalCredentials( invalidCredentials, ) @@ -208,7 +208,7 @@ internal class CredentialsSyncTest { } @Test - fun whenGetCredentialWithSyncIdThenReturnCredentials() = runTest { + fun `getCredentialWithSyncId - sync id found - returns credentials`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -220,7 +220,7 @@ internal class CredentialsSyncTest { } @Test - fun whenGetCredentialsWithSyncIdNotFoundThenReturnNull() = runTest { + fun `getCredentialWithSyncId - sync id not found - return null`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -232,7 +232,7 @@ internal class CredentialsSyncTest { } @Test - fun whenGetCredentialsWithLocalIdThenReturnCredentials() = runTest { + fun `getCredentialWithId - local id - returns credentials`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -244,7 +244,7 @@ internal class CredentialsSyncTest { } @Test - fun whenGetCredentialsWithLocalIdNotFoundThenReturnNull() = runTest { + fun `getCredentialWithId - local id not found - return null`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -256,7 +256,7 @@ internal class CredentialsSyncTest { } @Test - fun whenGetCredentialsForDomainThenReturnCredentials() = runTest { + fun `getCredentialsForDomain - return credentials`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -268,7 +268,7 @@ internal class CredentialsSyncTest { } @Test - fun whenSaveCredentialsThenSaveCredentialAndSyncMetadata() = runTest { + fun `saveCredential - sync metadata - saved credential and synced metadata`() = runTest { credentialsSync.saveCredential(twitterCredentials, "123") secureStorage.getWebsiteLoginDetailsWithCredentials(twitterCredentials.id!!)!!.toLoginCredentials().let { @@ -281,7 +281,7 @@ internal class CredentialsSyncTest { } @Test - fun whenSaveCredentialsToExistingSyncIdThenSaveToAutofillStoreAndOverrideSyncId() = runTest { + fun `saveCredential - existing sync id - overrides sync id`() = runTest { credentialsSyncMetadata.addOrUpdate(CredentialsSyncMetadataEntity("321", twitterCredentials.id!!, null, null)) credentialsSync.saveCredential(twitterCredentials, "123") @@ -297,7 +297,7 @@ internal class CredentialsSyncTest { } @Test - fun whenUpdateCredentialsThenUpdateAndSyncMetadata() = runTest { + fun `updateCredentials - update and sync metadata`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -315,7 +315,7 @@ internal class CredentialsSyncTest { } @Test - fun whenDeleteCredentialThenDeleteFromAutofillStoreAndSyncMetadata() = runTest { + fun `deleteCredential - delete from autofill store and sync metadata`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/RealCredentialsSyncStoreTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/RealCredentialsSyncStoreTest.kt index b45578f3922c..3550a96520b0 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/RealCredentialsSyncStoreTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/RealCredentialsSyncStoreTest.kt @@ -42,12 +42,12 @@ class RealCredentialsSyncStoreTest { val testee = RealCredentialsSyncStore(mockContext, coroutineRule.testScope, coroutineRule.testDispatcherProvider) @Test - fun whenNoValueIsSyncPausedThenReturnFalse() { + fun `isSyncPaused - no value - return false`() { assertFalse(testee.isSyncPaused) } @Test - fun whenIsSyncPausedUpdatedThenEmitNewValue() = runTest { + fun `isSyncPausedUpdated - emit new value`() = runTest { testee.isSyncPausedFlow().test { awaitItem() testee.isSyncPaused = true diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/SyncCredentialsListenerTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/SyncCredentialsListenerTest.kt index f9909f57f06b..1a342bfb9efc 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/SyncCredentialsListenerTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/SyncCredentialsListenerTest.kt @@ -50,7 +50,7 @@ class SyncCredentialsListenerTest { } @Test - fun whenOnCredentialAddedThenNotifySyncMetadata() { + fun `onCredentialAdded - notify sync metadata`() { testee.onCredentialAdded(1) syncMetatadaDao.getSyncMetadata(1)?.let { @@ -61,7 +61,7 @@ class SyncCredentialsListenerTest { } @Test - fun whenAddingCredentialRecentlyRemovedThenCancelDeleteOperationAndDoNotUpdateMetadata() = runTest { + fun `onCredentialAdded - recently removed credential - do not update metadata`() = runTest { testee.onCredentialAdded(1) val credential = syncMetatadaDao.getSyncMetadata(1) testee.onCredentialRemoved(1) @@ -74,7 +74,7 @@ class SyncCredentialsListenerTest { } @Test - fun whenCredentialNotReinsertedThenNotifySyncMetadata() = runTest { + fun `onCredentialNotReinserted - notify sync metadata`() = runTest { testee.onCredentialAdded(1) testee.onCredentialRemoved(1) this.advanceTimeBy(SYNC_CREDENTIALS_DELETE_DELAY + 1) @@ -85,7 +85,7 @@ class SyncCredentialsListenerTest { } @Test - fun whenMultipleCredentialsAddedThenNotifySyncMetadata() { + fun `onCredentialsAdded - notify sync metadata`() { testee.onCredentialsAdded(listOf(1, 2, 3, 4, 5)) assertEquals(5, syncMetatadaDao.getAll().size) @@ -97,7 +97,7 @@ class SyncCredentialsListenerTest { } @Test - fun whenReinsertingCredentialsRecentlyRemovedThenCancelDeleteOperationAndDoNotUpdateMetadata() = runTest { + fun `onCredentialRemoved - reinserting credentials recently removed - does not update metadata`() = runTest { testee.onCredentialsAdded(listOf(1, 2, 3, 4, 5)) val credentials = syncMetatadaDao.getAll() assertEquals(5, credentials.size) @@ -113,7 +113,7 @@ class SyncCredentialsListenerTest { } @Test - fun whenCredentialsNotReinsertedThenNotifySyncMetadata() = runTest { + fun `onCredentialsNotReinserted - notify sync metadata`() = runTest { testee.onCredentialsAdded(listOf(1, 2, 3, 4, 5)) testee.onCredentialRemoved(listOf(1, 2, 3, 4, 5)) diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/persister/CredentialsLastModifiedWinsStrategyTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/persister/CredentialsLastModifiedWinsStrategyTest.kt index 5f1a76699d17..9c78b88baa77 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/persister/CredentialsLastModifiedWinsStrategyTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/persister/CredentialsLastModifiedWinsStrategyTest.kt @@ -77,7 +77,7 @@ internal class CredentialsLastModifiedWinsStrategyTest { dispatchers = coroutineRule.testDispatcherProvider, ) - @Test fun whenNoLocalEntitiesThenAllRemoteEntitiesStored() = runTest { + @Test fun `processEntries - no local entities - all remote entities stored`() = runTest { givenLocalCredentials() val remoteCredentials = credentialsSyncEntries( entries = listOf( @@ -96,7 +96,7 @@ internal class CredentialsLastModifiedWinsStrategyTest { assertTrue(credentialsSyncMetadata.getLocalId("2") == spotifyCredentials.id) } - @Test fun whenRemoteAreMoreRecentThenRemoteWins() = runTest { + @Test fun `processEntries - remote are more recent - success`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -120,7 +120,7 @@ internal class CredentialsLastModifiedWinsStrategyTest { assertTrue(credentialsSync.getCredentialWithSyncId("2")!!.domainTitle == "NewTitle") } - @Test fun whenCredentialUpdatedAfterChangesTimeStampThenLocalWins() = runTest { + @Test fun `processEntries - credential updated after changes timestamp then local wins`() = runTest { givenLocalCredentials( twitterCredentials.copy(lastUpdatedMillis = DatabaseDateFormatter.parseIso8601ToMillis("2022-08-30T00:01:00Z")), spotifyCredentials.copy(lastUpdatedMillis = DatabaseDateFormatter.parseIso8601ToMillis("2022-08-30T00:01:00Z")), @@ -144,7 +144,7 @@ internal class CredentialsLastModifiedWinsStrategyTest { assertTrue(credentialsSync.getCredentialWithSyncId("2")!!.domainTitle == spotifyCredentials.domainTitle) } - @Test fun whenLocalIsMoreRecentThenLocalWins() = runTest { + @Test fun `processEntries - local is more recent - local wins`() = runTest { givenLocalCredentials( twitterCredentials.copy(lastUpdatedMillis = 1689592358516), spotifyCredentials.copy(lastUpdatedMillis = 1689592358516), @@ -168,7 +168,7 @@ internal class CredentialsLastModifiedWinsStrategyTest { assertTrue(credentialsSync.getCredentialWithSyncId("2")!!.domainTitle == spotifyCredentials.domainTitle) } - @Test fun whenLocalHasMoreCredentialsThenUpdateWithMoreRecentAndKeepOthers() = runTest { + @Test fun `processEntries - local has more credentials - update with more recent and keep others`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -192,7 +192,7 @@ internal class CredentialsLastModifiedWinsStrategyTest { assertTrue(credentialsSyncMetadata.getLocalId("3") == 3L) } - @Test fun whenRemoteHasMoreCredentialsThenKeepExistingAndAddNewCredentials() = runTest { + @Test fun `processEntries - remote has more credentials - keep existing and add new credentials`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -216,7 +216,7 @@ internal class CredentialsLastModifiedWinsStrategyTest { assertTrue(credentialsSyncMetadata.getLocalId("3") == 3L) } - @Test fun whenRemoteIsEmptyThenNoChanges() = runTest { + @Test fun `processEntries - remote empty - no changes`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -235,7 +235,7 @@ internal class CredentialsLastModifiedWinsStrategyTest { assertTrue(credentialsSyncMetadata.getLocalId("2") == 2L) } - @Test fun whenRemoteMoreRecentAndDeletedThenRemoteWins() = runTest { + @Test fun `processEntries - remote more recent and deleted - success`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/persister/CredentialsLocalWinsStrategyTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/persister/CredentialsLocalWinsStrategyTest.kt index 51eb5eef2b5a..edcf373e51cc 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/persister/CredentialsLocalWinsStrategyTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/persister/CredentialsLocalWinsStrategyTest.kt @@ -77,7 +77,7 @@ internal class CredentialsLocalWinsStrategyTest { ) @Test - fun whenNoLocalEntitiesThenAllRemoteEntitiesStored() = runTest { + fun `processEntries - no local entities - all remote entities stored`() = runTest { givenLocalCredentials() val remoteCredentials = credentialsSyncEntries( entries = listOf( @@ -97,7 +97,7 @@ internal class CredentialsLocalWinsStrategyTest { } @Test - fun whenRemoteAreMoreRecentThenLocalWins() = runTest { + fun `processEntries - remote are more recent - local wins`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -122,7 +122,7 @@ internal class CredentialsLocalWinsStrategyTest { } @Test - fun whenLocalIsMoreRecentThenLocalWins() = runTest { + fun `processEntries - local is more recent - local wins`() = runTest { givenLocalCredentials( twitterCredentials.copy(lastUpdatedMillis = 1689592358516), spotifyCredentials.copy(lastUpdatedMillis = 1689592358516), @@ -147,7 +147,7 @@ internal class CredentialsLocalWinsStrategyTest { } @Test - fun whenLocalHasMoreCredentialsThenNoChanges() = runTest { + fun `processEntries - local has more credentials - no changes`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -172,7 +172,7 @@ internal class CredentialsLocalWinsStrategyTest { } @Test - fun whenRemoteHasMoreCredentialsThenKeepExistingAndAddNewCredentials() = runTest { + fun `processEntries - remote has more credentials - keep existing and add new credentials`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -197,7 +197,7 @@ internal class CredentialsLocalWinsStrategyTest { } @Test - fun whenRemoteIsEmptyThenNoChanges() = runTest { + fun `processEntries - remote empty - no changes`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -217,7 +217,7 @@ internal class CredentialsLocalWinsStrategyTest { } @Test - fun whenRemoteMoreRecentAndDeletedThenNoChanges() = runTest { + fun `processEntries - remote more recent and deleted - no changes`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -240,7 +240,7 @@ internal class CredentialsLocalWinsStrategyTest { } @Test - fun whenServerReturnsDeletedEntityThenDoNotSavecredentials() = runTest { + fun `processEntries - server returns deleted entity - do not save credentials`() = runTest { val remoteCredentials = credentialsSyncEntries( entries = listOf( twitterCredentials.toLoginCredentialEntryResponse().copy(deleted = "1"), diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/persister/CredentialsRemoteWinsStrategyTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/persister/CredentialsRemoteWinsStrategyTest.kt index 41c213bd9c5e..27229797c1b8 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/persister/CredentialsRemoteWinsStrategyTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/persister/CredentialsRemoteWinsStrategyTest.kt @@ -77,7 +77,7 @@ internal class CredentialsRemoteWinsStrategyTest { ) @Test - fun whenNoLocalEntitiesThenAllRemoteEntitiesStored() = runTest { + fun `processEntries - no local entities - all remote entities stored`() = runTest { givenLocalCredentials() val remoteCredentials = credentialsSyncEntries( entries = listOf( @@ -97,7 +97,7 @@ internal class CredentialsRemoteWinsStrategyTest { } @Test - fun whenRemoteAreMoreRecentThenRemoteWins() = runTest { + fun `processEntries - remote credentials more recent - success`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -122,7 +122,7 @@ internal class CredentialsRemoteWinsStrategyTest { } @Test - fun whenLocalIsMoreRecentThenRemoteWins() = runTest { + fun `processEntries - local is more recent - remote wins`() = runTest { givenLocalCredentials( twitterCredentials.copy(lastUpdatedMillis = 1689592358516), spotifyCredentials.copy(lastUpdatedMillis = 1689592358516), @@ -147,7 +147,7 @@ internal class CredentialsRemoteWinsStrategyTest { } @Test - fun whenLocalHasMoreCredentialsThenOnlyUpdateWithRemoteInfo() = runTest { + fun `processEntries - local has more credentials - only update with remote info`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -172,7 +172,7 @@ internal class CredentialsRemoteWinsStrategyTest { } @Test - fun whenRemoteHasMoreCredentialsThenKeepExistingAndAddNewCredentials() = runTest { + fun `processEntries - remote has more credentials - keep existing and add new credentials`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -197,7 +197,7 @@ internal class CredentialsRemoteWinsStrategyTest { } @Test - fun whenRemoteIsEmptyThenNoChanges() = runTest { + fun `processEntries - remote empty - no changes`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -217,7 +217,7 @@ internal class CredentialsRemoteWinsStrategyTest { } @Test - fun whenRemoteMoreRecentAndDeletedThenRemoteWins() = runTest { + fun `processEntries - remote more recent and deleted - remote wins`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/persister/CrendentialsDedupStrategyTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/persister/CrendentialsDedupStrategyTest.kt index b036d821e749..73a3587834b2 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/persister/CrendentialsDedupStrategyTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/persister/CrendentialsDedupStrategyTest.kt @@ -77,7 +77,7 @@ internal class CredentialsDedupStrategyTest { ) @Test - fun whenNoLocalEntitiesThenAllRemoteEntitiesStored() = runTest { + fun `processEntries - no local entities - all remote entities stored`() = runTest { givenLocalCredentials() val remoteCredentials = credentialsSyncEntries( entries = listOf( @@ -97,7 +97,7 @@ internal class CredentialsDedupStrategyTest { } @Test - fun whenDuplicatesExistAndRemoteAreMoreRecentThenDeDupAndStoreMostRecent() = runTest { + fun `processEntries - duplicates exist and remote are more recent - de dup and store most recent`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -123,7 +123,7 @@ internal class CredentialsDedupStrategyTest { } @Test - fun whenDuplicatesExistAndLocalAreMoreRecentThenDeDupAndStoreMostRecent() = runTest { + fun `processEntries - duplicates exist and local are more recent - dedup and store most recent`() = runTest { givenLocalCredentials( twitterCredentials.copy(lastUpdatedMillis = 1689592358516), spotifyCredentials.copy(lastUpdatedMillis = 1689592358516), @@ -151,7 +151,7 @@ internal class CredentialsDedupStrategyTest { } @Test - fun whenLocalHasDuplicatesAndNoDuplicatesThenDedupAndKeepTheRest() = runTest { + fun `processEntries - local has duplicates and no duplicates - dedup and keep the rest`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -180,7 +180,7 @@ internal class CredentialsDedupStrategyTest { } @Test - fun whenRemoteHasDuplicatesAndNewCredentialsThenDedupAndInsertNew() = runTest { + fun `processEntries - remote has duplicates and new credentials - dedup and insert new`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -205,7 +205,7 @@ internal class CredentialsDedupStrategyTest { } @Test - fun whenRemoteIsEmptyThenNoChanges() = runTest { + fun `processEntries - remote empty - no changes`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, diff --git a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/provider/CredentialsSyncDataProviderTest.kt b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/provider/CredentialsSyncDataProviderTest.kt index 370d852ddbd0..a91df6af2e4c 100644 --- a/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/provider/CredentialsSyncDataProviderTest.kt +++ b/autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/sync/provider/CredentialsSyncDataProviderTest.kt @@ -79,14 +79,14 @@ internal class CredentialsSyncDataProviderTest { ) @Test - fun whenInitialSyncAndNoDataThenReturnEmptyList() = runTest { + fun `getChanges - initial sync and no data - empty list`() = runTest { val result = testee.getChanges() assertTrue(result.isEmpty()) } @Test - fun whenInitialSyncAndDataThenAllChanges() = runTest { + fun `getChanges - initial sync and data - all changes`() = runTest { givenLocalCredentials( CredentialsFixtures.twitterCredentials, CredentialsFixtures.spotifyCredentials, @@ -100,7 +100,7 @@ internal class CredentialsSyncDataProviderTest { } @Test - fun whenModifiedSinceExistsThenSendChangesWithServerTimeSince() = runTest { + fun `getChanges - modified since exists - send changes with server time since`() = runTest { credentialsSyncStore.clientModifiedSince = "2022-01-01T00:00:00Z" credentialsSyncStore.serverModifiedSince = "2022-08-30T00:00:00Z" @@ -117,7 +117,7 @@ internal class CredentialsSyncDataProviderTest { } @Test - fun whenSendingDataThenStartTimeUpdated() = runTest { + fun `getChanges - start time updated`() = runTest { credentialsSyncStore.startTimeStamp = "0" givenLocalCredentials( CredentialsFixtures.twitterCredentials, @@ -130,7 +130,7 @@ internal class CredentialsSyncDataProviderTest { } @Test - fun whenNullPropertyThenIncludeNullInJson() = runTest { + fun `getChanges - null property - include null in json`() = runTest { credentialsSyncStore.serverModifiedSince = "0" givenLocalCredentials( diff --git a/autofill/autofill-store/src/test/java/com.duckduckgo.autofill.store/RealSecureStorageKeyRepositoryTest.kt b/autofill/autofill-store/src/test/java/com.duckduckgo.autofill.store/RealSecureStorageKeyRepositoryTest.kt index db232bc111b2..f99735221f3f 100644 --- a/autofill/autofill-store/src/test/java/com.duckduckgo.autofill.store/RealSecureStorageKeyRepositoryTest.kt +++ b/autofill/autofill-store/src/test/java/com.duckduckgo.autofill.store/RealSecureStorageKeyRepositoryTest.kt @@ -39,70 +39,70 @@ class RealSecureStorageKeyRepositoryTest { } @Test - fun whenPasswordIsSetThenUpdateKeyForPasswordInKeyStore() { + fun `whenPasswordIsSet - update key for password in key store`() { testee.password = testValue verify(keyStore).updateKey("KEY_GENERATED_PASSWORD", testValue) } @Test - fun whenGettingPasswordThenGetKeyForPasswordInKeyStore() { + fun `getKeyForPassword - key store - gets generated password`() { whenever(keyStore.getKey("KEY_GENERATED_PASSWORD")).thenReturn(testValue) assertEquals(testValue, testee.password) } @Test - fun whenL1KeyIsSetThenUpdateKeyForL1KeyInKeyStore() { + fun `whenL1KeyIsSetThenUpdateKeyForL1KeyInKeyStore - update key for L1 key in key store`() { testee.l1Key = testValue verify(keyStore).updateKey("KEY_L1KEY", testValue) } @Test - fun whenGettingL1KeyThenGetKeyForL1KeyInKeyStore() { + fun `getKeyForL1Key - key store - returns l1 key`() { whenever(keyStore.getKey("KEY_L1KEY")).thenReturn(testValue) assertEquals(testValue, testee.l1Key) } @Test - fun whenPasswordSaltIsSetThenUpdateKeyForPasswordSaltInKeyStore() { + fun `whenPasswordSaltIsSet - update key for password salt in key store`() { testee.passwordSalt = testValue verify(keyStore).updateKey("KEY_PASSWORD_SALT", testValue) } @Test - fun whenGettingPasswordSaltThenGetKeyForPasswordSaltKeyInKeyStore() { + fun `getKeyForPasswordSalt - key store - password salt`() { whenever(keyStore.getKey("KEY_PASSWORD_SALT")).thenReturn(testValue) assertEquals(testValue, testee.passwordSalt) } @Test - fun whenEncryptedL2KeyIsSetThenUpdateKeyForEncryptedL2KeyInKeyStore() { + fun `whenEncryptedL2KeyIsSet - update key for encrypted L2 key in key store`() { testee.encryptedL2Key = testValue verify(keyStore).updateKey("KEY_ENCRYPTED_L2KEY", testValue) } @Test - fun whenGettingEncryptedL2KeyThenGetKeyForEncryptedL2KeyInKeyStore() { + fun `getKeyForEncryptedL2Key - key store - returns encrypted L2 key`() { whenever(keyStore.getKey("KEY_ENCRYPTED_L2KEY")).thenReturn(testValue) assertEquals(testValue, testee.encryptedL2Key) } @Test - fun whenEncryptedL2KeyIVIsSetThenUpdateKeyForEncryptedL2KeyIVInKeyStore() { + fun `whenEncryptedL2KeyIVIsSet - update key for encrypted L2 key IV in key store`() { testee.encryptedL2KeyIV = testValue verify(keyStore).updateKey("KEY_ENCRYPTED_L2KEY_IV", testValue) } @Test - fun whenGettingEncryptedL2KeyIVThenGetKeyForEncryptedL2KeyIVInKeyStore() { + fun `getKeyForEncryptedL2KeyIVInKeyStore - getting encrypted L2 key IV - returns test value`() { whenever(keyStore.getKey("KEY_ENCRYPTED_L2KEY_IV")).thenReturn(testValue) assertEquals(testValue, testee.encryptedL2KeyIV) diff --git a/autofill/autofill-store/src/test/java/com.duckduckgo.autofill.store/RealSecureStorageRepositoryTest.kt b/autofill/autofill-store/src/test/java/com.duckduckgo.autofill.store/RealSecureStorageRepositoryTest.kt index f88d22821c2a..7221ce221a0c 100644 --- a/autofill/autofill-store/src/test/java/com.duckduckgo.autofill.store/RealSecureStorageRepositoryTest.kt +++ b/autofill/autofill-store/src/test/java/com.duckduckgo.autofill.store/RealSecureStorageRepositoryTest.kt @@ -70,12 +70,12 @@ class RealSecureStorageRepositoryTest { } @Test - fun whenRetrievingLoginCredentialByIdThenNullReturnedIfNotExists() = runTest { + fun `getWebsiteLoginCredentialsById - null returned if not exists`() = runTest { assertNull(websiteLoginCredentialsDao.getWebsiteLoginCredentialsById(entity().id)) } @Test - fun whenRetrievingLoginCredentialByIdThenReturnedIfExists() = runTest { + fun `getWebsiteLoginCredentialsForId - retrieving login credential by id - returned if exists`() = runTest { val testEntity = entity() websiteLoginCredentialsDao.insert(entity()) val result = testee.getWebsiteLoginCredentialsForId(testEntity.id) @@ -83,7 +83,7 @@ class RealSecureStorageRepositoryTest { } @Test - fun whenRetrievingLoginCredentialByDomainThenReturnedIfDirectMatch() = runTest { + fun `websiteLoginCredentialsForDomain - domain match - returned if direct match`() = runTest { val testEntity = entity() websiteLoginCredentialsDao.insert(testEntity) val result: List = testee.websiteLoginCredentialsForDomain("test.com").first() @@ -91,7 +91,7 @@ class RealSecureStorageRepositoryTest { } @Test - fun whenRetrievingLoginCredentialByEmptyDomainThenReturnedIfDirectMatch() = runTest { + fun `websiteLoginCredentialsForDomain - empty domain - returned if direct match`() = runTest { val testEntity = entity().copy(domain = "") websiteLoginCredentialsDao.insert(testEntity) val result: List = testee.websiteLoginCredentialsForDomain("").first() @@ -99,7 +99,7 @@ class RealSecureStorageRepositoryTest { } @Test - fun whenRetrievingLoginCredentialByNullDomainThenReturnedIfDirectMatch() = runTest { + fun `websiteLoginCredentialsForDomain - domain null - returned if direct match`() = runTest { val testEntity = entity().copy(domain = null) websiteLoginCredentialsDao.insert(testEntity) val result: List = testee.websiteLoginCredentialsForDomain("").first() @@ -107,7 +107,7 @@ class RealSecureStorageRepositoryTest { } @Test - fun whenRetrievingLoginCredentialByDomainThenEmptyListReturnedIfNoMatches() = runTest { + fun `websiteLoginCredentialsForDomain - empty list returned if no matches`() = runTest { val testEntity = entity() websiteLoginCredentialsDao.insert(testEntity) val result: List = testee.websiteLoginCredentialsForDomain("no-matches.com").first() @@ -115,13 +115,13 @@ class RealSecureStorageRepositoryTest { } @Test - fun whenGetAllWebsiteLoginCredentialsWithSitesThenEmptyListReturned() = runTest { + fun `getWebsiteLoginCredentials - sites - empty list returned`() = runTest { val result: List = testee.websiteLoginCredentials().first() assertTrue(result.isEmpty()) } @Test - fun whenGetAllWebsiteLoginCredentialsWithASingleSiteThenThatOneIsReturned() = runTest { + fun `getWebsiteLoginCredentials - single site returned`() = runTest { val testEntity = entity() websiteLoginCredentialsDao.insert(testEntity) val result: List = testee.websiteLoginCredentials().first() @@ -129,7 +129,7 @@ class RealSecureStorageRepositoryTest { } @Test - fun whenGetAllWebsiteLoginCredentialsWithMultipleSitesThenThatAllReturned() = runTest { + fun `getWebsiteLoginCredentials - multiple sites - all returned`() = runTest { val testEntity = entity() val anotherEntity = entity(id = testEntity.id + 1) websiteLoginCredentialsDao.insert(testEntity) @@ -139,7 +139,7 @@ class RealSecureStorageRepositoryTest { } @Test - fun whenUpdateWebsiteLoginCredentialsThenCallUpdateToDao() = runTest { + fun `updateWebsiteLoginCredentials - call update to dao`() = runTest { val testEntity = entity() websiteLoginCredentialsDao.insert(testEntity) testee.updateWebsiteLoginCredentials(testEntity.copy(username = "newUsername")) @@ -149,7 +149,7 @@ class RealSecureStorageRepositoryTest { } @Test - fun whenDeleteWebsiteLoginCredentialsThenEntityRemoved() = runTest { + fun `deleteWebsiteLoginCredentials - entity removed`() = runTest { val testEntity = entity() websiteLoginCredentialsDao.insert(testEntity) testee.deleteWebsiteLoginCredentials(1) @@ -158,7 +158,7 @@ class RealSecureStorageRepositoryTest { } @Test - fun whenNoSitesEverAddedToNeverSaveListThenCountIs0() = runTest { + fun `neverSaveListCount - count is 0`() = runTest { testee.neverSaveListCount().test { assertEquals(0, awaitItem()) cancelAndIgnoreRemainingEvents() @@ -166,7 +166,7 @@ class RealSecureStorageRepositoryTest { } @Test - fun whenNeverSavedSiteAddedThenCountIncreases() = runTest { + fun `neverSaveListCount - site added - count increases`() = runTest { testee.neverSaveListCount().test { assertEquals(0, awaitItem()) neverSavedSitesDao.insert(NeverSavedSiteEntity(domain = "test.com")) @@ -176,7 +176,7 @@ class RealSecureStorageRepositoryTest { } @Test - fun whenNeverSavedSiteAddedButExactDomainAlreadyInDbThenCountDoesNotIncrease() = runTest { + fun `neverSaveListCount - site added but exact domain already in db - count does not increase`() = runTest { testee.neverSaveListCount().test { // starts at count = 0 assertEquals(0, awaitItem()) diff --git a/broken-site/broken-site-impl/src/test/java/com/duckduckgo/brokensite/impl/CleanupBrokenSiteLastSentReportWorkerTest.kt b/broken-site/broken-site-impl/src/test/java/com/duckduckgo/brokensite/impl/CleanupBrokenSiteLastSentReportWorkerTest.kt index e9b6e030c384..ec64aee9c049 100644 --- a/broken-site/broken-site-impl/src/test/java/com/duckduckgo/brokensite/impl/CleanupBrokenSiteLastSentReportWorkerTest.kt +++ b/broken-site/broken-site-impl/src/test/java/com/duckduckgo/brokensite/impl/CleanupBrokenSiteLastSentReportWorkerTest.kt @@ -43,7 +43,7 @@ class CleanupBrokenSiteLastSentReportWorkerTest { } @Test - fun whenDoWorkThenCallCleanupOldEntriesAndReturnSuccess() = + fun `doWork - cleanup old entries and return success`() = runTest { val worker = TestListenableWorkerBuilder(context = context).build() worker.brokenSiteReportRepository = mockBrokenSiteReportRepository diff --git a/broken-site/broken-site-impl/src/test/java/com/duckduckgo/brokensite/impl/RealBrokenSiteLastSentReportTest.kt b/broken-site/broken-site-impl/src/test/java/com/duckduckgo/brokensite/impl/RealBrokenSiteLastSentReportTest.kt index f3cbae05f6be..2b6a1915fd5c 100644 --- a/broken-site/broken-site-impl/src/test/java/com/duckduckgo/brokensite/impl/RealBrokenSiteLastSentReportTest.kt +++ b/broken-site/broken-site-impl/src/test/java/com/duckduckgo/brokensite/impl/RealBrokenSiteLastSentReportTest.kt @@ -39,7 +39,7 @@ class RealBrokenSiteLastSentReportTest { } @Test - fun whenGetLastSentDayCalledWithHostnameThenGetLastSentDayFromRepositoryIsCalled() = runTest { + fun `getlastsentday - get last sent day from repository - called with hostname`() = runTest { val hostname = "www.example.com" testee.getLastSentDay(hostname) @@ -48,7 +48,7 @@ class RealBrokenSiteLastSentReportTest { } @Test - fun whenSetLastSentDayCalledWithHostnameThenSetLastSentDayFromRepositoryIsCalled() = runTest { + fun `setLastSentDay - set last sent day from repository - called with hostname`() = runTest { val hostname = "www.example.com" testee.setLastSentDay(hostname) diff --git a/broken-site/broken-site-impl/src/test/java/com/duckduckgo/brokensite/impl/RealBrokenSiteReportRepositoryTest.kt b/broken-site/broken-site-impl/src/test/java/com/duckduckgo/brokensite/impl/RealBrokenSiteReportRepositoryTest.kt index 84b7220505c4..e5da0c548925 100644 --- a/broken-site/broken-site-impl/src/test/java/com/duckduckgo/brokensite/impl/RealBrokenSiteReportRepositoryTest.kt +++ b/broken-site/broken-site-impl/src/test/java/com/duckduckgo/brokensite/impl/RealBrokenSiteReportRepositoryTest.kt @@ -52,7 +52,7 @@ class RealBrokenSiteReportRepositoryTest { } @Test - fun whenGetLastSentDayCalledWithEmptyHostnameThenReturnNull() = runTest { + fun `getLastSentDay - empty hostname - null`() = runTest { val hostname = "" val result = testee.getLastSentDay(hostname) @@ -61,7 +61,7 @@ class RealBrokenSiteReportRepositoryTest { } @Test - fun whenGetLastSentDayCalledWithNewHostnameThenReturnNull() = runTest { + fun `getLastSentDay - new hostname - returns null`() = runTest { val hostname = "www.example.com" val hostnameHashPrefix = "80fc0f" val brokenSiteReportEntity = null @@ -73,7 +73,7 @@ class RealBrokenSiteReportRepositoryTest { } @Test - fun whenGetLastSentDayCalledWithExistingHostnameThenReturnLastSeenDay() = runTest { + fun `getLastSentDay - existing hostname - returns last seen day`() = runTest { val hostname = "www.example.com" val hostnameHashPrefix = "80fc0f" val lastSentDay = "2023-11-01T15:30:54.401Z" @@ -86,7 +86,7 @@ class RealBrokenSiteReportRepositoryTest { } @Test - fun whenSetLastSentDayCalledWithEmptyHostnameThenUpsertBrokenSiteReportIsNeverCalled() = runTest { + fun `setLastSentDay - empty hostname - upsert broken site report is never called`() = runTest { val hostname = "" testee.setLastSentDay(hostname) @@ -95,7 +95,7 @@ class RealBrokenSiteReportRepositoryTest { } @Test - fun whenSetLastSentDayCalledWithNonEmptyHostnameThenUpsertBrokenSiteReportIsCalled() = runTest { + fun `setLastSentDay - non-empty hostname - upsert broken site report is called`() = runTest { val hostname = "www.example.com" testee.setLastSentDay(hostname) @@ -104,7 +104,7 @@ class RealBrokenSiteReportRepositoryTest { } @Test - fun whenCleanupOldEntriesCalledThenCleanupBrokenSiteReportIsCalled() = runTest { + fun `cleanupOldEntries - cleanup broken site report is called`() = runTest { testee.cleanupOldEntries() verify(mockDatabase.brokenSiteDao()).deleteAllExpiredReports(any()) diff --git a/common/common-ui/src/test/java/com/duckduckgo/common/ui/notifyme/NotifyMeViewModelTest.kt b/common/common-ui/src/test/java/com/duckduckgo/common/ui/notifyme/NotifyMeViewModelTest.kt index 90b7c7380c22..cd9971bed9ab 100644 --- a/common/common-ui/src/test/java/com/duckduckgo/common/ui/notifyme/NotifyMeViewModelTest.kt +++ b/common/common-ui/src/test/java/com/duckduckgo/common/ui/notifyme/NotifyMeViewModelTest.kt @@ -59,7 +59,7 @@ class NotifyMeViewModelTest { } @Test - fun whenNotificationsNotAllowedAndDismissNotCalledAndViewIsNotDismissedThenViewIsVisible() = runTest { + fun `viewIsVisible - notifications not allowed and dismiss not called - is visible`() = runTest { setup( notificationsAllowed = false, dismissCalled = false, @@ -73,7 +73,7 @@ class NotifyMeViewModelTest { } @Test - fun whenNotificationsNotAllowedAndDismissNotCalledAndViewIsDismissedThenViewIsNotVisible() = runTest { + fun `whenNotificationsNotAllowedAndDismissNotCalledAndViewIsDismissedThenViewIsNotVisible - view is not visible`() = runTest { setup( notificationsAllowed = false, dismissCalled = false, @@ -87,7 +87,7 @@ class NotifyMeViewModelTest { } @Test - fun whenNotificationsNotAllowedAndDismissCalledAndViewIsNotDismissedThenViewIsNotVisible() = runTest { + fun `whenNotificationsNotAllowedAndDismissCalled - view is not visible`() = runTest { setup( notificationsAllowed = false, dismissCalled = true, @@ -101,7 +101,7 @@ class NotifyMeViewModelTest { } @Test - fun whenNotificationsNotAllowedAndDismissCalledAndViewIsDismissedThenViewIsNotVisible() = runTest { + fun `whenNotificationsNotAllowedAndDismissCalledAndViewIsDismissedThenViewIsNotVisible - view is not visible`() = runTest { setup( notificationsAllowed = false, dismissCalled = true, @@ -115,7 +115,7 @@ class NotifyMeViewModelTest { } @Test - fun whenNotificationsAllowedAndDismissNotCalledAndViewIsNotDismissedThenViewIsNotVisible() = runTest { + fun `viewIsNotVisible - notifications allowed and dismiss not called - view is not visible`() = runTest { setup( notificationsAllowed = true, dismissCalled = false, @@ -129,7 +129,7 @@ class NotifyMeViewModelTest { } @Test - fun whenNotificationsAllowedAndDismissNotCalledAndViewIsDismissedThenViewIsNotVisible() = runTest { + fun `whenNotificationsAllowedAndDismissNotCalledAndViewIsDismissedThenViewIsNotVisible - view state not visible`() = runTest { setup( notificationsAllowed = true, dismissCalled = false, @@ -143,7 +143,7 @@ class NotifyMeViewModelTest { } @Test - fun whenNotificationsAllowedAndDismissCalledAndViewIsNotDismissedThenViewIsNotVisible() = runTest { + fun `whenNotificationsAllowedAndDismissCalledAndViewIsNotDismissedThenViewIsNotVisible - view state not visible`() = runTest { setup( notificationsAllowed = true, dismissCalled = true, @@ -157,7 +157,7 @@ class NotifyMeViewModelTest { } @Test - fun whenNotificationsAllowedAndDismissCalledAndViewIsDismissedThenViewIsNotVisible() = runTest { + fun `whenNotificationsAllowedAndDismissCalledAndViewIsDismissedThenViewIsNotVisible - view state not visible`() = runTest { setup( notificationsAllowed = true, dismissCalled = true, @@ -171,7 +171,7 @@ class NotifyMeViewModelTest { } @Test - fun whenOnResumeCalledThenCheckPermissionsCommandIsSent() = runTest { + fun `onResume - check permissions command is sent`() = runTest { testee.onResume(mockLifecycleOwner) testee.commands().test { @@ -183,7 +183,7 @@ class NotifyMeViewModelTest { } @Test - fun whenOnNotifyMeButtonClickedOnAndroid13ThenCheckPermissionRationaleCommandIsSent() = runTest { + fun `onNotifyMeButtonClicked - on Android 13 - check permission rationale command is sent`() = runTest { whenever(mockAppBuildConfig.sdkInt).thenReturn(Build.VERSION_CODES.TIRAMISU) testee.onNotifyMeButtonClicked() @@ -196,7 +196,7 @@ class NotifyMeViewModelTest { } @Test - fun whenOnNotifyMeButtonClickedOnAndroid8ThenOpenSettingsOnAndroid8PlusCommandIsSent() = runTest { + fun `onNotifyMeButtonClicked - on Android 8 - open settings on Android 8 plus command is sent`() = runTest { whenever(mockAppBuildConfig.sdkInt).thenReturn(Build.VERSION_CODES.O) testee.onNotifyMeButtonClicked() @@ -210,7 +210,7 @@ class NotifyMeViewModelTest { } @Test - fun whenOnCloseButtonClickedThenCloseCommandIsSentAndSetDismissedIsCalled() = runTest { + fun `onCloseButtonClicked - set dismissed is called`() = runTest { testee.onCloseButtonClicked() testee.commands().test { @@ -223,7 +223,7 @@ class NotifyMeViewModelTest { } @Test - fun whenHandleRequestPermissionRationaleWithShouldShowRationaleTrueThenShowPermissionRationaleIsSent() = runTest { + fun `handleRequestPermissionRationale - show permission rationale`() = runTest { val shouldShowRationale = true testee.handleRequestPermissionRationale(shouldShowRationale) @@ -237,7 +237,7 @@ class NotifyMeViewModelTest { } @Test - fun whenHandleRequestPermissionRationaleOnAndroid8WithShouldShowRationaleFalseThenOpenSettingsOnAndroid8PlusCommandIsSent() = runTest { + fun `handleRequestPermissionRationale - should show rationale false - open settings on Android 8 plus command is sent`() = runTest { whenever(mockAppBuildConfig.sdkInt).thenReturn(Build.VERSION_CODES.O) val shouldShowRationale = false @@ -252,7 +252,7 @@ class NotifyMeViewModelTest { } @Test - fun whenOnResumeCalledForAndroid13PlusThenUpdateNotificationsStateOnAndroid13PlusCommandIsSent() = runTest { + fun `onResume - android 13 plus - update notifications state on android 13 plus command is sent`() = runTest { whenever(mockAppBuildConfig.sdkInt).thenReturn(Build.VERSION_CODES.TIRAMISU) testee.onResume(mockLifecycleOwner) @@ -266,7 +266,7 @@ class NotifyMeViewModelTest { } @Test - fun whenOnResumeCalledForAndroid12OrBelowThenUpdateNotificationsStateCommandIsSent() = runTest { + fun `onResume - android 12 or below - update notifications state command sent`() = runTest { whenever(mockAppBuildConfig.sdkInt).thenReturn(Build.VERSION_CODES.S) testee.onResume(mockLifecycleOwner) diff --git a/common/common-utils/src/test/java/com/duckduckgo/common/utils/extensions/LocaleExtensionsTest.kt b/common/common-utils/src/test/java/com/duckduckgo/common/utils/extensions/LocaleExtensionsTest.kt index 0e9918f42d18..4e9bee9a4c25 100644 --- a/common/common-utils/src/test/java/com/duckduckgo/common/utils/extensions/LocaleExtensionsTest.kt +++ b/common/common-utils/src/test/java/com/duckduckgo/common/utils/extensions/LocaleExtensionsTest.kt @@ -7,7 +7,7 @@ import org.junit.Test class LocaleExtensionsTest { @Test - fun whenHasUnicodeLocaleExtensionThenRemoveUnicodeLocaleExtension() { + fun `whenHasUnicodeLocaleExtensionThenRemoveUnicodeLocaleExtension - remove unicode locale extension`() { val locale = Locale.Builder() .setLanguage("en") .setRegion("US") @@ -19,7 +19,7 @@ class LocaleExtensionsTest { } @Test - fun whenDoesNotHaveUnicodeLocaleExtensionThenLanguageTagIsUnchanged() { + fun `whenDoesNotHaveUnicodeLocaleExtension - language tag unchanged`() { val locale = Locale.Builder() .setLanguage("en") .setRegion("US") diff --git a/common/common-utils/src/test/java/com/duckduckgo/common/utils/formatters/data/DataSizeFormatterTest.kt b/common/common-utils/src/test/java/com/duckduckgo/common/utils/formatters/data/DataSizeFormatterTest.kt index e74254622781..16ded53b2ead 100644 --- a/common/common-utils/src/test/java/com/duckduckgo/common/utils/formatters/data/DataSizeFormatterTest.kt +++ b/common/common-utils/src/test/java/com/duckduckgo/common/utils/formatters/data/DataSizeFormatterTest.kt @@ -32,32 +32,32 @@ class DataSizeFormatterTest { } @Test - fun whenNoDataThen0BytesReturned() { + fun `format - no data - 0 bytes returned`() { assertEquals("0 bytes", testee.format(0)) } @Test - fun whenLessThat1KbThenBytesReturned() { + fun `format - less than 1kb - bytes returned`() { assertEquals("100 bytes", testee.format(100)) } @Test - fun whenExactlyOn1KbThenKbReturned() { + fun `format - exactly 1KB - returns 1KB`() { assertEquals("1 KB", testee.format(1000)) } @Test - fun whenNotAWholeNumberOfKilobytesThenKbReturned() { + fun `format - not a whole number of kilobytes - returns 1·5 KB`() { assertEquals("1.5 KB", testee.format(1501)) } @Test - fun whenExactly1MegabyteThenMbReturned() { + fun `format - exactly 1 megabyte - 1 mb returned`() { assertEquals("1 MB", testee.format(1_000_000)) } @Test - fun whenExactly1GigabyteThenGbReturned() { + fun `format - exactly 1 gigabyte - returns 1 gb`() { assertEquals("1 GB", testee.format(1_000_000_000)) } } diff --git a/common/common-utils/src/test/java/com/duckduckgo/common/utils/formatters/time/DatabaseDateFormatterTest.kt b/common/common-utils/src/test/java/com/duckduckgo/common/utils/formatters/time/DatabaseDateFormatterTest.kt index 9c2642771969..9c75aab070a6 100644 --- a/common/common-utils/src/test/java/com/duckduckgo/common/utils/formatters/time/DatabaseDateFormatterTest.kt +++ b/common/common-utils/src/test/java/com/duckduckgo/common/utils/formatters/time/DatabaseDateFormatterTest.kt @@ -27,25 +27,25 @@ import org.junit.Test class DatabaseDateFormatterTest { @Test - fun whenBucketingByHourOnlyHourlyPrecisionIsUsed() { + fun `bucketByHour - only hourly precision used`() { val formatted = DatabaseDateFormatter.bucketByHour(fixedTime()) assertEquals("2020-12-25T13:00:00", formatted) } @Test - fun whenBucketingByTimestampOnlySecondsPrecisionIsUsed() { + fun `formatTimestamp - seconds precision used`() { val formatted = DatabaseDateFormatter.timestamp(fixedTime()) assertEquals("2020-12-25T13:14:15", formatted) } @Test - fun whenIso8601isUsedThenDateIsFormatted() { + fun `iso8601 - date formatted`() { val formatted = DatabaseDateFormatter.iso8601(fixedUTCTime()) assertEquals("2020-12-25T13:14:15.000000016Z", formatted) } @Test - fun whenIso8601isParsedThenDateIsCorrect() { + fun `parseIso8601 - date is correct`() { val now = OffsetDateTime.now(ZoneOffset.UTC) .truncatedTo(ChronoUnit.MILLIS) // SystemClock returns time with higher precision on JVM val format = DatabaseDateFormatter.iso8601(now) @@ -56,7 +56,7 @@ class DatabaseDateFormatterTest { } @Test - fun whenParsingSystemTimeMillisToIso8601ThenStringRepresentsExpectedDateTime() { + fun `parseSystemTimeToIso8601 - string represents expected datetime`() { val timeInMillisNow = System.currentTimeMillis() val formattedMillis = DatabaseDateFormatter.parseMillisIso8601(timeInMillisNow) @@ -70,7 +70,7 @@ class DatabaseDateFormatterTest { } @Test - fun whenParsingIso8601ToMillisThenMillisRepresentsExpectedDateTime() { + fun `parseIso8601ToMillis - parsing iso 8601 to millis - represents expected datetime`() { val timeInMillisNow = System.currentTimeMillis() val iso8601String = DatabaseDateFormatter.parseMillisIso8601(timeInMillisNow) diff --git a/common/common-utils/src/test/java/com/duckduckgo/common/utils/formatters/time/model/TimePassedTest.kt b/common/common-utils/src/test/java/com/duckduckgo/common/utils/formatters/time/model/TimePassedTest.kt index 628f100f927f..121440a31fee 100644 --- a/common/common-utils/src/test/java/com/duckduckgo/common/utils/formatters/time/model/TimePassedTest.kt +++ b/common/common-utils/src/test/java/com/duckduckgo/common/utils/formatters/time/model/TimePassedTest.kt @@ -29,79 +29,79 @@ class TimePassedTest { private val resources = getApplicationContext().resources @Test - fun whenOnlyHoursPassedThenFormatsProperTime() { + fun `format - only hours passed - proper time`() { val timePassed = TimePassed(1, 0, 0) assertEquals("1 hr 0 min 0 sec", timePassed.format(resources = resources)) } @Test - fun whenOnlyMinutesPassedThenFormatsProperTime() { + fun `format - only minutes passed - proper time`() { val timePassed = TimePassed(0, 10, 0) assertEquals("0 hr 10 min 0 sec", timePassed.format(resources = resources)) } @Test - fun whenOnlySecondsPassedThenFormatsProperTime() { + fun `format - only seconds passed - proper time`() { val timePassed = TimePassed(0, 0, 25) assertEquals("0 hr 0 min 25 sec", timePassed.format(resources = resources)) } @Test - fun whenHoursAndMinutesPassedThenFormatsProperTime() { + fun `format - hours and minutes passed - proper time`() { val timePassed = TimePassed(1, 10, 0) assertEquals("1 hr 10 min 0 sec", timePassed.format(resources = resources)) } @Test - fun whenHoursAndSecondsPassedThenFormatsProperTime() { + fun `format - hours and seconds passed - proper time`() { val timePassed = TimePassed(1, 0, 30) assertEquals("1 hr 0 min 30 sec", timePassed.format(resources = resources)) } @Test - fun whenMinutesAndSecondsPassedThenFormatsProperTime() { + fun `format - minutes and seconds passed - proper time`() { val timePassed = TimePassed(0, 10, 10) assertEquals("0 hr 10 min 10 sec", timePassed.format(resources = resources)) } @Test - fun whenOnlyHoursPassedThenShortFormatsProperTime() { + fun `whenOnlyHoursPassedThenShortFormatsProperTime - short formats proper time`() { val timePassed = TimePassed(1, 0, 0) assertEquals("1h ago", timePassed.shortFormat(resources)) } @Test - fun whenOnlyMinutesPassedThenShortFormatsProperTime() { + fun `whenOnlyMinutesPassedThenShortFormatsProperTime - short formats proper time`() { val timePassed = TimePassed(0, 10, 0) assertEquals("10m ago", timePassed.shortFormat(resources)) } @Test - fun whenOnlySecondsPassedThenShortFormatsProperTime() { + fun `whenOnlySecondsPassedThenShortFormatsProperTime - short formats proper time`() { val timePassed = TimePassed(0, 0, 45) assertEquals("Just Now", timePassed.shortFormat(resources)) } @Test - fun whenOnlyFewSecondsPassedThenShortFormatsProperTime() { + fun `whenOnlyFewSecondsPassed - short formats proper time - just now`() { val timePassed = TimePassed(0, 0, 25) assertEquals("Just Now", timePassed.shortFormat(resources)) } @Test - fun whenHoursAndMinutesPassedThenShortFormatsProperTime() { + fun `when HoursAndMinutesPassed Then Short Formats Proper Time - short formats proper time`() { val timePassed = TimePassed(1, 10, 0) assertEquals("1h ago", timePassed.shortFormat(resources)) } @Test - fun whenHoursAndSecondsPassedThenShortFormatsProperTime() { + fun `whenHoursAndSecondsPassed - short formats proper time`() { val timePassed = TimePassed(1, 0, 30) assertEquals("1h ago", timePassed.shortFormat(resources)) } @Test - fun whenMinutesAndSecondsPassedShortThenFormatsProperTime() { + fun `whenMinutesAndSecondsPassedShort - formats proper time`() { val timePassed = TimePassed(0, 10, 10) assertEquals("10m ago", timePassed.shortFormat(resources)) } diff --git a/common/common-utils/src/test/java/com/duckduckgo/common/utils/network/NetworkExtensionsTest.kt b/common/common-utils/src/test/java/com/duckduckgo/common/utils/network/NetworkExtensionsTest.kt index 13715b8a1e71..b95923509843 100644 --- a/common/common-utils/src/test/java/com/duckduckgo/common/utils/network/NetworkExtensionsTest.kt +++ b/common/common-utils/src/test/java/com/duckduckgo/common/utils/network/NetworkExtensionsTest.kt @@ -27,7 +27,7 @@ import org.junit.runner.RunWith class NetworkExtensionsTest { @Test - fun `test isCGNAT`() { + fun `test isCGNAT - cgnat range - true and false`() { // cover all CGNAT range for (octet2 in 64..127) { for (octet3 in 0..255) { diff --git a/content-scope-scripts/content-scope-scripts-impl/src/test/java/com/duckduckgo/contentscopescripts/impl/ContentScopeScriptsJsInjectorPluginTest.kt b/content-scope-scripts/content-scope-scripts-impl/src/test/java/com/duckduckgo/contentscopescripts/impl/ContentScopeScriptsJsInjectorPluginTest.kt index ca24512c77df..ecf19f3f1c83 100644 --- a/content-scope-scripts/content-scope-scripts-impl/src/test/java/com/duckduckgo/contentscopescripts/impl/ContentScopeScriptsJsInjectorPluginTest.kt +++ b/content-scope-scripts/content-scope-scripts-impl/src/test/java/com/duckduckgo/contentscopescripts/impl/ContentScopeScriptsJsInjectorPluginTest.kt @@ -26,7 +26,7 @@ class ContentScopeScriptsJsInjectorPluginTest { } @Test - fun whenEnabledAndInjectContentScopeScriptsThenPopulateMessagingParameters() { + fun `onPageStarted - enabled - populate messaging parameters`() { whenever(mockCoreContentScopeScripts.isEnabled()).thenReturn(true) whenever(mockCoreContentScopeScripts.getScript(null)).thenReturn("") contentScopeScriptsJsInjectorPlugin.onPageStarted(mockWebView, null, null) @@ -36,7 +36,7 @@ class ContentScopeScriptsJsInjectorPluginTest { } @Test - fun whenDisabledAndInjectContentScopeScriptsThenDoNothing() { + fun `onPageStarted - disabled - do nothing`() { whenever(mockCoreContentScopeScripts.isEnabled()).thenReturn(false) contentScopeScriptsJsInjectorPlugin.onPageStarted(mockWebView, null, null) @@ -44,7 +44,7 @@ class ContentScopeScriptsJsInjectorPluginTest { } @Test - fun whenEnabledAndInjectContentScopeScriptsThenUseSite() { + fun `onPageStarted - enabled and inject content scope scripts - use site`() { val site: Site = mock() whenever(mockCoreContentScopeScripts.isEnabled()).thenReturn(true) whenever(mockCoreContentScopeScripts.getScript(site)).thenReturn("") diff --git a/content-scope-scripts/content-scope-scripts-impl/src/test/java/com/duckduckgo/contentscopescripts/impl/RealContentScopeScriptsTest.kt b/content-scope-scripts/content-scope-scripts-impl/src/test/java/com/duckduckgo/contentscopescripts/impl/RealContentScopeScriptsTest.kt index 452df739ecad..0b9cfb468a37 100644 --- a/content-scope-scripts/content-scope-scripts-impl/src/test/java/com/duckduckgo/contentscopescripts/impl/RealContentScopeScriptsTest.kt +++ b/content-scope-scripts/content-scope-scripts-impl/src/test/java/com/duckduckgo/contentscopescripts/impl/RealContentScopeScriptsTest.kt @@ -72,7 +72,7 @@ class RealContentScopeScriptsTest { } @Test - fun whenGetScriptWhenVariablesAreCachedAndNoChangesThenUseCachedVariables() { + fun `getScript - variables cached and no changes - use cached variables`() { var js = testee.getScript(null) verifyJsScript(js) @@ -85,7 +85,7 @@ class RealContentScopeScriptsTest { } @Test - fun whenGetScriptAndVariablesAreCachedAndAllowListChangedThenUseNewAllowListValue() { + fun `getScript - allow list changed - use new allow list value`() { var js = testee.getScript(null) verifyJsScript(js) @@ -111,7 +111,7 @@ class RealContentScopeScriptsTest { } @Test - fun whenGetScriptAndVariablesAreCachedAndGpcChangedThenUseNewGpcValue() { + fun `getScript - gpc changed - use new gpc value`() { var js = testee.getScript(null) verifyJsScript(js) @@ -137,7 +137,7 @@ class RealContentScopeScriptsTest { } @Test - fun whenGetScriptAndVariablesAreCachedAndConfigChangedThenUseNewConfigValue() { + fun `getScript - config changed - use new config value`() { var js = testee.getScript(null) verifyJsScript(js) @@ -163,7 +163,7 @@ class RealContentScopeScriptsTest { } @Test - fun whenGetScriptAndVariablesAreCachedAndUnprotectedTemporaryChangedThenUseNewUnprotectedTemporaryValue() { + fun `getScript - cached and unprotected temporary changed - use new value`() { var js = testee.getScript(null) verifyJsScript(js) @@ -188,7 +188,7 @@ class RealContentScopeScriptsTest { } @Test - fun whenGetScriptAndVariablesAreCachedAndDesktopModeChangedThenUseNewDesktopModeValue() { + fun `getScript - desktop mode changed - use new desktop mode value`() { var js = testee.getScript(null) verifyJsScript(js) @@ -212,19 +212,19 @@ class RealContentScopeScriptsTest { } @Test - fun whenContentScopeScriptsIsEnabledThenReturnTrue() { + fun `isEnabled - content scope scripts enabled - true`() { whenever(mockContentScopeScriptsFeature.self()).thenReturn(EnabledToggle()) assertTrue(testee.isEnabled()) } @Test - fun whenContentScopeScriptsIsDisabledThenReturnFalse() { + fun `isEnabled - content scope scripts disabled - false`() { whenever(mockContentScopeScriptsFeature.self()).thenReturn(DisabledToggle()) assertFalse(testee.isEnabled()) } @Test - fun whenGetScriptThenPopulateMessagingParameters() { + fun `getScript - populate messaging parameters`() { val js = testee.getScript(null) verifyJsScript(js) verify(mockContentScopeJsReader).getContentScopeJS() diff --git a/content-scope-scripts/content-scope-scripts-impl/src/test/java/com/duckduckgo/contentscopescripts/impl/messaging/ContentScopeScriptsJsMessagingTest.kt b/content-scope-scripts/content-scope-scripts-impl/src/test/java/com/duckduckgo/contentscopescripts/impl/messaging/ContentScopeScriptsJsMessagingTest.kt index eead537c314c..d112b90ea2aa 100644 --- a/content-scope-scripts/content-scope-scripts-impl/src/test/java/com/duckduckgo/contentscopescripts/impl/messaging/ContentScopeScriptsJsMessagingTest.kt +++ b/content-scope-scripts/content-scope-scripts-impl/src/test/java/com/duckduckgo/contentscopescripts/impl/messaging/ContentScopeScriptsJsMessagingTest.kt @@ -57,7 +57,7 @@ class ContentScopeScriptsJsMessagingTest { } @Test - fun whenProcessUnknownMessageDoNothing() = runTest { + fun `processUnknownMessage - do nothing`() = runTest { givenInterfaceIsRegistered() contentScopeScriptsJsMessaging.process("", contentScopeScriptsJsMessaging.secret) @@ -66,7 +66,7 @@ class ContentScopeScriptsJsMessagingTest { } @Test - fun whenProcessUnknownSecretDoNothing() = runTest { + fun `processUnknownSecret - do nothing - counter unchanged`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -79,7 +79,7 @@ class ContentScopeScriptsJsMessagingTest { } @Test - fun whenProcessInterfaceNotRegisteredDoNothing() = runTest { + fun `processInterfaceNotRegistered - do nothing`() = runTest { whenever(mockWebView.url).thenReturn("https://example.com") val message = """ @@ -92,14 +92,14 @@ class ContentScopeScriptsJsMessagingTest { } @Test - fun whenRegisterInterfaceThenAddJsInterface() { + fun `register - add js interface`() { contentScopeScriptsJsMessaging.register(mockWebView, callback) verify(mockWebView).addJavascriptInterface(any(), anyOrNull()) } @Test - fun whenProcessAndWebShareThenCallbackExecutedAndNotResponseSent() = runTest { + fun `processAndWebShare - callback executed and not response sent`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -112,7 +112,7 @@ class ContentScopeScriptsJsMessagingTest { } @Test - fun whenProcessAndWebShareIfFeatureNameDoesNotMatchDoNothing() = runTest { + fun `processAndWebShareIfFeatureNameDoesNotMatch - do nothing`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -125,7 +125,7 @@ class ContentScopeScriptsJsMessagingTest { } @Test - fun whenProcessAndWebShareIfIdDoesNotExistThenDoNothing() = runTest { + fun `processAndWebShareIfIdDoesNotExist - do nothing`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -138,7 +138,7 @@ class ContentScopeScriptsJsMessagingTest { } @Test - fun whenProcessAndPermissionsQueryThenCallbackExecutedAndNotResponseSent() = runTest { + fun `processAndPermissionsQuery - callback executed and not response sent`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -151,7 +151,7 @@ class ContentScopeScriptsJsMessagingTest { } @Test - fun whenProcessAndPermissionsQueryIfIdDoesNotExistThenDoNothing() = runTest { + fun `processAndPermissionsQuery - id does not exist - do nothing`() = runTest { givenInterfaceIsRegistered() val message = """ diff --git a/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/CookiesContentScopeConfigPluginTest.kt b/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/CookiesContentScopeConfigPluginTest.kt index 2ddd062a9b97..159fd6494f8a 100644 --- a/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/CookiesContentScopeConfigPluginTest.kt +++ b/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/CookiesContentScopeConfigPluginTest.kt @@ -37,13 +37,13 @@ class CookiesContentScopeConfigPluginTest { } @Test - fun whenGetConfigThenReturnCorrectlyFormattedJson() { + fun `getConfig - get correctly formatted json - correctly formatted json`() { whenever(mockContentScopeScriptsCookieRepository.getCookieEntity()).thenReturn(CookieEntity(json = config)) assertEquals("\"cookie\":$config", testee.config()) } @Test - fun whenGetPreferencesThenReturnNull() { + fun `getPreferences - null`() { assertNull(testee.preferences()) } diff --git a/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/CookiesFeatureNameUtilTest.kt b/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/CookiesFeatureNameUtilTest.kt index 5894e645212d..eca347f83c16 100644 --- a/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/CookiesFeatureNameUtilTest.kt +++ b/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/CookiesFeatureNameUtilTest.kt @@ -25,19 +25,19 @@ import org.junit.runner.RunWith class CookiesFeatureNameUtilTest { @Test - fun whenQueryHasWhenThenReturnRedactedBase64Stacktrace() { + fun `redactStacktrace - has when - returns redacted base64 stack trace`() { val ss = redactStacktraceInBase64(WITH_WHEN) assertEquals(WITH_WHEN_BASE634, ss) } @Test - fun whenQueryDoesNotHaveWhenThenReturnBase64Stacktrace() { + fun `redactStacktraceInBase64 - without when - returns base64 stack trace`() { val ss = redactStacktraceInBase64(WITHOUT_WHEN) assertEquals(WITHOUT_WHEN_BASE64, ss) } @Test - fun whenQueryOneLineThenReturnBase64Stacktrace() { + fun `queryOneLine - return base64 stack trace`() { val ss = redactStacktraceInBase64(WITHOUT_NEW_LINE) assertEquals(WITHOUT_NEW_LINE_BASE64, ss) } diff --git a/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/RemoveCookiesTest.kt b/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/RemoveCookiesTest.kt index c81c6675888c..37f09fc14ddc 100644 --- a/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/RemoveCookiesTest.kt +++ b/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/RemoveCookiesTest.kt @@ -31,7 +31,7 @@ class RemoveCookiesTest { private val removeCookies = RemoveCookies(cookieManagerRemover, selectiveCookieRemover) @Test - fun whenSelectiveCookieRemoverSucceedsThenNoMoreInteractions() = runTest { + fun `selectiveCookieRemover - succeeds - no more interactions`() = runTest { selectiveCookieRemover.succeeds() removeCookies.removeCookies() @@ -40,7 +40,7 @@ class RemoveCookiesTest { } @Test - fun whenSelectiveCookieRemoverFailsThenFallbackToCookieManagerRemover() = runTest { + fun `whenSelectiveCookieRemoverFails - fallback to cookie manager remover`() = runTest { selectiveCookieRemover.fails() removeCookies.removeCookies() diff --git a/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/WebViewCookieManagerTest.kt b/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/WebViewCookieManagerTest.kt index 0959b128eb95..79eef565669f 100644 --- a/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/WebViewCookieManagerTest.kt +++ b/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/WebViewCookieManagerTest.kt @@ -58,7 +58,7 @@ class WebViewCookieManagerTest { } @Test - fun whenCookiesRemovedThenInternalCookiesRecreated() = runTest { + fun `removeExternalCookies - internal cookies recreated`() = runTest { givenCookieManagerWithCookies(ddgCookie, externalHostCookie) withContext(coroutineRule.testDispatcherProvider.main()) { @@ -69,7 +69,7 @@ class WebViewCookieManagerTest { } @Test - fun whenCookiesStoredThenRemoveCookiesExecuted() = runTest { + fun `removeExternalCookies - cookies stored - remove cookies executed`() = runTest { givenCookieManagerWithCookies(ddgCookie, externalHostCookie) withContext(coroutineRule.testDispatcherProvider.main()) { @@ -80,7 +80,7 @@ class WebViewCookieManagerTest { } @Test - fun whenCookiesStoredThenFlushBeforeAndAfterInteractingWithCookieManager() = runTest { + fun `removeExternalCookies - flush before and after interacting with cookie manager`() = runTest { givenCookieManagerWithCookies(ddgCookie, externalHostCookie) withContext(coroutineRule.testDispatcherProvider.main()) { @@ -97,7 +97,7 @@ class WebViewCookieManagerTest { } @Test - fun whenNoCookiesThenRemoveProcessNotExecuted() = runTest { + fun `removeExternalCookies - no cookies - remove process not executed`() = runTest { givenCookieManagerWithCookies() withContext(coroutineRule.testDispatcherProvider.main()) { diff --git a/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/features/CookiesFeaturePluginTest.kt b/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/features/CookiesFeaturePluginTest.kt index 2d3400664128..1e79224df95d 100644 --- a/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/features/CookiesFeaturePluginTest.kt +++ b/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/features/CookiesFeaturePluginTest.kt @@ -46,19 +46,19 @@ class CookiesFeaturePluginTest { } @Test - fun whenFeatureNameDoesNotMatchCookiesThenReturnFalse() { + fun `store - feature name does not match cookies - returns false`() { CookiesFeatureName.values().filter { it != FEATURE_NAME }.forEach { assertFalse(testee.store(it.value, EMPTY_JSON_STRING)) } } @Test - fun whenFeatureNameMatchesCookiesThenReturnTrue() { + fun `store - feature name matches cookies - returns true`() { TestCase.assertTrue(testee.store(FEATURE_NAME_VALUE, EMPTY_JSON_STRING)) } @Test - fun whenFeatureNameMatchesCookiesAndIsEnabledThenStoreFeatureEnabled() { + fun `store - feature name matches cookies and is enabled - store feature enabled`() { val jsonString = FileUtilities.loadText(CookiesFeaturePluginTest::class.java.classLoader!!, "json/cookies.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -67,7 +67,7 @@ class CookiesFeaturePluginTest { } @Test - fun whenFeatureNameMatchesCookiesAndIsNotEnabledThenStoreFeatureDisabled() { + fun `store - feature name matches cookies and is not enabled - store feature disabled`() { val jsonString = FileUtilities.loadText( CookiesFeaturePluginTest::class.java.classLoader!!, "json/cookies_disabled.json", @@ -79,7 +79,7 @@ class CookiesFeaturePluginTest { } @Test - fun whenFeatureNameMatchesCookiesAndHasMinSupportedVersionThenStoreMinSupportedVersion() { + fun `store - feature name matches cookies and has min supported version - store min supported version`() { val jsonString = FileUtilities.loadText(CookiesFeaturePluginTest::class.java.classLoader!!, "json/cookies_min_supported_version.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -88,7 +88,7 @@ class CookiesFeaturePluginTest { } @Test - fun whenFeatureNameMatchesCookiesThenUpdateAllExistingValues() { + fun `whenFeatureNameMatchesCookies - update all existing values - updates cookies and policies`() { val jsonString = FileUtilities.loadText(CookiesFeaturePluginTest::class.java.classLoader!!, "json/cookies.json") testee.store(FEATURE_NAME_VALUE, jsonString) diff --git a/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/features/CookiesFeatureTogglesPluginTest.kt b/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/features/CookiesFeatureTogglesPluginTest.kt index 1d0f3314e039..c8cef29acd07 100644 --- a/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/features/CookiesFeatureTogglesPluginTest.kt +++ b/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/features/CookiesFeatureTogglesPluginTest.kt @@ -45,12 +45,12 @@ class CookiesFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsNotACookieFeatureThenReturnNull() = runTest { + fun `isEnabled - is not a cookie feature - return null`() = runTest { assertNull(testee.isEnabled(NonPrivacyFeature().value, true)) } @Test - fun whenIsEnabledAndFeatureIsCookieFeatureThenReturnTrueWhenEnabled() = + fun `isEnabled - cookie feature enabled - returns true when enabled`() = runTest { giveCookieFeatureIsEnabled() @@ -60,7 +60,7 @@ class CookiesFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsCookieFeatureThenReturnFalseWhenDisabled() = + fun `isEnabled - cookie feature disabled - returns false when disabled`() = runTest { givenCookieFeatureIsDisabled() @@ -70,7 +70,7 @@ class CookiesFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsCookieFeatureThenReturnDefaultValueIfFeatureDoesNotExist() = + fun `isEnabled - cookie feature does not exist - return default value`() = runTest { val defaultValue = true givenCookieFeatureReturnsDefaultValue(defaultValue) @@ -82,7 +82,7 @@ class CookiesFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsCookieFeatureAndAppVersionEqualToMinSupportedVersionThenReturnTrueWhenEnabled() = + fun `isEnabled - cookie feature enabled and app version equal to min supported version - returns true when enabled`() = runTest { giveCookieFeatureIsEnabled() givenAppVersionIsEqualToMinSupportedVersion() @@ -93,7 +93,7 @@ class CookiesFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsCookieFeatureAndAppVersionIsGreaterThanMinSupportedVersionThenReturnTrueWhenEnabled() = + fun `isEnabled - cookie feature enabled and app version greater than min supported version - returns true when enabled`() = runTest { giveCookieFeatureIsEnabled() givenAppVersionIsGreaterThanMinSupportedVersion() @@ -104,7 +104,7 @@ class CookiesFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsCookieFeatureAndAppVersionIsSmallerThanMinSupportedVersionThenReturnFalseWhenEnabled() = + fun `isEnabled - cookie feature enabled and app version smaller than min supported version - false when enabled`() = runTest { giveCookieFeatureIsEnabled() givenAppVersionIsSmallerThanMinSupportedVersion() diff --git a/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/features/firstparty/FirstPartyCookiesModifierWorkerSchedulerTest.kt b/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/features/firstparty/FirstPartyCookiesModifierWorkerSchedulerTest.kt index aa2012634106..acfda47102b5 100644 --- a/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/features/firstparty/FirstPartyCookiesModifierWorkerSchedulerTest.kt +++ b/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/features/firstparty/FirstPartyCookiesModifierWorkerSchedulerTest.kt @@ -44,7 +44,7 @@ class FirstPartyCookiesModifierWorkerSchedulerTest { } @Test - fun whenOnStopIfFeatureEnabledThenEnqueueWorkWithReplacePolicy() { + fun `onStop - feature enabled - enqueue work with replace policy`() { whenever(mockToggle.isFeatureEnabled(CookiesFeatureName.Cookie.value)).thenReturn(true) firstPartyCookiesModifierWorkerScheduler.onStop(mockOwner) @@ -53,7 +53,7 @@ class FirstPartyCookiesModifierWorkerSchedulerTest { } @Test - fun whenOnStopIfFeatureNotEnabledThenDeleteTag() { + fun `onStop - feature not enabled - delete tag`() { whenever(mockToggle.isFeatureEnabled(CookiesFeatureName.Cookie.value)).thenReturn(false) firstPartyCookiesModifierWorkerScheduler.onStop(mockOwner) @@ -62,7 +62,7 @@ class FirstPartyCookiesModifierWorkerSchedulerTest { } @Test - fun whenOnStartIfFeatureEnabledThenEnqueueWorkWithKeepPolicy() { + fun `onStart - feature enabled - enqueue work with keep policy`() { whenever(mockToggle.isFeatureEnabled(CookiesFeatureName.Cookie.value)).thenReturn(true) firstPartyCookiesModifierWorkerScheduler.onStart(mockOwner) @@ -71,7 +71,7 @@ class FirstPartyCookiesModifierWorkerSchedulerTest { } @Test - fun whenOnStartIfFeatureNotEnabledThenDeleteTag() { + fun `onStart - feature not enabled - delete tag`() { whenever(mockToggle.isFeatureEnabled(CookiesFeatureName.Cookie.value)).thenReturn(false) firstPartyCookiesModifierWorkerScheduler.onStart(mockOwner) diff --git a/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/features/firstparty/FirstPartyCookiesModifierWorkerTest.kt b/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/features/firstparty/FirstPartyCookiesModifierWorkerTest.kt index 87bccbbdb0a0..fabb948a33c6 100644 --- a/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/features/firstparty/FirstPartyCookiesModifierWorkerTest.kt +++ b/cookies/cookies-impl/src/test/java/com/duckduckgo/cookies/impl/features/firstparty/FirstPartyCookiesModifierWorkerTest.kt @@ -40,7 +40,7 @@ class FirstPartyCookiesModifierWorkerTest { } @Test - fun whenDoWorkThenReturnSuccess() = runTest { + fun `doWork - return success`() = runTest { val worker = TestListenableWorkerBuilder(context = context).build() worker.firstPartyCookiesModifier = mockFirstPartyCookiesModifier diff --git a/cookies/cookies-store/src/test/java/com/duckduckgo/cookies/store/RealCookieRepositoryTest.kt b/cookies/cookies-store/src/test/java/com/duckduckgo/cookies/store/RealCookieRepositoryTest.kt index bf54252d0ef0..64b99995a525 100644 --- a/cookies/cookies-store/src/test/java/com/duckduckgo/cookies/store/RealCookieRepositoryTest.kt +++ b/cookies/cookies-store/src/test/java/com/duckduckgo/cookies/store/RealCookieRepositoryTest.kt @@ -45,7 +45,7 @@ class RealCookieRepositoryTest { } @Test - fun whenRepositoryIsCreatedThenValuesLoadedIntoMemory() { + fun `whenRepositoryIsCreated - values loaded into memory`() { givenCookiesDaoHasContent() testee = RealCookieRepository( @@ -61,7 +61,7 @@ class RealCookieRepositoryTest { } @Test - fun whenLoadToMemoryAndNoPolicyThenSetDefaultValues() { + fun `loadToMemory - no policy - set default values`() { whenever(mockCookiesDao.getFirstPartyCookiePolicy()).thenReturn(null) testee = RealCookieRepository( @@ -76,7 +76,7 @@ class RealCookieRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() { + fun `updateAll - update all called`() { val policy = FirstPartyCookiePolicyEntity(5, 6, 7) testee = RealCookieRepository( @@ -92,7 +92,7 @@ class RealCookieRepositoryTest { } @Test - fun whenUpdateAllThenPreviousValuesAreCleared() { + fun `updateAll - previous values cleared`() { givenCookiesDaoHasContent() testee = RealCookieRepository( diff --git a/cookies/cookies-store/src/test/java/com/duckduckgo/cookies/store/RealCookiesFeatureToggleRepositoryTest.kt b/cookies/cookies-store/src/test/java/com/duckduckgo/cookies/store/RealCookiesFeatureToggleRepositoryTest.kt index 4f7726af2038..5b5828166a48 100644 --- a/cookies/cookies-store/src/test/java/com/duckduckgo/cookies/store/RealCookiesFeatureToggleRepositoryTest.kt +++ b/cookies/cookies-store/src/test/java/com/duckduckgo/cookies/store/RealCookiesFeatureToggleRepositoryTest.kt @@ -33,21 +33,21 @@ class RealCookiesFeatureToggleRepositoryTest { } @Test - fun whenDeleteAllThenDeleteAllCalled() { + fun `deleteAll - cookies feature toggle store deleted`() { testee.deleteAll() verify(mockCookiesFeatureToggleStore).deleteAll() } @Test - fun whenGetThenGetCalled() { + fun `get - cookies feature toggle store get called`() { testee.get(Cookie, true) verify(mockCookiesFeatureToggleStore).get(Cookie, true) } @Test - fun whenInsertThenInsertCalled() { + fun `insert - cookies feature toggle store inserted`() { val cookieFeatureToggle = CookiesFeatureToggles(Cookie, true, null) testee.insert(cookieFeatureToggle) diff --git a/data-store/data-store-impl/src/test/java/com/duckduckgo/data/store/impl/SharedPreferencesProviderImplTest.kt b/data-store/data-store-impl/src/test/java/com/duckduckgo/data/store/impl/SharedPreferencesProviderImplTest.kt index 54e78536b070..249914195cfe 100644 --- a/data-store/data-store-impl/src/test/java/com/duckduckgo/data/store/impl/SharedPreferencesProviderImplTest.kt +++ b/data-store/data-store-impl/src/test/java/com/duckduckgo/data/store/impl/SharedPreferencesProviderImplTest.kt @@ -46,7 +46,7 @@ class SharedPreferencesProviderImplTest { } @Test - fun whenGetMultiprocessPreferencesThenMigrateToHarmony() { + fun `getMultiprocessPreferences - migrate to harmony - migrated`() { prefs.edit(commit = true) { putBoolean("bool", true) } prefs.edit(commit = true) { putString("string", "true") } prefs.edit(commit = true) { putInt("int", 1) } @@ -63,7 +63,7 @@ class SharedPreferencesProviderImplTest { } @Test - fun whenGetMultiprocessPreferencesAndMigrateIsFalseThenDoNotMigrateToHarmony() { + fun `getMultiprocessPreferences - migrate is false - do not migrate to harmony`() { prefs.edit(commit = true) { putBoolean("bool", true) } prefs.edit(commit = true) { putString("string", "true") } prefs.edit(commit = true) { putInt("int", 1) } @@ -80,7 +80,7 @@ class SharedPreferencesProviderImplTest { } @Test - fun testSafeSharedPreferences() { + fun `testSafeSharedPreferences - safe shared preferences - all values set and retrieved correctly`() { val prefs = com.duckduckgo.data.store.impl.SafeSharedPreferences(vpnPreferencesProvider.getSharedPreferences(NAME)) prefs.edit(commit = true) { putBoolean("bool", true) } diff --git a/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/DataUriParserTest.kt b/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/DataUriParserTest.kt index 3490216f3468..d5ae01e3bb5b 100644 --- a/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/DataUriParserTest.kt +++ b/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/DataUriParserTest.kt @@ -42,103 +42,103 @@ class DataUriParserTest { } @Test - fun whenMimeTypeProvidedAsImagePngThenPngSuffixGenerated() { + fun `generate - mime type provided as image png - png suffix generated`() { val parsed = testee.generate("data:image/png;base64,AAAA") as ParsedDataUri assertEquals("png", parsed.filename.fileType) } @Test - fun whenMimeTypeProvidedAsImageJpegThenJpgSuffixGenerated() { + fun `generate - mime type provided as image jpeg - jpg suffix generated`() { val parsed = testee.generate("data:image/jpeg;base64,AAAA") as ParsedDataUri assertEquals("jpg", parsed.filename.fileType) } @Test - fun whenMimeTypeProvidedAsArbitraryImageTypeThenNoSuffixGenerated() { + fun `generate - mime type provided - no suffix generated`() { val parsed = testee.generate("data:image/foo;base64,AAAA") as ParsedDataUri assertEquals("", parsed.filename.fileType) } @Test - fun whenMimeTypeNotProvidedThenNoSuffixAdded() { + fun `generate - no mime type provided - no suffix added`() { val parsed = testee.generate("data:,AAAA") as ParsedDataUri assertEquals("", parsed.filename.fileType) } @Test - fun whenInvalidDataUriProvidedInvalidTypeTurned() { + fun `generate - invalid data uri provided - turned to invalid type`() { val parsed = testee.generate("AAAA") assertTrue(parsed === Invalid) } @Test - fun whenInvalidDataUriContainingCommaIsProvidedTheInvalidTypeTurned() { + fun `generate - invalid data uri containing comma - turned to invalid type`() { val parsed = testee.generate("data:,") assertTrue(parsed === Invalid) } @Test - fun whenKnownMimeTypeProvidedAsNonImageTypeThenSuffixStillGenerated() { + fun `generate - known mime type provided as non-image type - suffix still generated`() { val parsed = testee.generate("data:text/plain;base64,AAAA") as ParsedDataUri assertEquals("txt", parsed.filename.fileType) } @Test - fun whenMimeTypeNotProvidedThenNoSuffixAddedInToString() { + fun `generate - no suffix added in toString - does not contain dot`() { val filename = testee.generate("data:,AAAA") as ParsedDataUri assertFalse(filename.toString().contains(".")) } @Test - fun whenMimeTypeIsTextPlainAndDataIsBase64AndIsPngThenSuffixIsPng() { + fun `generate - mime type is text plain and data is base 64 and is png - suffix is png`() { val parsed = testee.generate("data:text/plain;base64,iVBORw0KGgo") as ParsedDataUri assertEquals("png", parsed.filename.fileType) } @Test - fun whenMimeTypeIsTextPlainAndDataIsBase64AndIsJfifThenSuffixIsJpg() { + fun `generate - mime type is text plain and data is base 64 and is jfif - suffix is jpg`() { val parsed = testee.generate("data:text/plain;base64,/9j/4AAQSkZJRgABAQ") as ParsedDataUri assertEquals("jpg", parsed.filename.fileType) } @Test - fun whenMimeTypeIsTextPlainAndDataIsBase64AndIsSvgThenSuffixIsSvg() { + fun `generate - mime type is text plain and data is base64 and is svg - suffix is svg`() { val parsed = testee.generate("data:text/plain;base64,PHN2ZyB2ZXJzaW9uPSIxLjIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy") as ParsedDataUri assertEquals("svg", parsed.filename.fileType) } @Test - fun whenMimeTypeIsTextPlainAndDataIsBase64AndIsGifThenSuffixIsGif() { + fun `generate - mime type is text plain and data is base 64 and is gif - suffix is gif`() { val parsed = testee.generate("data:text/plain;base64,R0lGODlhAAXQAocAAP") as ParsedDataUri assertEquals("gif", parsed.filename.fileType) } @Test - fun whenMimeTypeIsTextPlainAndDataIsBase64AndIsPdfThenSuffixIsPdf() { + fun `generate - mime type is text plain and data is base 64 and is pdf - suffix is pdf`() { val parsed = testee.generate("data:text/plain;base64,JVBERi0xLjEKMSAwIG9iag") as ParsedDataUri assertEquals("pdf", parsed.filename.fileType) } @Test - fun whenMimeTypeIsTextPlainAndDataIsBase64AndIsWebpThenSuffixIsWebp() { + fun `generate - mime type is text plain and data is base 64 and is webp - suffix is webp`() { val parsed = testee.generate("data:text/plain;base64,UklGRs4IAABXRUJQVlA4WAo") as ParsedDataUri assertEquals("webp", parsed.filename.fileType) } @Test - fun whenMimeTypeIsTextPlainAndDataIsBase64AndIsBpThenSuffixIsBmp() { + fun `generate - mime type is text plain and data is base 64 and is bp - suffix is bmp`() { val parsed = testee.generate("data:text/plain;base64,Qk1AwgEA") as ParsedDataUri assertEquals("bmp", parsed.filename.fileType) } @Test - fun whenMimeTypeIsTextPlainAndDataIsBase64AndIsUnknownThenSuffixIsTxt() { + fun `generate - mime type is text plain and data is base 64 and is unknown - suffix is txt`() { val parsed = testee.generate("data:text/plain;base64,RUJQVlA4WAo") as ParsedDataUri assertEquals("txt", parsed.filename.fileType) } @Test - fun whenMimeTypeIsImageJpegThenSuffixIsJpg() { + fun `generate - mime type is image jpeg - suffix is jpg`() { val parsed = testee.generate("data:image/jpeg;base64,RUJQVlA4WAo") as ParsedDataUri assertEquals("jpg", parsed.filename.fileType) } diff --git a/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/DefaultDownloadsRepositoryTest.kt b/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/DefaultDownloadsRepositoryTest.kt index 835ed1ee9461..fc07c5665029 100644 --- a/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/DefaultDownloadsRepositoryTest.kt +++ b/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/DefaultDownloadsRepositoryTest.kt @@ -49,7 +49,7 @@ class DefaultDownloadsRepositoryTest { } @Test - fun whenInsertDownloadItemThenInsertCalled() = runTest { + fun `insert - download item inserted - insert called`() = runTest { val item = oneItem() val entity = oneEntity() @@ -60,7 +60,7 @@ class DefaultDownloadsRepositoryTest { } @Test - fun whenInsertAllDownloadItemsThenInsertAllCalled() = runTest { + fun `insertAll - download items inserted`() = runTest { val firstItem = oneItem() val secondItem = otherItem() val firstEntity = oneEntity() @@ -73,7 +73,7 @@ class DefaultDownloadsRepositoryTest { } @Test - fun whenUpdateDownloadItemByIdWithDownloadStatusFinishedAndContentLengthThenUpdateCalledWithSameParams() = + fun `update - update called with same params`() = runTest { val item = oneItem() val updatedStatus = FINISHED @@ -117,7 +117,7 @@ class DefaultDownloadsRepositoryTest { } @Test - fun whenUpdateDownloadItemByFileNameWithDownloadStatusFinishedAndContentLengthThenUpdateCalledWithSameParams() = + fun `update - download status finished and content length - update called with same params`() = runTest { val item = oneItem().copy(downloadId = 0L) val updatedStatus = FINISHED @@ -139,7 +139,7 @@ class DefaultDownloadsRepositoryTest { } @Test - fun whenUpdateDownloadItemByFileNameWithDownloadStatusStartedAndContentLengthThenUpdateCalledWithSameParams() = + fun `update - download status started and content length - update called with same params`() = runTest { val item = oneItem().copy(downloadId = 0L) val updatedStatus = FINISHED @@ -161,7 +161,7 @@ class DefaultDownloadsRepositoryTest { } @Test - fun whenDeleteDownloadItemThenDeleteCalled() = runTest { + fun `delete - download item deleted - delete called`() = runTest { val item = oneItem() repository.delete(item.downloadId) @@ -171,7 +171,7 @@ class DefaultDownloadsRepositoryTest { } @Test - fun whenDeleteListOfDownloadItemsThenDeleteCalled() = runTest { + fun `deleteListOfDownloadItems - delete called`() = runTest { val firstItem = oneItem() val secondItem = otherItem() @@ -182,7 +182,7 @@ class DefaultDownloadsRepositoryTest { } @Test - fun whenDeleteAllDownloadItemsThenDeleteWithNoParamsCalled() = runTest { + fun `deleteAll - delete with no params called`() = runTest { val entity = oneEntity() whenever(mockDb.downloadsDao().getDownloads()).thenReturn(listOf(entity)) @@ -193,7 +193,7 @@ class DefaultDownloadsRepositoryTest { } @Test - fun whenGetDownloadItemCalledThenGetDownloadItemCalled() = runTest { + fun `getDownloadItem - get download item called`() = runTest { val item = oneItem() val entity = oneEntity() whenever(mockDb.downloadsDao().getDownloadItem(item.downloadId)).thenReturn(entity) @@ -204,7 +204,7 @@ class DefaultDownloadsRepositoryTest { } @Test - fun whenGetDownloadItemsCalledThenGetDownloadsCalled() = runTest { + fun `getDownloadItems - get downloads called`() = runTest { whenever(mockDb.downloadsDao().getDownloads()).thenReturn(listOf(oneEntity())) repository.getDownloads() diff --git a/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/DownloaderUtilTest.kt b/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/DownloaderUtilTest.kt index fa76348e7c0c..fd97dd8e06c9 100644 --- a/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/DownloaderUtilTest.kt +++ b/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/DownloaderUtilTest.kt @@ -33,7 +33,7 @@ class DownloaderUtilTest { } @Test - fun whenNullContentDispositionAndApplicationPdfContentTypeAndIncorrectFileExtensionInUrlThenCorrectFilenameExtracted() { + fun `guessFileName - null content disposition and application pdf content type and incorrect file extension in url - correct filename extracted`() { assertEquals( "display_pdf.pdf", DownloaderUtil.guessFileName( @@ -47,7 +47,7 @@ class DownloaderUtilTest { } @Test - fun whenNullContentDispositionAndImageJpegContentTypeAndUnsupportedCharsInFilenameInsideUrlThenCorrectFilenameExtracted() { + fun `guessFileName - null content disposition and image/jpeg content type - correct filename extracted`() { assertEquals( "0_BRkMUINdhCYPk1KM.jpg", DownloaderUtil.guessFileName( @@ -59,7 +59,7 @@ class DownloaderUtilTest { } @Test - fun whenAttachmentWithFilenameContentDispositionAndApplicationPdfContentTypeAndCorrectFileExtensionInUrlThenCorrectFilenameExtracted() { + fun `guessFileName - attachment with filename and correct file extension in url - correct filename extracted`() { assertEquals( "MENU_2103.pdf", DownloaderUtil.guessFileName( @@ -71,7 +71,7 @@ class DownloaderUtilTest { } @Test - fun whenAttachmentWithFilenameContentDispositionAndApplicationOctetStreamContentTypeAndCorrectFileExtensionInUrlThenCorrectFilenameExtracted() { + fun `guessFileName - attachment with correct file extension in url - correct filename extracted`() { assertEquals( "Telegram.apk", DownloaderUtil.guessFileName( @@ -85,7 +85,7 @@ class DownloaderUtilTest { } @Test - fun whenNullContentDispositionAndApplicationOctetStreamContentTypeAndCorrectFileExtensionInUrlThenCorrectFilenameExtracted() { + fun `guessFileName - null content disposition and application octet stream content type - correct filename extracted`() { assertEquals( "youtube.apk", DownloaderUtil.guessFileName( @@ -99,7 +99,7 @@ class DownloaderUtilTest { } @Test - fun whenInlineWithFilenameContentDispositionAndApplicationPdfContentTypeAndCorrectFileExtensionInUrlThenCorrectFilenameExtracted() { + fun `guessFileName - inline with filename content disposition and application pdf content type and correct file extension in url - correct filename extracted`() { assertEquals( "Monitoraggio_Fase_2__report_nazionale_83_finale.pdf", DownloaderUtil.guessFileName( @@ -113,7 +113,7 @@ class DownloaderUtilTest { } @Test - fun whenEmptyContentDispositionAndApplicationOctetStreamContentTypeAndCorrectFileExtensionInUrlThenCorrectFilenameExtracted() { + fun `guessFileName - empty content disposition and application octet stream content type - correct filename extracted`() { assertEquals( "Pass-Example-Generic.pkpass", DownloaderUtil.guessFileName( @@ -125,7 +125,7 @@ class DownloaderUtilTest { } @Test - fun whenEmptyContentDispositionAndApplicationPdfContentTypeAndCorrectFileExtensionInUrlThenCorrectFilenameExtracted() { + fun `guessFileName - empty content disposition and application pdf content type and correct file extension in url - correct filename extracted`() { assertEquals( "be1da227fa380c8d057edbcf19cc8e14_pdf.pdf", DownloaderUtil.guessFileName( @@ -137,7 +137,7 @@ class DownloaderUtilTest { } @Test - fun whenEmptyContentDispositionAndApplicationOctetStreamContentTypeAndCorrectFileExtensionInUrlSecondExampleThenCorrectFilenameExtracted() { + fun `guessFileName - empty content disposition and application octet stream content type and correct file extension in url - correct filename extracted`() { assertEquals( "ahc01_learn_to_play_web.pdf", DownloaderUtil.guessFileName( @@ -149,7 +149,7 @@ class DownloaderUtilTest { } @Test - fun whenEmptyContentDispositionAndApplicationPdfContentTypeAndCorrectFileExtensionInUrlSecondExampleThenCorrectFilenameExtracted() { + fun `guessFileName - empty content disposition and application pdf content type and correct file extension in url second example - correct filename extracted`() { assertEquals( "m_series.pdf", DownloaderUtil.guessFileName( @@ -162,7 +162,7 @@ class DownloaderUtilTest { } @Test - fun whenEmptyContentDispositionAndApplicationVndApplePkPassContentTypeAndCorrectFileExtensionInUrlThenCorrectFilenameExtracted() { + fun `guessFileName - empty content disposition and application vnd apple pk pass content type and correct file extension in url - correct filename extracted`() { assertEquals( "93348617.pkpass", DownloaderUtil.guessFileName( @@ -176,7 +176,7 @@ class DownloaderUtilTest { } @Test - fun whenEmptyContentDispositionAndTextXpython3ContentTypeAndCorrectFileExtensionInUrlThenCorrectFilenameExtracted() { + fun `guessFileName - empty content disposition and text x python 3 content type and correct file extension in url - correct filename extracted`() { assertEquals( "bat.py", DownloaderUtil.guessFileName( @@ -190,32 +190,32 @@ class DownloaderUtilTest { } @Test - fun whenContentDispositionWithAttachmentAndFilenameBetweenQuotesAndSpaceAfterSemicolonThenCorrectFilenameExtracted() { + fun `fileNameFromContentDisposition - content disposition with attachment and filename between quotes and space after semicolon - correct filename extracted`() { assertEquals("filename.jpg", DownloaderUtil.fileNameFromContentDisposition("""attachment; filename="filename.jpg"""")) } @Test - fun whenContentDispositionWithAttachmentAndFilenameBetweenQuotesAndSpacesBeforeAndAfterSemicolonThenCorrectFilenameExtracted() { + fun `fileNameFromContentDisposition - content disposition with attachment and filename between quotes and spaces before and after semicolon - correct filename extracted`() { assertEquals("filename.jpg", DownloaderUtil.fileNameFromContentDisposition("""attachment ; filename="filename.jpg"""")) } @Test - fun whenContentDispositionWithAttachmentAndFilenameBetweenQuotesAndNoSpacesThenCorrectFilenameExtracted() { + fun `fileNameFromContentDisposition - content disposition with attachment and filename between quotes and no spaces - correct filename extracted`() { assertEquals("filename.jpg", DownloaderUtil.fileNameFromContentDisposition("""attachment;filename="filename.jpg"""")) } @Test - fun whenContentDispositionWithAttachmentAndFilenameWithoutQuotesAndWithSpaceAfterSemicolonThenCorrectFilenameExtracted() { + fun `fileNameFromContentDisposition - content disposition with attachment and filename without quotes and with space after semicolon - correct filename extracted`() { assertEquals("filename.jpg", DownloaderUtil.fileNameFromContentDisposition("""attachment; filename=filename.jpg""")) } @Test - fun whenContentDispositionWithInlineAndFilenameBetweenQuotesAndSpaceAfterSemicolonThenCorrectFilenameExtracted() { + fun `fileNameFromContentDisposition - content disposition with inline and filename between quotes and space after semicolon - correct filename extracted`() { assertEquals("filename.jpg", DownloaderUtil.fileNameFromContentDisposition("""inline; filename="filename.jpg"""")) } @Test - fun whenContentDispositionWithAttachmentAndFilenameEncodedThenEncodedFilenameExtracted() { + fun `fileNameFromContentDisposition - content disposition with attachment and filename encoded - encoded filename extracted`() { assertEquals( "%E4%B8%AD%E6%96%87%E6%96%87%E4%BB%B6%E5%90%8D%E6%B5%8B%E8%AF%95.txt", DownloaderUtil.fileNameFromContentDisposition( @@ -225,7 +225,7 @@ class DownloaderUtilTest { } @Test - fun whenContentDispositionWithAttachmentAndFilenameStarEncodedThenDecodedFilenameExtracted() { + fun `fileNameFromContentDisposition - content disposition with attachment and filename star encoded - decoded filename extracted`() { assertEquals( "中文文件名测试.txt", DownloaderUtil.fileNameFromContentDisposition( @@ -235,7 +235,7 @@ class DownloaderUtilTest { } @Test - fun whenContentDispositionWithAttachmentAndFilenameStarEncodedAndFilenameThenDecodedFilenameExtracted() { + fun `fileNameFromContentDisposition - content disposition with attachment and filename star encoded and filename - decoded filename extracted`() { assertEquals( "中文文件名测试.txt", DownloaderUtil.fileNameFromContentDisposition( @@ -249,7 +249,7 @@ class DownloaderUtilTest { } @Test - fun whenContentDispositionWithAttachmentAndFilenameAndFilenameStarEncodedThenDecodedFilenameExtracted() { + fun `fileNameFromContentDisposition - content disposition with attachment and filename and filename star encoded - decoded filename extracted`() { assertEquals( "中文文件名测试.txt", DownloaderUtil.fileNameFromContentDisposition( @@ -263,7 +263,7 @@ class DownloaderUtilTest { } @Test - fun whenContentDispositionWithAttachmentAndFilenameStarEncodedWithNoEncodingAndFilenameThenDecodedFilenameExtractedFallback() { + fun `fileNameFromContentDisposition - content disposition with attachment and filename star encoded with no encoding and filename then decoded filename extracted fallback`() { assertEquals( "%E4%B8%AD%E6%96%87%E6%96%87%E4%BB%B6%E5%90%8D%E6%B5%8B%E8%AF%95.txt", DownloaderUtil.fileNameFromContentDisposition( @@ -277,7 +277,7 @@ class DownloaderUtilTest { } @Test - fun whenContentDispositionWithInlineAndFilenameStarEncodedAndFilenameThenDecodedFilenameExtracted() { + fun `fileNameFromContentDisposition - content disposition with inline and filename star encoded and filename - decoded filename extracted`() { assertEquals( "中文文件名测试.txt", DownloaderUtil.fileNameFromContentDisposition( diff --git a/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/FileDownloadCallbackTest.kt b/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/FileDownloadCallbackTest.kt index d34f0c9043f9..f7ad18eecc96 100644 --- a/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/FileDownloadCallbackTest.kt +++ b/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/FileDownloadCallbackTest.kt @@ -72,7 +72,7 @@ class FileDownloadCallbackTest { } @Test - fun whenOnStartCalledThenPixelFiredAndItemInsertedAndDownloadStartedCommandSent() = runTest { + fun `onStart - pixel fired - item inserted - download started command sent`() = runTest { val item = oneItem() callback.onStart(downloadItem = item) @@ -89,7 +89,7 @@ class FileDownloadCallbackTest { } @Test - fun whenOnSuccessCalledForDownloadIdThenPixelFiredAndItemUpdatedAndDownloadSuccessCommandSent() = runTest { + fun `onSuccess - item updated - download success command sent`() = runTest { val item = oneItem() val updatedContentLength = 20L whenever(mockDownloadsRepository.getDownloadItem(item.downloadId)).thenReturn(item.copy(contentLength = updatedContentLength)) @@ -115,7 +115,7 @@ class FileDownloadCallbackTest { } @Test - fun whenOnSuccessCalledForFileThenPixelFiredAndItemUpdatedAndDownloadSuccessCommandSent() = runTest { + fun `onSuccess - file downloaded - pixel fired and item updated and download success command sent`() = runTest { val item = oneItem() val mimeType = "image/jpeg" val file = File(item.fileName) @@ -141,7 +141,7 @@ class FileDownloadCallbackTest { } @Test - fun whenOnErrorCalledForDownloadIdAndConnectionRefusedThenPixelFiredAndItemDeleted() = runTest { + fun `onError - pixel fired and item deleted`() = runTest { val downloadId = 1L val failReason = DownloadFailReason.ConnectionRefused @@ -154,7 +154,7 @@ class FileDownloadCallbackTest { } @Test - fun whenOnCancelCalledForDownloadIdAndNoItemInDbThenPixelFired() = runTest { + fun `onCancel - no item in db - pixel fired`() = runTest { val downloadId = 1L whenever(mockDownloadsRepository.getDownloadItem(downloadId)).thenReturn(null) @@ -166,7 +166,7 @@ class FileDownloadCallbackTest { } @Test - fun whenOnCancelCalledForDownloadIdAndExistingItemInDbThenPixelFired() = runTest { + fun `onCancel - existing item in db - pixel fired`() = runTest { val downloadId = 1L whenever(mockDownloadsRepository.getDownloadItem(downloadId)).thenReturn(oneItem()) @@ -177,7 +177,7 @@ class FileDownloadCallbackTest { } @Test - fun whenOnErrorCalledForUrlAndConnectionRefusedThenPixelFiredAndDownloadFailedCommandSent() = runTest { + fun `onError - url - connection refused - pixel fired and download failed command sent`() = runTest { val failReason = DownloadFailReason.ConnectionRefused callback.onError(url = "url", reason = failReason) @@ -192,7 +192,7 @@ class FileDownloadCallbackTest { } @Test - fun whenOnErrorCalledForNoDownloadIdAndUnsupportedUrlThenPixelFiredAndNotificationSentAndDownloadFailedCommandSent() = runTest { + fun `onError - no download id and unsupported url - pixel fired and notification sent and download failed command sent`() = runTest { callback.onError(url = "url", reason = DownloadFailReason.UnsupportedUrlType) verify(mockPixel).fire(DownloadsPixelName.DOWNLOAD_REQUEST_FAILED) diff --git a/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/PendingFileDownloadCompressTest.kt b/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/PendingFileDownloadCompressTest.kt index 905ef15967af..8f79eabfcf24 100644 --- a/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/PendingFileDownloadCompressTest.kt +++ b/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/PendingFileDownloadCompressTest.kt @@ -29,7 +29,11 @@ import org.junit.runner.RunWith class PendingFileDownloadCompressTest { @Test - fun whenDownloadUrlIsTooLargeAndToInputDataCalledThenAddCompressedUrl() { + fun `largeUrl`) which will be used to test the compression function· +2· It creates an instance of `PendingDownload` with the large URL, converts it to an input data object using the `toInputData()` method, and assigns it to the `data` variable· +3· It checks if the compressed URL is indeed compressed by verifying that the `IS_URL_COMPRESSED` boolean flag is set to `true`· +4· It extracts the compressed URL from the input data object using the `getString(URL)` method and trims any whitespace characters from the start and end of the string· +5· It verifies that the compressed URL starts with a specific expected prefix (`expectedEncodedUrlStart`) and ends with another specific expected suffix (`expectedEncodedUrlEnd`() { val largeUrl = """ https://chart.apis.google.com/chart?chs=500x500&chma=0,0,100,100&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity @@ -55,7 +59,7 @@ class PendingFileDownloadCompressTest { } @Test - fun whenDownloadUrlIsSmallAndToInputDataCalledThenUrlNotCompressed() { + fun `whenDownloadUrlIsSmallAndToInputDataCalledThenUrlNotCompressed - to input data - url not compressed`() { val smallUrl = "https://static.pexels.com/photos/45201/kitty-cat-kitten-pet-45201.jpeg" val data = buildPendingDownload(url = smallUrl).toInputData() @@ -65,7 +69,10 @@ class PendingFileDownloadCompressTest { } @Test - fun whenDownloadUrlIsCompressedAndToPendingFileDownloadCalledThenUrlIsDecompressed() { + fun `val data = buildPendingDownload(url = largeUrl)·toInputData()`· This line calls a function `buildPendingDownload` with the argument `largeUrl`, which returns an object that can be converted to an input data using the `toInputData()` method· +2· `val pending = data·toPendingFileDownload()`· This line converts the input data to a pending file download object· +3· `assertFalse(pending·isUrlCompressed)`· This line checks if the downloaded file is not compressed by calling the `isUrlCompressed` method on the pending file download object and asserting that it returns `false`· +4· `assertEquals(largeUrl, pending·url)`· This line checks if the URL of the downloaded file matches the expected value `largeUrl` by calling the `url` method on the pending file download object and comparing it to the expected value using the `assertEquals()`() { val largeUrl = """ https://chart.apis.google.com/chart?chs=500x500&chma=0,0,100,100&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity&cht=p&chco=FF0000%2CFFFF00%7CFF8000%2C00FF00%7C00FF00%2C0000FF&chd=t%3A122%2C42%2C17%2C10%2C8%2C7%2C7%2C7%2C7%2C6%2C6%2C6%2C6%2C5%2C5&chl=122%7C42%7C17%7C10%7C8%7C7%7C7%7C7%7C7%7C6%7C6%7C6%7C6%7C5%7C5&chdl=android%7Cjava%7Cstack-trace%7Cbroadcastreceiver%7Candroid-ndk%7Cuser-agent%7Candroid-webview%7Cwebview%7Cbackground%7Cmultithreading%7Candroid-source%7Csms%7Cadb%7Csollections%7Cactivity @@ -79,7 +86,7 @@ class PendingFileDownloadCompressTest { } @Test - fun whenDownloadUrlIsNotCompressedAndToPendingFileDownloadCalledThenUrlIsNotDecompressed() { + fun `whenDownloadUrlIsNotCompressedAndToPendingFileDownloadCalledThenUrlIsNotDecompressed - url not compressed`() { val smallUrl = "https://static.pexels.com/photos/45201/kitty-cat-kitten-pet-45201.jpeg" val data = buildPendingDownload(url = smallUrl).toInputData() diff --git a/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/RealUrlFileDownloadCallManagerTest.kt b/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/RealUrlFileDownloadCallManagerTest.kt index 01e36d785781..0a7e85cfcfe2 100644 --- a/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/RealUrlFileDownloadCallManagerTest.kt +++ b/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/RealUrlFileDownloadCallManagerTest.kt @@ -29,14 +29,14 @@ class RealUrlFileDownloadCallManagerTest { private val call: Call = mock() @Test - fun whenRemovingNotAddedDownloadIdThenNoop() { + fun `remove - no download id added - noop`() { RealUrlFileDownloadCallManager().remove(0L) verifyNoInteractions(call) } @Test - fun whenRemovingAddedDownloadIdThenCancelDownloadAndRemove() { + fun `remove - added download id - cancel and remove`() { val downloadManager = RealUrlFileDownloadCallManager() downloadManager.add(0L, call) @@ -49,7 +49,7 @@ class RealUrlFileDownloadCallManagerTest { } @Test - fun whenAddingDownloadIdTwiceThenOnlyLatestCallIsReplaced() { + fun `add - adding download id twice - only latest call is replaced`() { val secondCall: Call = mock() val downloadManager = RealUrlFileDownloadCallManager() diff --git a/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/UriUtilsFilenameExtractorTest.kt b/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/UriUtilsFilenameExtractorTest.kt index da11b97d0bff..5fd9f4aa0c18 100644 --- a/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/UriUtilsFilenameExtractorTest.kt +++ b/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/UriUtilsFilenameExtractorTest.kt @@ -34,7 +34,7 @@ class UriUtilsFilenameExtractorTest { private val testee: FilenameExtractor = FilenameExtractor(mockedPixel) @Test - fun whenUrlEndsWithFilenameAsJpgNoMimeOrContentDispositionThenFilenameShouldBeExtracted() { + fun `extract - url ends with filename as jpg no mime or content disposition - extracted`() { val url = "https://example.com/realFilename.jpg" val mimeType: String? = null val contentDisposition: String? = null @@ -47,7 +47,7 @@ class UriUtilsFilenameExtractorTest { } @Test - fun whenUrlContainsFilenameButContainsAdditionalPathSegmentsThenFilenameShouldBeExtracted() { + fun `extract - url contains filename but additional path segments - extracted`() { val url = "https://foo.example.com/path/images/b/b1/realFilename.jpg/other/stuff" val mimeType: String? = null val contentDisposition: String? = null @@ -60,7 +60,7 @@ class UriUtilsFilenameExtractorTest { } @Test - fun whenUrlContainsFilenameButContainsAdditionalPathSegmentsAndQueryParamsThenFilenameShouldBeExtracted() { + fun `extract - url contains filename but additional path segments and query params - extracted`() { val url = "https://foo.example.com/path/images/b/b1/realFilename.jpg/other/stuff?cb=123" val mimeType: String? = null val contentDisposition: String? = null @@ -73,7 +73,7 @@ class UriUtilsFilenameExtractorTest { } @Test - fun whenUrlContainsFilenameButContainsPathSegmentsWhichLookLikeAFilenameThenFilenameShouldBeExtracted() { + fun `extract - url contains filename but path segments look like a filename - extracted`() { val url = "https://foo.example.com/path/dotted.path/b/b1/realFilename.jpg" val mimeType: String? = null val contentDisposition: String? = null @@ -86,7 +86,7 @@ class UriUtilsFilenameExtractorTest { } @Test - fun whenUrlContainsAmbiguousFilenameButContainsPathSegmentsWhichLookLikeAFilenameAndMimeTypeProvidedThenFilenameShouldBeExtracted() { + fun `extract - url contains ambiguous filename - extracted`() { shadowOf(MimeTypeMap.getSingleton()).addExtensionMimeTypMapping("jpg", "image/jpeg") val url = "https://foo.example.com/path/dotted.path/b/b1/realFilename" @@ -101,7 +101,7 @@ class UriUtilsFilenameExtractorTest { } @Test - fun whenUrlContainsFilenameAndContainsMultiplePathSegmentsAndMimeTypeProvidedThenFilenameShouldBeExtracted() { + fun `extract - url contains filename and multiple path segments - extracted filename`() { val url = "https://foo.example.com/path/images/b/b1/realFilename.jpg" val mimeType = "image/jpeg" val contentDisposition: String? = null @@ -114,7 +114,7 @@ class UriUtilsFilenameExtractorTest { } @Test - fun whenUrlContainsFilenameButContainsAdditionalPathSegmentsAndQueryParamsWhichLookLikeAFilenameThenFilenameShouldBeExtracted() { + fun `extract - url contains filename but additional path segments and query params which look like a filename - extracted`() { val url = "https://foo.example.com/path/images/b/b1/realFilename.jpg/other/stuff?cb=123.com" val mimeType: String? = null val contentDisposition: String? = null @@ -127,7 +127,7 @@ class UriUtilsFilenameExtractorTest { } @Test - fun whenUrlContainsFilenameButContentDispositionSaysOtherwiseThenExtractFromContentDisposition() { + fun `extract - url contains filename but content disposition says otherwise - extracted from content disposition`() { val url = "https://example.com/filename.jpg" val mimeType: String? = null val contentDisposition = "Content-Disposition: attachment; filename=fromDisposition.jpg" @@ -140,7 +140,7 @@ class UriUtilsFilenameExtractorTest { } @Test - fun whenFilenameEndsInBinThenThatIsExtracted() { + fun `extract - filename ends in bin - extracted`() { val url = "https://example.com/realFilename.bin" val mimeType: String? = null val contentDisposition: String? = null @@ -154,7 +154,7 @@ class UriUtilsFilenameExtractorTest { } @Test - fun whenUrlContainsNoFileNameButLotsOfPathsSegmentsThenFirstSegmentNameIsUsed() { + fun `extract - url contains no file name but lots of path segments - first segment name used`() { val url = "https://example.com/foo/bar/files" val mimeType: String? = null val contentDisposition: String? = null @@ -167,7 +167,7 @@ class UriUtilsFilenameExtractorTest { } @Test - fun whenFilenameEndsInBinWithASlashThenThatIsExtracted() { + fun `extract - filename ends in bin with a slash - extracted`() { val url = "https://example.com/realFilename.bin/" val mimeType: String? = null val contentDisposition: String? = null @@ -181,7 +181,7 @@ class UriUtilsFilenameExtractorTest { } @Test - fun whenFilenameContainsBinThenThatIsExtracted() { + fun `extract - filename contains bin - extracted`() { val url = "https://example.com/realFilename.bin/foo/bar" val mimeType: String? = null val contentDisposition: String? = null @@ -195,7 +195,7 @@ class UriUtilsFilenameExtractorTest { } @Test - fun whenUrlIsEmptyStringAndNoOtherDataProvidedThenDefaultNameFiletypeReturned() { + fun `extract - url empty string and no other data provided - default name filetype returned`() { val url = "" val mimeType: String? = null val contentDisposition: String? = null @@ -209,7 +209,7 @@ class UriUtilsFilenameExtractorTest { } @Test - fun whenUrlIsEmptyStringAndMimeTypeProvidedThenDefaultNameAndFiletypeFromMimeReturned() { + fun `extract - url empty string and mime type provided - default name and filetype from mime returned`() { shadowOf(MimeTypeMap.getSingleton()).addExtensionMimeTypMapping("jpg", "image/jpeg") val url = "" @@ -225,7 +225,7 @@ class UriUtilsFilenameExtractorTest { } @Test - fun whenUrlIsEmptyStringAndContentDispositionProvidedThenExtractFromContentDisposition() { + fun `extract - url empty string and content disposition provided - extracted`() { val url = "" val mimeType: String? = null val contentDisposition = "Content-Disposition: attachment; filename=fromDisposition.jpg" @@ -239,7 +239,7 @@ class UriUtilsFilenameExtractorTest { } @Test - fun whenNoFilenameAndNoPathSegmentsThenDomainNameReturned() { + fun `extract - no filename and no path segments - domain name returned`() { val url = "http://example.com" val mimeType: String? = null val contentDisposition: String? = null @@ -253,7 +253,7 @@ class UriUtilsFilenameExtractorTest { } @Test - fun whenNoFilenameAndPathSegmentsThenPathNameFileIsReturned() { + fun `extract - no filename and path segments - returns path name file`() { val url = "http://example.com/cat/600/400" val mimeType: String? = null val contentDisposition: String? = null @@ -267,7 +267,7 @@ class UriUtilsFilenameExtractorTest { } @Test - fun whenUrlContainsFilenameAndMimeTypeIsTextXPython3AndContentDispositionIsEmptyThenFilenameIsReturned() { + fun `extract - url contains filename and mime type text x python 3 and content disposition empty - filename returned`() { val url = """ https://ddg-name-test-ubsgiobgibsdgsbklsdjgm.netlify.app/uploads/qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm/bat.py """.trimIndent() diff --git a/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/UrlFileDownloaderTest.kt b/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/UrlFileDownloaderTest.kt index ff44b583195e..cabf30123050 100644 --- a/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/UrlFileDownloaderTest.kt +++ b/downloads/downloads-impl/src/test/java/com/duckduckgo/downloads/impl/UrlFileDownloaderTest.kt @@ -55,7 +55,7 @@ class UrlFileDownloaderTest { } @Test - fun whenDownloadFileSuccessfulThenCallOnStartInProgressAndSuccessCallbacks() = runTest { + fun `downloadFile - successful - call on start in progress and success callbacks`() = runTest { val pendingFileDownload = buildPendingDownload("https://example.com/file.txt") val filename = "file.txt" val downloadCallback = mock() @@ -70,7 +70,7 @@ class UrlFileDownloaderTest { } @Test - fun whenDownloadFileFailedAsCancelledThenCallOnCancelCallback() = runTest { + fun `downloadFile - failed as cancelled - call on cancel callback`() = runTest { val pendingFileDownload = buildPendingDownload("https://example.com/file.txt") val filename = "file.txt" val downloadCallback = mock() @@ -91,7 +91,7 @@ class UrlFileDownloaderTest { } @Test - fun whenDownloadFileFailedAsWriteErrorThenCallOnCancelCallback() = runTest { + fun `downloadFile - failed as write error - call on cancel callback`() = runTest { val pendingFileDownload = buildPendingDownload("https://example.com/file.txt") val filename = "file.txt" val downloadCallback = mock() @@ -112,7 +112,7 @@ class UrlFileDownloaderTest { } @Test - fun whenDownloadFileFailedAsErrorThenCallOnErrorCallback() = runTest { + fun `downloadFile - download failed as error - call on error callback`() = runTest { val pendingFileDownload = buildPendingDownload("https://example.com/file.txt") val filename = "file.txt" val downloadCallback = mock() @@ -130,7 +130,7 @@ class UrlFileDownloaderTest { } @Test - fun whenDownloadFileSucceedsAsCancelledThenCallOnCancelCallback() = runTest { + fun `downloadFile - succeeds as cancelled - call on cancel callback`() = runTest { val pendingFileDownload = buildPendingDownload("https://example.com/file.txt") val filename = "file.txt" val downloadCallback = mock() @@ -151,7 +151,7 @@ class UrlFileDownloaderTest { } @Test - fun whenDownloadFileSucceedsAsFailedToWriteThenCallOnErrorCallback() = runTest { + fun `downloadFile - download succeeds as failed to write - call on error callback`() = runTest { val pendingFileDownload = buildPendingDownload("https://example.com/file.txt") val filename = "file.txt" val downloadCallback = mock() diff --git a/downloads/downloads-store/src/test/java/com/duckduckgo/downloads/store/DownloadsDaoTest.kt b/downloads/downloads-store/src/test/java/com/duckduckgo/downloads/store/DownloadsDaoTest.kt index 617be962531b..b9e13adac066 100644 --- a/downloads/downloads-store/src/test/java/com/duckduckgo/downloads/store/DownloadsDaoTest.kt +++ b/downloads/downloads-store/src/test/java/com/duckduckgo/downloads/store/DownloadsDaoTest.kt @@ -59,7 +59,7 @@ class DownloadsDaoTest { } @Test - fun whenDownloadItemAddedThenItIsInList() = runTest { + fun `getDownloads - item added - in list`() = runTest { val downloadItem = oneItem() dao.insert(downloadItem) @@ -69,7 +69,7 @@ class DownloadsDaoTest { } @Test - fun whenDownloadItemsAddedThenTheyAreInTheList() = runTest { + fun `getDownloads - items added - in the list`() = runTest { val downloadItems = listOf( oneItem(), otherItem(), @@ -82,7 +82,7 @@ class DownloadsDaoTest { } @Test - fun whenDownloadItemUpdatedByIdThenItIsInListWithNewValue() = runTest { + fun `updateDownloadItem - download item updated by id - in list with new value`() = runTest { val downloadItem = oneItem().copy(downloadStatus = STARTED, contentLength = 0L) val updatedStatus = FINISHED val updatedContentLength = 11111L @@ -101,7 +101,7 @@ class DownloadsDaoTest { } @Test - fun whenDownloadItemUpdatedByFileNameThenItIsInListWithNewValue() = runTest { + fun `updateDownloadItem - download item updated by file name - in list with new value`() = runTest { val downloadItem = oneItem().copy(downloadStatus = STARTED, contentLength = 0L, downloadId = 0L) val updatedStatus = FINISHED val updatedContentLength = 11111L @@ -120,7 +120,7 @@ class DownloadsDaoTest { } @Test - fun whenDownloadItemDeletedThenItIsNoLongerInTheList() = runTest { + fun `getDownloads - item deleted - is empty`() = runTest { val downloadItem = oneItem() dao.insert(downloadItem) @@ -131,7 +131,7 @@ class DownloadsDaoTest { } @Test - fun whenDownloadItemsDeletedThenTheyAreNoLongerInTheList() = runTest { + fun `getDownloads - deleted items no longer in the list`() = runTest { val downloadItems = listOf( oneItem(), otherItem(), @@ -145,7 +145,7 @@ class DownloadsDaoTest { } @Test - fun whenDownloadItemsRetrievedThenTheCorrectItemIsReturned() = runTest { + fun `getDownloadItem - when download items retrieved - correct item returned`() = runTest { val itemToRetrieve = oneItem() val downloadItems = listOf( otherItem(), diff --git a/element-hiding/element-hiding-impl/src/test/java/com/duckduckgo/elementhiding/impl/ElementHidingContentScopeConfigPluginTest.kt b/element-hiding/element-hiding-impl/src/test/java/com/duckduckgo/elementhiding/impl/ElementHidingContentScopeConfigPluginTest.kt index 0f72dafff56b..f9b540751318 100644 --- a/element-hiding/element-hiding-impl/src/test/java/com/duckduckgo/elementhiding/impl/ElementHidingContentScopeConfigPluginTest.kt +++ b/element-hiding/element-hiding-impl/src/test/java/com/duckduckgo/elementhiding/impl/ElementHidingContentScopeConfigPluginTest.kt @@ -37,13 +37,13 @@ class ElementHidingContentScopeConfigPluginTest { } @Test - fun whenGetConfigThenReturnCorrectlyFormattedJson() { + fun `getConfig - return correctly formatted json`() { whenever(mockElementHidingRepository.elementHidingEntity).thenReturn(ElementHidingEntity(json = config)) assertEquals("\"elementHiding\":$config", testee.config()) } @Test - fun whenGetPreferencesThenReturnNull() { + fun `getPreferences - null`() { assertNull(testee.preferences()) } diff --git a/element-hiding/element-hiding-impl/src/test/java/com/duckduckgo/elementhiding/impl/ElementHidingFeaturePluginTest.kt b/element-hiding/element-hiding-impl/src/test/java/com/duckduckgo/elementhiding/impl/ElementHidingFeaturePluginTest.kt index 6c5587fa32d6..68f091c0df59 100644 --- a/element-hiding/element-hiding-impl/src/test/java/com/duckduckgo/elementhiding/impl/ElementHidingFeaturePluginTest.kt +++ b/element-hiding/element-hiding-impl/src/test/java/com/duckduckgo/elementhiding/impl/ElementHidingFeaturePluginTest.kt @@ -36,19 +36,19 @@ class ElementHidingFeaturePluginTest { } @Test - fun whenFeatureNameDoesNotMatchElementHidingThenReturnFalse() { + fun `store - feature name does not match element hiding - returns false`() { ElementHidingFeatureName.values().filter { it != FEATURE_NAME }.forEach { assertFalse(testee.store(it.value, JSON_STRING)) } } @Test - fun whenFeatureNameMatchesElementHidingThenReturnTrue() { + fun `store - feature name matches element hiding - returns true`() { assertTrue(testee.store(FEATURE_NAME_VALUE, JSON_STRING)) } @Test - fun whenFeatureNameMatchesElementHidingThenUpdateAll() { + fun `whenFeatureNameMatchesElementHiding - update all - json string`() { testee.store(FEATURE_NAME_VALUE, JSON_STRING) val captor = argumentCaptor() verify(mockElementHidingRepository).updateAll(captor.capture()) diff --git a/element-hiding/element-hiding-store/src/test/java/com/duckduckgo/elementhiding/store/ElementHidingRepositoryTest.kt b/element-hiding/element-hiding-store/src/test/java/com/duckduckgo/elementhiding/store/ElementHidingRepositoryTest.kt index 23bf573fcf01..b6673d196852 100644 --- a/element-hiding/element-hiding-store/src/test/java/com/duckduckgo/elementhiding/store/ElementHidingRepositoryTest.kt +++ b/element-hiding/element-hiding-store/src/test/java/com/duckduckgo/elementhiding/store/ElementHidingRepositoryTest.kt @@ -42,7 +42,7 @@ class ElementHidingRepositoryTest { } @Test - fun whenInitializedAndDoesNotHaveStoredValueThenLoadEmptyJsonToMemory() = + fun `loadEmptyJsonToMemory - initialized and does not have stored value`() = runTest { testee = RealElementHidingRepository( @@ -57,7 +57,7 @@ class ElementHidingRepositoryTest { } @Test - fun whenInitializedAndHasStoredValueThenLoadStoredJsonToMemory() = + fun `whenInitializedAndHasStoredValue - load stored json to memory`() = runTest { whenever(mockElementHidingDao.get()).thenReturn(elementHidingEntity) testee = @@ -73,7 +73,7 @@ class ElementHidingRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - update all called`() = runTest { testee = RealElementHidingRepository( diff --git a/experiments/experiments-impl/src/test/java/com/duckduckgo/experiments/impl/ExperimentFiltersManagerImplTest.kt b/experiments/experiments-impl/src/test/java/com/duckduckgo/experiments/impl/ExperimentFiltersManagerImplTest.kt index 70df4947830d..801a5dc44b20 100644 --- a/experiments/experiments-impl/src/test/java/com/duckduckgo/experiments/impl/ExperimentFiltersManagerImplTest.kt +++ b/experiments/experiments-impl/src/test/java/com/duckduckgo/experiments/impl/ExperimentFiltersManagerImplTest.kt @@ -41,7 +41,7 @@ class ExperimentFiltersManagerImplTest { } @Test - fun whenVariantComplyWithLocaleFilterThenAddFiltersReturnsTrue() { + fun `addFilters - variant comply with locale filter - returns true`() { val locale = Locale("en", "US") Locale.setDefault(locale) val testEntity = addActiveVariant(localeFilter = listOf("en_US")) @@ -50,7 +50,7 @@ class ExperimentFiltersManagerImplTest { } @Test - fun whenVariantDoesNotComplyWithLocaleFilterThenAddFiltersReturnsFalse() { + fun `addFilters - variant does not comply with locale filter - returns false`() { val locale = Locale("en", "US") Locale.setDefault(locale) val testEntity = addActiveVariant(localeFilter = listOf("de_DE")) @@ -59,7 +59,7 @@ class ExperimentFiltersManagerImplTest { } @Test - fun whenVariantComplyWithAndroidVersionFilterThenAddFiltersReturnsTrue() { + fun `addFilters - variant comply with android version filter - returns true`() { whenever(mockAppBuildConfig.sdkInt).thenReturn(33) val testEntity = addActiveVariant(androidVersionFilter = listOf("33", "34")) @@ -67,7 +67,7 @@ class ExperimentFiltersManagerImplTest { } @Test - fun whenVariantDoesNotComplyWithAndroidVersionFilterThenAddFiltersReturnsFalse() { + fun `addFilters - variant does not comply with android version filter - returns false`() { whenever(mockAppBuildConfig.sdkInt).thenReturn(32) val testEntity = addActiveVariant(androidVersionFilter = listOf("33", "34")) @@ -75,7 +75,7 @@ class ExperimentFiltersManagerImplTest { } @Test - fun whenVariantComplyWithBothFiltersThenAddFiltersReturnsTrue() { + fun `addFilters - variant comply with both filters - returns true`() { val locale = Locale("en", "US") Locale.setDefault(locale) whenever(mockAppBuildConfig.sdkInt).thenReturn(33) diff --git a/experiments/experiments-impl/src/test/java/com/duckduckgo/experiments/impl/VariantManagerImplTest.kt b/experiments/experiments-impl/src/test/java/com/duckduckgo/experiments/impl/VariantManagerImplTest.kt index f202c98b9ec2..65b3a2cc39d1 100644 --- a/experiments/experiments-impl/src/test/java/com/duckduckgo/experiments/impl/VariantManagerImplTest.kt +++ b/experiments/experiments-impl/src/test/java/com/duckduckgo/experiments/impl/VariantManagerImplTest.kt @@ -54,28 +54,28 @@ class VariantManagerImplTest { } @Test - fun whenVariantAlreadyPersistedThenVariantReturned() { + fun `getVariantKey - variant already persisted - variant returned`() { whenever(mockExperimentVariantRepository.getUserVariant()).thenReturn("variantKey") assertEquals("variantKey", testee.getVariantKey()) } @Test - fun whenVariantNeverPersistedThenNullReturned() { + fun `getVariantKey - variant never persisted - null returned`() { whenever(mockExperimentVariantRepository.getUserVariant()).thenReturn(null) assertEquals(null, testee.getVariantKey()) } @Test - fun whenGetVariantsKeyThenVariantIsNeverUpdated() { + fun `getVariantKey - variant is never updated`() { testee.getVariantKey() verify(mockExperimentVariantRepository, never()).updateVariant(any()) } @Test - fun whenVariantAlreadyPersistedThenVariantAllocatorNeverInvoked() { + fun `updateVariants - variant already persisted - never invoked`() { val variantsConfig = listOf(VariantConfig("variantKey", 1.0)) whenever(mockExperimentVariantRepository.getUserVariant()).thenReturn("variantKey") testee.updateVariants(variantsConfig) @@ -84,7 +84,7 @@ class VariantManagerImplTest { } @Test - fun givenVariantsUpdateWhenVariantNeverPersistedThenVariantAllocatorNeverInvoked() { + fun `givenVariantsUpdate - variant never persisted - variant allocator never invoked`() { val variantsConfig = listOf(VariantConfig("variantKey", 1.0)) whenever(mockExperimentVariantRepository.getUserVariant()).thenReturn(null) testee.updateVariants(variantsConfig) @@ -94,7 +94,7 @@ class VariantManagerImplTest { } @Test - fun givenReturnUserVariantWhenVariantsConfigUpdatedThenNewVariantNoAllocated() { + fun `updateVariants - given return user variant when variants config updated then new variant no allocated`() { val variantsConfig = listOf(VariantConfig("variant1", 1.0), VariantConfig("variant2", 1.0)) whenever(mockExperimentVariantRepository.getUserVariant()).thenReturn("ru") @@ -105,7 +105,7 @@ class VariantManagerImplTest { } @Test - fun whenNoVariantsAvailableThenDefaultVariantIsAssigned() { + fun `updateVariants - no variants available - default variant assigned`() { whenever(mockExperimentVariantRepository.getUserVariant()).thenReturn(null) testee.updateVariants(emptyList()) @@ -113,7 +113,7 @@ class VariantManagerImplTest { } @Test - fun whenVariantPersistedIsNotFoundInActiveVariantListThenRestoredToDefaultVariant() { + fun `whenVariantPersistedIsNotFoundInActiveVariantListThenRestoredToDefaultVariant - update variant - restored to default`() { whenever(mockExperimentVariantRepository.getUserVariant()).thenReturn("variantKey") testee.updateVariants(emptyList()) @@ -121,7 +121,7 @@ class VariantManagerImplTest { } @Test - fun whenVariantPersistedHasWeightEqualToZeroInActiveVariantListThenVariantIsNotRestored() { + fun `updateVariants - persisted variant has weight equal to zero in active variant list - not restored`() { val variantsConfig = listOf(VariantConfig("variantKey", 0.0)) whenever(mockExperimentVariantRepository.getUserVariant()).thenReturn("variantKey") testee.updateVariants(variantsConfig) @@ -130,7 +130,7 @@ class VariantManagerImplTest { } @Test - fun whenNoVariantPersistedThenNewVariantAllocated() { + fun `updateVariants - no variant persisted - new variant allocated`() { val variantsConfig = listOf(VariantConfig("variantKey", 1.0)) whenever(mockExperimentVariantRepository.getUserVariant()).thenReturn(null) @@ -139,7 +139,7 @@ class VariantManagerImplTest { } @Test - fun whenNoVariantPersistedThenNewVariantKeyIsAllocatedAndPersisted() { + fun `updateVariants - no variant persisted - new variant key allocated and persisted`() { val variantsConfig = listOf(VariantConfig("variantKey", 1.0)) whenever(mockExperimentVariantRepository.getUserVariant()).thenReturn(null) @@ -149,7 +149,7 @@ class VariantManagerImplTest { } @Test - fun whenReferrerVariantSetWithNoActiveVariantsThenReferrerVariantReturned() { + fun `getVariantKey - referrer variant set with no active variants - referrer variant returned`() { val referrerVariantKey = "xx" mockUpdateScenario(referrerVariantKey) @@ -158,7 +158,7 @@ class VariantManagerImplTest { } @Test - fun whenReferrerVariantSetWithActiveVariantsThenReferrerVariantReturned() { + fun `getVariantKey - referrer variant set with active variants - referrer variant returned`() { val referrerVariantKey = "xx" mockUpdateScenario(referrerVariantKey) @@ -170,14 +170,14 @@ class VariantManagerImplTest { } @Test - fun whenUpdatingReferrerVariantThenDataStoreHasItsDataUpdated() { + fun `updateAppReferrerVariant - data store has its data updated`() { testee.updateAppReferrerVariant("xx") verify(mockExperimentVariantRepository).updateAppReferrerVariant("xx") } @Test - fun whenUpdatingReferrerVariantThenNewReferrerVariantReturned() { + fun `getVariantKey - updating referrer variant - new referrer variant returned`() { val originalVariant = testee.getVariantKey() mockUpdateScenario("xx") val newVariant = testee.getVariantKey() diff --git a/experiments/experiments-impl/src/test/java/com/duckduckgo/experiments/impl/VariantManagerTest.kt b/experiments/experiments-impl/src/test/java/com/duckduckgo/experiments/impl/VariantManagerTest.kt index 43fbe4bb44fe..136e181d30ec 100644 --- a/experiments/experiments-impl/src/test/java/com/duckduckgo/experiments/impl/VariantManagerTest.kt +++ b/experiments/experiments-impl/src/test/java/com/duckduckgo/experiments/impl/VariantManagerTest.kt @@ -31,19 +31,19 @@ class VariantManagerTest { // SERP Experiment(s) @Test - fun serpControlVariantHasExpectedWeightAndNoFeatures() { + fun `getSerpControlVariant - has expected weight and no features`() { val variant = variants.first { it.key == "sc" } assertEqualsDouble(0.0, variant.weight) } @Test - fun serpExperimentalVariantHasExpectedWeightAndNoFeatures() { + fun `getSerpExperimentalVariant - has expected weight and no features`() { val variant = variants.first { it.key == "se" } assertEqualsDouble(0.0, variant.weight) } @Test - fun verifyNoDuplicateVariantNames() { + fun `verifyNoDuplicateVariantNames - state - no duplicate variant names`() { val existingNames = mutableSetOf() variants.forEach { if (!existingNames.add(it.key)) { diff --git a/experiments/experiments-impl/src/test/java/com/duckduckgo/experiments/impl/reinstalls/ReinstallAtbListenerTest.kt b/experiments/experiments-impl/src/test/java/com/duckduckgo/experiments/impl/reinstalls/ReinstallAtbListenerTest.kt index 18dd3ecdbb8a..09e18063898c 100644 --- a/experiments/experiments-impl/src/test/java/com/duckduckgo/experiments/impl/reinstalls/ReinstallAtbListenerTest.kt +++ b/experiments/experiments-impl/src/test/java/com/duckduckgo/experiments/impl/reinstalls/ReinstallAtbListenerTest.kt @@ -60,14 +60,14 @@ class ReinstallAtbListenerTest { } @Test - fun whenBeforeAtbInitIsCalledThenClearBackupServiceSharedPreferences() = runTest { + fun `beforeAtbInit - clear backup service shared preferences`() = runTest { testee.beforeAtbInit() verify(mockBackupDataStore).clearBackupPreferences() } @Test - fun whenAndroidVersionIs10OrLowerThenDontCheckForDownloadsDirectory() = runTest { + fun `beforeAtbInit - android version 10 or lower - dont check for downloads directory`() = runTest { whenever(mockAppBuildConfig.sdkInt).thenReturn(Build.VERSION_CODES.Q) testee.beforeAtbInit() @@ -76,7 +76,7 @@ class ReinstallAtbListenerTest { } @Test - fun whenReturningUserHasBeenAlreadyCheckedThenDontCheckForDownloadsDirectory() = runTest { + fun `beforeAtbInit - returning user checked - don't get downloads directory`() = runTest { whenever(mockAppBuildConfig.sdkInt).thenReturn(Build.VERSION_CODES.R) setReturningUserChecked() @@ -86,7 +86,7 @@ class ReinstallAtbListenerTest { } @Test - fun whenDDGDirectoryIsFoundThenUpdateVariantForReturningUser() = runTest { + fun `beforeAtbInit - DDG directory found - update variant for returning user`() = runTest { whenever(mockAppBuildConfig.sdkInt).thenReturn(Build.VERSION_CODES.R) val mockDownloadsDirectory: File = mock { on { list() } doReturn arrayOf("DuckDuckGo") @@ -100,7 +100,7 @@ class ReinstallAtbListenerTest { } @Test - fun whenDDGDirectoryIsNotFoundThenVariantForReturningUserIsNotSet() = runTest { + fun `getDownloadsDirectory - directory not found - variant for returning user not set`() = runTest { whenever(mockAppBuildConfig.sdkInt).thenReturn(Build.VERSION_CODES.R) val mockDownloadsDirectory: File = mock { on { list() } doReturn emptyArray() @@ -114,7 +114,7 @@ class ReinstallAtbListenerTest { } @Test - fun whenDDGDirectoryIsNotFoundThenCreateIt() = runTest { + fun `beforeAtbInit - DDG directory not found - create it`() = runTest { whenever(mockAppBuildConfig.sdkInt).thenReturn(Build.VERSION_CODES.R) val mockDownloadsDirectory: File = mock { on { list() } doReturn emptyArray() diff --git a/feature-toggles/feature-toggles-impl/src/test/java/com/duckduckgo/feature/toggles/api/FeatureTogglesTest.kt b/feature-toggles/feature-toggles-impl/src/test/java/com/duckduckgo/feature/toggles/api/FeatureTogglesTest.kt index f63b3201773b..8688853e995c 100644 --- a/feature-toggles/feature-toggles-impl/src/test/java/com/duckduckgo/feature/toggles/api/FeatureTogglesTest.kt +++ b/feature-toggles/feature-toggles-impl/src/test/java/com/duckduckgo/feature/toggles/api/FeatureTogglesTest.kt @@ -52,53 +52,53 @@ class FeatureTogglesTest { } @Test - fun whenDisableByDefaultThenReturnDisabled() { + fun `disableByDefault - return disabled`() { assertFalse(feature.disableByDefault().isEnabled()) } @Test - fun whenDisableByDefaultAndSetEnabledThenReturnEnabled() { + fun `disableByDefault - set enabled - return enabled`() { feature.disableByDefault().setEnabled(Toggle.State(enable = true)) assertTrue(feature.disableByDefault().isEnabled()) } @Test - fun whenEnabledByDefaultThenReturnEnabled() { + fun `enabledByDefault - return enabled`() { assertTrue(feature.enabledByDefault().isEnabled()) } @Test - fun whenEnabledByDefaultAndSetDisabledThenReturnDisabled() { + fun `enabledByDefault - set disabled - return disabled`() { feature.enabledByDefault().setEnabled(Toggle.State(enable = false)) assertFalse(feature.enabledByDefault().isEnabled()) } @Test(expected = IllegalStateException::class) - fun whenNoDefaultValueThenThrow() { + fun `noDefaultValue - throw`() { feature.noDefaultValue().isEnabled() } @Test(expected = IllegalArgumentException::class) - fun whenWrongReturnValueThenThrow() { + fun `wrongReturnValue - throws - illegal argument exception`() { feature.wrongReturnValue() } @Test - fun whenNotAllowedMinVersionThenReturnDisabled() { + fun `enabledByDefault - not allowed min version - return disabled`() { provider.version = 10 feature.enabledByDefault().setEnabled(Toggle.State(enable = true, minSupportedVersion = 11)) assertFalse(feature.enabledByDefault().isEnabled()) } @Test - fun whenAllowedMinVersionThenReturnDisabled() { + fun `enabledByDefault - allowed min version - return disabled`() { provider.version = 10 feature.enabledByDefault().setEnabled(Toggle.State(enable = true, minSupportedVersion = 9)) assertTrue(feature.enabledByDefault().isEnabled()) } @Test - fun testInternalAlwaysEnabledAnnotation() { + fun `testInternalAlwaysEnabledAnnotation - always enabled`() { assertFalse(feature.internal().isEnabled()) provider.flavorName = BuildFlavor.PLAY.name @@ -133,7 +133,7 @@ class FeatureTogglesTest { } @Test - fun testForcesDefaultVariantIfNullOnExperiment() { + fun `setVariantIfNullOnExperiment - forces default variant if null`() { toggleStore.set( "test_forcesDefaultVariant", State( @@ -146,38 +146,38 @@ class FeatureTogglesTest { } @Test - fun testForcesDefaultVariantOnExperiment() { + fun `testForcesDefaultVariantOnExperiment - variant key empty - default experiment disabled`() { assertNull(provider.variantKey) assertFalse(feature.experimentDisabledByDefault().isEnabled()) assertEquals("", provider.variantKey) } @Test - fun testDoesNotForcesDefaultVariantOnFeatureFlag() { + fun `doesNotForceDefaultVariant - feature flag disabled - null variant key`() { assertNull(provider.variantKey) assertFalse(feature.disableByDefault().isEnabled()) assertNull(provider.variantKey) } @Test - fun testSkipForcesDefaultVariantWhenNotNull() { + fun `testSkipForcesDefaultVariantWhenNotNull - variant key set`() { provider.variantKey = "ma" assertFalse(feature.experimentDisabledByDefault().isEnabled()) assertEquals("ma", provider.variantKey) } @Test(expected = java.lang.IllegalArgumentException::class) - fun whenMethodWithArgumentsThenThrow() { + fun `methodWithArguments - throws exception`() { feature.methodWithArguments("") } @Test(expected = java.lang.IllegalArgumentException::class) - fun whenSuspendFunctionThenThrow() = runTest { + fun `suspendFun - suspend function then throw`() = runTest { feature.suspendFun() } @Test(expected = IllegalArgumentException::class) - fun whenValidFeatureAndMissingFeatureNameBuilderParameterThenThrow() { + fun `whenValidFeatureAndMissingFeatureNameBuilderParameterThenThrow - build - throws`() { FeatureToggles.Builder() .store(FakeToggleStore()) .appVersionProvider { provider.version } @@ -187,7 +187,7 @@ class FeatureTogglesTest { } @Test(expected = IllegalArgumentException::class) - fun whenValidFeatureAndMissingStoreBuilderParameterThenThrow() { + fun `whenValidFeatureAndMissingStoreBuilderParameterThenThrow - build - throws`() { FeatureToggles.Builder() .featureName("test") .appVersionProvider { provider.version } @@ -197,7 +197,7 @@ class FeatureTogglesTest { } @Test - fun whenEnabledAndInvalidOrValidRolloutThenIsEnableReturnsTrue() { + fun `setEnabled - enabled and rollout threshold - is enable returns true`() { val state = Toggle.State( enable = true, rollout = null, @@ -223,7 +223,7 @@ class FeatureTogglesTest { } @Test - fun whenEnabledAndValidRolloutThenReturnKeepRolloutStep() { + fun `setEnabled - valid rollout - return keep rollout step`() { val state = Toggle.State( enable = true, rollout = listOf(100.0), @@ -236,7 +236,7 @@ class FeatureTogglesTest { } @Test - fun whenDisabledAndValidRolloutThenDetermineRolloutValue() { + fun `whenDisabledAndValidRolloutThenDetermineRolloutValue - state updated`() { val state = Toggle.State( enable = false, rollout = listOf(100.0), @@ -250,7 +250,7 @@ class FeatureTogglesTest { } @Test - fun whenDisabledAndValidRolloutWithMultipleStepsThenDetermineRolloutValue() { + fun `whenDisabledAndValidRolloutWithMultipleStepsThenDetermineRolloutValue - state - rollout value determined`() { val state = Toggle.State( enable = false, rollout = listOf(1.0, 10.0, 20.0, 40.0, 100.0), @@ -264,7 +264,7 @@ class FeatureTogglesTest { } @Test - fun whenIncrementalRolloutThresholdIsSetOnlyOnce() { + fun `setRolloutThreshold - only once`() { var state = Toggle.State( enable = false, rollout = listOf(0.0), @@ -289,7 +289,7 @@ class FeatureTogglesTest { } @Test - fun whenDisabledWithPreviousStepsAndValidRolloutWithMultipleStepsThenDetermineRolloutValue() { + fun `selfEnabled - previous steps and valid rollout with multiple steps - enabled`() { val state = Toggle.State( enable = false, rollout = listOf(1.0, 10.0, 20.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0), @@ -303,7 +303,7 @@ class FeatureTogglesTest { } @Test - fun whenDisabledWithValidRolloutStepsAndNotSupportedVersionThenReturnDisabled() { + fun `whenDisabledWithValidRolloutStepsAndNotSupportedVersionThenReturnDisabled - state - disabled`() { provider.version = 10 val state = Toggle.State( enable = false, @@ -323,7 +323,7 @@ class FeatureTogglesTest { } @Test - fun whenRemoteEnableStateIsNullThenHonourLocalEnableStateAndUpdate() { + fun `self - remote enable state null - honour local and update`() { val state = Toggle.State(enable = false) feature.self().setEnabled(state) @@ -336,7 +336,7 @@ class FeatureTogglesTest { } @Test - fun whenRemoteStateDisabledThenIgnoreLocalState() { + fun `whenRemoteStateDisabledThenIgnoreLocalState - ignore local state`() { val state = Toggle.State( remoteEnableState = false, enable = true, @@ -347,7 +347,7 @@ class FeatureTogglesTest { } @Test - fun whenRemoteStateDisabledAndValidRolloutThenIgnoreRollout() { + fun `whenRemoteStateDisabledAndValidRollout - ignore rollout`() { val state = Toggle.State( remoteEnableState = false, enable = true, @@ -360,7 +360,7 @@ class FeatureTogglesTest { } @Test - fun whenRemoteStateEnabledAndLocalStateEnabledWithValidRolloutThenIgnoreRollout() { + fun `whenRemoteStateEnabledAndLocalStateEnabledWithValidRollout - ignore rollout`() { val state = Toggle.State( remoteEnableState = true, enable = true, @@ -374,7 +374,7 @@ class FeatureTogglesTest { } @Test - fun whenRemoteStateEnabledAndLocalStateDisabledWithValidRolloutThenDoRollout() { + fun `whenRemoteStateEnabledAndLocalStateDisabledWithValidRollout - do rollout`() { val state = Toggle.State( remoteEnableState = true, enable = false, @@ -388,7 +388,7 @@ class FeatureTogglesTest { } @Test - fun whenAppUpdateThenEvaluatePreviousState() { + fun `whenAppUpdateThenEvaluatePreviousState - evaluate previous state`() { // when remoteEnableState is null it means app update val state = Toggle.State( remoteEnableState = null, @@ -405,7 +405,7 @@ class FeatureTogglesTest { } @Test - fun whenNoMatchingVariantThenFeatureIsDisabled() { + fun `whenNoMatchingVariantThenFeatureIsDisabled - feature disabled`() { val state = Toggle.State( remoteEnableState = null, enable = true, @@ -422,7 +422,7 @@ class FeatureTogglesTest { } @Test - fun whenMatchingVariantThenReturnFeatureState() { + fun `whenMatchingVariantThenReturnFeatureState - return feature state`() { provider.variantKey = "ma" val state = Toggle.State( remoteEnableState = null, @@ -440,7 +440,7 @@ class FeatureTogglesTest { } @Test - fun testVariantsAreIgnoredInFeatureFlags() { + fun `setFeatureFlags - variants ignored - disabled by default`() { provider.variantKey = "ma" val state = Toggle.State( remoteEnableState = null, @@ -466,7 +466,7 @@ class FeatureTogglesTest { } @Test - fun whenMultipleNotMatchingVariantThenReturnFeatureState() { + fun `whenMultipleNotMatchingVariantThenReturnFeatureState - return feature state`() { provider.variantKey = "zz" val state = Toggle.State( remoteEnableState = null, @@ -487,7 +487,7 @@ class FeatureTogglesTest { } @Test - fun whenAnyMatchingVariantThenReturnFeatureState() { + fun `whenAnyMatchingVariantThenReturnFeatureState - return feature state`() { provider.variantKey = "zz" val state = Toggle.State( remoteEnableState = null, diff --git a/feature-toggles/feature-toggles-impl/src/test/java/com/duckduckgo/feature/toggles/codegen/ContributesRemoteFeatureCodeGeneratorTest.kt b/feature-toggles/feature-toggles-impl/src/test/java/com/duckduckgo/feature/toggles/codegen/ContributesRemoteFeatureCodeGeneratorTest.kt index 05b77d2a9355..41514844e6dd 100644 --- a/feature-toggles/feature-toggles-impl/src/test/java/com/duckduckgo/feature/toggles/codegen/ContributesRemoteFeatureCodeGeneratorTest.kt +++ b/feature-toggles/feature-toggles-impl/src/test/java/com/duckduckgo/feature/toggles/codegen/ContributesRemoteFeatureCodeGeneratorTest.kt @@ -80,14 +80,14 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `the class is generated`() { + fun `forName - class generated - not null`() { val generatedClass = Class .forName("com.duckduckgo.feature.toggles.codegen.TestTriggerFeature_RemoteFeature") assertNotNull(generatedClass) } @Test - fun `the class is generated implements Toggle Store and PrivacyFeaturePlugin`() { + fun `the class is generated - implements Toggle Store and PrivacyFeaturePlugin - correct implementation`() { val generatedClass = Class .forName("com.duckduckgo.feature.toggles.codegen.TestTriggerFeature_RemoteFeature") .kotlin @@ -98,14 +98,14 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `the class factory is generated`() { + fun `generateClass - the class factory is generated - not null`() { val generatedClass = Class .forName("com.duckduckgo.feature.toggles.codegen.TestTriggerFeature_RemoteFeature_Factory") assertNotNull(generatedClass) } @Test - fun `the generated class is singleInstance annotated in the right scope`() { + fun `the generated class is single instance annotated in the right scope - single instance - trigger test scope`() { val generatedClass = Class .forName("com.duckduckgo.feature.toggles.codegen.TestTriggerFeature_RemoteFeature") .kotlin @@ -115,7 +115,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `the generated class is RemoteFeatureStoreNamed annotated in the right scope`() { + fun `the generated class is RemoteFeatureStoreNamed annotated in the right scope - annotated with TestTriggerFeature`() { val generatedClass = Class .forName("com.duckduckgo.feature.toggles.codegen.TestTriggerFeature_RemoteFeature") .kotlin @@ -126,7 +126,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { @Test @Ignore("ContributesBinding is only present in kotlin metadata now, we need to fix") - fun `the generated class contributes the toggle store binding`() { + fun `the generated class contributes the toggle store binding - scope and bound type`() { val generatedClass = Class .forName("com.duckduckgo.feature.toggles.codegen.TestTriggerFeature_RemoteFeature") .kotlin @@ -138,7 +138,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { @Test @Ignore("ContributesMultibinding is only present in kotlin metadata now, we need to fix") - fun `the generated class contributes the privacy plugin multibinding`() { + fun `contributes multibinding - privacy plugin - expected outcome`() { val generatedClass = Class .forName("com.duckduckgo.feature.toggles.codegen.TestTriggerFeature_RemoteFeature") .kotlin @@ -150,7 +150,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `re-evaluate feature state when feature hash is null`() { + fun `store - feature state re-evaluation when hash is null - enabled and disabled states`() { val feature = generatedFeatureNewInstance() val privacyPlugin = (feature as PrivacyFeaturePlugin) @@ -199,7 +199,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `do not re-evaluate feature state if hash hasn't changed`() { + fun `store - feature state unchanged if hash hasn't changed - features enabled`() { val feature = generatedFeatureNewInstance() val privacyPlugin = (feature as PrivacyFeaturePlugin) @@ -250,7 +250,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `re-evaluate feature state if hash changed`() { + fun `store - re-evaluate feature state if hash changed - enabled and disabled states updated`() { val feature = generatedFeatureNewInstance() val privacyPlugin = (feature as PrivacyFeaturePlugin) @@ -301,7 +301,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `re-evaluate feature when already preset in remote config but just added to client`() { + fun `re-evaluate feature when already preset in remote config but just added to client - store updated - new foo feature enabled`() { fun createAnotherFooFeature(): Any { return Class .forName("com.duckduckgo.feature.toggles.codegen.AnotherTestTriggerFeature_RemoteFeature") @@ -371,7 +371,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `when sub-feature is present remotely but missing locally continue without error`() { + fun `when sub-feature is present remotely but missing locally continue without error - store feature - missing feature enabled, foo feature enabled`() { val feature = generatedFeatureNewInstance() val privacyPlugin = (feature as PrivacyFeaturePlugin) @@ -399,7 +399,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `fresh install and later update returns correct feature values`() { + fun `store - fresh install and later update returns correct feature values`() { val feature = generatedFeatureNewInstance() val privacyPlugin = (feature as PrivacyFeaturePlugin) @@ -443,7 +443,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `test internal always enabled annotation`() { + fun `test internal always enabled annotation - store - internal default false enabled`() { val feature = generatedFeatureNewInstance() val privacyPlugin = (feature as PrivacyFeaturePlugin) @@ -480,7 +480,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test // see https://app.asana.com/0/0/1205806409373059/1205806409373112/f - fun `test internal always enabled truth table`() { + fun `store - internal always enabled truth table - true`() { val feature = generatedFeatureNewInstance() val privacyPlugin = (feature as PrivacyFeaturePlugin) @@ -607,7 +607,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `test staged rollout for default-enabled feature flag`() { + fun `test staged rollout for default-enabled feature flag - store - enabled`() { val feature = generatedFeatureNewInstance() val privacyPlugin = (feature as PrivacyFeaturePlugin) @@ -638,7 +638,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `the disable state of the feature always wins`() { + fun `store - disable state of the feature always wins - disabled`() { val feature = generatedFeatureNewInstance() val privacyPlugin = (feature as PrivacyFeaturePlugin) @@ -695,7 +695,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `the rollout step set to 0 disables the feature`() { + fun `store - rollout step set to 0 disables the feature`() { val jsonFeature = """ { "state": "enabled", @@ -723,7 +723,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `the parent feature disabled doesn't interfer with the sub-feature state`() { + fun `store - parent feature disabled - sub-feature state enabled`() { val jsonFeature = """ { "state": "disabled", @@ -751,7 +751,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `the features have the right state for internal builds`() { + fun `generatedFeature - features have right state for internal builds - disabled`() { whenever(appBuildConfig.flavor).thenReturn(INTERNAL) val jsonFeature = """ @@ -782,7 +782,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `the feature incremental steps are ignored when feature disabled`() { + fun `store - feature disabled - foo feature not enabled`() { val jsonFeature = """ { "state": "enabled", @@ -817,7 +817,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `the feature incremental steps are executed when feature is enabled`() { + fun `store - feature incremental steps executed when enabled`() { val jsonFeature = """ { "state": "enabled", @@ -855,7 +855,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `the invalid rollout steps are ignored and not executed`() { + fun `store - invalid rollout steps ignored - enabled`() { val jsonFeature = """ { "state": "enabled", @@ -890,7 +890,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `disable a previously enabled incremental rollout`() { + fun `store - disable previously enabled incremental rollout - disabled`() { val jsonFeature = """ { "state": "enabled", @@ -941,7 +941,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `re-enable a previously disabled incremental rollout`() { + fun `store - re-enable incremental rollout - enabled`() { whenever(appBuildConfig.versionCode).thenReturn(1) val feature = generatedFeatureNewInstance() @@ -1027,7 +1027,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `feature was enabled remains enabled and rollout threshold is set`() { + fun `feature was enabled remains enabled and rollout threshold is set - feature state - enabled and rollout threshold set`() { whenever(appBuildConfig.versionCode).thenReturn(1) val feature = generatedFeatureNewInstance() @@ -1151,7 +1151,21 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `full feature lifecycle`() { + fun `testEnableDisableFeature`· Tests that a feature can be enabled and disabled· +2· `testRollout`· Tests that a feature can be rolled out to users, with the rollout percentage increasing over time· +3· `testHaltRollout`· Tests that a rollout can be halted· +4· `testResumeRollout`· Tests that a rollout can be resumed after being halted· +5· `testFinishRollout`· Tests that a rollout can be finished· + +The test class uses a mocking library (Mockk) to simulate the behavior of the app's build configuration and the feature flag system· + +Here are some key points from the code· + +* The `testFeature` object is used to represent the feature being tested· +* The `privacyPlugin` object is used to store and retrieve data about the feature flags· +* The test class uses a combination of JSON strings and Kotlin objects to simulate different scenarios· +* The `when` function is used to mock the behavior of the app's build configuration· +* The `thenReturn`() { whenever(appBuildConfig.versionCode).thenReturn(1) val feature = generatedFeatureNewInstance() @@ -1506,7 +1520,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `test variant parsing when no remote variant provided`() { + fun `test variant parsing when no remote variant provided - feature state enabled - all features enabled`() { val feature = generatedFeatureNewInstance() val privacyPlugin = (feature as PrivacyFeaturePlugin) @@ -1534,7 +1548,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `test variant parsing`() { + fun `testVariantParsing - variantManager set to mc - expected behavior`() { variantManager.variant = "mc" val feature = generatedFeatureNewInstance() @@ -1614,7 +1628,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `test variant when assigned variant key is null`() { + fun `testVariantWhenAssignedVariantKeyIsNull - variant manager - default variant assigned`() { variantManager.variant = null val feature = generatedFeatureNewInstance() @@ -1682,7 +1696,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `test variant when assigned variant key is not null`() { + fun `testVariantWhenAssignedVariantKeyIsNotNull - privacy plugin - all enabled`() { variantManager.variant = "na" val feature = generatedFeatureNewInstance() @@ -1747,7 +1761,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `test feature disabled and forces variant when variant is null`() { + fun `test feature disabled and forces variant when variant is null - store - forces variant`() { variantManager.variant = null val feature = generatedFeatureNewInstance() @@ -1788,7 +1802,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `test feature enabled and forces variant when variant is null`() { + fun `test feature enabled and forces variant when variant is null - state - expected outcome`() { variantManager.variant = null val feature = generatedFeatureNewInstance() @@ -1829,7 +1843,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `test feature does not force variant when already assigned`() { + fun `test feature does not force variant when already assigned - privacy plugin - enabled`() { variantManager.variant = "mc" val feature = generatedFeatureNewInstance() @@ -1870,7 +1884,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `test rollout roll back`() { + fun `store - rollout roll back - feature state updated`() { val feature = generatedFeatureNewInstance() val privacyPlugin = (feature as PrivacyFeaturePlugin) diff --git a/feature-toggles/feature-toggles-impl/src/test/java/com/duckduckgo/feature/toggles/impl/RealFeatureToggleImplTest.kt b/feature-toggles/feature-toggles-impl/src/test/java/com/duckduckgo/feature/toggles/impl/RealFeatureToggleImplTest.kt index 804d3626a0a9..3a7618e8c0d7 100644 --- a/feature-toggles/feature-toggles-impl/src/test/java/com/duckduckgo/feature/toggles/impl/RealFeatureToggleImplTest.kt +++ b/feature-toggles/feature-toggles-impl/src/test/java/com/duckduckgo/feature/toggles/impl/RealFeatureToggleImplTest.kt @@ -27,14 +27,14 @@ class RealFeatureToggleImplTest { RealFeatureToggleImpl(FakeFeatureTogglePluginPoint()) @Test - fun whenFeatureNameCanBeHandledByPluginThenReturnTheCorrectValue() { + fun `isFeatureEnabled - feature name can be handled by plugin - returns true`() { val result = testee.isFeatureEnabled(TrueFeatureName().value, false) assertNotNull(result) assertTrue(result) } @Test(expected = IllegalArgumentException::class) - fun whenFeatureNameCannotBeHandledByAnyPluginThenThrowException() { + fun `isFeatureEnabled - feature name cannot be handled by any plugin - throws exception`() { testee.isFeatureEnabled(NullFeatureName().value, false) } diff --git a/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/FingerprintProtectionSeedWorkerSchedulerTest.kt b/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/FingerprintProtectionSeedWorkerSchedulerTest.kt index c3f13fa7c842..85d3257f9188 100644 --- a/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/FingerprintProtectionSeedWorkerSchedulerTest.kt +++ b/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/FingerprintProtectionSeedWorkerSchedulerTest.kt @@ -43,7 +43,7 @@ class FingerprintProtectionSeedWorkerSchedulerTest { } @Test - fun whenOnStopThenStoreNewSeedAndEnqueueWorkWithReplacePolicy() { + fun `onStop - store new seed and enqueue work with replace policy`() { fingerprintProtectionSeedWorkerScheduler.onStop(mockOwner) verify(mockWorkManager).enqueueUniquePeriodicWork(any(), eq(REPLACE), any()) @@ -51,7 +51,7 @@ class FingerprintProtectionSeedWorkerSchedulerTest { } @Test - fun whenOnStartThenEnqueueWorkWithKeepPolicy() { + fun `onStart - enqueue work with keep policy`() { fingerprintProtectionSeedWorkerScheduler.onStart(mockOwner) verify(mockWorkManager).enqueueUniquePeriodicWork(any(), eq(KEEP), any()) diff --git a/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/FingerprintProtectionSeedWorkerTest.kt b/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/FingerprintProtectionSeedWorkerTest.kt index 94b66a8fa5bd..e51a137b3431 100644 --- a/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/FingerprintProtectionSeedWorkerTest.kt +++ b/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/FingerprintProtectionSeedWorkerTest.kt @@ -43,7 +43,7 @@ class FingerprintProtectionSeedWorkerTest { } @Test - fun whenDoWorkThenReturnSuccess() = runTest { + fun `doWork - fingerprint protection seed stored - success`() = runTest { val worker = TestListenableWorkerBuilder(context = context).build() worker.fingerprintProtectionSeedRepository = mockFingerprintProtectionSeedRepository diff --git a/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingbattery/FingerprintingBatteryContentScopeConfigPluginTest.kt b/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingbattery/FingerprintingBatteryContentScopeConfigPluginTest.kt index 18945ddd7a23..6849df30afa6 100644 --- a/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingbattery/FingerprintingBatteryContentScopeConfigPluginTest.kt +++ b/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingbattery/FingerprintingBatteryContentScopeConfigPluginTest.kt @@ -37,13 +37,13 @@ class FingerprintingBatteryContentScopeConfigPluginTest { } @Test - fun whenGetConfigThenReturnCorrectlyFormattedJson() { + fun `getConfig - return correctly formatted json`() { whenever(mockFingerprintingBatteryRepository.fingerprintingBatteryEntity).thenReturn(FingerprintingBatteryEntity(json = config)) assertEquals("\"fingerprintingBattery\":$config", testee.config()) } @Test - fun whenGetPreferencesThenReturnNull() { + fun `getPreferences - null`() { assertNull(testee.preferences()) } diff --git a/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingbattery/FingerprintingBatteryFeaturePluginTest.kt b/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingbattery/FingerprintingBatteryFeaturePluginTest.kt index 7960b7189433..4feae3a9fc1e 100644 --- a/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingbattery/FingerprintingBatteryFeaturePluginTest.kt +++ b/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingbattery/FingerprintingBatteryFeaturePluginTest.kt @@ -39,19 +39,19 @@ class FingerprintingBatteryFeaturePluginTest { } @Test - fun whenFeatureNameDoesNotMatchFingerprintingBatteryThenReturnFalse() { + fun `store - feature name does not match fingerprinting battery - returns false`() { FingerprintProtectionFeatureName.values().filter { it != FEATURE_NAME }.forEach { assertFalse(testee.store(it.value, JSON_STRING)) } } @Test - fun whenFeatureNameMatchesFingerprintingBatteryThenReturnTrue() { + fun `store - feature name matches fingerprinting battery - true`() { assertTrue(testee.store(FEATURE_NAME_VALUE, JSON_STRING)) } @Test - fun whenFeatureNameMatchesFingerprintingBatteryThenUpdateAll() { + fun `whenFeatureNameMatchesFingerprintingBattery - update all - json string`() { testee.store(FEATURE_NAME_VALUE, JSON_STRING) val captor = argumentCaptor() verify(mockFingerprintingBatteryRepository).updateAll(captor.capture()) diff --git a/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingcanvas/FingerprintingCanvasContentScopeConfigPluginTest.kt b/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingcanvas/FingerprintingCanvasContentScopeConfigPluginTest.kt index 520ae5cf49aa..9013a779df65 100644 --- a/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingcanvas/FingerprintingCanvasContentScopeConfigPluginTest.kt +++ b/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingcanvas/FingerprintingCanvasContentScopeConfigPluginTest.kt @@ -37,13 +37,13 @@ class FingerprintingCanvasContentScopeConfigPluginTest { } @Test - fun whenGetConfigThenReturnCorrectlyFormattedJson() { + fun `getConfig - return correctly formatted json`() { whenever(mockFingerprintingCanvasRepository.fingerprintingCanvasEntity).thenReturn(FingerprintingCanvasEntity(json = config)) assertEquals("\"fingerprintingCanvas\":$config", testee.config()) } @Test - fun whenGetPreferencesThenReturnNull() { + fun `getPreferences - null`() { assertNull(testee.preferences()) } diff --git a/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingcanvas/FingerprintingCanvasFeaturePluginTest.kt b/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingcanvas/FingerprintingCanvasFeaturePluginTest.kt index e8e3140f53db..2c13f494144f 100644 --- a/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingcanvas/FingerprintingCanvasFeaturePluginTest.kt +++ b/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingcanvas/FingerprintingCanvasFeaturePluginTest.kt @@ -39,19 +39,19 @@ class FingerprintingCanvasFeaturePluginTest { } @Test - fun whenFeatureNameDoesNotMatchFingerprintingCanvasThenReturnFalse() { + fun `store - feature name does not match fingerprinting canvas - returns false`() { FingerprintProtectionFeatureName.values().filter { it != FEATURE_NAME }.forEach { assertFalse(testee.store(it.value, JSON_STRING)) } } @Test - fun whenFeatureNameMatchesFingerprintingCanvasThenReturnTrue() { + fun `store - feature name matches fingerprinting canvas - returns true`() { assertTrue(testee.store(FEATURE_NAME_VALUE, JSON_STRING)) } @Test - fun whenFeatureNameMatchesFingerprintingCanvasThenUpdateAll() { + fun `whenFeatureNameMatchesFingerprintingCanvasThenUpdateAll - update all`() { testee.store(FEATURE_NAME_VALUE, JSON_STRING) val captor = argumentCaptor() verify(mockFingerprintingCanvasRepository).updateAll(captor.capture()) diff --git a/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintinghardware/FingerprintingHardwareContentScopeConfigPluginTest.kt b/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintinghardware/FingerprintingHardwareContentScopeConfigPluginTest.kt index 14d08d94db4f..b397bb666319 100644 --- a/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintinghardware/FingerprintingHardwareContentScopeConfigPluginTest.kt +++ b/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintinghardware/FingerprintingHardwareContentScopeConfigPluginTest.kt @@ -37,13 +37,13 @@ class FingerprintingHardwareContentScopeConfigPluginTest { } @Test - fun whenGetConfigThenReturnCorrectlyFormattedJson() { + fun `getConfig - return correctly formatted json`() { whenever(mockFingerprintingHardwareRepository.fingerprintingHardwareEntity).thenReturn(FingerprintingHardwareEntity(json = config)) assertEquals("\"fingerprintingHardware\":$config", testee.config()) } @Test - fun whenGetPreferencesThenReturnNull() { + fun `getPreferences - null`() { assertNull(testee.preferences()) } diff --git a/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintinghardware/FingerprintingHardwareFeaturePluginTest.kt b/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintinghardware/FingerprintingHardwareFeaturePluginTest.kt index 30c7c7150ed4..805c2651d3e9 100644 --- a/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintinghardware/FingerprintingHardwareFeaturePluginTest.kt +++ b/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintinghardware/FingerprintingHardwareFeaturePluginTest.kt @@ -39,19 +39,19 @@ class FingerprintingHardwareFeaturePluginTest { } @Test - fun whenFeatureNameDoesNotMatchFingerprintingHardwareThenReturnFalse() { + fun `store - feature name does not match fingerprinting hardware - returns false`() { FingerprintProtectionFeatureName.values().filter { it != FEATURE_NAME }.forEach { assertFalse(testee.store(it.value, JSON_STRING)) } } @Test - fun whenFeatureNameMatchesFingerprintingHardwareThenReturnTrue() { + fun `store - feature name matches fingerprinting hardware - returns true`() { assertTrue(testee.store(FEATURE_NAME_VALUE, JSON_STRING)) } @Test - fun whenFeatureNameMatchesFingerprintingHardwareThenUpdateAll() { + fun `whenFeatureNameMatchesFingerprintingHardware - update all - json string`() { testee.store(FEATURE_NAME_VALUE, JSON_STRING) val captor = argumentCaptor() verify(mockFingerprintingHardwareRepository).updateAll(captor.capture()) diff --git a/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingscreensize/FingerprintingScreenSizeContentScopeConfigPluginTest.kt b/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingscreensize/FingerprintingScreenSizeContentScopeConfigPluginTest.kt index e122bf6dbdf0..3d705c76f502 100644 --- a/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingscreensize/FingerprintingScreenSizeContentScopeConfigPluginTest.kt +++ b/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingscreensize/FingerprintingScreenSizeContentScopeConfigPluginTest.kt @@ -37,13 +37,13 @@ class FingerprintingScreenSizeContentScopeConfigPluginTest { } @Test - fun whenGetConfigThenReturnCorrectlyFormattedJson() { + fun `getConfig - return correctly formatted json`() { whenever(mockFingerprintingScreenSizeRepository.fingerprintingScreenSizeEntity).thenReturn(FingerprintingScreenSizeEntity(json = config)) assertEquals("\"fingerprintingScreenSize\":$config", testee.config()) } @Test - fun whenGetPreferencesThenReturnNull() { + fun `getPreferences - null`() { assertNull(testee.preferences()) } diff --git a/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingscreensize/FingerprintingScreenSizeFeaturePluginTest.kt b/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingscreensize/FingerprintingScreenSizeFeaturePluginTest.kt index f26dbbe002e9..4f4e2f471f4f 100644 --- a/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingscreensize/FingerprintingScreenSizeFeaturePluginTest.kt +++ b/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingscreensize/FingerprintingScreenSizeFeaturePluginTest.kt @@ -39,19 +39,19 @@ class FingerprintingScreenSizeFeaturePluginTest { } @Test - fun whenFeatureNameDoesNotMatchFingerprintingScreenSizeThenReturnFalse() { + fun `store - feature name does not match fingerprinting screen size - returns false`() { FingerprintProtectionFeatureName.values().filter { it != FEATURE_NAME }.forEach { assertFalse(testee.store(it.value, JSON_STRING)) } } @Test - fun whenFeatureNameMatchesFingerprintingScreenSizeThenReturnTrue() { + fun `store - feature name matches fingerprinting screen size - true`() { assertTrue(testee.store(FEATURE_NAME_VALUE, JSON_STRING)) } @Test - fun whenFeatureNameMatchesFingerprintingScreenSizeThenUpdateAll() { + fun `whenFeatureNameMatchesFingerprintingScreenSizeThenUpdateAll - update all`() { testee.store(FEATURE_NAME_VALUE, JSON_STRING) val captor = argumentCaptor() verify(mockFingerprintingScreenSizeRepository).updateAll(captor.capture()) diff --git a/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingtemporarystorage/FingerprintingTemporaryStorageContentScopeConfigPluginTest.kt b/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingtemporarystorage/FingerprintingTemporaryStorageContentScopeConfigPluginTest.kt index 5265ace4d356..0bbb56d1549e 100644 --- a/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingtemporarystorage/FingerprintingTemporaryStorageContentScopeConfigPluginTest.kt +++ b/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingtemporarystorage/FingerprintingTemporaryStorageContentScopeConfigPluginTest.kt @@ -37,14 +37,14 @@ class FingerprintingTemporaryStorageContentScopeConfigPluginTest { } @Test - fun whenGetConfigThenReturnCorrectlyFormattedJson() { + fun `getConfig - return correctly formatted json`() { whenever(mockFingerprintingTemporaryStorageRepository.fingerprintingTemporaryStorageEntity) .thenReturn(FingerprintingTemporaryStorageEntity(json = config)) assertEquals("\"fingerprintingTemporaryStorage\":$config", testee.config()) } @Test - fun whenGetPreferencesThenReturnNull() { + fun `getPreferences - null`() { assertNull(testee.preferences()) } diff --git a/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingtemporarystorage/FingerprintingTemporaryStorageFeaturePluginTest.kt b/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingtemporarystorage/FingerprintingTemporaryStorageFeaturePluginTest.kt index e33f10640dd7..7e15fbe26147 100644 --- a/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingtemporarystorage/FingerprintingTemporaryStorageFeaturePluginTest.kt +++ b/fingerprint-protection/fingerprint-protection-impl/src/test/java/com/duckduckgo/fingerprintprotection/impl/features/fingerprintingtemporarystorage/FingerprintingTemporaryStorageFeaturePluginTest.kt @@ -39,19 +39,19 @@ class FingerprintingTemporaryStorageFeaturePluginTest { } @Test - fun whenFeatureNameDoesNotMatchFingerprintingTemporaryStorageThenReturnFalse() { + fun `store - feature name does not match fingerprinting temporary storage - returns false`() { FingerprintProtectionFeatureName.values().filter { it != FEATURE_NAME }.forEach { assertFalse(testee.store(it.value, JSON_STRING)) } } @Test - fun whenFeatureNameMatchesFingerprintingTemporaryStorageThenReturnTrue() { + fun `store - feature name matches fingerprinting temporary storage - returns true`() { assertTrue(testee.store(FEATURE_NAME_VALUE, JSON_STRING)) } @Test - fun whenFeatureNameMatchesFingerprintingTemporaryStorageThenUpdateAll() { + fun `whenFeatureNameMatchesFingerprintingTemporaryStorageThenUpdateAll - update all`() { testee.store(FEATURE_NAME_VALUE, JSON_STRING) val captor = argumentCaptor() verify(mockFingerprintingTemporaryStorageRepository).updateAll(captor.capture()) diff --git a/fingerprint-protection/fingerprint-protection-store/src/test/java/com/duckduckgo/fingerprintprotection/store/features/fingerprintingbattery/RealFingerprintingBatteryRepositoryTest.kt b/fingerprint-protection/fingerprint-protection-store/src/test/java/com/duckduckgo/fingerprintprotection/store/features/fingerprintingbattery/RealFingerprintingBatteryRepositoryTest.kt index 90221bc6f6e8..5cba3f7f344c 100644 --- a/fingerprint-protection/fingerprint-protection-store/src/test/java/com/duckduckgo/fingerprintprotection/store/features/fingerprintingbattery/RealFingerprintingBatteryRepositoryTest.kt +++ b/fingerprint-protection/fingerprint-protection-store/src/test/java/com/duckduckgo/fingerprintprotection/store/features/fingerprintingbattery/RealFingerprintingBatteryRepositoryTest.kt @@ -44,7 +44,7 @@ class RealFingerprintingBatteryRepositoryTest { } @Test - fun whenInitializedAndDoesNotHaveStoredValueThenLoadEmptyJsonToMemory() = + fun `loadFingerprintingBattery - initialized and no stored value - load empty json to memory`() = runTest { testee = RealFingerprintingBatteryRepository( @@ -59,7 +59,7 @@ class RealFingerprintingBatteryRepositoryTest { } @Test - fun whenInitializedAndHasStoredValueThenLoadStoredJsonToMemory() = + fun `whenInitializedAndHasStoredValueThenLoadStoredJsonToMemory - load stored json to memory`() = runTest { whenever(mockFingerprintingBatteryDao.get()).thenReturn(fingerprintingBatteryEntity) testee = @@ -75,7 +75,7 @@ class RealFingerprintingBatteryRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - update all called`() = runTest { testee = RealFingerprintingBatteryRepository( diff --git a/fingerprint-protection/fingerprint-protection-store/src/test/java/com/duckduckgo/fingerprintprotection/store/features/fingerprintingcanvas/RealFingerprintingCanvasRepositoryTest.kt b/fingerprint-protection/fingerprint-protection-store/src/test/java/com/duckduckgo/fingerprintprotection/store/features/fingerprintingcanvas/RealFingerprintingCanvasRepositoryTest.kt index cd8cdb9e6e84..0a5e814b4772 100644 --- a/fingerprint-protection/fingerprint-protection-store/src/test/java/com/duckduckgo/fingerprintprotection/store/features/fingerprintingcanvas/RealFingerprintingCanvasRepositoryTest.kt +++ b/fingerprint-protection/fingerprint-protection-store/src/test/java/com/duckduckgo/fingerprintprotection/store/features/fingerprintingcanvas/RealFingerprintingCanvasRepositoryTest.kt @@ -44,7 +44,7 @@ class RealFingerprintingCanvasRepositoryTest { } @Test - fun whenInitializedAndDoesNotHaveStoredValueThenLoadEmptyJsonToMemory() = + fun `loadEmptyJson - initialized and does not have stored value - load empty json to memory`() = runTest { testee = RealFingerprintingCanvasRepository( @@ -59,7 +59,7 @@ class RealFingerprintingCanvasRepositoryTest { } @Test - fun whenInitializedAndHasStoredValueThenLoadStoredJsonToMemory() = + fun `whenInitializedAndHasStoredValueThenLoadStoredJsonToMemory - load stored json to memory`() = runTest { whenever(mockFingerprintingCanvasDao.get()).thenReturn(fingerprintingCanvasEntity) testee = @@ -75,7 +75,7 @@ class RealFingerprintingCanvasRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - update all called`() = runTest { testee = RealFingerprintingCanvasRepository( diff --git a/fingerprint-protection/fingerprint-protection-store/src/test/java/com/duckduckgo/fingerprintprotection/store/features/fingerprintinghardware/RealFingerprintingHardwareRepositoryTest.kt b/fingerprint-protection/fingerprint-protection-store/src/test/java/com/duckduckgo/fingerprintprotection/store/features/fingerprintinghardware/RealFingerprintingHardwareRepositoryTest.kt index 5fdd7e6fbd7f..f69c80f3be72 100644 --- a/fingerprint-protection/fingerprint-protection-store/src/test/java/com/duckduckgo/fingerprintprotection/store/features/fingerprintinghardware/RealFingerprintingHardwareRepositoryTest.kt +++ b/fingerprint-protection/fingerprint-protection-store/src/test/java/com/duckduckgo/fingerprintprotection/store/features/fingerprintinghardware/RealFingerprintingHardwareRepositoryTest.kt @@ -44,7 +44,7 @@ class RealFingerprintingHardwareRepositoryTest { } @Test - fun whenInitializedAndDoesNotHaveStoredValueThenLoadEmptyJsonToMemory() = + fun `loadFingerprintingHardware - initialized and no stored value - load empty json to memory`() = runTest { testee = RealFingerprintingHardwareRepository( @@ -59,7 +59,7 @@ class RealFingerprintingHardwareRepositoryTest { } @Test - fun whenInitializedAndHasStoredValueThenLoadStoredJsonToMemory() = + fun `whenInitializedAndHasStoredValue - load stored json to memory`() = runTest { whenever(mockFingerprintingHardwareDao.get()).thenReturn(fingerprintingHardwareEntity) testee = @@ -75,7 +75,7 @@ class RealFingerprintingHardwareRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - update all called`() = runTest { testee = RealFingerprintingHardwareRepository( diff --git a/fingerprint-protection/fingerprint-protection-store/src/test/java/com/duckduckgo/fingerprintprotection/store/features/fingerprintingscreensize/RealFingerprintingScreenSizeRepositoryTest.kt b/fingerprint-protection/fingerprint-protection-store/src/test/java/com/duckduckgo/fingerprintprotection/store/features/fingerprintingscreensize/RealFingerprintingScreenSizeRepositoryTest.kt index 648e5f9b1cd4..1b129a44505b 100644 --- a/fingerprint-protection/fingerprint-protection-store/src/test/java/com/duckduckgo/fingerprintprotection/store/features/fingerprintingscreensize/RealFingerprintingScreenSizeRepositoryTest.kt +++ b/fingerprint-protection/fingerprint-protection-store/src/test/java/com/duckduckgo/fingerprintprotection/store/features/fingerprintingscreensize/RealFingerprintingScreenSizeRepositoryTest.kt @@ -44,7 +44,7 @@ class RealFingerprintingScreenSizeRepositoryTest { } @Test - fun whenInitializedAndDoesNotHaveStoredValueThenLoadEmptyJsonToMemory() = + fun `loadEmptyJsonToMemory - initialized and does not have stored value`() = runTest { testee = RealFingerprintingScreenSizeRepository( @@ -59,7 +59,7 @@ class RealFingerprintingScreenSizeRepositoryTest { } @Test - fun whenInitializedAndHasStoredValueThenLoadStoredJsonToMemory() = + fun `whenInitializedAndHasStoredValueThenLoadStoredJsonToMemory - load stored json to memory`() = runTest { whenever(mockFingerprintingScreenSizeDao.get()).thenReturn(fingerprintingScreenSizeEntity) testee = @@ -75,7 +75,7 @@ class RealFingerprintingScreenSizeRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - update all called`() = runTest { testee = RealFingerprintingScreenSizeRepository( diff --git a/fingerprint-protection/fingerprint-protection-store/src/test/java/com/duckduckgo/fingerprintprotection/store/features/fingerprintingtemporarystorage/RealFingerprintingTemporaryStorageRepositoryTest.kt b/fingerprint-protection/fingerprint-protection-store/src/test/java/com/duckduckgo/fingerprintprotection/store/features/fingerprintingtemporarystorage/RealFingerprintingTemporaryStorageRepositoryTest.kt index 5550ad352a72..b1b0efd364ad 100644 --- a/fingerprint-protection/fingerprint-protection-store/src/test/java/com/duckduckgo/fingerprintprotection/store/features/fingerprintingtemporarystorage/RealFingerprintingTemporaryStorageRepositoryTest.kt +++ b/fingerprint-protection/fingerprint-protection-store/src/test/java/com/duckduckgo/fingerprintprotection/store/features/fingerprintingtemporarystorage/RealFingerprintingTemporaryStorageRepositoryTest.kt @@ -44,7 +44,7 @@ class RealFingerprintingTemporaryStorageRepositoryTest { } @Test - fun whenInitializedAndDoesNotHaveStoredValueThenLoadEmptyJsonToMemory() = + fun `loadEmptyJsonToMemory - initialized and does not have stored value`() = runTest { testee = RealFingerprintingTemporaryStorageRepository( @@ -59,7 +59,7 @@ class RealFingerprintingTemporaryStorageRepositoryTest { } @Test - fun whenInitializedAndHasStoredValueThenLoadStoredJsonToMemory() = + fun `whenInitializedAndHasStoredValueThenLoadStoredJsonToMemory - load stored json to memory`() = runTest { whenever(mockFingerprintingTemporaryStorageDao.get()).thenReturn(fingerprintingTemporaryStorageEntity) testee = @@ -75,7 +75,7 @@ class RealFingerprintingTemporaryStorageRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - update all called`() = runTest { testee = RealFingerprintingTemporaryStorageRepository( diff --git a/fingerprint-protection/fingerprint-protection-store/src/test/java/com/duckduckgo/fingerprintprotection/store/seed/RealFingerprintProtectionSeedRepositoryTest.kt b/fingerprint-protection/fingerprint-protection-store/src/test/java/com/duckduckgo/fingerprintprotection/store/seed/RealFingerprintProtectionSeedRepositoryTest.kt index 0f45c6410126..9545ccdccc59 100644 --- a/fingerprint-protection/fingerprint-protection-store/src/test/java/com/duckduckgo/fingerprintprotection/store/seed/RealFingerprintProtectionSeedRepositoryTest.kt +++ b/fingerprint-protection/fingerprint-protection-store/src/test/java/com/duckduckgo/fingerprintprotection/store/seed/RealFingerprintProtectionSeedRepositoryTest.kt @@ -30,12 +30,12 @@ class RealFingerprintProtectionSeedRepositoryTest { } @Test - fun whenInitializedRandomSeedIsSet() { + fun `initialize - seed set`() { assertFalse(testee.seed.isBlank()) } @Test - fun whenStoredNewSeedThenSeedIsRefreshed() { + fun `storeNewSeed - seed refreshed`() { val oldSeed = testee.seed testee.storeNewSeed() assertNotEquals(oldSeed, testee.seed) diff --git a/httpsupgrade/httpsupgrade-impl/src/test/java/com/duckduckgo/httpsupgrade/impl/HttpsBloomFilterSpecJsonTest.kt b/httpsupgrade/httpsupgrade-impl/src/test/java/com/duckduckgo/httpsupgrade/impl/HttpsBloomFilterSpecJsonTest.kt index 1eef0d9d07eb..3956a940159f 100644 --- a/httpsupgrade/httpsupgrade-impl/src/test/java/com/duckduckgo/httpsupgrade/impl/HttpsBloomFilterSpecJsonTest.kt +++ b/httpsupgrade/httpsupgrade-impl/src/test/java/com/duckduckgo/httpsupgrade/impl/HttpsBloomFilterSpecJsonTest.kt @@ -24,7 +24,7 @@ import org.junit.Test class HttpsBloomFilterSpecJsonTest { @Test - fun whenGivenValidJsonThenParsesCorrectly() { + fun `fromJson - given valid json - parses correctly`() { val moshi = Moshi.Builder().build() val jsonAdapter = moshi.adapter(HttpsBloomFilterSpec::class.java) val result = jsonAdapter.fromJson(json())!! diff --git a/httpsupgrade/httpsupgrade-impl/src/test/java/com/duckduckgo/httpsupgrade/impl/HttpsFalsePositivesJsonTest.kt b/httpsupgrade/httpsupgrade-impl/src/test/java/com/duckduckgo/httpsupgrade/impl/HttpsFalsePositivesJsonTest.kt index 373abc7b9e77..fc16931d0fa7 100644 --- a/httpsupgrade/httpsupgrade-impl/src/test/java/com/duckduckgo/httpsupgrade/impl/HttpsFalsePositivesJsonTest.kt +++ b/httpsupgrade/httpsupgrade-impl/src/test/java/com/duckduckgo/httpsupgrade/impl/HttpsFalsePositivesJsonTest.kt @@ -26,7 +26,7 @@ import org.junit.Test class HttpsFalsePositivesJsonTest { @Test - fun whenGivenValidJsonThenParsesCorrectly() { + fun `fromJson - given valid json - parses correctly`() { val moshi = Moshi.Builder().add(HttpsFalsePositivesJsonAdapter()).build() val type = Types.newParameterizedType(List::class.java, HttpsFalsePositiveDomain::class.java) val jsonAdapter: JsonAdapter> = moshi.adapter(type) diff --git a/httpsupgrade/httpsupgrade-store/src/test/java/com/duckduckgo/httpsupgrade/store/HttpsBloomFilterSpecDaoTest.kt b/httpsupgrade/httpsupgrade-store/src/test/java/com/duckduckgo/httpsupgrade/store/HttpsBloomFilterSpecDaoTest.kt index 90afd09f5e67..e4a0fd83b4e7 100644 --- a/httpsupgrade/httpsupgrade-store/src/test/java/com/duckduckgo/httpsupgrade/store/HttpsBloomFilterSpecDaoTest.kt +++ b/httpsupgrade/httpsupgrade-store/src/test/java/com/duckduckgo/httpsupgrade/store/HttpsBloomFilterSpecDaoTest.kt @@ -56,18 +56,18 @@ class HttpsBloomFilterSpecDaoTest { } @Test - fun whenModelIsEmptyThenGetIsNull() = runTest { + fun `get - model empty - is null`() = runTest { assertNull(dao.get()) } @Test - fun whenModelIsInsertedThenGetIsNotNull() = runTest { + fun `insert - get is not null`() = runTest { dao.insert(HttpsBloomFilterSpec(errorRate = 0.1, bitCount = 1000, totalEntries = 55, sha256 = "abc")) assertNotNull(dao.get()) } @Test - fun whenNewModelIsInsertedThenGetIsNotNullAndDetailsUpdates() = runTest { + fun `get - new model inserted - is not null and details updates`() = runTest { dao.insert(HttpsBloomFilterSpec(bitCount = 1000, errorRate = 0.1, totalEntries = 55, sha256 = "abc")) dao.insert(HttpsBloomFilterSpec(bitCount = 2000, errorRate = 0.2, totalEntries = 60, sha256 = "xyz")) diff --git a/httpsupgrade/httpsupgrade-store/src/test/java/com/duckduckgo/httpsupgrade/store/HttpsFalsePositivesDaoTest.kt b/httpsupgrade/httpsupgrade-store/src/test/java/com/duckduckgo/httpsupgrade/store/HttpsFalsePositivesDaoTest.kt index 2ef948ec74e1..8f36df516bc9 100644 --- a/httpsupgrade/httpsupgrade-store/src/test/java/com/duckduckgo/httpsupgrade/store/HttpsFalsePositivesDaoTest.kt +++ b/httpsupgrade/httpsupgrade-store/src/test/java/com/duckduckgo/httpsupgrade/store/HttpsFalsePositivesDaoTest.kt @@ -56,29 +56,29 @@ class HttpsFalsePositivesDaoTest { } @Test - fun whenModelIsEmptyThenCountIsZero() = runTest { + fun `count - model empty - zero`() = runTest { assertEquals(0, dao.count()) } @Test - fun whenModelIsEmptyThenContainsDomainIsFalse() = runTest { + fun `containsDomain - model empty - false`() = runTest { assertFalse(dao.contains(domain)) } @Test - fun whenDomainInsertedThenContainsDomainIsTrue() = runTest { + fun `insertAll - contains domain is true`() = runTest { dao.insertAll(listOf(HttpsFalsePositiveDomain(domain))) assertTrue(dao.contains(domain)) } @Test - fun whenDomainInsertedThenCountIsOne() = runTest { + fun `insertAll - count is one`() = runTest { dao.insertAll(listOf(HttpsFalsePositiveDomain(domain))) assertEquals(1, dao.count()) } @Test - fun whenSecondUniqueDomainInsertedThenCountIsTwo() = runTest { + fun `insertAll - count is two`() = runTest { dao.insertAll(listOf(HttpsFalsePositiveDomain(domain))) dao.insertAll(listOf(HttpsFalsePositiveDomain(anotherDomain))) assertEquals(2, dao.count()) @@ -92,7 +92,7 @@ class HttpsFalsePositivesDaoTest { } @Test - fun whenAllUpdatedThenPreviousValuesAreReplaced() = runTest { + fun `updateAll - previous values replaced`() = runTest { dao.insertAll(listOf(HttpsFalsePositiveDomain(domain))) dao.updateAll(listOf(HttpsFalsePositiveDomain(anotherDomain))) assertEquals(1, dao.count()) @@ -100,7 +100,7 @@ class HttpsFalsePositivesDaoTest { } @Test - fun whenAllDeletedThenContainsDomainIsFalse() = runTest { + fun `insertAll - delete all - does not contain domain`() = runTest { dao.insertAll(listOf(HttpsFalsePositiveDomain(domain))) dao.deleteAll() assertFalse(dao.contains(domain)) diff --git a/installation/installation-impl/src/test/java/InstallSourceLifecycleObserverTest.kt b/installation/installation-impl/src/test/java/InstallSourceLifecycleObserverTest.kt index 01dd92185057..d7c95cbe2d8b 100644 --- a/installation/installation-impl/src/test/java/InstallSourceLifecycleObserverTest.kt +++ b/installation/installation-impl/src/test/java/InstallSourceLifecycleObserverTest.kt @@ -53,13 +53,13 @@ class InstallSourceLifecycleObserverTest { ) @Test - fun whenNotPreviouslyProcessedThenPixelSent() = runTest { + fun `onCreate - not previously processed - pixel sent`() = runTest { testee.onCreate(mockLifecycleOwner) verify(mockPixel).fire(eq(APP_INSTALLER_PACKAGE_NAME), any(), any(), eq(COUNT)) } @Test - fun whenPreviouslyProcessedThenPixelNotSent() = runTest { + fun `recordInstallSourceProcessed - pixel not sent`() = runTest { testee.recordInstallSourceProcessed() testee.onCreate(mockLifecycleOwner) verify(mockPixel, never()).fire(eq(APP_INSTALLER_PACKAGE_NAME), any(), any(), eq(COUNT)) diff --git a/js-messaging/js-messaging-impl/src/test/java/com/duckduckgo/js/messaging/impl/RealJsMessageHelperTest.kt b/js-messaging/js-messaging-impl/src/test/java/com/duckduckgo/js/messaging/impl/RealJsMessageHelperTest.kt index 45c3950a8f0f..0a80fb4dfd69 100644 --- a/js-messaging/js-messaging-impl/src/test/java/com/duckduckgo/js/messaging/impl/RealJsMessageHelperTest.kt +++ b/js-messaging/js-messaging-impl/src/test/java/com/duckduckgo/js/messaging/impl/RealJsMessageHelperTest.kt @@ -23,7 +23,7 @@ class RealJsMessageHelperTest { private val jsMessageHelper = RealJsMessageHelper(TestScope(), coroutineRule.testDispatcherProvider) @Test - fun whenSendSubscriptionEventThenResponseMatches() = runTest { + fun `sendSubscriptionEvent - response matches`() = runTest { val expected = """ javascript:(function() { window['callbackName']('secret', {"context":"myContext","featureName":"myFeature","params":{"test":"this is a test"},"subscriptionName":"mySubscription"}); @@ -45,7 +45,7 @@ class RealJsMessageHelperTest { } @Test - fun whenSendJsResponseAsSuccessThenResponseMatches() = runTest { + fun `sendJsResponse - as success - response matches`() = runTest { val expected = """ javascript:(function() { window['callbackName']('secret', {"context":"myContext","featureName":"myFeature","id":"myId","method":"myMethod","result":{"test":"this is a test"}}); @@ -68,7 +68,7 @@ class RealJsMessageHelperTest { } @Test - fun whenSendJsResponseAsErrorThenResponseMatches() = runTest { + fun `sendJsResponse - as error - response matches`() = runTest { val expected = """ javascript:(function() { window['callbackName']('secret', {"context":"myContext","error":"this is an error","featureName":"myFeature","id":"myId","method":"myMethod"}); diff --git a/macos/macos-impl/src/test/java/com/duckduckgo/macos/impl/MacOsViewModelTest.kt b/macos/macos-impl/src/test/java/com/duckduckgo/macos/impl/MacOsViewModelTest.kt index 134f887b3096..1e1667e9b0b0 100644 --- a/macos/macos-impl/src/test/java/com/duckduckgo/macos/impl/MacOsViewModelTest.kt +++ b/macos/macos-impl/src/test/java/com/duckduckgo/macos/impl/MacOsViewModelTest.kt @@ -47,7 +47,7 @@ class MacOsViewModelTest { } @Test - fun whenOnShareClickedAndInviteCodeExistsThenEmitCommandShareInviteCodeWithCorrectCode() = runTest { + fun `onShareClicked - invite code exists - emit command share invite code with correct code`() = runTest { testee.commands.test { testee.onShareClicked() assertEquals(ShareLink, awaitItem()) @@ -62,7 +62,7 @@ class MacOsViewModelTest { } @Test - fun whenOnShareClickedAThenPixelFired() = runTest { + fun `onShareClicked - pixel fired`() = runTest { testee.onShareClicked() verify(mockPixel).fire(MACOS_WAITLIST_SHARE_PRESSED) diff --git a/navigation/navigation-impl/src/test/java/com/duckduckgo/navigation/impl/GlobalActivityStarterImplTest.kt b/navigation/navigation-impl/src/test/java/com/duckduckgo/navigation/impl/GlobalActivityStarterImplTest.kt index 7264fb66dafb..1c076b7d3ff1 100644 --- a/navigation/navigation-impl/src/test/java/com/duckduckgo/navigation/impl/GlobalActivityStarterImplTest.kt +++ b/navigation/navigation-impl/src/test/java/com/duckduckgo/navigation/impl/GlobalActivityStarterImplTest.kt @@ -42,17 +42,17 @@ class GlobalActivityStarterImplTest { private val globalActivityStarter = GlobalActivityStarterImpl(setOf(TestActivityWithParamsMapper(), TestActivityNoParamsMapper())) @Test - fun whenStartIntentNotFoundActivityThenReturnNull() { + fun `startIntent - not found activity - return null`() { assertNull(globalActivityStarter.startIntent(context, NotFoundParams)) } @Test - fun whenStartIntentNotFoundDeeplinkActivityThenReturnNull() { + fun `startIntent - deeplink activity not found - return null`() { assertNull(globalActivityStarter.startIntent(context, notFoundDeeplinkParams)) } @Test - fun whenStartIntentWithParamsFindsActivityThenReturnIntent() { + fun `startIntent - finds activity then returns intent`() { val intent = globalActivityStarter.startIntent(context, TestParams("test")) assertNotNull(intent) @@ -60,7 +60,7 @@ class GlobalActivityStarterImplTest { } @Test - fun whenStartIntentWithDeeplinkNoParamsFindsActivityThenReturnIntent() { + fun `startIntent - deeplink no params - returns intent`() { val intent = globalActivityStarter.startIntent(context, DeeplinkActivityParams("screenTest")) assertNotNull(intent) @@ -68,7 +68,7 @@ class GlobalActivityStarterImplTest { } @Test - fun whenStartIntentWithDeeplinkParamsFindsActivityThenReturnIntent() { + fun `startIntent - deeplink params - returns intent with activity params`() { val intent = globalActivityStarter.startIntent(context, DeeplinkActivityParams("screenTest", jsonArguments = "{\"value\": \"test\"}")) assertNotNull(intent) @@ -76,17 +76,17 @@ class GlobalActivityStarterImplTest { } @Test(expected = IllegalArgumentException::class) - fun whenStartNotFoundActivityThenThrow() { + fun `start - start not found activity - throws`() { globalActivityStarter.start(context, NotFoundParams) } @Test(expected = IllegalArgumentException::class) - fun whenStartNotFoundDeeplinkActivityThenThrow() { + fun `start - deeplink activity not found - throws`() { globalActivityStarter.start(context, notFoundDeeplinkParams) } @Test - fun whenStartWithParamsFindsActivityThenSucceeds() { + fun `startWithParams - finds activity then succeeds`() { val context: Context = mock() globalActivityStarter.start(context, TestParams("test")) @@ -94,7 +94,7 @@ class GlobalActivityStarterImplTest { } @Test - fun whenStartWithDeeplinkParamsArgumentsFindsActivityThenSucceeds() { + fun `startWithDeeplinkParams - finds activity then succeeds`() { val context: Context = mock() globalActivityStarter.start(context, DeeplinkActivityParams("screenTest", jsonArguments = "{\"value\": \"test\"}")) @@ -102,7 +102,7 @@ class GlobalActivityStarterImplTest { } @Test - fun whenStartWithDeeplinkNoParamsArgumentsFindsActivityThenSucceeds() { + fun `startWithDeeplinkNoParamsArgumentsFindsActivityThenSucceeds - starts activity`() { val context: Context = mock() globalActivityStarter.start(context, DeeplinkActivityParams("screenTest")) diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/WgVpnNetworkStackTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/WgVpnNetworkStackTest.kt index c904fb8a19f6..bda8fc714962 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/WgVpnNetworkStackTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/WgVpnNetworkStackTest.kt @@ -123,7 +123,7 @@ class WgVpnNetworkStackTest { } @Test - fun whenOnPrepareVpnThenReturnVpnTunnelConfigAndStoreServerDetails() = runTest { + fun `onPrepareVpn - return vpn tunnel config and store server details`() = runTest { whenever(wgTunnel.createAndSetWgConfig()).thenReturn(wgConfig.success()) val actual = wgVpnNetworkStack.onPrepareVpn().getOrNull() @@ -140,7 +140,7 @@ class WgVpnNetworkStackTest { } @Test - fun whenOnPrepareVpnAndPrivateDnsConfiguredThenReturnEmptyDnsList() = runTest { + fun `onPrepareVpn - private Dns configured - return empty dns list`() = runTest { whenever(wgTunnel.createAndSetWgConfig()).thenReturn(wgConfig.success()) privateDnsProvider.mutablePrivateDns.add(InetAddress.getByName("1.1.1.1")) @@ -153,7 +153,7 @@ class WgVpnNetworkStackTest { } @Test - fun whenOnStartVpnAndEnabledTimeHasBeenResetThenSetEnabledTimeInMillis() = runTest { + fun `onStartVpn - enabled time reset - set enabled time in milliseconds`() = runTest { whenever(wgTunnel.createAndSetWgConfig()).thenReturn(wgConfig.success()) whenever(currentTimeProvider.getTimeInMillis()).thenReturn(1672229650358L) @@ -171,7 +171,7 @@ class WgVpnNetworkStackTest { } @Test - fun whenOnStartVpnAndEnabledTimeHasBeenSetThenDoNotUpdateEnabledTime() = runTest { + fun `onStartVpn - enabled time set - do not update enabled time`() = runTest { whenever(wgTunnel.createAndSetWgConfig()).thenReturn(Result.success(wgConfig)) whenever(currentTimeProvider.getTimeInMillis()).thenReturn(1672229650358L) @@ -197,7 +197,7 @@ class WgVpnNetworkStackTest { } @Test - fun whenNoWgTunnelDataThenOnStartVpnReturnsFailure() = runTest { + fun `onStartVpn - no wg tunnel data - returns failure`() = runTest { val result = wgVpnNetworkStack.onStartVpn(mock()) assertTrue(result.isFailure) @@ -208,7 +208,7 @@ class WgVpnNetworkStackTest { } @Test - fun whenOnStopVpnWithSelfStopThenResetEnabledTimeInMillisAndServerDetails() = runTest { + fun `onStopVpn - self stop - reset enabled time and server details`() = runTest { assertEquals( Result.success(Unit), wgVpnNetworkStack.onStopVpn(SELF_STOP()), @@ -220,7 +220,7 @@ class WgVpnNetworkStackTest { } @Test - fun whenOnStopVpnWithRestartThenResetEnabledTimeInMillisAndServerDetails() = runTest { + fun `onStopVpn - restart - reset enabled time and server details`() = runTest { assertEquals( Result.success(Unit), wgVpnNetworkStack.onStopVpn(RESTART), @@ -229,7 +229,7 @@ class WgVpnNetworkStackTest { } @Test - fun whenWgTunnelDataProviderThrowsExceptionThenOnPrepareShouldReturnFailure() = runTest { + fun `onPrepare - wgTunnel data provider throws exception - on prepare should return failure`() = runTest { whenever(wgTunnel.createAndSetWgConfig()).thenReturn(Result.failure(NullPointerException("null"))) assertTrue(wgVpnNetworkStack.onPrepareVpn().isFailure) @@ -240,7 +240,7 @@ class WgVpnNetworkStackTest { } @Test - fun whenWgProtocolStartWgReturnsFailureThenOnStartVpnShouldReturnFailure() = runTest { + fun `onStartVpn - wg protocol start wg returns failure - on start vpn should return failure`() = runTest { whenever(wgProtocol.startWg(any(), any(), eq(null))).thenReturn(Result.failure(java.lang.IllegalStateException())) whenever(wgTunnel.createAndSetWgConfig()).thenReturn(wgConfig.success()) @@ -254,7 +254,7 @@ class WgVpnNetworkStackTest { } @Test - fun whenWgProtocolStartWgReturnsSuccessThenOnStartVpnShouldReturnSuccess() = runTest { + fun `onStartVpn - wg protocol start successful - on start vpn success`() = runTest { whenever(wgProtocol.startWg(any(), any(), eq(null))).thenReturn(Result.success(Unit)) whenever(wgTunnel.createAndSetWgConfig()).thenReturn(wgConfig.success()) diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/cohort/NetPCohortUpdaterTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/cohort/NetPCohortUpdaterTest.kt index 10cd1b673a3f..d6fb7471e792 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/cohort/NetPCohortUpdaterTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/cohort/NetPCohortUpdaterTest.kt @@ -53,7 +53,7 @@ class NetPCohortUpdaterTest { } @Test - fun whenNetPIsNotRegisteredThenDoNothingWithCohort() = runTest { + fun `onVpnStarted - net pi not registered - do nothing with cohort`() = runTest { whenever(networkProtectionState.isEnabled()).thenReturn(false) testee.onVpnStarted(coroutineRule.testScope) @@ -63,7 +63,7 @@ class NetPCohortUpdaterTest { } @Test - fun whenNetPIsRegisteredAndCohortNotSetThenUpdateCohort() = runTest { + fun `onVpnStarted - cohort not set - update cohort`() = runTest { whenever(networkProtectionState.isEnabled()).thenReturn(true) whenever(cohortStore.cohortLocalDate).thenReturn(null) @@ -74,7 +74,7 @@ class NetPCohortUpdaterTest { } @Test - fun whenNetPIsRegisteredAndCohortSetThenDoNothingWithCohort() = runTest { + fun `onVpnStarted - cohort set - do nothing with cohort`() = runTest { whenever(networkProtectionState.isEnabled()).thenReturn(true) whenever(cohortStore.cohortLocalDate).thenReturn(LocalDate.of(2023, 1, 1)) @@ -86,7 +86,7 @@ class NetPCohortUpdaterTest { } @Test - fun whenNetPIsEnabledOnReconfigureAndCohortNotYetSetThenUpdateCohort() = runTest { + fun `onVpnReconfigured - cohort not yet set - update cohort`() = runTest { whenever(networkProtectionState.isEnabled()).thenReturn(false) whenever(cohortStore.cohortLocalDate).thenReturn(null) testee.onVpnStarted(coroutineRule.testScope) @@ -100,7 +100,7 @@ class NetPCohortUpdaterTest { } @Test - fun whenNetPIsEnabledOnReconfigureAndCohortSetThenDoNothingWithCohort() = runTest { + fun `onVpnReconfigured - cohort set - do nothing with cohort`() = runTest { whenever(networkProtectionState.isEnabled()).thenReturn(true) whenever(cohortStore.cohortLocalDate).thenReturn(LocalDate.of(2023, 1, 1)) diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/cohort/NetpCohortPixelInterceptorTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/cohort/NetpCohortPixelInterceptorTest.kt index f07c563126bd..ec5b9c2184e3 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/cohort/NetpCohortPixelInterceptorTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/cohort/NetpCohortPixelInterceptorTest.kt @@ -39,7 +39,7 @@ class NetpCohortPixelInterceptorTest { } @Test - fun whenCohortLocalDateIsNotSetThenDropNetpPixelUrl() { + fun `intercept - cohort local date not set - dropped netp pixel`() { whenever(netpCohortStore.cohortLocalDate).thenReturn(null) val pixelUrl = String.format(PIXEL_TEMPLATE, "m_netp_ev_enabled_d") @@ -50,7 +50,7 @@ class NetpCohortPixelInterceptorTest { } @Test - fun whenCohortLocalDateIsSetThenFireNetpEvPixelUrl() { + fun `intercept - cohort local date set - fire netp ev pixel url`() { whenever(netpCohortStore.cohortLocalDate).thenReturn(LocalDate.of(2023, 1, 1)) val pixelUrl = String.format(PIXEL_TEMPLATE, "m_netp_ev_enabled_d") @@ -62,7 +62,7 @@ class NetpCohortPixelInterceptorTest { } @Test - fun whenCohortLocalDateIsSetThenFireNetpImpPixelUrl() { + fun `intercept - cohort local date set - fire netp imp pixel url`() { whenever(netpCohortStore.cohortLocalDate).thenReturn(LocalDate.of(2023, 1, 1)) val pixelUrl = String.format(PIXEL_TEMPLATE, "m_netp_imp_dialog_d") @@ -74,7 +74,7 @@ class NetpCohortPixelInterceptorTest { } @Test - fun whenCohortLocalDateIsNotSetButPixelUrlIsNotNetpThenFireNonNetpPixelUrl() { + fun `intercept - cohort local date not set but pixel url is not netp - fire non netp pixel url`() { whenever(netpCohortStore.cohortLocalDate).thenReturn(null) val pixelUrl = String.format(PIXEL_TEMPLATE, "m_atp_ev_enabled_d") @@ -86,7 +86,7 @@ class NetpCohortPixelInterceptorTest { } @Test - fun whenCohortLocalDateIsNotSetThenSendExemptedBackendApiErrorNetpPixelUrl() { + fun `intercept - cohort local date not set - send exempted backend api error netp pixel url`() { whenever(netpCohortStore.cohortLocalDate).thenReturn(null) val pixelUrl = String.format(PIXEL_TEMPLATE, "m_netp_ev_backend_api_error_device_registration_failed_c") @@ -98,7 +98,7 @@ class NetpCohortPixelInterceptorTest { } @Test - fun whenCohortLocalDateIsNotSetThenSendExemptedWgErrorNetpPixelUrl() { + fun `intercept - cohort local date not set - send exempted wg error netp pixel url`() { whenever(netpCohortStore.cohortLocalDate).thenReturn(null) val pixelUrl = String.format(PIXEL_TEMPLATE, "m_netp_ev_wireguard_error_unable_to_load_wireguard_library_d") @@ -110,7 +110,7 @@ class NetpCohortPixelInterceptorTest { } @Test - fun whenCohortLocalDateIsNotSetThenSendExemptedVpnConflictPixelUrl() { + fun `intercept - cohort local date not set - send exempted vpn conflict pixel url`() { whenever(netpCohortStore.cohortLocalDate).thenReturn(null) val pixelUrl = String.format(PIXEL_TEMPLATE, "m_netp_imp_vpn_conflict_dialog_c") @@ -122,7 +122,7 @@ class NetpCohortPixelInterceptorTest { } @Test - fun whenCohortLocalDateIsNotSetThenSendExemptedAlwaysOnConflictPixelUrl() { + fun `intercept - cohort local date not set - send exempted always on conflict pixel url`() { whenever(netpCohortStore.cohortLocalDate).thenReturn(null) val pixelUrl = String.format(PIXEL_TEMPLATE, "m_netp_imp_always_on_conflict_dialog_d") @@ -134,7 +134,7 @@ class NetpCohortPixelInterceptorTest { } @Test - fun whenCohortLocalDateIsNotSetThenSendExemptedInfoVpnPixelUrl() { + fun `intercept - cohort local date not set - send exempted info vpn pixel url`() { whenever(netpCohortStore.cohortLocalDate).thenReturn(null) val pixelUrl = String.format(PIXEL_TEMPLATE, "m_netp_imp_info_vpn_c") @@ -146,7 +146,7 @@ class NetpCohortPixelInterceptorTest { } @Test - fun whenCohortLocalDateIsNotSetThenSendExemptedFaqsPixelUrl() { + fun `intercept - cohort local date not set - send exempted faqs pixel url`() { whenever(netpCohortStore.cohortLocalDate).thenReturn(null) val pixelUrl = String.format(PIXEL_TEMPLATE, "m_netp_imp_faqs_d") diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/configuration/NetpControllerRequestInterceptorTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/configuration/NetpControllerRequestInterceptorTest.kt index de469939af3b..a204f0814cfb 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/configuration/NetpControllerRequestInterceptorTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/configuration/NetpControllerRequestInterceptorTest.kt @@ -38,7 +38,7 @@ class NetpControllerRequestInterceptorTest { } @Test - fun whenInterceptNotNetPUrlThenDoNothing() { + fun `intercept - not net p url - do nothing`() { val chain = FakeChain("https://this.is.not.the.url/servers") val headers = interceptor.intercept(chain).headers @@ -47,7 +47,7 @@ class NetpControllerRequestInterceptorTest { } @Test - fun whenInterceptServersCallThenAddAuthHeader() { + fun `interceptServersCall - add auth header`() { val chain = FakeChain("https://staging.netp.duckduckgo.com/servers") val headers = interceptor.intercept(chain).headers @@ -58,7 +58,7 @@ class NetpControllerRequestInterceptorTest { } @Test - fun whenInterceptRegisterCallThenAddAuthHeader() { + fun `interceptRegisterCall - add auth header`() { val chain = FakeChain("https://staging.netp.duckduckgo.com/register") val headers = interceptor.intercept(chain).headers @@ -69,7 +69,7 @@ class NetpControllerRequestInterceptorTest { } @Test - fun whenInterceptServersCallInternalBuildThenAddAuthAndDebugHeaders() { + fun `interceptServersCallInternalBuild - add auth and debug headers`() { whenever(appBuildConfig.flavor).thenReturn(BuildFlavor.INTERNAL) val chain = FakeChain("https://staging.netp.duckduckgo.com/servers") @@ -82,7 +82,7 @@ class NetpControllerRequestInterceptorTest { } @Test - fun whenInterceptRegisterCallInternalBuildThenAddAuthAndDebugHeaders() { + fun `interceptRegisterCallInternalBuild - add auth and debug headers`() { whenever(appBuildConfig.flavor).thenReturn(BuildFlavor.INTERNAL) val chain = FakeChain("https://staging.netp.duckduckgo.com/register") @@ -95,7 +95,7 @@ class NetpControllerRequestInterceptorTest { } @Test - fun whenInterceptServersCallPlayBuildThenAddAuthHeader() { + fun `interceptServersCallPlayBuild - add auth header`() { whenever(appBuildConfig.flavor).thenReturn(BuildFlavor.PLAY) val chain = FakeChain("https://staging.netp.duckduckgo.com/servers") @@ -108,7 +108,7 @@ class NetpControllerRequestInterceptorTest { } @Test - fun whenInterceptRegisterCallPlayBuildThenAddAuthHeader() { + fun `interceptRegisterCallPlayBuild - add auth header`() { whenever(appBuildConfig.flavor).thenReturn(BuildFlavor.PLAY) val chain = FakeChain("https://staging.netp.duckduckgo.com/register") @@ -124,7 +124,7 @@ class NetpControllerRequestInterceptorTest { // Here starts the tests for the subscriptions // ---------------------------------------------------------------------------------------------------------------------------------- @Test - fun whenUrlIsServersAndFlavorIsPlayThenOnlyAddTokenToHeader() = runTest { + fun `intercept - url is servers and flavor is play - only add token to header`() = runTest { val fakeChain = FakeChain(url = "https://controller.netp.duckduckgo.com/servers") whenever(appBuildConfig.flavor).thenReturn(PLAY) whenever(subscriptions.getAccessToken()).thenReturn("token123") @@ -136,7 +136,7 @@ class NetpControllerRequestInterceptorTest { } @Test - fun whenUrlIsLocationsAndFlavorIsPlayThenOnlyAddTokenToHeader() = runTest { + fun `intercept - url is locations and flavor is play - only add token to header`() = runTest { val fakeChain = FakeChain(url = "https://controller.netp.duckduckgo.com/locations") whenever(appBuildConfig.flavor).thenReturn(PLAY) whenever(subscriptions.getAccessToken()).thenReturn("token123") @@ -148,7 +148,7 @@ class NetpControllerRequestInterceptorTest { } @Test - fun whenUrlIsRegisterAndFlavorIsPlayThenOnlyAddTokenToHeader() = runTest { + fun `intercept - url is register and flavor is play - only add token to header`() = runTest { val fakeChain = FakeChain(url = "https://staging1.netp.duckduckgo.com/register") whenever(appBuildConfig.flavor).thenReturn(PLAY) whenever(subscriptions.getAccessToken()).thenReturn("token123") @@ -160,7 +160,7 @@ class NetpControllerRequestInterceptorTest { } @Test - fun whenUrlIsNotNetPAndFlavorIsInternalThenDoNothingWithHeaders() = runTest { + fun `intercept - url not net p and flavor internal - do nothing with headers`() = runTest { val fakeChain = FakeChain(url = "https://improving.duckduckgo.com/t/m_netp_ev_enabled_android_phone?atb=v336-7&appVersion=5.131.0&test=1") interceptor.intercept(fakeChain).run { @@ -170,7 +170,7 @@ class NetpControllerRequestInterceptorTest { } @Test - fun whenUrlIsNetPAndFlavorIsInternalThenAddTokenAndDebugCodeToHeader() = runTest { + fun `intercept - url is net p and flavor is internal - add token and debug code to header`() = runTest { val fakeChain = FakeChain(url = "https://controller.netp.duckduckgo.com/servers") whenever(appBuildConfig.flavor).thenReturn(INTERNAL) whenever(subscriptions.getAccessToken()).thenReturn("token123") diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/configuration/RealWgServerApiTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/configuration/RealWgServerApiTest.kt index 1a05cf8bb8d1..5c3e05427db5 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/configuration/RealWgServerApiTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/configuration/RealWgServerApiTest.kt @@ -66,7 +66,7 @@ class RealWgServerApiTest { } @Test - fun whenRegisterInProductionThenReturnTheFirstServer() = runTest { + fun `registerInProduction - return the first server`() = runTest { assertEquals( WgServerData( serverName = "egress.usw.1", @@ -81,7 +81,7 @@ class RealWgServerApiTest { } @Test - fun whenRegisterInInternalAndServerSelectedThenReturnSelectedServer() = runTest { + fun `registerInInternalAndServerSelected - return selected server`() = runTest { whenever(appBuildConfig.flavor).thenReturn(INTERNAL) internalWgServerDebugProvider.selectedServer = "egress.euw.2" @@ -99,7 +99,7 @@ class RealWgServerApiTest { } @Test - fun whenRegisterInInternalAndServerSelectedWithNoServerCountryThenReturnSelectedServerWithNullLocation() = runTest { + fun `registerPublicKey - server selected with no country - return selected server with null location`() = runTest { whenever(appBuildConfig.flavor).thenReturn(INTERNAL) internalWgServerDebugProvider.selectedServer = "egress.euw" @@ -117,7 +117,7 @@ class RealWgServerApiTest { } @Test - fun whenRegisterInInternalAndWrongServerSelectedThenReturnFirstServer() = runTest { + fun `registerPublicKey - wrong server selected - returns first server`() = runTest { internalWgServerDebugProvider.selectedServer = "egress.wrong" assertEquals( @@ -134,14 +134,14 @@ class RealWgServerApiTest { } @Test - fun whenRegisterInProductionThenDoNotCacheServers() = runTest { + fun `registerInProduction - do not cache servers`() = runTest { productionApi.registerPublicKey("testpublickey") assertTrue(internalWgServerDebugProvider.cachedServers.isEmpty()) } @Test - fun whenInternalFlavorGetWgServerDataThenStoreReturnedServers() = runTest { + fun `getWgServerData - store returned servers`() = runTest { whenever(appBuildConfig.flavor).thenReturn(INTERNAL) internalApi.registerPublicKey("testpublickey") @@ -149,21 +149,21 @@ class RealWgServerApiTest { } @Test - fun whenRegisterInProductionThenDownloadGeoswitchingData() = runTest { + fun `registerInProduction - download geoswitching data`() = runTest { productionApi.registerPublicKey("testpublickey") verify(netpEgressServersProvider).updateServerLocationsAndReturnPreferred() } @Test - fun whenRegisterInInternalThenDownloadGeoswitchingData() = runTest { + fun `registerInInternal - download geoswitching data`() = runTest { internalApi.registerPublicKey("testpublickey") verify(netpEgressServersProvider).updateServerLocationsAndReturnPreferred() } @Test - fun whenUserPreferredCountrySetThenRegisterPublicKeyShouldRequestForCountry() = runTest { + fun `registerPublicKey - user preferred country set - requests for country`() = runTest { whenever(netpEgressServersProvider.updateServerLocationsAndReturnPreferred()).thenReturn(PreferredLocation("nl")) assertEquals( @@ -180,7 +180,7 @@ class RealWgServerApiTest { } @Test - fun whenUserPreferredLocationSetThenRegisterPublicKeyShouldRequestForCountryAndCity() = runTest { + fun `registerPublicKey - preferred location set - requests country and city`() = runTest { whenever(netpEgressServersProvider.updateServerLocationsAndReturnPreferred()).thenReturn( PreferredLocation(countryCode = "us", cityName = "Des Moines"), ) @@ -199,7 +199,7 @@ class RealWgServerApiTest { } @Test - fun whenUserPreferredLocationSetAndInternalDebugServerSelectedThenRegisterPublicKeyShouldReturnDebugServer() = runTest { + fun `registerPublicKey - user preferred location set and internal debug server selected - returns debug server`() = runTest { whenever(appBuildConfig.flavor).thenReturn(INTERNAL) internalWgServerDebugProvider.selectedServer = "egress.euw.2" whenever(netpEgressServersProvider.updateServerLocationsAndReturnPreferred()).thenReturn( diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/configuration/WgTunnelTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/configuration/WgTunnelTest.kt index 1356e2d4d210..1ed10ac9c203 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/configuration/WgTunnelTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/configuration/WgTunnelTest.kt @@ -65,7 +65,7 @@ class WgTunnelTest { } @Test - fun establishThenReturnWgTunnelData() = runTest { + fun `establish - create wg tunnel data - matches expected config`() = runTest { val actual = wgTunnel.createWgConfig(keys).getOrThrow() val expected = Config.parse(BufferedReader(StringReader(wgQuickConfig))) @@ -73,21 +73,21 @@ class WgTunnelTest { } @Test - fun establishErrorThenLogError() = runTest { + fun `establishError - log error`() = runTest { whenever(wgServerApi.registerPublicKey(any(), isNull())).thenReturn(serverData) assertNull(wgTunnel.createWgConfig(keys).getOrNull()) } @Test - fun withNoKeysEstablishErrorThenLogError() = runTest { + fun `withNoKeys - establish error then log error`() = runTest { whenever(wgServerApi.registerPublicKey(any(), isNull())).thenReturn(serverData) assertNull(wgTunnel.createWgConfig().getOrNull()) } @Test - fun whenTunnelIsMarkedAsUnhealthyAndCreateWgConfigThenUpdateStateToFailureRecovery() = runTest { + fun `markTunnelAsUnhealthy - create wg config - update state to failure recovery`() = runTest { whenever(wgServerApi.registerPublicKey(any(), eq(FailureRecovery(currentServer = "name")))).thenReturn(serverData) wgTunnelStore.wireguardConfig = Config.parse(BufferedReader(StringReader(wgQuickConfig))) @@ -98,7 +98,7 @@ class WgTunnelTest { } @Test - fun whenTunnelIsMarkAsUnhealthyAndCreateAndSetWgConfigThenResetTunnelHealth() = runTest { + fun `markTunnelAsUnhealthy - create and set wg config - reset tunnel health`() = runTest { whenever(wgServerApi.registerPublicKey(any(), isNull())).thenReturn(serverData) wgTunnel.markTunnelUnhealthy() @@ -108,7 +108,7 @@ class WgTunnelTest { } @Test - fun whenTunnelIsMarkedAsUnhealthyTheHealthyAndCreateWgConfigThenResetTunnelHealth() = runTest { + fun `markTunnelAsUnhealthy - mark tunnel healthy and create wg config then reset tunnel health`() = runTest { whenever(wgServerApi.registerPublicKey(any(), isNull())).thenReturn(serverData) wgTunnel.markTunnelUnhealthy() diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/connectionclass/ConnectionClassManagerTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/connectionclass/ConnectionClassManagerTest.kt index c14ca2408bd5..8a44edd9e714 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/connectionclass/ConnectionClassManagerTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/connectionclass/ConnectionClassManagerTest.kt @@ -28,14 +28,14 @@ class ConnectionClassManagerTest { } @Test - fun addLatencyThenGetLatency() = runTest { + fun `addLatency - get latency`() = runTest { connectionClassManager.addLatency(100.0) assertEquals(100.0, connectionClassManager.getLatencyAverage(), 0.1) } @Test - fun addLatencyThenGetConnectionQuality() = runTest { + fun `addLatency - get connection quality`() = runTest { connectionClassManager.addLatency(0.0) assertEquals(ConnectionQuality.UNKNOWN, connectionClassManager.getConnectionQuality()) connectionClassManager.reset() @@ -78,7 +78,7 @@ class ConnectionClassManagerTest { } @Test - fun addLatencyThenCalculateRunningAverage() = runTest { + fun `addLatency - calculate running average`() = runTest { val expected = ExponentialGeometricAverage() for (i in 0..2000 step 1) { diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/connectionclass/ConnectionQualityStoreTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/connectionclass/ConnectionQualityStoreTest.kt index 7f03e8588728..5df27ed13201 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/connectionclass/ConnectionQualityStoreTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/connectionclass/ConnectionQualityStoreTest.kt @@ -20,7 +20,7 @@ class ConnectionQualityStoreTest { } @Test - fun saveConnectionLatency() = runTest { + fun `saveConnectionLatency - state - latency saved`() = runTest { connectionQualityStore.saveConnectionLatency(100) assertEquals(100, connectionQualityStore.getConnectionLatency()) diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/exclusion/RealNetworkProtectionExclusionListTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/exclusion/RealNetworkProtectionExclusionListTest.kt index 1f2db54eab8f..7903bc20b06b 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/exclusion/RealNetworkProtectionExclusionListTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/exclusion/RealNetworkProtectionExclusionListTest.kt @@ -45,7 +45,7 @@ class RealNetworkProtectionExclusionListTest { } @Test - fun whenNetpIsEnabledAndAppIsInExcludedPackagesThenReturnIsExcludedTrue() = runTest { + fun `isExcluded - netp enabled and app in excluded packages - return is excluded true`() = runTest { whenever(netPExclusionListRepository.getExcludedAppPackages()).thenReturn(listOf("com.test.app")) whenever(vpnFeaturesRegistry.isFeatureRegistered(NetPVpnFeature.NETP_VPN)).thenReturn(true) @@ -53,7 +53,7 @@ class RealNetworkProtectionExclusionListTest { } @Test - fun whenNetpIsDisabledAndAppIsInExcludedPackagesThenReturnIsExcludedFalse() = runTest { + fun `isExcluded - netp disabled and app in excluded packages - return is excluded false`() = runTest { whenever(netPExclusionListRepository.getExcludedAppPackages()).thenReturn(listOf("com.test.app")) whenever(vpnFeaturesRegistry.isFeatureRegistered(NetPVpnFeature.NETP_VPN)).thenReturn(false) @@ -61,7 +61,7 @@ class RealNetworkProtectionExclusionListTest { } @Test - fun whenNetpIsEnabledAndAppIsNotInExcludedPackagesThenReturnIsExcludedFalse() = runTest { + fun `isExcluded - netp enabled and app not in excluded packages - is excluded false`() = runTest { whenever(netPExclusionListRepository.getExcludedAppPackages()).thenReturn(emptyList()) whenever(vpnFeaturesRegistry.isFeatureRegistered(NetPVpnFeature.NETP_VPN)).thenReturn(true) @@ -69,7 +69,7 @@ class RealNetworkProtectionExclusionListTest { } @Test - fun whenNetpIsNotEnabledAndAppIsNotInExcludedPackagesThenReturnIsExcludedFalse() = runTest { + fun `isExcluded - netp not enabled and app not in excluded packages - return is excluded false`() = runTest { whenever(netPExclusionListRepository.getExcludedAppPackages()).thenReturn(emptyList()) whenever(vpnFeaturesRegistry.isFeatureRegistered(NetPVpnFeature.NETP_VPN)).thenReturn(false) diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/exclusion/ui/NetpAppExclusionListViewModelTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/exclusion/ui/NetpAppExclusionListViewModelTest.kt index 9a976d76a924..61b2f35a357e 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/exclusion/ui/NetpAppExclusionListViewModelTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/exclusion/ui/NetpAppExclusionListViewModelTest.kt @@ -110,7 +110,7 @@ class NetpAppExclusionListViewModelTest { } @Test - fun whenFilterIsAllAndGetAppsThenReturnCorrectViewState() = runTest { + fun `getApps - filter is all - correct view state`() = runTest { whenever(systemAppsExclusionRepository.getAvailableCategories()).thenReturn(emptySet()) testee.getApps().test { assertEquals( @@ -134,7 +134,7 @@ class NetpAppExclusionListViewModelTest { } @Test - fun whenFilterIsProtectedOnlyAndGetAppsThenReturnCorrectViewState() = runTest { + fun `getApps - filter protected only - correct view state`() = runTest { whenever(systemAppsExclusionRepository.getAvailableCategories()).thenReturn(emptySet()) testee.applyAppsFilter(AppsFilter.PROTECTED_ONLY) @@ -156,7 +156,7 @@ class NetpAppExclusionListViewModelTest { } @Test - fun whenFilterIsUnprotectedOnlyAndGetAppsThenReturnCorrectViewState() = runTest { + fun `applyAppsFilter - get apps - correct view state`() = runTest { whenever(systemAppsExclusionRepository.getAvailableCategories()).thenReturn(emptySet()) testee.applyAppsFilter(AppsFilter.UNPROTECTED_ONLY) @@ -177,7 +177,7 @@ class NetpAppExclusionListViewModelTest { } @Test - fun whenGetAppsAndSystemAppIsInOverrideThenReturnCorrectViewState() = runTest { + fun `getApps - system app override - correct view state`() = runTest { whenever(systemAppsExclusionRepository.getAvailableCategories()).thenReturn(emptySet()) whenever(systemAppOverridesProvider.getSystemAppOverridesList()).thenReturn(listOf("com.example.system")) @@ -202,7 +202,7 @@ class NetpAppExclusionListViewModelTest { } @Test - fun whenSystemAppCategoriesAvailableThenReturnCorrectViewState() = runTest { + fun `getApps - system app categories available - correct view state`() = runTest { whenever(systemAppOverridesProvider.getSystemAppOverridesList()).thenReturn(listOf("com.example.system")) whenever(systemAppsExclusionRepository.getAvailableCategories()).thenReturn( setOf( @@ -241,7 +241,7 @@ class NetpAppExclusionListViewModelTest { } @Test - fun whenOnAppProtectionChangedToProtectedThenManuallyEnableApp() { + fun `onAppProtectionChanged - manually enable app`() { testee.onAppProtectionChanged( NetpExclusionListApp("com.example.app2", "App Name", false), true, @@ -250,7 +250,7 @@ class NetpAppExclusionListViewModelTest { } @Test - fun whenOnAppProtectionChangedToUnProtectedThenShowDisabledDialog() = runTest { + fun `onAppProtectionChanged - show disabled dialog`() = runTest { val app = NetpExclusionListApp("com.example.app1", "App Name", true) testee.onAppProtectionChanged(app, false) @@ -264,7 +264,7 @@ class NetpAppExclusionListViewModelTest { } @Test - fun whenOnAppProtectionDisabledWithNoReportThenOnlyManuallyExcludeApp() = runTest { + fun `onAppProtectionDisabled - no report - manually exclude app`() = runTest { testee.onAppProtectionDisabled("App Name", "com.example.app1", false) verify(netPExclusionListRepository).manuallyExcludeApp("com.example.app1") @@ -273,7 +273,7 @@ class NetpAppExclusionListViewModelTest { } @Test - fun whenOnAppProtectionDisabledAndReportThenManuallyExcludeAndShowIssueReporting() = runTest { + fun `onAppProtectionDisabled - report - manually exclude and show issue reporting`() = runTest { testee.onAppProtectionDisabled("App Name", "com.example.app1", true) verify(netPExclusionListRepository).manuallyExcludeApp("com.example.app1") @@ -296,7 +296,7 @@ class NetpAppExclusionListViewModelTest { } @Test - fun whenLaunchFeedbackThenShowIssueReporting() = runTest { + fun `launchFeedback - show issue reporting - shows issue reporting page`() = runTest { testee.launchFeedback() verify(networkProtectionPixels).reportExclusionListLaunchBreakageReport() @@ -317,7 +317,7 @@ class NetpAppExclusionListViewModelTest { } @Test - fun whenRestoreProtectedAppsTheResetRepositoryAndRestartVpn() = runTest { + fun `restoreProtectedApps - reset repository and restart VPN`() = runTest { testee.restoreProtectedApps() verify(netPExclusionListRepository).restoreDefaultProtectedList() @@ -330,7 +330,7 @@ class NetpAppExclusionListViewModelTest { } @Test - fun whenUserMadeChangesToExclusionListThenOnPauseRestartVpn() = runTest { + fun `whenUserMadeChangesToExclusionListThenOnPauseRestartVpn - on pause - restart vpn`() = runTest { testee.onResume(mock()) exclusionListFlow.emit( listOf( @@ -349,7 +349,7 @@ class NetpAppExclusionListViewModelTest { } @Test - fun whenUserMadeNoChangesToExclusionListThenOnPauseDoNothing() = runTest { + fun `onResume - on pause do nothing - no events expected`() = runTest { testee.onResume(mock()) testee.onPause(mock()) @@ -359,7 +359,7 @@ class NetpAppExclusionListViewModelTest { } @Test - fun whenExclusionListResetToOriginalThenOnPauseDoNothing() = runTest { + fun `onPause - reset to original - do nothing`() = runTest { testee.onResume(mock()) exclusionListFlow.emit( listOf( @@ -378,7 +378,7 @@ class NetpAppExclusionListViewModelTest { } @Test - fun whenWarningNotYetShownOnSystemAppCategoryStateChangedThenShowWarning() = runTest { + fun `onSystemAppCategoryStateChanged - warning not yet shown - show warning`() = runTest { whenever(systemAppsExclusionRepository.hasShownWarning()).thenReturn(false) val category = NetpExclusionListSystemAppCategory( @@ -401,7 +401,7 @@ class NetpAppExclusionListViewModelTest { } @Test - fun whenWarningShownAndCategorySetToDisabledOnSystemAppCategoryStateChangedThenExcludeCategory() = runTest { + fun `whenWarningShownAndCategorySetToDisabledOnSystemAppCategoryStateChanged - exclude category`() = runTest { whenever(systemAppsExclusionRepository.hasShownWarning()).thenReturn(true) val category = NetpExclusionListSystemAppCategory( @@ -422,7 +422,7 @@ class NetpAppExclusionListViewModelTest { } @Test - fun whenWarningShownAndCategorySetToEnabledOnSystemAppCategoryStateChangedThenIncludeCategory() = runTest { + fun `whenWarningShownAndCategorySetToEnabledOnSystemAppCategoryStateChanged - include category`() = runTest { whenever(systemAppsExclusionRepository.hasShownWarning()).thenReturn(true) val category = NetpExclusionListSystemAppCategory( diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/failure/FailureRecoveryHandlerTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/failure/FailureRecoveryHandlerTest.kt index cd2b501c089b..9f1d69db0cb2 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/failure/FailureRecoveryHandlerTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/failure/FailureRecoveryHandlerTest.kt @@ -95,7 +95,7 @@ class FailureRecoveryHandlerTest { } @Test - fun whenDiffFromHandshakeIsBelowThresholdThenDoNothing() = runTest { + fun `onTunnelFailure - diff from handshake below threshold - do nothing`() = runTest { whenever(currentTimeProvider.getTimeInEpochSeconds()).thenReturn(300) failureRecoveryHandler.onTunnelFailure(180) @@ -107,7 +107,7 @@ class FailureRecoveryHandlerTest { } @Test - fun whenOnTunnelFailureRecoveredThenMarkTunnelHealthy() = runTest { + fun `onTunnelFailureRecovered - mark tunnel healthy`() = runTest { failureRecoveryHandler.onTunnelFailureRecovered() verify(wgTunnel).markTunnelHealthy() @@ -115,7 +115,7 @@ class FailureRecoveryHandlerTest { } @Test - fun whenFailureRecoveryAndServerChangedThenSetConfigAndRefreshNetp() = runTest { + fun `onTunnelFailure - set config and refresh netp - different server`() = runTest { val newConfig = getWgConfig(updatedServerDataDifferentServer) whenever(currentTimeProvider.getTimeInEpochSeconds()).thenReturn(1080) whenever(vpnFeaturesRegistry.isFeatureRegistered(NetPVpnFeature.NETP_VPN)).thenReturn(true) @@ -134,7 +134,7 @@ class FailureRecoveryHandlerTest { } @Test - fun whenFailureRecoveryAndTunnelAddressChangedThenSetConfigAndRefreshNetp() = runTest { + fun `onTunnelFailure - set config and refresh netp - different tunnel address`() = runTest { val newConfig = getWgConfig(updatedServerDataDifferentAddress) whenever(currentTimeProvider.getTimeInEpochSeconds()).thenReturn(1080) whenever(vpnFeaturesRegistry.isFeatureRegistered(NetPVpnFeature.NETP_VPN)).thenReturn(true) @@ -153,7 +153,7 @@ class FailureRecoveryHandlerTest { } @Test - fun whenFailureRecoveryAndServerDidnotChangedThenDoNothing() = runTest { + fun `onTunnelFailure - server did not change - do nothing`() = runTest { whenever(currentTimeProvider.getTimeInEpochSeconds()).thenReturn(1080) whenever(vpnFeaturesRegistry.isFeatureRegistered(NetPVpnFeature.NETP_VPN)).thenReturn(true) whenever(wgTunnelConfig.getWgConfig()).thenReturn(getWgConfig(defaultServerData)) @@ -170,7 +170,7 @@ class FailureRecoveryHandlerTest { } @Test - fun whenFailureRecoveryAndCreateConfigFailedThenAttemptMax5TimesOnly() = runTest { + fun `onTunnelFailure - failure recovery and create config failed - attempt max 5 times only`() = runTest { whenever(currentTimeProvider.getTimeInEpochSeconds()).thenReturn(1080) whenever(vpnFeaturesRegistry.isFeatureRegistered(NetPVpnFeature.NETP_VPN)).thenReturn(true) whenever(wgTunnelConfig.getWgConfig()).thenReturn(getWgConfig(defaultServerData)) @@ -184,7 +184,7 @@ class FailureRecoveryHandlerTest { } @Test - fun whenOnTunnelFailureCalledTwiceThenAttemptRecoveryOnceOnly() = runTest { + fun `onTunnelFailure - called twice - attempt recovery once only`() = runTest { val newConfig = getWgConfig(updatedServerDataDifferentServer) whenever(currentTimeProvider.getTimeInEpochSeconds()).thenReturn(1080) whenever(vpnFeaturesRegistry.isFeatureRegistered(NetPVpnFeature.NETP_VPN)).thenReturn(true) @@ -204,7 +204,7 @@ class FailureRecoveryHandlerTest { } @Test - fun whenOnTunnelFailureCalledTwiceAndDifferentTunnelAddressThenAttemptRecoveryOnceOnly() = runTest { + fun `onTunnelFailure - different tunnel address - attempt recovery once only`() = runTest { val newConfig = getWgConfig(updatedServerDataDifferentAddress) whenever(currentTimeProvider.getTimeInEpochSeconds()).thenReturn(1080) whenever(vpnFeaturesRegistry.isFeatureRegistered(NetPVpnFeature.NETP_VPN)).thenReturn(true) @@ -224,7 +224,7 @@ class FailureRecoveryHandlerTest { } @Test - fun whenOnTunnelFailureCalledAfterRecoveryThenAttemptRecoveryTwice() = runTest { + fun `onTunnelFailure - after recovery - attempt recovery twice`() = runTest { val newConfig = getWgConfig(updatedServerDataDifferentServer) whenever(currentTimeProvider.getTimeInEpochSeconds()).thenReturn(1080) whenever(vpnFeaturesRegistry.isFeatureRegistered(NetPVpnFeature.NETP_VPN)).thenReturn(true) @@ -244,7 +244,7 @@ class FailureRecoveryHandlerTest { } @Test - fun whenOnTunnelFailureCalledAfterRecoveryAndDifferentTunnelAddrThenAttemptRecoveryTwice() = runTest { + fun `onTunnelFailure - after recovery and different tunnel addr - attempt recovery twice`() = runTest { val newConfig = getWgConfig(updatedServerDataDifferentAddress) whenever(currentTimeProvider.getTimeInEpochSeconds()).thenReturn(1080) whenever(vpnFeaturesRegistry.isFeatureRegistered(NetPVpnFeature.NETP_VPN)).thenReturn(true) diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/management/NetworkProtectionManagementViewModelTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/management/NetworkProtectionManagementViewModelTest.kt index 3e5283833949..531ed76aa39d 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/management/NetworkProtectionManagementViewModelTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/management/NetworkProtectionManagementViewModelTest.kt @@ -152,7 +152,7 @@ class NetworkProtectionManagementViewModelTest { } @Test - fun whenOnNetpToggleClickedToEnabledThenEmitCheckVPNPermissionCommand() = runTest { + fun `onNetpToggleClicked - on netp toggle clicked to enabled - emit check vpn permission command`() = runTest { whenever(externalVpnDetector.isExternalVpnDetected()).thenReturn(false) testee.commands().test { @@ -163,21 +163,21 @@ class NetworkProtectionManagementViewModelTest { } @Test - fun whenOnStartVpnThenRegisterFeature() = runTest { + fun `onStartVpn - register feature - network protection state started`() = runTest { testee.onStartVpn() verify(networkProtectionState).start() } @Test - fun whenOnNetpToggleClickedToDisabledThenUnregisterFeature() = runTest { + fun `onNetpToggleClicked - network protection state cleared - unregistered feature`() = runTest { testee.onNetpToggleClicked(false) verify(networkProtectionState).clearVPNConfigurationAndStop() } @Test - fun whenExternalVPNDetectedAndOnNetpToggleClickedTrueThenEmitShowVpnConflictDialog() = runTest { + fun `onNetpToggleClicked - external VPN detected - emit show VPN conflict dialog`() = runTest { whenever(externalVpnDetector.isExternalVpnDetected()).thenReturn(true) testee.commands().test { @@ -188,7 +188,7 @@ class NetworkProtectionManagementViewModelTest { } @Test - fun whenNoExternalVPNDetectedAndOnNetpToggleClickedTrueThenEmitCheckVPNPermission() = runTest { + fun `onNetpToggleClicked - no external VPN detected - emit check VPN permission`() = runTest { whenever(externalVpnDetector.isExternalVpnDetected()).thenReturn(false) testee.commands().test { @@ -198,7 +198,7 @@ class NetworkProtectionManagementViewModelTest { } @Test - fun wheOnVPNPermissionRejectedWithTimeToLastVPNRequestDiffLessThan500ThenEmitShowVpnAlwaysOnConflictDialog() = runTest { + fun `onVPNPermissionRejected - time to last VPN request diff less than 500 - emit show VPN always on conflict dialog`() = runTest { testee.commands().test { val intent = Intent() testee.onRequiredPermissionNotGranted(intent, 600) @@ -211,7 +211,7 @@ class NetworkProtectionManagementViewModelTest { } @Test - fun whenOnVPNPermissionRejectedWithTimeToLastVPNRequestDiffGreaterThan500ThenDoNotShowAlwaysOnConflictDialog() = runTest { + fun `onVPNPermissionRejected - time to last VPN request diff greater than 500 - do not show always on conflict dialog`() = runTest { testee.commands().test { val intent = Intent() testee.onRequiredPermissionNotGranted(intent, 600) @@ -223,7 +223,7 @@ class NetworkProtectionManagementViewModelTest { } @Test - fun whenOnRequiredPermissionNotGrantedThenEmitRequestVPNPermission() = runTest { + fun `onRequiredPermissionNotGranted - emit request VPN permission`() = runTest { testee.commands().test { val intent = Intent() testee.onRequiredPermissionNotGranted(intent, 1000) @@ -232,7 +232,7 @@ class NetworkProtectionManagementViewModelTest { } @Test - fun whenVpnStateIsEnablingThenViewStateEmitsConnecting() = runTest { + fun `onStartVpn - view state emits connecting`() = runTest { whenever(vpnStateMonitor.getStateFlow(NetPVpnFeature.NETP_VPN)).thenReturn( flowOf( VpnState( @@ -262,7 +262,7 @@ class NetworkProtectionManagementViewModelTest { } @Test - fun whenVpnStateIsDisabledThenViewStateEmitsDisconnected() = runTest { + fun `whenVpnStateIsDisabledThenViewStateEmitsDisconnected - view state emits disconnected`() = runTest { whenever(vpnStateMonitor.getStateFlow(NetPVpnFeature.NETP_VPN)).thenReturn( flowOf( VpnState( @@ -295,7 +295,7 @@ class NetworkProtectionManagementViewModelTest { } @Test - fun whenEnabledAndServerDetailsAvailableThenEmitViewStateConnectedWithDetails() = runTest { + fun `whenEnabledAndServerDetailsAvailableThenEmitViewStateConnectedWithDetails - view state connected with details`() = runTest { whenever(networkProtectionRepository.enabledTimeInMillis).thenReturn(-1) whenever(wgTunnelConfig.getWgConfig()).thenReturn(wgConfig) whenever(vpnStateMonitor.getStateFlow(NetPVpnFeature.NETP_VPN)).thenReturn( @@ -330,7 +330,7 @@ class NetworkProtectionManagementViewModelTest { } @Test - fun whenOnResumeThenReturnViewStateExcludeAppCount() = runTest { + fun `onResume - return view state exclude app count`() = runTest { whenever(vpnStateMonitor.getStateFlow(NetPVpnFeature.NETP_VPN)).thenReturn( flowOf( VpnState( @@ -362,74 +362,74 @@ class NetworkProtectionManagementViewModelTest { } @Test - fun whenTimeDifferenceIs0ThenShowStartingTimeString() { + fun `toDisplayableTimerText - time difference is 0 - show starting timer string`() { assertEquals("00:00:00", 0L.toDisplayableTimerText()) } @Test - fun whenTimeDifferenceHasHoursOnlyThenSetMinsAndSecondsToDefault() { + fun `whenTimeDifferenceHasHoursOnly - set minutes and seconds to default - timer text`() { assertEquals("27:00:00", 97_200_000L.toDisplayableTimerText()) } @Test - fun whenTimeDifferenceHasMinsOnlyThenSetHoursAndSecondsToDefault() { + fun `whenTimeDifferenceHasMinsOnly - set hours and seconds to default - 00·00·00`() { assertEquals("00:38:00", 2_280_000L.toDisplayableTimerText()) } @Test - fun whenTimeDifferenceHasSecondsOnlyThenSetHoursAndMinutesToDefault() { + fun `whenTimeDifferenceHasSecondsOnly - set hours and minutes to default - default timer text`() { assertEquals("00:00:32", 32_000L.toDisplayableTimerText()) } @Test - fun whenTimeDifferenceThenSetHoursAndMinutesToDefault() { + fun `whenTimeDifference - set hours and minutes to default`() { assertEquals("27:38:32", 99_512_000L.toDisplayableTimerText()) } @Test - fun whenOnStartVpnThenResetValuesInRepository() { + fun `onStartVpn - reset values in repository`() { testee.onStartVpn() verify(networkProtectionRepository).enabledTimeInMillis = -1L } @Test - fun whenVpnStateIsDisabledAndNullStopReasonThenNone() { + fun `getAlertState - vpn state disabled and null stop reason - none`() { assertEquals(None, testee.getAlertState(DISABLED, null, AlwaysOnState.DEFAULT)) } @Test - fun whenVpnStateIsDisabledAndUnknownStopReasonThenNone() { + fun `getAlertState - vpn state disabled and unknown stop reason - none`() { assertEquals(None, testee.getAlertState(DISABLED, UNKNOWN, AlwaysOnState.DEFAULT)) } @Test - fun whenVpnStateIsEnabledAndNullStopReasonThenNone() { + fun `getAlertState - vpn state enabled and null stop reason - none`() { assertEquals(None, testee.getAlertState(ENABLED, null, AlwaysOnState.DEFAULT)) } @Test - fun whenVpnStateIsEnablingAndNoneStopReasonThenNone() { + fun `getAlertState - vpn state enabling and none stop reason - none`() { assertEquals(None, testee.getAlertState(ENABLING, null, AlwaysOnState.DEFAULT)) } @Test - fun whenVpnStateIsEnabledAndAlwaysOnStateIsLockdownThenAlertStateIsShowAlwaysOnLockdownEnabled() { + fun `getAlertState - vpn state enabled and always on state lockdown - show always on lockdown enabled`() { assertEquals(ShowAlwaysOnLockdownEnabled, testee.getAlertState(ENABLED, null, AlwaysOnState.ALWAYS_ON_LOCKED_DOWN)) } @Test - fun whenNotReconnectingThenAlertStateIsNone() { + fun `getAlertState - not reconnecting - none`() { assertEquals(None, testee.getAlertState(DISABLED, UNKNOWN, AlwaysOnState.DEFAULT)) } @Test - fun whenStopReasonIsRevokedAndNotReconnectingThenAlertStateIsShowRevoked() { + fun `getAlertState - stop reason revoked and not reconnecting - show revoked`() { assertEquals(ShowRevoked, testee.getAlertState(DISABLED, REVOKED, AlwaysOnState.DEFAULT)) } @Test - fun whenOnAlwaysOnOpenSettingsClickedFromPromotionThenEmitOpenVPNSettingsCommandAndEmitPixels() = runTest { + fun `onOpenSettingsFromAlwaysOnPromotionClicked - emit openvpn settings command and report pixels`() = runTest { testee.commands().test { testee.onOpenSettingsFromAlwaysOnPromotionClicked() assertEquals(OpenVPNSettings, this.awaitItem()) @@ -438,7 +438,7 @@ class NetworkProtectionManagementViewModelTest { } @Test - fun whenOnAlwaysOnOpenSettingsClickedFromLockdownThenEmitOpenVPNSettingsCommandAndEmitPixels() = runTest { + fun `onOpenSettingsFromAlwaysOnLockdown - emit open VPN settings command and report pixels`() = runTest { testee.commands().test { testee.onOpenSettingsFromAlwaysOnLockdownClicked() assertEquals(OpenVPNSettings, this.awaitItem()) @@ -447,7 +447,7 @@ class NetworkProtectionManagementViewModelTest { } @Test - fun whenOnStartVpnWithAlwaysOnOFFAndVPNLastDisabledByAndroidThenEmitShowAlwaysOnPromotionDialogCommand() = runTest { + fun `onStartVpn - always on off and vpn last disabled by android - emit show always on promotion dialog command`() = runTest { whenever(vpnStateMonitor.isAlwaysOnEnabled()).thenReturn(false) whenever(vpnStateMonitor.vpnLastDisabledByAndroid()).thenReturn(true) @@ -459,7 +459,7 @@ class NetworkProtectionManagementViewModelTest { } @Test - fun whenOnStartVpnWithAlwaysOnEnabledThenDoNotEmitShowAlwaysOnPromotionDialogCommand() = runTest { + fun `onStartVpn - always on enabled - do not emit show always on promotion dialog command`() = runTest { whenever(vpnStateMonitor.isAlwaysOnEnabled()).thenReturn(true) whenever(vpnStateMonitor.vpnLastDisabledByAndroid()).thenReturn(true) @@ -470,7 +470,7 @@ class NetworkProtectionManagementViewModelTest { } @Test - fun whenOnStartVpnWithAlwaysOnOffButVPNNotKilledByAndroidThenDoNotEmitShowAlwaysOnPromotionDialogCommand() = runTest { + fun `onStartVpn - always on off but vpn not killed by android - do not emit show always on promotion dialog command`() = runTest { whenever(vpnStateMonitor.isAlwaysOnEnabled()).thenReturn(false) whenever(vpnStateMonitor.vpnLastDisabledByAndroid()).thenReturn(false) @@ -481,7 +481,7 @@ class NetworkProtectionManagementViewModelTest { } @Test - fun whenOnStartWithAlwaysOnLockdownThenDoNotEmitShowAlwaysOnLockdownDialogCommand() = runTest { + fun `onStart - always on lockdown - do not emit show always on lockdown dialog command`() = runTest { whenever(vpnStateMonitor.getStateFlow(NetPVpnFeature.NETP_VPN)).thenReturn( flowOf( VpnState( @@ -499,7 +499,7 @@ class NetworkProtectionManagementViewModelTest { } @Test - fun whenOnStartWithoutAlwaysOnLockdowmThenDoNotEmitShowAlwaysOnLockdownDialogCommand() = runTest { + fun `onStart - without always on lockdown - do not emit show always on lockdown dialog command`() = runTest { whenever(vpnStateMonitor.getStateFlow(NetPVpnFeature.NETP_VPN)).thenReturn( flowOf( VpnState( @@ -516,7 +516,7 @@ class NetworkProtectionManagementViewModelTest { } @Test - fun whenOnReportIssuesClickedThenEmitShowIssueReportingPageCommand() = runTest { + fun `onReportIssuesClicked - emit show issue reporting page command`() = runTest { testee.onReportIssuesClicked() testee.commands().test { diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/notification/NetPDisabledNotificationSchedulerTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/notification/NetPDisabledNotificationSchedulerTest.kt index c81ae09df420..30414ae63e8b 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/notification/NetPDisabledNotificationSchedulerTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/notification/NetPDisabledNotificationSchedulerTest.kt @@ -71,7 +71,7 @@ class NetPDisabledNotificationSchedulerTest { } @Test - fun whenVpnManuallyStoppedThenDoNotShowSnooze() = runTest { + fun `onVpnStopped - do not show snooze - vpn manually stopped`() = runTest { netPSettingsLocalConfig.vpnNotificationAlerts().setEnabled(State(enable = true)) whenever(networkProtectionState.isEnabled()).thenReturn(true) whenever(networkProtectionState.isOnboarded()).thenReturn(true) @@ -82,7 +82,7 @@ class NetPDisabledNotificationSchedulerTest { } @Test - fun whenVpnManuallyStoppedWithSnoozeButNoTriggerTimeThenDoNotShowSnooze() = runTest { + fun `onVpnStopped - no trigger time - do not show snooze`() = runTest { netPSettingsLocalConfig.vpnNotificationAlerts().setEnabled(State(enable = true)) whenever(networkProtectionState.isEnabled()).thenReturn(true) whenever(networkProtectionState.isOnboarded()).thenReturn(true) @@ -94,7 +94,7 @@ class NetPDisabledNotificationSchedulerTest { } @Test - fun whenVpnSnoozedThenShowSnoozeNotification() = runTest { + fun `onVpnSnoozed - show snooze notification`() = runTest { netPSettingsLocalConfig.vpnNotificationAlerts().setEnabled(State(enable = true)) whenever(networkProtectionState.isEnabled()).thenReturn(true) whenever(networkProtectionState.isOnboarded()).thenReturn(true) diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/notification/NetPEnabledNotificationContentPluginTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/notification/NetPEnabledNotificationContentPluginTest.kt index 2a9af6d37285..a92a54ca8386 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/notification/NetPEnabledNotificationContentPluginTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/notification/NetPEnabledNotificationContentPluginTest.kt @@ -66,7 +66,7 @@ class NetPEnabledNotificationContentPluginTest { } @Test - fun getInitialContentNetPDisabledReturnNull() = runTest { + fun `getInitialContent - net p disabled - returns null`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(false) whenever(networkProtectionState.isEnabled()).thenReturn(false) val content = plugin.getInitialContent() @@ -75,7 +75,7 @@ class NetPEnabledNotificationContentPluginTest { } @Test - fun getInitialContentNetPEnabledReturnContent() = runTest { + fun `getInitialContent - netP enabled - return content`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(false) whenever(networkProtectionState.isEnabled()).thenReturn(true) val content = plugin.getInitialContent() @@ -85,7 +85,7 @@ class NetPEnabledNotificationContentPluginTest { } @Test - fun getUpdatedContentNetPDisabledReturnNull() = runTest { + fun `getUpdatedContent - net p disabled - returns null`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(false) whenever(networkProtectionState.isEnabled()).thenReturn(false) plugin.getUpdatedContent().test { @@ -96,7 +96,7 @@ class NetPEnabledNotificationContentPluginTest { } @Test - fun getUpdatedContentNetPEnabledNoServerLocationReturnInitialContent() = runTest { + fun `getUpdatedContent - netP enabled no server location - initial content`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(false) whenever(networkProtectionState.isEnabled()).thenReturn(true) whenever(networkProtectionState.serverLocation()).thenReturn(null) @@ -111,7 +111,7 @@ class NetPEnabledNotificationContentPluginTest { } @Test - fun getUpdatedContentNetPEnabledReturnContent() = runTest { + fun `getUpdatedContent - netP enabled - return content`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(false) whenever(networkProtectionState.isEnabled()).thenReturn(true) whenever(networkProtectionState.serverLocation()).thenReturn("Stockholm, SE") @@ -126,26 +126,26 @@ class NetPEnabledNotificationContentPluginTest { } @Test - fun getPriorityReturnsHigh() { + fun `getPriority - returns high`() { assertEquals(VpnEnabledNotificationContentPlugin.VpnEnabledNotificationPriority.HIGH, plugin.getPriority()) } @Test - fun isActiveNetPDisabledReturnFalse() = runTest { + fun `isActive - net p disabled - false`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(false) whenever(networkProtectionState.isEnabled()).thenReturn(false) assertFalse(plugin.isActive()) } @Test - fun isActiveNetPEnabledReturnTrue() = runTest { + fun `isActive - net p enabled - true`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(false) whenever(networkProtectionState.isEnabled()).thenReturn(true) assertTrue(plugin.isActive()) } @Test - fun isActiveNetPEnabledAppTPEnabledReturnFalse() = runTest { + fun `isActive - net P enabled app TP enabled - return false`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(true) whenever(networkProtectionState.isEnabled()).thenReturn(true) assertFalse(plugin.isActive()) diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/pixels/NetworkProtectionPixelNamesTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/pixels/NetworkProtectionPixelNamesTest.kt index d6ef521334f6..4c39a127f83c 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/pixels/NetworkProtectionPixelNamesTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/pixels/NetworkProtectionPixelNamesTest.kt @@ -21,7 +21,7 @@ import org.junit.Test class NetworkProtectionPixelNamesTest { @Test - fun allNetworkProtectionPixelsShallBePrefixed() { + fun `allNetworkProtectionPixelsShallBePrefixed - all network protection pixels prefixed`() { NetworkProtectionPixelNames.values().map { it.pixelName }.forEach { pixel -> assertTrue(pixel.startsWith("m_netp") || pixel.startsWith("m_vpn")) } diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/pixels/NetworkProtectionRetentionPixelSenderTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/pixels/NetworkProtectionRetentionPixelSenderTest.kt index afac8580e36c..26d06d229154 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/pixels/NetworkProtectionRetentionPixelSenderTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/pixels/NetworkProtectionRetentionPixelSenderTest.kt @@ -34,7 +34,7 @@ class NetworkProtectionRetentionPixelSenderTest { } @Test - fun reportSearchRetentionWhenEnabled() = runTest { + fun `onSearchRetention - enabled - reports enabled on search`() = runTest { pixelSender.onSearchRetentionAtbRefreshed() whenever(networkProtectionState.isEnabled()).thenReturn(false) pixelSender.onSearchRetentionAtbRefreshed() diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/pixels/RealNetworkProtectionPixelTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/pixels/RealNetworkProtectionPixelTest.kt index 9ec841c2ae0b..b687f102470d 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/pixels/RealNetworkProtectionPixelTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/pixels/RealNetworkProtectionPixelTest.kt @@ -66,7 +66,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportErrorInRegistrationIsCalledTwiceThenFireCountPixelTwiceAndDailyPixelOnce() { + fun `reportErrorInRegistration - is called twice - fire count pixel twice and daily pixel once`() { testee.reportErrorInRegistration() testee.reportErrorInRegistration() @@ -75,7 +75,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportErrorWgInvalidStateIsCalledTwiceThenFireCountPixelTwiceAndDailyPixelOnce() { + fun `reportErrorWgInvalidState - pixel fired twice and daily once`() { testee.reportErrorWgInvalidState() testee.reportErrorWgInvalidState() @@ -84,7 +84,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportErrorWgBackendCantStartIsCalledTwiceThenFireCountPixelTwiceAndDailyPixelOnce() { + fun `reportErrorWgBackendCantStart - is called twice - fire count pixel twice and daily pixel once`() { testee.reportErrorWgBackendCantStart() testee.reportErrorWgBackendCantStart() @@ -93,7 +93,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportEnabledCalledTwiceThenFireDailyPixelOnce() { + fun `reportEnabled - fire daily pixel once`() { testee.reportEnabled() testee.reportEnabled() val baseDate = LocalDate.of(2023, 1, 1) @@ -110,7 +110,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun `whenReportEnabledThenSendCohortFrom2023-01-01`() { + fun `whenReportEnabledThenSendCohortFrom20-01-01 - send cohort from 2023-01-01`() { testee.reportEnabled() val baseDate = LocalDate.of(2023, 1, 1) val week = ChronoUnit.WEEKS.between(baseDate, fakeNetpCohortStore.cohortLocalDate!!) + 1 @@ -126,7 +126,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun doNotCoalesceCohortAtTheBoundary() { + fun `reportEnabled - do not coalesce cohort at the boundary`() { fakeNetpCohortStore.cohortLocalDate = LocalDate.now().minusWeeks(6) testee.reportEnabled() val baseDate = LocalDate.of(2023, 1, 1) @@ -143,7 +143,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun coalesceCohortWhenPastTheWeekBoundary() { + fun `reportEnabled - coalesce cohort when past the week boundary`() { fakeNetpCohortStore.cohortLocalDate = LocalDate.now().minusWeeks(7) testee.reportEnabled() @@ -158,7 +158,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportDisabledCalledTwiceThenFireDailyPixelOnce() { + fun `reportDisabled - called twice - fire daily pixel once`() { testee.reportDisabled() testee.reportDisabled() @@ -166,7 +166,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportWireguardLibraryLoadFailedCalledTwiceThenFireCountPixelTwiceAndDailyPixelOnce() { + fun `reportWireguardLibraryLoadFailed - fire count pixel twice and daily pixel once`() { testee.reportWireguardLibraryLoadFailed() testee.reportWireguardLibraryLoadFailed() @@ -175,7 +175,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportRekeyCompletedCalledTwiceThenFireDailyPixelOnce() { + fun `reportRekeyCompleted - fire daily pixel once`() { testee.reportRekeyCompleted() testee.reportRekeyCompleted() @@ -184,7 +184,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportVpnConflictDialogShownCalledTwiceThenFireDailyPixelOnce() { + fun `reportVpnConflictDialogShown - pixel fired once`() { testee.reportVpnConflictDialogShown() testee.reportVpnConflictDialogShown() @@ -193,7 +193,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportAlwaysOnConflictDialogShownCalledTwiceThenFireDailyPixelOnce() { + fun `reportAlwaysOnConflictDialogShown - pixel fired once`() { testee.reportAlwaysOnConflictDialogShown() testee.reportAlwaysOnConflictDialogShown() @@ -202,7 +202,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportAlwaysOnPromotionDialogShownCalledTwiceThenFireDailyPixelOnce() { + fun `reportAlwaysOnPromotionDialogShown - pixel fired once`() { testee.reportAlwaysOnPromotionDialogShown() testee.reportAlwaysOnPromotionDialogShown() @@ -211,7 +211,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportAlwaysOnLockdownDialogShownCalledTwiceThenFireDailyPixelOnce() { + fun `reportAlwaysOnLockdownDialogShown - pixel fired`() { testee.reportAlwaysOnLockdownDialogShown() testee.reportAlwaysOnLockdownDialogShown() @@ -220,7 +220,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportOpenSettingsFromAlwaysOnPromotionCalledTwiceThenFireDailyPixelOnce() { + fun `reportOpenSettingsFromAlwaysOnPromotion - pixel fired once`() { testee.reportOpenSettingsFromAlwaysOnPromotion() testee.reportOpenSettingsFromAlwaysOnPromotion() @@ -229,7 +229,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportOpenSettingsFromAlwaysOnLockdownCalledTwiceThenFireDailyPixelOnce() { + fun `reportOpenSettingsFromAlwaysOnLockdown - pixel fired once`() { testee.reportOpenSettingsFromAlwaysOnLockdown() testee.reportOpenSettingsFromAlwaysOnLockdown() @@ -238,7 +238,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportExclusionListShownCalledTwiceThenFireDailyPixelOnce() { + fun `reportExclusionListShown - pixel fired once`() { testee.reportExclusionListShown() testee.reportExclusionListShown() @@ -247,7 +247,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportAppAddedToExclusionListCalledTwiceThenFirePixelTwice() { + fun `reportAppAddedToExclusionList - fire pixel twice`() { testee.reportAppAddedToExclusionList() testee.reportAppAddedToExclusionList() @@ -255,7 +255,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportAppRemovedFromExclusionListCalledTwiceThenFirePixelTwice() { + fun `reportAppRemovedFromExclusionList - fire pixel twice`() { testee.reportAppRemovedFromExclusionList() testee.reportAppRemovedFromExclusionList() @@ -263,7 +263,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportSkippedReportAfterExcludingAppCalledTwiceThenFireDailyPixelOnce() { + fun `reportSkippedReportAfterExcludingApp - pixel fired once`() { testee.reportSkippedReportAfterExcludingApp() testee.reportSkippedReportAfterExcludingApp() @@ -272,7 +272,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportExclusionListRestoreDefaultsCalledTwiceThenFireDailyPixelOnce() { + fun `reportExclusionListRestoreDefaults - fire daily pixel once`() { testee.reportExclusionListRestoreDefaults() testee.reportExclusionListRestoreDefaults() @@ -281,7 +281,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportExclusionListLaunchBreakageReportCalledTwiceThenFireDailyPixelOnce() { + fun `reportExclusionListLaunchBreakageReport - pixel fired once`() { testee.reportExclusionListLaunchBreakageReport() testee.reportExclusionListLaunchBreakageReport() @@ -290,7 +290,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportFaqsShownCalledTwiceThenFireDailyPixelOnce() { + fun `reportFaqsShown - shown called twice - fire daily pixel once`() { testee.reportFaqsShown() testee.reportFaqsShown() diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/rekey/RealNetPRekeyerTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/rekey/RealNetPRekeyerTest.kt index f19cd30d309a..122257dd2f69 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/rekey/RealNetPRekeyerTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/rekey/RealNetPRekeyerTest.kt @@ -101,7 +101,7 @@ class RealNetPRekeyerTest { } @Test - fun `do not rekey in production if time since last rekey is less than 24h`() = runTest { + fun `doRekey - time since last rekey less than 24h - does not rekey`() = runTest { whenever(vpnFeaturesRegistry.isFeatureRegistered(NETP_VPN)).thenReturn(true) whenever(wgTunnelConfig.getWgConfigCreatedAt()) .thenReturn(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(23)) @@ -114,7 +114,7 @@ class RealNetPRekeyerTest { } @Test - fun `do not rekey in internal if time since last rekey is less than 24h`() = runTest { + fun `doRekey - time since last rekey less than 24h - no rekey`() = runTest { whenever(vpnFeaturesRegistry.isFeatureRegistered(NETP_VPN)).thenReturn(true) whenever(wgTunnelConfig.getWgConfigCreatedAt()) .thenReturn(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(23)) @@ -127,7 +127,7 @@ class RealNetPRekeyerTest { } @Test - fun `do not rekey if registering new key fails`() = runTest { + fun `doRekey - registering new key fails - do not rekey`() = runTest { whenever(vpnFeaturesRegistry.isFeatureRegistered(NETP_VPN)).thenReturn(true) whenever(wgTunnelConfig.getWgConfigCreatedAt()) .thenReturn(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1)) @@ -138,7 +138,7 @@ class RealNetPRekeyerTest { } @Test - fun `do not rekey device is not locked`() = runTest { + fun `doRekey - device not locked - no rekey`() = runTest { whenever(vpnFeaturesRegistry.isFeatureRegistered(NETP_VPN)).thenReturn(true) whenever(wgTunnelConfig.getWgConfigCreatedAt()) .thenReturn(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1)) @@ -150,7 +150,7 @@ class RealNetPRekeyerTest { } @Test - fun `do not rekey if not internal build and forced rekey`() = runTest { + fun `forceRekey - not internal build and forced rekey - does not rekey`() = runTest { whenever(vpnFeaturesRegistry.isFeatureRegistered(NETP_VPN)).thenReturn(true) whenever(wgTunnelConfig.getWgConfigCreatedAt()) .thenReturn(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1)) @@ -163,7 +163,7 @@ class RealNetPRekeyerTest { } @Test - fun `do rekey if internal build and forced rekey`() = runTest { + fun `forceRekey - internal build and forced rekey - rekeyed`() = runTest { whenever(vpnFeaturesRegistry.isFeatureRegistered(NETP_VPN)).thenReturn(true) whenever(wgTunnelConfig.getWgConfigCreatedAt()) .thenReturn(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1)) @@ -176,7 +176,7 @@ class RealNetPRekeyerTest { } @Test - fun `do not rekey if internal build and forced rekey but vpn disabled`() = runTest { + fun `forceRekey - internal build and forced rekey but vpn disabled - no rekey`() = runTest { whenever(vpnFeaturesRegistry.isFeatureRegistered(NETP_VPN)).thenReturn(false) whenever(wgTunnelConfig.getWgConfigCreatedAt()) .thenReturn(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1)) @@ -189,7 +189,7 @@ class RealNetPRekeyerTest { } @Test - fun `do rekey if production build`() = runTest { + fun `do rekey if production build - do rekey`() = runTest { whenever(vpnFeaturesRegistry.isFeatureRegistered(NETP_VPN)).thenReturn(true) whenever(wgTunnelConfig.getWgConfigCreatedAt()) .thenReturn(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1)) @@ -202,7 +202,7 @@ class RealNetPRekeyerTest { } @Test - fun `do not rekey if production build but vpn disabled`() = runTest { + fun `doRekey - production build but vpn disabled - does not rekey`() = runTest { whenever(vpnFeaturesRegistry.isFeatureRegistered(NETP_VPN)).thenReturn(false) whenever(wgTunnelConfig.getWgConfigCreatedAt()) .thenReturn(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1)) diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/revoked/NetpVpnAccessRevokedDialogMonitorTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/revoked/NetpVpnAccessRevokedDialogMonitorTest.kt index 2d1a780e70c7..bd995fc8a3a5 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/revoked/NetpVpnAccessRevokedDialogMonitorTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/revoked/NetpVpnAccessRevokedDialogMonitorTest.kt @@ -67,7 +67,7 @@ class NetpVpnAccessRevokedDialogMonitorTest { } @Test - fun whenVPNStateIsInactiveThenDontShowDialogs() { + fun `getVpnStatus - vpn state inactive - dont show dialogs`() { coroutineTestRule.testScope.launch { whenever(netpSubscriptionManager.getVpnStatus()).thenReturn(INACTIVE) @@ -79,7 +79,7 @@ class NetpVpnAccessRevokedDialogMonitorTest { } @Test - fun whenVPNStateIsActiveThenDontShowDialogs() { + fun `getVpnStatus - vpn state active - dont show dialogs`() { coroutineTestRule.testScope.launch { whenever(netpSubscriptionManager.getVpnStatus()).thenReturn(ACTIVE) @@ -91,7 +91,7 @@ class NetpVpnAccessRevokedDialogMonitorTest { } @Test - fun whenVPNEnabledAndStateIsActiveThenDontShowDialogs() { + fun `whenVPNEnabledAndStateIsActiveThenDontShowDialogs - network protection state active - dont show dialogs`() { coroutineTestRule.testScope.launch { whenever(networkProtectionState.isEnabled()).thenReturn(true) whenever(netpSubscriptionManager.getVpnStatus()).thenReturn(ACTIVE) @@ -104,7 +104,7 @@ class NetpVpnAccessRevokedDialogMonitorTest { } @Test - fun whenVPNEnabledAndStateIsInactiveThenDontShowDialogs() { + fun `whenVPNEnabledAndStateIsInactiveThenDontShowDialogs - network protection state inactive - dont show dialogs`() { coroutineTestRule.testScope.launch { whenever(networkProtectionState.isEnabled()).thenReturn(true) whenever(netpSubscriptionManager.getVpnStatus()).thenReturn(INACTIVE) @@ -117,7 +117,7 @@ class NetpVpnAccessRevokedDialogMonitorTest { } @Test - fun whenVPNStateIsSignedOutThenDontShowDialogs() { + fun `getVpnStatus - vpn state signed out - dont show dialogs`() { coroutineTestRule.testScope.launch { whenever(netpSubscriptionManager.getVpnStatus()).thenReturn(SIGNED_OUT) @@ -129,7 +129,7 @@ class NetpVpnAccessRevokedDialogMonitorTest { } @Test - fun whenVPNEnabledAndStateIsSignedOutThenDontShowDialogs() { + fun `whenVPNEnabledAndStateIsSignedOut - dont show dialogs`() { coroutineTestRule.testScope.launch { whenever(networkProtectionState.isEnabled()).thenReturn(true) whenever(netpSubscriptionManager.getVpnStatus()).thenReturn(SIGNED_OUT) @@ -142,7 +142,7 @@ class NetpVpnAccessRevokedDialogMonitorTest { } @Test - fun whenVPNStateIsExpiredThenShowAccessRevokedDialog() { + fun `getVpnStatus - vpn state expired - show access revoked dialog`() { coroutineTestRule.testScope.launch { whenever(netpSubscriptionManager.getVpnStatus()).thenReturn(EXPIRED) @@ -154,7 +154,7 @@ class NetpVpnAccessRevokedDialogMonitorTest { } @Test - fun whenVPNEnabledStateIsExpiredThenShowAccessRevokedDialog() { + fun `whenVPNEnabledStateIsExpiredThenShowAccessRevokedDialog - show access revoked dialog`() { coroutineTestRule.testScope.launch { whenever(networkProtectionState.isEnabled()).thenReturn(true) whenever(netpSubscriptionManager.getVpnStatus()).thenReturn(EXPIRED) @@ -167,7 +167,7 @@ class NetpVpnAccessRevokedDialogMonitorTest { } @Test - fun whenVPNNotOnboardedAndStateIsExpiredThenDontShowDialogs() { + fun `whenVPNNotOnboardedAndStateIsExpiredThenDontShowDialogs - dont show dialogs`() { coroutineTestRule.testScope.launch { whenever(networkProtectionState.isOnboarded()).thenReturn(false) whenever(netpSubscriptionManager.getVpnStatus()).thenReturn(EXPIRED) @@ -181,7 +181,7 @@ class NetpVpnAccessRevokedDialogMonitorTest { } @Test - fun whenVPNEnabledNotOnboardedAndStateIsExpiredThenDontShowDialogs() { + fun `whenVPNEnabledNotOnboardedAndStateIsExpiredThenDontShowDialogs - dont show dialogs`() { coroutineTestRule.testScope.launch { whenever(networkProtectionState.isOnboarded()).thenReturn(false) whenever(networkProtectionState.isEnabled()).thenReturn(true) diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/settings/NetPVpnSettingsViewModelTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/settings/NetPVpnSettingsViewModelTest.kt index 2a3074244f5f..e139936f1ca8 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/settings/NetPVpnSettingsViewModelTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/settings/NetPVpnSettingsViewModelTest.kt @@ -46,14 +46,14 @@ class NetPVpnSettingsViewModelTest { } @Test - fun whenVpnSettingsScreenShownThenEmitImpressionPixels() { + fun `onCreate - vpn settings screen shown - emit impression pixels`() { viewModel.onCreate(mock()) verify(networkProtectionPixels).reportVpnSettingsShown() } @Test - fun whenIgnoringBatteryOptimizationsFalseThenRecommendedSettingsAreCorrect() = runTest { + fun `recommendedSettings - ignoring battery optimizations false - correct settings`() = runTest { viewModel.recommendedSettings().test { isIgnoringBatteryOptimizations = false assertEquals(NetPVpnSettingsViewModel.RecommendedSettings(false), awaitItem()) @@ -62,7 +62,7 @@ class NetPVpnSettingsViewModelTest { } @Test - fun whenIgnoringBatteryOptimizationsTrueThenRecommendedSettingsAreCorrect() = runTest { + fun `recommendedSettings - ignoring battery optimizations true - correct settings`() = runTest { viewModel.recommendedSettings().test { isIgnoringBatteryOptimizations = true assertEquals(NetPVpnSettingsViewModel.RecommendedSettings(false), awaitItem()) @@ -71,7 +71,7 @@ class NetPVpnSettingsViewModelTest { } @Test - fun onStartEmitDefaultState() = runTest { + fun `onStart - view state default - equals default state`() = runTest { whenever(vpnDisableOnCall.isEnabled()).thenReturn(false) viewModel.viewState().test { viewModel.onStart(mock()) @@ -88,7 +88,7 @@ class NetPVpnSettingsViewModelTest { } @Test - fun onStartEmitCorrectState() = runTest { + fun `onStart - view state correct - exclude local networks and pause during wifi calls`() = runTest { whenever(vpnDisableOnCall.isEnabled()).thenReturn(true) viewModel.viewState().test { netPSettingsLocalConfig.vpnExcludeLocalNetworkRoutes().setEnabled(Toggle.State(remoteEnableState = true)) @@ -102,7 +102,7 @@ class NetPVpnSettingsViewModelTest { } @Test - fun onExcludeLocalRoutesEmitsCorrectState() = runTest { + fun `onExcludeLocalRoutes - view state updated`() = runTest { viewModel.viewState().test { viewModel.onExcludeLocalRoutes(false) assertEquals(NetPVpnSettingsViewModel.ViewState(false), awaitItem()) @@ -114,14 +114,14 @@ class NetPVpnSettingsViewModelTest { } @Test - fun onPauseDoNotRestartVpn() = runTest { + fun `onStart - vpn paused - do not restart`() = runTest { whenever(vpnDisableOnCall.isEnabled()).thenReturn(false) viewModel.onStart(mock()) verify(networkProtectionState, never()).restart() } @Test - fun onPauseDoNotRestartVpnWhenNothingChanges() = runTest { + fun `onPause - do not restart vpn when nothing changes - does not restart`() = runTest { viewModel.onExcludeLocalRoutes(false) viewModel.onPause(mock()) @@ -133,21 +133,21 @@ class NetPVpnSettingsViewModelTest { } @Test - fun onPauseRestartVpnWhenSettingChanged() = runTest { + fun `onPause - restart vpn when setting changed`() = runTest { viewModel.onExcludeLocalRoutes(true) viewModel.onPause(mock()) verify(networkProtectionState).restart() } @Test - fun whenOnEnablePauseDuringWifiCallsThenEnableFeature() { + fun `onEnablePauseDuringWifiCalls - enable feature`() { viewModel.onEnablePauseDuringWifiCalls() verify(vpnDisableOnCall).enable() } @Test - fun whenOnDisablePauseDuringWifiCallsThenDisableFeature() { + fun `onDisablePauseDuringWifiCalls - disable feature`() { viewModel.onDisablePauseDuringWifiCalls() verify(vpnDisableOnCall).disable() diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/settings/geoswitching/CountryUtilsKtTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/settings/geoswitching/CountryUtilsKtTest.kt index d7cabdfc51bf..a84f776d784a 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/settings/geoswitching/CountryUtilsKtTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/settings/geoswitching/CountryUtilsKtTest.kt @@ -6,7 +6,7 @@ import org.junit.Test class CountryUtilsTest { @Test - fun testEmojiForCountryCode() { + fun `getEmojiForCountryCode - country code empty - returns flag for world`() { assertEquals("🇬🇧", getEmojiForCountryCode("gb")) assertEquals("🇬🇧", getEmojiForCountryCode("GB")) diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/settings/geoswitching/NetpGeoSwitchingViewModelTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/settings/geoswitching/NetpGeoSwitchingViewModelTest.kt index ff619bee42e7..4b2639398278 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/settings/geoswitching/NetpGeoSwitchingViewModelTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/settings/geoswitching/NetpGeoSwitchingViewModelTest.kt @@ -79,7 +79,7 @@ class NetpGeoSwitchingViewModelTest { } @Test - fun whenViewModelIsInitializedThenViewStateShouldEmitParsedList() = runTest { + fun `onStart - view state should emit parsed list`() = runTest { testee.onStart(mockLifecycleOwner) testee.viewState().test { expectMostRecentItem().also { @@ -113,7 +113,7 @@ class NetpGeoSwitchingViewModelTest { } @Test - fun whenProviderHasNoDownloadedDataThenViewStateShouldOnlyContainNearestAvailable() = runTest { + fun `onStart - provider has no downloaded data - view state only contains nearest available`() = runTest { val mockProvider = mock(NetpEgressServersProvider::class.java) testee = NetpGeoSwitchingViewModel( mockProvider, @@ -136,7 +136,7 @@ class NetpGeoSwitchingViewModelTest { } @Test - fun whenChosenPreferredCountryAndCityAreChangedThenUpdateStoredCountryAndResetCity() = runTest { + fun `onCountrySelected - update stored country and reset city`() = runTest { fakeRepository.setUserPreferredLocation(UserPreferredLocation("us", "Newark")) testee.onCountrySelected("uk") @@ -149,7 +149,7 @@ class NetpGeoSwitchingViewModelTest { } @Test - fun whenChosenPreferredCountryAndCityAreSameThenStoredDataShouldBeSame() = runTest { + fun `onCountrySelected - same preferred country and city - stored data same`() = runTest { fakeRepository.setUserPreferredLocation(UserPreferredLocation("us", "Newark")) testee.onCountrySelected("us") @@ -162,7 +162,7 @@ class NetpGeoSwitchingViewModelTest { } @Test - fun whenNearestAvailableCountrySelectedThenStoredDataShouldBeNull() = runTest { + fun `onNearestAvailableCountrySelected - stored data should be null`() = runTest { fakeRepository.setUserPreferredLocation(UserPreferredLocation("us", "Newark")) testee.onNearestAvailableCountrySelected() @@ -175,7 +175,7 @@ class NetpGeoSwitchingViewModelTest { } @Test - fun whenNetPIsNotEnabledThenDoNotRestart() = runTest { + fun `onStart - netP not enabled - do not restart`() = runTest { whenever(networkProtectionState.isEnabled()).thenReturn(false) testee.onStart(mockLifecycleOwner) @@ -186,7 +186,7 @@ class NetpGeoSwitchingViewModelTest { } @Test - fun whenNetPIsEnabledButNoChangeInPreferredLocationThenDoNotRestart() = runTest { + fun `onStart - netP enabled but no change in preferred location - do not restart`() = runTest { fakeRepository.setUserPreferredLocation(UserPreferredLocation(countryCode = "us")) whenever(networkProtectionState.isEnabled()).thenReturn(true) @@ -199,7 +199,7 @@ class NetpGeoSwitchingViewModelTest { } @Test - fun whenNetPIsEnabledAndPreferredCountryChangedThenRestart() = runTest { + fun `onStart - netP enabled and preferred country changed - restart`() = runTest { whenever(networkProtectionState.isEnabled()).thenReturn(true) testee.onStart(mockLifecycleOwner) @@ -210,7 +210,7 @@ class NetpGeoSwitchingViewModelTest { } @Test - fun whenNetPIsEnabledAndPreferredCityChangedThenRestart() = runTest { + fun `onStart - netPis enabled and preferred city changed - restart`() = runTest { fakeRepository.setUserPreferredLocation(UserPreferredLocation(countryCode = "us", cityName = "El Segundo")) whenever(networkProtectionState.isEnabled()).thenReturn(true) @@ -222,14 +222,14 @@ class NetpGeoSwitchingViewModelTest { } @Test - fun whenOnCreateIsCalledThenEmitImpressionPixels() { + fun `onCreate - emit impression pixels`() { testee.onCreate(mockLifecycleOwner) verify(networkProtectionPixels).reportGeoswitchingScreenShown() } @Test - fun whenNoCountriesAvailableThenEmitNoLocationsPixel() = runTest { + fun `onStart - no countries available - emit no locations pixel`() = runTest { val mockProvider = mock(NetpEgressServersProvider::class.java) testee = NetpGeoSwitchingViewModel( mockProvider, @@ -247,7 +247,7 @@ class NetpGeoSwitchingViewModelTest { } @Test - fun whenNetpIsNotEnabledAndPreferredLocationChangedToNearestThenEmitPixelForNearest() = runTest { + fun `onStart - netp not enabled - emit pixel for nearest`() = runTest { fakeRepository.setUserPreferredLocation(UserPreferredLocation(countryCode = "us", cityName = "El Segundo")) whenever(networkProtectionState.isEnabled()).thenReturn(false) testee.onStart(mockLifecycleOwner) @@ -259,7 +259,7 @@ class NetpGeoSwitchingViewModelTest { } @Test - fun whenNetpIsEnabledAndPreferredLocationChangedToNearestThenEmitPixelForNearest() = runTest { + fun `onStart - netp enabled and preferred location changed to nearest - emit pixel for nearest`() = runTest { fakeRepository.setUserPreferredLocation(UserPreferredLocation(countryCode = "us", cityName = "El Segundo")) whenever(networkProtectionState.isEnabled()).thenReturn(true) testee.onStart(mockLifecycleOwner) @@ -271,7 +271,7 @@ class NetpGeoSwitchingViewModelTest { } @Test - fun whenNetpIsNotEnabledAndPreferredLocationChangedToCustomThenEmitPixelForCustom() = runTest { + fun `onStart - netp not enabled - emit pixel for custom`() = runTest { fakeRepository.setUserPreferredLocation(UserPreferredLocation()) whenever(networkProtectionState.isEnabled()).thenReturn(false) testee.onStart(mockLifecycleOwner) @@ -283,7 +283,7 @@ class NetpGeoSwitchingViewModelTest { } @Test - fun whenNetpEnabledAndPreferredLocationChangedToCustomThenEmitPixelForCustom() = runTest { + fun `onStart - netp enabled and preferred location changed to custom - emit pixel for custom`() = runTest { fakeRepository.setUserPreferredLocation(UserPreferredLocation()) whenever(networkProtectionState.isEnabled()).thenReturn(true) testee.onStart(mockLifecycleOwner) @@ -295,7 +295,7 @@ class NetpGeoSwitchingViewModelTest { } @Test - fun whenNetPIsEnabledButNoChangeInCustomPreferredLocationThenEmitNoPixels() = runTest { + fun `onStart - netP enabled but no change in custom preferred location - emit no pixels`() = runTest { fakeRepository.setUserPreferredLocation(UserPreferredLocation(countryCode = "us")) whenever(networkProtectionState.isEnabled()).thenReturn(true) @@ -307,7 +307,7 @@ class NetpGeoSwitchingViewModelTest { } @Test - fun whenNetPIsEnabledButNoChangeInDefaultPreferredLocationThenEmitNoPixels() = runTest { + fun `onStart - netP enabled but no change in default preferred location - emit no pixels`() = runTest { whenever(networkProtectionState.isEnabled()).thenReturn(true) testee.onStart(mockLifecycleOwner) diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/settings/geoswitching/RealDisplayablePreferredLocationProviderTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/settings/geoswitching/RealDisplayablePreferredLocationProviderTest.kt index e29730fad7cc..9406ff359aeb 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/settings/geoswitching/RealDisplayablePreferredLocationProviderTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/settings/geoswitching/RealDisplayablePreferredLocationProviderTest.kt @@ -52,7 +52,7 @@ class RealDisplayablePreferredLocationProviderTest { } @Test - fun whenNoInternalServerOverrideAndOnlyCountryPreferredThenReturnCountryOnly() = runTest { + fun `getDisplayablePreferredLocation - no internal server override and country preferred - return country only`() = runTest { whenever(weServerDebugProvider.getSelectedServerName()).thenReturn(null) whenever(netPGeoswitchingRepository.getUserPreferredLocation()).thenReturn(UserPreferredLocation(countryCode = "us")) @@ -60,7 +60,7 @@ class RealDisplayablePreferredLocationProviderTest { } @Test - fun whenNoInternalServerOverrideAndNoPreferredThenReturnNull() = runTest { + fun `getSelectedServerName - no internal server override and no preferred - return null`() = runTest { whenever(weServerDebugProvider.getSelectedServerName()).thenReturn(null) whenever(netPGeoswitchingRepository.getUserPreferredLocation()).thenReturn(UserPreferredLocation()) @@ -68,7 +68,7 @@ class RealDisplayablePreferredLocationProviderTest { } @Test - fun whenNoInternalServerOverrideAndCityCountryPreferredThenReturnCityAndCountry() = runTest { + fun `getDisplayablePreferredLocation - no internal server override and city country preferred - El Segundo, United States`() = runTest { whenever(weServerDebugProvider.getSelectedServerName()).thenReturn(null) whenever(netPGeoswitchingRepository.getUserPreferredLocation()).thenReturn(UserPreferredLocation(countryCode = "us", cityName = "El Segundo")) @@ -76,7 +76,7 @@ class RealDisplayablePreferredLocationProviderTest { } @Test - fun whenInternalServerSetWithCountryThenReturnServerNameAndLocation() = runTest { + fun `getSelectedServerName - internal server set with country - return server name and location`() = runTest { whenever(weServerDebugProvider.getSelectedServerName()).thenReturn("test server") whenever(netPGeoswitchingRepository.getUserPreferredLocation()).thenReturn(UserPreferredLocation(countryCode = "se", cityName = "Stockholm")) @@ -84,7 +84,7 @@ class RealDisplayablePreferredLocationProviderTest { } @Test - fun whenInternalServerSetWithoutCountryThenReturnServerNameOnly() = runTest { + fun `getSelectedServerName - internal server set without country - return server name only`() = runTest { whenever(weServerDebugProvider.getSelectedServerName()).thenReturn("test server") whenever(netPGeoswitchingRepository.getUserPreferredLocation()).thenReturn(UserPreferredLocation()) diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/settings/geoswitching/RealNetpEgressServersProviderTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/settings/geoswitching/RealNetpEgressServersProviderTest.kt index c99376f53047..1c1f443f72bd 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/settings/geoswitching/RealNetpEgressServersProviderTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/settings/geoswitching/RealNetpEgressServersProviderTest.kt @@ -51,7 +51,7 @@ class RealNetpEgressServersProviderTest { } @Test - fun whenDownloadDateThenParseAndReplaceStoredLocations() = runTest { + fun `updateServerLocationsAndReturnPreferred - parse and replace stored locations - expected result`() = runTest { assertNull(testee.updateServerLocationsAndReturnPreferred()) val expectedResult = listOf( NetPGeoswitchingLocation( @@ -74,7 +74,7 @@ class RealNetpEgressServersProviderTest { } @Test - fun whenUpdateLocationsUpdateUserPreferredIfNotPresent() = runTest { + fun `updateServerLocationsAndReturnPreferred - update locations - preferred location updated`() = runTest { netPGeoswitchingRepository.setUserPreferredLocation( UserPreferredLocation( countryCode = "se", @@ -134,7 +134,7 @@ class RealNetpEgressServersProviderTest { } @Test - fun whenUpdateLocationsUpdateUserPreferredIfNotPresentGoneCountry() = runTest { + fun `updateServerLocationsAndReturnPreferred - update locations - preferred location not present gone country`() = runTest { netPGeoswitchingRepository.setUserPreferredLocation( UserPreferredLocation( countryCode = "zz", @@ -164,7 +164,7 @@ class RealNetpEgressServersProviderTest { } @Test - fun whenUpdateLocationsUpdateUserPreferredIfNotPresentGoneCountryAndCity() = runTest { + fun `updateServerLocationsAndReturnPreferred - update locations - null preferred and expected locations`() = runTest { netPGeoswitchingRepository.setUserPreferredLocation( UserPreferredLocation( countryCode = "zz", @@ -194,7 +194,7 @@ class RealNetpEgressServersProviderTest { } @Test - fun whenUpdateLocationsKeepUserPreferredIfPresent() = runTest { + fun `updateServerLocationsAndReturnPreferred - keep user preferred if present - preferred location returned`() = runTest { netPGeoswitchingRepository.setUserPreferredLocation( UserPreferredLocation( countryCode = "se", @@ -224,7 +224,7 @@ class RealNetpEgressServersProviderTest { } @Test - fun whenGetDownloadedDataThenReturnDataFromRepository() = runTest { + fun `getServerLocations - replace locations - returns data from repository`() = runTest { netPGeoswitchingRepository.replaceLocations( listOf( NetPGeoswitchingLocation( diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/store/RealNetworkProtectionRepositoryTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/store/RealNetworkProtectionRepositoryTest.kt index 25158f19f6bf..fac288c2a56a 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/store/RealNetworkProtectionRepositoryTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/store/RealNetworkProtectionRepositoryTest.kt @@ -58,12 +58,12 @@ class RealNetworkProtectionRepositoryTest { } @Test - fun whenNoEnabledTimeMillisThenReturnDefaultValue() { + fun `getEnabledTimeInMillis - no enabled time - return default value`() { assertEquals(-1, testee.enabledTimeInMillis) } @Test - fun whenSettingEnabledTimeMillisThenPutLongInPrefs() { + fun `whenSettingEnabledTimeMillisThenPutLongInPrefs - put long in prefs`() { testee.enabledTimeInMillis = 12243235423453L assertEquals(12243235423453L, networkProtectionPrefs.getLong("wg_server_enable_time", -1)) diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/subscription/NetworkProtectionAccessStateImplTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/subscription/NetworkProtectionAccessStateImplTest.kt index c68be182e407..a6344dc907a5 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/subscription/NetworkProtectionAccessStateImplTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/subscription/NetworkProtectionAccessStateImplTest.kt @@ -65,7 +65,7 @@ class NetworkProtectionAccessStateImplTest { } @Test - fun whenSubscriptionsEnabledAndVpnInactiveAndNetpDisabledThenReturnNotUnlocked() = runTest { + fun `getState - subscriptions enabled and vpn inactive and netp disabled - not unlocked`() = runTest { whenever(netpSubscriptionManager.getVpnStatus()).thenReturn(INACTIVE) whenever(networkProtectionState.isEnabled()).thenReturn(false) testee.getState().also { @@ -75,7 +75,7 @@ class NetworkProtectionAccessStateImplTest { } @Test - fun whenSubscriptionsEnabledAndVpnExpiredAndNetpDisabledThenReturnNotUnlocked() = runTest { + fun `getState - subscriptions enabled and vpn expired and netp disabled - not unlocked`() = runTest { whenever(netpSubscriptionManager.getVpnStatus()).thenReturn(EXPIRED) whenever(networkProtectionState.isEnabled()).thenReturn(false) testee.getState().also { @@ -85,7 +85,7 @@ class NetworkProtectionAccessStateImplTest { } @Test - fun whenSubscriptionsEnabledAndVpnSignedOutAndNetpDisabledThenReturnNotUnlocked() = runTest { + fun `getState - subscriptions enabled and vpn signed out and netp disabled - not unlocked`() = runTest { whenever(netpSubscriptionManager.getVpnStatus()).thenReturn(SIGNED_OUT) whenever(networkProtectionState.isEnabled()).thenReturn(false) testee.getState().also { @@ -95,7 +95,7 @@ class NetworkProtectionAccessStateImplTest { } @Test - fun whenSubscriptionsEnabledAndVpnInactiveAndNetpEnabledThenReturnNotUnlockedAndResetVpnState() = runTest { + fun `getState - subscriptions enabled and vpn inactive and netp enabled - not unlocked and reset vpn state`() = runTest { whenever(netpSubscriptionManager.getVpnStatus()).thenReturn(INACTIVE) whenever(networkProtectionState.isEnabled()).thenReturn(true) testee.getState().also { @@ -105,7 +105,7 @@ class NetworkProtectionAccessStateImplTest { } @Test - fun whenSubscriptionsEnabledAndVpnExpiredAndNetpEnabledThenReturnNotUnlockedAndResetVpnState() = runTest { + fun `getState - subscriptions enabled and vpn expired and netp enabled - not unlocked and reset vpn state`() = runTest { whenever(netpSubscriptionManager.getVpnStatus()).thenReturn(EXPIRED) whenever(networkProtectionState.isEnabled()).thenReturn(true) testee.getState().also { @@ -115,7 +115,7 @@ class NetworkProtectionAccessStateImplTest { } @Test - fun whenSubscriptionsEnabledAndVpnSignedOutAndNetpEnabledThenReturnNotUnlockedAndResetVpnState() = runTest { + fun `getState - subscriptions enabled and vpn signed out and netp enabled - not unlocked and reset vpn state`() = runTest { whenever(netpSubscriptionManager.getVpnStatus()).thenReturn(SIGNED_OUT) whenever(networkProtectionState.isEnabled()).thenReturn(true) testee.getState().also { @@ -125,7 +125,7 @@ class NetworkProtectionAccessStateImplTest { } @Test - fun whenSubscriptionsEnabledAndVpnInactiveAndNetpDisabledThenReturnFlowEmitsNotUnlocked() = runTest { + fun `getStateFlow - subscriptions enabled - vpn inactive and netp disabled - not unlocked`() = runTest { whenever(netpSubscriptionManager.vpnStatus()).thenReturn(flowOf(INACTIVE)) whenever(networkProtectionState.isEnabled()).thenReturn(false) testee.getStateFlow().test { @@ -135,7 +135,7 @@ class NetworkProtectionAccessStateImplTest { } @Test - fun whenSubscriptionsEnabledAndVpnExpiredAndNetpDisabledThenReturnFlowEmitsNotUnlocked() = runTest { + fun `getStateFlow - subscriptions enabled - vpn expired and netp disabled - not unlocked`() = runTest { whenever(netpSubscriptionManager.vpnStatus()).thenReturn(flowOf(EXPIRED)) whenever(networkProtectionState.isEnabled()).thenReturn(false) testee.getStateFlow().test { @@ -145,7 +145,7 @@ class NetworkProtectionAccessStateImplTest { } @Test - fun whenSubscriptionsEnabledAndVpnSingedOutAndNetpDisabledThenReturnFlowEmitsNotUnlocked() = runTest { + fun `getStateFlow - subscriptions enabled - vpn signed out and netp disabled - not unlocked`() = runTest { whenever(netpSubscriptionManager.vpnStatus()).thenReturn(flowOf(SIGNED_OUT)) whenever(networkProtectionState.isEnabled()).thenReturn(false) testee.getStateFlow().test { @@ -155,7 +155,7 @@ class NetworkProtectionAccessStateImplTest { } @Test - fun whenSubscriptionsEnabledAndVpnInactiveAndNetpEnabledThenReturnFlowEmitNotUnlockedAndResetVpnState() = runTest { + fun `getStateFlow - subscriptions enabled and vpn inactive and netp enabled - return flow emit not unlocked and reset vpn state`() = runTest { whenever(netpSubscriptionManager.vpnStatus()).thenReturn(flowOf(INACTIVE)) whenever(networkProtectionState.isEnabled()).thenReturn(true) testee.getStateFlow().test { @@ -165,7 +165,7 @@ class NetworkProtectionAccessStateImplTest { } @Test - fun whenSubscriptionsEnabledAndVpnExpiredAndNetpEnabledThenReturnFlowEmitNotUnlockedAndResetVpnState() = runTest { + fun `getStateFlow - subscriptions enabled - return flow emit not unlocked and reset vpn state`() = runTest { whenever(netpSubscriptionManager.vpnStatus()).thenReturn(flowOf(EXPIRED)) whenever(networkProtectionState.isEnabled()).thenReturn(true) testee.getStateFlow().test { diff --git a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/subscription/settings/ProSettingNetPViewModelTest.kt b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/subscription/settings/ProSettingNetPViewModelTest.kt index 49e41b8e06a4..d36da14741ca 100644 --- a/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/subscription/settings/ProSettingNetPViewModelTest.kt +++ b/network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/subscription/settings/ProSettingNetPViewModelTest.kt @@ -66,7 +66,7 @@ class ProSettingNetPViewModelTest { } @Test - fun whenNetPSettingClickedThenReturnScreenForCurrentState() = runTest { + fun `onNetPSettingClicked - return screen for current state`() = runTest { val testScreen = object : ActivityParams {} whenever(networkProtectionAccessState.getScreenForCurrentState()).thenReturn(testScreen) @@ -81,7 +81,7 @@ class ProSettingNetPViewModelTest { } @Test - fun whenNetPIsNotUnlockedThenNetPEntryStateShouldShowHidden() = runTest { + fun `onStart - net p entry state should show hidden`() = runTest { whenever(networkProtectionState.getConnectionStateFlow()).thenReturn(flowOf(DISCONNECTED)) whenever(networkProtectionAccessState.getStateFlow()).thenReturn(flowOf(Locked)) @@ -96,7 +96,7 @@ class ProSettingNetPViewModelTest { } @Test - fun whenNetPStateIsInBetaButNotAcceptedTermsThenNetPEntryStateShouldShowPending() = runTest { + fun `onStart - net p state in beta but not accepted terms - pending`() = runTest { whenever(networkProtectionState.getConnectionStateFlow()).thenReturn(flowOf(DISCONNECTED)) whenever(networkProtectionAccessState.getStateFlow()).thenReturn(flowOf(UnLocked)) whenever(networkProtectionState.isOnboarded()).thenReturn(false) @@ -112,7 +112,7 @@ class ProSettingNetPViewModelTest { } @Test - fun whenNetPStateIsInBetaAndOnboardedAndEnabledThenNetPEntryStateShouldCorrectShowState() = runTest { + fun `onStart - net p state in beta and onboarded and enabled - show correct state`() = runTest { whenever(networkProtectionState.getConnectionStateFlow()).thenReturn(flowOf(CONNECTED)) whenever(networkProtectionAccessState.getStateFlow()).thenReturn(flowOf(UnLocked)) whenever(networkProtectionState.isOnboarded()).thenReturn(true) @@ -131,7 +131,7 @@ class ProSettingNetPViewModelTest { } @Test - fun whenNetPStateIsInBetaAndNotOnboardedAndEnabledThenNetPEntryStateShouldCorrectShowState() = runTest { + fun `onStart - net p state in beta and not onboarded and enabled - pending`() = runTest { whenever(networkProtectionState.getConnectionStateFlow()).thenReturn(flowOf(CONNECTED)) whenever(networkProtectionAccessState.getStateFlow()).thenReturn(flowOf(UnLocked)) whenever(networkProtectionState.isOnboarded()).thenReturn(false) @@ -147,7 +147,7 @@ class ProSettingNetPViewModelTest { } @Test - fun whenNetPStateIsInBetaOnboardedAndEnabledThenNetPEntryStateShouldCorrectShowState() = runTest { + fun `onStart - net p state in beta onboarded and enabled - correct show state`() = runTest { whenever(networkProtectionState.getConnectionStateFlow()).thenReturn(flowOf(CONNECTED)) whenever(networkProtectionAccessState.getStateFlow()).thenReturn(flowOf(UnLocked)) whenever(networkProtectionState.isOnboarded()).thenReturn(true) @@ -166,7 +166,7 @@ class ProSettingNetPViewModelTest { } @Test - fun whenNetPStateIsInBetaAndConnectingThenNetPEntryStateShouldCorrectShowState() = runTest { + fun `onStart - net p state in beta and connecting - show correct state`() = runTest { whenever(networkProtectionState.getConnectionStateFlow()).thenReturn(flowOf(CONNECTING)) whenever(networkProtectionAccessState.getStateFlow()).thenReturn(flowOf(UnLocked)) whenever(networkProtectionState.isOnboarded()).thenReturn(true) @@ -185,7 +185,7 @@ class ProSettingNetPViewModelTest { } @Test - fun whenNetPStateIsInBetaAndDisabledThenNetPEntryStateShouldCorrectShowState() = runTest { + fun `onStart - net p state in beta and disabled - show disconnected state`() = runTest { whenever(networkProtectionState.getConnectionStateFlow()).thenReturn(flowOf(DISCONNECTED)) whenever(networkProtectionAccessState.getStateFlow()).thenReturn(flowOf(UnLocked)) whenever(networkProtectionState.isOnboarded()).thenReturn(true) diff --git a/network-protection/network-protection-internal/src/test/java/com/duckduckgo/networkprotection/internal/feature/TestNetPInternalFeatureToggles.kt b/network-protection/network-protection-internal/src/test/java/com/duckduckgo/networkprotection/internal/feature/TestNetPInternalFeatureToggles.kt index 99daa5e0893f..3b1e51c7f6a4 100644 --- a/network-protection/network-protection-internal/src/test/java/com/duckduckgo/networkprotection/internal/feature/TestNetPInternalFeatureToggles.kt +++ b/network-protection/network-protection-internal/src/test/java/com/duckduckgo/networkprotection/internal/feature/TestNetPInternalFeatureToggles.kt @@ -38,7 +38,7 @@ class TestNetPInternalFeatureToggles { } @Test - fun testDefaultValues() { + fun `testDefaultValues - default values - all false`() { assertTrue(toggles.self().isEnabled()) assertFalse(toggles.cloudflareDnsFallback().isEnabled()) assertFalse(toggles.excludeSystemApps().isEnabled()) diff --git a/network-protection/network-protection-store/src/test/java/com/duckduckgo/networkprotection/store/RealNetPExclusionListRepositoryTest.kt b/network-protection/network-protection-store/src/test/java/com/duckduckgo/networkprotection/store/RealNetPExclusionListRepositoryTest.kt index a3a3c7435725..ce43d180339c 100644 --- a/network-protection/network-protection-store/src/test/java/com/duckduckgo/networkprotection/store/RealNetPExclusionListRepositoryTest.kt +++ b/network-protection/network-protection-store/src/test/java/com/duckduckgo/networkprotection/store/RealNetPExclusionListRepositoryTest.kt @@ -39,21 +39,21 @@ class RealNetPExclusionListRepositoryTest { } @Test - fun whenGetManualAppExclusionListThenDelegateToNetPExclusionListDao() { + fun `getManualAppExclusionList - delegate to net p exclusion list dao`() { testee.getManualAppExclusionList() verify(exclusionListDao).getManualAppExclusionList() } @Test - fun whenGetManualAppExclusionListFlowThenDelegateToNetPExclusionListDao() { + fun `getManualAppExclusionListFlow - delegate to net p exclusion list dao`() { testee.getManualAppExclusionListFlow() verify(exclusionListDao).getManualAppExclusionListFlow() } @Test - fun whenGetExcludedAppPackagesThenReturnUnprotectedAppsPackages() { + fun `getExcludedAppPackages - return unprotected apps packages`() { assertEquals( listOf("com.example.app2", "com.example.app3"), testee.getExcludedAppPackages(), @@ -61,14 +61,14 @@ class RealNetPExclusionListRepositoryTest { } @Test - fun whenManuallyExcludeAppThenDelegateToNetPExclusionListDao() { + fun `manuallyExcludeApp - delegate to NetP exclusion list Dao`() { testee.manuallyExcludeApp("test") verify(exclusionListDao).insertIntoManualAppExclusionList(NetPManuallyExcludedApp(packageId = "test", isProtected = false)) } @Test - fun whenManuallyExcludeAppsThenDelegateToNetPExclusionListDao() { + fun `manuallyExcludeApps - delegate to net p exclusion list dao`() { testee.manuallyExcludeApps( listOf( "test1", @@ -87,14 +87,14 @@ class RealNetPExclusionListRepositoryTest { } @Test - fun whenManuallyEnableAppThenDelegateToNetPExclusionListDao() { + fun `manuallyEnableApp - delegate to NetP exclusion list Dao - insert into manual app exclusion list`() { testee.manuallyEnableApp("test") verify(exclusionListDao).insertIntoManualAppExclusionList(NetPManuallyExcludedApp(packageId = "test", isProtected = true)) } @Test - fun whenRestoreDefaultProtectedListThenDelegateToNetPExclusionListDao() { + fun `restoreDefaultProtectedList - delegate to net p exclusion list dao`() { testee.restoreDefaultProtectedList() verify(exclusionListDao).deleteManualAppExclusionList() diff --git a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/RealPrivacyConfigDownloaderTest.kt b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/RealPrivacyConfigDownloaderTest.kt index 64f292b06133..fd8e375f87ad 100644 --- a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/RealPrivacyConfigDownloaderTest.kt +++ b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/RealPrivacyConfigDownloaderTest.kt @@ -53,7 +53,7 @@ class RealPrivacyConfigDownloaderTest { } @Test - fun whenDownloadIsNotSuccessfulThenReturnFalse() = + fun `download - not successful - return false`() = runTest { testee = RealPrivacyConfigDownloader( @@ -65,11 +65,11 @@ class RealPrivacyConfigDownloaderTest { } @Test - fun whenDownloadIsSuccessfulThenReturnTrue() = + fun `download - successful - true`() = runTest { assertTrue(testee.download() is Success) } @Test - fun whenDownloadIsSuccessfulThenPersistPrivacyConfigCalled() = + fun `download - privacy config persisted`() = runTest { testee.download() diff --git a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/RealPrivacyConfigPersisterTest.kt b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/RealPrivacyConfigPersisterTest.kt index 8416bbaf64a0..8f0ba9af6c0d 100644 --- a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/RealPrivacyConfigPersisterTest.kt +++ b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/RealPrivacyConfigPersisterTest.kt @@ -110,26 +110,26 @@ class RealPrivacyConfigPersisterTest { } @Test - fun whenHashIsNullSignatureReturnsFeatureName() { + fun `getSignature - hash is null - feature name`() { val expected = pluginPoint.getPlugins().sumOf { it.featureName.hashCode() } assertEquals(expected, pluginPoint.signature()) } @Test - fun whenHashIsNotNullSignatureReturnsHash() { + fun `getSignature - hash is not null - returns hash`() { val pluginPoint = FakePrivacyFeaturePluginPoint(listOf(HashedFakePrivacyFeaturePlugin())) val expected = pluginPoint.getPlugins().sumOf { it.hash().hashCode() } assertEquals(expected, pluginPoint.signature()) } @Test - fun whenDifferentPluginPointsThenReturnDifferentSignatures() { + fun `pluginPoint - different plugin points - different signatures`() { val differentPluginPoint = FakePrivacyFeaturePluginPoint(listOf(FakePrivacyFeaturePlugin(), FakePrivacyFeaturePlugin())) assertNotEquals(pluginPoint.signature(), differentPluginPoint.signature()) } @Test - fun whenPersistPrivacyConfigThenDeleteAllTogglesPreviouslyStored() = + fun `persistPrivacyConfig - delete all toggles previously stored`() = runTest { testee.persistPrivacyConfig(getJsonPrivacyConfig()) @@ -137,7 +137,7 @@ class RealPrivacyConfigPersisterTest { } @Test - fun whenPersistPrivacyConfigThenUpdateAllUnprotectedTemporaryExceptions() = + fun `persistPrivacyConfig - update all unprotected temporary exceptions`() = runTest { assertEquals(0, unprotectedTemporaryRepository.exceptions.size) @@ -147,7 +147,7 @@ class RealPrivacyConfigPersisterTest { } @Test - fun whenPersistPrivacyConfigAndPluginMatchesFeatureNameThenStoreCalled() = + fun `persistPrivacyConfig - store called`() = runTest { testee.persistPrivacyConfig(getJsonPrivacyConfig()) @@ -156,7 +156,7 @@ class RealPrivacyConfigPersisterTest { } @Test - fun whenPersistPrivacyConfigAndVersionIsLowerThanPreviousOneStoredThenDoNothing() = + fun `persistPrivacyConfig - version lower than previous one stored - do nothing`() = runTest { privacyRepository.insert(PrivacyConfig(version = 3, readme = "readme", eTag = "eTag", timestamp = "2023-01-02")) @@ -167,7 +167,7 @@ class RealPrivacyConfigPersisterTest { } @Test - fun whenPersistPrivacyConfigAndVersionIsLowerThanPreviousOneAndDifferentPluginsThenStoreNewConfig() = + fun `persistPrivacyConfig - version lower than previous one and different plugins - store new config`() = runTest { sharedPreferences.edit().putInt("plugin_signature", 0) privacyRepository.insert(PrivacyConfig(version = 3, readme = "readme", eTag = "eTag", timestamp = "2023-01-02")) @@ -179,7 +179,7 @@ class RealPrivacyConfigPersisterTest { } @Test - fun whenPersistPrivacyConfigAndVersionIsEqualsThanPreviousOneStoredThenDoNothing() = + fun `persistPrivacyConfig - version equals previous one stored - do nothing`() = runTest { privacyRepository.insert(PrivacyConfig(version = 2, readme = "readme", eTag = "eTag", timestamp = "2023-01-02")) @@ -190,7 +190,7 @@ class RealPrivacyConfigPersisterTest { } @Test - fun whenPersistPrivacyConfigAndVersionIsEqualsThanPreviousOneStoredAndDifferentPluginsThenUpdateConfig() = + fun `persistPrivacyConfig - version equals previous one stored and different plugins - update config`() = runTest { sharedPreferences.edit().putInt("plugin_signature", 0) privacyRepository.insert(PrivacyConfig(version = 2, readme = "readme", eTag = "eTag", timestamp = "2023-01-02")) @@ -202,7 +202,7 @@ class RealPrivacyConfigPersisterTest { } @Test - fun whenPersistPrivacyConfigAndVersionIsHigherThanPreviousOneStoredThenStoreNewConfig() = + fun `persistPrivacyConfig - version higher than previous one stored - store new config`() = runTest { privacyRepository.insert(PrivacyConfig(version = 1, readme = "readme", eTag = "eTag", timestamp = "2023-01-02")) @@ -212,7 +212,7 @@ class RealPrivacyConfigPersisterTest { } @Test - fun whenPersistPrivacyConfigAndVersionIsHigherThanPreviousOneStoredAndDifferentPluginsThenStoreNewConfig() = + fun `persistPrivacyConfig - version higher than previous one stored and different plugins - store new config`() = runTest { sharedPreferences.edit().putInt("plugin_signature", 0) privacyRepository.insert(PrivacyConfig(version = 1, readme = "readme", eTag = "eTag", timestamp = "2023-01-02")) diff --git a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/amplinks/AmpLinksPluginTest.kt b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/amplinks/AmpLinksPluginTest.kt index 88c8c3aec8b9..6458d17e0cb9 100644 --- a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/amplinks/AmpLinksPluginTest.kt +++ b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/amplinks/AmpLinksPluginTest.kt @@ -41,19 +41,19 @@ class AmpLinksPluginTest { } @Test - fun whenFeatureNameDoesNotMatchAmpLinksThenReturnFalse() { + fun `store - feature name does not match amp links - returns false`() { PrivacyFeatureName.values().filter { it != FEATURE_NAME }.forEach { Assert.assertFalse(testee.store(it.value, EMPTY_JSON_STRING)) } } @Test - fun whenFeatureNameMatchesAmpLinksThenReturnTrue() { + fun `store - feature name matches amp links - returns true`() { assertTrue(testee.store(FEATURE_NAME_VALUE, EMPTY_JSON_STRING)) } @Test - fun whenFeatureNameMatchesAmpLinksAndIsEnabledThenStoreFeatureEnabled() { + fun `store - feature name matches amp links and is enabled - store feature enabled`() { val jsonString = FileUtilities.loadText(AmpLinksPluginTest::class.java.classLoader!!, "json/amp_links.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -62,7 +62,7 @@ class AmpLinksPluginTest { } @Test - fun whenFeatureNameMatchesAmpLinksAndIsNotEnabledThenStoreFeatureDisabled() { + fun `store - feature name matches amp links and is not enabled - store feature disabled`() { val jsonString = FileUtilities.loadText( AmpLinksPluginTest::class.java.classLoader!!, "json/amp_links_disabled.json", @@ -74,7 +74,7 @@ class AmpLinksPluginTest { } @Test - fun whenFeatureNameMatchesAmpLinksAndHasMinSupportedVersionThenStoreMinSupportedVersion() { + fun `store - feature name matches amp links and has min supported version - store min supported version`() { val jsonString = FileUtilities.loadText(AmpLinksPluginTest::class.java.classLoader!!, "json/amp_links_min_supported_version.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -83,7 +83,7 @@ class AmpLinksPluginTest { } @Test - fun whenFeatureNameMatchesAmpLinksThenUpdateAllExistingValues() { + fun `whenFeatureNameMatchesAmpLinksThenUpdateAllExistingValues - update all existing values`() { val jsonString = FileUtilities.loadText(AmpLinksPluginTest::class.java.classLoader!!, "json/amp_links.json") testee.store(FEATURE_NAME_VALUE, jsonString) diff --git a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/amplinks/RealAmpLinksTest.kt b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/amplinks/RealAmpLinksTest.kt index f57ecf4d46d3..dc697b35837e 100644 --- a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/amplinks/RealAmpLinksTest.kt +++ b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/amplinks/RealAmpLinksTest.kt @@ -42,38 +42,38 @@ class RealAmpLinksTest { } @Test - fun whenIsExceptionCalledAndDomainIsInUserAllowListThenReturnTrue() { + fun `isAnException - is domain in user allow list - returns true`() { whenever(mockUserAllowListRepository.isUrlInUserAllowList(anyString())).thenReturn(true) assertTrue(testee.isAnException("test.com")) } @Test - fun whenProcessDestinationUrlAndExtractedUrlIsNullThenReturnInitialUrl() { + fun `processDestinationUrl - extracted url is null - return initial url`() { val destinationUrl = testee.processDestinationUrl("https://example.com", null) assertEquals("https://example.com", destinationUrl) } @Test - fun whenProcessDestinationUrlAndExtractedUrlIsAnExceptionThenReturnInitialUrl() { + fun `processDestinationUrl - extracted url is an exception - return initial url`() { whenever(mockUserAllowListRepository.isUrlInUserAllowList(anyString())).thenReturn(true) val destinationUrl = testee.processDestinationUrl("https://example.com", "https://foo.com") assertEquals("https://example.com", destinationUrl) } @Test - fun whenProcessDestinationUrlAndExtractedUrlDoesNotStartWithHttpOrHttpsThenReturnInitialUrl() { + fun `processDestinationUrl - does not start with http or https - return initial url`() { val destinationUrl = testee.processDestinationUrl("https://example.com", "foo.com") assertEquals("https://example.com", destinationUrl) } @Test - fun whenProcessDestinationUrlAndExtractedUrlStartsWithHttpThenReturnExtractedUrl() { + fun `processDestinationUrl - extracted url starts with http - return extracted url`() { val destinationUrl = testee.processDestinationUrl("https://example.com", "http://foo.com") assertEquals("http://foo.com", destinationUrl) } @Test - fun whenProcessDestinationUrlAndExtractedUrlStartsWithHttpsThenReturnExtractedUrl() { + fun `processDestinationUrl - extracted url starts with https - return extracted url`() { val destinationUrl = testee.processDestinationUrl("https://example.com", "https://foo.com") assertEquals("https://foo.com", destinationUrl) } diff --git a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/contentblocking/ContentBlockingPluginTest.kt b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/contentblocking/ContentBlockingPluginTest.kt index d1335a317aa7..cd3b243b0116 100644 --- a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/contentblocking/ContentBlockingPluginTest.kt +++ b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/contentblocking/ContentBlockingPluginTest.kt @@ -40,19 +40,19 @@ class ContentBlockingPluginTest { } @Test - fun whenFeatureNameDoesNotMatchContentBlockingThenReturnFalse() { + fun `store - feature name does not match content blocking - returns false`() { PrivacyFeatureName.values().filter { it != FEATURE_NAME }.forEach { assertFalse(testee.store(it.value, EMPTY_JSON_STRING)) } } @Test - fun whenFeatureNameMatchesContentBlockingThenReturnTrue() { + fun `store - feature name matches content blocking - true`() { assertTrue(testee.store(FEATURE_NAME_VALUE, EMPTY_JSON_STRING)) } @Test - fun whenFeatureNameMatchesContentBlockingAndIsEnabledThenStoreFeatureEnabled() { + fun `store - feature name matches content blocking and is enabled - store feature enabled`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/content_blocking.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -61,7 +61,7 @@ class ContentBlockingPluginTest { } @Test - fun whenFeatureNameMatchesContentBlockingAndIsNotEnabledThenStoreFeatureDisabled() { + fun `store - feature name matches content blocking and is not enabled - store feature disabled`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/content_blocking_disabled.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -70,7 +70,7 @@ class ContentBlockingPluginTest { } @Test - fun whenFeatureNameMatchesContentBlockingAndHasMinSupportedVersionThenStoreMinSupportedVersion() { + fun `store - feature name matches content blocking and has min supported version - stores min supported version`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/content_blocking_min_supported_version.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -79,7 +79,7 @@ class ContentBlockingPluginTest { } @Test - fun whenFeatureNameMatchesContentBlockingThenUpdateAllExistingExceptions() { + fun `store - feature name matches content blocking - update all existing exceptions`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/content_blocking.json") testee.store(FEATURE_NAME_VALUE, jsonString) diff --git a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/contentblocking/RealContentBlockingTest.kt b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/contentblocking/RealContentBlockingTest.kt index c8ccc9f3030b..9cff699888e0 100644 --- a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/contentblocking/RealContentBlockingTest.kt +++ b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/contentblocking/RealContentBlockingTest.kt @@ -52,28 +52,28 @@ class RealContentBlockingTest { } @Test - fun whenIsAnExceptionAndDomainIsListedInTheExceptionsListThenReturnTrue() { + fun `isAnException - exception and domain listed in exceptions list - true`() { givenThereAreExceptions() assertTrue(testee.isAnException("http://www.example.com")) } @Test - fun whenIsAnExceptionWithSubdomainAndDomainIsListedInTheExceptionsListThenReturnTrue() { + fun `isAnException - exceptions list contains subdomain and domain - returns true`() { givenThereAreExceptions() assertTrue(testee.isAnException("http://test.example.com")) } @Test - fun whenIsAnExceptionAndDomainIsNotListedInTheExceptionsListThenReturnFalse() { + fun `isAnException - domain not listed in exceptions list - returns false`() { whenever(mockContentBlockingRepository.exceptions).thenReturn(CopyOnWriteArrayList()) assertFalse(testee.isAnException("http://test.example.com")) } @Test - fun whenIsAnExceptionAndDomainIsInTheUnprotectedTemporaryListThenReturnTrue() { + fun `isAnException - domain in unprotected temporary list - returns true`() { val url = "http://test.example.com" whenever(mockUnprotectedTemporary.isAnException(url)).thenReturn(true) whenever(mockContentBlockingRepository.exceptions).thenReturn(CopyOnWriteArrayList()) @@ -82,7 +82,7 @@ class RealContentBlockingTest { } @Test - fun whenIsAnExceptionAndFeatureIsDisabledThenReturnFalse() { + fun `isAnException - exception present and feature disabled - returns false`() { givenThereAreExceptions() givenFeatureIsDisabled() diff --git a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/drm/DrmPluginTest.kt b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/drm/DrmPluginTest.kt index 67ac2402d9f8..ffdd112cc518 100644 --- a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/drm/DrmPluginTest.kt +++ b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/drm/DrmPluginTest.kt @@ -40,19 +40,19 @@ class DrmPluginTest { } @Test - fun whenFeatureNameDoesNotMatchEmeThenReturnFalse() { + fun `store - feature name does not match EME - returns false`() { PrivacyFeatureName.values().filter { it != FEATURE_NAME }.forEach { assertFalse(testee.store(it.value, EMPTY_JSON_STRING)) } } @Test - fun whenFeatureNameMatchesEmeThenReturnTrue() { + fun `store - feature name matches eme - returns true`() { assertTrue(testee.store(FEATURE_NAME_VALUE, EMPTY_JSON_STRING)) } @Test - fun whenFeatureNameMatchesEmeAndIsEnabledThenStoreFeatureEnabled() { + fun `store - feature name matches EME and is enabled - store feature enabled`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/drm.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -61,7 +61,7 @@ class DrmPluginTest { } @Test - fun whenFeatureNameMatchesEmeAndIsNotEnabledThenStoreFeatureDisabled() { + fun `store - feature name matches EME and is not enabled - store feature disabled`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/drm_disabled.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -70,7 +70,7 @@ class DrmPluginTest { } @Test - fun whenFeatureNameMatchesEmeAndHasMinSupportedVersionThenStoreMinSupportedVersion() { + fun `store - feature name matches EME and has min supported version - store min supported version`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/drm_min_supported_version.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -79,7 +79,7 @@ class DrmPluginTest { } @Test - fun whenFeatureNameMatchesEmeThenUpdateAllExistingExceptions() { + fun `store - drm feature name matches eme - update all existing exceptions`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/drm.json") testee.store(FEATURE_NAME_VALUE, jsonString) diff --git a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/drm/RealDrmTest.kt b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/drm/RealDrmTest.kt index 5aa4b057e620..13d8c1deb115 100644 --- a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/drm/RealDrmTest.kt +++ b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/drm/RealDrmTest.kt @@ -43,7 +43,7 @@ class RealDrmTest { val testee: RealDrm = RealDrm(mockFeatureToggle, mockDrmRepository, mockUserAllowListRepository, mockUnprotectedTemporary) @Test - fun whenIsDrmAllowedForUrlIfFeatureIsEnabledAndProtectedMediaIdIsRequestedThenTrueIsReturned() { + fun `isDrmAllowedForUrl - feature enabled and protected media id requested - true returned`() { giveFeatureIsEnabled() givenUrlIsInExceptionList() @@ -52,7 +52,7 @@ class RealDrmTest { } @Test - fun whenIsDrmAllowedForUrlIfFeatureIsEnabledAndDomainIsNotInExceptionsListThenFalseIsReturned() { + fun `isDrmAllowedForUrl - feature enabled and domain not in exceptions list - false returned`() { giveFeatureIsEnabled() givenUrlIsNotInExceptionList() @@ -61,14 +61,14 @@ class RealDrmTest { } @Test - fun whenIsDrmAllowedForUrlIfFeatureIsDisableThenFalseIsReturned() { + fun `isDrmAllowedForUrl - feature disabled - false`() { val url = "https://open.spotify.com" assertFalse(testee.isDrmAllowedForUrl(url)) } @Test - fun whenIsDrmAllowedForUrlAndIsInUserAllowListThenTrueIsReturned() { + fun `isDrmAllowedForUrl - is in user allow list - true`() { giveFeatureIsEnabled() givenUrlIsNotInExceptionList() givenUriIsInUserAllowList() @@ -78,7 +78,7 @@ class RealDrmTest { } @Test - fun whenIsDrmAllowedForUrlAndIsInUnprotectedTemporaryThenTrueIsReturned() { + fun `isDrmAllowedForUrl - is in unprotected temporary - true returned`() { giveFeatureIsEnabled() givenUrlIsNotInExceptionList() givenUrlIsInUnprotectedTemporary() diff --git a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/gpc/GpcContentScopeConfigPluginTest.kt b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/gpc/GpcContentScopeConfigPluginTest.kt index 5a0ea5a4fd5d..21977a203594 100644 --- a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/gpc/GpcContentScopeConfigPluginTest.kt +++ b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/gpc/GpcContentScopeConfigPluginTest.kt @@ -35,19 +35,19 @@ class GpcContentScopeConfigPluginTest { } @Test - fun whenGetConfigThenReturnCorrectlyFormattedJson() { + fun `getConfig - return correctly formatted json`() { whenever(mockGpcRepository.gpcContentScopeConfig).thenReturn(config) assertEquals("\"gpc\":$config", testee.config()) } @Test - fun whenGetPreferencesThenReturnCorrectlyFormattedJsonWhenGpcIsEnabled() { + fun `getPreferences - gpc enabled - correctly formatted json`() { whenever(mockGpcRepository.isGpcEnabled()).thenReturn(true) assertEquals(testee.preferences(), "\"globalPrivacyControlValue\":true") } @Test - fun whenGetPreferencesThenReturnCorrectlyFormattedJsonWhenGpcIsDisabled() { + fun `getPreferences - gpc disabled - correctly formatted json`() { whenever(mockGpcRepository.isGpcEnabled()).thenReturn(false) assertEquals(testee.preferences(), "\"globalPrivacyControlValue\":false") } diff --git a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/gpc/GpcPluginTest.kt b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/gpc/GpcPluginTest.kt index 1af0074b2bb1..95a7a129ea6c 100644 --- a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/gpc/GpcPluginTest.kt +++ b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/gpc/GpcPluginTest.kt @@ -41,19 +41,19 @@ class GpcPluginTest { } @Test - fun whenFeatureNameDoesNotMatchGpcThenReturnFalse() { + fun `store - feature name does not match GPC - returns false`() { PrivacyFeatureName.values().filter { it != FEATURE_NAME }.forEach { assertFalse(testee.store(it.value, EMPTY_JSON_STRING)) } } @Test - fun whenFeatureNameMatchesGpcThenReturnTrue() { + fun `store - feature name matches GPC - returns true`() { assertTrue(testee.store(FEATURE_NAME_VALUE, EMPTY_JSON_STRING)) } @Test - fun whenFeatureNameMatchesGpcAndIsEnabledThenStoreFeatureEnabled() { + fun `store - feature name matches gpc and is enabled - store feature enabled`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/gpc.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -62,7 +62,7 @@ class GpcPluginTest { } @Test - fun whenFeatureNameMatchesGpcAndIsNotEnabledThenStoreFeatureDisabled() { + fun `store - feature name matches gpc and is not enabled - store feature disabled`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/gpc_disabled.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -71,7 +71,7 @@ class GpcPluginTest { } @Test - fun whenFeatureNameMatchesGpcAndHasMinSupportedVersionThenStoreMinSupportedVersion() { + fun `store - feature name matches gpc and has min supported version - store min supported version`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/gpc_min_supported_version.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -80,7 +80,7 @@ class GpcPluginTest { } @Test - fun whenFeatureNameMatchesGpcThenUpdateAllExistingExceptionsAndHeadersAndConfig() { + fun `store - gpc matches - update all existing exceptions and headers and config`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/gpc.json") testee.store(FEATURE_NAME_VALUE, jsonString) diff --git a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/gpc/RealGpcTest.kt b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/gpc/RealGpcTest.kt index 77274f46e036..4923e3afcb8f 100644 --- a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/gpc/RealGpcTest.kt +++ b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/gpc/RealGpcTest.kt @@ -58,25 +58,25 @@ class RealGpcTest { } @Test - fun whenIsEnabledThenIsGpcEnabledCalled() { + fun `isEnabled - is GPC enabled called`() { testee.isEnabled() verify(mockGpcRepository).isGpcEnabled() } @Test - fun whenEnableGpcThenEnableGpcCalled() { + fun `enableGpc - enable gpc called`() { testee.enableGpc() verify(mockGpcRepository).enableGpc() } @Test - fun whenDisableGpcThenDisableGpcCalled() { + fun `disableGpc - disable gpc called`() { testee.disableGpc() verify(mockGpcRepository).disableGpc() } @Test - fun whenGetHeadersIfFeatureAndGpcAreEnabledAndUrlIsInExceptionsThenReturnEmptyMap() { + fun `getHeaders - feature and gpc enabled - url in exceptions - return empty map`() { givenFeatureAndGpcAreEnabled() val result = testee.getHeaders(EXCEPTION_URL) @@ -85,7 +85,7 @@ class RealGpcTest { } @Test - fun whenGetHeadersIfFeatureAndGpcAreEnabledAndUrlIsNotInExceptionsThenReturnMapWithHeaders() { + fun `getHeaders - feature and GPC enabled - returns map with headers`() { givenFeatureAndGpcAreEnabled() val result = testee.getHeaders("test.com") @@ -95,7 +95,7 @@ class RealGpcTest { } @Test - fun whenGetHeadersIfFeatureIsEnabledAndGpcIsNotEnabledAndUrlIsNotInExceptionsThenReturnEmptyMap() { + fun `getHeaders - feature enabled - gpc not enabled - url not in exceptions - empty map`() { givenFeatureIsEnabledButGpcIsNot() val result = testee.getHeaders("test.com") @@ -104,7 +104,7 @@ class RealGpcTest { } @Test - fun whenGetHeadersIfFeatureIsNotEnabledAndGpcIsEnabledAndUrlIsNotInExceptionsThenReturnEmptyMap() { + fun `getHeaders - feature not enabled and GPC is enabled - return empty map`() { givenFeatureIsNotEnabledButGpcIsEnabled() val result = testee.getHeaders("test.com") @@ -113,14 +113,14 @@ class RealGpcTest { } @Test - fun whenCanUrlAddHeadersIfFeatureAndGpcAreEnabledAndAndUrlIsInExceptionsThenReturnFalse() { + fun `canUrlAddHeaders - feature and gpc enabled - url in exceptions - returns false`() { givenFeatureAndGpcAreEnabled() assertFalse(testee.canUrlAddHeaders(EXCEPTION_URL, emptyMap())) } @Test - fun whenCanUrlAddHeadersIfFeatureAndGpcAreEnabledAndAndUrlIsInConsumersListsAndHeaderAlreadyExistsThenReturnFalse() { + fun `canUrlAddHeaders - feature and gpc enabled - header already exists - returns false`() { givenFeatureAndGpcAreEnabled() assertFalse( @@ -129,21 +129,21 @@ class RealGpcTest { } @Test - fun whenCanUrlAddHeadersIfFeatureAndGpcAreEnabledAndAndUrlIsInConsumersListAndHeaderDoNotExistsThenReturnTrue() { + fun `canUrlAddHeaders - feature and GPC enabled - returns true`() { givenFeatureAndGpcAreEnabled() assertTrue(testee.canUrlAddHeaders(VALID_CONSUMER_URL, emptyMap())) } @Test - fun whenCanUrlAddHeadersIfFeatureAndGpcAreEnabledAndAndUrlIsInNotInConsumersListAndHeaderDoNotExistsThenReturnFalse() { + fun `canUrlAddHeaders - feature and GPC enabled - URL in not in consumers list - return false`() { givenFeatureAndGpcAreEnabled() assertFalse(testee.canUrlAddHeaders("test.com", emptyMap())) } @Test - fun whenCanUrlAddHeadersIfFeatureAndGpcAreEnabledAndUrlIsInConsumersButInTheExceptionListThenReturnFalse() { + fun `canUrlAddHeaders - feature and gpc enabled - url in exceptions list - returns false`() { val exceptions = CopyOnWriteArrayList().apply { add(GpcException(VALID_CONSUMER_URL)) } whenever(mockGpcRepository.exceptions).thenReturn(exceptions) @@ -153,49 +153,49 @@ class RealGpcTest { } @Test - fun whenCanUrlAddHeadersIfFeatureIsNotEnabledAndGpcIsEnabledAndAndUrlIsInConsumersListAndHeaderDoNotExistsThenReturnFalse() { + fun `canUrlAddHeaders - feature not enabled and GPC is enabled and URL in consumers list and header does not exist - returns false`() { givenFeatureIsNotEnabledButGpcIsEnabled() assertFalse(testee.canUrlAddHeaders(VALID_CONSUMER_URL, emptyMap())) } @Test - fun whenCanUrlAddHeadersIfFeatureIsEnabledAndGpcIsNotEnabledAndAndUrlIsInConsumersListAndHeaderDoNotExistsThenReturnFalse() { + fun `canUrlAddHeaders - feature enabled gpc not enabled url in consumers list header does not exist - returns false`() { givenFeatureIsEnabledButGpcIsNot() assertFalse(testee.canUrlAddHeaders(VALID_CONSUMER_URL, emptyMap())) } @Test - fun whenCanGpcBeUsedByUrlIfFeatureAndGpcAreEnabledAnUrlIsNotAnExceptionThenReturnTrue() { + fun `canGpcBeUsedByUrl - feature and gpc enabled - returns true`() { givenFeatureAndGpcAreEnabled() assertTrue(testee.canGpcBeUsedByUrl("test.com")) } @Test - fun whenCanGpcBeUsedByUrlIfFeatureAndGpcAreEnabledAnUrlIsAnExceptionThenReturnFalse() { + fun `canGpcBeUsedByUrl - feature and gpc enabled - returns false`() { givenFeatureAndGpcAreEnabled() assertFalse(testee.canGpcBeUsedByUrl(EXCEPTION_URL)) } @Test - fun whenCanGpcBeUsedByUrlIfFeatureIsEnabledAndGpcIsNotEnabledAnUrlIsNotAnExceptionThenReturnFalse() { + fun `canGpcBeUsedByUrl - feature enabled gpc not enabled url not exception - returns false`() { givenFeatureIsEnabledButGpcIsNot() assertFalse(testee.canGpcBeUsedByUrl("test.com")) } @Test - fun whenCanGpcBeUsedByUrlIfFeatureIsNotEnabledAndGpcIsEnabledAnUrlIsNotAnExceptionThenReturnFalse() { + fun `canGpcBeUsedByUrl - feature not enabled and GPC is enabled - returns false`() { givenFeatureIsNotEnabledButGpcIsEnabled() assertFalse(testee.canGpcBeUsedByUrl("test.com")) } @Test - fun whenCanGpcBeUsedByUrlIfFeatureAndGpcAreEnabledAnUrlIsInUnprotectedTemporaryThenReturnFalse() { + fun `canGpcBeUsedByUrl - url in unprotected temporary - returns false`() { givenFeatureAndGpcAreEnabled() whenever(mockUnprotectedTemporary.isAnException(VALID_CONSUMER_URL)).thenReturn(true) @@ -203,7 +203,7 @@ class RealGpcTest { } @Test - fun whenIsExceptionCalledAndDomainIsInUserAllowListThenReturnTrue() { + fun `isAnException - is domain in user allow list - returns true`() { whenever(mockUserAllowListRepository.isUrlInUserAllowList(anyString())).thenReturn(true) assertTrue(testee.isAnException("test.com")) } diff --git a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/https/HttpsPluginTest.kt b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/https/HttpsPluginTest.kt index 9f4adcc485d9..5b89f46728ec 100644 --- a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/https/HttpsPluginTest.kt +++ b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/https/HttpsPluginTest.kt @@ -40,19 +40,19 @@ class HttpsPluginTest { } @Test - fun whenFeatureNameDoesNotMatchHttpsThenReturnFalse() { + fun `store - feature name does not match https - return false`() { PrivacyFeatureName.values().filter { it != FEATURE_NAME }.forEach { assertFalse(testee.store(it.value, EMPTY_JSON_STRING)) } } @Test - fun whenFeatureNameMatchesHttpsThenReturnTrue() { + fun `store - feature name matches https - true`() { assertTrue(testee.store(FEATURE_NAME_VALUE, EMPTY_JSON_STRING)) } @Test - fun whenFeatureNameMatchesHttpsAndIsEnabledThenStoreFeatureEnabled() { + fun `store - feature name matches https and is enabled - store feature enabled`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/https.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -61,7 +61,7 @@ class HttpsPluginTest { } @Test - fun whenFeatureNameMatchesHttpsAndIsNotEnabledThenStoreFeatureDisabled() { + fun `store - feature name matches https and is not enabled - store feature disabled`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/https_disabled.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -70,7 +70,7 @@ class HttpsPluginTest { } @Test - fun whenFeatureNameMatchesHttpsAndHasMinSupportedVersionThenStoreMinSupportedVersion() { + fun `store - feature name matches https and has min supported version - stores min supported version`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/https_min_supported_version.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -79,7 +79,7 @@ class HttpsPluginTest { } @Test - fun whenFeatureNameMatchesHttpsThenUpdateAllExistingExceptions() { + fun `store - https feature name matches - update all existing exceptions`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/https.json") testee.store(FEATURE_NAME_VALUE, jsonString) diff --git a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/https/RealHttpsTest.kt b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/https/RealHttpsTest.kt index 051ba98344d6..120108d65eaf 100644 --- a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/https/RealHttpsTest.kt +++ b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/https/RealHttpsTest.kt @@ -42,28 +42,28 @@ class RealHttpsTest { } @Test - fun whenIsAnExceptionAndDomainIsListedInTheExceptionsListThenReturnTrue() { + fun `isAnException - exception and domain listed in exceptions list - true`() { givenThereAreExceptions() assertTrue(testee.isAnException("http://www.example.com")) } @Test - fun whenIsAnExceptionWithSubdomainAndDomainIsListedInTheExceptionsListThenReturnTrue() { + fun `isAnException - exceptions list contains subdomain and domain - returns true`() { givenThereAreExceptions() assertTrue(testee.isAnException("http://test.example.com")) } @Test - fun whenIsAnExceptionAndDomainIsNotListedInTheExceptionsListThenReturnFalse() { + fun `isAnException - domain not listed in exceptions list - returns false`() { whenever(mockHttpsRepository.exceptions).thenReturn(CopyOnWriteArrayList()) assertFalse(testee.isAnException("http://test.example.com")) } @Test - fun whenIsAnExceptionAndDomainIsListedInTheUnprotectedTemporaryListThenReturnTrue() { + fun `isAnException - domain listed in unprotected temporary list - returns true`() { val url = "http://example.com" whenever(mockUnprotectedTemporary.isAnException(url)).thenReturn(true) whenever(mockHttpsRepository.exceptions).thenReturn(CopyOnWriteArrayList()) @@ -72,7 +72,7 @@ class RealHttpsTest { } @Test - fun whenIsAnExceptionAndDomainIsListedInTheUserAllowListThenReturnTrue() { + fun `isAnException - domain listed in user allow list - returns true`() { val url = "http://example.com" whenever(mockUserAllowListRepository.isUrlInUserAllowList(url)).thenReturn(true) whenever(mockHttpsRepository.exceptions).thenReturn(CopyOnWriteArrayList()) diff --git a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/trackerallowlist/RealTrackerAllowlistTest.kt b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/trackerallowlist/RealTrackerAllowlistTest.kt index 03d00a393f06..3a4c36f58cdd 100644 --- a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/trackerallowlist/RealTrackerAllowlistTest.kt +++ b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/trackerallowlist/RealTrackerAllowlistTest.kt @@ -44,7 +44,7 @@ class RealTrackerAllowlistTest { } @Test - fun whenUrlCannotBeParsedThenDoNotThrowAnException() { + fun `isAnException - url cannot be parsed - does not throw exception`() { val url = "://allowlist-tracker-1.com:5000/videos.js" givenDomainIsAnException("allowlist-tracker-1.com") diff --git a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/trackerallowlist/TrackerAllowlistPluginTest.kt b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/trackerallowlist/TrackerAllowlistPluginTest.kt index 9d03516046ea..dedc867b7b15 100644 --- a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/trackerallowlist/TrackerAllowlistPluginTest.kt +++ b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/trackerallowlist/TrackerAllowlistPluginTest.kt @@ -41,19 +41,19 @@ class TrackerAllowlistPluginTest { } @Test - fun whenFeatureNameDoesNotMatchTrackerAllowlistThenReturnFalse() { + fun `store - feature name does not match tracker allowlist - return false`() { PrivacyFeatureName.values().filter { it != FEATURE_NAME }.forEach { assertFalse(testee.store(it.value, EMPTY_JSON_STRING)) } } @Test - fun whenFeatureNameMatchesTrackerAllowlistThenReturnTrue() { + fun `store - feature name matches tracker allowlist - true`() { assertTrue(testee.store(FEATURE_NAME_VALUE, EMPTY_JSON_STRING)) } @Test - fun whenFeatureNameMatchesTrackerAllowlistAndIsEnabledThenStoreFeatureEnabled() { + fun `store - feature name matches tracker allowlist and is enabled - store feature enabled`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/tracker_allowlist.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -62,7 +62,7 @@ class TrackerAllowlistPluginTest { } @Test - fun whenFeatureNameMatchesTrackerAllowlistAndIsNotEnabledThenStoreFeatureDisabled() { + fun `store - feature name matches tracker allowlist and is not enabled - store feature disabled`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/tracker_allowlist_disabled.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -71,7 +71,7 @@ class TrackerAllowlistPluginTest { } @Test - fun whenFeatureNameMatchesTrackerAllowlistAndHasMinSupportedVersionThenStoreMinSupportedVersion() { + fun `store - feature name matches tracker allowlist and has min supported version - store min supported version`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/tracker_allowlist_min_supported_version.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -80,7 +80,7 @@ class TrackerAllowlistPluginTest { } @Test - fun whenFeatureNameMatchesTrackerAllowlistThenUpdateAllExistingExceptions() { + fun `whenFeatureNameMatchesTrackerAllowlistThenUpdateAllExistingExceptions - store - update all existing exceptions`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/tracker_allowlist.json") testee.store(FEATURE_NAME_VALUE, jsonString) diff --git a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/trackingparameters/RealTrackingParametersTest.kt b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/trackingparameters/RealTrackingParametersTest.kt index dcb97165acd1..92ae4f7fa062 100644 --- a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/trackingparameters/RealTrackingParametersTest.kt +++ b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/trackingparameters/RealTrackingParametersTest.kt @@ -41,7 +41,7 @@ class RealTrackingParametersTest { } @Test - fun whenIsExceptionCalledAndDomainIsInUserAllowListThenReturnTrue() { + fun `isAnException - is domain in user allow list - returns true`() { whenever(mockUserAllowListRepository.isUrlInUserAllowList(anyString())).thenReturn(true) assertTrue(testee.isAnException("foo.com", "test.com")) } diff --git a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/trackingparameters/TrackingParametersPluginTest.kt b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/trackingparameters/TrackingParametersPluginTest.kt index 5641e19999c4..75d4f6e2586c 100644 --- a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/trackingparameters/TrackingParametersPluginTest.kt +++ b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/trackingparameters/TrackingParametersPluginTest.kt @@ -41,19 +41,19 @@ class TrackingParametersPluginTest { } @Test - fun whenFeatureNameDoesNotMatchTrackingParametersThenReturnFalse() { + fun `store - feature name does not match tracking parameters - returns false`() { PrivacyFeatureName.values().filter { it != FEATURE_NAME }.forEach { Assert.assertFalse(testee.store(it.value, EMPTY_JSON_STRING)) } } @Test - fun whenFeatureNameMatchesTrackingParametersThenReturnTrue() { + fun `store - feature name matches tracking parameters - returns true`() { assertTrue(testee.store(FEATURE_NAME_VALUE, EMPTY_JSON_STRING)) } @Test - fun whenFeatureNameMatchesTrackingParametersAndIsEnabledThenStoreFeatureEnabled() { + fun `store - feature name matches tracking parameters and is enabled - store feature enabled`() { val jsonString = FileUtilities.loadText(TrackingParametersPluginTest::class.java.classLoader!!, "json/tracking_parameters.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -62,7 +62,7 @@ class TrackingParametersPluginTest { } @Test - fun whenFeatureNameMatchesTrackingParametersAndIsNotEnabledThenStoreFeatureDisabled() { + fun `store - feature name matches tracking parameters and is not enabled - store feature disabled`() { val jsonString = FileUtilities.loadText( TrackingParametersPluginTest::class.java.classLoader!!, "json/tracking_parameters_disabled.json", @@ -74,7 +74,7 @@ class TrackingParametersPluginTest { } @Test - fun whenFeatureNameMatchesTrackingParametersAndHasMinSupportedVersionThenStoreMinSupportedVersion() { + fun `store - feature name matches tracking parameters and has min supported version - store min supported version`() { val jsonString = FileUtilities.loadText( TrackingParametersPluginTest::class.java.classLoader!!, "json/tracking_parameters_min_supported_version.json", @@ -86,7 +86,7 @@ class TrackingParametersPluginTest { } @Test - fun whenFeatureNameMatchesTrackingParametersThenUpdateAllExistingValues() { + fun `whenFeatureNameMatchesTrackingParametersThenUpdateAllExistingValues - update all existing values`() { val jsonString = FileUtilities.loadText(TrackingParametersPluginTest::class.java.classLoader!!, "json/tracking_parameters.json") testee.store(FEATURE_NAME_VALUE, jsonString) diff --git a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/unprotectedtemporary/RealUnprotectedTemporaryTest.kt b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/unprotectedtemporary/RealUnprotectedTemporaryTest.kt index 2ba347a2a5db..4e743b39a36b 100644 --- a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/unprotectedtemporary/RealUnprotectedTemporaryTest.kt +++ b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/features/unprotectedtemporary/RealUnprotectedTemporaryTest.kt @@ -38,21 +38,21 @@ class RealUnprotectedTemporaryTest { } @Test - fun whenIsAnExceptionAndDomainIsListedInTheExceptionsListThenReturnTrue() { + fun `isAnException - exception and domain listed in exceptions list - true`() { givenThereAreExceptions() assertTrue(testee.isAnException("http://www.example.com")) } @Test - fun whenIsAnExceptionWithSubdomainAndDomainIsListedInTheExceptionsListThenReturnTrue() { + fun `isAnException - exceptions list contains subdomain and domain - returns true`() { givenThereAreExceptions() assertTrue(testee.isAnException("http://test.example.com")) } @Test - fun whenIsAnExceptionAndDomainIsNotListedInTheExceptionsListThenReturnFalse() { + fun `isAnException - exception and domain not listed in exceptions list - returns false`() { val exceptions = CopyOnWriteArrayList() whenever(mockUnprotectedTemporaryRepository.exceptions).thenReturn(exceptions) diff --git a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/observers/LocalPrivacyConfigObserverTest.kt b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/observers/LocalPrivacyConfigObserverTest.kt index 0f5c92568978..c4a557d10fc9 100644 --- a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/observers/LocalPrivacyConfigObserverTest.kt +++ b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/observers/LocalPrivacyConfigObserverTest.kt @@ -57,7 +57,7 @@ class LocalPrivacyConfigObserverTest { } @Test - fun whenOnCreateApplicationThenCallPersistPrivacyConfig() = + fun `onCreateApplication - call persist privacy config`() = runTest { givenLocalPrivacyConfigFileExists() diff --git a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/plugins/PrivacyFeatureTogglesPluginTest.kt b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/plugins/PrivacyFeatureTogglesPluginTest.kt index 0b2dbb91c2b5..f5f4bb837e0d 100644 --- a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/plugins/PrivacyFeatureTogglesPluginTest.kt +++ b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/plugins/PrivacyFeatureTogglesPluginTest.kt @@ -45,12 +45,12 @@ class PrivacyFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsNotAPrivacyFeatureThenReturnNull() = runTest { + fun `isEnabled - is not a privacy feature - null`() = runTest { assertNull(testee.isEnabled(NonPrivacyFeature().value, true)) } @Test - fun whenIsEnabledAndFeatureIsPrivacyFeatureThenReturnTrueWhenEnabled() = + fun `isEnabled - privacy feature enabled - returns true when enabled`() = runTest { givenPrivacyFeatureIsEnabled() @@ -60,7 +60,7 @@ class PrivacyFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsPrivacyFeatureThenReturnFalseWhenDisabled() = + fun `isEnabled - privacy feature disabled - returns false when disabled`() = runTest { givenPrivacyFeatureIsDisabled() @@ -70,7 +70,7 @@ class PrivacyFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsPrivacyFeatureThenReturnDefaultValueIfFeatureDoesNotExist() = + fun `isEnabled - privacy feature does not exist - returns default value`() = runTest { val defaultValue = true givenPrivacyFeatureReturnsDefaultValue(defaultValue) @@ -82,7 +82,7 @@ class PrivacyFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsPrivacyFeatureAndAppVersionEqualToMinSupportedVersionThenReturnTrueWhenEnabled() = + fun `isEnabled - privacy feature enabled and app version equal to min supported version - returns true when enabled`() = runTest { givenPrivacyFeatureIsEnabled() givenAppVersionIsEqualToMinSupportedVersion() @@ -93,7 +93,7 @@ class PrivacyFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsPrivacyFeatureAndAppVersionIsGreaterThanMinSupportedVersionThenReturnTrueWhenEnabled() = + fun `isEnabled - privacy feature enabled and app version greater than min supported version - returns true when enabled`() = runTest { givenPrivacyFeatureIsEnabled() givenAppVersionIsGreaterThanMinSupportedVersion() @@ -104,7 +104,7 @@ class PrivacyFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsPrivacyFeatureAndAppVersionIsSmallerThanMinSupportedVersionThenReturnFalseWhenEnabled() = + fun `isEnabled - privacy feature enabled and app version smaller than min supported version - returns false when enabled`() = runTest { givenPrivacyFeatureIsEnabled() givenAppVersionIsSmallerThanMinSupportedVersion() diff --git a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/workers/PrivacyConfigDownloadWorkerTest.kt b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/workers/PrivacyConfigDownloadWorkerTest.kt index cdb0aa72e76e..3ca31c0468fd 100644 --- a/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/workers/PrivacyConfigDownloadWorkerTest.kt +++ b/privacy-config/privacy-config-impl/src/test/java/com/duckduckgo/privacy/config/impl/workers/PrivacyConfigDownloadWorkerTest.kt @@ -47,7 +47,7 @@ class PrivacyConfigDownloadWorkerTest { } @Test - fun whenDoWorkIfDownloadReturnsTrueThenReturnSuccess() = + fun `doWork - download returns true - return success`() = runTest { whenever(mockPrivacyConfigDownloader.download()).thenReturn(Success) @@ -62,7 +62,7 @@ class PrivacyConfigDownloadWorkerTest { } @Test - fun whenDoWorkIfDownloadReturnsFalseThenReturnRetry() = + fun `doWork - download returns false - return retry`() = runTest { whenever(mockPrivacyConfigDownloader.download()).thenReturn(Error("error")) diff --git a/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/RealPrivacyConfigRepositoryTest.kt b/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/RealPrivacyConfigRepositoryTest.kt index 4e8068b8e6db..d59b1b7e84f6 100644 --- a/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/RealPrivacyConfigRepositoryTest.kt +++ b/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/RealPrivacyConfigRepositoryTest.kt @@ -36,7 +36,7 @@ class RealPrivacyConfigRepositoryTest { } @Test - fun whenInsertPrivacyConfigThenCallInsert() { + fun `whenInsertPrivacyConfig - call insert`() { val privacyConfig = PrivacyConfig(id = 1, version = 1, readme = "readme", eTag = "eTag", timestamp = "2023-01-01") testee.insert(privacyConfig) @@ -45,14 +45,14 @@ class RealPrivacyConfigRepositoryTest { } @Test - fun whenDeleteThenCallDelete() { + fun `delete - call delete - delete`() { testee.delete() verify(mockPrivacyConfigDao).delete() } @Test - fun whenGetThenCallGet() { + fun `get - call get - gets privacy config`() { testee.get() verify(mockPrivacyConfigDao).get() diff --git a/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/RealPrivacyFeatureTogglesRepositoryTest.kt b/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/RealPrivacyFeatureTogglesRepositoryTest.kt index 9a2f1b78f06d..03c5509c72ae 100644 --- a/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/RealPrivacyFeatureTogglesRepositoryTest.kt +++ b/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/RealPrivacyFeatureTogglesRepositoryTest.kt @@ -34,21 +34,21 @@ class RealPrivacyFeatureTogglesRepositoryTest { } @Test - fun whenDeleteAllThenDeleteAllCalled() { + fun `deleteAll - delete all called`() { testee.deleteAll() verify(mockPrivacyFeatureTogglesDataStore).deleteAll() } @Test - fun whenGetThenGetCalled() { + fun `get - get called`() { testee.get(PrivacyFeatureName.GpcFeatureName, true) verify(mockPrivacyFeatureTogglesDataStore).get(PrivacyFeatureName.GpcFeatureName, true) } @Test - fun whenInsertThenInsertCalled() { + fun `insert - data store inserted`() { val privacyFeatureToggle = PrivacyFeatureToggles(PrivacyFeatureName.GpcFeatureName.value, true, null) testee.insert(privacyFeatureToggle) diff --git a/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/amplinks/RealAmpLinksRepositoryTest.kt b/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/amplinks/RealAmpLinksRepositoryTest.kt index d5c50667b675..86aa74a14121 100644 --- a/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/amplinks/RealAmpLinksRepositoryTest.kt +++ b/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/amplinks/RealAmpLinksRepositoryTest.kt @@ -52,7 +52,7 @@ class RealAmpLinksRepositoryTest { } @Test - fun whenRepositoryIsCreatedThenValuesLoadedIntoMemory() { + fun `whenRepositoryIsCreatedThenValuesLoadedIntoMemory - repository created - values loaded into memory`() { givenAmpLinksDaoContainsEntities() testee = RealAmpLinksRepository( @@ -68,7 +68,7 @@ class RealAmpLinksRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = runTest { + fun `updateAll - update all called`() = runTest { testee = RealAmpLinksRepository( mockDatabase, TestScope(), @@ -82,7 +82,7 @@ class RealAmpLinksRepositoryTest { } @Test - fun whenUpdateAllThenPreviousValuesAreCleared() = runTest { + fun `updateAll - previous values cleared`() = runTest { givenAmpLinksDaoContainsEntities() testee = RealAmpLinksRepository( diff --git a/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/contentblocking/RealContentBlockingRepositoryTest.kt b/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/contentblocking/RealContentBlockingRepositoryTest.kt index 43770d431a38..88cbbaf37096 100644 --- a/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/contentblocking/RealContentBlockingRepositoryTest.kt +++ b/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/contentblocking/RealContentBlockingRepositoryTest.kt @@ -47,7 +47,7 @@ class RealContentBlockingRepositoryTest { } @Test - fun whenRepositoryIsCreatedThenExceptionsLoadedIntoMemory() { + fun `whenRepositoryIsCreatedThenExceptionsLoadedIntoMemory - exceptions loaded into memory`() { givenContentBlockingDaoContainsExceptions() testee = @@ -65,7 +65,7 @@ class RealContentBlockingRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - update all called`() = runTest { testee = RealContentBlockingRepository( @@ -81,7 +81,7 @@ class RealContentBlockingRepositoryTest { } @Test - fun whenUpdateAllThenPreviousExceptionsAreCleared() = + fun `updateAll - previous exceptions cleared`() = runTest { givenContentBlockingDaoContainsExceptions() testee = diff --git a/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/drm/RealDrmRepositoryTest.kt b/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/drm/RealDrmRepositoryTest.kt index 600b6e77f194..2f8e7825d582 100644 --- a/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/drm/RealDrmRepositoryTest.kt +++ b/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/drm/RealDrmRepositoryTest.kt @@ -47,7 +47,7 @@ class RealDrmRepositoryTest { } @Test - fun whenRepositoryIsCreatedThenExceptionsLoadedIntoMemory() = runTest { + fun `whenRepositoryIsCreated - exceptions loaded into memory - drm exception`() = runTest { givenDrmDaoContainsExceptions() testee = RealDrmRepository(mockDatabase, this, coroutineRule.testDispatcherProvider, true) @@ -56,7 +56,7 @@ class RealDrmRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = runTest { + fun `updateAll - update all called`() = runTest { testee = RealDrmRepository(mockDatabase, this, coroutineRule.testDispatcherProvider, true) testee.updateAll(listOf()) @@ -65,7 +65,7 @@ class RealDrmRepositoryTest { } @Test - fun whenUpdateAllThenPreviousExceptionsAreCleared() = runTest { + fun `updateAll - previous exceptions cleared`() = runTest { givenDrmDaoContainsExceptions() testee = RealDrmRepository(mockDatabase, this, coroutineRule.testDispatcherProvider, true) assertEquals(1, testee.exceptions.size) diff --git a/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/gpc/RealGpcRepositoryTest.kt b/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/gpc/RealGpcRepositoryTest.kt index fd2744ed46b9..d9e106e587b4 100644 --- a/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/gpc/RealGpcRepositoryTest.kt +++ b/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/gpc/RealGpcRepositoryTest.kt @@ -61,7 +61,7 @@ class RealGpcRepositoryTest { } @Test - fun whenRepositoryIsCreatedThenExceptionsLoadedIntoMemory() { + fun `whenRepositoryIsCreatedThenExceptionsLoadedIntoMemory - exceptions loaded into memory`() { givenGpcDaoContainsExceptions() testee = @@ -77,7 +77,7 @@ class RealGpcRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - update all called`() = runTest { testee = RealGpcRepository( @@ -96,7 +96,7 @@ class RealGpcRepositoryTest { } @Test - fun whenUpdateAllThenPreviousExceptionsAreCleared() = + fun `updateAll - previous exceptions cleared`() = runTest { givenGpcDaoContainsExceptions() testee = @@ -116,7 +116,7 @@ class RealGpcRepositoryTest { } @Test - fun whenUpdateAllThenPreviousHeadersAreCleared() = + fun `updateAll - previous headers cleared`() = runTest { givenGpcDaoContainsHeaders() testee = @@ -136,7 +136,7 @@ class RealGpcRepositoryTest { } @Test - fun whenUpdateAllThenReplaceConfig() = + fun `updateAll - replace config`() = runTest { givenGpcDaoContainsConfig(configEntity) testee = @@ -156,21 +156,21 @@ class RealGpcRepositoryTest { } @Test - fun whenEnableGpcThenSetGpcEnabledToTrue() { + fun `enableGpc - set gpc enabled to true`() { testee.enableGpc() verify(mockGpcDataStore).gpcEnabled = true } @Test - fun whenDisableGpcThenSetGpcEnabledToFalse() { + fun `disableGpc - gpc data store set enabled to false`() { testee.disableGpc() verify(mockGpcDataStore).gpcEnabled = false } @Test - fun whenIsGpcEnabledThenReturnGpcEnabledValue() { + fun `isGpcEnabled - gpc enabled value`() { whenever(mockGpcDataStore.gpcEnabled).thenReturn(true) assertTrue(testee.isGpcEnabled()) diff --git a/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/https/RealHttpsRepositoryTest.kt b/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/https/RealHttpsRepositoryTest.kt index cc2b22c2a4b3..48ce614bb315 100644 --- a/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/https/RealHttpsRepositoryTest.kt +++ b/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/https/RealHttpsRepositoryTest.kt @@ -54,7 +54,7 @@ class RealHttpsRepositoryTest { } @Test - fun whenRepositoryIsCreatedThenExceptionsLoadedIntoMemory() { + fun `whenRepositoryIsCreatedThenExceptionsLoadedIntoMemory - exceptions loaded into memory`() { givenHttpsDaoContainsExceptions() testee = @@ -69,7 +69,7 @@ class RealHttpsRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - update all called`() = runTest { testee = RealHttpsRepository( @@ -85,7 +85,7 @@ class RealHttpsRepositoryTest { } @Test - fun whenUpdateAllThenPreviousExceptionsAreCleared() = + fun `updateAll - previous exceptions cleared`() = runTest { givenHttpsDaoContainsExceptions() testee = diff --git a/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/trackerallowlist/RealTrackerAllowlistRepositoryTest.kt b/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/trackerallowlist/RealTrackerAllowlistRepositoryTest.kt index 35f5e8c2e963..5f5e6832449d 100644 --- a/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/trackerallowlist/RealTrackerAllowlistRepositoryTest.kt +++ b/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/trackerallowlist/RealTrackerAllowlistRepositoryTest.kt @@ -54,7 +54,7 @@ class RealTrackerAllowlistRepositoryTest { } @Test - fun whenRepositoryIsCreatedThenExceptionsLoadedIntoMemory() { + fun `whenRepositoryIsCreated - exceptions loaded into memory`() { givenHttpsDaoContainsExceptions() testee = @@ -69,7 +69,7 @@ class RealTrackerAllowlistRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - update all called`() = runTest { testee = RealTrackerAllowlistRepository( @@ -85,7 +85,7 @@ class RealTrackerAllowlistRepositoryTest { } @Test - fun whenUpdateAllThenPreviousExceptionsAreCleared() = + fun `updateAll - previous exceptions cleared`() = runTest { givenHttpsDaoContainsExceptions() testee = diff --git a/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/trackingparameters/RealTrackingParametersRepositoryTest.kt b/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/trackingparameters/RealTrackingParametersRepositoryTest.kt index e98a894bc55d..e618397b15cf 100644 --- a/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/trackingparameters/RealTrackingParametersRepositoryTest.kt +++ b/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/trackingparameters/RealTrackingParametersRepositoryTest.kt @@ -52,7 +52,7 @@ class RealTrackingParametersRepositoryTest { } @Test - fun whenRepositoryIsCreatedThenValuesLoadedIntoMemory() { + fun `whenRepositoryIsCreatedThenValuesLoadedIntoMemory - repository created - values loaded into memory`() { givenTrackingParametersDaoContainsEntities() testee = RealTrackingParametersRepository( @@ -67,7 +67,7 @@ class RealTrackingParametersRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = runTest { + fun `updateAll - update all called`() = runTest { testee = RealTrackingParametersRepository( mockDatabase, TestScope(), @@ -81,7 +81,7 @@ class RealTrackingParametersRepositoryTest { } @Test - fun whenUpdateAllThenPreviousValuesAreCleared() = runTest { + fun `updateAll - previous values cleared`() = runTest { givenTrackingParametersDaoContainsEntities() testee = RealTrackingParametersRepository( diff --git a/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/unprotectedtemporary/RealUnprotectedTemporaryRepositoryTest.kt b/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/unprotectedtemporary/RealUnprotectedTemporaryRepositoryTest.kt index c6e0cc701cef..c712cfeaba2a 100644 --- a/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/unprotectedtemporary/RealUnprotectedTemporaryRepositoryTest.kt +++ b/privacy-config/privacy-config-store/src/test/java/com/duckduckgo/privacy/config/store/features/unprotectedtemporary/RealUnprotectedTemporaryRepositoryTest.kt @@ -54,7 +54,7 @@ class RealUnprotectedTemporaryRepositoryTest { } @Test - fun whenRepositoryIsCreatedThenExceptionsLoadedIntoMemory() { + fun `whenRepositoryIsCreatedThenExceptionsLoadedIntoMemory - exceptions loaded into memory`() { givenUnprotectedTemporaryDaoContainsExceptions() testee = @@ -69,7 +69,7 @@ class RealUnprotectedTemporaryRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - update all called`() = runTest { testee = RealUnprotectedTemporaryRepository( @@ -85,7 +85,7 @@ class RealUnprotectedTemporaryRepositoryTest { } @Test - fun whenUpdateAllThenPreviousExceptionsAreCleared() = + fun `updateAll - previous exceptions cleared`() = runTest { givenUnprotectedTemporaryDaoContainsExceptions() testee = diff --git a/privacy-dashboard/privacy-dashboard-impl/src/test/java/com/duckduckgo/privacy/dashboard/impl/ui/AppProtectionStatusViewStateMapperTest.kt b/privacy-dashboard/privacy-dashboard-impl/src/test/java/com/duckduckgo/privacy/dashboard/impl/ui/AppProtectionStatusViewStateMapperTest.kt index 6a73f44bed61..e5f99574067e 100644 --- a/privacy-dashboard/privacy-dashboard-impl/src/test/java/com/duckduckgo/privacy/dashboard/impl/ui/AppProtectionStatusViewStateMapperTest.kt +++ b/privacy-dashboard/privacy-dashboard-impl/src/test/java/com/duckduckgo/privacy/dashboard/impl/ui/AppProtectionStatusViewStateMapperTest.kt @@ -42,7 +42,7 @@ internal class AppProtectionStatusViewStateMapperTest { private val testee = AppProtectionStatusViewStateMapper(mockContentBlocking, mockUnprotectedTemporary) @Test - fun whenSiteUrlIsAContentBlockingExceptionThenFeatureNotEnabled() { + fun `mapFromSite - site url is a content blocking exception - feature not enabled`() { whenever(mockContentBlocking.isAnException(any())).thenReturn(true) val viewState = testee.mapFromSite(site()) @@ -51,7 +51,7 @@ internal class AppProtectionStatusViewStateMapperTest { } @Test - fun whenContentBlockingEnabledThenFeatureEnabled() { + fun `mapFromSite - content blocking enabled - feature enabled`() { whenever(mockContentBlocking.isAnException(any())).thenReturn(false) val viewState = testee.mapFromSite(site()) @@ -60,14 +60,14 @@ internal class AppProtectionStatusViewStateMapperTest { } @Test - fun whenSiteIsInUserAllowListThenAllowListedIsTrue() { + fun `mapFromSite - site in user allow list - allow listed is true`() { val viewState = testee.mapFromSite(site(allowListed = true)) assertTrue(viewState.allowlisted) } @Test - fun whenSiteIsUnprotectedTemporaryThenUnprotectedIsTrue() { + fun `mapFromSite - site is unprotected temporary - true`() { whenever(mockUnprotectedTemporary.isAnException(any())).thenReturn(true) val viewState = testee.mapFromSite(site()) @@ -76,7 +76,7 @@ internal class AppProtectionStatusViewStateMapperTest { } @Test - fun whenContentBlockingEnabledThenViewStateProtectionsEnabled() { + fun `mapFromSite - content blocking enabled - view state protections enabled`() { val viewState = testee.mapFromSite(site()) assertFalse(viewState.allowlisted) diff --git a/privacy-dashboard/privacy-dashboard-impl/src/test/java/com/duckduckgo/privacy/dashboard/impl/ui/AppSiteRequestDataViewStateMapperTest.kt b/privacy-dashboard/privacy-dashboard-impl/src/test/java/com/duckduckgo/privacy/dashboard/impl/ui/AppSiteRequestDataViewStateMapperTest.kt index 9241e49b674c..dba1bbdf843f 100644 --- a/privacy-dashboard/privacy-dashboard-impl/src/test/java/com/duckduckgo/privacy/dashboard/impl/ui/AppSiteRequestDataViewStateMapperTest.kt +++ b/privacy-dashboard/privacy-dashboard-impl/src/test/java/com/duckduckgo/privacy/dashboard/impl/ui/AppSiteRequestDataViewStateMapperTest.kt @@ -53,7 +53,7 @@ class AppSiteRequestDataViewStateMapperTest { private val testee = AppSiteRequestDataViewStateMapper() @Test - fun whenSiteHasTrackersThenRequestDataViewStateContainsSuchTrackers() { + fun `mapFromSite - site has trackers - request data view state contains such trackers`() { val site = site( events = listOf( TrackingEvent("test.com", "test.com", null, MAJOR_ENTITY_A, null, BLOCKED, AD), @@ -71,7 +71,7 @@ class AppSiteRequestDataViewStateMapperTest { } @Test - fun whenSiteHasTrackersBlockedAndNotBlockedThenRequestDataViewStateContainsSuchTrackers() { + fun `mapFromSite - site has trackers blocked and not blocked - request data view state contains such trackers`() { val site = site( events = listOf( TrackingEvent("test.com", "test1.com", null, MAJOR_ENTITY_A, null, BLOCKED, AD), @@ -95,7 +95,7 @@ class AppSiteRequestDataViewStateMapperTest { } @Test - fun whenSiteDoesNotHaveCategoryThenRequestDataViewStateRequestCategoryIsNull() { + fun `mapFromSite - site does not have category - request data view state request category is null`() { val site = site( events = listOf( TrackingEvent("test.com", "test.com", null, MAJOR_ENTITY_A, null, BLOCKED, AD), @@ -108,7 +108,7 @@ class AppSiteRequestDataViewStateMapperTest { } @Test - fun whenSiteDoesHaveAllowedCategoryThenRequestDataViewStateRequestHasCategory() { + fun `mapFromSite - site has allowed category - request data view state request has category`() { val site = site( events = listOf( TrackingEvent("test.com", "test.com", listOf("Advertising", "unknown"), MAJOR_ENTITY_A, null, BLOCKED, AD), @@ -121,7 +121,7 @@ class AppSiteRequestDataViewStateMapperTest { } @Test - fun whenSiteHasUnknownCategoriesThenRequestDataViewStateRequestHasCategoryIsNull() { + fun `mapFromSite - site has unknown categories - request data view state request category is null`() { val site = site( events = listOf( TrackingEvent("test.com", "test.com", listOf("unknown"), MAJOR_ENTITY_A, null, BLOCKED, AD), @@ -134,7 +134,7 @@ class AppSiteRequestDataViewStateMapperTest { } @Test - fun whenSiteContainsATrackerThenRequestDataContainsAllRequiredTrackerInfo() { + fun `mapFromSite - site contains tracker - request data contains all required tracker info`() { val site = site( events = listOf( TrackingEvent("test.com", "test.co.uk", null, MAJOR_ENTITY_A, null, BLOCKED, AD), @@ -154,7 +154,7 @@ class AppSiteRequestDataViewStateMapperTest { } @Test - fun whenSiteHasTrackersFromSameDomainAndSameStateThenRequestDataViewStateContainsFirstEvent() { + fun `mapFromSite - site has trackers from same domain and state - request data view state contains first event`() { val site = site( events = listOf( TrackingEvent("test.com", "test.com/a.js", null, MAJOR_ENTITY_A, null, BLOCKED, AD), @@ -169,7 +169,7 @@ class AppSiteRequestDataViewStateMapperTest { } @Test - fun whenSiteHasTrackersFromSameDomainAndSameStateButDifferentEntityThenRequestDataViewStateContainsBothEvent() { + fun `mapFromSite - site has trackers from same domain and state but different entity - request data view state contains both event`() { val site = site( events = listOf( TrackingEvent("test.com", "test.com/a.js", null, MINOR_ENTITY_A, null, BLOCKED, AD), @@ -185,7 +185,7 @@ class AppSiteRequestDataViewStateMapperTest { } @Test - fun whenSiteHasTrackersFromSameDomainButDifferentStateThenRequestDataViewStateContainsBothEvent() { + fun `mapFromSite - site has trackers from same domain but different state - request data view state contains both event`() { val site = site( events = listOf( TrackingEvent("test.com", "test.com/a.js", null, MAJOR_ENTITY_A, null, BLOCKED, AD), diff --git a/privacy-dashboard/privacy-dashboard-impl/src/test/java/com/duckduckgo/privacy/dashboard/impl/ui/AppSiteViewStateMapperTest.kt b/privacy-dashboard/privacy-dashboard-impl/src/test/java/com/duckduckgo/privacy/dashboard/impl/ui/AppSiteViewStateMapperTest.kt index 76764ef3ab9a..21bf5aa1f816 100644 --- a/privacy-dashboard/privacy-dashboard-impl/src/test/java/com/duckduckgo/privacy/dashboard/impl/ui/AppSiteViewStateMapperTest.kt +++ b/privacy-dashboard/privacy-dashboard-impl/src/test/java/com/duckduckgo/privacy/dashboard/impl/ui/AppSiteViewStateMapperTest.kt @@ -42,7 +42,7 @@ class AppSiteViewStateMapperTest { val testee = AppSiteViewStateMapper(PublicKeyInfoMapper(androidQAppBuildConfig)) @Test - fun whenSiteHasEntityThenViewStateHasParentEntity() { + fun `mapFromSite - site has entity - view state has parent entity`() { val site = site(entity = MAJOR_ENTITY_A) val siteProtectionsViewState = testee.mapFromSite(site) @@ -53,7 +53,7 @@ class AppSiteViewStateMapperTest { } @Test - fun whenSiteDoesNotHaveEntityThenViewStateParentEntityNull() { + fun `mapFromSite - site does not have entity - view state parent entity null`() { val site = site() val siteProtectionsViewState = testee.mapFromSite(site) @@ -62,7 +62,7 @@ class AppSiteViewStateMapperTest { } @Test - fun whenMappingSiteThenViewStateHasSiteInfo() { + fun `mapFromSite - view state has site info`() { val site = site() val siteProtectionsViewState = testee.mapFromSite(site) @@ -73,7 +73,7 @@ class AppSiteViewStateMapperTest { } @Test - fun whenSiteHasCertificateThenViewStateContainsCertificates() { + fun `mapFromSite - site has certificate - view state contains certificates`() { val site = site(certificate = TestCertificateInfo("cname")) val siteProtectionsViewState = testee.mapFromSite(site) @@ -83,7 +83,7 @@ class AppSiteViewStateMapperTest { } @Test - fun whenSiteDoesNotHaveCertificateThenViewStateCertificatesEmpty() { + fun `mapFromSite - site does not have certificate - view state certificates empty`() { val site = site() val siteProtectionsViewState = testee.mapFromSite(site) diff --git a/privacy-dashboard/privacy-dashboard-impl/src/test/java/com/duckduckgo/privacy/dashboard/impl/ui/PrivacyDashboardHybridViewModelTest.kt b/privacy-dashboard/privacy-dashboard-impl/src/test/java/com/duckduckgo/privacy/dashboard/impl/ui/PrivacyDashboardHybridViewModelTest.kt index 7439f0304806..954a220de649 100644 --- a/privacy-dashboard/privacy-dashboard-impl/src/test/java/com/duckduckgo/privacy/dashboard/impl/ui/PrivacyDashboardHybridViewModelTest.kt +++ b/privacy-dashboard/privacy-dashboard-impl/src/test/java/com/duckduckgo/privacy/dashboard/impl/ui/PrivacyDashboardHybridViewModelTest.kt @@ -96,7 +96,7 @@ class PrivacyDashboardHybridViewModelTest { } @Test - fun whenUserClicksOnReportBrokenSiteThenCommandEmitted() = runTest { + fun `onReportBrokenSiteSelected - commands emitted - launch report broken site`() = runTest { testee.onReportBrokenSiteSelected() testee.commands().test { @@ -106,7 +106,7 @@ class PrivacyDashboardHybridViewModelTest { } @Test - fun whenSiteChangesThenViewStateUpdates() = runTest { + fun `onSiteChanged - view state updates - site updated`() = runTest { testee.onSiteChanged(site()) testee.viewState.test { @@ -117,7 +117,7 @@ class PrivacyDashboardHybridViewModelTest { } @Test - fun whenOnPrivacyProtectionClickedThenUpdateViewState() = runTest { + fun `onPrivacyProtectionsClicked - update view state - allowlist add`() = runTest { testee.onSiteChanged(site(siteAllowed = false)) testee.onPrivacyProtectionsClicked(enabled = false) @@ -131,7 +131,7 @@ class PrivacyDashboardHybridViewModelTest { } @Test - fun whenOnPrivacyProtectionClickedThenValueStoredInStore() = runTest { + fun `onPrivacyProtectionsClicked - value stored in store`() = runTest { val site = site(siteAllowed = false) testee.onSiteChanged(site) @@ -144,7 +144,7 @@ class PrivacyDashboardHybridViewModelTest { } @Test - fun whenAllowlistIsChangedThenViewStateIsUpdated() = runTest { + fun `onSiteChanged - view state updated`() = runTest { val site = site(siteAllowed = false) testee.onSiteChanged(site) @@ -156,7 +156,7 @@ class PrivacyDashboardHybridViewModelTest { } @Test - fun whenOnPrivacyProtectionClickedThenListenerIsNotified() = runTest { + fun `onPrivacyProtectionsClicked - privacy protections toggle used - listener notified`() = runTest { val site = site(siteAllowed = false) testee.onSiteChanged(site) @@ -166,7 +166,7 @@ class PrivacyDashboardHybridViewModelTest { } @Test - fun whenPrivacyProtectionsPopupExperimentParamsArePresentThenTheyShouldBeIncludedInPixels() = runTest { + fun `whenPrivacyProtectionsPopupExperimentParamsArePresentThenTheyShouldBeIncludedInPixels - site changed - privacy protections toggled`() = runTest { val params = mapOf("test_key" to "test_value") whenever(privacyProtectionsPopupExperimentExternalPixels.getPixelParams()).thenReturn(params) val site = site(siteAllowed = false) @@ -184,7 +184,7 @@ class PrivacyDashboardHybridViewModelTest { } @Test - fun whenOnPrivacyProtectionClickedAndProtectionsEnabledAndOpenedFromCustomTabThenFireCustomTabSpecificPixel() = runTest { + fun `onPrivacyProtectionsClicked - protections enabled - fire custom tab specific pixel`() = runTest { val site = site(siteAllowed = false) testee.onSiteChanged(site) testee.onPrivacyProtectionsClicked(enabled = true, dashboardOpenedFromCustomTab = true) @@ -193,7 +193,7 @@ class PrivacyDashboardHybridViewModelTest { } @Test - fun whenOnPrivacyProtectionClickedAndProtectionsDisabledAndOpenedFromCustomTabThenFireCustomTabSpecificPixel() = runTest { + fun `onPrivacyProtectionsClicked - protections disabled - fire custom tab specific pixel`() = runTest { val site = site(siteAllowed = false) testee.onSiteChanged(site) testee.onPrivacyProtectionsClicked(enabled = false, dashboardOpenedFromCustomTab = true) diff --git a/privacy-dashboard/privacy-dashboard-impl/src/test/java/com/duckduckgo/privacy/dashboard/impl/ui/PrivacyDashboardRendererTest.kt b/privacy-dashboard/privacy-dashboard-impl/src/test/java/com/duckduckgo/privacy/dashboard/impl/ui/PrivacyDashboardRendererTest.kt index dcf2bf712930..0725291e213c 100644 --- a/privacy-dashboard/privacy-dashboard-impl/src/test/java/com/duckduckgo/privacy/dashboard/impl/ui/PrivacyDashboardRendererTest.kt +++ b/privacy-dashboard/privacy-dashboard-impl/src/test/java/com/duckduckgo/privacy/dashboard/impl/ui/PrivacyDashboardRendererTest.kt @@ -62,7 +62,7 @@ class PrivacyDashboardRendererTest { ) @Test - fun whenLoadDashboardThenJSInterfaceInjected() { + fun `loadDashboard - js interface injected`() { testee.loadDashboard(spyWebView) verify(spyWebView).addJavascriptInterface( @@ -72,14 +72,14 @@ class PrivacyDashboardRendererTest { } @Test - fun whenLoadDashboardThenLoadLocalHtml() { + fun `loadDashboard - load local html`() { testee.loadDashboard(spyWebView) verify(spyWebView).loadUrl("file:///android_asset/html/android.html") } @Test - fun whenRenderStateThenJSInterface() { + fun `render - state - js interface`() { val captor = argumentCaptor() testee.render(aViewState()) diff --git a/privacy-dashboard/privacy-dashboard-impl/src/test/java/com/duckduckgo/privacy/dashboard/impl/ui/PublicKeyInfoMapperTest.kt b/privacy-dashboard/privacy-dashboard-impl/src/test/java/com/duckduckgo/privacy/dashboard/impl/ui/PublicKeyInfoMapperTest.kt index e6697dafa7c6..cc634e031ff8 100644 --- a/privacy-dashboard/privacy-dashboard-impl/src/test/java/com/duckduckgo/privacy/dashboard/impl/ui/PublicKeyInfoMapperTest.kt +++ b/privacy-dashboard/privacy-dashboard-impl/src/test/java/com/duckduckgo/privacy/dashboard/impl/ui/PublicKeyInfoMapperTest.kt @@ -40,7 +40,7 @@ class PublicKeyInfoMapperTest { } @Test - fun whenRSASslCertificateThenReturnRsaPublicKeyInfo() { + fun `mapFrom - rsa ssl certificate - returns rsa public key info`() { val expected = PublicKeyInfo( type = "rsa", bitSize = 1, @@ -52,7 +52,7 @@ class PublicKeyInfoMapperTest { } @Test - fun whenDSASslCertificateThenReturnDSAPublicKeyInfo() { + fun `mapFrom - dsa ssl certificate - returns dsa public key info`() { val expected = PublicKeyInfo( type = "dsa", bitSize = 1, @@ -65,7 +65,7 @@ class PublicKeyInfoMapperTest { } @Test - fun whenDSAWithParamsSslCertificateThenReturnDSAPublicKeyInfo() { + fun `mapFrom - DSA with params SSL certificate - return DSA public key info`() { val expected = PublicKeyInfo( type = "dsa", bitSize = 1, @@ -78,7 +78,7 @@ class PublicKeyInfoMapperTest { } @Test - fun whenECSslCertificateThenReturnECPublicKeyInfo() { + fun `mapFrom - ECS ssl certificate - return ec public key info`() { val expected = PublicKeyInfo( type = "ec", bitSize = 1, diff --git a/privacy-protections-popup/privacy-protections-popup-impl/src/test/java/com/duckduckgo/privacyprotectionspopup/impl/PrivacyProtectionsPopupDomainsCleanupWorkerTest.kt b/privacy-protections-popup/privacy-protections-popup-impl/src/test/java/com/duckduckgo/privacyprotectionspopup/impl/PrivacyProtectionsPopupDomainsCleanupWorkerTest.kt index a7941fd474a5..cff91957313e 100644 --- a/privacy-protections-popup/privacy-protections-popup-impl/src/test/java/com/duckduckgo/privacyprotectionspopup/impl/PrivacyProtectionsPopupDomainsCleanupWorkerTest.kt +++ b/privacy-protections-popup/privacy-protections-popup-impl/src/test/java/com/duckduckgo/privacyprotectionspopup/impl/PrivacyProtectionsPopupDomainsCleanupWorkerTest.kt @@ -47,7 +47,7 @@ class PrivacyProtectionsPopupDomainsCleanupWorkerTest { } @Test - fun whenDoWorkThenCleanUpOldEntriesFromPopupDismissDomainRepository() = runTest { + fun `doWork - cleanup old entries from popup dismiss domain repository`() = runTest { timeProvider.time = Instant.parse("2023-11-29T10:15:30.000Z") val result = subject.doWork() diff --git a/privacy-protections-popup/privacy-protections-popup-impl/src/test/java/com/duckduckgo/privacyprotectionspopup/impl/PrivacyProtectionsPopupManagerImplTest.kt b/privacy-protections-popup/privacy-protections-popup-impl/src/test/java/com/duckduckgo/privacyprotectionspopup/impl/PrivacyProtectionsPopupManagerImplTest.kt index 162eb3ee8e50..de5f35120dac 100644 --- a/privacy-protections-popup/privacy-protections-popup-impl/src/test/java/com/duckduckgo/privacyprotectionspopup/impl/PrivacyProtectionsPopupManagerImplTest.kt +++ b/privacy-protections-popup/privacy-protections-popup-impl/src/test/java/com/duckduckgo/privacyprotectionspopup/impl/PrivacyProtectionsPopupManagerImplTest.kt @@ -104,7 +104,7 @@ class PrivacyProtectionsPopupManagerImplTest { ) @Test - fun whenRefreshIsTriggeredThenEmitsUpdateToShowPopup() = runTest { + fun `onPageRefreshTriggeredByUser - view state updated - emits update to show popup`() = runTest { val toggleUsedAt = timeProvider.time - Duration.ofDays(32) dataStore.setToggleUsageTimestamp(toggleUsedAt) @@ -119,7 +119,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenRefreshIsTriggeredThenPopupIsShown() = runTest { + fun `onPageRefreshTriggeredByUser - view state updated - popup is shown`() = runTest { subject.viewState.test { subject.onPageLoaded(url = "https://www.example.com", httpErrorCodes = emptyList(), hasBrowserError = false) subject.onPageRefreshTriggeredByUser() @@ -129,7 +129,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenUrlIsDuckDuckGoThenPopupIsNotShown() = runTest { + fun `onPageLoaded - popup not shown - not visible`() = runTest { subject.viewState.test { subject.onPageLoaded(url = "https://duckduckgo.com", httpErrorCodes = emptyList(), hasBrowserError = false) subject.onPageRefreshTriggeredByUser() @@ -139,7 +139,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenFeatureIsDisabledThenPopupIsNotShown() = runTest { + fun `onPageLoaded - feature disabled - popup not shown`() = runTest { featureFlag.enabled = false subject.viewState.test { subject.onPageLoaded(url = "https://www.example.com", httpErrorCodes = emptyList(), hasBrowserError = false) @@ -150,7 +150,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenProtectionsAreDisabledThenPopupIsNotShown() = runTest { + fun `onPageLoaded - protections disabled - popup not shown`() = runTest { protectionsStateProvider.protectionsEnabled = false subject.viewState.test { @@ -162,7 +162,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenUrlIsMissingThenPopupIsNotShown() = runTest { + fun `onPageLoaded - popup not shown`() = runTest { subject.viewState.test { subject.onPageLoaded(url = "", httpErrorCodes = emptyList(), hasBrowserError = false) subject.onPageRefreshTriggeredByUser() @@ -172,7 +172,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenPageLoadedWithHttpErrorThenPopupIsNotShown() = runTest { + fun `onPageLoaded - page loaded with http error - popup not shown`() = runTest { subject.viewState.test { subject.onPageLoaded(url = "https://www.example.com", httpErrorCodes = listOf(500), hasBrowserError = false) subject.onPageRefreshTriggeredByUser() @@ -182,7 +182,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenPageLoadedWithBrowserErrorThenPopupIsNotShown() = runTest { + fun `onPageLoaded - page loaded with browser error - popup not shown`() = runTest { subject.viewState.test { subject.onPageLoaded(url = "https://www.example.com", httpErrorCodes = emptyList(), hasBrowserError = true) subject.onPageRefreshTriggeredByUser() @@ -192,7 +192,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenPageIsChangedThenPopupIsNotDismissed() = runTest { + fun `onPageChanged - popup not dismissed`() = runTest { subject.viewState.test { subject.onPageLoaded(url = "https://www.example.com", httpErrorCodes = emptyList(), hasBrowserError = false) subject.onPageRefreshTriggeredByUser() @@ -206,7 +206,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenDismissEventIsHandledThenViewStateIsUpdated() = runTest { + fun `onUiEvent - view state updated - popup dismissed`() = runTest { subject.viewState.test { subject.onPageLoaded(url = "https://www.example.com", httpErrorCodes = emptyList(), hasBrowserError = false) subject.onPageRefreshTriggeredByUser() @@ -220,7 +220,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenDismissButtonClickedEventIsHandledThenPopupIsDismissed() = runTest { + fun `onUiEvent - popup dismissed`() = runTest { subject.viewState.test { subject.onPageLoaded(url = "https://www.example.com", httpErrorCodes = emptyList(), hasBrowserError = false) subject.onPageRefreshTriggeredByUser() @@ -235,7 +235,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenDisableProtectionsClickedEventIsHandledThenPopupIsDismissed() = runTest { + fun `onDisableProtectionsClicked - popup dismissed`() = runTest { subject.viewState.test { assertEquals(PrivacyProtectionsPopupViewState.Gone, awaitItem()) subject.onPageLoaded(url = "https://www.example.com", httpErrorCodes = emptyList(), hasBrowserError = false) @@ -251,7 +251,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenDisableProtectionsClickedEventIsHandledThenDomainIsAddedToUserAllowlist() = runTest { + fun `onDisableProtectionsClicked - view state updated - domain added to user allowlist`() = runTest { subject.viewState.test { subject.onPageLoaded(url = "https://www.example.com", httpErrorCodes = emptyList(), hasBrowserError = false) subject.onPageRefreshTriggeredByUser() @@ -266,7 +266,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenPopupWasDismissedRecentlyForTheSameDomainThenItWontBeShownOnRefresh() = runTest { + fun `onPageRefresh - popup dismissed recently - not shown on refresh`() = runTest { subject.viewState.test { subject.onPageLoaded(url = "https://www.example.com", httpErrorCodes = emptyList(), hasBrowserError = false) subject.onPageRefreshTriggeredByUser() @@ -281,7 +281,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenPopupWasDismissedMoreThan24HoursAgoForTheSameDomainThenItIsShownAgainOnRefresh() = runTest { + fun `onPageRefresh - popup dismissed more than 24 hours ago for same domain - shown again`() = runTest { subject.viewState.test { timeProvider.time = Instant.parse("2023-11-29T10:15:30.000Z") subject.onPageLoaded(url = "https://www.example.com", httpErrorCodes = emptyList(), hasBrowserError = false) @@ -297,7 +297,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenPopupWasDismissedRecentlyThenItWontBeShownOnForTheSameDomainButWillBeForOtherDomains() = runTest { + fun `onPageLoaded - popup dismissed recently - not shown for same domain but will be for other domains`() = runTest { subject.viewState.test { subject.onPageLoaded(url = "https://www.example.com", httpErrorCodes = emptyList(), hasBrowserError = false) subject.onPageRefreshTriggeredByUser() @@ -321,7 +321,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenRefreshIsTriggeredBeforeDataIsLoadedThenPopupIsNotShown() = runTest { + fun `onPageRefreshTriggeredByUser - view state - popup not shown`() = runTest { val protectionsEnabledFlow = MutableSharedFlow() protectionsStateProvider.overrideProtectionsEnabledFlow(protectionsEnabledFlow) @@ -335,7 +335,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenRefreshIsTriggeredThenPopupIsNotShownEvenIfOtherConditionsAreMetAfterAFewSeconds() = runTest { + fun `onPageRefreshTriggeredByUser - view state updated - popup not shown`() = runTest { val protectionsEnabledFlow = MutableSharedFlow() protectionsStateProvider.overrideProtectionsEnabledFlow(protectionsEnabledFlow) @@ -349,7 +349,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenToggleWasUsedInLast2WeeksThenPopupIsNotShownOnRefresh() = runTest { + fun `onPageRefreshTriggeredByUser - toggle used in last 2 weeks - popup is not shown on refresh`() = runTest { val toggleUsedAt = timeProvider.time - Duration.ofDays(10) dataStore.setToggleUsageTimestamp(toggleUsedAt) @@ -362,7 +362,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenToggleWasNotUsedInLast2WeeksThenPopupIsShownOnRefresh() = runTest { + fun `onPageRefreshTriggeredByUser - toggle not used in last 2 weeks - popup is shown on refresh`() = runTest { val toggleUsedAt = timeProvider.time - Duration.ofDays(32) dataStore.setToggleUsageTimestamp(toggleUsedAt) @@ -375,7 +375,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenPageReloadsOnRefreshWithHttpErrorThenPopupIsNotDismissed() = runTest { + fun `onPageRefresh - page reloads on refresh with http error - popup is not dismissed`() = runTest { subject.viewState.test { subject.onPageLoaded(url = "https://www.example.com", httpErrorCodes = emptyList(), hasBrowserError = false) subject.onPageRefreshTriggeredByUser() @@ -390,7 +390,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenPopupIsShownThenTriggerCountIsIncremented() = runTest { + fun `onPageLoaded - popup shown - trigger count incremented`() = runTest { subject.viewState.test { subject.onPageLoaded(url = "https://www.example.com", httpErrorCodes = emptyList(), hasBrowserError = false) subject.onPageRefreshTriggeredByUser() @@ -411,7 +411,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenPopupTriggerCountIsZeroThenDoNotShowAgainOptionIsNotAvailable() = runTest { + fun `onPageLoaded - popup trigger count zero - do not show again option not available`() = runTest { dataStore.setPopupTriggerCount(0) subject.viewState.test { @@ -423,7 +423,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenPopupTriggerCountIsGreaterThanZeroThenDoNotShowAgainOptionIsAvailable() = runTest { + fun `onPageLoaded - popup trigger count greater than zero - do not show again option available`() = runTest { dataStore.setPopupTriggerCount(1) subject.viewState.test { @@ -435,7 +435,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenDoNotShowAgainIsClickedThenPopupIsNotShownAgain() = runTest { + fun `onUiEvent - do not show again clicked - popup is not shown again`() = runTest { dataStore.setPopupTriggerCount(1) subject.viewState.test { @@ -457,7 +457,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenPopupConditionsAreMetAndExperimentVariantIsControlThenPopupIsNotShown() = runTest { + fun `onPageLoaded - popup conditions met and experiment variant is control - not shown`() = runTest { dataStore.setExperimentVariant(CONTROL) subject.viewState.test { subject.onPageLoaded(url = "https://www.example.com", httpErrorCodes = emptyList(), hasBrowserError = false) @@ -468,7 +468,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenPopupConditionsAreMetAndExperimentVariantIsNullThenInitializesVariantWithRandomValue() = runTest { + fun `onPageLoaded - popup conditions met - initializes variant with random value`() = runTest { variantRandomizer.variant = CONTROL assertNull(dataStore.getExperimentVariant()) @@ -482,7 +482,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenExperimentVariantIsAssignedThenPixelIsSent() = runTest { + fun `onPageLoaded - experiment variant assigned - pixel sent`() = runTest { variantRandomizer.variant = CONTROL assertNull(dataStore.getExperimentVariant()) var variantIncludedInPixel: PrivacyProtectionsPopupExperimentVariant? = null @@ -501,7 +501,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenVariantIsAlreadyAssignedThenPixelIsNotSent() = runTest { + fun `onPageLoaded - variant already assigned - pixel not sent`() = runTest { dataStore.setExperimentVariant(TEST) subject.viewState.test { subject.onPageLoaded(url = "https://www.example.com", httpErrorCodes = emptyList(), hasBrowserError = false) @@ -514,7 +514,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenPopupIsTriggeredThenPixelIsSent() = runTest { + fun `onPageRefreshTriggeredByUser - popup triggered - pixel sent`() = runTest { subject.viewState.test { subject.onPageLoaded(url = "https://www.example.com", httpErrorCodes = emptyList(), hasBrowserError = false) subject.onPageRefreshTriggeredByUser() @@ -525,7 +525,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenPrivacyProtectionsDisableButtonIsClickedThenPixelIsSent() = runTest { + fun `onUiEvent - privacy protections disable button clicked - pixel sent`() = runTest { subject.viewState.test { subject.onPageLoaded(url = "https://www.example.com", httpErrorCodes = emptyList(), hasBrowserError = false) subject.onPageRefreshTriggeredByUser() @@ -539,7 +539,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenDismissButtonIsClickedThenPixelIsSent() = runTest { + fun `onUiEvent - dismiss button clicked - pixel sent`() = runTest { subject.viewState.test { subject.onPageLoaded(url = "https://www.example.com", httpErrorCodes = emptyList(), hasBrowserError = false) subject.onPageRefreshTriggeredByUser() @@ -553,7 +553,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenPopupIsDismissedViaClickOutsideThenPixelIsSent() = runTest { + fun `onUiEvent - popup dismissed via click outside - pixel sent`() = runTest { subject.viewState.test { subject.onPageLoaded(url = "https://www.example.com", httpErrorCodes = emptyList(), hasBrowserError = false) subject.onPageRefreshTriggeredByUser() @@ -567,7 +567,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenDoNotShowAgainButtonIsClickedThenPixelIsSent() = runTest { + fun `onUiEvent - do not show again button clicked - pixel sent`() = runTest { subject.viewState.test { subject.onPageLoaded(url = "https://www.example.com", httpErrorCodes = emptyList(), hasBrowserError = false) subject.onPageRefreshTriggeredByUser() @@ -581,7 +581,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenPrivacyDashboardIsOpenedThenPixelIsSent() = runTest { + fun `onUiEvent - privacy dashboard opened - pixel sent`() = runTest { subject.viewState.test { subject.onPageLoaded(url = "https://www.example.com", httpErrorCodes = emptyList(), hasBrowserError = false) subject.onPageRefreshTriggeredByUser() @@ -595,7 +595,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenPageIsRefreshedAndConditionsAreMetThenPixelIsSent() = runTest { + fun `onPageRefresh - view state updated - pixel sent`() = runTest { subject.viewState.test { subject.onPageLoaded(url = "https://www.example.com", httpErrorCodes = emptyList(), hasBrowserError = false) subject.onPageRefreshTriggeredByUser() @@ -606,7 +606,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenPageIsRefreshedAndFeatureIsDisabledAndThereIsNoExperimentVariantThenPixelIsNotSent() = runTest { + fun `onPageRefresh - feature disabled - no experiment variant - pixel not sent`() = runTest { featureFlag.enabled = false subject.viewState.test { subject.onPageLoaded(url = "https://www.example.com", httpErrorCodes = emptyList(), hasBrowserError = false) diff --git a/privacy-protections-popup/privacy-protections-popup-impl/src/test/java/com/duckduckgo/privacyprotectionspopup/impl/ProtectionsStateProviderTest.kt b/privacy-protections-popup/privacy-protections-popup-impl/src/test/java/com/duckduckgo/privacyprotectionspopup/impl/ProtectionsStateProviderTest.kt index 4a547b453813..429ea0508e79 100644 --- a/privacy-protections-popup/privacy-protections-popup-impl/src/test/java/com/duckduckgo/privacyprotectionspopup/impl/ProtectionsStateProviderTest.kt +++ b/privacy-protections-popup/privacy-protections-popup-impl/src/test/java/com/duckduckgo/privacyprotectionspopup/impl/ProtectionsStateProviderTest.kt @@ -62,12 +62,12 @@ class ProtectionsStateProviderTest { } @Test - fun whenContentBlockingIsEnabledAndDomainIsNotAnExceptionThenProtectionsAreEnabled() = runTest { + fun `areProtectionsEnabled - content blocking enabled - protections are enabled`() = runTest { assertTrue(areProtectionsEnabled(domain = "www.example.com")) } @Test - fun whenContentBlockingFeatureIsDisabledThenProtectionsAreDisabled() = runTest { + fun `isContentBlockingFeatureEnabled - are protections disabled`() = runTest { val domain = "www.example.com" whenever(featureToggle.isFeatureEnabled(PrivacyFeatureName.ContentBlockingFeatureName.value)).thenReturn(false) @@ -75,7 +75,7 @@ class ProtectionsStateProviderTest { } @Test - fun whenDomainIsOnContentBlockingExceptionListThenProtectionsAreDisabled() = runTest { + fun `isOnContentBlockingExceptionList - protections disabled`() = runTest { val domain = "www.example.com" whenever(contentBlocking.isAnException(domain)).thenReturn(true) @@ -83,7 +83,7 @@ class ProtectionsStateProviderTest { } @Test - fun whenDomainIsOnUnprotectedTemporaryExceptionListThenProtectionsAreDisabled() = runTest { + fun `isOnUnprotectedTemporaryExceptionList - are protections disabled`() = runTest { val domain = "www.example.com" whenever(unprotectedTemporary.isAnException(domain)).thenReturn(true) @@ -91,7 +91,7 @@ class ProtectionsStateProviderTest { } @Test - fun whenDomainIsInUserAllowlistThenProtectionsAreDisabled() = runTest { + fun `addDomainToUserAllowList - are protections disabled`() = runTest { val domain = "www.example.com" userAllowListRepository.addDomainToUserAllowList(domain) diff --git a/privacy-protections-popup/privacy-protections-popup-impl/src/test/java/com/duckduckgo/privacyprotectionspopup/impl/db/PopupDismissDomainRepositoryTest.kt b/privacy-protections-popup/privacy-protections-popup-impl/src/test/java/com/duckduckgo/privacyprotectionspopup/impl/db/PopupDismissDomainRepositoryTest.kt index e7c236f410e5..e87f57327904 100644 --- a/privacy-protections-popup/privacy-protections-popup-impl/src/test/java/com/duckduckgo/privacyprotectionspopup/impl/db/PopupDismissDomainRepositoryTest.kt +++ b/privacy-protections-popup/privacy-protections-popup-impl/src/test/java/com/duckduckgo/privacyprotectionspopup/impl/db/PopupDismissDomainRepositoryTest.kt @@ -59,13 +59,13 @@ class PopupDismissDomainRepositoryTest { } @Test - fun whenDatabaseIsEmptyThenReturnsNullDismissTimestamp() = runTest { + fun `getPopupDismissTime - database empty - returns null`() = runTest { val dismissedAt = subject.getPopupDismissTime("www.example.com").first() assertNull(dismissedAt) } @Test - fun whenDismissTimeIsStoredThenQueryReturnsCorrectValue() = runTest { + fun `setPopupDismissTime - query returns correct value`() = runTest { val domain = "www.example.com" val dismissAt = Instant.parse("2023-11-29T10:15:30.000Z") @@ -75,7 +75,7 @@ class PopupDismissDomainRepositoryTest { } @Test - fun whenDismissTimeIsSetMultipleTimesThenReturnsMostRecentlyStoredValue() = runTest { + fun `setPopupDismissTime - returns most recently stored value`() = runTest { val domain = "www.example.com" subject.setPopupDismissTime(domain, Instant.parse("2023-11-28T10:15:30.000Z")) subject.setPopupDismissTime(domain, Instant.parse("2023-11-29T10:15:30.000Z")) @@ -86,7 +86,7 @@ class PopupDismissDomainRepositoryTest { } @Test - fun whenDismissTimeIsSetForDifferentDomainsThenCorrectValueIsReturned() = runTest { + fun `setPopupDismissTime - different domains - correct value returned`() = runTest { val domain = "www.example.com" subject.setPopupDismissTime(domain, Instant.parse("2023-11-28T10:15:30.000Z")) subject.setPopupDismissTime("www.example2.com", Instant.parse("2023-11-29T10:15:30.000Z")) @@ -97,7 +97,7 @@ class PopupDismissDomainRepositoryTest { } @Test - fun whenRemoveEntriesInvokedThenCorrectDataIsDeleted() = runTest { + fun `removeEntries - set popup dismiss time - correct data deleted`() = runTest { subject.setPopupDismissTime("www.example1.com", Instant.parse("2023-11-28T10:15:30.000Z")) subject.setPopupDismissTime("www.example2.com", Instant.parse("2023-11-29T10:15:30.000Z")) subject.setPopupDismissTime("www.example3.com", Instant.parse("2023-12-01T10:00:00.000Z")) @@ -112,7 +112,7 @@ class PopupDismissDomainRepositoryTest { } @Test - fun whenRemoreAllEntriesIsInvokedThenAllDataIsDeleted() = runTest { + fun `removeAllEntries - all data deleted`() = runTest { subject.setPopupDismissTime("www.example1.com", Instant.parse("2023-11-28T10:15:30.000Z")) subject.setPopupDismissTime("www.example2.com", Instant.parse("2023-11-29T10:15:30.000Z")) subject.setPopupDismissTime("www.example3.com", Instant.parse("2023-12-01T10:00:00.000Z")) diff --git a/privacy-protections-popup/privacy-protections-popup-impl/src/test/java/com/duckduckgo/privacyprotectionspopup/impl/store/PrivacyProtectionsPopupDataStoreTest.kt b/privacy-protections-popup/privacy-protections-popup-impl/src/test/java/com/duckduckgo/privacyprotectionspopup/impl/store/PrivacyProtectionsPopupDataStoreTest.kt index 5b46ddaf9867..8577b0a146bc 100644 --- a/privacy-protections-popup/privacy-protections-popup-impl/src/test/java/com/duckduckgo/privacyprotectionspopup/impl/store/PrivacyProtectionsPopupDataStoreTest.kt +++ b/privacy-protections-popup/privacy-protections-popup-impl/src/test/java/com/duckduckgo/privacyprotectionspopup/impl/store/PrivacyProtectionsPopupDataStoreTest.kt @@ -54,12 +54,12 @@ class PrivacyProtectionsPopupDataStoreTest { private val subject: PrivacyProtectionsPopupDataStore = PrivacyProtectionsPopupDataStoreImpl(testDataStore) @Test - fun whenDatabaseIsEmptyThenReturnsNullDismissTimestamp() = runTest { + fun `getToggleUsageTimestamp - database empty - returns null`() = runTest { assertNull(subject.getToggleUsageTimestamp()) } @Test - fun whenDismissTimeIsStoredThenQueryReturnsCorrectValue() = runTest { + fun `setToggleUsageTimestamp - query returns correct value`() = runTest { val timestamp = Instant.parse("2023-11-29T10:15:30.000Z") subject.setToggleUsageTimestamp(timestamp) @@ -68,7 +68,7 @@ class PrivacyProtectionsPopupDataStoreTest { } @Test - fun whenDismissTimeIsSetMultipleTimesThenReturnsMostRecentlyStoredValue() = runTest { + fun `setToggleUsageTimestamp - returns most recently stored value`() = runTest { subject.setToggleUsageTimestamp(Instant.parse("2023-11-28T10:15:30.000Z")) subject.setToggleUsageTimestamp(Instant.parse("2023-11-29T10:15:30.000Z")) subject.setToggleUsageTimestamp(Instant.parse("2023-11-10T10:15:30.000Z")) @@ -78,12 +78,12 @@ class PrivacyProtectionsPopupDataStoreTest { } @Test - fun whenPopupTriggerCountIsNotInitializedThenReturnsZero() = runTest { + fun `getPopupTriggerCount - not initialized - returns zero`() = runTest { assertEquals(0, subject.getPopupTriggerCount()) } @Test - fun whenPopupTriggerCountIsStoredThenReturnsCorrectValue() = runTest { + fun `setPopupTriggerCount - returns correct value`() = runTest { val count = 123 subject.setPopupTriggerCount(count) val storedCount = subject.getPopupTriggerCount() @@ -91,23 +91,23 @@ class PrivacyProtectionsPopupDataStoreTest { } @Test - fun whenDoNotShowAgainIsNotInitializedThenReturnsFalse() = runTest { + fun `getDoNotShowAgain - not initialized - returns false`() = runTest { assertFalse(subject.getDoNotShowAgainClicked()) } @Test - fun whenDoNotShowAgainIsStoredThenReturnsCorrectValue() = runTest { + fun `setDoNotShowAgain - returns correct value`() = runTest { subject.setDoNotShowAgainClicked(clicked = true) assertTrue(subject.getDoNotShowAgainClicked()) } @Test - fun whenExperimentVariantIsNotInitializedThenReturnsNull() = runTest { + fun `getExperimentVariant - not initialized - null`() = runTest { assertNull(subject.getExperimentVariant()) } @Test - fun whenExperimentVariantIsStoredThenReturnsCorrectValue() = runTest { + fun `setExperimentVariant - returns correct value`() = runTest { subject.setExperimentVariant(CONTROL) assertEquals(CONTROL, subject.getExperimentVariant()) } diff --git a/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/AppRemoteMessagingRepositoryTest.kt b/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/AppRemoteMessagingRepositoryTest.kt index 0176d11ffbbc..457c7b5f07ec 100644 --- a/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/AppRemoteMessagingRepositoryTest.kt +++ b/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/AppRemoteMessagingRepositoryTest.kt @@ -76,7 +76,7 @@ class AppRemoteMessagingRepositoryTest { } @Test - fun whenAddMediumMessageThenMessageStored() = runTest { + fun `addMediumMessage - message stored`() = runTest { testee.activeMessage( RemoteMessage( id = "id", @@ -111,7 +111,7 @@ class AppRemoteMessagingRepositoryTest { } @Test - fun whenAddSmallMessageThenMessageStored() = runTest { + fun `addSmallMessage - message stored`() = runTest { testee.activeMessage( RemoteMessage( id = "id", @@ -144,7 +144,7 @@ class AppRemoteMessagingRepositoryTest { } @Test - fun whenAddBigSingleActionMessageThenMessageStored() = runTest { + fun `addBigSingleActionMessage - message stored`() = runTest { testee.activeMessage( RemoteMessage( id = "id", @@ -183,7 +183,7 @@ class AppRemoteMessagingRepositoryTest { } @Test - fun whenAddBigTwoActionMessageThenMessageStored() = runTest { + fun `addBigTwoActionMessage - message stored`() = runTest { testee.activeMessage( RemoteMessage( id = "id", @@ -226,7 +226,7 @@ class AppRemoteMessagingRepositoryTest { } @Test - fun whenAddPromoSingleActionMessageThenMessageStored() = runTest { + fun `addPromoSingleActionMessage - message stored`() = runTest { testee.activeMessage( RemoteMessage( id = "id", @@ -265,7 +265,7 @@ class AppRemoteMessagingRepositoryTest { } @Test - fun whenDismissMessageThenUpdateState() = runTest { + fun `dismissMessage - state updated`() = runTest { testee.activeMessage( RemoteMessage( id = "id", @@ -294,7 +294,7 @@ class AppRemoteMessagingRepositoryTest { } @Test - fun whenGetDismissedMessagesThenReturnDismissedMessageIds() = runTest { + fun `getDismissedMessages - return dismissed message ids`() = runTest { testee.activeMessage( RemoteMessage( id = "id", @@ -319,7 +319,7 @@ class AppRemoteMessagingRepositoryTest { } @Test - fun whenNewMessageAddedThenPreviousNonDismissedMessagesRemoved() = runTest { + fun `whenNewMessageAddedThenPreviousNonDismissedMessagesRemoved - active message removed`() = runTest { dao.insert( RemoteMessageEntity( id = "id", diff --git a/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/RealRemoteMessagingConfigProcessorTest.kt b/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/RealRemoteMessagingConfigProcessorTest.kt index 75e26fb89af2..8e41265d2f07 100644 --- a/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/RealRemoteMessagingConfigProcessorTest.kt +++ b/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/RealRemoteMessagingConfigProcessorTest.kt @@ -67,7 +67,7 @@ class RealRemoteMessagingConfigProcessorTest { } @Test - fun whenNewVersionThenEvaluate() = runTest { + fun `process - new version - evaluate`() = runTest { whenever(remoteMessagingConfigRepository.get()).thenReturn( aRemoteMessagingConfig(version = 0L), ) @@ -78,7 +78,7 @@ class RealRemoteMessagingConfigProcessorTest { } @Test - fun whenSameVersionThenDoNothing() = runTest { + fun `process - same version - do nothing`() = runTest { val dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss") whenever(remoteMessagingConfigRepository.get()).thenReturn( aRemoteMessagingConfig( @@ -93,7 +93,7 @@ class RealRemoteMessagingConfigProcessorTest { } @Test - fun whenSameVersionButExpiredThenEvaluate() = runTest { + fun `process - same version but expired - evaluate`() = runTest { val dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss") whenever(remoteMessagingConfigRepository.get()).thenReturn( @@ -109,7 +109,7 @@ class RealRemoteMessagingConfigProcessorTest { } @Test - fun whenSameVersionButInvalidatedThenEvaluate() = runTest { + fun `process - same version invalidated - evaluate`() = runTest { whenever(remoteMessagingConfigRepository.get()).thenReturn( aRemoteMessagingConfig( version = 1L, diff --git a/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/RemoteMessagingConfigJsonMapperTest.kt b/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/RemoteMessagingConfigJsonMapperTest.kt index ad79faf42c7d..213c7d7d7670 100644 --- a/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/RemoteMessagingConfigJsonMapperTest.kt +++ b/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/RemoteMessagingConfigJsonMapperTest.kt @@ -51,7 +51,7 @@ class RemoteMessagingConfigJsonMapperTest { } @Test - fun whenValidJsonParsedThenMessagesMappedIntoRemoteConfig() = runTest { + fun `mapConfig - valid json parsed - messages mapped into remote config`() = runTest { val result = getConfigFromJson("json/remote_messaging_config.json") val testee = RemoteMessagingConfigJsonMapper(appBuildConfig, jsonMatchingAttributeMappers, messageActionPlugins) @@ -118,7 +118,7 @@ class RemoteMessagingConfigJsonMapperTest { } @Test - fun whenValidJsonParsedThenRulesMappedIntoRemoteConfig() = runTest { + fun `whenValidJsonParsedThenRulesMappedIntoRemoteConfig - remote config mapped`() = runTest { val result = getConfigFromJson("json/remote_messaging_config.json") val testee = RemoteMessagingConfigJsonMapper(appBuildConfig, jsonMatchingAttributeMappers, messageActionPlugins) @@ -148,7 +148,7 @@ class RemoteMessagingConfigJsonMapperTest { } @Test - fun whenJsonMessagesHaveUnknownTypesThenMessagesNotMappedIntoConfig() = runTest { + fun `map - json messages have unknown types - not mapped into config`() = runTest { val result = getConfigFromJson("json/remote_messaging_config_unsupported_items.json") val testee = RemoteMessagingConfigJsonMapper(appBuildConfig, jsonMatchingAttributeMappers, messageActionPlugins) @@ -159,7 +159,7 @@ class RemoteMessagingConfigJsonMapperTest { } @Test - fun whenJsonMessagesHaveUnknownTypesThenRulesMappedIntoConfig() = runTest { + fun `map - json messages have unknown types - rules mapped into config`() = runTest { val result = getConfigFromJson("json/remote_messaging_config_unsupported_items.json") val testee = RemoteMessagingConfigJsonMapper(appBuildConfig, jsonMatchingAttributeMappers, messageActionPlugins) @@ -176,7 +176,7 @@ class RemoteMessagingConfigJsonMapperTest { } @Test - fun whenJsonMessagesMalformedOrMissingInformationThenMessagesNotParsedIntoConfig() = runTest { + fun `getConfigFromJson - json messages malformed or missing information - not parsed into config`() = runTest { val result = getConfigFromJson("json/remote_messaging_config_malformed.json") val testee = RemoteMessagingConfigJsonMapper(appBuildConfig, jsonMatchingAttributeMappers, messageActionPlugins) @@ -197,7 +197,7 @@ class RemoteMessagingConfigJsonMapperTest { } @Test - fun whenJsonMatchingAttributesMalformedThenParsedAsUnknownIntoConfig() = runTest { + fun `map - json malformed - parsed as unknown into config`() = runTest { val result = getConfigFromJson("json/remote_messaging_config_malformed.json") val testee = RemoteMessagingConfigJsonMapper(appBuildConfig, jsonMatchingAttributeMappers, messageActionPlugins) @@ -212,7 +212,7 @@ class RemoteMessagingConfigJsonMapperTest { } @Test - fun whenUnknownMatchingAttributeDoesNotProvideFallbackThenFallbackIsNull() = runTest { + fun `map - unknown matching attribute does not provide fallback - fallback is null`() = runTest { val result = getConfigFromJson("json/remote_messaging_config_malformed.json") val testee = RemoteMessagingConfigJsonMapper(appBuildConfig, jsonMatchingAttributeMappers, messageActionPlugins) diff --git a/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/RemoteMessagingConfigMatcherTest.kt b/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/RemoteMessagingConfigMatcherTest.kt index a99a6f5a97d4..81b608a162b9 100644 --- a/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/RemoteMessagingConfigMatcherTest.kt +++ b/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/RemoteMessagingConfigMatcherTest.kt @@ -63,7 +63,7 @@ class RemoteMessagingConfigMatcherTest { ) @Test - fun whenEmptyConfigThenReturnNull() = runBlocking { + fun `evaluate - config empty - null`() = runBlocking { val emptyRemoteConfig = RemoteConfig(messages = emptyList(), rules = emptyList()) val message = testee.evaluate(emptyRemoteConfig) @@ -72,7 +72,7 @@ class RemoteMessagingConfigMatcherTest { } @Test - fun whenNoMatchingRulesThenReturnFirstMessage() = runBlocking { + fun `evaluate - no matching rules - return first message`() = runBlocking { val noRulesRemoteConfig = RemoteConfig(messages = listOf(aSmallMessage()), rules = emptyList()) val message = testee.evaluate(noRulesRemoteConfig) @@ -81,7 +81,7 @@ class RemoteMessagingConfigMatcherTest { } @Test - fun whenNotExistingRuleThenReturnSkipMessage() = runBlocking { + fun `evaluate - no existing rule - skip message`() = runBlocking { val noRulesRemoteConfig = RemoteConfig( messages = listOf( aSmallMessage(matchingRules = rules(1)), @@ -96,7 +96,7 @@ class RemoteMessagingConfigMatcherTest { } @Test - fun whenNoMessagesThenReturnNull() = runBlocking { + fun `evaluate - no messages - return null`() = runBlocking { val noMessagesRemoteConfig = RemoteConfig( messages = emptyList(), rules = listOf(rule(id = 1, matchingAttributes = arrayOf(Api(max = 19)))), @@ -108,7 +108,7 @@ class RemoteMessagingConfigMatcherTest { } @Test - fun whenDeviceDoesNotMatchMessageRulesThenReturnNull() = runBlocking { + fun `evaluate - device does not match message rules - return null`() = runBlocking { givenDeviceMatches() val message = testee.evaluate( @@ -125,7 +125,7 @@ class RemoteMessagingConfigMatcherTest { } @Test - fun whenNoMatchingRulesThenReturnFirstNonExcludedMessage() = runBlocking { + fun `evaluate - no matching rules - return first non-excluded message`() = runBlocking { givenDeviceMatches(Api(max = 19), Locale(value = listOf("en-US")), EmailEnabled(value = true)) val message = testee.evaluate( @@ -146,7 +146,7 @@ class RemoteMessagingConfigMatcherTest { } @Test - fun whenMatchingMessageShouldBeExcludedThenReturnNull() = runBlocking { + fun `evaluate - device matches - return null`() = runBlocking { givenDeviceMatches(Api(max = 19), Locale(value = listOf("en-US"))) val message = testee.evaluate( @@ -163,7 +163,7 @@ class RemoteMessagingConfigMatcherTest { } @Test - fun whenMatchingMessageShouldBeExcludedByOneOfMultipleRulesThenReturnNull() = runBlocking { + fun `evaluate - multiple rules - returns null`() = runBlocking { givenDeviceMatches(Api(max = 19), EmailEnabled(value = true), Bookmarks(max = 10)) val message = testee.evaluate( @@ -189,7 +189,7 @@ class RemoteMessagingConfigMatcherTest { } @Test - fun whenMultipleMatchingMessagesAndSomeExcludedThenReturnFirstNonExcludedMatch() = runBlocking { + fun `evaluate - multiple matching messages and some excluded - return first non-excluded match`() = runBlocking { givenDeviceMatches(Api(max = 19), Locale(value = listOf("en-US"))) val message = testee.evaluate( @@ -210,7 +210,7 @@ class RemoteMessagingConfigMatcherTest { } @Test - fun whenMessageMatchesAndExclusionRuleFailsThenReturnMessage() = runBlocking { + fun `evaluate - message matches and exclusion rule fails - return message`() = runBlocking { givenDeviceMatches(Api(max = 19), EmailEnabled(value = true)) val message = testee.evaluate( @@ -229,7 +229,7 @@ class RemoteMessagingConfigMatcherTest { } @Test - fun whenDeviceMatchesMessageRulesThenReturnFirstMatch() = runBlocking { + fun `evaluate - device matches message rules - returns first match`() = runBlocking { givenDeviceMatches(Api(max = 19)) val message = testee.evaluate( @@ -243,7 +243,7 @@ class RemoteMessagingConfigMatcherTest { } @Test - fun whenDeviceMatchesMessageRulesForMultipleMessagesThenReturnFirstMatch() = runBlocking { + fun `evaluate - device matches multiple messages - returns first match`() = runBlocking { givenDeviceMatches(Api(max = 19)) val message = testee.evaluate( @@ -260,7 +260,7 @@ class RemoteMessagingConfigMatcherTest { } @Test - fun whenDeviceMatchesMessageRulesForOneOfMultipleMessagesThenReturnMatch() = runBlocking { + fun `evaluate - device matches - return match`() = runBlocking { givenDeviceMatches(Api(max = 19), EmailEnabled(value = true)) val message = testee.evaluate( @@ -280,7 +280,7 @@ class RemoteMessagingConfigMatcherTest { } @Test - fun whenUserDismissedMessagesAndDeviceMatchesMultipleMessagesThenReturnFistMatchNotDismissed() = runBlocking { + fun `evaluate - user dismissed messages and device matches multiple messages - returns first match not dismissed`() = runBlocking { givenDeviceMatches(Api(max = 19), EmailEnabled(value = true)) givenUserDismissed("1") val rules = listOf( @@ -301,7 +301,7 @@ class RemoteMessagingConfigMatcherTest { } @Test - fun whenDeviceMatchesAnyRuleThenReturnFirstMatch() = runBlocking { + fun `evaluate - device matches any rule - return first match`() = runBlocking { givenDeviceMatches(Api(max = 19), Locale(value = listOf("en-US"))) val message = testee.evaluate( @@ -318,7 +318,7 @@ class RemoteMessagingConfigMatcherTest { } @Test - fun whenDeviceDoesMatchAnyRuleThenReturnNull() = runBlocking { + fun `evaluate - device matches any rule - return null`() = runBlocking { givenDeviceMatches(Locale(value = listOf("en-US")), Api(max = 19)) val message = testee.evaluate( @@ -338,7 +338,7 @@ class RemoteMessagingConfigMatcherTest { } @Test - fun whenUnknownRuleFailsThenReturnNull() = runBlocking { + fun `evaluate - unknown rule fails - return null`() = runBlocking { val message = testee.evaluate( RemoteConfig( messages = listOf( @@ -355,7 +355,7 @@ class RemoteMessagingConfigMatcherTest { } @Test - fun whenUnknownRuleMatchesThenReturnFirstMatch() = runBlocking { + fun `evaluate - unknown rule matches - return first match`() = runBlocking { val message = testee.evaluate( RemoteConfig( messages = listOf( @@ -372,7 +372,7 @@ class RemoteMessagingConfigMatcherTest { } @Test - fun whenDeviceMatchesMessageRulesAndPartOfPercentileThenReturnMessage() = runBlocking { + fun `evaluate - device matches message rules and part of percentile - returns message`() = runBlocking { givenDeviceMatches(Api(max = 19)) cohortDao.insert(RemoteMessagingCohort(messageId = "message1", percentile = 0.1f)) @@ -387,7 +387,7 @@ class RemoteMessagingConfigMatcherTest { } @Test - fun whenDeviceMatchesMessageRulesButOutOfPercentileThenReturnNull() = runBlocking { + fun `evaluate - device matches message rules but out of percentile - return null`() = runBlocking { givenDeviceMatches(Api(max = 19)) cohortDao.insert(RemoteMessagingCohort(messageId = "message1", percentile = 0.5f)) @@ -419,7 +419,7 @@ class RemoteMessagingConfigMatcherTest { } @Test - fun whenMatchingMessageShouldBeExcludedButOutOfPercentileThenReturnMessage() = runBlocking { + fun `evaluate - matching message excluded but out of percentile - return message`() = runBlocking { givenDeviceMatches(Locale(value = listOf("en-US"))) cohortDao.insert(RemoteMessagingCohort(messageId = "message1", percentile = 0.5f)) diff --git a/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/matchers/AndroidAppAttributeMatcherTest.kt b/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/matchers/AndroidAppAttributeMatcherTest.kt index 32c1adedf054..fb12c59e30b6 100644 --- a/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/matchers/AndroidAppAttributeMatcherTest.kt +++ b/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/matchers/AndroidAppAttributeMatcherTest.kt @@ -35,7 +35,7 @@ class AndroidAppAttributeMatcherTest { private val testee = AndroidAppAttributeMatcher(appProperties, appBuildConfig) @Test - fun whenFlavorMatchesThenReturnMatch() = runTest { + fun `evaluate - flavor matches - returns match`() = runTest { givenDeviceProperties(flavor = INTERNAL) val result = testee.evaluate( @@ -46,7 +46,7 @@ class AndroidAppAttributeMatcherTest { } @Test - fun whenFlavorDoesNotMatchThenReturnFail() = runTest { + fun `evaluate - flavor does not match - return fail`() = runTest { givenDeviceProperties(flavor = INTERNAL) val result = testee.evaluate( @@ -57,7 +57,7 @@ class AndroidAppAttributeMatcherTest { } @Test - fun whenAppIdMatchesThenReturnMatch() = runTest { + fun `evaluate - appId matches - returns match`() = runTest { givenDeviceProperties(appId = "com.duckduckgo.mobile.android") val result = testee.evaluate( @@ -68,7 +68,7 @@ class AndroidAppAttributeMatcherTest { } @Test - fun whenAppIdDoesNotMatchThenReturnFail() = runTest { + fun `evaluate - appId does not match - return fail`() = runTest { givenDeviceProperties(appId = "com.duckduckgo.mobile.android") val result = testee.evaluate( @@ -79,7 +79,7 @@ class AndroidAppAttributeMatcherTest { } @Test - fun whenAppVersionEqualOrLowerThanMaxThenReturnMatch() = runTest { + fun `evaluate - app version equal or lower than max - return match`() = runTest { givenDeviceProperties(appVersion = "5.100.0") val result = testee.evaluate( @@ -90,7 +90,7 @@ class AndroidAppAttributeMatcherTest { } @Test - fun whenAppVersionGreaterThanMaxThenReturnFail() = runTest { + fun `evaluate - app version greater than max - return fail`() = runTest { givenDeviceProperties(appVersion = "5.100.0") val result = testee.evaluate( @@ -101,7 +101,7 @@ class AndroidAppAttributeMatcherTest { } @Test - fun whenAppVersionEqualOrGreaterThanMinThenReturnMatch() = runTest { + fun `evaluate - app version equal or greater than min - return match`() = runTest { givenDeviceProperties(appVersion = "5.100.0") val result = testee.evaluate( @@ -112,7 +112,7 @@ class AndroidAppAttributeMatcherTest { } @Test - fun whenAppVersionLowerThanMinThenReturnFail() = runTest { + fun `evaluate - app version lower than min - return fail`() = runTest { givenDeviceProperties(appVersion = "5.99.0") val result = testee.evaluate( @@ -123,7 +123,7 @@ class AndroidAppAttributeMatcherTest { } @Test - fun whenAppVersionInRangeThenReturnMatch() = runTest { + fun `evaluate - app version in range - returns match`() = runTest { givenDeviceProperties(appVersion = "5.150.0") val result = testee.evaluate( @@ -134,7 +134,7 @@ class AndroidAppAttributeMatcherTest { } @Test - fun whenAppVersionNotInRangeThenReturnMatch() = runTest { + fun `evaluate - app version not in range - return match`() = runTest { givenDeviceProperties(appVersion = "5.000.0") val result = testee.evaluate( @@ -145,7 +145,7 @@ class AndroidAppAttributeMatcherTest { } @Test - fun whenAppVersionSameAsDeviceThenReturnMatch() = runTest { + fun `evaluate - app version same as device - return match`() = runTest { givenDeviceProperties(appVersion = "5.100.0") val result = testee.evaluate( @@ -156,7 +156,7 @@ class AndroidAppAttributeMatcherTest { } @Test - fun whenAppVersionDifferentToDeviceThenReturnFail() = runTest { + fun `evaluate - app version different - return fail`() = runTest { givenDeviceProperties(appVersion = "5.99.0") val result = testee.evaluate( @@ -167,7 +167,7 @@ class AndroidAppAttributeMatcherTest { } @Test - fun whenAtbMatchesThenReturnMatch() = runTest { + fun `evaluate - atb matches - return match`() = runTest { givenDeviceProperties(atb = "v105-2") val result = testee.evaluate( @@ -178,7 +178,7 @@ class AndroidAppAttributeMatcherTest { } @Test - fun whenAtbDoesNotMatchThenReturnFail() = runTest { + fun `evaluate - atb does not match - return fail`() = runTest { givenDeviceProperties(atb = "v105-2") val result = testee.evaluate( @@ -189,7 +189,7 @@ class AndroidAppAttributeMatcherTest { } @Test - fun whenAppAtbMatchesThenReturnMatch() = runTest { + fun `evaluate - app atb matches - returns match`() = runTest { givenDeviceProperties(appAtb = "v105-2") val result = testee.evaluate( @@ -200,7 +200,7 @@ class AndroidAppAttributeMatcherTest { } @Test - fun whenAppAtbDoesNotMatchThenReturnFail() = runTest { + fun `evaluate - app atb does not match - return fail`() = runTest { givenDeviceProperties(appAtb = "v105-2") val result = testee.evaluate( @@ -211,7 +211,7 @@ class AndroidAppAttributeMatcherTest { } @Test - fun whenSearchAtbMatchesThenReturnMatch() = runTest { + fun `evaluate - search atb matches - returns match`() = runTest { givenDeviceProperties(searchAtb = "v105-2") val result = testee.evaluate( @@ -222,7 +222,7 @@ class AndroidAppAttributeMatcherTest { } @Test - fun whenSearchAtbDoesNotMatchThenReturnFail() = runTest { + fun `evaluate - search atb does not match - return fail`() = runTest { givenDeviceProperties(searchAtb = "v105-2") val result = testee.evaluate( @@ -233,7 +233,7 @@ class AndroidAppAttributeMatcherTest { } @Test - fun whenExpVariantMatchesThenReturnMatch() = runTest { + fun `evaluate - exp variant matches - return match`() = runTest { givenDeviceProperties(expVariant = "zo") val result = testee.evaluate( @@ -244,7 +244,7 @@ class AndroidAppAttributeMatcherTest { } @Test - fun whenExpVariantDoesNotMatchThenReturnFail() = runTest { + fun `evaluate - exp variant does not match - return fail`() = runTest { givenDeviceProperties(expVariant = "zo") val result = testee.evaluate( @@ -255,7 +255,7 @@ class AndroidAppAttributeMatcherTest { } @Test - fun whenInstalledGPlayMatchesThenReturnMatch() = runTest { + fun `evaluate - installed GPlay matches - returns match`() = runTest { givenDeviceProperties(installedGPlay = true) val result = testee.evaluate( @@ -266,7 +266,7 @@ class AndroidAppAttributeMatcherTest { } @Test - fun whenInstalledGPlayDoesNotMatchThenReturnFail() = runTest { + fun `evaluate - installed G Play does not match - return fail`() = runTest { givenDeviceProperties(installedGPlay = false) val result = testee.evaluate( diff --git a/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/matchers/DeviceAttributeMatcherTest.kt b/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/matchers/DeviceAttributeMatcherTest.kt index eb2aa282f3b1..1d3e7354318d 100644 --- a/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/matchers/DeviceAttributeMatcherTest.kt +++ b/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/matchers/DeviceAttributeMatcherTest.kt @@ -34,7 +34,7 @@ class DeviceAttributeMatcherTest { private val testee = DeviceAttributeMatcher(appBuildConfig, appProperties) @Test - fun whenDeviceMatchesLocaleThenReturnMatch() = runTest { + fun `evaluate - device matches locale - returns match`() = runTest { givenDeviceProperties(locale = java.util.Locale.US) val result = testee.evaluate( @@ -45,7 +45,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenDeviceMatchesAnyLocaleThenReturnMatch() = runTest { + fun `evaluate - device matches any locale - returns match`() = runTest { givenDeviceProperties(locale = java.util.Locale.US) val result = testee.evaluate( @@ -56,7 +56,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenDeviceDoesNotMatchLocaleThenReturnFail() = runTest { + fun `evaluate - device does not match locale - return fail`() = runTest { givenDeviceProperties(locale = java.util.Locale.FRANCE) val result = testee.evaluate( @@ -67,7 +67,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenLocaleMatchingAttributeIsEmptyThenReturnFail() = runTest { + fun `evaluate - locale matching attribute empty - return fail`() = runTest { givenDeviceProperties(locale = java.util.Locale.US) val result = testee.evaluate( @@ -78,7 +78,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenDeviceSameAsOsApiLevelThenReturnMatch() = runTest { + fun `evaluate - device same as os api level - return match`() = runTest { givenDeviceProperties(apiLevel = 21) val result = testee.evaluate(Api(value = 21)) @@ -87,7 +87,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenDeviceDifferentAsOsApiLevelThenReturnFail() = runTest { + fun `evaluate - device different as os api level - return fail`() = runTest { givenDeviceProperties(apiLevel = 21) val result = testee.evaluate(Api(value = 19)) @@ -96,7 +96,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenDeviceMatchesOsApiLevelThenReturnMatch() = runTest { + fun `evaluate - device matches os api level - returns match`() = runTest { givenDeviceProperties(apiLevel = 21) val result = testee.evaluate(Api(min = 19)) @@ -105,7 +105,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenDeviceMatchesOsApiLevelRangeThenReturnMatch() = runTest { + fun `evaluate - device matches os api level range - returns match`() = runTest { givenDeviceProperties(apiLevel = 21) val result = testee.evaluate(Api(min = 19, max = 23)) @@ -114,7 +114,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenDeviceDoesNotMatchesOsApiLevelRangeThenReturnMatch() = runTest { + fun `evaluate - device does not match os api level range - returns match`() = runTest { givenDeviceProperties(apiLevel = 23) val result = testee.evaluate(Api(min = 19, max = 21)) @@ -123,7 +123,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenDeviceDoesNotMatchOsApiLevelThenReturnFail() = runTest { + fun `evaluate - device does not match os api level - return fail`() = runTest { givenDeviceProperties(apiLevel = 21) val result = testee.evaluate(Api(max = 19)) @@ -132,7 +132,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenOsApiMatchingAttributeEmptyThenReturnFail() = runTest { + fun `evaluate - os api matching attribute empty - return fail`() = runTest { givenDeviceProperties(apiLevel = 21) val result = testee.evaluate(Api()) @@ -141,7 +141,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenDeviceWVSameAsWVVersionThenReturnMatch() = runTest { + fun `evaluate - device WV same as WV version - return match`() = runTest { givenDeviceProperties(webView = "96.0.4664.104") val result = testee.evaluate(WebView(value = "96.0.4664.104")) @@ -150,7 +150,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenDeviceWVDifferentAsWVVersionThenReturnMatch() = runTest { + fun `evaluate - device WV different as WV version - return match`() = runTest { givenDeviceProperties(webView = "96.0.4664.104") val result = testee.evaluate(WebView(value = "96.0.4664.105")) @@ -159,7 +159,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenDeviceWVLowerThanMaxWVVersionThenReturnMatch() = runTest { + fun `evaluate - device WV lower than max WV version - returns match`() = runTest { givenDeviceProperties(webView = "96.0.4664.104") val result = testee.evaluate(WebView(max = "96.0.4665.101")) @@ -168,7 +168,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenDeviceWVGreaterThanMaxWVVersionThenReturnFail() = runTest { + fun `evaluate - device WV greater than max WV version - return fail`() = runTest { givenDeviceProperties(webView = "96.0.4665.0") val result = testee.evaluate(WebView(max = "96.0.4664.101")) @@ -177,7 +177,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenDeviceWVGreaterThanMinWVVersionThenReturnMatch() = runTest { + fun `evaluate - device WV greater than min WV version - returns match`() = runTest { givenDeviceProperties(webView = "96.0.4665.104") val result = testee.evaluate(WebView(min = "96.0.4664.101")) @@ -186,7 +186,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenDeviceWVLowerThanMinWVVersionThenReturnFail() = runTest { + fun `evaluate - device WV lower than min WV version - return fail`() = runTest { givenDeviceProperties(webView = "96.0.4664.104") val result = testee.evaluate(WebView(min = "96.1.4664.104")) @@ -195,7 +195,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenDeviceMatchesWebViewMaxVersionThenReturnMatch() = runTest { + fun `evaluate - device matches web view max version - returns match`() = runTest { givenDeviceProperties(webView = "96.0.4664.104") val result = testee.evaluate(WebView(max = "96.0.4664.104")) @@ -204,7 +204,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenDeviceMatchesWebViewMinVersionThenReturnMatch() = runTest { + fun `evaluate - device matches web view min version - returns match`() = runTest { givenDeviceProperties(webView = "96.0.4664.104") val result = testee.evaluate(WebView(min = "96.0.4664.104")) @@ -213,7 +213,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenDeviceWVMatchesMaxSimplifiedWVVersionThenReturnMatch() = runTest { + fun `evaluate - device WV matches max simplified WV version - returns match`() = runTest { givenDeviceProperties(webView = "96.0.4664.104") val result = testee.evaluate(WebView(max = "96")) @@ -222,7 +222,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenDeviceWVMatchesMinSimplifiedWVVersionThenReturnMatch() = runTest { + fun `evaluate - device WV matches min simplified WV version - returns match`() = runTest { givenDeviceProperties(webView = "96.0.4664.104") val result = testee.evaluate(WebView(min = "96")) @@ -231,7 +231,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenDeviceWVGreaterThanMaxSimplifiedWVVersionThenReturnFail() = runTest { + fun `evaluate - device WV greater than max simplified WV version - return fail`() = runTest { givenDeviceProperties(webView = "96.0.4664.104") val result = testee.evaluate(WebView(max = "95")) @@ -240,7 +240,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenDeviceWVLowerThanMinSimplifiedWVVersionThenReturnFail() = runTest { + fun `evaluate - device WV lower than min simplified WV version - return fail`() = runTest { givenDeviceProperties(webView = "96.0.4664.104") val result = testee.evaluate(WebView(min = "97")) @@ -249,7 +249,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenDeviceDoesNotProvideWVVersionsThenReturnFail() = runTest { + fun `evaluate - device does not provide WV versions - return fail`() = runTest { givenDeviceProperties(webView = "") val result = testee.evaluate(WebView(min = "97")) @@ -258,7 +258,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenDeviceWVVersionHasUnknownFormatThenReturnFail() = runTest { + fun `evaluate - device WV version unknown format - return fail`() = runTest { givenDeviceProperties(webView = "test93.91.0") val result = testee.evaluate(WebView(min = "91")) @@ -267,7 +267,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenDeviceWVVersionHasUnknownFormatInBetweenThenReturnFail() = runTest { + fun `evaluate - device WV version has unknown format in between - return fail`() = runTest { givenDeviceProperties(webView = "93.91.test.0") val result = testee.evaluate(WebView(min = "91")) @@ -276,7 +276,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenDeviceWVVersionHasUnknownFormatAtEndThenReturnFail() = runTest { + fun `evaluate - device WV version has unknown format at end - return fail`() = runTest { givenDeviceProperties(webView = "93.91.0.test") val result = testee.evaluate(WebView(min = "91")) @@ -285,7 +285,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenEmptyWebViewMatchingAttributeThenReturnFail() = runTest { + fun `evaluate - empty web view matching attribute - return fail`() = runTest { givenDeviceProperties(webView = "96.0.4664.104") val result = testee.evaluate(WebView()) diff --git a/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/matchers/InteractedWithMessageMatcherTest.kt b/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/matchers/InteractedWithMessageMatcherTest.kt index d871f62c1abf..73d4c3e27228 100644 --- a/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/matchers/InteractedWithMessageMatcherTest.kt +++ b/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/matchers/InteractedWithMessageMatcherTest.kt @@ -34,7 +34,7 @@ class InteractedWithMessageMatcherTest { private val remoteMessagingRepository: RemoteMessagingRepository = mock() @Test - fun whenMapKeyIsInteractedWithMessageThenReturnMatchingAttribute() = runTest { + fun `map - map key interacted with message - matching attribute`() = runTest { val matcher = InteractedWithMessageMatcher(remoteMessagingRepository) val jsonMatchingAttribute = JsonMatchingAttribute(value = listOf("1", "2", "3")) val result = matcher.map("interactedWithMessage", jsonMatchingAttribute) @@ -43,7 +43,7 @@ class InteractedWithMessageMatcherTest { } @Test - fun whenJsonMatchingAttributeValueIsNullThenReturnNull() = runTest { + fun `map - json matching attribute value is null - return null`() = runTest { val matcher = InteractedWithMessageMatcher(remoteMessagingRepository) val jsonMatchingAttribute = JsonMatchingAttribute(value = null) val result = matcher.map("interactedWithMessage", jsonMatchingAttribute) @@ -51,7 +51,7 @@ class InteractedWithMessageMatcherTest { } @Test - fun whenJsonMatchingAttributeValueIsEmptyThenReturnNull() = runTest { + fun `map - json matching attribute value is empty - return null`() = runTest { val matcher = InteractedWithMessageMatcher(remoteMessagingRepository) val jsonMatchingAttribute = JsonMatchingAttribute(value = emptyList()) val result = matcher.map("interactedWithMessage", jsonMatchingAttribute) @@ -59,7 +59,7 @@ class InteractedWithMessageMatcherTest { } @Test - fun whenJsonMatchingAttributeValueIsNotListThenReturnNull() = runTest { + fun `map - json matching attribute not list - return null`() = runTest { val matcher = InteractedWithMessageMatcher(remoteMessagingRepository) val jsonMatchingAttribute = JsonMatchingAttribute(value = 1) val result = matcher.map("interactedWithMessage", jsonMatchingAttribute) @@ -67,7 +67,7 @@ class InteractedWithMessageMatcherTest { } @Test - fun whenDismissedMessageIdMatchesThenReturnTrue() = runTest { + fun `evaluate - message id matches - true`() = runTest { givenMessageIdDismissed(listOf("1", "2", "3")) val matcher = InteractedWithMessageMatcher(remoteMessagingRepository) val matchingAttribute = InteractedWithMessageMatchingAttribute(listOf("1", "2", "3")) @@ -76,7 +76,7 @@ class InteractedWithMessageMatcherTest { } @Test - fun whenOneDismissedMessageIdMatchesThenReturnTrue() = runTest { + fun `evaluate - one dismissed message id matches - true`() = runTest { givenMessageIdDismissed(listOf("1", "2", "3")) val matcher = InteractedWithMessageMatcher(remoteMessagingRepository) val matchingAttribute = InteractedWithMessageMatchingAttribute(listOf("1", "4", "5")) @@ -85,7 +85,7 @@ class InteractedWithMessageMatcherTest { } @Test - fun whenNoDismissedMessageIdMatchesThenReturnFalse() = runTest { + fun `evaluate - no dismissed message id matches - false`() = runTest { givenMessageIdDismissed(listOf("1", "2", "3")) val matcher = InteractedWithMessageMatcher(remoteMessagingRepository) val matchingAttribute = InteractedWithMessageMatchingAttribute(listOf("4", "5")) @@ -94,7 +94,7 @@ class InteractedWithMessageMatcherTest { } @Test(expected = AssertionError::class) - fun whenEmptyListInMatchingAttributeThenReturnException() = runTest { + fun `givenMessageIdDismissed - empty list in matching attribute - return exception`() = runTest { givenMessageIdDismissed(listOf("1", "2", "3")) val matcher = InteractedWithMessageMatcher(remoteMessagingRepository) val matchingAttribute = InteractedWithMessageMatchingAttribute(emptyList()) diff --git a/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/matchers/UserAttributeMatcherTest.kt b/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/matchers/UserAttributeMatcherTest.kt index e2a368534de1..c445f123beea 100644 --- a/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/matchers/UserAttributeMatcherTest.kt +++ b/remote-messaging/remote-messaging-impl/src/test/java/com/duckduckgo/remote/messaging/impl/matchers/UserAttributeMatcherTest.kt @@ -34,7 +34,7 @@ class UserAttributeMatcherTest { private val testee = UserAttributeMatcher(userBrowserProperties) @Test - fun whenAppThemeMatchesThenReturnMatch() = runTest { + fun `evaluate - app theme matches - returns match`() = runTest { givenBrowserProperties(appTheme = DuckDuckGoTheme.SYSTEM_DEFAULT) val result = testee.evaluate( @@ -45,7 +45,7 @@ class UserAttributeMatcherTest { } @Test - fun whenAppThemeDoesNotMatchThenReturnFail() = runTest { + fun `evaluate - app theme does not match - return fail`() = runTest { givenBrowserProperties(appTheme = DuckDuckGoTheme.SYSTEM_DEFAULT) val result = testee.evaluate( @@ -56,7 +56,7 @@ class UserAttributeMatcherTest { } @Test - fun whenBookmarksMatchesThenReturnMatch() = runTest { + fun `evaluate - bookmarks matches - return match`() = runTest { givenBrowserProperties(bookmarks = 10L) val result = testee.evaluate( @@ -67,7 +67,7 @@ class UserAttributeMatcherTest { } @Test - fun whenBookmarksDoesNotMatchThenReturnFail() = runTest { + fun `evaluate - bookmarks does not match - return fail`() = runTest { givenBrowserProperties(bookmarks = 10L) val result = testee.evaluate( @@ -78,7 +78,7 @@ class UserAttributeMatcherTest { } @Test - fun whenBookmarksEqualOrLowerThanMaxThenReturnMatch() = runTest { + fun `evaluate - bookmarks equal or lower than max - return match`() = runTest { givenBrowserProperties(bookmarks = 10L) val result = testee.evaluate( @@ -89,7 +89,7 @@ class UserAttributeMatcherTest { } @Test - fun whenBookmarksGreaterThanMaxThenReturnFail() = runTest { + fun `evaluate - bookmarks greater than max - return fail`() = runTest { givenBrowserProperties(bookmarks = 15L) val result = testee.evaluate( @@ -100,7 +100,7 @@ class UserAttributeMatcherTest { } @Test - fun whenBookmarksEqualOrGreaterThanMinThenReturnMatch() = runTest { + fun `evaluate - bookmarks equal or greater than min - return match`() = runTest { givenBrowserProperties(bookmarks = 10L) val result = testee.evaluate( @@ -111,7 +111,7 @@ class UserAttributeMatcherTest { } @Test - fun whenBookmarksLowerThanMinThenReturnFail() = runTest { + fun `evaluate - bookmarks lower than min - return fail`() = runTest { givenBrowserProperties(bookmarks = 0L) val result = testee.evaluate( @@ -122,7 +122,7 @@ class UserAttributeMatcherTest { } @Test - fun whenBookmarksInRangeThenReturnMatch() = runTest { + fun `evaluate - bookmarks in range - returns match`() = runTest { givenBrowserProperties(bookmarks = 10L) val result = testee.evaluate( @@ -133,7 +133,7 @@ class UserAttributeMatcherTest { } @Test - fun whenBookmarksNotInRangeThenReturnMatch() = runTest { + fun `evaluate - bookmarks not in range - return match`() = runTest { givenBrowserProperties(bookmarks = 10L) val result = testee.evaluate( @@ -145,7 +145,7 @@ class UserAttributeMatcherTest { // Favorites @Test - fun whenFavoritesMatchesThenReturnMatch() = runTest { + fun `evaluate - favorites matches - returns match`() = runTest { givenBrowserProperties(favorites = 10L) val result = testee.evaluate( @@ -156,7 +156,7 @@ class UserAttributeMatcherTest { } @Test - fun whenFavoritesDoesNotMatchThenReturnFail() = runTest { + fun `evaluate - favorites does not match - return fail`() = runTest { givenBrowserProperties(favorites = 10L) val result = testee.evaluate( @@ -167,7 +167,7 @@ class UserAttributeMatcherTest { } @Test - fun whenFavoritesEqualOrLowerThanMaxThenReturnMatch() = runTest { + fun `evaluate - favorites equal or lower than max - return match`() = runTest { givenBrowserProperties(favorites = 10L) val result = testee.evaluate( @@ -178,7 +178,7 @@ class UserAttributeMatcherTest { } @Test - fun whenFavoritesGreaterThanMaxThenReturnFail() = runTest { + fun `evaluate - favorites greater than max - return fail`() = runTest { givenBrowserProperties(favorites = 10L) val result = testee.evaluate( @@ -189,7 +189,7 @@ class UserAttributeMatcherTest { } @Test - fun whenFavoritesEqualOrGreaterThanMinThenReturnMatch() = runTest { + fun `evaluate - favorites equal or greater than min - return match`() = runTest { givenBrowserProperties(favorites = 10L) val result = testee.evaluate( @@ -200,7 +200,7 @@ class UserAttributeMatcherTest { } @Test - fun whenFavoritesLowerThanMinThenReturnFail() = runTest { + fun `evaluate - favorites lower than min - return fail`() = runTest { givenBrowserProperties(favorites = 0L) val result = testee.evaluate( @@ -211,7 +211,7 @@ class UserAttributeMatcherTest { } @Test - fun whenFavoritesInRangeThenReturnMatch() = runTest { + fun `evaluate - favorites in range - return match`() = runTest { givenBrowserProperties(favorites = 10L) val result = testee.evaluate( @@ -222,7 +222,7 @@ class UserAttributeMatcherTest { } @Test - fun whenFavoritesNotInRangeThenReturnMatch() = runTest { + fun `evaluate - favorites not in range - return match`() = runTest { givenBrowserProperties(favorites = 10L) val result = testee.evaluate( @@ -234,7 +234,7 @@ class UserAttributeMatcherTest { // DaysSinceInstalled @Test - fun whenDaysSinceInstalledEqualOrLowerThanMaxThenReturnMatch() = runTest { + fun `evaluate - days since installed equal or lower than max - return match`() = runTest { givenBrowserProperties(daysSinceInstalled = 10L) val result = testee.evaluate( @@ -245,7 +245,7 @@ class UserAttributeMatcherTest { } @Test - fun whenDaysSinceInstalledGreaterThanMaxThenReturnFail() = runTest { + fun `evaluate - days since installed greater than max - return fail`() = runTest { givenBrowserProperties(daysSinceInstalled = 10L) val result = testee.evaluate( @@ -256,7 +256,7 @@ class UserAttributeMatcherTest { } @Test - fun whenDaysSinceInstalledEqualOrGreaterThanMinThenReturnMatch() = runTest { + fun `evaluate - days since installed equal or greater than min - return match`() = runTest { givenBrowserProperties(daysSinceInstalled = 10L) val result = testee.evaluate( @@ -267,7 +267,7 @@ class UserAttributeMatcherTest { } @Test - fun whenDaysSinceInstalledLowerThanMinThenReturnFail() = runTest { + fun `evaluate - days since installed lower than min - return fail`() = runTest { givenBrowserProperties(daysSinceInstalled = 1L) val result = testee.evaluate( @@ -278,7 +278,7 @@ class UserAttributeMatcherTest { } @Test - fun whenDaysSinceInstalledInRangeThenReturnMatch() = runTest { + fun `evaluate - days since installed in range - return match`() = runTest { givenBrowserProperties(daysSinceInstalled = 10L) val result = testee.evaluate( @@ -289,7 +289,7 @@ class UserAttributeMatcherTest { } @Test - fun whenDaysSinceInstalledNotInRangeThenReturnMatch() = runTest { + fun `evaluate - days since installed not in range - return match`() = runTest { givenBrowserProperties(daysSinceInstalled = 10L) val result = testee.evaluate( @@ -301,7 +301,7 @@ class UserAttributeMatcherTest { // DaysUsedSince @Test - fun whenDaysUsedSinceMatchesThenReturnMatch() = runTest { + fun `evaluate - days used since matches - return match`() = runTest { givenBrowserProperties(daysUsedSince = 10L) val result = testee.evaluate( @@ -312,7 +312,7 @@ class UserAttributeMatcherTest { } @Test - fun whenDaysUsedSinceDoesNotMatchThenReturnFail() = runTest { + fun `evaluate - days used since does not match - return fail`() = runTest { givenBrowserProperties(daysUsedSince = 10L) val result = testee.evaluate( @@ -324,7 +324,7 @@ class UserAttributeMatcherTest { // DefaultBrowser @Test - fun whenDefaultBrowserMatchesThenReturnMatch() = runTest { + fun `evaluate - default browser matches - returns match`() = runTest { givenBrowserProperties(defaultBrowser = true) val result = testee.evaluate( @@ -335,7 +335,7 @@ class UserAttributeMatcherTest { } @Test - fun whenDefaultBrowserDoesNotMatchThenReturnFail() = runTest { + fun `evaluate - default browser does not match - return fail`() = runTest { givenBrowserProperties(defaultBrowser = false) val result = testee.evaluate( @@ -347,7 +347,7 @@ class UserAttributeMatcherTest { // EmailEnabled @Test - fun whenEmailEnabledMatchesThenReturnMatch() = runTest { + fun `evaluate - email enabled matches - returns match`() = runTest { givenBrowserProperties(emailEnabled = true) val result = testee.evaluate( @@ -358,7 +358,7 @@ class UserAttributeMatcherTest { } @Test - fun whenEmailEnabledDoesNotMatchThenReturnFail() = runTest { + fun `evaluate - email enabled does not match - return fail`() = runTest { givenBrowserProperties(emailEnabled = false) val result = testee.evaluate( @@ -370,7 +370,7 @@ class UserAttributeMatcherTest { // SearchCount @Test - fun whenSearchCountMatchesThenReturnMatch() = runTest { + fun `evaluate - search count matches - returns match`() = runTest { givenBrowserProperties(searchCount = 10L) val result = testee.evaluate( @@ -381,7 +381,7 @@ class UserAttributeMatcherTest { } @Test - fun whenSearchCountDoesNotMatchThenReturnFail() = runTest { + fun `evaluate - search count does not match - return fail`() = runTest { givenBrowserProperties(searchCount = 10L) val result = testee.evaluate( @@ -392,7 +392,7 @@ class UserAttributeMatcherTest { } @Test - fun whenSearchCountEqualOrLowerThanMaxThenReturnMatch() = runTest { + fun `evaluate - search count equal or lower than max - return match`() = runTest { givenBrowserProperties(searchCount = 10L) val result = testee.evaluate( @@ -403,7 +403,7 @@ class UserAttributeMatcherTest { } @Test - fun whenSearchCountGreaterThanMaxThenReturnFail() = runTest { + fun `evaluate - search count greater than max - return fail`() = runTest { givenBrowserProperties(searchCount = 10L) val result = testee.evaluate( @@ -414,7 +414,7 @@ class UserAttributeMatcherTest { } @Test - fun whenSearchCountEqualOrGreaterThanMinThenReturnMatch() = runTest { + fun `evaluate - search count equal or greater than min - return match`() = runTest { givenBrowserProperties(searchCount = 10L) val result = testee.evaluate( @@ -425,7 +425,7 @@ class UserAttributeMatcherTest { } @Test - fun whenSearchCountLowerThanMinThenReturnFail() = runTest { + fun `evaluate - search count lower than min - return fail`() = runTest { givenBrowserProperties(searchCount = 1L) val result = testee.evaluate( @@ -436,7 +436,7 @@ class UserAttributeMatcherTest { } @Test - fun whenSearchCountInRangeThenReturnMatch() = runTest { + fun `evaluate - search count in range - return match`() = runTest { givenBrowserProperties(searchCount = 10L) val result = testee.evaluate( @@ -447,7 +447,7 @@ class UserAttributeMatcherTest { } @Test - fun whenSearchCountNotInRangeThenReturnMatch() = runTest { + fun `evaluate - search count not in range - return match`() = runTest { givenBrowserProperties(searchCount = 10L) val result = testee.evaluate( @@ -459,7 +459,7 @@ class UserAttributeMatcherTest { // WidgetAdded @Test - fun whenWidgetAddedMatchesThenReturnMatch() = runTest { + fun `evaluate - widget added matches - return match`() = runTest { givenBrowserProperties(widgetAdded = true) val result = testee.evaluate( @@ -470,7 +470,7 @@ class UserAttributeMatcherTest { } @Test - fun whenWidgetAddedDoesNotMatchThenReturnFail() = runTest { + fun `evaluate - widget added does not match - return fail`() = runTest { givenBrowserProperties(widgetAdded = false) val result = testee.evaluate( diff --git a/remote-messaging/remote-messaging-internal/src/test/java/com/duckduckgo/remote/messaging/internal/feature/RmfStagingEnvInterceptorTest.kt b/remote-messaging/remote-messaging-internal/src/test/java/com/duckduckgo/remote/messaging/internal/feature/RmfStagingEnvInterceptorTest.kt index 8e11468793f1..7018db867554 100644 --- a/remote-messaging/remote-messaging-internal/src/test/java/com/duckduckgo/remote/messaging/internal/feature/RmfStagingEnvInterceptorTest.kt +++ b/remote-messaging/remote-messaging-internal/src/test/java/com/duckduckgo/remote/messaging/internal/feature/RmfStagingEnvInterceptorTest.kt @@ -13,7 +13,7 @@ class RmfStagingEnvInterceptorTest { private val interceptor = RmfStagingEnvInterceptor(rmfInternalSettings) @Test - fun interceptEndpointWhenEnabled() { + fun `interceptEndpoint - enabled - staging url`() { rmfInternalSettings.useStatingEndpoint().setEnabled(State(enable = true)) val chain = FakeChain(RMF_URL_V1) @@ -28,7 +28,7 @@ class RmfStagingEnvInterceptorTest { } @Test - fun interceptNoopWhenDisabled() { + fun `interceptNoopWhenDisabled - disabled - no op`() { rmfInternalSettings.useStatingEndpoint().setEnabled(State(enable = false)) val chain = FakeChain(RMF_URL_V1) @@ -43,7 +43,7 @@ class RmfStagingEnvInterceptorTest { } @Test - fun interceptIgnoreUnknownEndpointWhenEnabled() { + fun `intercept - ignore unknown endpoint when enabled - unknown endpoint ignored`() { rmfInternalSettings.useStatingEndpoint().setEnabled(State(enable = true)) val chain = FakeChain(UNKNOWN_URL) @@ -53,7 +53,7 @@ class RmfStagingEnvInterceptorTest { } @Test - fun interceptIgnoreUnknownEndpointWhenDisabled() { + fun `intercept - ignore unknown endpoint when disabled - unknown endpoint ignored`() { rmfInternalSettings.useStatingEndpoint().setEnabled(State(enable = false)) val chain = FakeChain(UNKNOWN_URL) diff --git a/remote-messaging/remote-messaging-store/src/test/java/com/duckduckgo/remote/messaging/store/LocalRemoteMessagingConfigRepositoryTest.kt b/remote-messaging/remote-messaging-store/src/test/java/com/duckduckgo/remote/messaging/store/LocalRemoteMessagingConfigRepositoryTest.kt index 129204d948a1..97e44c78411f 100644 --- a/remote-messaging/remote-messaging-store/src/test/java/com/duckduckgo/remote/messaging/store/LocalRemoteMessagingConfigRepositoryTest.kt +++ b/remote-messaging/remote-messaging-store/src/test/java/com/duckduckgo/remote/messaging/store/LocalRemoteMessagingConfigRepositoryTest.kt @@ -24,7 +24,7 @@ import org.junit.Test class LocalRemoteMessagingConfigRepositoryTest { @Test - fun whenRemoteConfigTimestampGreaterThan1DayThenConfigExpired() { + fun `remoteConfigTimestamp - greater than 1 day - config expired`() { val remoteMessagingConfig = RemoteMessagingConfig( version = 0, evaluationTimestamp = databaseTimestampFormatter().format(LocalDateTime.now().minusDays(2L)), @@ -36,7 +36,7 @@ class LocalRemoteMessagingConfigRepositoryTest { } @Test - fun whenRemoteConfigTimestampLessThan1DayThenConfigIsNotExpired() { + fun `getRemoteConfig - timestamp less than 1 day - not expired`() { val remoteMessagingConfig = RemoteMessagingConfig( version = 0, evaluationTimestamp = databaseTimestampFormatter().format(LocalDateTime.now().minusHours(15L)), diff --git a/remote-messaging/remote-messaging-store/src/test/java/com/duckduckgo/remote/messaging/store/RemoteMessagingCohortStoreImplTest.kt b/remote-messaging/remote-messaging-store/src/test/java/com/duckduckgo/remote/messaging/store/RemoteMessagingCohortStoreImplTest.kt index cc18b705feea..8429cd897522 100644 --- a/remote-messaging/remote-messaging-store/src/test/java/com/duckduckgo/remote/messaging/store/RemoteMessagingCohortStoreImplTest.kt +++ b/remote-messaging/remote-messaging-store/src/test/java/com/duckduckgo/remote/messaging/store/RemoteMessagingCohortStoreImplTest.kt @@ -38,19 +38,19 @@ class RemoteMessagingCohortStoreImplTest { private val testee = RemoteMessagingCohortStoreImpl(db, coroutineRule.testDispatcherProvider) @Test - fun whenPercentileIsSetForMessageThenReturnSameValue() = runTest { + fun `getPercentile - set percentile for message - same value`() = runTest { cohortDao.insert(RemoteMessagingCohort(messageId = "message1", percentile = 0.5f)) assertEquals(0.5f, testee.getPercentile("message1")) } @Test - fun whenPercentileIsNotSetForMessageThenItIsCalculated() = runTest { + fun `getPercentile - no percentile set - calculated`() = runTest { val percentile = testee.getPercentile("message1") assertTrue(percentile in 0.0f..1.0f) } @Test - fun whenMoreThanOneMessageWithCohortThenReturnExpectedCohort() = runTest { + fun `getPercentile - more than one message with cohort - expected cohort`() = runTest { cohortDao.insert(RemoteMessagingCohort(messageId = "message1", percentile = 0.5f)) cohortDao.insert(RemoteMessagingCohort(messageId = "message2", percentile = 0.6f)) assertEquals(0.5f, testee.getPercentile("message1")) diff --git a/request-filterer/request-filterer-impl/src/test/java/com/duckduckgo/request/filterer/impl/RequestFiltererImplTest.kt b/request-filterer/request-filterer-impl/src/test/java/com/duckduckgo/request/filterer/impl/RequestFiltererImplTest.kt index 982769eb0b30..50429668b3be 100644 --- a/request-filterer/request-filterer-impl/src/test/java/com/duckduckgo/request/filterer/impl/RequestFiltererImplTest.kt +++ b/request-filterer/request-filterer-impl/src/test/java/com/duckduckgo/request/filterer/impl/RequestFiltererImplTest.kt @@ -67,7 +67,7 @@ class RequestFiltererImplTest { } @Test - fun whenFeatureIsDisabledThenReturnFalse() { + fun `shouldFilterOutRequest - feature disabled - returns false`() { whenever(mockFeatureToggle.isFeatureEnabled(eq(RequestFiltererFeatureName.RequestFilterer.value), any())).thenReturn(false) val previousUrl = "http://example.com" @@ -80,7 +80,7 @@ class RequestFiltererImplTest { } @Test - fun whenUrlInExceptionsListThenReturnFalse() { + fun `shouldFilterOutRequest - url in exceptions list - returns false`() { val exceptions = CopyOnWriteArrayList().apply { add(FeatureException("http://test.com", "my reason here")) } @@ -96,7 +96,7 @@ class RequestFiltererImplTest { } @Test - fun whenUrlInUnprotectedTemporaryThenReturnFalse() { + fun `shouldFilterOutRequest - url in unprotected temporary - return false`() { whenever(mockUnprotectedTemporary.isAnException("http://test.com")).thenReturn(true) val previousUrl = "http://example.com" val documentUrl = "http://test.com" @@ -108,7 +108,7 @@ class RequestFiltererImplTest { } @Test - fun whenRequestRefererHeaderMatchesPreviousUrlThenReturnTrue() = runTest { + fun `registerOnPageCreated - referer header matches previous url - returns true`() = runTest { val previousUrl = "http://example.com" val documentUrl = "http://test.com" whenever(mockRequest.requestHeaders).thenReturn(mapOf(REFERER to previousUrl)) @@ -119,7 +119,7 @@ class RequestFiltererImplTest { } @Test - fun whenRequestRefererHeaderMatchesPreviousUrlAndTimeHasElapsedThenReturnFalse() = runTest { + fun `shouldFilterOutRequest - referer header matches previous url and time has elapsed - return false`() = runTest { val previousUrl = "http://example.com" val documentUrl = "http://test.com" whenever(mockRequest.requestHeaders).thenReturn(mapOf(REFERER to previousUrl)) @@ -130,7 +130,7 @@ class RequestFiltererImplTest { } @Test - fun whenRequestOriginHeaderMatchesPreviousUrlAndNoRefererHeaderThenReturnTrue() { + fun `registerOnPageCreated - origin header matches previous url and no referer header - returns true`() { val previousUrl = "http://example.com" val documentUrl = "http://test.com" whenever(mockRequest.requestHeaders).thenReturn(mapOf(ORIGIN to previousUrl)) @@ -141,7 +141,7 @@ class RequestFiltererImplTest { } @Test - fun whenDocumentUrlMatchesPreviousPageThenReturnFalse() { + fun `shouldFilterOutRequest - document url matches previous page - return false`() { val previousUrl = "http://example.com" val documentUrl = "http://example.com" whenever(mockRequest.requestHeaders).thenReturn(mapOf(REFERER to previousUrl)) @@ -152,7 +152,7 @@ class RequestFiltererImplTest { } @Test - fun whenDocumentUrlMatchesPreviousETLDPlusOneThenReturnFalse() { + fun `shouldFilterOutRequest - document url matches previous ETL plus one - return false`() { val previousUrl = "http://example.com" val documentUrl = "http://test.example.com" whenever(mockRequest.requestHeaders).thenReturn(mapOf(REFERER to previousUrl)) @@ -163,7 +163,7 @@ class RequestFiltererImplTest { } @Test - fun whenRequestRefererHeaderDoesNotMatchPreviousUrlThenReturnFalse() { + fun `registerOnPageCreated - referer header does not match previous url - return false`() { val previousUrl = "http://example.com" val documentUrl = "http://test.com" whenever(mockRequest.requestHeaders).thenReturn(mapOf(REFERER to "http://notamatch.com")) @@ -174,7 +174,7 @@ class RequestFiltererImplTest { } @Test - fun whenRequestOriginHeaderDoesNotMatchPreviousUrlThenReturnFalse() { + fun `registerOnPageCreated - request origin header does not match previous url - return false`() { val previousUrl = "http://example.com" val documentUrl = "http://test.com" whenever(mockRequest.requestHeaders).thenReturn(mapOf(ORIGIN to "http://notamatch.com")) @@ -185,7 +185,7 @@ class RequestFiltererImplTest { } @Test - fun whenNoPreviousUrlRegisteredThenReturnFalse() { + fun `registerOnPageCreated - no previous url registered - return false`() { val previousUrl = "http://example.com" val documentUrl = "http://test.com" whenever(mockRequest.requestHeaders).thenReturn(mapOf(REFERER to previousUrl)) @@ -195,7 +195,7 @@ class RequestFiltererImplTest { } @Test - fun whenRegisterOnPageCreatedThenUrlsChange() { + fun `registerOnPageCreated - urls change - should filter out request`() { val previousUrl = "http://example.com" val documentUrl = "http://test.com" whenever(mockRequest.requestHeaders).thenReturn(mapOf(REFERER to previousUrl)) @@ -208,13 +208,13 @@ class RequestFiltererImplTest { } @Test - fun whenDocumentUrlIsMalformedThenReturnFalse() { + fun `registerOnPageCreated - document url is malformed - return false`() { requestFilterer.registerOnPageCreated("http://foo.com") assertFalse(requestFilterer.shouldFilterOutRequest(mockRequest, "abc123")) } @Test - fun whenPreviousUrlIsMalformedThenReturnFalse() { + fun `registerOnPageCreated - previous url malformed - return false`() { requestFilterer.registerOnPageCreated("abc123") requestFilterer.registerOnPageCreated("http://foo.com") assertFalse(requestFilterer.shouldFilterOutRequest(mockRequest, "http://bar.com")) diff --git a/request-filterer/request-filterer-impl/src/test/java/com/duckduckgo/request/filterer/impl/plugins/RequestFiltererFeaturePluginTest.kt b/request-filterer/request-filterer-impl/src/test/java/com/duckduckgo/request/filterer/impl/plugins/RequestFiltererFeaturePluginTest.kt index ed5d1a26da91..54ad2b8c3a0f 100644 --- a/request-filterer/request-filterer-impl/src/test/java/com/duckduckgo/request/filterer/impl/plugins/RequestFiltererFeaturePluginTest.kt +++ b/request-filterer/request-filterer-impl/src/test/java/com/duckduckgo/request/filterer/impl/plugins/RequestFiltererFeaturePluginTest.kt @@ -43,19 +43,19 @@ class RequestFiltererFeaturePluginTest { } @Test - fun whenFeatureNameDoesNotMatchRequestFiltererThenReturnFalse() { + fun `store - feature name does not match request filterer - returns false`() { RequestFiltererFeatureName.values().filter { it != FEATURE_NAME }.forEach { assertFalse(testee.store(it.value, EMPTY_JSON_STRING)) } } @Test - fun whenFeatureNameMatchesRequestFiltererThenReturnTrue() { + fun `store - feature name matches request filterer - returns true`() { TestCase.assertTrue(testee.store(FEATURE_NAME_VALUE, EMPTY_JSON_STRING)) } @Test - fun whenFeatureNameMatchesRequestFiltererAndIsEnabledThenStoreFeatureEnabled() { + fun `store - feature name matches request filterer and is enabled - store feature enabled`() { val jsonString = FileUtilities.loadText(RequestFiltererFeaturePluginTest::class.java.classLoader!!, "json/request_filterer.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -64,7 +64,7 @@ class RequestFiltererFeaturePluginTest { } @Test - fun whenFeatureNameMatchesRequestFiltererAndIsNotEnabledThenStoreFeatureDisabled() { + fun `store - feature name matches request filterer and is not enabled - store feature disabled`() { val jsonString = FileUtilities.loadText( RequestFiltererFeaturePluginTest::class.java.classLoader!!, "json/request_filterer_disabled.json", @@ -76,7 +76,7 @@ class RequestFiltererFeaturePluginTest { } @Test - fun whenFeatureNameMatchesRequestFiltererAndHasMinSupportedVersionThenStoreMinSupportedVersion() { + fun `store - feature name matches request filterer and has min supported version - store min supported version`() { val jsonString = FileUtilities.loadText( RequestFiltererFeaturePluginTest::class.java.classLoader!!, @@ -89,7 +89,7 @@ class RequestFiltererFeaturePluginTest { } @Test - fun whenFeatureNameMatchesRequestFiltererThenUpdateAllExistingValues() { + fun `whenFeatureNameMatchesRequestFiltererThenUpdateAllExistingValues - update all existing values`() { val jsonString = FileUtilities.loadText(RequestFiltererFeaturePluginTest::class.java.classLoader!!, "json/request_filterer.json") testee.store(FEATURE_NAME_VALUE, jsonString) diff --git a/request-filterer/request-filterer-impl/src/test/java/com/duckduckgo/request/filterer/impl/plugins/RequestFiltererFeatureTogglesPluginTest.kt b/request-filterer/request-filterer-impl/src/test/java/com/duckduckgo/request/filterer/impl/plugins/RequestFiltererFeatureTogglesPluginTest.kt index 2756b66c0a87..da818faf6807 100644 --- a/request-filterer/request-filterer-impl/src/test/java/com/duckduckgo/request/filterer/impl/plugins/RequestFiltererFeatureTogglesPluginTest.kt +++ b/request-filterer/request-filterer-impl/src/test/java/com/duckduckgo/request/filterer/impl/plugins/RequestFiltererFeatureTogglesPluginTest.kt @@ -45,12 +45,12 @@ class RequestFiltererFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsNotRequestFiltererFeatureThenReturnNull() = runTest { + fun `isEnabled - is not request filterer feature - return null`() = runTest { assertNull(testee.isEnabled(NonRequestFiltererFeature().value, true)) } @Test - fun whenIsEnabledAndFeatureIsRequestFiltererFeatureThenReturnTrueWhenEnabled() = + fun `isEnabled - request filterer feature enabled - returns true when enabled`() = runTest { givenRequestFiltererFeatureIsEnabled() @@ -60,7 +60,7 @@ class RequestFiltererFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsRequestFiltererFeatureThenReturnFalseWhenDisabled() = + fun `isEnabled - request filterer feature disabled - false when disabled`() = runTest { givenRequestFiltererFeatureIsDisabled() @@ -70,7 +70,7 @@ class RequestFiltererFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsRequestFiltererFeatureThenReturnDefaultValueIfFeatureDoesNotExist() = + fun `isEnabled - request filterer feature does not exist - return default value`() = runTest { val defaultValue = true givenRequestFiltererFeatureReturnsDefaultValue(defaultValue) @@ -82,7 +82,7 @@ class RequestFiltererFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsRequestFiltererFeatureAndAppVersionEqualToMinSupportedVersionThenReturnTrueWhenEnabled() = + fun `isEnabled - request filterer feature enabled and app version equal to min supported version - returns true when enabled`() = runTest { givenRequestFiltererFeatureIsEnabled() givenAppVersionIsEqualToMinSupportedVersion() @@ -93,7 +93,7 @@ class RequestFiltererFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsRequestFiltererFeatureAndAppVersionIsGreaterThanMinSupportedVersionThenReturnTrueWhenEnabled() = + fun `isEnabled - request filterer feature enabled and app version greater than min supported version - returns true when enabled`() = runTest { givenRequestFiltererFeatureIsEnabled() givenAppVersionIsGreaterThanMinSupportedVersion() @@ -104,7 +104,7 @@ class RequestFiltererFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsRequestFiltererFeatureAndAppVersionIsSmallerThanMinSupportedVersionThenReturnFalseWhenEnabled() = + fun `isEnabled - request filterer feature enabled and app version smaller than min supported version - false when enabled`() = runTest { givenRequestFiltererFeatureIsEnabled() givenAppVersionIsSmallerThanMinSupportedVersion() diff --git a/request-filterer/request-filterer-store/src/test/java/com/duckduckgo/request/filterer/store/RealFiltererRequestFeatureToggleRepositoryTest.kt b/request-filterer/request-filterer-store/src/test/java/com/duckduckgo/request/filterer/store/RealFiltererRequestFeatureToggleRepositoryTest.kt index bf4afc1d942e..2fe591d55b08 100644 --- a/request-filterer/request-filterer-store/src/test/java/com/duckduckgo/request/filterer/store/RealFiltererRequestFeatureToggleRepositoryTest.kt +++ b/request-filterer/request-filterer-store/src/test/java/com/duckduckgo/request/filterer/store/RealFiltererRequestFeatureToggleRepositoryTest.kt @@ -33,21 +33,21 @@ class RealFiltererRequestFeatureToggleRepositoryTest { } @Test - fun whenDeleteAllThenDeleteAllCalled() { + fun `deleteAll - delete all called`() { testee.deleteAll() verify(mockRequestFiltererFeatureToggleStore).deleteAll() } @Test - fun whenGetThenGetCalled() { + fun `get - get called`() { testee.get(RequestFilterer, true) verify(mockRequestFiltererFeatureToggleStore).get(RequestFilterer, true) } @Test - fun whenInsertThenInsertCalled() { + fun `insert - feature toggle inserted`() { val requestFiltererFeatureToggle = RequestFiltererFeatureToggles(RequestFilterer, true, null) testee.insert(requestFiltererFeatureToggle) diff --git a/request-filterer/request-filterer-store/src/test/java/com/duckduckgo/request/filterer/store/RealRequestFiltererRepositoryTest.kt b/request-filterer/request-filterer-store/src/test/java/com/duckduckgo/request/filterer/store/RealRequestFiltererRepositoryTest.kt index b61cd9d98fe3..9b5562a5f1fe 100644 --- a/request-filterer/request-filterer-store/src/test/java/com/duckduckgo/request/filterer/store/RealRequestFiltererRepositoryTest.kt +++ b/request-filterer/request-filterer-store/src/test/java/com/duckduckgo/request/filterer/store/RealRequestFiltererRepositoryTest.kt @@ -44,7 +44,7 @@ class RealRequestFiltererRepositoryTest { } @Test - fun whenRepositoryIsCreatedThenValuesLoadedIntoMemory() { + fun `whenRepositoryIsCreatedThenValuesLoadedIntoMemory - repository created - values loaded into memory`() { givenRequestFiltererDaoHasContent() testee = RealRequestFiltererRepository( @@ -59,7 +59,7 @@ class RealRequestFiltererRepositoryTest { } @Test - fun whenLoadToMemoryAndNoSettingsThenSetDefaultValues() { + fun `loadToMemory - no settings - set default values`() { whenever(mockRequestFiltererDao.getSettings()).thenReturn(null) testee = RealRequestFiltererRepository( @@ -73,7 +73,7 @@ class RealRequestFiltererRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() { + fun `updateAll - update all called`() { val policy = SettingsEntity(2, 600) testee = RealRequestFiltererRepository( @@ -89,7 +89,7 @@ class RealRequestFiltererRepositoryTest { } @Test - fun whenUpdateAllThenPreviousValuesAreCleared() { + fun `updateAll - previous values cleared`() { givenRequestFiltererDaoHasContent() testee = RealRequestFiltererRepository( diff --git a/runtime-checks/runtime-checks-impl/src/test/java/com/duckduckgo/runtimechecks/impl/RuntimeChecksContentScopeConfigPluginTest.kt b/runtime-checks/runtime-checks-impl/src/test/java/com/duckduckgo/runtimechecks/impl/RuntimeChecksContentScopeConfigPluginTest.kt index ee59d84d4ac1..cf1a72aaf069 100644 --- a/runtime-checks/runtime-checks-impl/src/test/java/com/duckduckgo/runtimechecks/impl/RuntimeChecksContentScopeConfigPluginTest.kt +++ b/runtime-checks/runtime-checks-impl/src/test/java/com/duckduckgo/runtimechecks/impl/RuntimeChecksContentScopeConfigPluginTest.kt @@ -37,13 +37,13 @@ class RuntimeChecksContentScopeConfigPluginTest { } @Test - fun whenGetConfigThenReturnCorrectlyFormattedJson() { + fun `getConfig - return correctly formatted json`() { whenever(mockRuntimeChecksRepository.getRuntimeChecksEntity()).thenReturn(RuntimeChecksEntity(json = config)) assertEquals("\"runtimeChecks\":$config", testee.config()) } @Test - fun whenGetPreferencesThenReturnNull() { + fun `getPreferences - null`() { assertNull(testee.preferences()) } diff --git a/runtime-checks/runtime-checks-impl/src/test/java/com/duckduckgo/runtimechecks/impl/RuntimeChecksFeaturePluginTest.kt b/runtime-checks/runtime-checks-impl/src/test/java/com/duckduckgo/runtimechecks/impl/RuntimeChecksFeaturePluginTest.kt index 8addaa566309..93e6b3ae1b62 100644 --- a/runtime-checks/runtime-checks-impl/src/test/java/com/duckduckgo/runtimechecks/impl/RuntimeChecksFeaturePluginTest.kt +++ b/runtime-checks/runtime-checks-impl/src/test/java/com/duckduckgo/runtimechecks/impl/RuntimeChecksFeaturePluginTest.kt @@ -36,19 +36,19 @@ class RuntimeChecksFeaturePluginTest { } @Test - fun whenFeatureNameDoesNotMatchRuntimeChecksThenReturnFalse() { + fun `store - feature name does not match runtime checks - returns false`() { RuntimeChecksFeatureName.values().filter { it != FEATURE_NAME }.forEach { assertFalse(testee.store(it.value, JSON_STRING)) } } @Test - fun whenFeatureNameMatchesRuntimeChecksThenReturnTrue() { + fun `store - feature name matches runtime checks - true`() { assertTrue(testee.store(FEATURE_NAME_VALUE, JSON_STRING)) } @Test - fun whenFeatureNameMatchesRuntimeChecksThenUpdateAll() { + fun `whenFeatureNameMatchesRuntimeChecks - update all - json string`() { testee.store(FEATURE_NAME_VALUE, JSON_STRING) val captor = argumentCaptor() verify(mockRuntimeChecksRepository).updateAll(captor.capture()) diff --git a/runtime-checks/runtime-checks-store/src/test/java/com/duckduckgo/runtimechecks/store/RuntimeChecksRepositoryTest.kt b/runtime-checks/runtime-checks-store/src/test/java/com/duckduckgo/runtimechecks/store/RuntimeChecksRepositoryTest.kt index 6aba7197ca28..8985f875b8f8 100644 --- a/runtime-checks/runtime-checks-store/src/test/java/com/duckduckgo/runtimechecks/store/RuntimeChecksRepositoryTest.kt +++ b/runtime-checks/runtime-checks-store/src/test/java/com/duckduckgo/runtimechecks/store/RuntimeChecksRepositoryTest.kt @@ -42,7 +42,7 @@ class RuntimeChecksRepositoryTest { } @Test - fun whenInitializedAndDoesNotHaveStoredValueThenLoadEmptyJsonToMemory() = + fun `getRuntimeChecks - initialized and no stored value - load empty json to memory`() = runTest { testee = RealRuntimeChecksRepository( @@ -57,7 +57,7 @@ class RuntimeChecksRepositoryTest { } @Test - fun whenInitializedAndHasStoredValueThenLoadStoredJsonToMemory() = + fun `loadStoredJsonToMemory - initialized and has stored value`() = runTest { whenever(mockRuntimeChecksDao.get()).thenReturn(runtimeChecksEntity) testee = @@ -73,7 +73,7 @@ class RuntimeChecksRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - update all called`() = runTest { testee = RealRuntimeChecksRepository( diff --git a/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/service/SavedSitesManagerTest.kt b/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/service/SavedSitesManagerTest.kt index d1e0a74c3553..fa4815f6e6a5 100644 --- a/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/service/SavedSitesManagerTest.kt +++ b/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/service/SavedSitesManagerTest.kt @@ -59,7 +59,7 @@ class SavedSitesManagerTest { } @Test - fun whenBookmarksImportSucceedsThenPixelIsSent() = runTest { + fun `import - bookmarks import succeeds - pixel sent`() = runTest { val someUri = Uri.parse("") val importedBookmarks = listOf(aBookmark()) whenever(importer.import(someUri)).thenReturn(ImportSavedSitesResult.Success(importedBookmarks)) @@ -73,7 +73,7 @@ class SavedSitesManagerTest { } @Test - fun whenFavoritesImportSucceedsThenPixelIsSent() = runTest { + fun `import - favorites succeed - pixel sent`() = runTest { val someUri = Uri.parse("") val importedFavorites = listOf(aFavorite()) whenever(importer.import(someUri)).thenReturn(ImportSavedSitesResult.Success(importedFavorites)) @@ -87,7 +87,7 @@ class SavedSitesManagerTest { } @Test - fun whenSavedSitesImportFailsThenPixelIsSent() = runTest { + fun `import - saved sites import fails - pixel sent`() = runTest { val someUri = Uri.parse("") whenever(importer.import(someUri)).thenReturn(ImportSavedSitesResult.Error(Exception())) @@ -97,7 +97,7 @@ class SavedSitesManagerTest { } @Test - fun whenSavedSitesExportSucceedsThenPixelIsSent() = runTest { + fun `export - saved sites export succeeds - pixel sent`() = runTest { val someUri = Uri.parse("") whenever(exporter.export(someUri)).thenReturn(ExportSavedSitesResult.Success) @@ -107,7 +107,7 @@ class SavedSitesManagerTest { } @Test - fun whenSavedSitesExportFailsThenPixelIsSent() = runTest { + fun `export - saved sites export fails - pixel sent`() = runTest { val someUri = Uri.parse("") whenever(exporter.export(someUri)).thenReturn(ExportSavedSitesResult.Error(Exception())) diff --git a/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/AppSavedSitesSyncFeatureListenerTest.kt b/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/AppSavedSitesSyncFeatureListenerTest.kt index c9f08b804735..7f8fdf88aaec 100644 --- a/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/AppSavedSitesSyncFeatureListenerTest.kt +++ b/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/AppSavedSitesSyncFeatureListenerTest.kt @@ -54,12 +54,12 @@ class AppSavedSitesSyncFeatureListenerTest { ) @Test - fun whenNoValuesThenIsSyncPausedIsFalse() { + fun `isSyncPaused - no values - is false`() { assertFalse(savedSitesSyncStore.isSyncPaused) } @Test - fun whenSyncPausedAndOnSuccessWithChangesThenIsSyncPausedIsFalse() { + fun `onSuccess - is sync paused false`() { savedSitesSyncStore.isSyncPaused = true val updatesJSON = FileUtilities.loadText(javaClass.classLoader!!, "json/merger_first_get.json") val validChanges = SyncChangesResponse(BOOKMARKS, updatesJSON) @@ -70,7 +70,7 @@ class AppSavedSitesSyncFeatureListenerTest { } @Test - fun whenSyncPausedAndOnSuccessWithoutChangesThenSyncPaused() { + fun `onSuccess - sync paused and no changes - sync paused`() { savedSitesSyncStore.isSyncPaused = true val validChanges = SyncChangesResponse.empty(BOOKMARKS) @@ -80,7 +80,7 @@ class AppSavedSitesSyncFeatureListenerTest { } @Test - fun whenSyncPausedAndOnErrorThenSyncPaused() { + fun `onError - sync paused - still sync paused`() { savedSitesSyncStore.isSyncPaused = true testee.onError(FeatureSyncError.COLLECTION_LIMIT_REACHED) @@ -89,7 +89,7 @@ class AppSavedSitesSyncFeatureListenerTest { } @Test - fun whenSyncActiveAndOnErrorThenSyncPaused() { + fun `sync - active and on error - sync paused`() { savedSitesSyncStore.isSyncPaused = false testee.onError(FeatureSyncError.COLLECTION_LIMIT_REACHED) @@ -98,7 +98,7 @@ class AppSavedSitesSyncFeatureListenerTest { } @Test - fun whenOnSyncDisabledThenSyncPausedFalse() { + fun `onSyncDisabled - sync paused - false`() { savedSitesSyncStore.isSyncPaused = true testee.onSyncDisabled() diff --git a/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/DisplayModeSyncableSettingTest.kt b/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/DisplayModeSyncableSettingTest.kt index 9049a6205718..4deff97bd991 100644 --- a/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/DisplayModeSyncableSettingTest.kt +++ b/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/DisplayModeSyncableSettingTest.kt @@ -27,33 +27,33 @@ class DisplayModeSyncableSettingTest { ) @Test - fun whenGetValueThenReturnStoredValue() = runTest { + fun `getValue - stored value - native`() = runTest { savedSitesSettingsStore.favoritesDisplayMode = FavoritesDisplayMode.NATIVE assertEquals(FavoritesDisplayMode.NATIVE.value, testee.getValue()) } @Test - fun whenSaveWithValidValueThenReturnTrue() = runTest { + fun `save - valid value - returns true`() = runTest { assertTrue(testee.save(FavoritesDisplayMode.NATIVE.value)) } @Test - fun whenSaveWithInvalidValidValueThenReturnFalse() = runTest { + fun `save - invalid value - returns false`() = runTest { assertFalse(testee.save("unknown_value")) } @Test - fun whenDeduplicateWithValidValueThenReturnTrue() = runTest { + fun `deduplicate - valid value - returns true`() = runTest { assertTrue(testee.deduplicate(FavoritesDisplayMode.NATIVE.value)) } @Test - fun whenDeduplicateWithInvalidValidValueThenReturnFalse() = runTest { + fun `deduplicate - invalid value - returns false`() = runTest { assertFalse(testee.deduplicate("unknown_value")) } @Test - fun whenOnSettingChangedThenNotifyListener() = runTest { + fun `onSettingChanged - notify listener`() = runTest { testee.onSettingChanged() verify(syncSettingsListener).onSettingChanged(testee.key) } diff --git a/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/DisplayModeViewModelTest.kt b/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/DisplayModeViewModelTest.kt index c2b9e5cb099b..2cc2178b6527 100644 --- a/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/DisplayModeViewModelTest.kt +++ b/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/DisplayModeViewModelTest.kt @@ -43,14 +43,14 @@ class DisplayModeViewModelTest { private val testee = DisplayModeViewModel(favoritesDisplayModeSettingsRepository, coroutineRule.testDispatcherProvider) @Test - fun whenObserverAddedThenCurrentViewStateEmitted() = runTest { + fun `viewState - observer added - current view state emitted`() = runTest { testee.viewState().test { assertEquals(ViewState(), awaitItem()) } } @Test - fun whenDisplayModeChangedThenViewStateIsUpdated() = runTest { + fun `onDisplayModeChanged - view state updated`() = runTest { testee.viewState().test { awaitItem() testee.onDisplayModeChanged(true) diff --git a/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/RealSavedSitesSyncStoreTest.kt b/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/RealSavedSitesSyncStoreTest.kt index 24027ff04b18..74d453ee4e69 100644 --- a/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/RealSavedSitesSyncStoreTest.kt +++ b/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/RealSavedSitesSyncStoreTest.kt @@ -43,12 +43,12 @@ class RealSavedSitesSyncStoreTest { val testee = RealSavedSitesSyncStore(mockContext, coroutineRule.testScope, coroutineRule.testDispatcherProvider) @Test - fun whenNoValueIsSyncPausedThenReturnFalse() { + fun `isSyncPaused - no value - return false`() { assertFalse(testee.isSyncPaused) } @Test - fun whenIsSyncPausedUpdatedThenEmitNewValue() = runTest { + fun `isSyncPausedUpdated - emit new value`() = runTest { testee.isSyncPausedFlow().test { awaitItem() testee.isSyncPaused = true diff --git a/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/SavedSiteRateLimitViewModelTest.kt b/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/SavedSiteRateLimitViewModelTest.kt index 34f20667ee43..232f167ddcf2 100644 --- a/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/SavedSiteRateLimitViewModelTest.kt +++ b/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/SavedSiteRateLimitViewModelTest.kt @@ -41,7 +41,7 @@ class SavedSiteRateLimitViewModelTest { ) @Test - fun whenSyncPausedThenWarningVisible() = runTest { + fun `viewState - sync paused - warning visible`() = runTest { savedSitesSyncStore.isSyncPaused = true testee.viewState().test { assertTrue(awaitItem().warningVisible) @@ -50,7 +50,7 @@ class SavedSiteRateLimitViewModelTest { } @Test - fun whenUserClicksWarningActionThenNavigateToBookmarks() = runTest { + fun `onWarningActionClicked - navigate to bookmarks`() = runTest { testee.commands().test { testee.onWarningActionClicked() assertEquals(NavigateToBookmarks, awaitItem()) diff --git a/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/SavedSitesSyncPersisterTest.kt b/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/SavedSitesSyncPersisterTest.kt index d305e6424098..cee670524ff3 100644 --- a/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/SavedSitesSyncPersisterTest.kt +++ b/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/SavedSitesSyncPersisterTest.kt @@ -67,7 +67,7 @@ class SavedSitesSyncPersisterTest { } @Test - fun whenValidatingCorruptedDataThenResultIsError() { + fun `process - corrupted data - error`() { val updatesJSON = FileUtilities.loadText(javaClass.classLoader!!, "json/merger_invalid_data.json") val corruptedChanges = SyncChangesResponse(BOOKMARKS, updatesJSON) val result = syncPersister.process(corruptedChanges, TIMESTAMP) @@ -76,7 +76,7 @@ class SavedSitesSyncPersisterTest { } @Test - fun whenValidatingNullEntriesThenResultIsError() { + fun `process - validating null entries - error`() { val updatesJSON = FileUtilities.loadText(javaClass.classLoader!!, "json/merger_null_entries.json") val corruptedChanges = SyncChangesResponse(BOOKMARKS, updatesJSON) val result = syncPersister.process(corruptedChanges, TIMESTAMP) @@ -85,7 +85,7 @@ class SavedSitesSyncPersisterTest { } @Test - fun whenProcessingDataInEmptyDBThenResultIsSuccess() { + fun `process - data processing in empty DB - success`() { whenever(persisterAlgorithm.processEntries(any(), any(), any())).thenReturn(Success(true)) whenever(store.serverModifiedSince).thenReturn(DatabaseDateFormatter.iso8601()) whenever(store.startTimeStamp).thenReturn(DatabaseDateFormatter.iso8601()) @@ -99,7 +99,7 @@ class SavedSitesSyncPersisterTest { } @Test - fun whenMergingEmptyEntriesThenResultIsSuccess() { + fun `process - merging empty entries - success`() { val updatesJSON = FileUtilities.loadText(javaClass.classLoader!!, "json/merger_empty_entries.json") val corruptedChanges = SyncChangesResponse(BOOKMARKS, updatesJSON) val result = syncPersister.process(corruptedChanges, TIMESTAMP) @@ -108,7 +108,7 @@ class SavedSitesSyncPersisterTest { } @Test - fun whenMergingWithDeletedDataThenResultIsSuccess() { + fun `process - merging with deleted data - success`() { whenever(store.serverModifiedSince).thenReturn(DatabaseDateFormatter.iso8601()) whenever(store.startTimeStamp).thenReturn(DatabaseDateFormatter.iso8601()) whenever(store.clientModifiedSince).thenReturn(DatabaseDateFormatter.iso8601()) @@ -121,7 +121,7 @@ class SavedSitesSyncPersisterTest { } @Test - fun whenOnSuccessThenNotifyListener() { + fun `onSuccess - notify listener`() { val updatesJSON = FileUtilities.loadText(javaClass.classLoader!!, "json/merger_first_get.json") val validChanges = SyncChangesResponse(BOOKMARKS, updatesJSON) @@ -131,13 +131,13 @@ class SavedSitesSyncPersisterTest { } @Test - fun whenOnErrorThenNotifyListener() { + fun `syncPersister - on error - notify listener`() { syncPersister.onError(SyncErrorResponse(BOOKMARKS, COLLECTION_LIMIT_REACHED)) verify(savedSitesSyncFeatureListener).onError(COLLECTION_LIMIT_REACHED) } @Test - fun whenOnSyncDisabledTheNotifyListener() { + fun `onSyncDisabled - notify listener - remove metadata`() { syncPersister.onSyncDisabled() verify(store).serverModifiedSince = "0" verify(store).clientModifiedSince = "0" diff --git a/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/algorithm/SavedSitesSyncPersisterAlgorithmTest.kt b/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/algorithm/SavedSitesSyncPersisterAlgorithmTest.kt index b3b9a56da93c..a9a58d7aad7a 100644 --- a/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/algorithm/SavedSitesSyncPersisterAlgorithmTest.kt +++ b/saved-sites/saved-sites-impl/src/test/java/com/duckduckgo/savedsites/impl/sync/algorithm/SavedSitesSyncPersisterAlgorithmTest.kt @@ -82,7 +82,7 @@ class SavedSitesSyncPersisterAlgorithmTest { } @Test - fun whenProcessingEntriesWithDeduplicationStrategyThenDeduplicationPersisterIsUsed() { + fun `processEntries - deduplication strategy used - deduplication persister used`() { val rootFolder = BookmarkFolder( id = SavedSitesNames.BOOKMARKS_ROOT, name = SavedSitesNames.BOOKMARKS_NAME, @@ -110,7 +110,7 @@ class SavedSitesSyncPersisterAlgorithmTest { } @Test - fun whenProcessingEntriesWithTimestampStrategyThenTimestampPersisterIsUsed() { + fun `processEntries - timestamp strategy used - timestamp persister used`() { val rootFolder = BookmarkFolder( id = SavedSitesNames.BOOKMARKS_ROOT, name = SavedSitesNames.BOOKMARKS_NAME, @@ -138,7 +138,7 @@ class SavedSitesSyncPersisterAlgorithmTest { } @Test - fun whenProcessingEntriesWithRemoteStrategyThenRemotePersisterIsUsed() { + fun `processEntries - remote strategy used - remote persister used`() { val rootFolder = BookmarkFolder( id = SavedSitesNames.BOOKMARKS_ROOT, name = SavedSitesNames.BOOKMARKS_NAME, @@ -166,7 +166,7 @@ class SavedSitesSyncPersisterAlgorithmTest { } @Test - fun whenProcessingEntriesWithLocalStrategyThenLocalPersisterIsUsed() { + fun `processEntries - local strategy used - success`() { val rootFolder = BookmarkFolder( id = SavedSitesNames.BOOKMARKS_ROOT, name = SavedSitesNames.BOOKMARKS_NAME, @@ -199,7 +199,7 @@ class SavedSitesSyncPersisterAlgorithmTest { } @Test - fun whenProcessingOrphansThenResultIsSuccess() { + fun `processOrphans - result is success`() { val folder = BookmarkFolder(id = "folder1", name = "name", lastModified = twoHoursAgo, parentId = SavedSitesNames.BOOKMARKS_ROOT) val bookmark = Bookmark(id = "bookmark1", title = "title", url = "foo.com", lastModified = twoHoursAgo, parentId = folder.id) val someEntries = SyncBookmarkEntries( diff --git a/saved-sites/saved-sites-store/src/test/java/com/duckduckgo/savedsites/store/SavedSitesSettingsSharedPrefStoreTest.kt b/saved-sites/saved-sites-store/src/test/java/com/duckduckgo/savedsites/store/SavedSitesSettingsSharedPrefStoreTest.kt index afddd330569d..59a42f92b1f5 100644 --- a/saved-sites/saved-sites-store/src/test/java/com/duckduckgo/savedsites/store/SavedSitesSettingsSharedPrefStoreTest.kt +++ b/saved-sites/saved-sites-store/src/test/java/com/duckduckgo/savedsites/store/SavedSitesSettingsSharedPrefStoreTest.kt @@ -35,19 +35,19 @@ class SavedSitesSettingsSharedPrefStoreTest { } @Test - fun whenGetFavoritesDisplayModeThenReturnStoredValue() = runTest { + fun `getFavoritesDisplayMode - stored value - native`() = runTest { prefs.edit().putString(KEY_FAVORITES_DISPLAY_MODE, NATIVE.value).commit() assertEquals(NATIVE, testee.favoritesDisplayMode) } @Test - fun whenNoValueThenReturnNative() = runTest { + fun `whenNoValueThenReturnNative - favorites display mode native`() = runTest { assertEquals(NATIVE, testee.favoritesDisplayMode) } @Test - fun whenValueChangedThenFlowEmitsNewValue() = runTest { + fun `favoritesFormFactorModeFlow - value changed - emits new value`() = runTest { prefs.edit().putString(KEY_FAVORITES_DISPLAY_MODE, NATIVE.value).commit() testee.favoritesFormFactorModeFlow().test { assertEquals(NATIVE, awaitItem()) diff --git a/site-permissions/site-permissions-impl/src/test/java/com/duckduckgo/site/permissions/impl/SitePermissionsManagerTest.kt b/site-permissions/site-permissions-impl/src/test/java/com/duckduckgo/site/permissions/impl/SitePermissionsManagerTest.kt index c713f64bde8d..a041271a3ebe 100644 --- a/site-permissions/site-permissions-impl/src/test/java/com/duckduckgo/site/permissions/impl/SitePermissionsManagerTest.kt +++ b/site-permissions/site-permissions-impl/src/test/java/com/duckduckgo/site/permissions/impl/SitePermissionsManagerTest.kt @@ -55,7 +55,7 @@ class SitePermissionsManagerTest { } @Test - fun givenListOfPermissionsThenPermissionsReturnedCorrectly() = runTest { + fun `getSitePermissions - given list of permissions - permissions returned correctly`() = runTest { val resources = arrayOf(PermissionRequest.RESOURCE_AUDIO_CAPTURE, PermissionRequest.RESOURCE_VIDEO_CAPTURE) whenever(mockSitePermissionsRepository.isDomainAllowedToAsk(url, PermissionRequest.RESOURCE_VIDEO_CAPTURE)).thenReturn(true) whenever(mockSitePermissionsRepository.isDomainAllowedToAsk(url, PermissionRequest.RESOURCE_AUDIO_CAPTURE)).thenReturn(true) @@ -74,7 +74,7 @@ class SitePermissionsManagerTest { } @Test - fun givenListOfPermissionsShouldAutoAcceptThenGrantAndClearAutoHandlePermissions() = runTest { + fun `getSitePermissions - auto accept then grant and clear auto handle permissions`() = runTest { val resources = arrayOf(PermissionRequest.RESOURCE_AUDIO_CAPTURE, PermissionRequest.RESOURCE_VIDEO_CAPTURE) whenever(mockSitePermissionsRepository.isDomainAllowedToAsk(url, PermissionRequest.RESOURCE_VIDEO_CAPTURE)).thenReturn(true) whenever(mockSitePermissionsRepository.isDomainAllowedToAsk(url, PermissionRequest.RESOURCE_AUDIO_CAPTURE)).thenReturn(true) @@ -92,7 +92,7 @@ class SitePermissionsManagerTest { } @Test - fun givenListOfPermissionsThenFilterNotSupportedAndReturnOnlyPermissionsAllowedToAsk() = runTest { + fun `getSitePermissions - given list of permissions - filter not supported and return only permissions allowed to ask`() = runTest { val resources = arrayOf(PermissionRequest.RESOURCE_VIDEO_CAPTURE, PermissionRequest.RESOURCE_MIDI_SYSEX, PermissionRequest.RESOURCE_AUDIO_CAPTURE) whenever(mockSitePermissionsRepository.isDomainAllowedToAsk(url, PermissionRequest.RESOURCE_VIDEO_CAPTURE)).thenReturn(true) @@ -110,7 +110,7 @@ class SitePermissionsManagerTest { } @Test - fun givenListOfPermissionsNoHardwareCameraThenFilterNotSupportedAndThenDenyPermissions() = runTest { + fun `getSitePermissions - no hardware camera - filter not supported and then deny permissions`() = runTest { val resources = arrayOf(PermissionRequest.RESOURCE_VIDEO_CAPTURE, PermissionRequest.RESOURCE_MIDI_SYSEX, PermissionRequest.RESOURCE_AUDIO_CAPTURE) whenever(mockSitePermissionsRepository.isDomainAllowedToAsk(url, PermissionRequest.RESOURCE_VIDEO_CAPTURE)).thenReturn(true) @@ -128,7 +128,7 @@ class SitePermissionsManagerTest { } @Test - fun whenPermissionsShouldAutoDenyThenDeny() = runTest { + fun `getSitePermissions - permissions should auto deny - deny`() = runTest { val resources = arrayOf(PermissionRequest.RESOURCE_VIDEO_CAPTURE, PermissionRequest.RESOURCE_MIDI_SYSEX, PermissionRequest.RESOURCE_AUDIO_CAPTURE) whenever(mockSitePermissionsRepository.isDomainAllowedToAsk(url, PermissionRequest.RESOURCE_VIDEO_CAPTURE)).thenReturn(false) @@ -145,7 +145,7 @@ class SitePermissionsManagerTest { } @Test - fun whenClearAllButFireproofThenDontDeleteEntitiesWhichDomainIsInTheFireproofList() = runTest { + fun `clearAllButFireproof - dont delete entities which domain is in fireproof list`() = runTest { val fireproofDomain = "domain.com" val testFireproofList = listOf(fireproofDomain, "domain1.com") val testSitePermissionsList = listOf(SitePermissionsEntity(fireproofDomain), SitePermissionsEntity("domain2.com")) @@ -156,7 +156,7 @@ class SitePermissionsManagerTest { } @Test - fun whenClearAllButFireproofThenDeleteEntitiesWhichDomainIsNotInTheFireproofList() = runTest { + fun `clearAllButFireproof - delete entities which domain is not in fireproof list`() = runTest { val domain = "domain2.com" val testFireproofList = listOf("domain.com", "domain1.com") val testSitePermissionsList = listOf(SitePermissionsEntity("domain.com"), SitePermissionsEntity(domain)) @@ -167,14 +167,14 @@ class SitePermissionsManagerTest { } @Test - fun whenDomainGrantedThenGetPermissionsQueryResponseReturnsGranted() { + fun `getPermissionsQueryResponse - domain granted - granted`() { whenever(mockSitePermissionsRepository.isDomainGranted(url, tabId, PermissionRequest.RESOURCE_VIDEO_CAPTURE)).thenReturn(true) assertEquals(SitePermissionQueryResponse.Granted, testee.getPermissionsQueryResponse(url, tabId, "camera")) } @Test - fun whenDomainAllowedToAskThenGetPermissionsQueryResponseReturnsPrompt() { + fun `getPermissionsQueryResponse - domain allowed to ask - prompt`() { whenever(mockSitePermissionsRepository.isDomainGranted(url, tabId, PermissionRequest.RESOURCE_VIDEO_CAPTURE)).thenReturn(false) whenever(mockPackageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)).thenReturn(true) whenever(mockSitePermissionsRepository.isDomainAllowedToAsk(url, PermissionRequest.RESOURCE_VIDEO_CAPTURE)).thenReturn(true) @@ -183,7 +183,7 @@ class SitePermissionsManagerTest { } @Test - fun whenDomainNotAllowedToAskThenGetPermissionsQueryResponseReturnsDenied() { + fun `getPermissionsQueryResponse - domain not allowed to ask - denied`() { whenever(mockSitePermissionsRepository.isDomainGranted(url, tabId, PermissionRequest.RESOURCE_VIDEO_CAPTURE)).thenReturn(false) whenever(mockPackageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)).thenReturn(true) whenever(mockSitePermissionsRepository.isDomainAllowedToAsk(url, PermissionRequest.RESOURCE_VIDEO_CAPTURE)).thenReturn(false) @@ -192,7 +192,7 @@ class SitePermissionsManagerTest { } @Test - fun whenHardwareNotSupportedThenGetPermissionsQueryResponseReturnsDenied() { + fun `getPermissionsQueryResponse - hardware not supported - denied`() { whenever(mockSitePermissionsRepository.isDomainGranted(url, tabId, PermissionRequest.RESOURCE_VIDEO_CAPTURE)).thenReturn(false) whenever(mockPackageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)).thenReturn(false) whenever(mockSitePermissionsRepository.isDomainAllowedToAsk(url, PermissionRequest.RESOURCE_VIDEO_CAPTURE)).thenReturn(true) @@ -201,7 +201,7 @@ class SitePermissionsManagerTest { } @Test - fun whenAndroidPermissionNotSupportedThenGetPermissionsQueryResponseReturnsDenied() { + fun `getPermissionsQueryResponse - android permission not supported - denied`() { assertEquals(SitePermissionQueryResponse.Denied, testee.getPermissionsQueryResponse(url, tabId, "unsupported")) } } diff --git a/site-permissions/site-permissions-impl/src/test/java/com/duckduckgo/site/permissions/impl/SitePermissionsRepositoryTest.kt b/site-permissions/site-permissions-impl/src/test/java/com/duckduckgo/site/permissions/impl/SitePermissionsRepositoryTest.kt index 06c28422dc3d..bb71bd3e5257 100644 --- a/site-permissions/site-permissions-impl/src/test/java/com/duckduckgo/site/permissions/impl/SitePermissionsRepositoryTest.kt +++ b/site-permissions/site-permissions-impl/src/test/java/com/duckduckgo/site/permissions/impl/SitePermissionsRepositoryTest.kt @@ -63,7 +63,7 @@ class SitePermissionsRepositoryTest { private val domain = "domain.com" @Test - fun givenPermissionNotSupportedThenDomainIsNotAllowedToAsk() { + fun `givenPermissionNotSupported - is domain allowed to ask - not allowed`() { setInitialSettings() val permission = PermissionRequest.RESOURCE_MIDI_SYSEX @@ -71,7 +71,7 @@ class SitePermissionsRepositoryTest { } @Test - fun givenPermissionSupportedThenDomainIsAllowedToAsk() { + fun `givenPermissionSupported - is domain allowed to ask - true`() { setInitialSettings() val permission = PermissionRequest.RESOURCE_AUDIO_CAPTURE @@ -79,7 +79,7 @@ class SitePermissionsRepositoryTest { } @Test - fun whenAskForPermissionIsDisabledThenDomainIsNotAllowedToAsk() { + fun `askForPermissionIsDisabled - domain is not allowed to ask - is not allowed`() { setInitialSettings(cameraEnabled = false) val permission = PermissionRequest.RESOURCE_VIDEO_CAPTURE @@ -87,7 +87,7 @@ class SitePermissionsRepositoryTest { } @Test - fun whenAskForPermissionDisabledButSitePermissionSettingIsAlwaysAllowThenIsAllowedToAsk() { + fun `isDomainAllowedToAsk - ask for permission disabled but site permission setting is always allow - is allowed to ask`() { val testEntity = SitePermissionsEntity(domain, askMicSetting = SitePermissionAskSettingType.ALLOW_ALWAYS.name) setInitialSettings(micEnabled = false, sitePermissionEntity = testEntity) val permission = PermissionRequest.RESOURCE_AUDIO_CAPTURE @@ -96,7 +96,7 @@ class SitePermissionsRepositoryTest { } @Test - fun whenSitePermissionSettingIsDenyAlwaysThenDomainIsNotAllowedToAsk() { + fun `isDomainAllowedToAsk - site permission setting is deny always - not allowed to ask`() { val testEntity = SitePermissionsEntity(domain, askCameraSetting = SitePermissionAskSettingType.DENY_ALWAYS.name) setInitialSettings(sitePermissionEntity = testEntity) val permission = PermissionRequest.RESOURCE_VIDEO_CAPTURE @@ -105,7 +105,7 @@ class SitePermissionsRepositoryTest { } @Test - fun whenNoSitePermissionSettingAndDrmBlockedThenDomainIsNotAllowedToAsk() { + fun `isDomainAllowedToAsk - no site permission setting and drm blocked - domain is not allowed to ask`() { val permission = PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID whenever(mockDrmBlock.isDrmBlockedForUrl(url)).thenReturn(true) @@ -114,7 +114,7 @@ class SitePermissionsRepositoryTest { } @Test - fun whenSitePermissionSettingIsAskAndDrmBlockedThenDomainIsAllowedToAsk() { + fun `isDomainAllowedToAsk - site permission setting ask and drm blocked - allowed to ask`() { val testEntity = SitePermissionsEntity(domain, askDrmSetting = SitePermissionAskSettingType.ASK_EVERY_TIME.name) setInitialSettings(sitePermissionEntity = testEntity) val permission = PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID @@ -125,7 +125,7 @@ class SitePermissionsRepositoryTest { } @Test - fun whenSitePermissionsWasGrantedWithin24hThenReturnPermissionGranted() { + fun `isDomainGranted - site permissions granted within 24h - return permission granted`() { setInitialSettings() val permission = PermissionRequest.RESOURCE_VIDEO_CAPTURE val tabId = "tabId" @@ -136,7 +136,7 @@ class SitePermissionsRepositoryTest { } @Test - fun whenSitePermissionsWasMoreThen24hAgoThenReturnPermissionNotGranted() { + fun `getSitePermission - site permissions was more than 24 hours ago - return permission not granted`() { setInitialSettings() val permission = PermissionRequest.RESOURCE_VIDEO_CAPTURE val tabId = "tabId" @@ -147,7 +147,7 @@ class SitePermissionsRepositoryTest { } @Test - fun whenSitePermissionsSettingIsAllowAlwaysThenReturnPermissionGranted() { + fun `getSitePermission - site permissions setting allow always - permission granted`() { val testEntity = SitePermissionsEntity(domain, askCameraSetting = SitePermissionAskSettingType.ALLOW_ALWAYS.name) setInitialSettings(sitePermissionEntity = testEntity) val permission = PermissionRequest.RESOURCE_VIDEO_CAPTURE @@ -158,7 +158,7 @@ class SitePermissionsRepositoryTest { } @Test - fun whenUserGrantsSitePermissionFirstTimeThenSaveEntity() = runTest { + fun `whenUserGrantsSitePermissionFirstTime - save entity`() = runTest { val testEntity = SitePermissionsEntity(domain) setInitialSettings() repository.sitePermissionGranted(url, "tabId", PermissionRequest.RESOURCE_VIDEO_CAPTURE) @@ -167,7 +167,7 @@ class SitePermissionsRepositoryTest { } @Test - fun whenUserGrantsSitePermissionAlreadyInDbThenSkipSaveEntity() = runTest { + fun `whenUserGrantsSitePermissionAlreadyInDbThenSkipSaveEntity - site permission granted - skip save entity`() = runTest { val testEntity = SitePermissionsEntity(domain) setInitialSettings(sitePermissionEntity = testEntity) repository.sitePermissionGranted(url, "tabId", PermissionRequest.RESOURCE_VIDEO_CAPTURE) @@ -176,7 +176,7 @@ class SitePermissionsRepositoryTest { } @Test - fun whenUserGrantsSitePermissionThenSaveAllowedEntity() = runTest { + fun `whenUserGrantsSitePermission - save allowed entity`() = runTest { setInitialSettings() repository.sitePermissionGranted(url, "tabId", PermissionRequest.RESOURCE_VIDEO_CAPTURE) @@ -184,28 +184,28 @@ class SitePermissionsRepositoryTest { } @Test - fun whenSitePermissionsWebsitesFlowIsCalledThenGetSitePermissionsWebsitesFlow() = runTest { + fun `sitePermissionsWebsitesFlow - site permissions websites flow`() = runTest { repository.sitePermissionsWebsitesFlow() verify(mockSitePermissionsDao).getAllSitesPermissionsAsFlow() } @Test - fun whenSitePermissionsForAllWebsitesIsCalledThenGetSitePermissionsForAllWebsites() = runTest { + fun `sitePermissionsForAllWebsites - get site permissions for all websites`() = runTest { repository.sitePermissionsForAllWebsites() verify(mockSitePermissionsDao).getAllSitesPermissions() } @Test - fun whenSitePermissionsAllowedFlowIsCalledThenGetSitePermissionsAllowedFlow() = runTest { + fun `sitePermissionsAllowedFlow - site permissions allowed flow`() = runTest { repository.sitePermissionsAllowedFlow() verify(mockSitePermissionsAllowedDao).getAllSitesPermissionsAllowedAsFlow() } @Test - fun whenUndoDeleteAllThenInsertSitePermissionsBackToAllowedDao() = runTest { + fun `undoDeleteAll - site permissions allowed dao - insert back to allowed`() = runTest { val tabId = "tabId" val permission = PermissionRequest.RESOURCE_AUDIO_CAPTURE val testAllowedEntity = SitePermissionAllowedEntity(domain, tabId, permission, setAllowedAtTime(12)) @@ -217,7 +217,7 @@ class SitePermissionsRepositoryTest { } @Test - fun whenUndoDeleteAllThenInsertSitePermissionsBackToSitePermissionsDao() = runTest { + fun `undoDeleteAll - site permissions dao inserted`() = runTest { val testEntity = SitePermissionsEntity(domain) val sitePermissions = listOf(testEntity) @@ -227,7 +227,7 @@ class SitePermissionsRepositoryTest { } @Test - fun whenDeleteAllThenDeleteEntitiesFromDatabases() = runTest { + fun `deleteAll - delete entities from databases`() = runTest { repository.deleteAll() verify(mockSitePermissionsDao).deleteAll() @@ -235,14 +235,14 @@ class SitePermissionsRepositoryTest { } @Test - fun whenGetSitePermissionsForWebsiteCalledThenGetSitePermissionsByDomain() = runTest { + fun `getSitePermissionsForWebsite - get site permissions by domain`() = runTest { repository.getSitePermissionsForWebsite(url) verify(mockSitePermissionsDao).getSitePermissionsByDomain(domain) } @Test - fun whenDeletePermissionForSiteThenDeleteItFromDbs() = runTest { + fun `deletePermissionForSite - delete from dbs`() = runTest { val testEntity = SitePermissionsEntity(domain) whenever(mockSitePermissionsDao.getSitePermissionsByDomain(domain)).thenReturn(testEntity) repository.deletePermissionsForSite(url) @@ -252,7 +252,7 @@ class SitePermissionsRepositoryTest { } @Test - fun whenSavePermissionCalledThenInsertEntityInDb() = runTest { + fun `savePermission - insert entity in db`() = runTest { val testEntity = SitePermissionsEntity(domain) repository.savePermission(testEntity) diff --git a/site-permissions/site-permissions-impl/src/test/java/com/duckduckgo/site/permissions/impl/drmblock/RealDrmBlockTest.kt b/site-permissions/site-permissions-impl/src/test/java/com/duckduckgo/site/permissions/impl/drmblock/RealDrmBlockTest.kt index 6439349aa4c3..58079bbb1777 100644 --- a/site-permissions/site-permissions-impl/src/test/java/com/duckduckgo/site/permissions/impl/drmblock/RealDrmBlockTest.kt +++ b/site-permissions/site-permissions-impl/src/test/java/com/duckduckgo/site/permissions/impl/drmblock/RealDrmBlockTest.kt @@ -50,12 +50,12 @@ class RealDrmBlockTest { } @Test - fun whenFeatureDisabledThenFalseIsReturned() { + fun `isDrmBlockedForUrl - feature disabled - false`() { assertFalse(testee.isDrmBlockedForUrl(url)) } @Test - fun whenFeatureEnabledUrlNotBlockedThenFalseIsReturned() { + fun `isDrmBlockedForUrl - feature enabled url not blocked - false returned`() { givenFeatureIsEnabled() givenUrlIsNotInExceptionList() @@ -63,7 +63,7 @@ class RealDrmBlockTest { } @Test - fun whenFeatureEnabledUrlBlockedUserAllowedThenFalseIsReturned() { + fun `givenFeatureEnabled - url blocked user allowed - false returned`() { givenFeatureIsEnabled() givenUrlIsInExceptionList() givenUriIsInUserAllowList() @@ -72,7 +72,7 @@ class RealDrmBlockTest { } @Test - fun whenFeatureEnabledUrlBlockedNotUserAllowedUnprotectedTempThenFalseIsReturned() { + fun `isDrmBlockedForUrl - feature enabled - url blocked not user allowed unprotected temp - false returned`() { givenFeatureIsEnabled() givenUrlIsInExceptionList() givenUrlIsInUnprotectedTemporary() @@ -81,7 +81,7 @@ class RealDrmBlockTest { } @Test - fun whenFeatureEnabledUrlBlockedNotUserAllowedNotUnprotectedTempThenTrueIsReturned() { + fun `isDrmBlockedForUrl - feature enabled - true returned`() { givenFeatureIsEnabled() givenUrlIsInExceptionList() diff --git a/statistics/src/test/java/com/duckduckgo/app/statistics/AtbInitializerTest.kt b/statistics/src/test/java/com/duckduckgo/app/statistics/AtbInitializerTest.kt index a346fcb8f985..54df27c56e70 100644 --- a/statistics/src/test/java/com/duckduckgo/app/statistics/AtbInitializerTest.kt +++ b/statistics/src/test/java/com/duckduckgo/app/statistics/AtbInitializerTest.kt @@ -41,7 +41,7 @@ class AtbInitializerTest { private var atbInitializerListener = FakeAtbInitializerListener() @Test - fun whenReferrerInformationInstantlyAvailableThenAtbInitialized() = runTest { + fun `onPrivacyConfigDownloaded - atb initialized`() = runTest { configureNeverInitialized() testee.onPrivacyConfigDownloaded() @@ -67,7 +67,7 @@ class AtbInitializerTest { } @Test - fun whenReferrerInformationTimesOutThenRefreshAtbNotCalled() = runTest { + fun `initialize - referrer information times out - refresh atb not called`() = runTest { whenever(statisticsDataStore.hasInstallationStatistics).thenReturn(false) atbInitializerListener.delay = Duration.INFINITE testee = AtbInitializer( @@ -84,7 +84,7 @@ class AtbInitializerTest { } @Test - fun whenAlreadyInitializedThenRefreshCalled() = runTest { + fun `initialize - already initialized - refresh called`() = runTest { configureAlreadyInitialized() testee.initialize() @@ -93,7 +93,7 @@ class AtbInitializerTest { } @Test - fun givenHasInstallationStatisticsWhenOnPrivacyConfigDownloadedThenAtbInitializedNeverCalled() = runTest { + fun `onPrivacyConfigDownloaded - given has installation statistics - atb initialized never called`() = runTest { configureAlreadyInitialized() testee.onPrivacyConfigDownloaded() @@ -102,7 +102,7 @@ class AtbInitializerTest { } @Test - fun givenNeverInstallationStatisticsWhenOnPrivacyConfigDownloadedThenAtbInitialized() = runTest { + fun `onPrivacyConfigDownloaded - never installation statistics - atb initialized`() = runTest { configureNeverInitialized() testee.onPrivacyConfigDownloaded() diff --git a/statistics/src/test/java/com/duckduckgo/app/statistics/api/RxPixelSenderTest.kt b/statistics/src/test/java/com/duckduckgo/app/statistics/api/RxPixelSenderTest.kt index 80c304da37ac..b4eba2e79070 100644 --- a/statistics/src/test/java/com/duckduckgo/app/statistics/api/RxPixelSenderTest.kt +++ b/statistics/src/test/java/com/duckduckgo/app/statistics/api/RxPixelSenderTest.kt @@ -112,7 +112,7 @@ class RxPixelSenderTest { } @Test - fun whenPixelFiredThenPixelServiceCalledWithCorrectAtbAndVariant() { + fun `sendPixel - pixel fired - pixel service called with correct atb and variant`() { givenPixelApiSucceeds() givenAtbVariant(Atb("atb")) givenVariant("variant") @@ -125,7 +125,7 @@ class RxPixelSenderTest { } @Test - fun whenPixelFiredTabletFormFactorThenPixelServiceCalledWithTabletParameter() { + fun `sendPixel - pixel fired tablet form factor - pixel service called with tablet parameter`() { givenApiSendPixelSucceeds() givenFormFactor(DeviceInfo.FormFactor.TABLET) @@ -136,7 +136,7 @@ class RxPixelSenderTest { } @Test - fun whenPixelFiredWithNoAtbThenPixelServiceCalledWithCorrectPixelNameAndNoAtb() { + fun `sendPixel - no atb - pixel service called with correct pixel name and no atb`() { givenApiSendPixelSucceeds() givenFormFactor(DeviceInfo.FormFactor.PHONE) @@ -147,7 +147,7 @@ class RxPixelSenderTest { } @Test - fun whenPixelFiredWithAdditionalParametersThenPixelServiceCalledWithDefaultAndAdditionalParameters() { + fun `sendPixel - pixel fired with additional parameters - pixel service called`() { givenPixelApiSucceeds() givenAtbVariant(Atb("atb")) givenVariant("variant") @@ -163,7 +163,7 @@ class RxPixelSenderTest { } @Test - fun whenPixelFiredWithoutAdditionalParametersThenPixelServiceCalledWithOnlyDefaultParameters() { + fun `sendPixel - no additional parameters - pixel service called with default parameters`() { givenPixelApiSucceeds() givenAtbVariant(Atb("atb")) givenVariant("variant") @@ -178,7 +178,7 @@ class RxPixelSenderTest { } @Test - fun whenPixelEnqueuedWitAdditionalParametersThenPixelEnqueuedWithParameters() { + fun `enqueuePixel - with additional parameters - enqueued with parameters`() { givenAtbVariant(Atb("atb")) givenVariant("variant") givenFormFactor(DeviceInfo.FormFactor.PHONE) @@ -203,7 +203,7 @@ class RxPixelSenderTest { } @Test - fun whenPixelEnqueuedWithoutAdditionalParametersThenPixelEnqueuedWithOnlyDefaultParameters() { + fun `enqueuePixel - no additional parameters - pixel enqueued with default parameters`() { givenAtbVariant(Atb("atb")) givenVariant("variant") givenFormFactor(DeviceInfo.FormFactor.PHONE) @@ -225,7 +225,7 @@ class RxPixelSenderTest { } @Test - fun whenAppForegroundedThenPixelSent() { + fun `onStart - app foregrounded - pixel sent`() { givenPixelApiSucceeds() val pixelEntity = PixelEntity( pixelName = "test", @@ -248,7 +248,7 @@ class RxPixelSenderTest { } @Test - fun whenAppForegroundedAndPixelSentThenPixelRemoved() { + fun `onStart - app foregrounded and pixel sent - pixel removed`() { givenPixelApiSucceeds() val pixelEntity = PixelEntity( pixelName = "test", @@ -266,7 +266,7 @@ class RxPixelSenderTest { } @Test - fun whenAppForegroundedAndSendPixelFailsThenPixelNotRemoved() { + fun `onStart - app foregrounded and send pixel fails - pixel not removed`() { givenPixelApiFails() val pixelEntity = PixelEntity( pixelName = "test", @@ -285,7 +285,7 @@ class RxPixelSenderTest { } @Test - fun whenAppForegroundedWithMultiplePixelsEnqueuedThenSendAllPixels() { + fun `onStart - app foregrounded with multiple pixels enqueued - send all pixels`() { givenPixelApiSucceeds() val pixelEntity = PixelEntity( pixelName = "test", @@ -308,7 +308,7 @@ class RxPixelSenderTest { } @Test - fun whenDailyPixelIsFiredThenPixelNameIsStored() = runTest { + fun `sendPixel - daily pixel fired - pixel name stored`() = runTest { givenPixelApiSucceeds() givenFormFactor(DeviceInfo.FormFactor.PHONE) @@ -320,7 +320,7 @@ class RxPixelSenderTest { } @Test - fun whenDailyPixelFireFailsThenPixelNameIsNotStored() = runTest { + fun `sendPixel - daily pixel fire fails - pixel name not stored`() = runTest { givenPixelApiFails() givenFormFactor(DeviceInfo.FormFactor.PHONE) @@ -332,7 +332,7 @@ class RxPixelSenderTest { } @Test - fun whenDailyPixelHasAlreadyBeenFiredTodayThenItIsNotFiredAgain() = runTest { + fun `sendPixel - daily pixel already fired today - not fired again`() = runTest { pixelFiredRepository.dailyPixelsFiredToday += TEST.pixelName testee.sendPixel(TEST.pixelName, emptyMap(), emptyMap(), DAILY) @@ -343,7 +343,7 @@ class RxPixelSenderTest { } @Test - fun whenUniquePixelIsFiredThenPixelNameIsStored() = runTest { + fun `sendPixel - unique pixel fired - pixel name stored`() = runTest { givenPixelApiSucceeds() givenFormFactor(DeviceInfo.FormFactor.PHONE) @@ -355,7 +355,7 @@ class RxPixelSenderTest { } @Test - fun whenUniquePixelFireFailsThenPixelNameIsNotStored() = runTest { + fun `sendPixel - unique pixel fire fails - not stored`() = runTest { givenPixelApiFails() givenFormFactor(DeviceInfo.FormFactor.PHONE) @@ -367,7 +367,7 @@ class RxPixelSenderTest { } @Test - fun whenUniquePixelHasAlreadyBeenFiredThenItIsNotFiredAgain() = runTest { + fun `sendPixel - unique pixel already fired - not fired again`() = runTest { pixelFiredRepository.uniquePixelsFired += TEST.pixelName testee.sendPixel(TEST.pixelName, emptyMap(), emptyMap(), UNIQUE) diff --git a/statistics/src/test/java/com/duckduckgo/app/statistics/api/StatisticsRequesterTest.kt b/statistics/src/test/java/com/duckduckgo/app/statistics/api/StatisticsRequesterTest.kt index bc6e79d0a1be..92431376a2e4 100644 --- a/statistics/src/test/java/com/duckduckgo/app/statistics/api/StatisticsRequesterTest.kt +++ b/statistics/src/test/java/com/duckduckgo/app/statistics/api/StatisticsRequesterTest.kt @@ -76,7 +76,7 @@ class StatisticsRequesterTest { } @Test - fun whenUpdateVersionPresentDuringRefreshSearchRetentionThenPreviousAtbIsReplacedWithUpdateVersion() { + fun `refreshSearchRetentionAtb - update version present during refresh search retention - previous atb replaced with update version`() { configureStoredStatistics() whenever(mockService.updateSearchAtb(any(), any(), any(), eq(0))).thenReturn(Observable.just(UPDATE_ATB)) testee.refreshSearchRetentionAtb() @@ -84,7 +84,7 @@ class StatisticsRequesterTest { } @Test - fun whenUpdateVersionPresentDuringRefreshSearchRetentionThenPreviousVariantIsReplacedWithDefaultVariant() { + fun `refreshSearchRetentionAtb - update version present during refresh search retention - previous variant replaced with default variant`() { configureStoredStatistics() whenever(mockService.updateSearchAtb(any(), any(), any(), eq(0))).thenReturn(Observable.just(UPDATE_ATB)) testee.refreshSearchRetentionAtb() @@ -92,7 +92,7 @@ class StatisticsRequesterTest { } @Test - fun whenUpdateVersionPresentDuringRefreshAppRetentionThenPreviousAtbIsReplacedWithUpdateVersion() { + fun `refreshAppRetention - update version present during refresh app retention - previous atb replaced with update version`() { configureStoredStatistics() whenever(mockService.updateAppAtb(any(), any(), any(), eq(0))).thenReturn(Observable.just(UPDATE_ATB)) testee.refreshAppRetentionAtb() @@ -100,7 +100,7 @@ class StatisticsRequesterTest { } @Test - fun whenUpdateVersionPresentDuringRefreshAppRetentionThenPreviousVariantIsReplacedWithDefaultVariant() { + fun `refreshAppRetention - update version present during refresh app retention - previous variant replaced with default variant`() { configureStoredStatistics() whenever(mockService.updateAppAtb(any(), any(), any(), eq(0))).thenReturn(Observable.just(UPDATE_ATB)) testee.refreshAppRetentionAtb() @@ -108,7 +108,7 @@ class StatisticsRequesterTest { } @Test - fun whenNoStatisticsStoredThenInitializeAtbInvokesExti() { + fun `initializeAtb - no statistics stored - invokes exti`() { configureNoStoredStatistics() testee.initializeAtb() verify(mockService).atb(any(), eq(0)) @@ -117,7 +117,7 @@ class StatisticsRequesterTest { } @Test - fun whenStatisticsStoredThenInitializeAtbDoesNothing() { + fun `initializeAtb - statistics stored - does nothing`() { configureStoredStatistics() testee.initializeAtb() verify(mockService, never()).atb(any(), any()) @@ -125,7 +125,7 @@ class StatisticsRequesterTest { } @Test - fun whenNoStatisticsStoredThenRefreshSearchRetentionRetrievesAtbAndInvokesExti() { + fun `refreshSearchRetention - no statistics stored - retrieves atb and invokes exti`() { configureNoStoredStatistics() testee.refreshSearchRetentionAtb() verify(mockService).atb(any(), any()) @@ -134,7 +134,7 @@ class StatisticsRequesterTest { } @Test - fun whenNoStatisticsStoredThenRefreshAppRetentionRetrievesAtbAndInvokesExti() { + fun `refreshAppRetention - no statistics stored - retrieves atb and invokes exti`() { configureNoStoredStatistics() testee.refreshAppRetentionAtb() verify(mockService).atb(any(), any()) @@ -143,7 +143,7 @@ class StatisticsRequesterTest { } @Test - fun whenExtiFailsThenAtbCleared() { + fun `initializeAtb - exti fails - atb cleared`() { whenever(mockService.exti(any(), any())).thenReturn(Observable.error(Throwable())) configureNoStoredStatistics() testee.initializeAtb() @@ -152,7 +152,7 @@ class StatisticsRequesterTest { } @Test - fun whenStatisticsStoredThenRefreshIncludesRefreshedAtb() { + fun `refreshSearchRetentionAtb - statistics stored - refresh includes refreshed atb`() { configureStoredStatistics() val retentionAtb = "foo" whenever(mockStatisticsStore.searchRetentionAtb).thenReturn(retentionAtb) @@ -161,7 +161,7 @@ class StatisticsRequesterTest { } @Test - fun whenStatisticsStoredThenRefreshUpdatesAtb() { + fun `refresh - statistics stored - updates atb`() { configureStoredStatistics() testee.refreshSearchRetentionAtb() verify(mockService).updateSearchAtb(eq(ATB_WITH_VARIANT), eq(ATB.version), any(), any()) @@ -169,7 +169,7 @@ class StatisticsRequesterTest { } @Test - fun whenAlreadyInitializedWithLegacyAtbThenInitializationRemovesLegacyVariant() { + fun `initializeAtb - already initialized with legacy atb - removes legacy variant`() { configureStoredStatistics() whenever(mockVariantManager.defaultVariantKey()).thenReturn("") whenever(mockStatisticsStore.atb).thenReturn(Atb("v123ma")) @@ -179,7 +179,7 @@ class StatisticsRequesterTest { } @Test - fun whenInitializeAtbAndEmailEnabledThenEmailSignalToTrue() { + fun `initializeAtb - email enabled - email signal to true`() { whenever(mockEmailManager.isSignedIn()).thenReturn(true) configureNoStoredStatistics() @@ -189,7 +189,7 @@ class StatisticsRequesterTest { } @Test - fun whenRefreshSearchAtbAndEmailEnabledThenEmailSignalToTrue() { + fun `refreshSearchAtb - email enabled - email signal to true`() { whenever(mockEmailManager.isSignedIn()).thenReturn(true) configureStoredStatistics() whenever(mockService.updateSearchAtb(any(), any(), any(), eq(1))).thenReturn(Observable.just(UPDATE_ATB)) @@ -200,7 +200,7 @@ class StatisticsRequesterTest { } @Test - fun whenRefreshAppRetentionAndEmailEnabledThenEmailSignalToTrue() { + fun `refreshAppRetention - email enabled - email signal to true`() { whenever(mockEmailManager.isSignedIn()).thenReturn(true) configureStoredStatistics() whenever(mockService.updateAppAtb(any(), any(), any(), eq(1))).thenReturn(Observable.just(UPDATE_ATB)) diff --git a/statistics/src/test/java/com/duckduckgo/app/statistics/model/AtbJsonTest.kt b/statistics/src/test/java/com/duckduckgo/app/statistics/model/AtbJsonTest.kt index 9b088feb8dc7..17dce1ff708b 100644 --- a/statistics/src/test/java/com/duckduckgo/app/statistics/model/AtbJsonTest.kt +++ b/statistics/src/test/java/com/duckduckgo/app/statistics/model/AtbJsonTest.kt @@ -33,14 +33,14 @@ class AtbJsonTest { private val jsonAdapter: JsonAdapter = moshi.adapter(Atb::class.java) @Test - fun whenFormatIsValidThenDataIsConverted() { + fun `formatIsValid - data converted`() { val json = loadText(javaClass.classLoader!!, "json/atb_response_valid.json") val atb = jsonAdapter.fromJson(json)!! assertEquals("v105-3", atb.version) } @Test(expected = JsonEncodingException::class) - fun whenFormatIsInvalidThenExceptionIsThrown() { + fun `fromJson - format is invalid - exception thrown`() { assertNull(jsonAdapter.fromJson("invalid")) } } diff --git a/statistics/src/test/java/com/duckduckgo/app/statistics/pixels/RxBasedPixelTest.kt b/statistics/src/test/java/com/duckduckgo/app/statistics/pixels/RxBasedPixelTest.kt index 8e92da95b36e..bf49b520448d 100644 --- a/statistics/src/test/java/com/duckduckgo/app/statistics/pixels/RxBasedPixelTest.kt +++ b/statistics/src/test/java/com/duckduckgo/app/statistics/pixels/RxBasedPixelTest.kt @@ -42,7 +42,7 @@ class RxBasedPixelTest { val mockPixelSender = mock() @Test - fun whenPixelWithoutQueryParamsFiredThenPixelSentWithDefaultParams() { + fun `whenPixelWithoutQueryParamsFired - pixel sent with default params`() { givenSendPixelSucceeds() val pixel = RxBasedPixel(mockPixelSender) @@ -52,7 +52,7 @@ class RxBasedPixelTest { } @Test - fun whenPixelWithoutQueryParamsFiredFailsThenErrorHandled() { + fun `fire - pixel without query params fired fails - error handled`() { givenSendPixelFails() val pixel = RxBasedPixel(mockPixelSender) @@ -62,7 +62,7 @@ class RxBasedPixelTest { } @Test - fun whenPixelWithQueryParamsFiredThenPixelSentWithParams() { + fun `fire - with query params - sent with params`() { givenSendPixelSucceeds() val pixel = RxBasedPixel(mockPixelSender) @@ -73,7 +73,7 @@ class RxBasedPixelTest { } @Test - fun whenPixelWithoutQueryParamsEnqueuedThenPixelEnqueuedWithDefaultParams() { + fun `whenPixelWithoutQueryParamsEnqueuedThenPixelEnqueuedWithDefaultParams - default params`() { givenEnqueuePixelSucceeds() val pixel = RxBasedPixel(mockPixelSender) @@ -83,7 +83,7 @@ class RxBasedPixelTest { } @Test - fun whenPixelWithoutQueryParamsEnqueuedThenErrorHandled() { + fun `enqueuePixel - without query params enqueued - error handled`() { givenEnqueuePixelFails() val pixel = RxBasedPixel(mockPixelSender) @@ -93,7 +93,7 @@ class RxBasedPixelTest { } @Test - fun whenPixelWithQueryParamsEnqueuedThenPixelEnqueuedWithParams() { + fun `enqueuePixel - with query params enqueued - pixel enqueued with params`() { givenEnqueuePixelSucceeds() val pixel = RxBasedPixel(mockPixelSender) diff --git a/statistics/src/test/java/com/duckduckgo/app/statistics/store/PixelFiredRepositoryTest.kt b/statistics/src/test/java/com/duckduckgo/app/statistics/store/PixelFiredRepositoryTest.kt index bc7dbc4b773d..b40318bb9e2a 100644 --- a/statistics/src/test/java/com/duckduckgo/app/statistics/store/PixelFiredRepositoryTest.kt +++ b/statistics/src/test/java/com/duckduckgo/app/statistics/store/PixelFiredRepositoryTest.kt @@ -67,13 +67,13 @@ class PixelFiredRepositoryTest { } @Test - fun whenDatabaseIsEmptyThenPixelFiredIsFalse() = runTest { + fun `hasDailyPixelFired - database empty - false`() = runTest { assertFalse(subject.hasDailyPixelFiredToday("pixel_d")) assertFalse(subject.hasUniquePixelFired("pixel_u")) } @Test - fun whenPixelWasFiredThenPixelFiredIsTrue() = runTest { + fun `storeDailyPixelFired - pixel fired is true`() = runTest { subject.storeDailyPixelFiredToday("pixel_d") subject.storeUniquePixelFired("pixel_u") @@ -82,7 +82,7 @@ class PixelFiredRepositoryTest { } @Test - fun whenADayHasPassedThenDailyPixelFiredIsFalse() = runTest { + fun `storeDailyPixelFiredToday - daily pixel fired is false`() = runTest { subject.storeDailyPixelFiredToday("pixel_d") subject.storeUniquePixelFired("pixel_u") @@ -93,7 +93,7 @@ class PixelFiredRepositoryTest { } @Test - fun whenDailyPixelWasFiredAgainThenDateIsUpdated() = runTest { + fun `storeDailyPixelFiredToday - date is updated`() = runTest { subject.storeDailyPixelFiredToday("pixel_d") assertTrue(subject.hasDailyPixelFiredToday("pixel_d")) timeProvider.time += 1.days.toJavaDuration() diff --git a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/RealSubscriptionsManagerTest.kt b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/RealSubscriptionsManagerTest.kt index 9c96480f8c5c..962940a07c92 100644 --- a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/RealSubscriptionsManagerTest.kt +++ b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/RealSubscriptionsManagerTest.kt @@ -91,7 +91,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenRecoverSubscriptionFromStoreIfUserNotAuthenticatedAndNotPurchaseStoredThenReturnFailure() = runTest { + fun `recoverSubscriptionFromStore - user not authenticated and no purchase stored - return failure`() = runTest { givenUserIsNotAuthenticated() val value = subscriptionsManager.recoverSubscriptionFromStore() @@ -100,7 +100,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenRecoverSubscriptionFromStoreIfUserNotAuthenticatedAndPurchaseStoredThenReturnSubscriptionAndStoreData() = runTest { + fun `recoverSubscriptionFromStore - user not authenticated and purchase stored - return subscription and store data`() = runTest { givenUserIsNotAuthenticated() givenPurchaseStored() givenStoreLoginSucceeds() @@ -116,7 +116,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenRecoverSubscriptionFromStoreIfStoreLoginFailsThenReturnFailure() = runTest { + fun `recoverSubscriptionFromStore - store login fails - failure`() = runTest { givenUserIsNotAuthenticated() givenPurchaseStored() givenStoreLoginSucceeds() @@ -128,7 +128,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenRecoverSubscriptionFromStoreIfUserAuthenticatedWithNotPurchasesThenReturnFailure() = runTest { + fun `recoverSubscriptionFromStore - user authenticated with no purchases - return failure`() = runTest { givenUserIsAuthenticated() givenAccessTokenSucceeds() @@ -138,7 +138,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenRecoverSubscriptionFromStoreIfValidateTokenSucceedsThenReturnExternalId() = runTest { + fun `recoverSubscriptionFromStore - validate token succeeds - return external id`() = runTest { givenPurchaseStored() givenStoreLoginSucceeds() givenSubscriptionSucceedsWithEntitlements() @@ -152,7 +152,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenRecoverSubscriptionFromStoreIfSubscriptionExpiredThenReturnFailure() = runTest { + fun `recoverSubscriptionFromStore - subscription expired - failure`() = runTest { givenPurchaseStored() givenStoreLoginSucceeds() givenSubscriptionExists(EXPIRED) @@ -164,7 +164,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenRecoverSubscriptionFromStoreIfValidateTokenFailsReturnFailure() = runTest { + fun `recoverSubscriptionFromStore - validate token fails - failure`() = runTest { givenUserIsAuthenticated() givenValidateTokenFails("failure") @@ -174,7 +174,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenRecoverSubscriptionFromStoreIfPurchaseHistoryRetrievedThenSignInUserAndSetToken() = runTest { + fun `recoverSubscriptionFromStore - is signed in - signed in with token`() = runTest { givenUserIsNotAuthenticated() givenPurchaseStored() givenStoreLoginSucceeds() @@ -190,7 +190,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenFetchAndStoreAllDataIfUserNotAuthenticatedThenReturnNullSubscription() = runTest { + fun `fetchAndStoreAllData - user not authenticated - return null subscription`() = runTest { givenUserIsNotAuthenticated() val value = subscriptionsManager.fetchAndStoreAllData() @@ -199,7 +199,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenFetchAndStoreAllDataIfTokenIsValidThenReturnSubscription() = runTest { + fun `fetchAndStoreAllData - token valid - return subscription`() = runTest { givenUserIsAuthenticated() givenSubscriptionSucceedsWithEntitlements() @@ -209,7 +209,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenFetchAndStoreAllDataIfTokenIsValidThenReturnEmitEntitlements() = runTest { + fun `fetchAndStoreAllData - entitlements returned`() = runTest { givenUserIsAuthenticated() givenSubscriptionSucceedsWithEntitlements() @@ -221,7 +221,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenFetchAndStoreAllDataIfSubscriptionFailsThenReturnNull() = runTest { + fun `fetchAndStoreAllData - subscription fails - return null`() = runTest { givenUserIsAuthenticated() givenSubscriptionFails() @@ -229,7 +229,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseFlowIfUserNotAuthenticatedAndNotPurchaseStoredThenCreateAccount() = runTest { + fun `purchase - user not authenticated and no purchase stored - create account`() = runTest { givenUserIsNotAuthenticated() subscriptionsManager.purchase(mock(), planId = "") @@ -238,7 +238,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseFlowIfUserNotAuthenticatedAndNotPurchaseStoredAndSignedInEmailThenCreateAccountWithEmailToken() = runTest { + fun `subscriptionsManager - purchase flow - create account with email token`() = runTest { whenever(emailManager.getToken()).thenReturn("emailToken") givenUserIsNotAuthenticated() @@ -248,7 +248,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseFlowIfCreateAccountFailsThenReturnFailure() = runTest { + fun `purchase - create account fails - return failure`() = runTest { givenUserIsNotAuthenticated() givenCreateAccountFails() @@ -261,7 +261,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseFlowIfCreateAccountSucceedsThenBillingFlowUsesCorrectExternalId() = runTest { + fun `purchase - create account succeeds - uses correct external id`() = runTest { givenUserIsNotAuthenticated() givenCreateAccountSucceeds() givenValidateTokenSucceedsNoEntitlements() @@ -273,7 +273,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseFlowIfUserNotAuthenticatedAndPurchaseNotActiveInStoreThenGetIdFromPurchase() = runTest { + fun `purchase - user not authenticated and purchase not active in store - get id from purchase`() = runTest { givenUserIsNotAuthenticated() givenPurchaseStored() givenStoreLoginSucceeds() @@ -286,7 +286,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseFlowIfUserNotAuthenticatedAndPurchaseActiveInStoreThenRecoverSubscription() = runTest { + fun `purchase - user not authenticated and purchase active in store - recover subscription`() = runTest { givenUserIsNotAuthenticated() givenPurchaseStored() givenStoreLoginSucceeds() @@ -303,7 +303,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseFlowIfStoreLoginFailsThenReturnFailure() = runTest { + fun `purchase - store login fails - return failure`() = runTest { givenUserIsNotAuthenticated() givenPurchaseStored() givenStoreLoginSucceeds() @@ -318,7 +318,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseFlowIfUserAuthenticatedThenValidateToken() = runTest { + fun `purchase - user authenticated - validate token`() = runTest { givenUserIsAuthenticated() subscriptionsManager.purchase(mock(), planId = "") @@ -327,7 +327,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseFlowIfValidateTokenSucceedsThenBillingFlowUsesCorrectExternalIdAndEmitStates() = runTest { + fun `purchase - validate token succeeds - uses correct external id and emit states`() = runTest { givenUserIsAuthenticated() givenSubscriptionSucceedsWithoutEntitlements(status = "Expired") @@ -341,7 +341,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseFlowIfCreateAccountFailsReturnFailure() = runTest { + fun `purchase - create account fails - failure`() = runTest { givenUserIsNotAuthenticated() givenCreateAccountFails() @@ -354,7 +354,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseFlowIfNullSubscriptionAndAuthenticatedThenDoNotCreateAccount() = runTest { + fun `subscriptionsManager - purchase flow if null subscription and authenticated - do not create account`() = runTest { givenUserIsAuthenticated() givenValidateTokenFails("failure") @@ -364,7 +364,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseFlowIfAccountCreatedThenSetTokens() = runTest { + fun `purchaseFlow - account created - set tokens`() = runTest { givenUserIsNotAuthenticated() givenCreateAccountSucceeds() givenSubscriptionSucceedsWithoutEntitlements() @@ -376,7 +376,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseFlowIfPurchaseHistoryRetrievedThenSignInUserAndSetToken() = runTest { + fun `purchase - purchase history retrieved - sign in user and set token`() = runTest { givenUserIsNotAuthenticated() givenPurchaseStored() givenStoreLoginSucceeds() @@ -393,14 +393,14 @@ class RealSubscriptionsManagerTest { } @Test(expected = Exception::class) - fun whenExchangeTokenFailsTokenThenReturnThrow() = runTest { + fun `exchangeAuthToken - token fails - returns throw`() = runTest { givenAccessTokenFails() subscriptionsManager.exchangeAuthToken("authToken") } @Test - fun whenExchangeTokenIfAccessTokenThenExchangeTokenAndStore() = runTest { + fun `exchangeAuthToken - exchange token and store - access token stored`() = runTest { givenAccessTokenSucceeds() val result = subscriptionsManager.exchangeAuthToken("authToken") @@ -409,7 +409,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenSubscribedToSubscriptionStatusThenEmit() = runTest { + fun `whenSubscribedToSubscriptionStatusThenEmit - subscription status emitted`() = runTest { val manager = RealSubscriptionsManager( authService, subscriptionsService, @@ -429,7 +429,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenSubscribedToSubscriptionStatusAndSubscriptionExistsThenEmit() = runTest { + fun `whenSubscribedToSubscriptionStatusAndSubscriptionExistsThenEmit - subscription status updated`() = runTest { givenUserIsAuthenticated() givenSubscriptionExists() val manager = RealSubscriptionsManager( @@ -451,7 +451,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseSuccessfulThenPurchaseCheckedAndSuccessEmit() = runTest { + fun `whenPurchaseSuccessfulThenPurchaseCheckedAndSuccessEmit - current purchase state updated - success`() = runTest { givenUserIsAuthenticated() givenConfirmPurchaseSucceeds() @@ -491,7 +491,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseFailedThenPurchaseCheckedAndWaitingEmit() = runTest { + fun `whenPurchaseFailedThenPurchaseCheckedAndWaitingEmit - purchase failed - waiting emit`() = runTest { givenUserIsAuthenticated() givenValidateTokenFails("failure") givenConfirmPurchaseFails() @@ -526,7 +526,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseCanceledThenEmitCanceled() = runTest { + fun `whenPurchaseCanceledThenEmitCanceled - current purchase state updated - canceled`() = runTest { val flowTest: MutableSharedFlow = MutableSharedFlow() whenever(playBillingManager.purchaseState).thenReturn(flowTest) @@ -550,7 +550,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenGetAccessTokenIfUserIsAuthenticatedThenReturnSuccess() = runTest { + fun `getAccessToken - user authenticated - success`() = runTest { givenUserIsAuthenticated() val result = subscriptionsManager.getAccessToken() @@ -560,7 +560,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenGetAccessTokenIfUserIsAuthenticatedThenReturnFailure() = runTest { + fun `getAccessToken - user not authenticated - failure`() = runTest { givenUserIsNotAuthenticated() val result = subscriptionsManager.getAccessToken() @@ -569,7 +569,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenGetAuthTokenIfUserAuthenticatedAndValidTokenThenReturnSuccess() = runTest { + fun `getAuthToken - user authenticated and valid token - success`() = runTest { givenUserIsAuthenticated() givenValidateTokenSucceedsWithEntitlements() @@ -580,7 +580,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenGetAuthTokenIfUserNotAuthenticatedThenReturnFailure() = runTest { + fun `getAuthToken - user not authenticated - failure`() = runTest { givenUserIsNotAuthenticated() val result = subscriptionsManager.getAuthToken() @@ -589,7 +589,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenGetAuthTokenIfUserAuthenticatedWithSubscriptionAndTokenExpiredAndEntitlementsExistsThenReturnSuccess() = runTest { + fun `getAuthToken - user authenticated with subscription and token expired and entitlements exists - return success`() = runTest { authDataStore.externalId = "1234" givenUserIsAuthenticated() givenSubscriptionSucceedsWithEntitlements() @@ -606,7 +606,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenGetAuthTokenIfUserAuthenticatedWithSubscriptionAndTokenExpiredAndEntitlementsExistsAndExternalIdDifferentThenReturnFailure() = runTest { + fun `getAuthToken - user authenticated with subscription and token expired and external id different - return failure`() = runTest { authDataStore.externalId = "test" givenUserIsAuthenticated() givenSubscriptionSucceedsWithEntitlements() @@ -622,7 +622,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenGetAuthTokenIfUserAuthenticatedWithSubscriptionAndTokenExpiredAndEntitlementsDoNotExistThenReturnFailure() = runTest { + fun `getAuthToken - user authenticated with subscription and token expired and entitlements do not exist - return failure`() = runTest { givenUserIsAuthenticated() givenValidateTokenSucceedsNoEntitlements() givenValidateTokenFailsAndThenSucceedsWithNoEntitlements("""{ "error": "expired_token" }""") @@ -637,7 +637,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenGetAuthTokenIfUserAuthenticatedAndTokenExpiredAndNoPurchaseInTheStoreThenReturnFailure() = runTest { + fun `getAuthToken - user authenticated and token expired and no purchase in store - return failure`() = runTest { givenUserIsAuthenticated() givenValidateTokenFailsAndThenSucceeds("""{ "error": "expired_token" }""") @@ -648,7 +648,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenGetAuthTokenIfUserAuthenticatedAndTokenExpiredAndPurchaseNotValidThenReturnFailure() = runTest { + fun `getAuthToken - user authenticated and token expired and purchase not valid - return failure`() = runTest { givenUserIsAuthenticated() givenValidateTokenFailsAndThenSucceeds("""{ "error": "expired_token" }""") givenStoreLoginFails() @@ -661,7 +661,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenGetSubscriptionThenReturnCorrectStatus() = runTest { + fun `getSubscription - when get subscription then return correct status`() = runTest { givenUserIsAuthenticated() givenValidateTokenSucceedsWithEntitlements() @@ -691,7 +691,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenGetPortalAndUserAuthenticatedReturnUrl() = runTest { + fun `getPortal - user authenticated - returns url`() = runTest { givenUserIsAuthenticated() givenUrlPortalSucceeds() @@ -699,14 +699,14 @@ class RealSubscriptionsManagerTest { } @Test - fun whenGetPortalAndUserIsNotAuthenticatedReturnNull() = runTest { + fun `getPortal - user not authenticated - null`() = runTest { givenUserIsNotAuthenticated() assertNull(subscriptionsManager.getPortalUrl()) } @Test - fun whenGetPortalFailsReturnNull() = runTest { + fun `getPortal - fails - returns null`() = runTest { givenUserIsAuthenticated() givenUrlPortalFails() @@ -714,7 +714,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenSignOutThenCallRepositorySignOut() = runTest { + fun `signOut - call repository sign out`() = runTest { val mockRepo: AuthRepository = mock() val manager = RealSubscriptionsManager( authService, @@ -733,7 +733,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenSignOutEmitFalseForIsSignedIn() = runTest { + fun `signOut - is signed in false`() = runTest { givenSubscriptionExists() givenUserIsAuthenticated() @@ -746,7 +746,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenSignOutThenEmitUnknown() = runTest { + fun `signOut - subscription status updated - unknown`() = runTest { givenUserIsAuthenticated() givenSubscriptionExists() @@ -771,7 +771,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseIsSuccessfulThenPixelIsSent() = runTest { + fun `whenPurchaseIsSuccessfulThenPixelIsSent - current purchase state in progress and success - pixel sent`() = runTest { givenUserIsAuthenticated() givenValidateTokenSucceedsWithEntitlements() givenConfirmPurchaseSucceeds() @@ -791,7 +791,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenSubscriptionIsRestoredOnPurchaseAttemptThenPixelIsSent() = runTest { + fun `subscriptionsManager - purchase restored on attempt - pixel sent`() = runTest { givenUserIsNotAuthenticated() givenPurchaseStored() givenStoreLoginSucceeds() @@ -812,7 +812,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseFailsThenPixelIsSent() = runTest { + fun `whenPurchaseFailsThenPixelIsSent - subscriptions manager current purchase state - pixel is sent`() = runTest { givenUserIsAuthenticated() givenValidateTokenFails("failure") givenConfirmPurchaseFails() @@ -831,7 +831,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseFlowIfCreateAccountFailsThenPixelIsSent() = runTest { + fun `purchaseFlow - create account fails - pixel sent`() = runTest { givenUserIsNotAuthenticated() givenCreateAccountFails() @@ -849,7 +849,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenGetSubscriptionOfferThenReturnValue() = runTest { + fun `getSubscriptionOffer - return value - subscription offer details`() = runTest { val productDetails: ProductDetails = mock { productDetails -> whenever(productDetails.productId).thenReturn(SubscriptionsConstants.BASIC_SUBSCRIPTION) @@ -889,12 +889,12 @@ class RealSubscriptionsManagerTest { } @Test - fun whenCanSupportEncryptionThenReturnTrue() = runTest { + fun `canSupportEncryption - state - returns true`() = runTest { assertTrue(subscriptionsManager.canSupportEncryption()) } @Test - fun whenCanSupportEncryptionIfCannotThenReturnFalse() = runTest { + fun `canSupportEncryption - cannot support encryption - returns false`() = runTest { val authDataStore: SubscriptionsDataStore = FakeSubscriptionsDataStore(supportEncryption = false) val authRepository = RealAuthRepository(authDataStore, coroutineRule.testDispatcherProvider) subscriptionsManager = RealSubscriptionsManager( @@ -913,7 +913,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenDeleteAccountIfUserAuthenticatedAndValidTokenThenReturnTrue() = runTest { + fun `deleteAccount - authenticated and valid token - returns true`() = runTest { givenUserIsAuthenticated() givenValidateTokenSucceedsWithEntitlements() givenDeleteAccountSucceeds() @@ -922,7 +922,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenDeleteAccountIfUserNotAuthenticatedThenReturnFalse() = runTest { + fun `deleteAccount - user not authenticated - returns false`() = runTest { givenUserIsNotAuthenticated() givenDeleteAccountFails() @@ -930,7 +930,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenDeleteAccountIfUserAuthenticatedWithSubscriptionAndTokenExpiredAndEntitlementsExistsThenReturnTrue() = runTest { + fun `deleteAccount - authenticated with subscription and token expired and entitlements exists - returns true`() = runTest { authDataStore.externalId = "1234" givenUserIsAuthenticated() givenSubscriptionSucceedsWithEntitlements() @@ -944,7 +944,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenRemoveEntitlementsThenEntitlementsDeleted() = runTest { + fun `removeEntitlements - entitlements deleted`() = runTest { givenSubscriptionExists() assertEquals("""[{"product":"product", "name":"name"}]""", authDataStore.entitlements) diff --git a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/RealSubscriptionsTest.kt b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/RealSubscriptionsTest.kt index cea323288cdf..d7f7a24916f8 100644 --- a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/RealSubscriptionsTest.kt +++ b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/RealSubscriptionsTest.kt @@ -65,20 +65,20 @@ class RealSubscriptionsTest { } @Test - fun whenGetAccessTokenSucceedsThenReturnAccessToken() = runTest { + fun `getAccessToken - succeeds - return access token`() = runTest { whenever(mockSubscriptionsManager.getAccessToken()).thenReturn(AccessToken.Success("accessToken")) val result = subscriptions.getAccessToken() assertEquals("accessToken", result) } @Test - fun whenGetAccessTokenFailsThenReturnNull() = runTest { + fun `getAccessToken - fails - returns null`() = runTest { whenever(mockSubscriptionsManager.getAccessToken()).thenReturn(AccessToken.Failure("error")) assertNull(subscriptions.getAccessToken()) } @Test - fun whenGetEntitlementStatusHasEntitlementAndEnabledAndActiveThenReturnList() = runTest { + fun `getEntitlementStatus - has entitlement and enabled and active - returns list`() = runTest { whenever(mockSubscriptionsManager.subscriptionStatus()).thenReturn(AUTO_RENEWABLE) whenever(mockSubscriptionsManager.entitlements).thenReturn(flowOf(listOf(NetP))) @@ -89,7 +89,7 @@ class RealSubscriptionsTest { } @Test - fun whenGetEntitlementStatusHasEntitlementAndEnabledAndInactiveThenReturnEmptyList() = runTest { + fun `getEntitlementStatus - has entitlement and enabled and inactive - returns empty list`() = runTest { whenever(mockSubscriptionsManager.subscriptionStatus()).thenReturn(INACTIVE) whenever(mockSubscriptionsManager.entitlements).thenReturn(flowOf(listOf(NetP))) @@ -101,7 +101,7 @@ class RealSubscriptionsTest { } @Test - fun whenGetEntitlementStatusHasNoEntitlementAndEnabledAndActiveThenReturnEmptyList() = runTest { + fun `getEntitlementStatus - no entitlement and enabled and active - return empty list`() = runTest { whenever(mockSubscriptionsManager.subscriptionStatus()).thenReturn(AUTO_RENEWABLE) whenever(mockSubscriptionsManager.entitlements).thenReturn(flowOf(emptyList())) @@ -112,7 +112,7 @@ class RealSubscriptionsTest { } @Test - fun whenIsEligibleIfOffersReturnedThenReturnTrueRegardlessOfStatus() = runTest { + fun `isEligible - offers returned - return true regardless of status`() = runTest { whenever(mockSubscriptionsManager.subscriptionStatus()).thenReturn(UNKNOWN) whenever(mockSubscriptionsManager.getSubscriptionOffer()).thenReturn( SubscriptionOffer(monthlyPlanId = "test", yearlyFormattedPrice = "test", yearlyPlanId = "test", monthlyFormattedPrice = "test"), @@ -121,28 +121,28 @@ class RealSubscriptionsTest { } @Test - fun whenIsEligibleIfNotOffersReturnedThenReturnFalseIfNotActiveOrWaiting() = runTest { + fun `isEligible - not active or waiting - return false`() = runTest { whenever(mockSubscriptionsManager.subscriptionStatus()).thenReturn(UNKNOWN) whenever(mockSubscriptionsManager.getSubscriptionOffer()).thenReturn(null) assertFalse(subscriptions.isEligible()) } @Test - fun whenIsEligibleIfNotOffersReturnedThenReturnTrueIfWaiting() = runTest { + fun `isEligible - waiting - returns true`() = runTest { whenever(mockSubscriptionsManager.subscriptionStatus()).thenReturn(WAITING) whenever(mockSubscriptionsManager.getSubscriptionOffer()).thenReturn(null) assertTrue(subscriptions.isEligible()) } @Test - fun whenIsEligibleIfNotOffersReturnedThenReturnTrueIfActive() = runTest { + fun `isEligible - subscription status active and no offers returned - returns true`() = runTest { whenever(mockSubscriptionsManager.subscriptionStatus()).thenReturn(AUTO_RENEWABLE) whenever(mockSubscriptionsManager.getSubscriptionOffer()).thenReturn(null) assertTrue(subscriptions.isEligible()) } @Test - fun whenIsEligibleIfNotEncryptionThenReturnTrueIfActive() = runTest { + fun `isEligible - not encryption - true if active`() = runTest { whenever(mockSubscriptionsManager.canSupportEncryption()).thenReturn(false) whenever(mockSubscriptionsManager.subscriptionStatus()).thenReturn(AUTO_RENEWABLE) whenever(mockSubscriptionsManager.getSubscriptionOffer()).thenReturn( @@ -152,7 +152,7 @@ class RealSubscriptionsTest { } @Test - fun whenIsEligibleIfNotEncryptionAndNotActiveThenReturnFalse() = runTest { + fun `isEligible - not encryption and not active - return false`() = runTest { whenever(mockSubscriptionsManager.canSupportEncryption()).thenReturn(false) whenever(mockSubscriptionsManager.subscriptionStatus()).thenReturn(UNKNOWN) whenever(mockSubscriptionsManager.getSubscriptionOffer()).thenReturn( @@ -162,7 +162,7 @@ class RealSubscriptionsTest { } @Test - fun whenShouldLaunchPrivacyProForUrlThenReturnCorrectValue() = runTest { + fun `shouldLaunchPrivacyProForUrl - correct value returned`() = runTest { whenever(mockSubscriptionsManager.getSubscriptionOffer()).thenReturn( SubscriptionOffer(monthlyPlanId = "test", yearlyFormattedPrice = "test", yearlyPlanId = "test", monthlyFormattedPrice = "test"), ) @@ -179,7 +179,7 @@ class RealSubscriptionsTest { } @Test - fun whenShouldLaunchPrivacyProForUrlThenReturnTrue() = runTest { + fun `shouldLaunchPrivacyProForUrl - subscription status unknown - returns true`() = runTest { whenever(mockSubscriptionsManager.getSubscriptionOffer()).thenReturn( SubscriptionOffer(monthlyPlanId = "test", yearlyFormattedPrice = "test", yearlyPlanId = "test", monthlyFormattedPrice = "test"), ) @@ -189,14 +189,14 @@ class RealSubscriptionsTest { } @Test - fun whenShouldLaunchPrivacyProForUrlAndNotEligibleThenReturnFalse() = runTest { + fun `shouldLaunchPrivacyProForUrl - unknown subscription status - returns false`() = runTest { whenever(mockSubscriptionsManager.subscriptionStatus()).thenReturn(UNKNOWN) assertFalse(subscriptions.shouldLaunchPrivacyProForUrl("https://duckduckgo.com/pro")) } @Test - fun whenLaunchPrivacyProWithOriginThenPassTheOriginToActivity() = runTest { + fun `launchPrivacyPro - origin passed to activity`() = runTest { whenever(globalActivityStarter.startIntent(any(), any())).thenReturn(mock()) val captor = argumentCaptor() @@ -207,7 +207,7 @@ class RealSubscriptionsTest { } @Test - fun whenLaunchPrivacyProWithNoOriginThenDoNotPassTheOriginToActivity() = runTest { + fun `launchPrivacyPro - no origin - do not pass origin to activity`() = runTest { whenever(globalActivityStarter.startIntent(any(), any())).thenReturn(mock()) val captor = argumentCaptor() diff --git a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/billing/RealPlayBillingManagerTest.kt b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/billing/RealPlayBillingManagerTest.kt index b68a997be6af..1eaa96610d48 100644 --- a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/billing/RealPlayBillingManagerTest.kt +++ b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/billing/RealPlayBillingManagerTest.kt @@ -59,7 +59,7 @@ class RealPlayBillingManagerTest { } @Test - fun `when process created then connects to billing service and loads data`() = runTest { + fun `processCreated - connects to billing service and loads data`() = runTest { processLifecycleOwner.currentState = CREATED billingClientAdapter.verifyConnectInvoked() @@ -68,7 +68,7 @@ class RealPlayBillingManagerTest { } @Test - fun `when connection failed then does not attempt loading anything`() = runTest { + fun `when connection failed then does not attempt loading anything - verify connect and subscription calls - times zero`() = runTest { billingClientAdapter.billingInitResult = BillingInitResult.Failure(BILLING_UNAVAILABLE) processLifecycleOwner.currentState = CREATED @@ -79,7 +79,7 @@ class RealPlayBillingManagerTest { } @Test - fun `when connected then returns products`() = runTest { + fun `when connected then returns products - state - product returned`() = runTest { billingClientAdapter.subscriptions = listOf( mock { whenever(it.productId).thenReturn("test-sub") @@ -93,7 +93,7 @@ class RealPlayBillingManagerTest { } @Test - fun `when service not ready before launching billing flow then attempts to connect`() = runTest { + fun `when service not ready before launching billing flow then attempts to connect - in progress - connects`() = runTest { processLifecycleOwner.currentState = RESUMED billingClientAdapter.connected = false billingClientAdapter.launchBillingFlowResult = LaunchBillingFlowResult.Success @@ -115,7 +115,7 @@ class RealPlayBillingManagerTest { } @Test - fun `when can't connect to service then launching billing flow is cancelled`() = runTest { + fun `launchBillingFlow - can't connect to service - cancelled`() = runTest { billingClientAdapter.billingInitResult = BillingInitResult.Failure(BILLING_UNAVAILABLE) processLifecycleOwner.currentState = RESUMED billingClientAdapter.launchBillingFlowResult = LaunchBillingFlowResult.Failure @@ -136,7 +136,7 @@ class RealPlayBillingManagerTest { } @Test - fun `when service disconnected then attempt to connect`() = runTest { + fun `when service disconnected then attempt to connect - verify connect invoked`() = runTest { processLifecycleOwner.currentState = RESUMED billingClientAdapter.methodInvocations.clear() @@ -148,7 +148,7 @@ class RealPlayBillingManagerTest { } @Test - fun `when connect fails with recoverable error then retry with exponential backoff`() = runTest { + fun `when connect fails with recoverable error then retry with exponential backoff - verify connect invoked - does not time out`() = runTest { billingClientAdapter.billingInitResult = BillingInitResult.Failure(NETWORK_ERROR) processLifecycleOwner.currentState = RESUMED @@ -164,7 +164,7 @@ class RealPlayBillingManagerTest { } @Test - fun `when launch billing flow then retrieves ProductDetails for provided plan id`() = runTest { + fun `launchBillingFlow - retrieves product details for provided plan id`() = runTest { processLifecycleOwner.currentState = RESUMED billingClientAdapter.launchBillingFlowResult = LaunchBillingFlowResult.Success diff --git a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/billing/RetryTest.kt b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/billing/RetryTest.kt index cadb303d7738..2367e27ec272 100644 --- a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/billing/RetryTest.kt +++ b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/billing/RetryTest.kt @@ -14,7 +14,7 @@ import org.junit.Test class RetryTest { @Test - fun `when block returns false and config is null then does not retry`() = runTest { + fun `retry - block returns false and config is null - does not retry`() = runTest { var attemptCount = 0 retry(retryPolicy = null) { @@ -26,7 +26,7 @@ class RetryTest { } @Test - fun `when block returns true then does not retry`() = runTest { + fun `when block returns true then does not retry - retry policy satisfied`() = runTest { val retryPolicy = RetryPolicy( retryCount = 10, initialDelay = 1.seconds, @@ -45,7 +45,7 @@ class RetryTest { } @Test - fun `when block returns false then does retry`() = runTest { + fun `when block returns false then does retry - retry policy applied`() = runTest { val retryPolicy = RetryPolicy( retryCount = 10, initialDelay = 1.seconds, @@ -64,7 +64,7 @@ class RetryTest { } @Test - fun `when block returns true on retry then stops retrying`() = runTest { + fun `when block returns true on retry then stops retrying - retry policy stopped`() = runTest { val retryPolicy = RetryPolicy( retryCount = 10, initialDelay = 1.seconds, @@ -83,7 +83,7 @@ class RetryTest { } @Test - fun `when about to retry then delays incrementally`() = runTest { + fun `when about to retry then delays incrementally - state - delays incrementally`() = runTest { val retryPolicy = RetryPolicy( retryCount = 8, initialDelay = 1.seconds, diff --git a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/messaging/ItrMessagingInterfaceTest.kt b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/messaging/ItrMessagingInterfaceTest.kt index 0c756e960586..49964b4e9c54 100644 --- a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/messaging/ItrMessagingInterfaceTest.kt +++ b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/messaging/ItrMessagingInterfaceTest.kt @@ -47,7 +47,7 @@ class ItrMessagingInterfaceTest { } @Test - fun whenProcessUnknownMessageDoNothing() = runTest { + fun `processUnknownMessage - do nothing`() = runTest { givenInterfaceIsRegistered() messagingInterface.process("", "secret") @@ -56,7 +56,7 @@ class ItrMessagingInterfaceTest { } @Test - fun whenProcessUnknownSecretDoNothing() = runTest { + fun `processUnknownSecret - do nothing`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -69,7 +69,7 @@ class ItrMessagingInterfaceTest { } @Test - fun whenProcessNoUrlDoNothing() = runTest { + fun `process - no url - do nothing`() = runTest { messagingInterface.register(webView, callback) val message = """ @@ -82,7 +82,7 @@ class ItrMessagingInterfaceTest { } @Test - fun whenProcessInterfaceNotRegisteredDoNothing() = runTest { + fun `processInterfaceNotRegistered - do nothing`() = runTest { whenever(webView.url).thenReturn("https://duckduckgo.com/test") val message = """ @@ -95,7 +95,7 @@ class ItrMessagingInterfaceTest { } @Test - fun whenProcessIfMethodDoesNotMatchDoNothing() = runTest { + fun `processIfMethodDoesNotMatch - do nothing`() = runTest { givenInterfaceIsRegistered() givenAccessTokenIsSuccess() @@ -109,7 +109,7 @@ class ItrMessagingInterfaceTest { } @Test - fun whenProcessAndGetAccessTokenIfNoIdDoNothing() = runTest { + fun `processAndGetAccessTokenIfNoId - do nothing`() = runTest { givenInterfaceIsRegistered() givenAccessTokenIsSuccess() @@ -123,7 +123,7 @@ class ItrMessagingInterfaceTest { } @Test - fun whenProcessAndGetAccessTokenMessageThenReturnResponse() = runTest { + fun `processAndGetAccessTokenMessage - return response`() = runTest { givenInterfaceIsRegistered() givenAccessTokenIsSuccess() @@ -150,7 +150,7 @@ class ItrMessagingInterfaceTest { } @Test - fun whenProcessAndGetAccessTokenMessageErrorThenReturnResponse() = runTest { + fun `processAndGetAccessTokenMessageError - return response`() = runTest { givenInterfaceIsRegistered() givenAccessTokenIsFailure() @@ -177,7 +177,7 @@ class ItrMessagingInterfaceTest { } @Test - fun whenProcessAndGetAccessTokenMessageIfUrlNotInAllowListedDomainsThenDoNothing() = runTest { + fun `processAndGetAccessTokenMessage - url not in allow listed domains - do nothing`() = runTest { messagingInterface.register(webView, callback) whenever(webView.url).thenReturn("https://duckduckgo.example.com") givenAccessTokenIsSuccess() diff --git a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/messaging/SubscriptionMessagingInterfaceTest.kt b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/messaging/SubscriptionMessagingInterfaceTest.kt index 286aae56cd09..ffd2a574d620 100644 --- a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/messaging/SubscriptionMessagingInterfaceTest.kt +++ b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/messaging/SubscriptionMessagingInterfaceTest.kt @@ -58,7 +58,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessUnknownMessageDoNothing() = runTest { + fun `processUnknownMessage - do nothing`() = runTest { givenInterfaceIsRegistered() messagingInterface.process("", "secret") @@ -68,7 +68,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessUnknownSecretDoNothing() = runTest { + fun `processUnknownSecret - do nothing`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -82,7 +82,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessNoUrlDoNothing() = runTest { + fun `processNoUrl - do nothing`() = runTest { messagingInterface.register(webView, callback) val message = """ @@ -96,7 +96,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessInterfaceNotRegisteredDoNothing() = runTest { + fun `processInterfaceNotRegistered - do nothing`() = runTest { whenever(webView.url).thenReturn("https://duckduckgo.com/test") val message = """ @@ -110,7 +110,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessIfMethodDoesNotMatchDoNothing() = runTest { + fun `processIfMethodDoesNotMatch - do nothing`() = runTest { givenInterfaceIsRegistered() givenAuthTokenIsSuccess() @@ -124,7 +124,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndGetSubscriptionsMessageIfActiveThenReturnResponse() = runTest { + fun `processAndGetSubscriptions - active - return response`() = runTest { givenInterfaceIsRegistered() givenAuthTokenIsSuccess() givenSubscriptionIsActive() @@ -152,7 +152,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndGetSubscriptionsMessageIfNotActiveThenReturnError() = runTest { + fun `processAndGetSubscriptions - not active - return error`() = runTest { givenInterfaceIsRegistered() givenAuthTokenIsSuccess() @@ -179,7 +179,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndGetSubscriptionsMessageErrorThenReturnResponse() = runTest { + fun `processAndGetSubscriptionsMessageError - return response`() = runTest { givenInterfaceIsRegistered() givenAuthTokenIsFailure() @@ -206,7 +206,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndGetSubscriptionsIfFeatureNameDoesNotMatchDoNothing() = runTest { + fun `processAndGetSubscriptions - feature name does not match - do nothing`() = runTest { givenInterfaceIsRegistered() givenAuthTokenIsSuccess() @@ -220,7 +220,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndGetSubscriptionIfNoIdDoNothing() = runTest { + fun `processAndGetSubscription - no id - do nothing`() = runTest { givenInterfaceIsRegistered() givenAuthTokenIsSuccess() @@ -234,7 +234,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndBackToSettingsIfFeatureNameDoesNotMatchDoNothing() = runTest { + fun `processAndBackToSettings - feature name does not match - do nothing`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -247,7 +247,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndBackToSettingsThenCallbackExecuted() = runTest { + fun `processAndBackToSettings - callback executed`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -260,7 +260,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndSetSubscriptionMessageIfFeatureNameDoesNotMatchDoNothing() = runTest { + fun `processAndSetSubscriptionMessageIfFeatureNameDoesNotMatch - do nothing`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -274,7 +274,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndSetSubscriptionMessageThenAuthenticate() = runTest { + fun `processAndSetSubscriptionMessage - authenticate`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -290,7 +290,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndSetSubscriptionMessageAndNoTokenThenDoNothing() = runTest { + fun `processAndSetSubscriptionMessage - no token - do nothing`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -304,7 +304,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndGetSubscriptionOptionsMessageIfFeatureNameDoesNotMatchDoNothing() = runTest { + fun `processAndGetSubscriptionOptionsMessageIfFeatureNameDoesNotMatch - do nothing`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -317,7 +317,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndGetSubscriptionOptionsMessageThenCallbackCalled() = runTest { + fun `processAndGetSubscriptionOptionsMessage - callback called`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -330,7 +330,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndGetSubscriptionOptionsMessageAndNoIdThenDoNothing() = runTest { + fun `processAndGetSubscriptionOptionsMessage - no id - do nothing`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -344,7 +344,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndSubscriptionSelectedMessageIfFeatureNameDoesNotMatchDoNothing() = runTest { + fun `processAndSubscriptionSelectedMessage - feature name does not match - do nothing`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -357,7 +357,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndSubscriptionSelectedMessageThenCallbackCalled() = runTest { + fun `processAndSubscriptionSelectedMessage - callback called`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -370,7 +370,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndActivateSubscriptionIfFeatureNameDoesNotMatchDoNothing() = runTest { + fun `processAndActivateSubscription - feature name does not match - do nothing`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -383,7 +383,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndActivateSubscriptionThenCallbackExecuted() = runTest { + fun `processAndActivateSubscription - callback executed`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -396,7 +396,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndFeatureSelectedIfFeatureNameDoesNotMatchDoNothing() = runTest { + fun `processAndFeatureSelected - feature name does not match - do nothing`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -409,7 +409,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndFeatureSelectedThenCallbackExecuted() = runTest { + fun `processAndFeatureSelected - callback executed`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -422,7 +422,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndFeatureSelectedMessageIfUrlNotInAllowListedDomainsThenDoNothing() = runTest { + fun `processAndFeatureSelectedMessage - url not in allow listed domains - do nothing`() = runTest { messagingInterface.register(webView, callback) whenever(webView.url).thenReturn("https://duckduckgo.example.com") @@ -449,7 +449,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndBackToSettingsActiveSuccessThenCallbackExecuted() = runTest { + fun `processAndBackToSettingsActiveSuccess - callback executed`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -462,7 +462,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndMonthlyPriceClickedThenPixelSent() = runTest { + fun `processAndMonthlyPriceClicked - pixel sent`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -476,7 +476,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndYearlyPriceClickedThenPixelSent() = runTest { + fun `processAndYearlyPriceClicked - pixel sent`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -490,7 +490,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndAddEmailSuccessThenPixelSent() = runTest { + fun `processAndAddEmail - success - pixel sent`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -504,7 +504,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndFaqClickedThenCallbackExecuted() = runTest { + fun `processAndFaqClicked - callback executed`() = runTest { val jsMessageCallback: JsMessageCallback = mock() messagingInterface.register(webView, jsMessageCallback) whenever(webView.url).thenReturn("https://duckduckgo.com/test") @@ -519,7 +519,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndAddEmailClickedThenCallbackExecuted() = runTest { + fun `processAndAddEmailClicked - callback executed`() = runTest { val jsMessageCallback: JsMessageCallback = mock() messagingInterface.register(webView, jsMessageCallback) whenever(webView.url).thenReturn("https://duckduckgo.com/test") diff --git a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/pixels/SubscriptionRefreshRetentionAtbPluginTest.kt b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/pixels/SubscriptionRefreshRetentionAtbPluginTest.kt index 9a0634c14949..9976f275c63e 100644 --- a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/pixels/SubscriptionRefreshRetentionAtbPluginTest.kt +++ b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/pixels/SubscriptionRefreshRetentionAtbPluginTest.kt @@ -27,7 +27,7 @@ class SubscriptionRefreshRetentionAtbPluginTest { ) @Test - fun `when subscription is active then pixel is sent`() = runTest { + fun `onAppRetentionAtbRefreshed - subscription active - pixel sent`() = runTest { whenever(subscriptionsManager.subscriptionStatus()).thenReturn(AUTO_RENEWABLE) subject.onAppRetentionAtbRefreshed() @@ -36,7 +36,7 @@ class SubscriptionRefreshRetentionAtbPluginTest { } @Test - fun `when subscription is not active then pixel is not sent`() = runTest { + fun `onAppRetentionAtbRefreshed - subscription not active - pixel not sent`() = runTest { whenever(subscriptionsManager.subscriptionStatus()).thenReturn(EXPIRED) subject.onAppRetentionAtbRefreshed() diff --git a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/repository/RealAuthRepositoryTest.kt b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/repository/RealAuthRepositoryTest.kt index 5cdea7ca20ca..78bf470e7bc7 100644 --- a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/repository/RealAuthRepositoryTest.kt +++ b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/repository/RealAuthRepositoryTest.kt @@ -21,31 +21,31 @@ class RealAuthRepositoryTest { private val authRepository: AuthRepository = RealAuthRepository(authStore, coroutineRule.testDispatcherProvider) @Test - fun whenIsAuthenticatedAndNoAccessTokenThenReturnFalse() = runTest { + fun `isUserAuthenticated - is authenticated and no access token - returns false`() = runTest { authStore.authToken = "authToken" assertFalse(authRepository.isUserAuthenticated()) } @Test - fun whenIsAuthenticatedAndNoAuthTokenThenReturnFalse() = runTest { + fun `isUserAuthenticated - no auth token - false`() = runTest { authStore.accessToken = "accessToken" assertFalse(authRepository.isUserAuthenticated()) } @Test - fun whenIsAuthenticatedAndNoAuthTokenAndAccessTokenThenReturnFalse() = runTest { + fun `isUserAuthenticated - no auth token and access token - returns false`() = runTest { assertFalse(authRepository.isUserAuthenticated()) } @Test - fun whenIsAuthenticatedThenReturnTrue() = runTest { + fun `isUserAuthenticated - authenticated - true`() = runTest { authStore.authToken = "authToken" authStore.accessToken = "accessToken" assertTrue(authRepository.isUserAuthenticated()) } @Test - fun whenClearAccountThenClearData() = runTest { + fun `clearAccount - clear data`() = runTest { authStore.email = "email@duck.com" authStore.externalId = "externalId" authStore.authToken = "authToken" @@ -60,7 +60,7 @@ class RealAuthRepositoryTest { } @Test - fun whenClearSubscriptionThenClearData() = runTest { + fun `clearSubscription - clear data`() = runTest { authStore.status = "expired" authStore.startedAt = 1000L authStore.expiresOrRenewsAt = 1000L @@ -79,7 +79,7 @@ class RealAuthRepositoryTest { } @Test - fun whenSaveAccountDataThenSetData() = runTest { + fun `saveAccountData - set data - set account data`() = runTest { assertNull(authStore.authToken) assertNull(authStore.externalId) @@ -90,7 +90,7 @@ class RealAuthRepositoryTest { } @Test - fun whenTokensThenReturnTokens() = runTest { + fun `getTokens - tokens returned`() = runTest { assertNull(authStore.authToken) assertNull(authStore.accessToken) @@ -102,13 +102,13 @@ class RealAuthRepositoryTest { } @Test - fun whenPurchaseToWaitingStatusThenStoreWaiting() = runTest { + fun `purchaseToWaitingStatus - store waiting - waiting status`() = runTest { authRepository.purchaseToWaitingStatus() assertEquals(WAITING.statusName, authStore.status) } @Test - fun whenGetStatusReturnCorrectStatus() = runTest { + fun `getStatus - various statuses returned correctly`() = runTest { authStore.status = AUTO_RENEWABLE.statusName assertEquals(AUTO_RENEWABLE, authRepository.getStatus()) authStore.status = NOT_AUTO_RENEWABLE.statusName @@ -126,12 +126,12 @@ class RealAuthRepositoryTest { } @Test - fun whenCanSupportEncryptionThenReturnValue() = runTest { + fun `canSupportEncryption - return value`() = runTest { assertTrue(authRepository.canSupportEncryption()) } @Test - fun whenCanSupportEncryptionItCannotThenReturnFalse() = runTest { + fun `canSupportEncryption - cannot support encryption - return false`() = runTest { val repository: AuthRepository = RealAuthRepository( FakeSubscriptionsDataStore(supportEncryption = false), coroutineRule.testDispatcherProvider, diff --git a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/rmf/RMFPProEligibleMatchingAttributeTest.kt b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/rmf/RMFPProEligibleMatchingAttributeTest.kt index 162188535e97..edb9d97db1d0 100644 --- a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/rmf/RMFPProEligibleMatchingAttributeTest.kt +++ b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/rmf/RMFPProEligibleMatchingAttributeTest.kt @@ -17,7 +17,7 @@ class RMFPProEligibleMatchingAttributeTest { private val attribute = RMFPProEligibleMatchingAttribute(subscriptions) @Test - fun evaluateWithWrongAttributeThenNull() = runTest { + fun `evaluate - wrong attribute - null`() = runTest { whenever(subscriptions.isEligible()).thenReturn(false) assertNull(attribute.evaluate(FakeStringMatchingAttribute { "" })) @@ -29,7 +29,7 @@ class RMFPProEligibleMatchingAttributeTest { } @Test - fun evaluateWithProEligibleMatchingAttributeThenValue() = runTest { + fun `evaluate - ppro eligible matching attribute then value`() = runTest { whenever(subscriptions.isEligible()).thenReturn(false) assertTrue(attribute.evaluate(attribute.map("pproEligible", JsonMatchingAttribute(value = false))!!)!!) @@ -44,7 +44,7 @@ class RMFPProEligibleMatchingAttributeTest { } @Test - fun mapNoProEligibleMatchingAttributeKeyThenReturnNull() = runTest { + fun `map - no pro eligible matching attribute key - return null`() = runTest { assertNull(attribute.map("wrong", JsonMatchingAttribute(value = null))) assertNull(attribute.map("wrong", JsonMatchingAttribute(value = true))) assertNull(attribute.map("wrong", JsonMatchingAttribute(value = false))) diff --git a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/rmf/RMFPProSubscriberMatchingAttributeTest.kt b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/rmf/RMFPProSubscriberMatchingAttributeTest.kt index fad49904f5ae..a53e4057e913 100644 --- a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/rmf/RMFPProSubscriberMatchingAttributeTest.kt +++ b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/rmf/RMFPProSubscriberMatchingAttributeTest.kt @@ -15,7 +15,7 @@ class RMFPProSubscriberMatchingAttributeTest { private val attribute = RMFPProSubscriberMatchingAttribute(subscriptions) @Test - fun evaluateWithWrongAttributeThenNull() = runTest { + fun `evaluate - wrong attribute - null`() = runTest { whenever(subscriptions.getAccessToken()).thenReturn(null) Assert.assertNull(attribute.evaluate(FakeStringMatchingAttribute { "" })) @@ -27,7 +27,7 @@ class RMFPProSubscriberMatchingAttributeTest { } @Test - fun evaluateWithProEligibleMatchingAttributeThenValue() = runTest { + fun `evaluateWithProEligibleMatchingAttributeThenValue - attribute evaluated`() = runTest { whenever(subscriptions.getAccessToken()).thenReturn(null) Assert.assertTrue(attribute.evaluate(attribute.map("pproSubscriber", JsonMatchingAttribute(value = false))!!)!!) @@ -42,7 +42,7 @@ class RMFPProSubscriberMatchingAttributeTest { } @Test - fun mapNoProEligibleMatchingAttributeKeyThenReturnNull() = runTest { + fun `mapNoProEligibleMatchingAttributeKey - return null`() = runTest { Assert.assertNull(attribute.map("wrong", JsonMatchingAttribute(value = null))) Assert.assertNull(attribute.map("wrong", JsonMatchingAttribute(value = true))) Assert.assertNull(attribute.map("wrong", JsonMatchingAttribute(value = false))) diff --git a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/settings/views/ItrSettingViewModelTest.kt b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/settings/views/ItrSettingViewModelTest.kt index e738cb4971f6..c8b4e768cd86 100644 --- a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/settings/views/ItrSettingViewModelTest.kt +++ b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/settings/views/ItrSettingViewModelTest.kt @@ -32,7 +32,7 @@ class ItrSettingViewModelTest { } @Test - fun whenOnItrThenCommandSent() = runTest { + fun `onItr - command sent`() = runTest { viewModel.commands().test { viewModel.onItr() assertTrue(awaitItem() is OpenItr) @@ -41,13 +41,13 @@ class ItrSettingViewModelTest { } @Test - fun whenOnItrThenPixelSent() = runTest { + fun `onItr - pixel sent`() = runTest { viewModel.onItr() verify(pixelSender).reportAppSettingsIdtrClick() } @Test - fun whenOnResumeIfSubscriptionEmitViewState() = runTest { + fun `onResume - subscription emit view state`() = runTest { whenever(subscriptions.getEntitlementStatus()).thenReturn( flowOf( listOf(ITR), @@ -62,7 +62,7 @@ class ItrSettingViewModelTest { } @Test - fun whenOnResumeIfNotSubscriptionEmitViewState() = runTest { + fun `onResume - no subscription - view state updated`() = runTest { whenever(subscriptions.getEntitlementStatus()).thenReturn(flowOf(emptyList())) viewModel.onResume(mock()) diff --git a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/settings/views/PirSettingViewModelTest.kt b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/settings/views/PirSettingViewModelTest.kt index ed5b5010d19e..da2220a61466 100644 --- a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/settings/views/PirSettingViewModelTest.kt +++ b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/settings/views/PirSettingViewModelTest.kt @@ -32,7 +32,7 @@ class PirSettingViewModelTest { } @Test - fun whenOnPirThenCommandSent() = runTest { + fun `onPir - command sent`() = runTest { viewModel.commands().test { viewModel.onPir() assertTrue(awaitItem() is OpenPir) @@ -41,13 +41,13 @@ class PirSettingViewModelTest { } @Test - fun whenOnPirThenPixelSent() = runTest { + fun `onPir - pixel sent`() = runTest { viewModel.onPir() verify(pixelSender).reportAppSettingsPirClick() } @Test - fun whenOnResumeIfEntitlementPresentEmitViewState() = runTest { + fun `onResume - entitlement present - emit view state`() = runTest { whenever(subscriptions.getEntitlementStatus()).thenReturn(flowOf(listOf(PIR))) viewModel.onCreate(mock()) @@ -59,7 +59,7 @@ class PirSettingViewModelTest { } @Test - fun whenOnResumeIfEntitlementNotPresentEmitViewState() = runTest { + fun `onResume - entitlement not present - emit view state`() = runTest { whenever(subscriptions.getEntitlementStatus()).thenReturn(flowOf(emptyList())) viewModel.onResume(mock()) diff --git a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/settings/views/ProSettingViewModelTest.kt b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/settings/views/ProSettingViewModelTest.kt index fd1a9f387a39..b8320c7636ec 100644 --- a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/settings/views/ProSettingViewModelTest.kt +++ b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/settings/views/ProSettingViewModelTest.kt @@ -33,7 +33,7 @@ class ProSettingViewModelTest { } @Test - fun whenOnSettingsThenCommandSent() = runTest { + fun `onSettings - command sent`() = runTest { viewModel.commands().test { viewModel.onSettings() assertTrue(awaitItem() is OpenSettings) @@ -42,7 +42,7 @@ class ProSettingViewModelTest { } @Test - fun whenOnBuyThenCommandSent() = runTest { + fun `onBuy - command sent`() = runTest { viewModel.commands().test { viewModel.onBuy() assertTrue(awaitItem() is OpenBuyScreen) @@ -51,7 +51,7 @@ class ProSettingViewModelTest { } @Test - fun whenOnRestoreThenCommandSent() = runTest { + fun `onRestore - command sent`() = runTest { viewModel.commands().test { viewModel.onRestore() assertTrue(awaitItem() is OpenRestoreScreen) @@ -60,7 +60,7 @@ class ProSettingViewModelTest { } @Test - fun whenOnResumeEmitViewState() = runTest { + fun `onResume - view state emitted - subscription expired`() = runTest { whenever(subscriptionsManager.subscriptionStatus).thenReturn(flowOf(SubscriptionStatus.EXPIRED)) viewModel.onCreate(mock()) @@ -71,7 +71,7 @@ class ProSettingViewModelTest { } @Test - fun whenOnRestoreThenPixelSent() = runTest { + fun `onRestore - pixel sent`() = runTest { viewModel.commands().test { viewModel.onRestore() verify(pixelSender).reportAppSettingsRestorePurchaseClick() diff --git a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/ui/AddDeviceViewModelTest.kt b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/ui/AddDeviceViewModelTest.kt index b458be296406..7503455cfb96 100644 --- a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/ui/AddDeviceViewModelTest.kt +++ b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/ui/AddDeviceViewModelTest.kt @@ -35,7 +35,7 @@ class AddDeviceViewModelTest { } @Test - fun whenUseEmailIfNoDataThenEmitError() = runTest { + fun `useEmail - no data - emit error`() = runTest { viewModel.commands().test { viewModel.useEmail() assertTrue(awaitItem() is Error) @@ -43,7 +43,7 @@ class AddDeviceViewModelTest { } @Test - fun whenUseEmailIfFailureThenEmitError() = runTest { + fun `useEmail - error emitted`() = runTest { whenever(subscriptionsManager.getSubscription()).thenReturn(null) viewModel.commands().test { viewModel.useEmail() @@ -52,7 +52,7 @@ class AddDeviceViewModelTest { } @Test - fun whenUseEmailIEmailBlankThenEmitAddEmail() = runTest { + fun `useEmail - email blank - emit add email`() = runTest { whenever(subscriptionsManager.getAccount()).thenReturn( Account(email = "", externalId = "externalId"), ) @@ -63,7 +63,7 @@ class AddDeviceViewModelTest { } @Test - fun whenUseEmailIEmailNullThenEmitAddEmail() = runTest { + fun `useEmail - account email null - emit add email`() = runTest { whenever(subscriptionsManager.getAccount()).thenReturn( Account(email = null, externalId = "externalId"), ) @@ -74,7 +74,7 @@ class AddDeviceViewModelTest { } @Test - fun whenUseEmailIfEmailThenEmitManage() = runTest { + fun `useEmail - account set - emit manage`() = runTest { whenever(subscriptionsManager.getAccount()).thenReturn( Account(email = "email@email.com", externalId = "externalId"), ) @@ -85,7 +85,7 @@ class AddDeviceViewModelTest { } @Test - fun whenOnCreateIfEmailExistsThenEmitIt() = runTest { + fun `onCreate - email exists - emits it`() = runTest { whenever(subscriptionsManager.getAccount()).thenReturn( Account(email = "email@email.com", externalId = "externalId"), ) @@ -101,7 +101,7 @@ class AddDeviceViewModelTest { } @Test - fun whenOnCreateIfEmailBlankThenEmitIt() = runTest { + fun `onCreate - email blank - emit it`() = runTest { val flowTest: MutableSharedFlow = MutableSharedFlow() whenever(subscriptionsManager.subscriptionStatus).thenReturn(flowTest) @@ -114,7 +114,7 @@ class AddDeviceViewModelTest { } @Test - fun whenEnterEmailClickedThenPixelIsSent() = runTest { + fun `useEmail - pixel sent`() = runTest { viewModel.useEmail() verify(pixelSender).reportAddDeviceEnterEmailClick() } diff --git a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/ui/RestoreSubscriptionViewModelTest.kt b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/ui/RestoreSubscriptionViewModelTest.kt index cf9b392fc38b..3f19c915492a 100644 --- a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/ui/RestoreSubscriptionViewModelTest.kt +++ b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/ui/RestoreSubscriptionViewModelTest.kt @@ -45,7 +45,7 @@ class RestoreSubscriptionViewModelTest { } @Test - fun whenRestoreFromEmailThenSendCommand() = runTest { + fun `restoreFromEmail - send command - restore from email`() = runTest { viewModel.commands().test { viewModel.restoreFromEmail() assertTrue(awaitItem() is RestoreFromEmail) @@ -53,7 +53,7 @@ class RestoreSubscriptionViewModelTest { } @Test - fun whenRestoreFromStoreIfFailureThenReturnError() = runTest { + fun `restoreFromStore - restore from store if failure - return error`() = runTest { whenever(subscriptionsManager.recoverSubscriptionFromStore()).thenReturn( RecoverSubscriptionResult.Failure("error"), ) @@ -66,7 +66,7 @@ class RestoreSubscriptionViewModelTest { } @Test - fun whenRestoreFromStoreIfNoSubscriptionFoundThenReturnNotFound() = runTest { + fun `restoreFromStore - no subscription found - not found`() = runTest { whenever(subscriptionsManager.recoverSubscriptionFromStore()).thenReturn( RecoverSubscriptionResult.Failure(SUBSCRIPTION_NOT_FOUND_ERROR), ) @@ -79,7 +79,7 @@ class RestoreSubscriptionViewModelTest { } @Test - fun whenRestoreFromStoreIfNotActiveThenReturnNotFound() = runTest { + fun `restoreFromStore - not active - subscription not found`() = runTest { whenever(subscriptionsManager.recoverSubscriptionFromStore()).thenReturn( RecoverSubscriptionResult.Success(subscriptionNotActive()), ) @@ -92,7 +92,7 @@ class RestoreSubscriptionViewModelTest { } @Test - fun whenRestoreFromStoreIfActiveThenReturnSuccess() = runTest { + fun `restoreFromStore - if active - return success`() = runTest { whenever(subscriptionsManager.recoverSubscriptionFromStore()).thenReturn( RecoverSubscriptionResult.Success(subscriptionActive()), ) @@ -105,19 +105,19 @@ class RestoreSubscriptionViewModelTest { } @Test - fun whenRestoreFromStoreClickThenPixelIsSent() = runTest { + fun `restoreFromStore - pixel sent`() = runTest { viewModel.restoreFromStore() verify(pixelSender).reportActivateSubscriptionRestorePurchaseClick() } @Test - fun whenRestoreFromEmailClickThenPixelIsSent() = runTest { + fun `restoreFromEmail - pixel sent`() = runTest { viewModel.restoreFromEmail() verify(pixelSender).reportActivateSubscriptionEnterEmailClick() } @Test - fun whenRestoreFromStoreSuccessThenPixelIsSent() = runTest { + fun `restoreFromStore - success - pixel sent`() = runTest { whenever(subscriptionsManager.recoverSubscriptionFromStore()).thenReturn( RecoverSubscriptionResult.Success(subscriptionActive()), ) @@ -127,7 +127,7 @@ class RestoreSubscriptionViewModelTest { } @Test - fun whenRestoreFromStoreFailsBecauseThereAreNoEntitlementsThenPixelIsSent() = runTest { + fun `restoreFromStore - restore from store fails because there are no entitlements - pixel is sent`() = runTest { whenever(subscriptionsManager.recoverSubscriptionFromStore()).thenReturn( RecoverSubscriptionResult.Success(subscriptionNotActive()), ) @@ -137,7 +137,7 @@ class RestoreSubscriptionViewModelTest { } @Test - fun whenRestoreFromStoreFailsBecauseThereIsNoSubscriptionThenPixelIsSent() = runTest { + fun `restoreFromStore - restore from store fails because there is no subscription - pixel sent`() = runTest { whenever(subscriptionsManager.recoverSubscriptionFromStore()).thenReturn( RecoverSubscriptionResult.Failure(SUBSCRIPTION_NOT_FOUND_ERROR), ) @@ -147,7 +147,7 @@ class RestoreSubscriptionViewModelTest { } @Test - fun whenRestoreFromStoreFailsForOtherReasonThenPixelIsSent() = runTest { + fun `restoreFromStore - fails for other reason - pixel sent`() = runTest { whenever(subscriptionsManager.recoverSubscriptionFromStore()).thenReturn( RecoverSubscriptionResult.Failure("bad stuff happened"), ) diff --git a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/ui/SubscriptionSettingsViewModelTest.kt b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/ui/SubscriptionSettingsViewModelTest.kt index b148ee804bdd..3879ca248879 100644 --- a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/ui/SubscriptionSettingsViewModelTest.kt +++ b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/ui/SubscriptionSettingsViewModelTest.kt @@ -37,7 +37,7 @@ class SubscriptionSettingsViewModelTest { } @Test - fun whenRemoveFromDeviceThenFinishSignOut() = runTest { + fun `removeFromDevice - finish sign out`() = runTest { viewModel.commands().test { viewModel.removeFromDevice() assertTrue(awaitItem() is FinishSignOut) @@ -45,7 +45,7 @@ class SubscriptionSettingsViewModelTest { } @Test - fun whenSubscriptionThenFormatDateCorrectly() = runTest { + fun `whenSubscription - view state date correctly - December 04, 20XX`() = runTest { whenever(subscriptionsManager.getSubscription()).thenReturn( Subscription( productId = SubscriptionsConstants.MONTHLY_PLAN, @@ -67,7 +67,7 @@ class SubscriptionSettingsViewModelTest { } @Test - fun whenSubscriptionMonthlyThenReturnMonthly() = runTest { + fun `onCreate - subscription monthly - monthly`() = runTest { whenever(subscriptionsManager.getSubscription()).thenReturn( Subscription( productId = SubscriptionsConstants.MONTHLY_PLAN, @@ -89,7 +89,7 @@ class SubscriptionSettingsViewModelTest { } @Test - fun whenSubscriptionYearlyThenReturnYearly() = runTest { + fun `onCreate - view state yearly`() = runTest { whenever(subscriptionsManager.getSubscription()).thenReturn( Subscription( productId = SubscriptionsConstants.YEARLY_PLAN, @@ -112,7 +112,7 @@ class SubscriptionSettingsViewModelTest { } @Test - fun whenGoToStripeIfNoUrlThenDoNothing() = runTest { + fun `goToStripe - no url - do nothing`() = runTest { whenever(subscriptionsManager.getPortalUrl()).thenReturn(null) viewModel.commands().test { @@ -123,7 +123,7 @@ class SubscriptionSettingsViewModelTest { } @Test - fun whenGoToStripeIfNoUrlThenDoSendCommandWithUrl() = runTest { + fun `goToStripe - no url - do send command with url`() = runTest { whenever(subscriptionsManager.getPortalUrl()).thenReturn("example.com") viewModel.commands().test { @@ -135,7 +135,7 @@ class SubscriptionSettingsViewModelTest { } @Test - fun whenRemoveFromDeviceThenPixelIsSent() = runTest { + fun `removeFromDevice - pixel sent`() = runTest { viewModel.removeFromDevice() verify(pixelSender).reportSubscriptionSettingsRemoveFromDeviceClick() } diff --git a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/ui/SubscriptionWebViewViewModelTest.kt b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/ui/SubscriptionWebViewViewModelTest.kt index 1547851ab746..70366d65162f 100644 --- a/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/ui/SubscriptionWebViewViewModelTest.kt +++ b/subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/ui/SubscriptionWebViewViewModelTest.kt @@ -69,7 +69,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenPurchaseStateChangesThenReturnCorrectState() = runTest { + fun `whenCurrentPurchaseStateChangesThenReturnCorrectState - view state updated`() = runTest { val flowTest: MutableSharedFlow = MutableSharedFlow() whenever(subscriptionsManager.currentPurchaseState).thenReturn(flowTest) viewModel.start() @@ -104,7 +104,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenPurchaseStateFailedThenSendCanceledMessage() = runTest { + fun `start - purchase state failed - send canceled message`() = runTest { val flowTest: MutableSharedFlow = MutableSharedFlow() whenever(subscriptionsManager.currentPurchaseState).thenReturn(flowTest) viewModel.start() @@ -121,7 +121,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenPurchaseStateCanceledThenSendCanceledMessage() = runTest { + fun `start - purchase state canceled - send canceled message`() = runTest { val flowTest: MutableSharedFlow = MutableSharedFlow() whenever(subscriptionsManager.currentPurchaseState).thenReturn(flowTest) viewModel.start() @@ -138,7 +138,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenSubscriptionSelectedAndIdInObjectEmptyThenReturnFailure() = runTest { + fun `processJsCallbackMessage - subscription selected and id in object empty - return failure`() = runTest { val json = """ {"id":""} """.trimIndent() @@ -151,7 +151,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenSubscriptionSelectedAndIdIsInObjectNullThenReturnFailure() = runTest { + fun `processJsCallbackMessage - subscription selected and id is in object null - failure`() = runTest { viewModel.currentPurchaseViewState.test { assertTrue(awaitItem().purchaseState is PurchaseStateView.Inactive) viewModel.processJsCallbackMessage("test", "subscriptionSelected", "id", JSONObject("{}")) @@ -160,7 +160,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenSubscriptionSelectedThenSendCommandWithCorrectId() = runTest { + fun `processJsCallbackMessage - subscription selected - send command with correct id`() = runTest { val json = """ {"id":"myId"} """.trimIndent() @@ -173,7 +173,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenBackToSettingsThenCommandSent() = runTest { + fun `processJsCallbackMessage - back to settings - command sent`() = runTest { viewModel.commands().test { viewModel.processJsCallbackMessage("test", "backToSettings", "id", JSONObject("{}")) assertTrue(awaitItem() is Command.BackToSettings) @@ -181,7 +181,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenBackToSettingsActivateSuccessThenCommandSent() = runTest { + fun `processJsCallbackMessage - back to settings activate success - command sent`() = runTest { viewModel.commands().test { viewModel.processJsCallbackMessage("test", "backToSettingsActivateSuccess", "id", JSONObject("{}")) assertTrue(awaitItem() is Command.BackToSettingsActivateSuccess) @@ -189,7 +189,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenGetSubscriptionOptionsThenSendCommand() = runTest { + fun `whenGetSubscriptionOptionsThenSendCommand - send command`() = runTest { privacyProFeature.allowPurchase().setEnabled(Toggle.State(enable = true)) whenever(subscriptionsManager.getSubscriptionOffer()).thenReturn( @@ -217,7 +217,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenGetSubscriptionsAndNoSubscriptionOfferThenSendCommandWithEmptyData() = runTest { + fun `whenGetSubscriptionsAndNoSubscriptionOfferThenSendCommandWithEmptyData - send command with empty data`() = runTest { privacyProFeature.allowPurchase().setEnabled(Toggle.State(enable = true)) viewModel.commands().test { @@ -238,7 +238,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenGetSubscriptionsAndToggleOffThenSendCommandWithEmptyData() = runTest { + fun `processJsCallbackMessage - get subscriptions and toggle off - send command with empty data`() = runTest { privacyProFeature.allowPurchase().setEnabled(Toggle.State(enable = false)) whenever(subscriptionsManager.getSubscriptionOffer()).thenReturn( SubscriptionOffer( @@ -267,7 +267,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenActivateSubscriptionAndSubscriptionActiveThenNoCommandSent() = runTest { + fun `activateSubscription - subscription active - no command sent`() = runTest { whenever(subscriptionsManager.subscriptionStatus()).thenReturn(AUTO_RENEWABLE) viewModel.commands().test { expectNoEvents() @@ -275,7 +275,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenActivateSubscriptionAndSubscriptionInactiveThenCommandSent() = runTest { + fun `processJsCallbackMessage - subscription inactive - command sent`() = runTest { whenever(subscriptionsManager.subscriptionStatus()).thenReturn(INACTIVE) viewModel.commands().test { viewModel.processJsCallbackMessage("test", "activateSubscription", null, null) @@ -284,7 +284,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenSetSubscriptionAndExpiredSubscriptionThenCommandNotSent() = runTest { + fun `processJsCallbackMessage - set subscription and expired subscription - command not sent`() = runTest { whenever(subscriptionsManager.subscriptionStatus()).thenReturn(EXPIRED) viewModel.commands().test { viewModel.processJsCallbackMessage("test", "setSubscription", null, null) @@ -293,7 +293,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenSetSubscriptionAndActiveSubscriptionThenCommandNotSent() = runTest { + fun `processJsCallbackMessage - set subscription and active subscription - command not sent`() = runTest { whenever(subscriptionsManager.subscriptionStatus()).thenReturn(AUTO_RENEWABLE) viewModel.commands().test { viewModel.processJsCallbackMessage("test", "setSubscription", null, null) @@ -302,7 +302,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenFeatureSelectedAndNoDataThenCommandNotSent() = runTest { + fun `processJsCallbackMessage - feature selected and no data - command not sent`() = runTest { whenever(subscriptionsManager.subscriptionStatus()).thenReturn(EXPIRED) viewModel.commands().test { viewModel.processJsCallbackMessage("test", "featureSelected", null, null) @@ -311,7 +311,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenFeatureSelectedAndInvalidDataThenCommandNotSent() = runTest { + fun `processJsCallbackMessage - feature selected and invalid data - command not sent`() = runTest { whenever(subscriptionsManager.subscriptionStatus()).thenReturn(EXPIRED) viewModel.commands().test { viewModel.processJsCallbackMessage("test", "featureSelected", null, JSONObject("{}")) @@ -320,7 +320,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenFeatureSelectedAndInvalidFeatureThenCommandNotSent() = runTest { + fun `processJsCallbackMessage - feature selected and invalid feature - command not sent`() = runTest { whenever(subscriptionsManager.subscriptionStatus()).thenReturn(EXPIRED) viewModel.commands().test { viewModel.processJsCallbackMessage("test", "featureSelected", null, JSONObject("""{"feature":"test"}""")) @@ -329,7 +329,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenFeatureSelectedAndFeatureIsNetPThenCommandSent() = runTest { + fun `processJsCallbackMessage - feature selected and feature is net p - command sent`() = runTest { whenever(subscriptionsManager.subscriptionStatus()).thenReturn(EXPIRED) viewModel.commands().test { viewModel.processJsCallbackMessage( @@ -343,7 +343,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenFeatureSelectedAndFeatureIsItrThenCommandSent() = runTest { + fun `processJsCallbackMessage - feature selected and feature is ITR - command sent`() = runTest { whenever(subscriptionsManager.subscriptionStatus()).thenReturn(EXPIRED) viewModel.commands().test { viewModel.processJsCallbackMessage( @@ -357,7 +357,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenFeatureSelectedAndFeatureIsPirThenCommandSent() = runTest { + fun `processJsCallbackMessage - feature selected and pir - command sent`() = runTest { whenever(subscriptionsManager.subscriptionStatus()).thenReturn(EXPIRED) viewModel.commands().test { viewModel.processJsCallbackMessage( @@ -371,7 +371,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenSubscriptionSelectedThenPixelIsSent() = runTest { + fun `processJsCallbackMessage - subscription selected - pixel is sent`() = runTest { viewModel.processJsCallbackMessage( featureName = "test", method = "subscriptionSelected", @@ -382,7 +382,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenRestorePurchaseClickedThenPixelIsSent() = runTest { + fun `processJsCallbackMessage - restore purchase clicked - pixel sent`() = runTest { whenever(subscriptionsManager.subscriptionStatus()).thenReturn(EXPIRED) viewModel.processJsCallbackMessage( featureName = "test", @@ -394,7 +394,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenAddEmailClickedAndInPurchaseFlowThenPixelIsSent() = runTest { + fun `start - add email clicked and in purchase flow - pixel sent`() = runTest { whenever(subscriptionsManager.subscriptionStatus()).thenReturn(AUTO_RENEWABLE) whenever(subscriptionsManager.currentPurchaseState).thenReturn(flowOf(CurrentPurchase.Success)) viewModel.start() @@ -409,7 +409,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenAddEmailClickedAndNotInPurchaseFlowThenPixelIsNotSent() = runTest { + fun `processJsCallbackMessage - not in purchase flow - pixel is not sent`() = runTest { whenever(subscriptionsManager.subscriptionStatus()).thenReturn(AUTO_RENEWABLE) viewModel.processJsCallbackMessage( @@ -422,7 +422,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenFeatureSelectedAndFeatureIsNetPAndInPurchaseFlowThenPixelIsSent() = runTest { + fun `start - feature selected and in purchase flow - pixel sent`() = runTest { whenever(subscriptionsManager.subscriptionStatus()).thenReturn(AUTO_RENEWABLE) whenever(subscriptionsManager.currentPurchaseState).thenReturn(flowOf(CurrentPurchase.Success)) viewModel.start() @@ -437,7 +437,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenFeatureSelectedAndFeatureIsNetPAndNotInPurchaseFlowThenPixelIsNotSent() = runTest { + fun `processJsCallbackMessage - feature selected and not in purchase flow - pixel is not sent`() = runTest { whenever(subscriptionsManager.subscriptionStatus()).thenReturn(AUTO_RENEWABLE) viewModel.processJsCallbackMessage( @@ -478,7 +478,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenFeatureSelectedAndFeatureIsPirAndInPurchaseFlowThenPixelIsSent() = runTest { + fun `start - feature selected and pir in purchase flow - pixel is sent`() = runTest { whenever(subscriptionsManager.subscriptionStatus()).thenReturn(AUTO_RENEWABLE) whenever(subscriptionsManager.currentPurchaseState).thenReturn(flowOf(CurrentPurchase.Success)) viewModel.start() @@ -506,7 +506,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenSubscriptionsWelcomeFaqClickedAndInPurchaseFlowThenPixelIsSent() = runTest { + fun `start - subscriptions welcome faq clicked and in purchase flow - pixel is sent`() = runTest { whenever(subscriptionsManager.subscriptionStatus()).thenReturn(AUTO_RENEWABLE) whenever(subscriptionsManager.currentPurchaseState).thenReturn(flowOf(CurrentPurchase.Success)) viewModel.start() @@ -521,7 +521,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenSubscriptionsWelcomeFaqClickedAndNotInPurchaseFlowThenPixelIsNotSent() = runTest { + fun `processJsCallbackMessage - subscriptions welcome faq clicked and not in purchase flow - pixel is not sent`() = runTest { whenever(subscriptionsManager.subscriptionStatus()).thenReturn(AUTO_RENEWABLE) viewModel.processJsCallbackMessage( diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/AppSyncDeviceIdsTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/AppSyncDeviceIdsTest.kt index 3e1668856ace..2085e405cfc8 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/AppSyncDeviceIdsTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/AppSyncDeviceIdsTest.kt @@ -36,28 +36,28 @@ class AppSyncDeviceIdsTest { private var deviceInfo: DeviceInfo = mock() @Test - fun whenUserIdExistsInStoreThenReturnsStoredValue() { + fun `getAppSyncDeviceIds - user id exists in store - returns stored value`() { val syncStore = getFakeSyncStore() val appSyncDeviceIds = AppSyncDeviceIds(syncStore, deviceInfo) assertEquals(syncStore.userId, appSyncDeviceIds.userId()) } @Test - fun whenDeviceIdExistsInStoreThenReturnsStoredValue() { + fun `getDeviceId - device id exists in store - returns stored value`() { val syncStore = getFakeSyncStore() val appSyncDeviceIds = AppSyncDeviceIds(syncStore, deviceInfo) assertEquals(syncStore.deviceId, appSyncDeviceIds.deviceId()) } @Test - fun whenDeviceNameExistsInStoreThenReturnsStoredValue() { + fun `getAppSyncDeviceIds - device name exists in store - returns stored value`() { val syncStore = getFakeSyncStore() val appSyncDeviceIds = AppSyncDeviceIds(syncStore, deviceInfo) assertEquals(syncStore.deviceName, appSyncDeviceIds.deviceName()) } @Test - fun whenUserIdDoesNotExistInStoreThenNewIdIsReturned() { + fun `getUserId - user id does not exist in store - new id returned`() { val emptySyncStore = getFakeEmptySyncStore() assertNull(emptySyncStore.userId) @@ -68,7 +68,7 @@ class AppSyncDeviceIdsTest { } @Test - fun whenDeviceIdDoesNotExistInStoreThenNewIdIsReturned() { + fun `deviceId - does not exist in store - new id returned`() { val emptySyncStore = getFakeEmptySyncStore() assertNull(emptySyncStore.deviceId) @@ -79,7 +79,7 @@ class AppSyncDeviceIdsTest { } @Test - fun whenDeviceNameDoesNotExistInStoreThenNewIdIsReturned() { + fun `deviceName - does not exist in store - new id is returned`() { val emptySyncStore = getFakeEmptySyncStore() assertNull(emptySyncStore.deviceName) val appSyncDeviceIds = AppSyncDeviceIds(emptySyncStore, deviceInfo) @@ -89,7 +89,7 @@ class AppSyncDeviceIdsTest { } @Test - fun whenPlatformTypeIsAndroidPhoneThenDeviceTypeMobile() { + fun `getAppSyncDeviceIds - platform type android phone - mobile`() { val emptySyncStore = getFakeEmptySyncStore() whenever(deviceInfo.formFactor()).thenReturn(DeviceInfo.FormFactor.PHONE) val appSyncDeviceIds = AppSyncDeviceIds(emptySyncStore, deviceInfo) diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/AppDeviceSyncStateTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/AppDeviceSyncStateTest.kt index 96616ebf5c67..1f3d4c85f826 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/AppDeviceSyncStateTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/AppDeviceSyncStateTest.kt @@ -29,21 +29,21 @@ internal class AppDeviceSyncStateTest { private val appDeviceSyncState = AppDeviceSyncState(syncFeatureToggle, syncAccountRepository) @Test - fun whenUserSignedInThenDeviceSyncEnabled() { + fun `isUserSignedInOnDevice - device sync enabled`() { whenever(syncAccountRepository.isSignedIn()).thenReturn(true) assertTrue(appDeviceSyncState.isUserSignedInOnDevice()) } @Test - fun whenShowSyncDisabledThenFeatureDisabled() { + fun `showSync - feature disabled - not enabled`() { givenFeatureFlag(enabled = false) assertFalse(appDeviceSyncState.isFeatureEnabled()) } @Test - fun whenShowSyncEnabledThenFeatureEnabled() { + fun `showSync - is feature enabled`() { givenFeatureFlag(enabled = true) assertTrue(appDeviceSyncState.isFeatureEnabled()) diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/AppSyncAccountRepositoryTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/AppSyncAccountRepositoryTest.kt index 762a021f8b94..eae2d81c32ca 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/AppSyncAccountRepositoryTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/AppSyncAccountRepositoryTest.kt @@ -103,7 +103,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenCreateAccountSucceedsThenAccountPersisted() { + fun `createAccount - store credentials persisted`() { prepareToProvideDeviceIds() prepareForCreateAccountSuccess() @@ -121,7 +121,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenUserSignedInCreatesAccountThenReturnAlreadySignedInError() { + fun `createAccount - user signed in - already signed in error`() { whenever(syncStore.isSignedIn()).thenReturn(true) val result = syncRepo.createAccount() as Error @@ -130,7 +130,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenCreateAccountFailsThenReturnCreateAccountError() { + fun `createAccount - fails - return create account error`() { prepareToProvideDeviceIds() prepareForEncryption() whenever(nativeLib.generateAccountKeys(userId = anyString(), password = anyString())).thenReturn(accountKeys) @@ -143,7 +143,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenCreateAccountGenerateKeysFailsThenReturnCreateAccountError() { + fun `createAccount - generate keys fails - return create account error`() { prepareToProvideDeviceIds() whenever(nativeLib.generateAccountKeys(userId = anyString(), password = anyString())).thenReturn(accountKeysFailed) whenever(syncApi.createAccount(anyString(), anyString(), anyString(), anyString(), anyString(), anyString())) @@ -156,7 +156,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenAccountExistsThenGetAccountInfoReturnData() { + fun `getAccountInfo - account exists - returns data`() { givenAuthenticatedDevice() val result = syncRepo.getAccountInfo() @@ -168,7 +168,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenAccountNotCreatedThenAccountInfoEmpty() { + fun `getAccountInfo - account not created - empty`() { whenever(syncStore.primaryKey).thenReturn("") val result = syncRepo.getAccountInfo() @@ -180,7 +180,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenLogoutSucceedsThenReturnSuccessAndRemoveData() { + fun `logout - succeeds - return success and remove data`() { givenAuthenticatedDevice() whenever(syncApi.logout(token, deviceId)).thenReturn(logoutSuccess) @@ -191,7 +191,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenLogoutRemoteDeviceSucceedsThenReturnSuccessButDoNotRemoveLocalData() { + fun `logout - succeeds - return success but do not remove local data`() { whenever(syncStore.deviceId).thenReturn(deviceId) whenever(syncStore.token).thenReturn(token) whenever(syncApi.logout(eq(token), anyString())).thenReturn(logoutSuccess) @@ -203,7 +203,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenDeleteAccountSucceedsThenReturnSuccessAndRemoveData() { + fun `deleteAccount - succeeds - return success and remove data`() { givenAuthenticatedDevice() whenever(syncApi.deleteAccount(token)).thenReturn(deleteAccountSuccess) @@ -214,7 +214,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenProcessJsonRecoveryCodeSucceedsThenAccountPersisted() { + fun `processJsonRecoveryCode - account persisted`() { prepareForLoginSuccess() val result = syncRepo.processCode(jsonRecoveryKeyEncoded) @@ -231,7 +231,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenGenerateKeysFromRecoveryCodeFailsThenReturnLoginFailedError() { + fun `generateKeysFromRecoveryCode - fails - return login failed error`() { prepareToProvideDeviceIds() whenever(nativeLib.prepareForLogin(primaryKey = primaryKey)).thenReturn(failedLoginKeys) @@ -241,7 +241,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenLoginFailsThenReturnLoginFailedError() { + fun `processCode - login fails - return login failed error`() { prepareToProvideDeviceIds() prepareForEncryption() whenever(nativeLib.prepareForLogin(primaryKey = primaryKey)).thenReturn(validLoginKeys) @@ -253,7 +253,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenProcessRecoveryKeyAndDecryptSecretKeyFailsThenReturnLoginFailedError() { + fun `processRecoveryKey - decryption fails - login failed error`() { prepareToProvideDeviceIds() prepareForEncryption() whenever(nativeLib.prepareForLogin(primaryKey = primaryKey)).thenReturn(validLoginKeys) @@ -266,14 +266,14 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenProcessInvalidCodeThenReturnInvalidCodeError() { + fun `processCode - invalid code - invalid code error`() { val result = syncRepo.processCode("invalidCode") as Error assertEquals(INVALID_CODE.code, result.code) } @Test - fun getConnectedDevicesSucceedsThenReturnSuccess() { + fun `getConnectedDevices - succeeds - returns success`() { whenever(syncStore.token).thenReturn(token) whenever(syncStore.primaryKey).thenReturn(primaryKey) whenever(syncStore.deviceId).thenReturn(deviceId) @@ -286,7 +286,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun getConnectedDevicesReturnsListWithLocalDeviceInFirstPosition() { + fun `getConnectedDevices - returns list with local device in first position`() { givenAuthenticatedDevice() prepareForEncryption() val thisDevice = Device(deviceId = deviceId, deviceName = deviceName, jwIat = "", deviceType = deviceFactor) @@ -300,7 +300,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun getConnectedDevicesFailsThenReturnGenericError() { + fun `getConnectedDevices - fails - return generic error`() { whenever(syncStore.token).thenReturn(token) whenever(syncStore.deviceId).thenReturn(deviceId) whenever(syncStore.primaryKey).thenReturn(primaryKey) @@ -312,7 +312,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun getConnectedDevicesDecryptionFailsThenLogoutDevice() { + fun `getConnectedDevices - decryption fails - logout device`() { givenAuthenticatedDevice() prepareForEncryption() val thisDevice = Device(deviceId = deviceId, deviceName = deviceName, jwIat = "", deviceType = deviceFactor) @@ -330,7 +330,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenGenerateRecoveryCodeAsStringThenReturnExpectedJson() { + fun `getRecoveryCode - when generate recovery code as string then return expected json`() { whenever(syncStore.primaryKey).thenReturn(primaryKey) whenever(syncStore.userId).thenReturn(userId) @@ -340,14 +340,14 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenGenerateRecoveryCodeWithoutAccountThenReturnGenericError() { + fun `getRecoveryCode - no account - generic error`() { val result = syncRepo.getRecoveryCode() as Error assertEquals(GENERIC_ERROR.code, result.code) } @Test - fun whenGetConnectQRThenReturnExpectedJson() { + fun `getConnectQR - return expected json`() { whenever(nativeLib.prepareForConnect()).thenReturn(connectKeys) prepareToProvideDeviceIds() @@ -357,7 +357,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenProcessConnectCodeFromAuthenticatedDeviceThenConnectsDevice() { + fun `processConnectCodeFromAuthenticatedDevice - connects device`() { givenAuthenticatedDevice() whenever(nativeLib.seal(jsonRecoveryKey, primaryKey)).thenReturn(encryptedRecoveryCode) whenever(syncApi.connect(token, deviceId, encryptedRecoveryCode)).thenReturn(Result.Success(true)) @@ -369,7 +369,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenProcessConnectCodeFromUnauthenticatedDeviceThenAccountCreatedAndConnects() { + fun `processConnectCodeFromUnauthenticatedDevice - account created and connects`() { whenever(syncStore.primaryKey).thenReturn(primaryKey) whenever(syncStore.isSignedIn()).thenReturn(false).thenReturn(true) whenever(syncStore.userId).thenReturn(userId) @@ -387,7 +387,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenPollingConnectionKeysAndKeysFoundThenPerformLogin() { + fun `pollConnectionKeys - keys found - perform login`() { prepareForLoginSuccess() whenever(syncStore.userId).thenReturn(userId) whenever(syncStore.primaryKey).thenReturn(primaryKey) @@ -401,7 +401,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenPollingConnectionAndLoginFailsThenReturnLoginError() { + fun `pollConnectionKeys - login fails - return login error`() { whenever(syncDeviceIds.deviceId()).thenReturn(deviceId) whenever(syncStore.userId).thenReturn(userId) whenever(syncStore.primaryKey).thenReturn(primaryKey) @@ -416,7 +416,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenPollingConnectionAndKeysNotFoundThenReturnSuccessFalse() { + fun `pollConnectionKeys - keys not found - return success false`() { whenever(syncDeviceIds.deviceId()).thenReturn(deviceId) whenever(syncStore.userId).thenReturn(userId) whenever(syncStore.primaryKey).thenReturn(primaryKey) @@ -429,7 +429,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenPollingConnectionAndSealOpenFailsThenReturnConnectError() { + fun `pollConnectionKeys - seal open fails - return connect error`() { whenever(syncDeviceIds.deviceId()).thenReturn(deviceId) whenever(syncStore.userId).thenReturn(userId) whenever(syncStore.primaryKey).thenReturn(primaryKey) @@ -443,7 +443,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenPollingConnectionAndKeysExpiredThenReturnConnectFailedError() { + fun `pollConnectionKeys - polling connection and keys expired - connect failed error`() { whenever(syncDeviceIds.deviceId()).thenReturn(deviceId) whenever(syncStore.userId).thenReturn(userId) whenever(syncStore.primaryKey).thenReturn(primaryKey) @@ -456,7 +456,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenGetThisConnectedDeviceThenReturnExpectedDevice() { + fun `getThisConnectedDevice - when get this connected device then return expected device`() { givenAuthenticatedDevice() whenever(syncStore.deviceId).thenReturn(deviceId) whenever(syncStore.deviceName).thenReturn(deviceName) @@ -470,21 +470,21 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenGetThisConnectedDeviceAndNotAuthenticatedThenReturnNull() { + fun `getThisConnectedDevice - not authenticated - null`() { val result = syncRepo.getThisConnectedDevice() assertNull(result) } @Test - fun whenRenameDeviceUnAuthenticatedThenReturnError() { + fun `renameDevice - unauthenticated - return error`() { val result = syncRepo.renameDevice(connectedDevice) assertTrue(result is Error) } @Test - fun whenRenameDeviceSuccessThenReturnSuccess() { + fun `renameDevice - success - return success`() { givenAuthenticatedDevice() prepareForLoginSuccess() @@ -495,7 +495,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenEncryptionNotSupportedThenSyncNotSupported() { + fun `isSyncSupported - encryption not supported - not supported`() { whenever(syncStore.isEncryptionSupported()).thenReturn(false) val result = syncRepo.isSyncSupported() diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/RealSyncStateMonitorTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/RealSyncStateMonitorTest.kt index 34f878a95de0..2de8e7809f60 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/RealSyncStateMonitorTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/RealSyncStateMonitorTest.kt @@ -60,7 +60,7 @@ class RealSyncStateMonitorTest { } @Test - fun whenSyncDisabledThenStateIsOff() = runTest { + fun `syncState - state is off`() = runTest { testee.syncState().test { val state = awaitItem() Assert.assertTrue(state == OFF) @@ -68,7 +68,7 @@ class RealSyncStateMonitorTest { } @Test - fun whenSyncEnabledThenStateIsREADY() = runTest { + fun `syncState - state is READY`() = runTest { testee.syncState().test { signedInFlow.emit(true) val state = expectMostRecentItem() @@ -77,7 +77,7 @@ class RealSyncStateMonitorTest { } @Test - fun whenSyncEnabledAndAttemptSuccessThenStateIsReady() = runTest { + fun `syncEnabled - attempt success - state is ready`() = runTest { testee.syncState().test { signedInFlow.emit(true) stateFlow.emit(SyncAttempt(state = SyncAttemptState.SUCCESS)) @@ -87,7 +87,7 @@ class RealSyncStateMonitorTest { } @Test - fun whenSyncEnabledAndAttemptFailThenStateIsFailed() = runTest { + fun `syncEnabled - attempt fail - state is failed`() = runTest { testee.syncState().test { signedInFlow.emit(true) stateFlow.emit(SyncAttempt(state = SyncAttemptState.FAIL)) @@ -97,7 +97,7 @@ class RealSyncStateMonitorTest { } @Test - fun whenSyncEnabledAndAttemptInProgressThenStateIsInProgress() = runTest { + fun `syncState - in progress - in progress`() = runTest { testee.syncState().test { signedInFlow.emit(true) stateFlow.emit(SyncAttempt(state = SyncAttemptState.IN_PROGRESS)) diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/SyncCryptoTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/SyncCryptoTest.kt index 197e6d1a0751..162a46788989 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/SyncCryptoTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/SyncCryptoTest.kt @@ -48,7 +48,7 @@ class SyncCryptoTest { } @Test(expected = java.lang.Exception::class) - fun whenEncryptFailsThenResultIsEmpty() { + fun `encrypt - fails - result is empty`() { whenever(nativeLib.encryptData(any(), any())).thenReturn(EncryptResult(1, "not encrypted")) val result = syncCrypto.encrypt("something") @@ -59,7 +59,7 @@ class SyncCryptoTest { } @Test - fun whenEncryptSucceedsThenResultIsEncrypted() { + fun `encrypt - succeeds - result is encrypted`() { whenever(nativeLib.encryptData(any(), any())).thenReturn(EncryptResult(0, "not encrypted")) val result = syncCrypto.encrypt("something") @@ -70,7 +70,7 @@ class SyncCryptoTest { } @Test(expected = java.lang.Exception::class) - fun whenDecryptFailsThenResultIsEmpty() { + fun `decrypt - fails - empty result`() { whenever(nativeLib.decryptData(any(), any())).thenReturn(DecryptResult(1, "not decrypted")) val result = syncCrypto.decrypt("something") @@ -81,7 +81,7 @@ class SyncCryptoTest { } @Test - fun whenDecryptSucceedsThenResultIsDecrypted() { + fun `decrypt - succeeds - result is decrypted`() { whenever(nativeLib.decryptData(any(), any())).thenReturn(DecryptResult(0, "not decrypted")) val result = syncCrypto.decrypt("something") @@ -92,7 +92,7 @@ class SyncCryptoTest { } @Test - fun whenDataToDecryptIsEmptyThenResultIsEmpty() { + fun `decrypt - data to decrypt empty - result empty`() { val result = syncCrypto.decrypt("") verifyNoInteractions(recorder) diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/SyncRemoteFeatureToggleTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/SyncRemoteFeatureToggleTest.kt index 115991bdf658..6d6eaae815f1 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/SyncRemoteFeatureToggleTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/SyncRemoteFeatureToggleTest.kt @@ -56,7 +56,7 @@ class SyncRemoteFeatureToggleTest { private lateinit var testee: SyncRemoteFeatureToggle @Test - fun whenFeatureDisabledThenInternalBuildShowSyncTrue() { + fun `whenFeatureDisabledThenInternalBuildShowSyncTrue - internal build - show sync true`() { whenever(appBuildConfig.flavor).thenReturn(BuildFlavor.INTERNAL) val syncFeature = TestSyncFeature(appBuildConfig).apply { sync = false @@ -67,7 +67,7 @@ class SyncRemoteFeatureToggleTest { } @Test - fun whenFeatureDisabledThenShowSyncIsFalse() { + fun `whenFeatureDisabledThenShowSyncIsFalse - show sync is false`() { whenever(appBuildConfig.flavor).thenReturn(BuildFlavor.PLAY) val syncFeature = TestSyncFeature(appBuildConfig).apply { sync = false @@ -78,7 +78,7 @@ class SyncRemoteFeatureToggleTest { } @Test - fun whenShowSyncDisabledThenAllFeaturesDisabled() { + fun `showSyncDisabled - all features disabled`() { val syncFeature = TestSyncFeature(appBuildConfig).apply { showSync = false } @@ -90,7 +90,7 @@ class SyncRemoteFeatureToggleTest { } @Test - fun whenAllowDataSyncingFalseThenAllowDataSyncingFalse() { + fun `allowDataSyncing - false - false`() { val syncFeature = TestSyncFeature(appBuildConfig).apply { allowDataSyncing = false } @@ -100,7 +100,7 @@ class SyncRemoteFeatureToggleTest { } @Test - fun whenAllowDataSyncEnabledButNotForThisVersionThenAllowDataSyncingOnNewerVersionTrue() { + fun `allowDataSync - enabled but not for this version - allow data syncing on newer version true`() { whenever(appBuildConfig.versionCode).thenReturn(1) val syncFeature = TestSyncFeature(appBuildConfig).apply { allowDataSyncing = true @@ -113,7 +113,7 @@ class SyncRemoteFeatureToggleTest { } @Test - fun whenAllowDataSyncingFalseThenSetupFlowsAndCreateAccountDisabled() { + fun `whenAllowDataSyncingFalseThenSetupFlowsAndCreateAccountDisabled - setup flows and create account disabled`() { val syncFeature = TestSyncFeature(appBuildConfig).apply { allowDataSyncing = false } @@ -124,7 +124,7 @@ class SyncRemoteFeatureToggleTest { } @Test - fun whenAllowSetupFlowsFalseThenAllowDataSyncingEnabled() { + fun `givenSyncRemoteFeatureToggle - allow setup flows false - allow data syncing enabled`() { val syncFeature = TestSyncFeature(appBuildConfig).apply { allowSetupFlows = false } @@ -134,7 +134,7 @@ class SyncRemoteFeatureToggleTest { } @Test - fun whenAllowSetupFlowsEnabledButNotForThisVersionThenAllowSetupFlowsOnNewerVersionTrue() { + fun `allowSetupFlows - not for this version - allow setup flows on newer version true`() { whenever(appBuildConfig.versionCode).thenReturn(1) val syncFeature = TestSyncFeature(appBuildConfig).apply { allowSetupFlows = true @@ -147,7 +147,7 @@ class SyncRemoteFeatureToggleTest { } @Test - fun whenAllowSetupFlowsFalseThenSetupFlowsAndCreateAccountDisabled() { + fun `allowSetupFlows - setup flows and create account disabled`() { val syncFeature = TestSyncFeature(appBuildConfig).apply { allowSetupFlows = false } @@ -158,7 +158,7 @@ class SyncRemoteFeatureToggleTest { } @Test - fun whenAllowCreateAccountFalseThenAllowCreateAccountFalse() { + fun `givenSyncRemoteFeatureToggle - allow create account false - false`() { val syncFeature = TestSyncFeature(appBuildConfig).apply { allowCreateAccount = false } @@ -168,7 +168,7 @@ class SyncRemoteFeatureToggleTest { } @Test - fun whenAllowCreateAccountTrueButNotForThisVersionThenAllowCreateAccountOnNewerVersionTrue() { + fun `allowCreateAccount - not for this version - allow create account on newer version true`() { whenever(appBuildConfig.versionCode).thenReturn(1) val syncFeature = TestSyncFeature(appBuildConfig).apply { allowCreateAccount = true @@ -181,7 +181,7 @@ class SyncRemoteFeatureToggleTest { } @Test - fun whenAllowCreateAccountFalseThenDataSyncingAndSetupFlowsEnabled() { + fun `whenAllowCreateAccountFalseThenDataSyncingAndSetupFlowsEnabled - data syncing and setup flows enabled`() { val syncFeature = TestSyncFeature(appBuildConfig).apply { allowCreateAccount = false } diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/SyncServiceRemoteTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/SyncServiceRemoteTest.kt index d33ee63ef3bd..52f04c448719 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/SyncServiceRemoteTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/SyncServiceRemoteTest.kt @@ -75,7 +75,7 @@ class SyncServiceRemoteTest { private val syncStore: SyncStore = mock() @Test - fun whenCreateAccountSucceedsThenReturnAccountCreatedSuccess() { + fun `createAccount - succeeds - return account created success`() { val syncRemote = SyncServiceRemote(syncService, syncStore) val call: Call = mock() whenever(syncService.signup(signUpRequest)).thenReturn(call) @@ -89,7 +89,7 @@ class SyncServiceRemoteTest { } @Test - fun whenCreateAccountIsInvalidThenReturnError() { + fun `createAccount - is invalid - return error`() { val syncRemote = SyncServiceRemote(syncService, syncStore) val call: Call = mock() whenever(syncService.signup(signUpRequest)).thenReturn(call) @@ -103,7 +103,7 @@ class SyncServiceRemoteTest { } @Test - fun whenCreateAccountDuplicateUserThenReturnError() { + fun `createAccount - duplicate user - return error`() { val syncRemote = SyncServiceRemote(syncService, syncStore) val call: Call = mock() whenever(syncService.signup(signUpRequest)).thenReturn(call) @@ -117,7 +117,7 @@ class SyncServiceRemoteTest { } @Test - fun whenLogoutSucceedsThenReturnLogoutSuccess() { + fun `logout - succeeds - return logout success`() { val syncRemote = SyncServiceRemote(syncService, syncStore) val call: Call = mock() whenever(syncService.logout(anyString(), eq(deviceLogoutBody))).thenReturn(call) @@ -129,7 +129,7 @@ class SyncServiceRemoteTest { } @Test - fun whenLogoutIsInvalidThenReturnError() { + fun `logout - invalid logout - return error`() { val syncRemote = SyncServiceRemote(syncService, syncStore) val call: Call = mock() whenever(syncService.logout(anyString(), eq(deviceLogoutBody))).thenReturn(call) @@ -142,7 +142,7 @@ class SyncServiceRemoteTest { } @Test - fun whenDeleteAccountSucceedsThenReturnDeleteAccountSuccess() { + fun `deleteAccount - succeeds - return delete account success`() { val syncRemote = SyncServiceRemote(syncService, syncStore) val call: Call = mock() whenever(syncService.deleteAccount(anyString())).thenReturn(call) @@ -154,7 +154,7 @@ class SyncServiceRemoteTest { } @Test - fun whenDeleteAccountIsInvalidThenReturnError() { + fun `deleteAccount - invalid token - return error`() { val syncRemote = SyncServiceRemote(syncService, syncStore) val call: Call = mock() whenever(syncService.deleteAccount(anyString())).thenReturn(call) @@ -167,7 +167,7 @@ class SyncServiceRemoteTest { } @Test - fun whenLoginSucceedsThenReturnLoginSuccess() { + fun `login - succeeds - returns login success`() { val syncRemote = SyncServiceRemote(syncService, syncStore) val call: Call = mock() whenever(syncService.login(loginRequestBody)).thenReturn(call) @@ -179,7 +179,7 @@ class SyncServiceRemoteTest { } @Test - fun whenLoginIsInvalidThenReturnError() { + fun `login - invalid login - returns error`() { val syncRemote = SyncServiceRemote(syncService, syncStore) val call: Call = mock() whenever(syncService.login(loginRequestBody)).thenReturn(call) @@ -191,7 +191,7 @@ class SyncServiceRemoteTest { } @Test - fun whenGetDevicesSuccessThenResultSuccess() { + fun `getDevices - success - result success`() { val syncRemote = SyncServiceRemote(syncService, syncStore) val call: Call = mock() whenever(syncService.getDevices(anyString())).thenReturn(call) @@ -203,7 +203,7 @@ class SyncServiceRemoteTest { } @Test - fun whenGetDevicesSuccessFailsThenResultError() { + fun `getDevices - success fails - result error`() { val syncRemote = SyncServiceRemote(syncService, syncStore) val call: Call = mock() whenever(syncService.getDevices(anyString())).thenReturn(call) @@ -215,7 +215,7 @@ class SyncServiceRemoteTest { } @Test - fun whenGetDevicesIsInvalidCodeThenResultError() { + fun `getDevices - invalid code - result error`() { val syncRemote = SyncServiceRemote(syncService, syncStore) val call: Call = mock() whenever(syncService.getDevices(anyString())).thenReturn(call) @@ -228,7 +228,7 @@ class SyncServiceRemoteTest { } @Test - fun whenConnectSuccedsThenReturnSuccess() { + fun `connect - succeeds - returns success`() { val syncRemote = SyncServiceRemote(syncService, syncStore) val call: Call = mock() whenever(syncService.connect(anyString(), eq(connectBody))).thenReturn(call) @@ -240,7 +240,7 @@ class SyncServiceRemoteTest { } @Test - fun whenConnectFailsThenReturnError() { + fun `connect - fails - returns error`() { val syncRemote = SyncServiceRemote(syncService, syncStore) val call: Call = mock() whenever(syncService.connect(anyString(), eq(connectBody))).thenReturn(call) @@ -252,7 +252,7 @@ class SyncServiceRemoteTest { } @Test - fun whenConnectDeviceSuccedsThenReturnSuccess() { + fun `connectDevice - succeeds - return success`() { val syncRemote = SyncServiceRemote(syncService, syncStore) val call: Call = mock() whenever(syncService.connectDevice(deviceId)).thenReturn(call) @@ -264,7 +264,7 @@ class SyncServiceRemoteTest { } @Test - fun whenConnectDeviceFailsThenReturnError() { + fun `connectDevice - fails - return error`() { val syncRemote = SyncServiceRemote(syncService, syncStore) val call: Call = mock() whenever(syncService.connectDevice(deviceId)).thenReturn(call) diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/engine/SyncApiClientTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/engine/SyncApiClientTest.kt index 05d731db171b..fc921a5894fc 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/engine/SyncApiClientTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/engine/SyncApiClientTest.kt @@ -55,7 +55,7 @@ internal class SyncApiClientTest { } @Test - fun whenPatchAndTokenEmptyThenReturnError() { + fun `patch - token empty - return error`() { whenever(syncStore.token).thenReturn("") val result = apiClient.patch(SyncChangesRequest.empty()) @@ -65,7 +65,7 @@ internal class SyncApiClientTest { } @Test - fun whenPatchAndChangesEmptyThenReturnError() { + fun `patch - changes empty - return error`() { whenever(syncStore.token).thenReturn(TestSyncFixtures.token) val result = apiClient.patch(SyncChangesRequest.empty()) @@ -75,7 +75,7 @@ internal class SyncApiClientTest { } @Test - fun whenPatchAndBookmarkChangesThenApiIsSuccessful() { + fun `patchAndBookmarkChanges - api successful`() { val updatesJSON = FileUtilities.loadText(javaClass.classLoader!!, "data_sync_sent_bookmarks.json") val bookmarksChanges = SyncChangesRequest(BOOKMARKS, updatesJSON, FirstSync) whenever(syncStore.token).thenReturn(TestSyncFixtures.token) @@ -87,7 +87,7 @@ internal class SyncApiClientTest { } @Test - fun whenPatchAndBookmarkChangesThenApiFailsAndApiErrorIsRecorded() { + fun `patchAndBookmarkChanges - api fails and error recorded`() { val updatesJSON = FileUtilities.loadText(javaClass.classLoader!!, "data_sync_sent_bookmarks.json") val bookmarksChanges = SyncChangesRequest(BOOKMARKS, updatesJSON, FirstSync) whenever(syncStore.token).thenReturn(TestSyncFixtures.token) @@ -99,7 +99,7 @@ internal class SyncApiClientTest { } @Test - fun whenMappingChangesThenGeneratedObjectIsCorrect() { + fun `mapRequest - mapping changes - generated object is correct`() { val updatesJSON = FileUtilities.loadText(javaClass.classLoader!!, "data_sync_sent_bookmarks.json") val bookmarksChanges = SyncChangesRequest(BOOKMARKS, updatesJSON, FirstSync) val changes = apiClient.mapRequest(listOf(bookmarksChanges)) @@ -108,7 +108,7 @@ internal class SyncApiClientTest { } @Test - fun whenGetBookmarksAndTokenEmptyThenReturnError() { + fun `get - token empty - return error`() { whenever(syncStore.token).thenReturn("") val result = apiClient.get(BOOKMARKS, "") @@ -128,7 +128,7 @@ internal class SyncApiClientTest { } @Test - fun whenGetBookmarksAndApiFailsThenResultIsErrorAndErrorIsRecorded() { + fun `get - bookmarks - error and error recorded`() { whenever(syncStore.token).thenReturn(TestSyncFixtures.token) whenever(syncApi.getBookmarks(any(), any())).thenReturn(getAllError) @@ -138,7 +138,7 @@ internal class SyncApiClientTest { } @Test - fun whenGetCredentialsAndApiFailsThenResultIsErrorAndErrorIsRecorded() { + fun `getCredentials - api fails - error recorded`() { whenever(syncStore.token).thenReturn(TestSyncFixtures.token) whenever(syncApi.getCredentials(any(), any())).thenReturn(getAllError) @@ -148,7 +148,7 @@ internal class SyncApiClientTest { } @Test - fun whenGetBookmarksAndApiCountLimitFailsThenResultIsErrorAndErrorIsRecorded() { + fun `get - get bookmarks and api count limit fails - error recorded`() { whenever(syncStore.token).thenReturn(TestSyncFixtures.token) whenever(syncApi.getBookmarks(any(), any())).thenReturn(getCountLimitError) @@ -158,7 +158,7 @@ internal class SyncApiClientTest { } @Test - fun whenGetCredentialsAndApiCountLimitFailsThenResultIsErrorAndErrorIsRecorded() { + fun `get - credentials and api count limit fails - error recorded`() { whenever(syncStore.token).thenReturn(TestSyncFixtures.token) whenever(syncApi.getCredentials(any(), any())).thenReturn(getCountLimitError) diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/engine/SyncEngineTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/engine/SyncEngineTest.kt index 41b6187dbc31..dd2a8208d15c 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/engine/SyncEngineTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/engine/SyncEngineTest.kt @@ -81,7 +81,7 @@ internal class SyncEngineTest { } @Test - fun whenFeatureReadTriggeredAndSyncIsDisabledNoSyncOperationIsTriggered() { + fun `triggerFeatureRead - sync disabled - no sync operation triggered`() { whenever(syncStore.isSignedIn()).thenReturn(false) syncEngine.triggerSync(FEATURE_READ) verifyNoInteractions(syncApiClient) @@ -90,7 +90,7 @@ internal class SyncEngineTest { } @Test - fun whenAppOpensAndSyncIsDisabledNoSyncOperationIsTriggered() { + fun `triggerSync - app opens and sync is disabled - no sync operation triggered`() { whenever(syncStore.isSignedIn()).thenReturn(false) syncEngine.triggerSync(APP_OPEN) verifyNoInteractions(syncApiClient) @@ -99,7 +99,7 @@ internal class SyncEngineTest { } @Test - fun whenBackgroundSyncOperationTriggeredAndSyncIsDisabledNoSyncOperationIsTriggered() { + fun `triggerBackgroundSync - sync is disabled - no sync operation triggered`() { whenever(syncStore.isSignedIn()).thenReturn(false) syncEngine.triggerSync(BACKGROUND_SYNC) verifyNoInteractions(syncApiClient) @@ -108,7 +108,7 @@ internal class SyncEngineTest { } @Test - fun whenDataChangesAndSyncIsDisabledNoSyncOperationIsTriggered() { + fun `triggerSync - data changes and sync disabled - no sync operation triggered`() { whenever(syncStore.isSignedIn()).thenReturn(false) syncEngine.triggerSync(DATA_CHANGE) verifyNoInteractions(syncApiClient) @@ -117,14 +117,14 @@ internal class SyncEngineTest { } @Test - fun whenCreatingSyncAccountAndNoLocalChangesThenNothingIsSent() { + fun `triggerSync - no local changes - nothing is sent`() { syncEngine.triggerSync(ACCOUNT_CREATION) verifyNoInteractions(syncApiClient) } @Test - fun whenCreatingSyncAccountThenDataIsSentAndStateUpdatedWithSuccess() { + fun `triggerSync - state updated with success`() { givenLocalChanges() givenPatchSuccess() @@ -136,7 +136,7 @@ internal class SyncEngineTest { } @Test - fun whenSyncingDataIsDisabledThenNoSyncOperationIsTriggered() { + fun `triggerSync - syncing data disabled - no sync operation triggered`() { whenever(syncStore.isSignedIn()).thenReturn(true) whenever(syncStore.syncingDataEnabled).thenReturn(false) @@ -152,7 +152,7 @@ internal class SyncEngineTest { @Test @Ignore // https://app.asana.com/0/1204842202586359/1205158805627400/f - fun whenCreatingSyncAccountThenDataIsSentAndStateUpdatedWithError() { + fun `whenCreatingSyncAccountThenDataIsSentAndStateUpdatedWithError - state updated with error`() { givenLocalChanges() givenPatchError() @@ -164,7 +164,7 @@ internal class SyncEngineTest { } @Test - fun whenAppOpenWithoutChangesAndGetRemoteSucceedsThenStateIsUpdated() { + fun `sync - app open without changes - state updated`() { givenNoLocalChanges() givenGetSuccess() @@ -177,7 +177,7 @@ internal class SyncEngineTest { @Test @Ignore // https://app.asana.com/0/1204842202586359/1205158805627400/f - fun whenAppOpenWithoutChangesAndGetRemoteFailsThenStateIsUpdated() { + fun `whenAppOpenWithoutChangesAndGetRemoteFails - state updated`() { givenNoLocalChanges() givenGetError() @@ -188,7 +188,7 @@ internal class SyncEngineTest { } @Test - fun whenAppOpenWithChangesAndPatchRemoteSucceedsThenStateIsUpdated() { + fun `sync - app open with changes and patch remote succeeds - state updated`() { givenLocalChanges() givenPatchSuccess() @@ -199,7 +199,7 @@ internal class SyncEngineTest { } @Test - fun whenAppOpenWithChangesAndFeatureFirstSyncThenPerformGetAndPatch() { + fun `whenAppOpenWithChangesAndFeatureFirstSync - perform get and patch`() { givenFirstSyncLocalChanges() givenGetSuccess() givenPatchSuccess() @@ -214,7 +214,7 @@ internal class SyncEngineTest { @Test @Ignore // https://app.asana.com/0/1204842202586359/1205158805627400/f - fun whenAppOpenWithChangesAndPatchRemoteFailsThenStateIsUpdated() { + fun `sync - app open with changes and patch remote fails - state updated`() { givenLocalChanges() givenPatchError() @@ -225,7 +225,7 @@ internal class SyncEngineTest { } @Test - fun whenFeatureReadWithoutChangesAndGetRemoteSucceedsThenStateIsUpdated() { + fun `whenFeatureReadWithoutChangesAndGetRemoteSucceedsThenStateIsUpdated - state updated`() { givenNoLocalChanges() givenGetSuccess() @@ -238,7 +238,7 @@ internal class SyncEngineTest { @Test @Ignore // https://app.asana.com/0/1204842202586359/1205158805627400/f - fun whenFeatureReadWithoutChangesAndGetRemoteFailsThenStateIsUpdated() { + fun `whenFeatureReadWithoutChangesAndGetRemoteFails - state updated`() { givenNoLocalChanges() givenGetError() @@ -249,7 +249,7 @@ internal class SyncEngineTest { } @Test - fun whenFeatureReadWithChangesAndPatchRemoteSucceedsThenStateIsUpdated() { + fun `syncFeatureRead - state updated`() { givenLocalChanges() givenPatchSuccess() @@ -262,7 +262,7 @@ internal class SyncEngineTest { @Test @Ignore // https://app.asana.com/0/1204842202586359/1205158805627400/f - fun whenFeatureReadWithChangesAndPatchRemoteFailsThenStateIsUpdated() { + fun `sync - feature read with changes and patch remote fails - state updated`() { givenLocalChanges() givenPatchError() @@ -273,7 +273,7 @@ internal class SyncEngineTest { } @Test - fun whenDataChangeWithoutChangesAndGetRemoteSucceedsThenStateIsUpdated() { + fun `whenDataChangeWithoutChangesAndGetRemoteSucceeds - state updated`() { givenNoLocalChanges() givenGetSuccess() @@ -286,7 +286,7 @@ internal class SyncEngineTest { @Test @Ignore // https://app.asana.com/0/1204842202586359/1205158805627400/f - fun whenDataChangeWithoutChangesAndGetRemoteFailsThenStateIsUpdated() { + fun `whenDataChangeWithoutChangesAndGetRemoteFails - state updated`() { givenNoLocalChanges() givenGetError() @@ -297,7 +297,7 @@ internal class SyncEngineTest { } @Test - fun whenDataChangeWithChangesAndPatchRemoteSucceedsThenStateIsUpdated() { + fun `syncData - state updated`() { givenLocalChanges() givenPatchSuccess() @@ -308,7 +308,7 @@ internal class SyncEngineTest { } @Test - fun whenDataChangeWithChangesForFirstSyncThenStateIsUpdated() { + fun `sync - data change with changes for first sync - state updated`() { givenFirstSyncLocalChanges() givenPatchSuccess() givenGetSuccess() @@ -323,7 +323,7 @@ internal class SyncEngineTest { @Test @Ignore // https://app.asana.com/0/1204842202586359/1205158805627400/f - fun whenDataChangeWithChangesAndPatchRemoteFailsThenStateIsUpdated() { + fun `sync - data change with changes and patch remote fails - state updated`() { givenLocalChanges() givenPatchError() @@ -334,7 +334,7 @@ internal class SyncEngineTest { } @Test - fun whenBackgroundSyncCantBeScheduledThenNothingHappens() { + fun `scheduleOperation - background sync cant be scheduled - nothing happens`() { whenever(syncScheduler.scheduleOperation()).thenReturn(DISCARD) verifyNoInteractions(syncApiClient) @@ -342,7 +342,7 @@ internal class SyncEngineTest { } @Test - fun whenBackgroundSyncWithoutChangesAndGetRemoteSucceedsThenStateIsUpdated() { + fun `sync - background sync without changes - state updated`() { whenever(syncScheduler.scheduleOperation()).thenReturn(EXECUTE) givenNoLocalChanges() givenGetSuccess() @@ -356,7 +356,7 @@ internal class SyncEngineTest { @Test @Ignore // https://app.asana.com/0/1204842202586359/1205158805627400/f - fun whenBackgroundSyncWithoutChangesAndGetRemoteFailsThenStateIsUpdated() { + fun `sync - background sync without changes get remote fails - state updated`() { whenever(syncScheduler.scheduleOperation()).thenReturn(EXECUTE) givenNoLocalChanges() givenGetError() @@ -368,7 +368,7 @@ internal class SyncEngineTest { } @Test - fun whenBackgroundSyncWithChangesAndPatchRemoteSucceedsThenStateIsUpdated() { + fun `sync - background sync with changes and patch remote succeeds - state updated`() { whenever(syncScheduler.scheduleOperation()).thenReturn(EXECUTE) givenLocalChanges() givenPatchSuccess() @@ -380,7 +380,7 @@ internal class SyncEngineTest { } @Test - fun whenFirstSyncBackgroundSyncWithChangesAndPatchRemoteSucceedsThenStateIsUpdated() { + fun `triggerSync - background sync with changes and patch remote succeeds - state updated`() { whenever(syncScheduler.scheduleOperation()).thenReturn(EXECUTE) givenFirstSyncLocalChanges() givenPatchSuccess() @@ -396,7 +396,7 @@ internal class SyncEngineTest { @Test @Ignore // https://app.asana.com/0/1204842202586359/1205158805627400/f - fun whenBackgroundSyncWithChangesAndPatchRemoteFailsThenStateIsUpdated() { + fun `sync - background sync with changes and patch remote fails - state updated`() { whenever(syncScheduler.scheduleOperation()).thenReturn(EXECUTE) givenLocalChanges() givenPatchError() @@ -410,7 +410,7 @@ internal class SyncEngineTest { @Test @Ignore // https://app.asana.com/0/1204842202586359/1205158805627400/f - fun whenAccountLoginGetRemoteFailsThenStateIsUpdated() { + fun `whenAccountLoginGetRemoteFails - state updated`() { givenLocalChanges() givenGetError() @@ -421,7 +421,7 @@ internal class SyncEngineTest { } @Test - fun whenAccountLoginSucceedsThenStateIsUpdated() { + fun `sync - account login succeeds - state updated`() { givenFirstSyncLocalChanges() givenPatchSuccess() givenGetSuccess() @@ -434,14 +434,14 @@ internal class SyncEngineTest { } @Test - fun whenTriggeringSyncAndSyncAlreadyInProgressThenSyncIsDismissed() { + fun `triggerSync - in progress - dismissed`() { whenever(syncStateRepository.current()).thenReturn(SyncAttempt(state = IN_PROGRESS)) syncEngine.triggerSync(DATA_CHANGE) verifyNoInteractions(syncApiClient) } @Test - fun whenPatchNewDataFailsBecauseCountLimitThenNotifyFeature() { + fun `sync - patch new data fails because count limit - notify feature`() { givenLocalChanges() givenPatchLimitError() val persisterPluginMock = mock() @@ -453,7 +453,7 @@ internal class SyncEngineTest { } @Test - fun whenPatchNewDataFailsBecauseContentTooLargeThenNotifyFeature() { + fun `sync - patch new data fails because content too large - notify feature`() { givenLocalChanges() givenPatchContentTooLargeError() val persisterPluginMock = mock() @@ -465,7 +465,7 @@ internal class SyncEngineTest { } @Test - fun whenPatchNewDataFailsBecauseNonFeatureErrorThenDoNotNotifyFeature() { + fun `sync - patch new data fails because non-feature error - do not notify feature`() { givenLocalChanges() givenPatchError() val persisterPluginMock = mock() @@ -477,7 +477,7 @@ internal class SyncEngineTest { } @Test - fun whenSyncTriggeredDailyPixelIsSent() { + fun `syncTriggered - daily pixel sent - success`() { givenLocalChanges() givenPatchSuccess() @@ -490,7 +490,7 @@ internal class SyncEngineTest { } @Test - fun whenSyncTriggeredWithChangesAndPatchRemoteSucceedsWithTimestampConflictThenStateIsUpdatedAndPixelIsFired() { + fun `syncTriggered - state updated and pixel fired - timestamp conflict`() { givenLocalChangesWithTimestampConflict() givenPatchSuccess() @@ -504,7 +504,7 @@ internal class SyncEngineTest { } @Test - fun whenSyncTriggeredWithChangesAndPatchRemoteSucceedsWithOrphansThenStateIsUpdatedAndPixelIsFired() { + fun `sync - state updated and pixel fired`() { givenLocalChangesWithOrphansPresent() givenPatchSuccess() diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/engine/SyncSchedulerTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/engine/SyncSchedulerTest.kt index 2d02c110297e..1f352807f6ae 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/engine/SyncSchedulerTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/engine/SyncSchedulerTest.kt @@ -41,7 +41,7 @@ class SyncSchedulerTest { } @Test - fun whenFirstSyncThenSyncCanBeExecuted() { + fun `syncScheduler - first sync - execute`() { whenever(syncStateRepository.current()).thenReturn(null) val syncOperation = syncScheduler.scheduleOperation() @@ -50,7 +50,7 @@ class SyncSchedulerTest { } @Test - fun whenLastSyncFailedThenSyncIsExecuted() { + fun `syncStateRepository - last sync failed - execute sync operation`() { val lastSyncTimestamp = timestamp(Instant.now().minus(5, ChronoUnit.MINUTES)) val lastSync = SyncAttempt(timestamp = lastSyncTimestamp, state = FAIL) @@ -62,7 +62,7 @@ class SyncSchedulerTest { } @Test - fun whenLastSyncInProgressThenSyncIsDiscarded() { + fun `syncScheduler - last sync in progress - discard`() { val lastSyncTimestamp = timestamp(Instant.now().minus(5, ChronoUnit.MINUTES)) val lastSync = SyncAttempt(timestamp = lastSyncTimestamp, state = IN_PROGRESS) @@ -74,7 +74,7 @@ class SyncSchedulerTest { } @Test - fun whenLastSyncWasBeforeDebouncePeriodThenSyncIsDiscarded() { + fun `syncScheduler - last sync before debounce period - discard`() { val lastSyncTimestamp = timestamp(Instant.now().minus(5, ChronoUnit.MINUTES)) val lastSync = SyncAttempt(timestamp = lastSyncTimestamp, state = SUCCESS) @@ -86,7 +86,7 @@ class SyncSchedulerTest { } @Test - fun whenLastSyncWasAfterDebouncePeriodThenSyncIsDiscarded() { + fun `syncScheduler - last sync after debounce period - sync is discarded`() { val lastSyncTimestamp = timestamp(Instant.now().minus(30, ChronoUnit.MINUTES)) val lastSync = SyncAttempt(timestamp = lastSyncTimestamp, state = SUCCESS) diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/engine/SyncStateObserverTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/engine/SyncStateObserverTest.kt index d4483bd64117..901fdf1bc8ff 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/engine/SyncStateObserverTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/engine/SyncStateObserverTest.kt @@ -26,7 +26,7 @@ class SyncStateObserverTest { ) @Test - fun whenSignedOutThenFirstEventDropsAndDoesNotNotifySyncEngine() = runTest { + fun `onCreate - signed out - does not notify sync engine`() = runTest { val isSignedInFlow = MutableStateFlow(false) whenever(syncStore.isSignedInFlow()).thenReturn(isSignedInFlow) testee.onCreate(mock()) @@ -34,7 +34,7 @@ class SyncStateObserverTest { } @Test - fun whenSignedInTheDoesNotNotifySyncEngine() = runTest { + fun `onCreate - signed in - does not notify sync engine`() = runTest { val isSignedInFlow = MutableStateFlow(true) whenever(syncStore.isSignedInFlow()).thenReturn(isSignedInFlow) testee.onCreate(mock()) @@ -42,7 +42,7 @@ class SyncStateObserverTest { } @Test - fun whenSignedInAndSignedOutEventReceivedTheNotifySyncEngine() = runTest { + fun `isSignedIn - signed in and out event received - notify sync engine`() = runTest { val isSignedInFlow = MutableStateFlow(true) whenever(syncStore.isSignedInFlow()).thenReturn(isSignedInFlow) testee.onCreate(mock()) diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/engine/SyncStateRepositoryTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/engine/SyncStateRepositoryTest.kt index 4b8771155688..2f4229ad16e7 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/engine/SyncStateRepositoryTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/engine/SyncStateRepositoryTest.kt @@ -49,13 +49,13 @@ class SyncStateRepositoryTest { } @Test - fun whenSyncDaoIsEmptyCurrentReturnsNull() { + fun `current - sync dao empty - returns null`() { val currentSync = repository.current() assertTrue(currentSync == null) } @Test - fun whenSyncInProgressThenCurrentReturnsAttempt() { + fun `current - in progress - attempt`() { val sync = SyncAttempt(state = SyncAttemptState.IN_PROGRESS) repository.store(sync) @@ -64,7 +64,7 @@ class SyncStateRepositoryTest { } @Test - fun whenSyncStateIsUpdatedThenDaoIsUpdated() { + fun `updateSyncState - dao updated`() { val syncInProgress = SyncAttempt(state = SyncAttemptState.IN_PROGRESS) repository.store(syncInProgress) diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/error/SyncApiErrorRecorderTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/error/SyncApiErrorRecorderTest.kt index d734f94f4871..d77960646f9b 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/error/SyncApiErrorRecorderTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/error/SyncApiErrorRecorderTest.kt @@ -36,7 +36,7 @@ internal class SyncApiErrorRecorderTest { private val apiErrorReporter = RealSyncApiErrorRecorder(syncPixels, syncApiErrorRepository) @Test - fun wheneverCountLimitErrorReportedThenRepositoryAddsError() { + fun `record - count limit error reported - repository adds error`() { val feature = SyncableType.BOOKMARKS val error = Error(API_CODE.COUNT_LIMIT.code, "") @@ -46,7 +46,7 @@ internal class SyncApiErrorRecorderTest { } @Test - fun wheneverContentTooLargeErrorReportedThenRepositoryAddsError() { + fun `record - content too large error reported - repository adds error`() { val feature = SyncableType.BOOKMARKS val error = Error(API_CODE.CONTENT_TOO_LARGE.code, "") @@ -56,7 +56,7 @@ internal class SyncApiErrorRecorderTest { } @Test - fun wheneverValidationErrorReportedThenRepositoryAddsError() { + fun `record - whenever validation error reported - repository adds error`() { val feature = SyncableType.BOOKMARKS val error = Error(API_CODE.VALIDATION_ERROR.code, "") @@ -66,7 +66,7 @@ internal class SyncApiErrorRecorderTest { } @Test - fun wheneverFirstTooManyRequestsErrorReportedThenRepositoryAddsError() { + fun `record - first too many requests error reported - adds error to repository`() { val feature = SyncableType.BOOKMARKS val error = Error(API_CODE.TOO_MANY_REQUESTS_1.code, "") @@ -76,7 +76,7 @@ internal class SyncApiErrorRecorderTest { } @Test - fun wheneverSecondTooManyRequestsErrorReportedThenRepositoryAddsError() { + fun `record - second too many requests error reported - adds error to repository`() { val feature = SyncableType.BOOKMARKS val error = Error(API_CODE.TOO_MANY_REQUESTS_2.code, "") diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/error/SyncApiErrorRepositoryTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/error/SyncApiErrorRepositoryTest.kt index b6f3a1ef83c6..36168072b805 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/error/SyncApiErrorRepositoryTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/error/SyncApiErrorRepositoryTest.kt @@ -54,7 +54,7 @@ class SyncApiErrorRepositoryTest { } @Test - fun whenApiErrorAddedAndNotPresentThenNewEntryAdded() { + fun `addError - api error added and not present - new entry added`() { val feature = SyncableType.BOOKMARKS val errorType = SyncApiErrorType.OBJECT_LIMIT_EXCEEDED val date = DatabaseDateFormatter.getUtcIsoLocalDate() @@ -68,7 +68,7 @@ class SyncApiErrorRepositoryTest { } @Test - fun whenApiErrorAddedAndPresentThenCountUpdated() { + fun `addError - api error added and present - count updated`() { val feature = SyncableType.BOOKMARKS val errorType = SyncApiErrorType.OBJECT_LIMIT_EXCEEDED val date = DatabaseDateFormatter.getUtcIsoLocalDate() @@ -83,7 +83,7 @@ class SyncApiErrorRepositoryTest { } @Test - fun whenNoErrorsStoredThenGettingErrorsReturnsEmpty() { + fun `getErrors - no errors stored - empty`() { val date = DatabaseDateFormatter.getUtcIsoLocalDate() val errors = testee.getErrorsByDate(date) @@ -92,7 +92,7 @@ class SyncApiErrorRepositoryTest { } @Test - fun whenNoErrorsStoredFromYesterdayThenGettingErrorsFromYesterdayReturnsEmpty() { + fun `getErrorsByDate - no errors stored from yesterday - returns empty`() { val feature = SyncableType.BOOKMARKS val errorType = SyncApiErrorType.OBJECT_LIMIT_EXCEEDED @@ -106,7 +106,7 @@ class SyncApiErrorRepositoryTest { } @Test - fun whenErrorsStoredThenGettingErrorsReturnsData() { + fun `addError - getting errors returns data`() { val feature = SyncableType.BOOKMARKS val errorType = SyncApiErrorType.OBJECT_LIMIT_EXCEEDED diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/error/SyncOperationErrorRecorderTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/error/SyncOperationErrorRecorderTest.kt index b9f8782dcd09..8c36854363d1 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/error/SyncOperationErrorRecorderTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/error/SyncOperationErrorRecorderTest.kt @@ -30,7 +30,7 @@ internal class SyncOperationErrorRecorderTest { private val recorder = RealSyncOperationErrorRecorder(syncPixels, repository) @Test - fun wheneverEncryptErrorReportedThenRepositoryAddsError() { + fun `record - repository adds error`() { val error = SyncOperationErrorType.DATA_ENCRYPT recorder.record(error) diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/error/SyncOperationErrorRepositoryTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/error/SyncOperationErrorRepositoryTest.kt index 7fac160f7f1a..3d1ed8148908 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/error/SyncOperationErrorRepositoryTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/error/SyncOperationErrorRepositoryTest.kt @@ -62,7 +62,7 @@ class SyncOperationErrorRepositoryTest { } @Test - fun whenOperationErrorAddedAndNotPresentThenNewEntryAdded() { + fun `addError - not present - new entry added`() { val errorType = SyncOperationErrorType.DATA_ENCRYPT val date = DatabaseDateFormatter.getUtcIsoLocalDate() @@ -75,7 +75,7 @@ class SyncOperationErrorRepositoryTest { } @Test - fun whenFeatureErrorAddedAndNotPresentThenNewEntryAdded() { + fun `addError - feature error added and not present - new entry added`() { val feature = SyncableType.BOOKMARKS val errorType = SyncOperationErrorType.DATA_PERSISTER_ERROR val date = DatabaseDateFormatter.getUtcIsoLocalDate() @@ -89,7 +89,7 @@ class SyncOperationErrorRepositoryTest { } @Test - fun whenOperationErrorAddedAndPresentThenCountUpdated() { + fun `addError - present - count updated`() { val errorType = SyncOperationErrorType.DATA_ENCRYPT val date = DatabaseDateFormatter.getUtcIsoLocalDate() @@ -103,7 +103,7 @@ class SyncOperationErrorRepositoryTest { } @Test - fun whenNoErrorsStoredThenGettingErrorsReturnsEmpty() { + fun `getErrors - no errors stored - empty`() { val date = DatabaseDateFormatter.getUtcIsoLocalDate() val errors = testee.getErrorsByDate(date) @@ -112,7 +112,7 @@ class SyncOperationErrorRepositoryTest { } @Test - fun whenNoErrorsStoredFromYesterdayThenGettingErrorsFromYesterdayReturnsEmpty() { + fun `getErrorsByDate - no errors stored from yesterday - returns empty`() { val errorType = SyncOperationErrorType.DATA_ENCRYPT val yesterday = LocalDate.now().minusDays(1).format(DateTimeFormatter.ISO_LOCAL_DATE) @@ -124,7 +124,7 @@ class SyncOperationErrorRepositoryTest { } @Test - fun whenErrorsStoredThenGettingErrorsReturnsData() { + fun `addError - getting errors returns data - is not empty and has correct error name and count`() { val errorType = SyncOperationErrorType.DATA_ENCRYPT val today = DatabaseDateFormatter.getUtcIsoLocalDate() @@ -139,7 +139,7 @@ class SyncOperationErrorRepositoryTest { } @Test - fun whenFeatureErrorsStoredThenGettingErrorsReturnsData() { + fun `getErrorsByDate - feature errors stored - returns data`() { val feature = SyncableType.BOOKMARKS val errorType = SyncOperationErrorType.DATA_PERSISTER_ERROR val today = DatabaseDateFormatter.getUtcIsoLocalDate() @@ -156,7 +156,7 @@ class SyncOperationErrorRepositoryTest { } @Test - fun whenProviderErrorsStoredThenGettingErrorsReturnsData() { + fun `addError - getting errors returns data - has stored provider errors`() { val feature = SyncableType.BOOKMARKS val errorType = SyncOperationErrorType.DATA_PROVIDER_ERROR val today = DatabaseDateFormatter.getUtcIsoLocalDate() @@ -173,7 +173,7 @@ class SyncOperationErrorRepositoryTest { } @Test - fun whenTimestampErrorsStoredThenGettingErrorsReturnsData() { + fun `whenTimestampErrorsStoredThenGettingErrorsReturnsData - getting errors returns data`() { val feature = SyncableType.BOOKMARKS val errorType = SyncOperationErrorType.TIMESTAMP_CONFLICT val today = DatabaseDateFormatter.getUtcIsoLocalDate() @@ -190,7 +190,7 @@ class SyncOperationErrorRepositoryTest { } @Test - fun whenOrphansErrorsStoredThenGettingErrorsReturnsData() { + fun `getErrorsByDate - orphans errors stored - returns data`() { val feature = SyncableType.BOOKMARKS val errorType = SyncOperationErrorType.ORPHANS_PRESENT val today = DatabaseDateFormatter.getUtcIsoLocalDate() diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/favicons/FaviconsFetchingPromptTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/favicons/FaviconsFetchingPromptTest.kt index 22612a900954..c6b2bad10bff 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/favicons/FaviconsFetchingPromptTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/favicons/FaviconsFetchingPromptTest.kt @@ -44,7 +44,7 @@ class FaviconsFetchingPromptTest { } @Test - fun whenPromptAlreadyShownThenShouldNotShowAgain() { + fun `shouldShow - prompt already shown - should not show again`() { whenever(faviconsFetchingStore.promptShown).thenReturn(true) val shouldShow = faviconsFetchingPrompt.shouldShow() @@ -53,7 +53,7 @@ class FaviconsFetchingPromptTest { } @Test - fun whenFaviconsFetchingEnabledThenShouldNotShow() { + fun `shouldShow - favicons fetching enabled - should not show`() { whenever(faviconsFetchingStore.promptShown).thenReturn(false) whenever(faviconsFetchingStore.isFaviconsFetchingEnabled).thenReturn(true) @@ -63,7 +63,7 @@ class FaviconsFetchingPromptTest { } @Test - fun whenSyncNotEnabledThenShouldNotShow() { + fun `shouldShow - sync not enabled - should not show`() { whenever(faviconsFetchingStore.promptShown).thenReturn(false) whenever(faviconsFetchingStore.isFaviconsFetchingEnabled).thenReturn(false) whenever(syncAccountRepository.isSignedIn()).thenReturn(false) @@ -74,7 +74,7 @@ class FaviconsFetchingPromptTest { } @Test - fun whenSyncOnlyHasOnceDeviceConnectedThenShouldNotShow() { + fun `shouldShow - sync only has once device connected - should not show`() { whenever(faviconsFetchingStore.promptShown).thenReturn(false) whenever(faviconsFetchingStore.isFaviconsFetchingEnabled).thenReturn(false) whenever(syncAccountRepository.isSignedIn()).thenReturn(true) @@ -87,7 +87,7 @@ class FaviconsFetchingPromptTest { } @Test - fun whenSyncHasMoreThenOnceDevicesConnectedThenShouldShow() { + fun `getFaviconsFetchingPrompt - sync has more then once devices connected - should show`() { whenever(faviconsFetchingStore.promptShown).thenReturn(false) whenever(faviconsFetchingStore.isFaviconsFetchingEnabled).thenReturn(false) whenever(syncAccountRepository.isSignedIn()).thenReturn(true) @@ -100,7 +100,7 @@ class FaviconsFetchingPromptTest { } @Test - fun whenPromptNotShownThenShouldShow() { + fun `shouldShow - prompt not shown - false`() { whenever(faviconsFetchingStore.promptShown).thenReturn(false) val shouldShow = faviconsFetchingPrompt.shouldShow() diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/pixels/SyncPixelsTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/pixels/SyncPixelsTest.kt index 46e642156903..585eaf20649a 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/pixels/SyncPixelsTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/pixels/SyncPixelsTest.kt @@ -55,7 +55,7 @@ class SyncPixelsTest { } @Test - fun whenDailyPixelCalledThenPixelFired() { + fun `fireDailySuccessRatePixel - pixel fired`() { val dailyStats = givenSomeDailyStats() testee.fireDailySuccessRatePixel() @@ -69,7 +69,7 @@ class SyncPixelsTest { } @Test - fun whenDailyPixelCalledTwiceThenPixelFiredOnce() { + fun `fireDailySuccessRatePixel - pixel fired once`() { val dailyStats = givenSomeDailyStats() testee.fireDailySuccessRatePixel() @@ -84,21 +84,21 @@ class SyncPixelsTest { } @Test - fun whenLoginPixelCalledThenPixelFired() { + fun `fireLoginPixel - pixel fired`() { testee.fireLoginPixel() verify(pixel).fire(SyncPixelName.SYNC_LOGIN) } @Test - fun whenSignupDirectPixelCalledThenPixelFired() { + fun `fireSignupDirectPixel - pixel fired`() { testee.fireSignupDirectPixel() verify(pixel).fire(SyncPixelName.SYNC_SIGNUP_DIRECT) } @Test - fun whenSignupConnectPixelCalledThenPixelFired() { + fun `fireSignupConnectPixel - pixel fired`() { testee.fireSignupConnectPixel() verify(pixel).fire(SyncPixelName.SYNC_SIGNUP_CONNECT) diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/stats/SyncStatsRepositoryTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/stats/SyncStatsRepositoryTest.kt index f280cf7cf581..3de74b4ad386 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/stats/SyncStatsRepositoryTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/stats/SyncStatsRepositoryTest.kt @@ -50,7 +50,7 @@ class SyncStatsRepositoryTest { } @Test - fun whenNoAttemptsThenDailyStatsIsEmpty() { + fun `getYesterdayDailyStats - no attempts - daily stats empty`() { whenever(syncStateRepository.attempts()).thenReturn(emptyList()) whenever(syncApiErrorRepository.getErrorsByDate(any())).thenReturn(emptyList()) whenever(syncOperationErrorRepository.getErrorsByDate(any())).thenReturn(emptyList()) @@ -63,7 +63,7 @@ class SyncStatsRepositoryTest { } @Test - fun whenOnlyPastAttemptsAndErrorsThenDailyStatsHasCorrectData() { + fun `getYesterdayDailyStats - only past attempts and errors - daily stats has correct data`() { val lastSyncTimestamp = timestamp(Instant.now().minus(5, ChronoUnit.DAYS)) val lastSync = SyncAttempt(timestamp = lastSyncTimestamp, state = SUCCESS) whenever(syncStateRepository.attempts()).thenReturn(listOf(lastSync)) @@ -78,7 +78,7 @@ class SyncStatsRepositoryTest { } @Test - fun whenOnlyYesterdayAttemptsThenDailyStatsHasCorrectData() { + fun `getYesterdayDailyStats - only yesterday attempts - daily stats has correct data`() { val lastSyncTimestamp = timestamp(Instant.now().minus(1, ChronoUnit.DAYS)) val lastSync = SyncAttempt(timestamp = lastSyncTimestamp, state = SUCCESS) whenever(syncStateRepository.attempts()).thenReturn(listOf(lastSync)) @@ -99,7 +99,7 @@ class SyncStatsRepositoryTest { } @Test - fun whenOnlyTodayAttemptsThenDailyStatsHasCorrectData() { + fun `getYesterdayDailyStats - only today attempts - daily stats has correct data`() { val lastSyncTimestamp = timestamp(Instant.now().minus(5, ChronoUnit.MINUTES)) val lastSync = SyncAttempt(timestamp = lastSyncTimestamp, state = SUCCESS) whenever(syncStateRepository.attempts()).thenReturn(listOf(lastSync)) @@ -115,7 +115,7 @@ class SyncStatsRepositoryTest { } @Test - fun whenOnlySuccessfulAttemptsThenDailyStatsHasCorrectData() { + fun `getYesterdayDailyStats - only successful attempts - daily stats has correct data`() { val lastSyncTimestamp = timestamp(Instant.now().minus(1, ChronoUnit.DAYS)) val lastSync = SyncAttempt(timestamp = lastSyncTimestamp, state = SUCCESS) whenever(syncStateRepository.attempts()).thenReturn(listOf(lastSync)) @@ -136,7 +136,7 @@ class SyncStatsRepositoryTest { } @Test - fun whenOnlyFailedAttemptsThenDailyStatsHasCorrectData() { + fun `getYesterdayDailyStats - only failed attempts - daily stats has correct data`() { val lastSyncTimestamp = timestamp(Instant.now().minus(1, ChronoUnit.DAYS)) val lastSync = SyncAttempt(timestamp = lastSyncTimestamp, state = FAIL) @@ -152,7 +152,7 @@ class SyncStatsRepositoryTest { } @Test - fun whenFewAttemptsThenDailyStatsHasCorrectData() { + fun `getYesterdayDailyStats - few attempts - daily stats has correct data`() { val lastSyncTimestamp = timestamp(Instant.now().minus(1, ChronoUnit.DAYS)) val first = SyncAttempt(timestamp = lastSyncTimestamp, state = FAIL) val second = SyncAttempt(timestamp = lastSyncTimestamp, state = SUCCESS) diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/triggers/AppLifecycleSyncObserverTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/triggers/AppLifecycleSyncObserverTest.kt index 565de2bf741f..ccb0d3e706d5 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/triggers/AppLifecycleSyncObserverTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/triggers/AppLifecycleSyncObserverTest.kt @@ -49,7 +49,7 @@ class AppLifecycleSyncObserverTest { ) @Test - fun whenAppStartedAndSyncDisabledThenNothingHappens() = runTest { + fun `onStart - sync disabled - nothing happens`() = runTest { whenever(mockDeviceSyncState.isUserSignedInOnDevice()).thenReturn(false) testee.onStart(mockLifecycleOwner) @@ -58,7 +58,7 @@ class AppLifecycleSyncObserverTest { } @Test - fun whenAppStartedAndSyncEnabledThenSyncIsTriggered() = runTest { + fun `onStart - sync enabled - trigger sync`() = runTest { whenever(mockDeviceSyncState.isUserSignedInOnDevice()).thenReturn(true) testee.onStart(mockLifecycleOwner) diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/triggers/BackgroundSyncWorkerSchedulerTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/triggers/BackgroundSyncWorkerSchedulerTest.kt index 09eb84997cbf..d4aa86dd5475 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/triggers/BackgroundSyncWorkerSchedulerTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/triggers/BackgroundSyncWorkerSchedulerTest.kt @@ -49,7 +49,7 @@ class BackgroundSyncWorkerSchedulerTest { } @Test - fun whenOnCreateAndSyncEnabledThenWorkerEnqueued() { + fun `onCreate - sync enabled - worker enqueued`() { whenever(deviceSyncState.isUserSignedInOnDevice()).thenReturn(true) syncBackgroundWorkerScheduler.onCreate(mockOwner) @@ -57,7 +57,7 @@ class BackgroundSyncWorkerSchedulerTest { } @Test - fun whenOnCreateAndSyncDisabledThenWorkerIsNotEnqueued() { + fun `onCreate - sync disabled - worker not enqueued`() { whenever(deviceSyncState.isUserSignedInOnDevice()).thenReturn(false) syncBackgroundWorkerScheduler.onCreate(mockOwner) diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/triggers/BackgroundSyncWorkerTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/triggers/BackgroundSyncWorkerTest.kt index 148c768bbfe5..4c5815c1b019 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/triggers/BackgroundSyncWorkerTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/triggers/BackgroundSyncWorkerTest.kt @@ -49,7 +49,7 @@ internal class BackgroundSyncWorkerTest { } @Test - fun whenDoWorkTriggeredAndSyncEnabledThenSyncTriggeredReturnSuccess() = + fun `doWork - sync enabled - triggered return success`() = runTest { val worker = TestListenableWorkerBuilder(context = context).build() worker.syncEngine = mockSyncEngine @@ -65,7 +65,7 @@ internal class BackgroundSyncWorkerTest { } @Test - fun whenDoWorkTriggeredAndSyncDisabledThenSyncNotTriggeredReturnSuccess() = + fun `doWork - sync disabled - return success`() = runTest { val worker = TestListenableWorkerBuilder(context = context).build() worker.syncEngine = mockSyncEngine diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/EnterCodeViewModelTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/EnterCodeViewModelTest.kt index 4c1434a83d6e..9aec10694dc4 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/EnterCodeViewModelTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/EnterCodeViewModelTest.kt @@ -60,7 +60,7 @@ internal class EnterCodeViewModelTest { ) @Test - fun whenUIStartsThenViewStateIsIdle() = runTest { + fun `viewState - ui starts - idle`() = runTest { testee.viewState().test { val item = awaitItem() assertTrue(item.authState is Idle) @@ -69,7 +69,7 @@ internal class EnterCodeViewModelTest { } @Test - fun whenUserClicksOnPasteCodeThenClipboardIsPasted() = runTest { + fun `onPasteCodeClicked - clipboard pasted`() = runTest { whenever(clipboard.pasteFromClipboard()).thenReturn(jsonRecoveryKeyEncoded) testee.onPasteCodeClicked() @@ -78,7 +78,7 @@ internal class EnterCodeViewModelTest { } @Test - fun whenUserClicksOnPasteCodeWithRecoveryCodeThenProcessCode() = runTest { + fun `onPasteCodeClicked - process code with recovery code - login success`() = runTest { whenever(clipboard.pasteFromClipboard()).thenReturn(jsonRecoveryKeyEncoded) whenever(syncAccountRepository.processCode(jsonRecoveryKeyEncoded)).thenReturn(Success(true)) @@ -92,7 +92,7 @@ internal class EnterCodeViewModelTest { } @Test - fun whenUserClicksOnPasteCodeWithConnectCodeThenProcessCode() = runTest { + fun `onPasteCodeClicked - process code - login success`() = runTest { whenever(clipboard.pasteFromClipboard()).thenReturn(jsonConnectKeyEncoded) whenever(syncAccountRepository.processCode(jsonConnectKeyEncoded)).thenReturn(Success(true)) @@ -106,7 +106,7 @@ internal class EnterCodeViewModelTest { } @Test - fun whenPastedInvalidCodeThenAuthStateError() = runTest { + fun `onPasteCodeClicked - view state error`() = runTest { whenever(clipboard.pasteFromClipboard()).thenReturn("invalid code") whenever(syncAccountRepository.processCode("invalid code")).thenReturn(Error(code = INVALID_CODE.code)) @@ -120,7 +120,7 @@ internal class EnterCodeViewModelTest { } @Test - fun whenProcessCodeButUserSignedInThenShowError() = runTest { + fun `onPasteCodeClicked - user signed in - show error`() = runTest { whenever(clipboard.pasteFromClipboard()).thenReturn(jsonRecoveryKeyEncoded) whenever(syncAccountRepository.processCode(jsonRecoveryKeyEncoded)).thenReturn(Error(code = ALREADY_SIGNED_IN.code)) @@ -134,7 +134,7 @@ internal class EnterCodeViewModelTest { } @Test - fun whenProcessCodeAndLoginFailsThenShowError() = runTest { + fun `onPasteCodeClicked - process code and login fails - show error`() = runTest { whenever(clipboard.pasteFromClipboard()).thenReturn(jsonRecoveryKeyEncoded) whenever(syncAccountRepository.processCode(jsonRecoveryKeyEncoded)).thenReturn(Error(code = LOGIN_FAILED.code)) @@ -148,7 +148,7 @@ internal class EnterCodeViewModelTest { } @Test - fun whenProcessCodeAndConnectFailsThenShowError() = runTest { + fun `onPasteCodeClicked - process code and connect fails - show error`() = runTest { whenever(clipboard.pasteFromClipboard()).thenReturn(jsonConnectKeyEncoded) whenever(syncAccountRepository.processCode(jsonConnectKeyEncoded)).thenReturn(Error(code = CONNECT_FAILED.code)) @@ -162,7 +162,7 @@ internal class EnterCodeViewModelTest { } @Test - fun whenProcessCodeAndCreateAccountFailsThenShowError() = runTest { + fun `onPasteCodeClicked - process code and create account fails - show error`() = runTest { whenever(clipboard.pasteFromClipboard()).thenReturn(jsonRecoveryKeyEncoded) whenever(syncAccountRepository.processCode(jsonRecoveryKeyEncoded)).thenReturn(Error(code = CREATE_ACCOUNT_FAILED.code)) @@ -176,7 +176,7 @@ internal class EnterCodeViewModelTest { } @Test - fun whenProcessCodeAndGenericErrorThenDoNothing() = runTest { + fun `onPasteCodeClicked - process code and generic error - do nothing`() = runTest { whenever(clipboard.pasteFromClipboard()).thenReturn(jsonRecoveryKeyEncoded) whenever(syncAccountRepository.processCode(jsonRecoveryKeyEncoded)).thenReturn(Error(code = GENERIC_ERROR.code)) diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/SyncActivityViewModelTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/SyncActivityViewModelTest.kt index 583870099bfe..c6ef8243b147 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/SyncActivityViewModelTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/SyncActivityViewModelTest.kt @@ -103,7 +103,7 @@ class SyncActivityViewModelTest { } @Test - fun whenUserSignedInThenDeviceSyncViewStateIsEnabled() = runTest { + fun `viewState - user signed in - enabled`() = runTest { givenAuthenticatedUser() testee.viewState().test { @@ -114,7 +114,7 @@ class SyncActivityViewModelTest { } @Test - fun whenUserSignedInThenShowAccount() = runTest { + fun `whenUserSignedIn - view state - show account`() = runTest { givenAuthenticatedUser() testee.viewState().test { @@ -127,7 +127,7 @@ class SyncActivityViewModelTest { } @Test - fun whenUserSignedInThenLoginQRCodeIsNotNull() = runTest { + fun `viewState - user signed in - login QR code is not null`() = runTest { givenAuthenticatedUser() testee.viewState().test { @@ -140,7 +140,7 @@ class SyncActivityViewModelTest { } @Test - fun whenUserHasMultipleConnectedDevicesThenShowDevices() = runTest { + fun `getConnectedDevices - view state updated`() = runTest { givenAuthenticatedUser() val connectedDevices = listOf(connectedDevice, connectedDevice) @@ -154,7 +154,7 @@ class SyncActivityViewModelTest { } @Test - fun whenSyncWithAnotherDeviceThenEmitCommandSyncWithAnotherDevice() = runTest { + fun `onSyncWithAnotherDevice - emit command sync with another device`() = runTest { givenUserHasDeviceAuthentication(true) testee.onSyncWithAnotherDevice() @@ -165,7 +165,7 @@ class SyncActivityViewModelTest { } @Test - fun whenSyncWithAnotherDeviceWithoutDeviceAuthenticationThenEmitCommandRequestSetupAuthentication() = runTest { + fun `onSyncWithAnotherDevice - without device authentication - emit command request setup authentication`() = runTest { givenUserHasDeviceAuthentication(false) testee.onSyncWithAnotherDevice() @@ -176,7 +176,7 @@ class SyncActivityViewModelTest { } @Test - fun whenScanAnotherDeviceQRCodeThenEmitCommandAddAnotherDevice() = runTest { + fun `onAddAnotherDevice - emit command add another device`() = runTest { givenUserHasDeviceAuthentication(true) testee.onAddAnotherDevice() @@ -187,7 +187,7 @@ class SyncActivityViewModelTest { } @Test - fun whenScanAnotherDeviceQRCodeWithoutDeviceAuthenticationThenEmitCommandRequestSetupAuthentication() = runTest { + fun `onAddAnotherDevice - no device authentication - emit command request setup authentication`() = runTest { givenUserHasDeviceAuthentication(false) testee.onAddAnotherDevice() @@ -198,7 +198,7 @@ class SyncActivityViewModelTest { } @Test - fun whenSyncThisDeviceThenLaunchCreateAccountFlow() = runTest { + fun `onSyncThisDevice - launch create account flow`() = runTest { givenUserHasDeviceAuthentication(true) testee.commands().test { testee.onSyncThisDevice() @@ -208,7 +208,7 @@ class SyncActivityViewModelTest { } @Test - fun whenSyncThisDeviceWithoutDeviceAuthenticationThenEmitCommandRequestSetupAuthentication() = runTest { + fun `onSyncThisDevice - no device authentication - emit command request setup authentication`() = runTest { givenUserHasDeviceAuthentication(false) testee.commands().test { testee.onSyncThisDevice() @@ -218,7 +218,7 @@ class SyncActivityViewModelTest { } @Test - fun whenRecoverDataThenRecoverDataCommandSent() = runTest { + fun `onRecoverYourSyncedData - commands sent - recover data command`() = runTest { givenUserHasDeviceAuthentication(true) testee.onRecoverYourSyncedData() @@ -229,7 +229,7 @@ class SyncActivityViewModelTest { } @Test - fun whenRecoverDataWithoutDeviceAuthenticationThenEmitCommandRequestSetupAuthentication() = runTest { + fun `onRecoverYourSyncedData - emit command request setup authentication`() = runTest { givenUserHasDeviceAuthentication(false) testee.onRecoverYourSyncedData() @@ -240,7 +240,7 @@ class SyncActivityViewModelTest { } @Test - fun whenTurnOffClickedThenAskTurnOffCommandShown() = runTest { + fun `onTurnOffClicked - ask turn off command shown`() = runTest { givenAuthenticatedUser() testee.onTurnOffClicked() @@ -252,7 +252,7 @@ class SyncActivityViewModelTest { } @Test - fun whenTurnOffSyncConfirmedThenLogoutLocalDevice() = runTest { + fun `onTurnOffSyncConfirmed - logout local device`() = runTest { whenever(syncAccountRepository.getThisConnectedDevice()).thenReturn(connectedDevice) whenever(syncAccountRepository.logout(deviceId)).thenReturn(Result.Success(true)) @@ -262,7 +262,7 @@ class SyncActivityViewModelTest { } @Test - fun whenLogoutSuccessThenUpdateViewState() = runTest { + fun `logout - view state updated`() = runTest { givenAuthenticatedUser() whenever(syncAccountRepository.logout(deviceId)).thenReturn(Result.Success(true)) @@ -278,7 +278,7 @@ class SyncActivityViewModelTest { } @Test - fun whenLogoutErrorThenUpdateViewState() = runTest { + fun `onTurnOffSyncConfirmed - view state updated`() = runTest { givenAuthenticatedUser() whenever(syncAccountRepository.logout(deviceId)).thenReturn(Result.Error(reason = "error")) @@ -293,7 +293,7 @@ class SyncActivityViewModelTest { } @Test - fun whenTurnOffSyncCancelledThenDeviceSyncViewStateIsEnabled() = runTest { + fun `onTurnOffSyncCancelled - device sync view state is enabled`() = runTest { givenAuthenticatedUser() testee.viewState().test { @@ -305,7 +305,7 @@ class SyncActivityViewModelTest { } @Test - fun whenDeleteAccountClickedThenAskDeleteAccount() = runTest { + fun `onDeleteAccountClicked - ask delete account`() = runTest { testee.onDeleteAccountClicked() testee.commands().test { @@ -315,7 +315,7 @@ class SyncActivityViewModelTest { } @Test - fun whenDeleteAccountSuccessThenUpdateViewState() = runTest { + fun `onDeleteAccountSuccess - view state updated`() = runTest { givenAuthenticatedUser() whenever(syncAccountRepository.deleteAccount()).thenReturn(Result.Success(true)) @@ -331,7 +331,7 @@ class SyncActivityViewModelTest { } @Test - fun whenDeleteAccountErrorThenUpdateViewState() = runTest { + fun `onDeleteAccountError - update view state`() = runTest { givenAuthenticatedUser() whenever(syncAccountRepository.deleteAccount()).thenReturn(Result.Error(reason = "error")) @@ -346,7 +346,7 @@ class SyncActivityViewModelTest { } @Test - fun whenDeleteAccountConfirmedThenDeleteAccount() = runTest { + fun `onDeleteAccountConfirmed - delete account confirmed - delete account`() = runTest { whenever(syncAccountRepository.getThisConnectedDevice()).thenReturn(connectedDevice) whenever(syncAccountRepository.logout(deviceId)).thenReturn(Result.Success(true)) @@ -356,7 +356,7 @@ class SyncActivityViewModelTest { } @Test - fun whenDeleteAccountCancelledThenDeviceSyncViewStateIsEnabled() = runTest { + fun `onDeleteAccountCancelled - device sync view state is enabled`() = runTest { givenAuthenticatedUser() testee.viewState().test { @@ -368,7 +368,7 @@ class SyncActivityViewModelTest { } @Test - fun whenOnRemoveDeviceClickedThenAskRemoveDevice() = runTest { + fun `onRemoveDeviceClicked - ask remove device`() = runTest { testee.onRemoveDeviceClicked(connectedDevice) testee.commands().test { @@ -378,7 +378,7 @@ class SyncActivityViewModelTest { } @Test - fun whenOnRemoveDeviceConfirmedThenRemoveDevice() = runTest { + fun `onRemoveDeviceConfirmed - remove device`() = runTest { givenAuthenticatedUser() whenever(syncAccountRepository.logout(deviceId)).thenReturn(Result.Success(true)) @@ -389,7 +389,7 @@ class SyncActivityViewModelTest { } @Test - fun whenOnRemoveDeviceSucceedsThenFetchRemoteDevices() = runTest { + fun `onRemoveDevice - fetch remote devices`() = runTest { givenAuthenticatedUser() whenever(syncAccountRepository.logout(deviceId)).thenReturn(Result.Success(true)) @@ -400,7 +400,7 @@ class SyncActivityViewModelTest { } @Test - fun whenOnRemoveDeviceSucceedsThenReturnUpdateDevices() = runTest { + fun `onRemoveDevice - viewState updated - return update devices`() = runTest { givenAuthenticatedUser() whenever(syncAccountRepository.logout(deviceId)).thenReturn(Result.Success(true)) @@ -417,7 +417,7 @@ class SyncActivityViewModelTest { } @Test - fun whenOnRemoveDeviceFailsThenRestorePreviousList() = runTest { + fun `onRemoveDevice - restore previous list - fails`() = runTest { givenAuthenticatedUser() whenever(syncAccountRepository.logout(deviceId)).thenReturn(Result.Error(reason = "error")) @@ -431,7 +431,7 @@ class SyncActivityViewModelTest { } @Test - fun whenOnDeviceEditedThenUpdateDevice() = runTest { + fun `onDeviceEdited - viewState updated`() = runTest { givenAuthenticatedUser() whenever(syncAccountRepository.renameDevice(any())).thenReturn(Result.Success(true)) @@ -448,7 +448,7 @@ class SyncActivityViewModelTest { } @Test - fun whenUserClicksOnSaveRecoveryCodeThenEmitCheckIfUserHasPermissionCommand() = runTest { + fun `onSaveRecoveryCodeClicked - emit check if user has permission command`() = runTest { givenUserHasDeviceAuthentication(true) whenever(syncAccountRepository.getRecoveryCode()).thenReturn(Result.Success(jsonRecoveryKeyEncoded)) testee.commands().test { @@ -460,7 +460,7 @@ class SyncActivityViewModelTest { } @Test - fun whenUserClicksOnSaveRecoveryCodeWithoutDeviceAuthenticationThenEmitCommandRequestSetupAuthentication() = runTest { + fun `onSaveRecoveryCodeClicked - no device authentication - emit command request setup authentication`() = runTest { givenUserHasDeviceAuthentication(false) whenever(syncAccountRepository.getRecoveryCode()).thenReturn(Result.Success(jsonRecoveryKeyEncoded)) testee.commands().test { @@ -472,7 +472,7 @@ class SyncActivityViewModelTest { } @Test - fun whenGenerateRecoveryCodeThenGenerateFileAndEmitSuccessCommand() = runTest { + fun `generateRecoveryCode - generate file and emit success command`() = runTest { whenever(syncAccountRepository.getRecoveryCode()).thenReturn(Result.Success(jsonRecoveryKeyEncoded)) whenever(recoveryPDF.generateAndStoreRecoveryCodePDF(any(), eq(jsonRecoveryKeyEncoded))).thenReturn(TestSyncFixtures.pdfFile()) @@ -485,7 +485,7 @@ class SyncActivityViewModelTest { } @Test - fun whenOnDeviceConnectedThenFetchRemoteDevices() = runTest { + fun `onDeviceConnected - view state updated`() = runTest { givenAuthenticatedUser() val connectedDevices = listOf(connectedDevice, connectedDevice) @@ -501,7 +501,7 @@ class SyncActivityViewModelTest { } @Test - fun whenSyncStateIsDisabledThenViewStateChanges() = runTest { + fun `syncStateIsDisabled - viewState changes`() = runTest { givenAuthenticatedUser() testee.viewState().test { @@ -515,7 +515,7 @@ class SyncActivityViewModelTest { } @Test - fun whenSyncStateIsEnabledThenViewStateChanges() = runTest { + fun `syncStateEnabled - viewState changes`() = runTest { givenAuthenticatedUser() stateFlow.value = SyncState.OFF @@ -530,7 +530,7 @@ class SyncActivityViewModelTest { } @Test - fun whenSyncStateIsInProgressEnabledThenViewStateDoesNotChange() = runTest { + fun `syncStateIsInProgressEnabled - viewState does not change`() = runTest { givenAuthenticatedUser() testee.viewState().test { @@ -543,7 +543,7 @@ class SyncActivityViewModelTest { } @Test - fun whenUserSignedAndSetupFlowsDisabledThenAllSetupFlowsDisabledViewState() = runTest { + fun `whenUserSignedAndSetupFlowsDisabled - viewState - all setup flows disabled`() = runTest { whenever(syncFeatureToggle.allowSetupFlows()).thenReturn(false) whenever(syncFeatureToggle.allowCreateAccount()).thenReturn(false) givenAuthenticatedUser() @@ -557,7 +557,7 @@ class SyncActivityViewModelTest { } @Test - fun whenUserSignedAndCreateAccountDisabledThenOnlySignInFlowDisabledViewState() = runTest { + fun `whenUserSignedAndCreateAccountDisabled - viewState only sign in flow disabled`() = runTest { whenever(syncFeatureToggle.allowSetupFlows()).thenReturn(true) whenever(syncFeatureToggle.allowCreateAccount()).thenReturn(false) givenAuthenticatedUser() @@ -571,7 +571,7 @@ class SyncActivityViewModelTest { } @Test - fun whenSetupFlowsDisabledThenAllSetupFlowsDisabledViewState() = runTest { + fun `setupFlowsDisabled - all setup flows disabled view state`() = runTest { whenever(syncFeatureToggle.allowSetupFlows()).thenReturn(false) whenever(syncFeatureToggle.allowCreateAccount()).thenReturn(true) @@ -584,7 +584,7 @@ class SyncActivityViewModelTest { } @Test - fun whenCreateAccountDisabledThenOnlySignInFlowDisabledViewState() = runTest { + fun `createAccountDisabled - viewState only sign in flow disabled`() = runTest { whenever(syncFeatureToggle.allowSetupFlows()).thenReturn(true) whenever(syncFeatureToggle.allowCreateAccount()).thenReturn(false) @@ -597,7 +597,7 @@ class SyncActivityViewModelTest { } @Test - fun whenSyncNotSupportedThenEmitCommandShowDeviceUnsupported() = runTest { + fun `isSyncSupported - emit command show device unsupported`() = runTest { whenever(syncAccountRepository.isSyncSupported()).thenReturn(false) testee.commands().test { diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/SyncConnectViewModelTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/SyncConnectViewModelTest.kt index 920383a638af..8254bef82d6a 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/SyncConnectViewModelTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/SyncConnectViewModelTest.kt @@ -65,7 +65,7 @@ class SyncConnectViewModelTest { ) @Test - fun whenScreenStartedThenShowQRCode() = runTest { + fun `whenScreenStarted - show QR code - shows QR code bitmap`() = runTest { val bitmap = TestSyncFixtures.qrBitmap() whenever(syncRepository.getConnectQR()).thenReturn(Result.Success(jsonConnectKeyEncoded)) whenever(qrEncoder.encodeAsBitmap(eq(jsonConnectKeyEncoded), any(), any())).thenReturn(bitmap) @@ -78,7 +78,7 @@ class SyncConnectViewModelTest { } @Test - fun whenGenerateConnectQRFailsThenFinishWithError() = runTest { + fun `generateConnectQR - fails - finish with error`() = runTest { whenever(syncRepository.getConnectQR()).thenReturn(Result.Error(reason = "error")) whenever(syncRepository.pollConnectionKeys()).thenReturn(Result.Success(true)) testee.viewState().test { @@ -94,7 +94,7 @@ class SyncConnectViewModelTest { } @Test - fun whenConnectionKeysSuccessThenLoginSuccess() = runTest { + fun `whenConnectionKeysSuccess - login success`() = runTest { whenever(syncRepository.getConnectQR()).thenReturn(Result.Success(jsonConnectKeyEncoded)) whenever(syncRepository.pollConnectionKeys()).thenReturn(Result.Success(true)) testee.viewState().test { @@ -111,7 +111,7 @@ class SyncConnectViewModelTest { } @Test - fun whenOnCopyCodeClickedThenShowMessage() = runTest { + fun `onCopyCodeClicked - show message`() = runTest { whenever(syncRepository.getConnectQR()).thenReturn(Result.Success(jsonConnectKeyEncoded)) testee.onCopyCodeClicked() @@ -124,7 +124,7 @@ class SyncConnectViewModelTest { } @Test - fun whenOnCopyCodeClickedThenCopyCodeToClipboard() = runTest { + fun `onCopyCodeClicked - clipboard copied`() = runTest { whenever(syncRepository.getConnectQR()).thenReturn(Result.Success(jsonConnectKeyEncoded)) testee.onCopyCodeClicked() @@ -133,7 +133,7 @@ class SyncConnectViewModelTest { } @Test - fun whenUserClicksOnReadTextCodeThenCommandIsReadTextCode() = runTest { + fun `onReadTextCodeClicked - commands - read text code`() = runTest { testee.commands().test { testee.onReadTextCodeClicked() val command = awaitItem() @@ -143,7 +143,7 @@ class SyncConnectViewModelTest { } @Test - fun whenUserScansConnectQRCodeAndConnectDeviceSucceedsThenCommandIsLoginSuccess() = runTest { + fun `onQRCodeScanned - connect device succeeds - login success`() = runTest { whenever(syncRepository.processCode(jsonConnectKeyEncoded)).thenReturn(Result.Success(true)) testee.commands().test { testee.onQRCodeScanned(jsonConnectKeyEncoded) @@ -155,7 +155,7 @@ class SyncConnectViewModelTest { } @Test - fun whenUserScansRecoveryCodeButSignedInThenCommandIsError() = runTest { + fun `onQRCodeScanned - signed in - error`() = runTest { whenever(syncRepository.processCode(jsonRecoveryKeyEncoded)).thenReturn(Result.Error(code = ALREADY_SIGNED_IN.code)) testee.commands().test { testee.onQRCodeScanned(jsonRecoveryKeyEncoded) @@ -167,7 +167,7 @@ class SyncConnectViewModelTest { } @Test - fun whenUserScansConnectQRCodeAndConnectDeviceFailsThenCommandIsError() = runTest { + fun `onQRCodeScanned - connect device fails - error command`() = runTest { whenever(syncRepository.processCode(jsonConnectKeyEncoded)).thenReturn(Result.Error(code = CONNECT_FAILED.code)) testee.commands().test { testee.onQRCodeScanned(jsonConnectKeyEncoded) @@ -179,7 +179,7 @@ class SyncConnectViewModelTest { } @Test - fun whenLoginSucceedsThenCommandIsLoginSuccess() = runTest { + fun `onLoginSuccess - command login success - login success`() = runTest { testee.commands().test { testee.onLoginSuccess() val command = awaitItem() @@ -190,7 +190,7 @@ class SyncConnectViewModelTest { } @Test - fun whenPollingIfConnectFailsThenShowError() = runTest { + fun `pollIfConnectFails - view state updated - show error`() = runTest { whenever(syncRepository.pollConnectionKeys()).thenReturn(Result.Error(CONNECT_FAILED.code)) testee.viewState().test { awaitItem() @@ -205,7 +205,7 @@ class SyncConnectViewModelTest { } @Test - fun whenPollingIfLoginFailsThenShowError() = runTest { + fun `pollIfLoginFails - view state updated - show error`() = runTest { whenever(syncRepository.pollConnectionKeys()).thenReturn(Result.Error(LOGIN_FAILED.code)) testee.viewState().test { awaitItem() @@ -220,7 +220,7 @@ class SyncConnectViewModelTest { } @Test - fun whenPollingIfGenericErrorThenDoNothing() = runTest { + fun `pollConnectionKeys - generic error - do nothing`() = runTest { whenever(syncRepository.getConnectQR()).thenReturn(Result.Success(jsonConnectKeyEncoded)) whenever(syncRepository.pollConnectionKeys()) .thenReturn(Result.Error()) diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/SyncDisabledViewModelTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/SyncDisabledViewModelTest.kt index ece33f8bf8ef..61dcc247f364 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/SyncDisabledViewModelTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/SyncDisabledViewModelTest.kt @@ -56,7 +56,7 @@ class SyncDisabledViewModelTest { ) @Test - fun whenUnauthenticatedUserDataSyncingDisabledThenMessageIsDisplayed() = runTest { + fun `onResume - unauthenticated data syncing disabled - message displayed`() = runTest { givenAllowDataSyncing(enabled = false) syncStateFlow.emit(OFF) testee.onResume(mock()) @@ -69,7 +69,7 @@ class SyncDisabledViewModelTest { } @Test - fun whenUnauthenticatedUserDataSyncingEnabledOnNewerVersionThenMessageIsDisplayed() = runTest { + fun `onResume - unauthenticated data syncing enabled on newer version - message displayed`() = runTest { givenAllowDataSyncing(enabledOnNewerVersion = true) syncStateFlow.emit(OFF) testee.onResume(mock()) @@ -82,7 +82,7 @@ class SyncDisabledViewModelTest { } @Test - fun whenAuthenticatedUserDataSyncingDisabledThenMessageIsDisplayed() = runTest { + fun `onResume - authenticated user data syncing disabled - message displayed`() = runTest { givenAllowDataSyncing(enabled = false) syncStateFlow.emit(READY) testee.onResume(mock()) @@ -95,7 +95,7 @@ class SyncDisabledViewModelTest { } @Test - fun whenAuthenticatedUserDataSyncingEnabledOnNewerVersionThenMessageIsDisplayed() = runTest { + fun `onResume - authenticated user data syncing enabled on newer version - message displayed`() = runTest { givenAllowDataSyncing(enabledOnNewerVersion = true) syncStateFlow.emit(READY) testee.onResume(mock()) @@ -108,7 +108,7 @@ class SyncDisabledViewModelTest { } @Test - fun whenUnauthenticatedSetupFlowsDisabledThenMessageIsDisplayed() = runTest { + fun `onResume - unauthenticated setup flows disabled - message displayed`() = runTest { givenAllowSetupFlows(enabled = false) syncStateFlow.emit(OFF) testee.onResume(mock()) @@ -121,7 +121,7 @@ class SyncDisabledViewModelTest { } @Test - fun whenUnauthenticatedSetupFlowsEnabledOnNewerVersionThenMessageIsDisplayed() = runTest { + fun `onResume - unauthenticated setup flows enabled on newer version - message displayed`() = runTest { givenAllowSetupFlows(enabledOnNewerVersion = true) syncStateFlow.emit(OFF) testee.onResume(mock()) @@ -134,7 +134,7 @@ class SyncDisabledViewModelTest { } @Test - fun whenAuthenticatedSetupFlowsDisabledThenMessageIsDisplayed() = runTest { + fun `onResume - authenticated setup flows disabled - no message displayed`() = runTest { givenAllowSetupFlows(enabled = false) syncStateFlow.emit(READY) testee.onResume(mock()) @@ -147,7 +147,7 @@ class SyncDisabledViewModelTest { } @Test - fun whenAuthenticatedSetupFlowsEnabledOnNewerVersionThenMessageIsDisplayed() = runTest { + fun `onResume - authenticated setup flows enabled on newer version - no message displayed`() = runTest { givenAllowSetupFlows(enabledOnNewerVersion = true) syncStateFlow.emit(READY) testee.onResume(mock()) @@ -160,7 +160,7 @@ class SyncDisabledViewModelTest { } @Test - fun whenUnauthenticatedCreateAccountDisabledThenMessageIsDisplayed() = runTest { + fun `onResume - unauthenticated create account disabled - message displayed`() = runTest { givenCreateAccountFlows(enabled = false) syncStateFlow.emit(OFF) testee.onResume(mock()) @@ -173,7 +173,7 @@ class SyncDisabledViewModelTest { } @Test - fun whenUnauthenticatedCreateAccountEnabledOnNewerVersionThenMessageIsDisplayed() = runTest { + fun `onResume - unauthenticated create account enabled on newer version - message displayed`() = runTest { givenCreateAccountFlows(enabledOnNewerVersion = true) syncStateFlow.emit(OFF) testee.onResume(mock()) @@ -186,7 +186,7 @@ class SyncDisabledViewModelTest { } @Test - fun whenAuthenticatedCreateAccountDisabledThenMessageIsDisplayed() = runTest { + fun `onResume - create account disabled - message is null`() = runTest { givenCreateAccountFlows(enabled = false) syncStateFlow.emit(READY) testee.onResume(mock()) @@ -199,7 +199,7 @@ class SyncDisabledViewModelTest { } @Test - fun whenAuthenticatedCreateAccountEnabledOnNewerVersionThenMessageIsDisplayed() = runTest { + fun `onResume - create account enabled on newer version - message is not displayed`() = runTest { givenCreateAccountFlows(enabledOnNewerVersion = true) syncStateFlow.emit(READY) testee.onResume(mock()) diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/SyncLoginViewModelTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/SyncLoginViewModelTest.kt index 90ea44713608..ad2f91ba6842 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/SyncLoginViewModelTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/SyncLoginViewModelTest.kt @@ -49,7 +49,7 @@ class SyncLoginViewModelTest { ) @Test - fun whenReadTextCodeClickedThenCommandIsReadTextCode() = runTest { + fun `onReadTextCodeClicked - command read text code`() = runTest { testee.commands().test { testee.onReadTextCodeClicked() val command = awaitItem() @@ -59,7 +59,7 @@ class SyncLoginViewModelTest { } @Test - fun whenProcessRecoveryCodeThenPerformLoginAndEmitResult() = runTest { + fun `onQRCodeScanned - perform login and emit result`() = runTest { whenever(syncRepostitory.processCode(jsonRecoveryKeyEncoded)).thenReturn(Success(true)) testee.commands().test { @@ -72,7 +72,7 @@ class SyncLoginViewModelTest { } @Test - fun whenOnLoginSuccessThenCommandIsLoginSuccess() = runTest { + fun `onLoginSuccess - command login success - login success`() = runTest { testee.commands().test { testee.onLoginSuccess() val command = awaitItem() diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/SyncWithAnotherDeviceViewModelTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/SyncWithAnotherDeviceViewModelTest.kt index 341736152591..d05637829619 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/SyncWithAnotherDeviceViewModelTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/SyncWithAnotherDeviceViewModelTest.kt @@ -63,7 +63,7 @@ class SyncWithAnotherDeviceViewModelTest { ) @Test - fun whenScreenStartedThenShowQRCode() = runTest { + fun `whenScreenStarted - show QR code - shows QR code bitmap`() = runTest { val bitmap = TestSyncFixtures.qrBitmap() whenever(syncRepository.getRecoveryCode()).thenReturn(Result.Success(jsonRecoveryKeyEncoded)) whenever(qrEncoder.encodeAsBitmap(eq(jsonRecoveryKeyEncoded), any(), any())).thenReturn(bitmap) @@ -75,7 +75,7 @@ class SyncWithAnotherDeviceViewModelTest { } @Test - fun whenGenerateRecoveryQRFailsThenFinishWithError() = runTest { + fun `generateRecoveryQR - fails - finish with error`() = runTest { whenever(syncRepository.getRecoveryCode()).thenReturn(Result.Error(reason = "error")) testee.viewState().test { awaitItem() @@ -90,7 +90,7 @@ class SyncWithAnotherDeviceViewModelTest { } @Test - fun whenOnCopyCodeClickedThenShowMessage() = runTest { + fun `onCopyCodeClicked - show message`() = runTest { whenever(syncRepository.getRecoveryCode()).thenReturn(Result.Success(jsonRecoveryKeyEncoded)) testee.onCopyCodeClicked() @@ -103,7 +103,7 @@ class SyncWithAnotherDeviceViewModelTest { } @Test - fun whenOnCopyCodeClickedThenCopyCodeToClipboard() = runTest { + fun `onCopyCodeClicked - copy code to clipboard`() = runTest { whenever(syncRepository.getRecoveryCode()).thenReturn(Result.Success(jsonRecoveryKeyEncoded)) testee.onCopyCodeClicked() @@ -112,7 +112,7 @@ class SyncWithAnotherDeviceViewModelTest { } @Test - fun whenUserClicksOnReadTextCodeThenCommandIsReadTextCode() = runTest { + fun `onReadTextCodeClicked - commands - read text code`() = runTest { testee.commands().test { testee.onReadTextCodeClicked() val command = awaitItem() @@ -122,7 +122,7 @@ class SyncWithAnotherDeviceViewModelTest { } @Test - fun whenUserScansRecoveryCodeButSignedInThenCommandIsError() = runTest { + fun `onQRCodeScanned - signed in - error`() = runTest { whenever(syncRepository.processCode(jsonRecoveryKeyEncoded)).thenReturn(Result.Error(code = ALREADY_SIGNED_IN.code)) testee.commands().test { testee.onQRCodeScanned(jsonRecoveryKeyEncoded) @@ -134,7 +134,7 @@ class SyncWithAnotherDeviceViewModelTest { } @Test - fun whenUserScansRecoveryQRCodeAndConnectDeviceFailsThenCommandIsError() = runTest { + fun `onQRCodeScanned - connect device fails - error command`() = runTest { whenever(syncRepository.processCode(jsonRecoveryKeyEncoded)).thenReturn(Result.Error(code = LOGIN_FAILED.code)) testee.commands().test { testee.onQRCodeScanned(jsonRecoveryKeyEncoded) @@ -146,7 +146,7 @@ class SyncWithAnotherDeviceViewModelTest { } @Test - fun whenLoginSucceedsThenCommandIsLoginSuccess() = runTest { + fun `onLoginSuccess - command login success - login success`() = runTest { testee.commands().test { testee.onLoginSuccess() val command = awaitItem() diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/qrcode/SyncBarcodeViewModelTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/qrcode/SyncBarcodeViewModelTest.kt index b4b82cf7fd4d..06ba2b79687a 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/qrcode/SyncBarcodeViewModelTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/qrcode/SyncBarcodeViewModelTest.kt @@ -63,7 +63,7 @@ class SyncBarcodeViewModelTest { } @Test - fun whenHandleCameraAvailabilityWithCameraUnavailableThenViewStateCameraUnavailable() = runTest { + fun `handleCameraAvailability - viewState camera unavailable - camera unavailable`() = runTest { testee.handleCameraAvailability(false) testee.viewState.test { @@ -73,7 +73,7 @@ class SyncBarcodeViewModelTest { } @Test - fun whenHandlePermissionsWithPermissionGrantedThenViewStatePermissionsGranted() = runTest { + fun `handlePermissions - permission granted - view state permissions granted`() = runTest { testee.handlePermissions(true) testee.viewState.test { @@ -83,7 +83,7 @@ class SyncBarcodeViewModelTest { } @Test - fun whenHandlePermissionsWithPermissionNotGrantedAndPermissionNotDeniedYetThenCommandRequestPermissions() = runTest { + fun `handlePermissions - permission not granted and not denied yet - request permissions`() = runTest { permissionDeniedWrapper.permissionAlreadyDenied = false testee.handlePermissions(false) @@ -94,7 +94,7 @@ class SyncBarcodeViewModelTest { } @Test - fun whenHandlePermissionsWithPermissionNotGrantedThenViewStateUnknown() = runTest { + fun `handlePermissions - permission not granted - view state unknown`() = runTest { testee.handlePermissions(false) testee.viewState.test { @@ -104,7 +104,7 @@ class SyncBarcodeViewModelTest { } @Test - fun whenHandlePermissionsWithPermissionNotGrantedAndPermissionAlreadyDeniedThenViewStatePermissionsNotGranted() = runTest { + fun `handlePermissions - permission not granted and permission already denied - view state permissions not granted`() = runTest { permissionDeniedWrapper.permissionAlreadyDenied = true testee.handlePermissions(false) @@ -115,7 +115,7 @@ class SyncBarcodeViewModelTest { } @Test - fun whenGoToSettingsThenCommandOpenSettings() = runTest { + fun `goToSettings - command open settings`() = runTest { testee.goToSettings() testee.commands().test { @@ -125,7 +125,7 @@ class SyncBarcodeViewModelTest { } @Test - fun whenGoToSettingsThenViewStateUnknown() = runTest { + fun `goToSettings - viewState unknown - unknown`() = runTest { testee.goToSettings() testee.viewState.test { @@ -135,7 +135,7 @@ class SyncBarcodeViewModelTest { } @Test - fun whenOnResumeThenCommandCheckCameraAvailable() = runTest { + fun `onResume - command check camera available - check camera available`() = runTest { testee.onResume(fakeLifecycleOwner) testee.commands().test { @@ -145,7 +145,7 @@ class SyncBarcodeViewModelTest { } @Test - fun whenOnResumeThenViewStateUnknown() = runTest { + fun `onResume - viewState unknown`() = runTest { testee.onResume(fakeLifecycleOwner) testee.viewState.test { @@ -155,7 +155,7 @@ class SyncBarcodeViewModelTest { } @Test - fun whenHandleCameraAvailabilityWithCameraAvailableThenCommandCheckPermissions() = runTest { + fun `handleCameraAvailability - camera available - command check permissions`() = runTest { testee.handleCameraAvailability(true) testee.commands().test { @@ -165,7 +165,7 @@ class SyncBarcodeViewModelTest { } @Test - fun whenHandleCameraAvailabilityWithCameraAvailableThenViewStateUnknown() = runTest { + fun `handleCameraAvailability - camera available - view state unknown`() = runTest { testee.handleCameraAvailability(true) testee.viewState.test { @@ -175,7 +175,7 @@ class SyncBarcodeViewModelTest { } @Test - fun whenHandlePermissionsWithPermissionNotGrantedAndPermissionNotDeniedYetThenPermissionAlreadyDeniedTrue() = runTest { + fun `handlePermissions - permission not granted and not denied yet - permission already denied true`() = runTest { permissionDeniedWrapper.permissionAlreadyDenied = false testee.handlePermissions(false) diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/setup/SaveRecoveryCodeViewModelTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/setup/SaveRecoveryCodeViewModelTest.kt index 47a27afaef9a..a53b91743c19 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/setup/SaveRecoveryCodeViewModelTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/setup/SaveRecoveryCodeViewModelTest.kt @@ -63,7 +63,7 @@ class SaveRecoveryCodeViewModelTest { ) @Test - fun whenUserIsNotSignedInThenAccountCreatedAndViewStateUpdated() = runTest { + fun `isNotSignedIn - account created - view state updated`() = runTest { whenever(syncAccountRepository.isSignedIn()).thenReturn(false) whenever(syncAccountRepository.createAccount()).thenReturn(Result.Success(true)) whenever(syncAccountRepository.getRecoveryCode()).thenReturn(Result.Success(jsonRecoveryKeyEncoded)) @@ -76,7 +76,7 @@ class SaveRecoveryCodeViewModelTest { } @Test - fun whenUserSignedInThenShowViewState() = runTest { + fun `whenUserSignedInThenShowViewState - view state - signed in`() = runTest { whenever(syncAccountRepository.isSignedIn()).thenReturn(true) whenever(syncAccountRepository.getRecoveryCode()).thenReturn(Result.Success(jsonRecoveryKeyEncoded)) @@ -88,7 +88,7 @@ class SaveRecoveryCodeViewModelTest { } @Test - fun whenCreateAccountFailsThenEmitFinishWithError() = runTest { + fun `createAccount - view state updated - emit finish with error`() = runTest { whenever(syncAccountRepository.isSignedIn()).thenReturn(false) whenever(syncAccountRepository.createAccount()).thenReturn(accountCreatedFailInvalid) @@ -106,7 +106,7 @@ class SaveRecoveryCodeViewModelTest { } @Test - fun whenUserClicksNextThenFinishFlow() = runTest { + fun `onNextClicked - finish flow`() = runTest { testee.commands().test { testee.onNextClicked() val command = awaitItem() @@ -116,7 +116,7 @@ class SaveRecoveryCodeViewModelTest { } @Test - fun whenUserClicksOnSaveRecoveryCodeThenEmitCheckIfUserHasPermissionCommand() = runTest { + fun `onSaveRecoveryCodeClicked - emit check if user has permission command`() = runTest { whenever(syncAccountRepository.getRecoveryCode()).thenReturn(Result.Success(jsonRecoveryKeyEncoded)) testee.commands().test { testee.onSaveRecoveryCodeClicked() @@ -127,7 +127,7 @@ class SaveRecoveryCodeViewModelTest { } @Test - fun whenGenerateRecoveryCodeThenGenerateFileAndEmitSuccessCommand() = runTest { + fun `generateRecoveryCode - generate file and emit success command`() = runTest { whenever(syncAccountRepository.getRecoveryCode()).thenReturn(Result.Success(jsonRecoveryKeyEncoded)) whenever(recoveryPDF.generateAndStoreRecoveryCodePDF(any(), eq(jsonRecoveryKeyEncoded))).thenReturn(pdfFile()) @@ -140,7 +140,7 @@ class SaveRecoveryCodeViewModelTest { } @Test - fun whenUserClicksCopyThenCopyToClipboard() = runTest { + fun `onCopyCodeClicked - copy to clipboard`() = runTest { whenever(syncAccountRepository.getRecoveryCode()).thenReturn(Result.Success(jsonRecoveryKeyEncoded)) testee.commands().test { testee.onCopyCodeClicked() diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/setup/SetupAccountViewModelTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/setup/SetupAccountViewModelTest.kt index 663683209120..82e1c3d59d26 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/setup/SetupAccountViewModelTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/setup/SetupAccountViewModelTest.kt @@ -33,7 +33,7 @@ class SetupAccountViewModelTest { private val testee = SetupAccountViewModel(coroutineTestRule.testDispatcherProvider) @Test - fun whenFlowStartedFromSyncSetupScreenViewModeThenCreateAccountCommandSent() = runTest { + fun `whenFlowStartedFromSyncSetupScreenViewMode - create account command sent`() = runTest { testee.viewState(Screen.SYNC_SETUP).test { val viewState = awaitItem() assertTrue(viewState.viewMode is ViewMode.CreateAccount) @@ -41,7 +41,7 @@ class SetupAccountViewModelTest { } @Test - fun whenFlowStartedFromSyncIntroViewModeThenIntroCreateAccountCommandSent() = runTest { + fun `whenFlowStartedFromSyncIntroViewModeThenIntroCreateAccountCommandSent - view state intro create account command sent`() = runTest { testee.viewState(Screen.SYNC_INTRO).test { val viewState = awaitItem() assertTrue(viewState.viewMode is ViewMode.IntroCreateAccount) @@ -49,7 +49,7 @@ class SetupAccountViewModelTest { } @Test - fun whenFlowStartedFromRecoveryIntroViewModeThenIntroRecoveryCodeCommandSent() = runTest { + fun `viewState - flow started from recovery intro view mode - intro recovery code command sent`() = runTest { testee.viewState(Screen.RECOVERY_INTRO).test { val viewState = awaitItem() assertTrue(viewState.viewMode is ViewMode.IntroRecoveryCode) @@ -57,7 +57,7 @@ class SetupAccountViewModelTest { } @Test - fun whenFlowStartedFromSetupScreenViewModeDeviceConnected() = runTest { + fun `viewState - setup complete - sync setup completed`() = runTest { testee.viewState(Screen.SETUP_COMPLETE).test { val viewState = awaitItem() assertTrue(viewState.viewMode is ViewMode.SyncSetupCompleted) @@ -65,7 +65,7 @@ class SetupAccountViewModelTest { } @Test - fun whenOnBackPressedAndViewModeDeviceConnectedThenClose() = runTest { + fun `onBackPressed - view mode device connected - close`() = runTest { testee.viewState(Screen.SETUP_COMPLETE).test { val viewState = awaitItem() assertTrue(viewState.viewMode is ViewMode.SyncSetupCompleted) @@ -79,7 +79,7 @@ class SetupAccountViewModelTest { } @Test - fun whenFlowStartedFromConnectionScreenViewThenRecoveryCodeMode() = runTest { + fun `whenFlowStartedFromConnectionScreenViewThenRecoveryCodeMode - view state recovery code mode`() = runTest { testee.viewState(Screen.RECOVERY_CODE).test { val viewState = awaitItem() assertTrue(viewState.viewMode is ViewMode.AskSaveRecoveryCode) @@ -87,7 +87,7 @@ class SetupAccountViewModelTest { } @Test - fun whenOnBackPressedAndViewModeRecoveryCodeThenClose() = runTest { + fun `onBackPressed - view mode recovery code - close`() = runTest { testee.viewState(Screen.RECOVERY_CODE).test { val viewState = awaitItem() assertTrue(viewState.viewMode is ViewMode.AskSaveRecoveryCode) @@ -101,7 +101,7 @@ class SetupAccountViewModelTest { } @Test - fun whenSetupStartedAndAccountCreatedThenCreateAccountCommandSent() = runTest { + fun `onCreateAccount - view state updated - create account command sent`() = runTest { testee.viewState(Screen.SYNC_SETUP).test { testee.onCreateAccount() val viewState = expectMostRecentItem() @@ -110,7 +110,7 @@ class SetupAccountViewModelTest { } @Test - fun whenSetupStartedAndDeviceConnectedSyncSetupCompletedCommandSent() = runTest { + fun `onDeviceConnected - view state sync setup completed`() = runTest { testee.viewState(Screen.SYNC_SETUP).test { testee.onDeviceConnected() val viewState = expectMostRecentItem() @@ -119,7 +119,7 @@ class SetupAccountViewModelTest { } @Test - fun whenSetupStartedAndRecoveryCodeProDeviceConnectedThenAskSaveRecoveryCodeCommandSent() = runTest { + fun `onRecoveryCodePrompt - view state updated - ask save recovery code command sent`() = runTest { testee.viewState(Screen.SYNC_SETUP).test { testee.onRecoveryCodePrompt() val viewState = expectMostRecentItem() diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/setup/SyncCreateAccountViewModelTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/setup/SyncCreateAccountViewModelTest.kt index 1b1aace2b5b4..b492143836b4 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/setup/SyncCreateAccountViewModelTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/setup/SyncCreateAccountViewModelTest.kt @@ -49,7 +49,7 @@ class SyncCreateAccountViewModelTest { ) @Test - fun whenUserIsNotSignedInThenAccountCreatedAndViewStateUpdated() = runTest { + fun `whenUserIsNotSignedIn - account created and view state updated - creating account and finish setup flow`() = runTest { whenever(syncRepostitory.createAccount()).thenReturn(Result.Success(true)) testee.viewState().test { @@ -67,7 +67,7 @@ class SyncCreateAccountViewModelTest { } @Test - fun whenCreateAccountFailsThenEmitError() = runTest { + fun `createAccount - fails - emit error`() = runTest { whenever(syncRepostitory.createAccount()).thenReturn(Result.Error(1, "")) testee.viewState().test { diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/setup/SyncSetupIntroViewModelTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/setup/SyncSetupIntroViewModelTest.kt index 79498946c81a..728d2ee396c6 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/setup/SyncSetupIntroViewModelTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/setup/SyncSetupIntroViewModelTest.kt @@ -38,7 +38,7 @@ class SyncSetupIntroViewModelTest { private val testee = SyncSetupIntroViewModel() @Test - fun whenSyncIntroArgumentThenIntroCreateAccountScreenShown() = runTest { + fun `syncIntro - view state updated - intro create account screen shown`() = runTest { testee.viewState(SYNC_INTRO).test { val viewState = awaitItem() Assert.assertTrue(viewState.viewMode is CreateAccountIntro) @@ -47,7 +47,7 @@ class SyncSetupIntroViewModelTest { } @Test - fun whenRecoverIntroArgumentThenIntroRecoveryScreenShown() = runTest { + fun `recoverIntroArgument - view state updated - intro recovery screen shown`() = runTest { testee.viewState(RECOVERY_INTRO).test { val viewState = awaitItem() Assert.assertTrue(viewState.viewMode is RecoverAccountIntro) @@ -56,7 +56,7 @@ class SyncSetupIntroViewModelTest { } @Test - fun whenOnTurnSyncOnClickedThenStartSetupFlowCommandSent() = runTest { + fun `onTurnSyncOnClicked - start setup flow command sent`() = runTest { testee.onTurnSyncOnClicked() testee.commands().test { @@ -67,7 +67,7 @@ class SyncSetupIntroViewModelTest { } @Test - fun whenOnStartRecoveryDataClickedThenRecoverDataFlowCommandSent() = runTest { + fun `onStartRecoverDataClicked - commands sent - recover data flow`() = runTest { testee.onStartRecoverDataClicked() testee.commands().test { @@ -78,7 +78,7 @@ class SyncSetupIntroViewModelTest { } @Test - fun whenOnAbortCLickedThenAbortFlowCommandSent() = runTest { + fun `onAbortClicked - commands sent - abort flow command`() = runTest { testee.onAbortClicked() testee.commands().test { diff --git a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/setup/SyncShowRecoveryCodeViewModelTest.kt b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/setup/SyncShowRecoveryCodeViewModelTest.kt index b312393dd5b2..7e4466770535 100644 --- a/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/setup/SyncShowRecoveryCodeViewModelTest.kt +++ b/sync/sync-impl/src/test/java/com/duckduckgo/sync/impl/ui/setup/SyncShowRecoveryCodeViewModelTest.kt @@ -34,7 +34,7 @@ class SyncShowRecoveryCodeViewModelTest { ) @Test - fun whenNextClickedThenEmitFinishSetupCommand() = runTest { + fun `onDoneClicked - emit finish setup command`() = runTest { testee.onDoneClicked() testee.commands().test { diff --git a/sync/sync-settings-impl/src/test/java/com/duckduckgo/sync/settings/impl/SettingsSyncDataPersisterTest.kt b/sync/sync-settings-impl/src/test/java/com/duckduckgo/sync/settings/impl/SettingsSyncDataPersisterTest.kt index 25a565e0f7ee..430964c734f1 100644 --- a/sync/sync-settings-impl/src/test/java/com/duckduckgo/sync/settings/impl/SettingsSyncDataPersisterTest.kt +++ b/sync/sync-settings-impl/src/test/java/com/duckduckgo/sync/settings/impl/SettingsSyncDataPersisterTest.kt @@ -67,7 +67,7 @@ class SettingsSyncDataPersisterTest { } @Test - fun whenPersistChangesDeduplicationWithdValueThenCallDeduplicateWithValue() { + fun `onSuccess - deduplication with value - call deduplicate with value`() { val result = testee.onSuccess( changes = SyncChangesResponse( type = SyncableType.SETTINGS, @@ -81,7 +81,7 @@ class SettingsSyncDataPersisterTest { } @Test - fun whenPersistChangesDeduplicationWithDeletedValueThenCallDeduplicateWithNull() { + fun `onSuccess - deduplication with deleted value - call deduplicate with null`() { val result = testee.onSuccess( changes = SyncChangesResponse( type = SyncableType.SETTINGS, @@ -95,7 +95,7 @@ class SettingsSyncDataPersisterTest { } @Test - fun whenPersistChangesTimestampAndNoRecentChangeThenCallMergeWithValue() { + fun `onSuccess - persist changes timestamp and no recent change - call merge with value`() { settingSyncStore.startTimeStamp = "2023-08-31T10:06:16.022Z" val result = testee.onSuccess( changes = SyncChangesResponse( @@ -110,7 +110,7 @@ class SettingsSyncDataPersisterTest { } @Test - fun whenPersistChangesTimestampWithDeletedValueThenCallSaveWithNull() { + fun `onSuccess - persist changes timestamp with deleted value - save with null`() { val result = testee.onSuccess( changes = SyncChangesResponse( type = SyncableType.SETTINGS, @@ -124,7 +124,7 @@ class SettingsSyncDataPersisterTest { } @Test - fun whenPersistChangesTimestampButRecentlyModifiedThenSkip() { + fun `onSuccess - persist changes timestamp but recently modified - skip`() { settingSyncStore.startTimeStamp = "2023-08-31T10:06:16.022Z" metadataDao.addOrUpdate( SettingsSyncMetadataEntity( @@ -147,7 +147,7 @@ class SettingsSyncDataPersisterTest { } @Test - fun whenPersistChangesSucceedsThenUpdateServerAndClientTimestamps() { + fun `onSuccess - update server and client timestamps`() { settingSyncStore.startTimeStamp = "2023-08-31T10:06:16.022Z" val result = testee.onSuccess( diff --git a/sync/sync-settings-impl/src/test/java/com/duckduckgo/sync/settings/impl/SettingsSyncDataProviderTest.kt b/sync/sync-settings-impl/src/test/java/com/duckduckgo/sync/settings/impl/SettingsSyncDataProviderTest.kt index 5feed39f78b5..f85075c0712d 100644 --- a/sync/sync-settings-impl/src/test/java/com/duckduckgo/sync/settings/impl/SettingsSyncDataProviderTest.kt +++ b/sync/sync-settings-impl/src/test/java/com/duckduckgo/sync/settings/impl/SettingsSyncDataProviderTest.kt @@ -68,7 +68,7 @@ class SettingsSyncDataProviderTest { } @Test - fun whenGetChangesForFirstTimeThenMetadataIsInitialized() = runTest { + fun `getChanges - metadata initialized`() = runTest { assertTrue(metadataDao.getAllObservable().first().isEmpty()) testee.getChanges() @@ -77,7 +77,7 @@ class SettingsSyncDataProviderTest { } @Test - fun whenGetChangesForFirstTimeThenExistingMetadataUpdated() = runTest { + fun `getChanges - existing metadata updated - metadata updated`() = runTest { metadataDao.addOrUpdate( SettingsSyncMetadataEntity(duckAddressSetting.key, "", ""), ) @@ -96,7 +96,7 @@ class SettingsSyncDataProviderTest { } @Test - fun whenGetChangesForFirstSyncThenChangesIncludeAllValues() { + fun `getChanges - first sync - changes include all values`() { val changes = testee.getChanges() assertTrue(changes.type == SyncableType.SETTINGS) @@ -111,7 +111,7 @@ class SettingsSyncDataProviderTest { @Test @Ignore("Need to decide strategy first") - fun whenGetChangesSubsequentCallsWithNewValueThenIncludeNewValues() { + fun `getChanges - subsequent calls with new value - include new values`() { settingSyncStore.serverModifiedSince = "2022-01-01T00:00:00Z" settingSyncStore.clientModifiedSince = "2022-01-01T00:00:00Z" @@ -128,7 +128,7 @@ class SettingsSyncDataProviderTest { } @Test - fun whenGetChangesSubsequentCallsAndNoChangesThenUpdatesAreEmpty() { + fun `getChanges - subsequent calls and no changes - updates are empty`() { settingSyncStore.serverModifiedSince = "2022-01-01T00:00:00Z" settingSyncStore.clientModifiedSince = "2022-01-01T00:00:00Z" metadataDao.addOrUpdate(SettingsSyncMetadataEntity(duckAddressSetting.key, "2022-01-01T00:00:00Z", "")) @@ -141,7 +141,7 @@ class SettingsSyncDataProviderTest { } @Test - fun whenDBHasDataButItIsFirstSyncThenIncludeAllValues() { + fun `getChanges - db has data but it's first sync - include all values`() { metadataDao.addOrUpdate(SettingsSyncMetadataEntity(duckAddressSetting.key, "2022-01-01T00:00:00Z", "")) val changes = testee.getChanges() @@ -157,7 +157,7 @@ class SettingsSyncDataProviderTest { } @Test - fun whenGetChangesForFirstSyncAndSettingNullThenSendAsDeleted() { + fun `getChanges - setting null - send as deleted`() { duckAddressSetting.save(null) val changes = testee.getChanges() @@ -173,7 +173,7 @@ class SettingsSyncDataProviderTest { } @Test - fun whenGetChangesSubsequentCallsAndSettingNullThenSendAsDeleted() { + fun `getChanges - subsequent calls and setting null - send as deleted`() { settingSyncStore.serverModifiedSince = "2022-01-01T00:00:00Z" settingSyncStore.clientModifiedSince = "2022-01-01T00:00:00Z" metadataDao.addOrUpdate(SettingsSyncMetadataEntity(duckAddressSetting.key, "2022-01-02T00:00:00Z", "")) @@ -192,7 +192,7 @@ class SettingsSyncDataProviderTest { } @Test - fun whenSyncableSettingNotFoundThenSkipUpdate() { + fun `getChanges - setting not found - skip update`() { settingSyncStore.serverModifiedSince = "2022-01-01T00:00:00Z" settingSyncStore.clientModifiedSince = "2022-01-01T00:00:00Z" metadataDao.addOrUpdate(SettingsSyncMetadataEntity("unknown_setting", "2022-01-02T00:00:00Z", "")) diff --git a/sync/sync-store/src/test/java/com/duckduckgo/sync/store/SyncSharedPrefsStoreTest.kt b/sync/sync-store/src/test/java/com/duckduckgo/sync/store/SyncSharedPrefsStoreTest.kt index ba8905c345a3..792f6b9ac23a 100644 --- a/sync/sync-store/src/test/java/com/duckduckgo/sync/store/SyncSharedPrefsStoreTest.kt +++ b/sync/sync-store/src/test/java/com/duckduckgo/sync/store/SyncSharedPrefsStoreTest.kt @@ -43,7 +43,7 @@ class SyncSharedPrefsStoreTest { } @Test - fun whenUserIdStoredThenValueUpdatedInPrefsStore() { + fun `whenUserIdStored - value updated in prefs store`() { assertNull(store.userId) store.userId = "test_user" assertEquals("test_user", store.userId) @@ -52,7 +52,7 @@ class SyncSharedPrefsStoreTest { } @Test - fun whenDeviceNameStoredThenValueUpdatedInPrefsStore() { + fun `whenDeviceNameStored - value updated in prefs store`() { assertNull(store.deviceName) store.deviceName = "test_device" assertEquals("test_device", store.deviceName) @@ -61,7 +61,7 @@ class SyncSharedPrefsStoreTest { } @Test - fun whenDeviceIdStoredThenValueUpdatedInPrefsStore() { + fun `whenDeviceIdStored - value updated in prefs store`() { assertNull(store.deviceId) store.deviceId = "test_device_id" assertEquals("test_device_id", store.deviceId) @@ -70,7 +70,7 @@ class SyncSharedPrefsStoreTest { } @Test - fun whenStoreCredentialsThenValuesUpdatedInPrefsStore() { + fun `storeCredentials - values updated in prefs store`() { assertNull(store.userId) assertNull(store.deviceName) assertNull(store.deviceId) @@ -87,14 +87,14 @@ class SyncSharedPrefsStoreTest { } @Test - fun whenIsSignedInThenReturnTrueIfUserHasAuthKeys() { + fun `isSignedIn - has auth keys - true`() { store.storeCredentials("userId", "deviceId", "deviceName", "primaryKey", "secretKey", "token") assertTrue(store.isSignedIn()) } @Test - fun whenClearAllThenReturnRemoveAllKeys() { + fun `clearAll - return remove all keys`() { store.storeCredentials("userId", "deviceId", "deviceName", "primaryKey", "secretKey", "token") assertEquals("userId", store.userId) assertEquals("deviceName", store.deviceName) diff --git a/sync/sync-store/src/test/java/com/duckduckgo/sync/store/dao/SyncApiErrorDaoTest.kt b/sync/sync-store/src/test/java/com/duckduckgo/sync/store/dao/SyncApiErrorDaoTest.kt index c56ac2ca66ec..319de786da59 100644 --- a/sync/sync-store/src/test/java/com/duckduckgo/sync/store/dao/SyncApiErrorDaoTest.kt +++ b/sync/sync-store/src/test/java/com/duckduckgo/sync/store/dao/SyncApiErrorDaoTest.kt @@ -56,7 +56,7 @@ class SyncApiErrorDaoTest { } @Test - fun whenApiErrorAddedThenItCanBeRetrieved() = runTest { + fun `whenApiErrorAddedThenItCanBeRetrieved - api error added - can be retrieved`() = runTest { val feature = "bookmarks" val errorType = SyncApiErrorType.OBJECT_LIMIT_EXCEEDED val date = DatabaseDateFormatter.getUtcIsoLocalDate() @@ -69,7 +69,7 @@ class SyncApiErrorDaoTest { } @Test - fun whenApiErrorIncrementedThenCounterIncremented() = runTest { + fun `whenApiErrorIncrementedThenCounterIncremented - api error incremented - counter incremented`() = runTest { val feature = "bookmarks" val errorType = SyncApiErrorType.OBJECT_LIMIT_EXCEEDED val date = DatabaseDateFormatter.getUtcIsoLocalDate() diff --git a/user-agent/user-agent-impl/src/test/java/com/duckduckgo/user/agent/impl/RealUserAgentTest.kt b/user-agent/user-agent-impl/src/test/java/com/duckduckgo/user/agent/impl/RealUserAgentTest.kt index e181a65567f1..79d18e3c9a03 100644 --- a/user-agent/user-agent-impl/src/test/java/com/duckduckgo/user/agent/impl/RealUserAgentTest.kt +++ b/user-agent/user-agent-impl/src/test/java/com/duckduckgo/user/agent/impl/RealUserAgentTest.kt @@ -40,28 +40,28 @@ class RealUserAgentTest { } @Test - fun whenIsExceptionAndDomainIsListedInTheExceptionsListThenReturnTrue() { + fun `isException - domain listed in exceptions list - true`() { givenThereAreExceptions() assertTrue(testee.isException("http://www.example.com")) } @Test - fun whenIsExceptionWithSubdomainAndDomainIsListedInTheExceptionsListThenReturnTrue() { + fun `isException - exceptions list contains subdomain and domain - returns true`() { givenThereAreExceptions() assertTrue(testee.isException("http://test.example.com")) } @Test - fun whenIsExceptionAndDomainIsNotListedInTheExceptionsListThenReturnFalse() { + fun `isException - domain not listed in exceptions list - returns false`() { whenever(mockUserAgentRepository.exceptions).thenReturn(CopyOnWriteArrayList()) assertFalse(testee.isException("http://test.example.com")) } @Test - fun whenIsExceptionAndDomainIsListedInTheUnprotectedTemporaryListThenReturnTrue() { + fun `isException - is listed in unprotected temporary list - returns true`() { val url = "http://example.com" whenever(mockUnprotectedTemporary.isAnException(url)).thenReturn(true) whenever(mockUserAgentRepository.exceptions).thenReturn(CopyOnWriteArrayList()) @@ -70,21 +70,21 @@ class RealUserAgentTest { } @Test - fun whenSiteInLegacySitesListThenUseLegacyUserAgent() { + fun `useLegacyUserAgent - site in legacy sites list`() { val url = "http://duckduckgo.com" assertTrue(testee.useLegacyUserAgent(url)) } @Test - fun whenSubdomainInLegacySitesListThenUseLegacyUserAgent() { + fun `useLegacyUserAgent - subdomain in legacy sites list`() { val url = "http://test.duckduckgo.com" assertTrue(testee.useLegacyUserAgent(url)) } @Test - fun whenSiteNotInLegacySitesListThenDoNotUseLegacyUserAgent() { + fun `useLegacyUserAgent - site not in legacy sites list - does not use legacy user agent`() { val url = "http://example.com" assertFalse(testee.useLegacyUserAgent(url)) diff --git a/user-agent/user-agent-impl/src/test/java/com/duckduckgo/user/agent/impl/UserAgentPluginTest.kt b/user-agent/user-agent-impl/src/test/java/com/duckduckgo/user/agent/impl/UserAgentPluginTest.kt index a726d7572f48..36e7dea0eca0 100644 --- a/user-agent/user-agent-impl/src/test/java/com/duckduckgo/user/agent/impl/UserAgentPluginTest.kt +++ b/user-agent/user-agent-impl/src/test/java/com/duckduckgo/user/agent/impl/UserAgentPluginTest.kt @@ -41,19 +41,19 @@ class UserAgentPluginTest { } @Test - fun whenFeatureNameDoesNotMatchUserAgentThenReturnFalse() { + fun `store - feature name does not match user agent - returns false`() { UserAgentFeatureName.values().filter { it != FEATURE_NAME }.forEach { assertFalse(testee.store(it.value, EMPTY_JSON_STRING)) } } @Test - fun whenFeatureNameMatchesUserAgentThenReturnTrue() { + fun `store - feature name matches user agent - returns true`() { assertTrue(testee.store(FEATURE_NAME_VALUE, EMPTY_JSON_STRING)) } @Test - fun whenFeatureNameMatchesUserAgentAndIsEnabledThenStoreFeatureEnabled() { + fun `store - feature name matches user agent and is enabled - store feature enabled`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/useragent.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -62,7 +62,7 @@ class UserAgentPluginTest { } @Test - fun whenFeatureNameMatchesUserAgentAndIsNotEnabledThenStoreFeatureDisabled() { + fun `store - feature name matches user agent and is not enabled - store feature disabled`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/useragent_disabled.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -71,7 +71,7 @@ class UserAgentPluginTest { } @Test - fun whenFeatureNameMatchesUserAgentAndHasMinSupportedVersionThenStoreMinSupportedVersion() { + fun `whenFeatureNameMatchesUserAgentAndHasMinSupportedVersion - store min supported version`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/useragent_min_supported_version.json") testee.store(FEATURE_NAME_VALUE, jsonString) @@ -80,7 +80,7 @@ class UserAgentPluginTest { } @Test - fun whenFeatureNameMatchesUserAgentThenUpdateAllExistingExceptions() { + fun `whenFeatureNameMatchesUserAgentThenUpdateAllExistingExceptions - store - update all existing exceptions`() { val jsonString = FileUtilities.loadText(javaClass.classLoader!!, "json/useragent.json") val exceptionsCaptor = argumentCaptor>() diff --git a/user-agent/user-agent-impl/src/test/java/com/duckduckgo/user/agent/impl/UserAgentProviderTest.kt b/user-agent/user-agent-impl/src/test/java/com/duckduckgo/user/agent/impl/UserAgentProviderTest.kt index 7bcd10b33e10..3138492561a4 100644 --- a/user-agent/user-agent-impl/src/test/java/com/duckduckgo/user/agent/impl/UserAgentProviderTest.kt +++ b/user-agent/user-agent-impl/src/test/java/com/duckduckgo/user/agent/impl/UserAgentProviderTest.kt @@ -74,84 +74,84 @@ class UserAgentProviderTest { } @Test - fun whenUaRetrievedWithNoParamsThenDeviceStrippedAndApplicationComponentAddedBeforeSafari() { + fun `whenUaRetrievedWithNoParams - device stripped and application component added before safari`() { testee = getUserAgentProvider(Agent.DEFAULT, deviceInfo) val actual = testee.userAgent(DOMAIN) assertTrue("$actual does not match expected regex", ValidationRegex.converted.matches(actual)) } @Test - fun whenMobileUaRetrievedThenDeviceStrippedAndApplicationComponentAddedBeforeSafari() { + fun `whenMobileUaRetrieved - device stripped and application component added before safari - matches expected regex`() { testee = getUserAgentProvider(Agent.DEFAULT, deviceInfo) val actual = testee.userAgent(DOMAIN, isDesktop = false) assertTrue("$actual does not match expected regex", ValidationRegex.converted.matches(actual)) } @Test - fun whenDesktopUaRetrievedThenDeviceStrippedAndApplicationComponentAddedBeforeSafari() { + fun `whenDesktopUaRetrieved - device stripped and application component added before safari - matches desktop regex`() { testee = getUserAgentProvider(Agent.DEFAULT, deviceInfo) val actual = testee.userAgent(DOMAIN, isDesktop = true) assertTrue("$actual does not match expected regex", ValidationRegex.desktop.matches(actual)) } @Test - fun whenMissingAppleWebKitComponentThenUaContainsMozillaAndApplicationAndSafariComponents() { + fun `whenMissingAppleWebKitComponent - ua contains mozilla and application and safari components`() { testee = getUserAgentProvider(Agent.NO_WEBKIT, deviceInfo) val actual = testee.userAgent(DOMAIN, isDesktop = false) assertTrue("$actual does not match expected regex", ValidationRegex.missingWebKit.matches(actual)) } @Test - fun whenMissingSafariComponentThenUaContainsMozillaAndVersionAndApplicationComponents() { + fun `whenMissingSafariComponent - ua contains mozilla and version and application components`() { testee = getUserAgentProvider(Agent.NO_SAFARI, deviceInfo) val actual = testee.userAgent(DOMAIN, isDesktop = false) assertTrue("$actual does not match expected result", ValidationRegex.missingSafari.matches(actual)) } @Test - fun whenMissingVersionComponentThenUaContainsMozillaAndApplicationAndSafariComponents() { + fun `whenMissingVersionComponentThenUaContainsMozillaAndApplicationAndSafariComponents - ua contains mozilla and application and safari components`() { testee = getUserAgentProvider(Agent.NO_VERSION, deviceInfo) val actual = testee.userAgent(DOMAIN, isDesktop = false) assertTrue("$actual does not match expected result", ValidationRegex.noVersion.matches(actual)) } @Test - fun whenDomainSupportsApplicationThenUaAddsApplicationComponentBeforeSafari() { + fun `whenDomainSupportsApplicationThenUaAddsApplicationComponentBeforeSafari - ua adds application component before safari`() { testee = getUserAgentProvider(Agent.DEFAULT, deviceInfo) val actual = testee.userAgent(DOMAIN) assertTrue("$actual does not match expected regex", ValidationRegex.converted.matches(actual)) } @Test - fun whenDomainHasExceptionThenUaIsDefault() { + fun `getUa - domain has exception - default ua`() { testee = getUserAgentProvider(Agent.DEFAULT, deviceInfo) val actual = testee.userAgent(DEFAULT_DOMAIN) assertTrue("$actual does not match expected regex", ValidationRegex.default.matches(actual)) } @Test - fun whenSubdomainHasExceptionThenUaIsDefault() { + fun `getUa - subdomain has exception - default ua`() { testee = getUserAgentProvider(Agent.DEFAULT, deviceInfo) val actual = testee.userAgent(DEFAULT_SUBDOMAIN) assertTrue("$actual does not match expected regex", ValidationRegex.default.matches(actual)) } @Test - fun whenDomainInUnprotectedTemporaryThenUaIsDefault() { + fun `userAgent - domain in unprotected temporary - default ua`() { testee = getUserAgentProvider(Agent.DEFAULT, deviceInfo) val actual = testee.userAgent(UNPROTECTED_DOMAIN) assertTrue("$actual does not match expected regex", ValidationRegex.default.matches(actual)) } @Test - fun whenSubdomainInUnprotectedTemporaryThenUaIsDefault() { + fun `userAgent - subdomain in unprotected temporary - default ua`() { testee = getUserAgentProvider(Agent.DEFAULT, deviceInfo) val actual = testee.userAgent(UNPROTECTED_SUBDOMAIN) assertTrue("$actual does not match expected regex", ValidationRegex.default.matches(actual)) } @Test - fun whenFeatureIsDisabledThenUaIsDefault() { + fun `whenFeatureIsDisabledThenUaIsDefault - ua is default`() { whenever(toggle.isFeatureEnabled(UserAgentFeatureName.UserAgent.value)).thenReturn(false) testee = getUserAgentProvider(Agent.DEFAULT, deviceInfo) val actual = testee.userAgent(DOMAIN) @@ -159,63 +159,63 @@ class UserAgentProviderTest { } @Test - fun whenDomainSupportsVersionThenUaIncludesVersionComponentInUsualLocation() { + fun `getUa - domain supports version - includes version component in usual location`() { testee = getUserAgentProvider(Agent.DEFAULT, deviceInfo) val actual = testee.userAgent(DOMAIN) assertTrue("$actual does not match expected regex", ValidationRegex.converted.matches(actual)) } @Test - fun whenUserAgentIsForASiteThatShouldUseDesktopAgentThenReturnDesktopUserAgent() { + fun `getUserAgent - desktop user agent for specific site - returns desktop user agent`() { testee = getUserAgentProvider(Agent.DEFAULT, deviceInfo) val actual = testee.userAgent(DESKTOP_ONLY_SITE) assertTrue("$actual does not match expected regex", ValidationRegex.desktop.matches(actual)) } @Test - fun whenUserAgentIsForASiteThatShouldUseDesktopAgentButContainsAnExclusionThenDoNotReturnConvertedUserAgent() { + fun `getUserAgent - desktop only site exception - does not return converted user agent`() { testee = getUserAgentProvider(Agent.DEFAULT, deviceInfo) val actual = testee.userAgent(DESKTOP_ONLY_SITE_EXCEPTION) assertTrue("$actual does not match expected regex", ValidationRegex.converted.matches(actual)) } @Test - fun whenUserAgentShouldBeDefaultAndShouldUseDesktopAgentThenReturnDesktopUserAgent() { + fun `whenUserAgentShouldBeDefaultAndShouldUseDesktopAgentThenReturnDesktopUserAgent - return desktop user agent`() { testee = getUserAgentProvider(Agent.DEFAULT, deviceInfo) val actual = testee.userAgent(DEFAULT_DOMAIN, true) assertTrue("$actual does not match expected regex", ValidationRegex.desktop_default.matches(actual)) } @Test - fun whenUserAgentAndUrlAllowedByUserThenReturnDefaultUserAgent() { + fun `whenUserAgentAndUrlAllowedByUserThenReturnDefaultUserAgent - return default user agent`() { testee = getUserAgentProvider(Agent.DEFAULT, deviceInfo) val actual = testee.userAgent(ALLOWED_URL, false) assertTrue("$actual does not match expected regex", ValidationRegex.default.matches(actual)) } @Test - fun whenUserAgentAndUrlAllowedByUserAndIsDesktopThenReturnDefaultDesktopUserAgent() { + fun `getUserAgent - user agent and url allowed by user and is desktop - returns default desktop user agent`() { testee = getUserAgentProvider(Agent.DEFAULT, deviceInfo) val actual = testee.userAgent(ALLOWED_URL, true) assertTrue("$actual does not match expected regex", ValidationRegex.desktop_default.matches(actual)) } @Test - fun whenIsLegacySiteThenReturnLegacyUserAgent() { + fun `isLegacySite - return legacy user agent`() { testee = getUserAgentProvider(Agent.DEFAULT, deviceInfo) val actual = testee.userAgent(DOMAIN, false) assertTrue("$actual does not match expected regex", ValidationRegex.converted.matches(actual)) } @Test - fun whenIsLegacySiteAndIsDesktopThenReturnDesktopLegacyUserAgent() { + fun `isLegacySite - is desktop - return desktop legacy user agent`() { testee = getUserAgentProvider(Agent.DEFAULT, deviceInfo) val actual = testee.userAgent(DOMAIN, true) assertTrue("$actual does not match expected regex", ValidationRegex.desktop.matches(actual)) } @Test - fun whenHasNoExceptionsThenReturnUserAgent() { + fun `getUSERAGENT - no exceptions - returns user agent`() { whenever(userAgent.useLegacyUserAgent(anyString())).thenReturn(false) testee = getUserAgentProvider(Agent.DEFAULT, deviceInfo) val actual = testee.userAgent(DOMAIN, false) @@ -223,7 +223,7 @@ class UserAgentProviderTest { } @Test - fun whenIsDesktopThenReturnDesktopUserAgent() { + fun `isDesktop - return desktop user agent`() { whenever(userAgent.useLegacyUserAgent(anyString())).thenReturn(false) testee = getUserAgentProvider(Agent.DEFAULT, deviceInfo) val actual = testee.userAgent(DOMAIN, true) @@ -231,7 +231,7 @@ class UserAgentProviderTest { } @Test - fun whenIsDesktopAndIsAarch64ThenReturnX86_64DesktopUserAgent() { + fun `getDesktopUserAgent - is desktop and aarch64 - return x86_64 desktop user agent`() { whenever(userAgent.useLegacyUserAgent(anyString())).thenReturn(false) testee = getUserAgentProvider(Agent.DEFAULT, deviceInfo) val actual = testee.userAgent(DOMAIN, true) diff --git a/user-agent/user-agent-store/src/test/java/com/duckduckgo/user/agent/store/RealUserAgentFeatureToggleRepositoryTest.kt b/user-agent/user-agent-store/src/test/java/com/duckduckgo/user/agent/store/RealUserAgentFeatureToggleRepositoryTest.kt index a2ff17f33097..47589d07ce69 100644 --- a/user-agent/user-agent-store/src/test/java/com/duckduckgo/user/agent/store/RealUserAgentFeatureToggleRepositoryTest.kt +++ b/user-agent/user-agent-store/src/test/java/com/duckduckgo/user/agent/store/RealUserAgentFeatureToggleRepositoryTest.kt @@ -33,21 +33,21 @@ class RealUserAgentFeatureToggleRepositoryTest { } @Test - fun whenDeleteAllThenDeleteAllCalled() { + fun `deleteAll - privacy feature toggles store deleted`() { testee.deleteAll() verify(mockPrivacyFeatureTogglesStore).deleteAll() } @Test - fun whenGetThenGetCalled() { + fun `get - get called`() { testee.get(UserAgentFeatureName.UserAgent, true) verify(mockPrivacyFeatureTogglesStore).get(UserAgentFeatureName.UserAgent, true) } @Test - fun whenInsertThenInsertCalled() { + fun `insert - called`() { val privacyFeatureToggle = UserAgentFeatureToggle(UserAgentFeatureName.UserAgent.value, true, null) testee.insert(privacyFeatureToggle) diff --git a/user-agent/user-agent-store/src/test/java/com/duckduckgo/user/agent/store/RealUserAgentRepositoryTest.kt b/user-agent/user-agent-store/src/test/java/com/duckduckgo/user/agent/store/RealUserAgentRepositoryTest.kt index 91e1ff8210da..fac5df7dc084 100644 --- a/user-agent/user-agent-store/src/test/java/com/duckduckgo/user/agent/store/RealUserAgentRepositoryTest.kt +++ b/user-agent/user-agent-store/src/test/java/com/duckduckgo/user/agent/store/RealUserAgentRepositoryTest.kt @@ -51,7 +51,7 @@ class RealUserAgentRepositoryTest { } @Test - fun whenRepositoryIsCreatedThenExceptionsLoadedIntoMemory() { + fun `whenRepositoryIsCreatedThenExceptionsLoadedIntoMemory - exceptions loaded into memory`() { givenUserAgentExceptionsDaoContainExceptions() testee = RealUserAgentRepository( @@ -65,7 +65,7 @@ class RealUserAgentRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = runTest { + fun `updateAll - update all called`() = runTest { testee = RealUserAgentRepository( mockDatabase, @@ -80,7 +80,7 @@ class RealUserAgentRepositoryTest { } @Test - fun whenUpdateAllThenPreviousExceptionsAreCleared() = runTest { + fun `updateAll - previous exceptions cleared`() = runTest { givenUserAgentExceptionsDaoContainExceptions() testee = RealUserAgentRepository( diff --git a/verified-installation/verified-installation-impl/src/test/kotlin/com/duckduckgo/verifiedinstallation/apppackage/VerificationCheckAppPackageImplTest.kt b/verified-installation/verified-installation-impl/src/test/kotlin/com/duckduckgo/verifiedinstallation/apppackage/VerificationCheckAppPackageImplTest.kt index 0b25b20697c7..95775391df78 100644 --- a/verified-installation/verified-installation-impl/src/test/kotlin/com/duckduckgo/verifiedinstallation/apppackage/VerificationCheckAppPackageImplTest.kt +++ b/verified-installation/verified-installation-impl/src/test/kotlin/com/duckduckgo/verifiedinstallation/apppackage/VerificationCheckAppPackageImplTest.kt @@ -29,19 +29,19 @@ class VerificationCheckAppPackageImplTest { private val testee = VerificationCheckAppPackageImpl(appBuildConfig) @Test - fun whenPackageIsDebugVersionThenIsNotVerified() { + fun `isPackageDebug - is not verified`() { whenever(appBuildConfig.applicationId).thenReturn("com.duckduckgo.mobile.android.debug") assertFalse(testee.isProductionPackage()) } @Test - fun whenPackageIsProductionVersionThenIsVerified() { + fun `isProductionPackage - package is production version - is verified`() { whenever(appBuildConfig.applicationId).thenReturn("com.duckduckgo.mobile.android") assertTrue(testee.isProductionPackage()) } @Test - fun whenPackageIsUnrelatedToUsThenIsNotVerified() { + fun `isProductionPackage - package unrelated to us - is not verified`() { whenever(appBuildConfig.applicationId).thenReturn("com.random.app") assertFalse(testee.isProductionPackage()) } diff --git a/verified-installation/verified-installation-impl/src/test/kotlin/com/duckduckgo/verifiedinstallation/buildtype/VerificationCheckBuildTypeImplTest.kt b/verified-installation/verified-installation-impl/src/test/kotlin/com/duckduckgo/verifiedinstallation/buildtype/VerificationCheckBuildTypeImplTest.kt index 99d947471351..08f10a2444be 100644 --- a/verified-installation/verified-installation-impl/src/test/kotlin/com/duckduckgo/verifiedinstallation/buildtype/VerificationCheckBuildTypeImplTest.kt +++ b/verified-installation/verified-installation-impl/src/test/kotlin/com/duckduckgo/verifiedinstallation/buildtype/VerificationCheckBuildTypeImplTest.kt @@ -32,28 +32,28 @@ class VerificationCheckBuildTypeImplTest { private val testee = VerificationCheckBuildTypeImpl(appBuildConfig) @Test - fun whenIsPlayReleaseThenIdentifiedCorrectly() { + fun `isPlayRelease - identified correctly`() { configureFlavor(PLAY) configureAsReleaseBuild() assertTrue(testee.isPlayReleaseBuild()) } @Test - fun whenIsPlayAndNotReleaseThenIdentifiedCorrectly() { + fun `isPlay - not release build - false`() { configureFlavor(PLAY) configureAsDebugBuild() assertFalse(testee.isPlayReleaseBuild()) } @Test - fun whenIsNotPlayFlavorThenIdentifiedCorrectly() { + fun `isNotPlayFlavor - identified correctly`() { configureFlavor(FDROID) configureAsReleaseBuild() assertFalse(testee.isPlayReleaseBuild()) } @Test - fun whenIsNotPlayFlavorAndNotReleaseThenIdentifiedCorrectly() { + fun `isNotPlayFlavorAndNotRelease - identified correctly`() { configureFlavor(FDROID) configureAsDebugBuild() assertFalse(testee.isPlayReleaseBuild()) diff --git a/verified-installation/verified-installation-impl/src/test/kotlin/com/duckduckgo/verifiedinstallation/certificate/VerificationCheckBuildCertificateImplTest.kt b/verified-installation/verified-installation-impl/src/test/kotlin/com/duckduckgo/verifiedinstallation/certificate/VerificationCheckBuildCertificateImplTest.kt index 5782d534b5e4..cee9335f69b2 100644 --- a/verified-installation/verified-installation-impl/src/test/kotlin/com/duckduckgo/verifiedinstallation/certificate/VerificationCheckBuildCertificateImplTest.kt +++ b/verified-installation/verified-installation-impl/src/test/kotlin/com/duckduckgo/verifiedinstallation/certificate/VerificationCheckBuildCertificateImplTest.kt @@ -29,19 +29,19 @@ class VerificationCheckBuildCertificateImplTest { private val testee = VerificationCheckBuildCertificateImpl(certHashExtractor) @Test - fun whenExtractedHashIsNullThenNotAMatch() { + fun `extractHash - null hash - not a match`() { whenever(certHashExtractor.sha256Hash()).thenReturn(null) assertFalse(testee.builtWithVerifiedCertificate()) } @Test - fun whenExtractedHashIsNotProductionHashThenNotAMatch() { + fun `extractCertHash - not production hash - not a match`() { whenever(certHashExtractor.sha256Hash()).thenReturn("ABC-123") assertFalse(testee.builtWithVerifiedCertificate()) } @Test - fun whenExtractedHashIsProductionHashThenIsAMatch() { + fun `extractCertHash - production hash - is a match`() { whenever(certHashExtractor.sha256Hash()).thenReturn(PRODUCTION_SHA_256_HASH) assertTrue(testee.builtWithVerifiedCertificate()) } diff --git a/verified-installation/verified-installation-impl/src/test/kotlin/com/duckduckgo/verifiedinstallation/installsource/VerificationCheckPlayStoreInstallImplTest.kt b/verified-installation/verified-installation-impl/src/test/kotlin/com/duckduckgo/verifiedinstallation/installsource/VerificationCheckPlayStoreInstallImplTest.kt index 6c16db07b2ea..432fa4aaf46a 100644 --- a/verified-installation/verified-installation-impl/src/test/kotlin/com/duckduckgo/verifiedinstallation/installsource/VerificationCheckPlayStoreInstallImplTest.kt +++ b/verified-installation/verified-installation-impl/src/test/kotlin/com/duckduckgo/verifiedinstallation/installsource/VerificationCheckPlayStoreInstallImplTest.kt @@ -31,13 +31,13 @@ class VerificationCheckPlayStoreInstallImplTest { private val testee = VerificationCheckPlayStoreInstallImpl(installSourceExtractor) @Test - fun whenInstallSourceMatchesPlayStorePackageThenIdentifiedAsInstalledFromPlayStore() { + fun `install - install source matches play store package - identified as installed from play store`() { whenever(installSourceExtractor.extract()).thenReturn("com.android.vending") assertTrue(testee.installedFromPlayStore()) } @Test - fun whenInstallSourceDoesNotMatchPlayStorePackageThenNotIdentifiedAsInstalledFromPlayStore() { + fun `installSource - does not match Play Store package - not identified as installed from Play Store`() { whenever(installSourceExtractor.extract()).thenReturn("com.random.app") assertFalse(testee.installedFromPlayStore()) } diff --git a/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/MicrophonePermissionRequestTest.kt b/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/MicrophonePermissionRequestTest.kt index 9f52d5972f90..e8ce61fec1e9 100644 --- a/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/MicrophonePermissionRequestTest.kt +++ b/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/MicrophonePermissionRequestTest.kt @@ -66,7 +66,7 @@ class MicrophonePermissionRequestTest { } @Test - fun whenPermissionRequestResultIsTrueThenInvokeOnPermissionsGranted() { + fun `registerResultsCallback - permission request result is true - invoke on permissions granted`() { var permissionGranted = false testee.registerResultsCallback( mock(), @@ -84,7 +84,7 @@ class MicrophonePermissionRequestTest { } @Test - fun whenPermissionRequestResultIsFalseThenOnPermissionsGrantedNotInvokedAndDeclinePermissionForever() { + fun `registerResultsCallback - permission request result is false - on permissions granted not invoked and decline permission forever`() { whenever(permissionRationale.shouldShow(any())).thenReturn(false) var permissionGranted = false testee.registerResultsCallback(mock(), mock(), mock()) { @@ -99,7 +99,7 @@ class MicrophonePermissionRequestTest { } @Test - fun whenPermissionRequestResultIsFalseThenOnPermissionsGrantedNotInvoked() { + fun `registerResultsCallback - permission request result is false - on permissions granted not invoked`() { whenever(permissionRationale.shouldShow(any())).thenReturn(true) var permissionGranted = false testee.registerResultsCallback(mock(), mock(), mock()) { @@ -114,7 +114,7 @@ class MicrophonePermissionRequestTest { } @Test - fun whenPermissionDeclinedForeverThenLaunchNoMicAccessDialog() { + fun `whenPermissionDeclinedForever - launch no mic access dialog`() { whenever(voiceSearchRepository.getHasPermissionDeclinedForever()).thenReturn(true) testee.registerResultsCallback(mock(), mock(), mock()) { } @@ -125,7 +125,7 @@ class MicrophonePermissionRequestTest { } @Test - fun whenLaunchNoMicAccessDialogDeclinedThenShowRemoveVoiceSearchDialog() { + fun `launch - no mic access dialog declined - show remove voice search dialog`() { whenever(voiceSearchRepository.getHasPermissionDeclinedForever()).thenReturn(true) testee.registerResultsCallback(mock(), mock(), mock()) { } @@ -136,7 +136,7 @@ class MicrophonePermissionRequestTest { } @Test - fun whenRationalDialogNotYetAcceptedThenLaunchRationalDialog() { + fun `launchRationalDialog - rational dialog not yet accepted`() { whenever(voiceSearchRepository.getHasPermissionDeclinedForever()).thenReturn(false) whenever(voiceSearchRepository.getHasAcceptedRationaleDialog()).thenReturn(false) @@ -148,7 +148,7 @@ class MicrophonePermissionRequestTest { } @Test - fun whenRationalDialogAcceptedThenLaunchPermisionRequestFlow() { + fun `launchPermissionRequestFlow - rational dialog accepted - launch permission request flow`() { whenever(voiceSearchRepository.getHasPermissionDeclinedForever()).thenReturn(false) whenever(voiceSearchRepository.getHasAcceptedRationaleDialog()).thenReturn(true) @@ -161,7 +161,7 @@ class MicrophonePermissionRequestTest { } @Test - fun whenRationalDialogShownThenRationalAcceptedInvokedThenFilePixelAndLaunchPermission() { + fun `whenRationalDialogShown - rational accepted invoked - file pixel and launch permission`() { whenever(voiceSearchRepository.getHasPermissionDeclinedForever()).thenReturn(false) whenever(voiceSearchRepository.getHasAcceptedRationaleDialog()).thenReturn(false) testee.registerResultsCallback(mock(), mock(), mock()) { } @@ -175,7 +175,7 @@ class MicrophonePermissionRequestTest { } @Test - fun whenRationalDialogShownThenRationalCancelledInvokedThenFilePixelAndLaunchPermission() { + fun `whenRationalDialogShown - rational cancelled invoked - file pixel and launch permission`() { whenever(voiceSearchRepository.getHasPermissionDeclinedForever()).thenReturn(false) whenever(voiceSearchRepository.getHasAcceptedRationaleDialog()).thenReturn(false) testee.registerResultsCallback(mock(), mock(), mock()) { } @@ -187,7 +187,7 @@ class MicrophonePermissionRequestTest { } @Test - fun whenRationalDialogShownThenRationalCancelledThenShowRemoveVoiceSearchDialog() { + fun `whenRationalDialogShownThenRationalCancelled - show remove voice search dialog`() { whenever(voiceSearchRepository.getHasPermissionDeclinedForever()).thenReturn(false) whenever(voiceSearchRepository.getHasAcceptedRationaleDialog()).thenReturn(false) testee.registerResultsCallback(mock(), mock(), mock()) { } @@ -199,7 +199,7 @@ class MicrophonePermissionRequestTest { } @Test - fun whenNoMicAccessDialogAcceptedThenDisableVoiceSearch() { + fun `whenNoMicAccessDialogAcceptedThenDisableVoiceSearch - voice search disabled`() { var disableVoiceSearch = false whenever(voiceSearchRepository.getHasPermissionDeclinedForever()).thenReturn(false) whenever(voiceSearchRepository.getHasAcceptedRationaleDialog()).thenReturn(false) diff --git a/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/PermissionAwareVoiceSearchLauncherTest.kt b/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/PermissionAwareVoiceSearchLauncherTest.kt index 2d730c21cdde..d91e44e8d611 100644 --- a/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/PermissionAwareVoiceSearchLauncherTest.kt +++ b/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/PermissionAwareVoiceSearchLauncherTest.kt @@ -50,7 +50,7 @@ class PermissionAwareVoiceSearchLauncherTest { } @Test - fun whenPermissionsNotGrantedThenLaunchPermissionRequest() { + fun `whenPermissionsNotGrantedThenLaunchPermissionRequest - permission request launched`() { whenever(voiceSearchPermissionCheck.hasRequiredPermissionsGranted()).thenReturn(false) whenever(voiceSearchAvailability.isVoiceSearchAvailable).thenReturn(true) @@ -61,7 +61,7 @@ class PermissionAwareVoiceSearchLauncherTest { } @Test - fun whenPermissionsNotGrantedAndVoiceSearchNotAvailableThenLaunchPermissionRequest() { + fun `whenPermissionsNotGrantedAndVoiceSearchNotAvailableThenLaunchPermissionRequest - - does not launch permission request`() { whenever(voiceSearchPermissionCheck.hasRequiredPermissionsGranted()).thenReturn(false) whenever(voiceSearchAvailability.isVoiceSearchAvailable).thenReturn(false) @@ -72,7 +72,7 @@ class PermissionAwareVoiceSearchLauncherTest { } @Test - fun whenPermissionsGrantedThenLaunchVoiceSearchActivity() { + fun `whenPermissionsGranted - launch voice search activity`() { whenever(voiceSearchPermissionCheck.hasRequiredPermissionsGranted()).thenReturn(true) whenever(voiceSearchAvailability.isVoiceSearchAvailable).thenReturn(true) @@ -83,7 +83,7 @@ class PermissionAwareVoiceSearchLauncherTest { } @Test - fun whenPermissionsGrantedAndVoiceSearchNotAvailableThenLaunchVoiceSearchActivity() { + fun `whenPermissionsGrantedAndVoiceSearchNotAvailable - launch voice search activity`() { whenever(voiceSearchPermissionCheck.hasRequiredPermissionsGranted()).thenReturn(true) whenever(voiceSearchAvailability.isVoiceSearchAvailable).thenReturn(false) diff --git a/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/RealVoiceSearchActivityLauncherTest.kt b/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/RealVoiceSearchActivityLauncherTest.kt index b89c9da5f82a..19029961de58 100644 --- a/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/RealVoiceSearchActivityLauncherTest.kt +++ b/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/RealVoiceSearchActivityLauncherTest.kt @@ -69,7 +69,7 @@ class RealVoiceSearchActivityLauncherTest { } @Test - fun whenResultFromVoiceSearchBrowserIsOKAndNotEmptyThenEmitVoiceRecognitionSuccess() { + fun `whenResultFromVoiceSearchBrowserIsOKAndNotEmptyThenEmitVoiceRecognitionSuccess - result from voice search browser is OK and not empty - emit voice recognition success`() { var lastKnownEvent: Event? = null testee.registerResultsCallback(mock(), mock(), BROWSER) { lastKnownEvent = it @@ -83,7 +83,7 @@ class RealVoiceSearchActivityLauncherTest { } @Test - fun whenResultFromVoiceSearchBrowserIsErrorThenEmitVoiceRecognitionError() { + fun `whenResultFromVoiceSearchBrowserIsErrorThenEmitVoiceRecognitionError - emit voice recognition error`() { var lastKnownEvent: Event? = null testee.registerResultsCallback(mock(), mock(), BROWSER) { lastKnownEvent = it @@ -97,7 +97,7 @@ class RealVoiceSearchActivityLauncherTest { } @Test - fun whenResultFromVoiceSearchWidgetIsOKAndNotEmptyThenEmitVoiceRecognitionSuccess() { + fun `whenResultFromVoiceSearchWidgetIsOKAndNotEmptyThenEmitVoiceRecognitionSuccess - result from voice search widget is OK and not empty - emit voice recognition success`() { var lastKnownEvent: Event? = null testee.registerResultsCallback(mock(), mock(), WIDGET) { lastKnownEvent = it @@ -111,7 +111,7 @@ class RealVoiceSearchActivityLauncherTest { } @Test - fun whenResultFromVoiceSearchIsOKAndEmptyThenEmitSearchCancelled() { + fun `whenResultFromVoiceSearchIsOKAndEmptyThenEmitSearchCancelled - emit search cancelled`() { var lastKnownEvent: Event? = null testee.registerResultsCallback(mock(), mock(), BROWSER) { lastKnownEvent = it @@ -125,7 +125,7 @@ class RealVoiceSearchActivityLauncherTest { } @Test - fun whenResultFromVoiceSearchIsCancelledThenEmitSearchCancelled() { + fun `whenResultFromVoiceSearchIsCancelledThenEmitSearchCancelled - emit search cancelled`() { var lastKnownEvent: Event? = null testee.registerResultsCallback(mock(), mock(), BROWSER) { lastKnownEvent = it @@ -140,7 +140,7 @@ class RealVoiceSearchActivityLauncherTest { } @Test - fun whenResultFromVoiceSearchIsCancelledSeveralTimesThenShowDialog() { + fun `whenResultFromVoiceSearchIsCancelledSeveralTimesThenShowDialog - show dialog`() { var lastKnownEvent: Event? = null testee.registerResultsCallback(mock(), mock(), BROWSER) { lastKnownEvent = it @@ -156,7 +156,7 @@ class RealVoiceSearchActivityLauncherTest { } @Test - fun whenResultFromVoiceSearchIsCancelledLessThanTwoTimesThenDoNotShowDialog() { + fun `whenResultFromVoiceSearchIsCancelledLessThanTwoTimesThenDoNotShowDialog - do not show dialog`() { var lastKnownEvent: Event? = null testee.registerResultsCallback(mock(), mock(), BROWSER) { lastKnownEvent = it @@ -172,7 +172,7 @@ class RealVoiceSearchActivityLauncherTest { } @Test - fun whenResultFromVoiceSearchIsOkThenResetDismissedCounter() { + fun `whenResultFromVoiceSearchIsOkThenResetDismissedCounter - reset dismissed counter`() { var lastKnownEvent: Event? = null testee.registerResultsCallback(mock(), mock(), BROWSER) { lastKnownEvent = it @@ -187,7 +187,7 @@ class RealVoiceSearchActivityLauncherTest { } @Test - fun whenBrowserVoiceSearchLaunchedThenEmitStartedPixelAndCallLaunchVoiceSearch() { + fun `launch - browser voice search launched - emit started pixel and call launch voice search`() { testee.registerResultsCallback(mock(), mock(), BROWSER) { } testee.launch(mock()) @@ -197,7 +197,7 @@ class RealVoiceSearchActivityLauncherTest { } @Test - fun whenWidgetVoiceSearchLaunchedThenEmitStartedPixelAndCallLaunchVoiceSearch() { + fun `launch - widget voice search launched - emit started pixel and call launch voice search`() { testee.registerResultsCallback(mock(), mock(), WIDGET) { } testee.launch(mock()) diff --git a/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/RealVoiceSearchAvailabilityPixelLoggerTest.kt b/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/RealVoiceSearchAvailabilityPixelLoggerTest.kt index 4dcd1098868b..49f42811573d 100644 --- a/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/RealVoiceSearchAvailabilityPixelLoggerTest.kt +++ b/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/RealVoiceSearchAvailabilityPixelLoggerTest.kt @@ -42,7 +42,7 @@ class RealVoiceSearchAvailabilityPixelLoggerTest { } @Test - fun whenHasNotLoggedAvailabilityThenLogPixel() { + fun `log - has not logged availability - log pixel`() { whenever(voiceSearchRepository.getHasLoggedAvailability()).thenReturn(false) testee.log() @@ -52,7 +52,7 @@ class RealVoiceSearchAvailabilityPixelLoggerTest { } @Test - fun whenHasLoggedAvailabilityThenDoNothing() { + fun `log - has logged availability - do nothing`() { whenever(voiceSearchRepository.getHasLoggedAvailability()).thenReturn(true) testee.log() diff --git a/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/RealVoiceSearchAvailabilityTest.kt b/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/RealVoiceSearchAvailabilityTest.kt index 4725824c5b91..fcf3727060e1 100644 --- a/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/RealVoiceSearchAvailabilityTest.kt +++ b/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/RealVoiceSearchAvailabilityTest.kt @@ -68,7 +68,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenDeviceHasValidConfigThenIsVoiceSearchSupportedTrue() { + fun `setupRemoteConfig - device has valid config - is voice search supported true`() { setupRemoteConfig(voiceSearchEnabled = true, minSdk = 30, excludedManufacturers = emptyArray(), excludedLocales = emptyArray()) setupDeviceConfig(manufacturer = "Google", sdkInt = 31, languageTag = "en-US", isOnDeviceSpeechRecognitionAvailable = true) setupUserSettings(true) @@ -77,7 +77,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenDeviceHasValidConfigAndLanguageIsNotSupportedThenIsVoiceSearchSupportedFalse() { + fun `whenDeviceHasValidConfigAndLanguageIsNotSupported - is voice search supported false`() { whenever(languageSupportChecker.isLanguageSupported()).thenReturn(false) setupRemoteConfig(voiceSearchEnabled = true, minSdk = 30, excludedManufacturers = emptyArray(), excludedLocales = emptyArray()) @@ -88,7 +88,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenDeviceHasValidConfigAndMinVersionIsNullThenIsVoiceSearchSupportedTrue() { + fun `setupRemoteConfig - device has valid config and min version null - is voice search supported true`() { setupRemoteConfig(voiceSearchEnabled = true, minSdk = null, excludedManufacturers = emptyArray(), excludedLocales = emptyArray()) setupDeviceConfig(manufacturer = "Google", sdkInt = 31, languageTag = "en-US", isOnDeviceSpeechRecognitionAvailable = true) setupUserSettings(true) @@ -97,7 +97,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenDeviceHasInvalidLanguageThenIsVoiceSearchSupportedFalse() { + fun `setupDeviceHasInvalidLanguage - is voice search supported false`() { setupRemoteConfig(voiceSearchEnabled = true, minSdk = 30, excludedManufacturers = emptyArray(), excludedLocales = arrayOf("en-UK")) setupDeviceConfig(manufacturer = "Google", sdkInt = 31, languageTag = "en-UK", isOnDeviceSpeechRecognitionAvailable = true) setupUserSettings(true) @@ -106,7 +106,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenDeviceHasInvalidSdkThenIsVoiceSearchSupportedFalse() { + fun `setupDevice - device has invalid SDK - not voice search supported`() { setupRemoteConfig(voiceSearchEnabled = true, minSdk = 33, excludedManufacturers = emptyArray(), excludedLocales = emptyArray()) setupDeviceConfig(manufacturer = "Google", sdkInt = 31, languageTag = "en-UK", isOnDeviceSpeechRecognitionAvailable = true) setupUserSettings(true) @@ -115,7 +115,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenDeviceHasNoSupportForOnDeviceSpeechRecognitionThenIsVoiceSearchSupportedFalse() { + fun `setup - device has no support for on-device speech recognition - is voice search supported false`() { setupRemoteConfig(voiceSearchEnabled = true, minSdk = 30, excludedManufacturers = emptyArray(), excludedLocales = emptyArray()) setupDeviceConfig(manufacturer = "Google", sdkInt = 31, languageTag = "en-US", isOnDeviceSpeechRecognitionAvailable = false) setupUserSettings(true) @@ -124,7 +124,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenManufacturerIsInExcludedManufacturersListThenIsVoiceSearchSupportedFalse() { + fun `setupRemoteConfig - manufacturer in excluded manufacturers list - is voice search supported false`() { setupRemoteConfig(voiceSearchEnabled = true, minSdk = 30, excludedManufacturers = arrayOf("Google"), excludedLocales = emptyArray()) setupDeviceConfig(manufacturer = "Google", sdkInt = 31, languageTag = "en-US", isOnDeviceSpeechRecognitionAvailable = true) setupUserSettings(true) @@ -133,7 +133,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenVoiceSearchNotSupportedThenShouldShowVoiceSearchFalse() { + fun `shouldShowVoiceSearch - voice search not supported - should show voice search false`() { setupRemoteConfig(voiceSearchEnabled = true, minSdk = 30, excludedManufacturers = emptyArray(), excludedLocales = emptyArray()) setupDeviceConfig(manufacturer = "Google", sdkInt = 31, languageTag = "en-US", isOnDeviceSpeechRecognitionAvailable = false) setupUserSettings(true) @@ -149,7 +149,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenVoiceSearchSupportedAndIsEditingUrlAndUserDisabledThenShouldShowVoiceSearchFalse() { + fun `shouldShowVoiceSearch - voice search supported and is editing url and user disabled - should show voice search false`() { setupRemoteConfig(voiceSearchEnabled = true, minSdk = 30, excludedManufacturers = emptyArray(), excludedLocales = emptyArray()) setupDeviceConfig(manufacturer = "Google", sdkInt = 31, languageTag = "en-US", isOnDeviceSpeechRecognitionAvailable = true) setupUserSettings(false) @@ -165,7 +165,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenVoiceSearchSupportedAndIsEditingUrlWithUnchangedQueryThenShouldShowVoiceSearchTrue() { + fun `shouldShowVoiceSearch - voice search supported - shows voice search true`() { setupRemoteConfig(voiceSearchEnabled = true, minSdk = 30, excludedManufacturers = emptyArray(), excludedLocales = emptyArray()) setupDeviceConfig(manufacturer = "Google", sdkInt = 31, languageTag = "en-US", isOnDeviceSpeechRecognitionAvailable = true) @@ -198,7 +198,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenVoiceSearchSupportedAndIsEditingUrlWithChangedQueryThenShouldShowVoiceSearchTrue() { + fun `shouldShowVoiceSearch - voice search supported - shows false`() { setupRemoteConfig(voiceSearchEnabled = true, minSdk = 30, excludedManufacturers = emptyArray(), excludedLocales = emptyArray()) setupDeviceConfig(manufacturer = "Google", sdkInt = 31, languageTag = "en-US", isOnDeviceSpeechRecognitionAvailable = true) @@ -215,7 +215,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenVoiceSearchSupportedAndUrlShownInAddressBarWithNoFocusThenShouldShowVoiceSearchFalse() { + fun `shouldShowVoiceSearch - voice search supported - no focus - show voice search false`() { setupRemoteConfig(voiceSearchEnabled = true, minSdk = 30, excludedManufacturers = emptyArray(), excludedLocales = emptyArray()) setupDeviceConfig(manufacturer = "Google", sdkInt = 31, languageTag = "en-US", isOnDeviceSpeechRecognitionAvailable = true) setupUserSettings(true) @@ -279,7 +279,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenVoiceSearchSupportedAndUrlEmptyThenShouldShowVoiceSearchTrue() { + fun `shouldShowVoiceSearch - voice search supported and url empty - shows voice search true`() { setupRemoteConfig(voiceSearchEnabled = true, minSdk = 30, excludedManufacturers = emptyArray(), excludedLocales = emptyArray()) setupDeviceConfig(manufacturer = "Google", sdkInt = 31, languageTag = "en-US", isOnDeviceSpeechRecognitionAvailable = true) setupUserSettings(true) @@ -295,7 +295,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenVoiceSearchSupportedAndUrlEmptyWithNoFocusThenShouldShowVoiceSearchTrue() { + fun `shouldShowVoiceSearch - voice search supported and url empty with no focus - true`() { setupRemoteConfig(voiceSearchEnabled = true, minSdk = 30, excludedManufacturers = emptyArray(), excludedLocales = emptyArray()) setupDeviceConfig(manufacturer = "Google", sdkInt = 31, languageTag = "en-US", isOnDeviceSpeechRecognitionAvailable = true) setupUserSettings(true) @@ -311,7 +311,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenFeatureIsDisabledThenShouldShowVoiceSearchFalse() { + fun `shouldShowVoiceSearch - feature disabled - shows voice search false`() { setupRemoteConfig(voiceSearchEnabled = false, minSdk = 30, excludedManufacturers = emptyArray(), excludedLocales = emptyArray()) setupDeviceConfig(manufacturer = "Google", sdkInt = 31, languageTag = "en-US", isOnDeviceSpeechRecognitionAvailable = true) setupUserSettings(true) @@ -327,7 +327,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenVoiceSearchSupportedAndSERPShownThenShouldShowVoiceSearchTrue() { + fun `shouldShowVoiceSearch - voice search supported and SERP shown - true`() { setupRemoteConfig(voiceSearchEnabled = true, minSdk = 30, excludedManufacturers = emptyArray(), excludedLocales = emptyArray()) setupDeviceConfig(manufacturer = "Google", sdkInt = 31, languageTag = "en-US", isOnDeviceSpeechRecognitionAvailable = true) setupUserSettings(true) @@ -343,7 +343,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenVoiceSearchSupportedAndIsEditingSERPWithUnchangedQueryThenShouldShowVoiceSearchTrue() { + fun `shouldShowVoiceSearch - voice search supported and is editing SERP with unchanged query - should show voice search true`() { setupRemoteConfig(voiceSearchEnabled = true, minSdk = 30, excludedManufacturers = emptyArray(), excludedLocales = emptyArray()) setupDeviceConfig(manufacturer = "Google", sdkInt = 31, languageTag = "en-US", isOnDeviceSpeechRecognitionAvailable = true) setupUserSettings(true) @@ -359,7 +359,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenVoiceSearchSupportedAndIsEditingSERPWithChangedQueryThenShouldShowVoiceSearchFalse() { + fun `shouldShowVoiceSearch - voice search supported and is editing SERP with changed query - should not show voice search`() { setupRemoteConfig(voiceSearchEnabled = true, minSdk = 30, excludedManufacturers = emptyArray(), excludedLocales = emptyArray()) setupDeviceConfig(manufacturer = "Google", sdkInt = 31, languageTag = "en-US", isOnDeviceSpeechRecognitionAvailable = true) setupUserSettings(true) @@ -375,7 +375,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenVoiceSearchSupportedAndIsEditingSERPWithEmptyQueryThenShouldShowVoiceSearchTrue() { + fun `shouldShowVoiceSearch - voice search supported and editing SERP with empty query - shows voice search true`() { setupRemoteConfig(voiceSearchEnabled = true, minSdk = 30, excludedManufacturers = emptyArray(), excludedLocales = emptyArray()) setupDeviceConfig(manufacturer = "Google", sdkInt = 31, languageTag = "en-US", isOnDeviceSpeechRecognitionAvailable = true) setupUserSettings(true) @@ -391,7 +391,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenModelIsPixel6ThenDefaultUserSettingsTrue() { + fun `setupModel - pixel 6 - default user settings true`() { setupRemoteConfig(voiceSearchEnabled = true, minSdk = 30, excludedManufacturers = emptyArray(), excludedLocales = emptyArray()) setupDeviceConfig(manufacturer = "Google", sdkInt = 31, languageTag = "en-US", isOnDeviceSpeechRecognitionAvailable = true) whenever(voiceSearchRepository.getHasAcceptedRationaleDialog()).thenReturn(true) @@ -402,7 +402,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenDeviceHadNotPreviouslyAcceptedVoiceRationaleThenDefaultUserSettingsFalse() { + fun `whenDeviceHadNotPreviouslyAcceptedVoiceRationale - isVoiceSearchAvailable - default user settings false`() { setupRemoteConfig(voiceSearchEnabled = true, minSdk = 30, excludedManufacturers = emptyArray(), excludedLocales = emptyArray()) setupDeviceConfig(manufacturer = "Google", sdkInt = 31, languageTag = "en-US", isOnDeviceSpeechRecognitionAvailable = true) whenever(voiceSearchRepository.getHasAcceptedRationaleDialog()).thenReturn(false) diff --git a/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/language/RealLanguageSupportCheckerTest.kt b/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/language/RealLanguageSupportCheckerTest.kt index ffb68d5ceb13..90fe09676267 100644 --- a/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/language/RealLanguageSupportCheckerTest.kt +++ b/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/language/RealLanguageSupportCheckerTest.kt @@ -59,7 +59,7 @@ class RealLanguageSupportCheckerTest { } @Test - fun whenLanguageInstalledThenLanguageIsSupported() { + fun `whenLanguageInstalledThenLanguageIsSupported - language support checker - is supported`() { instantiate() val callbackCaptor = argumentCaptor() @@ -74,7 +74,7 @@ class RealLanguageSupportCheckerTest { } @Test - fun whenLanguageNotInstalledThenLanguageIsNotSupported() { + fun `whenLanguageNotInstalledThenLanguageIsNotSupported - language not installed - is not supported`() { instantiate() val callbackCaptor = argumentCaptor() @@ -89,7 +89,7 @@ class RealLanguageSupportCheckerTest { } @Test - fun whenSpeechRecognizerErrorThenLanguageIsNotSupported() { + fun `whenSpeechRecognizerErrorThenLanguageIsNotSupported - language not supported`() { instantiate() val callbackCaptor = argumentCaptor() @@ -101,7 +101,7 @@ class RealLanguageSupportCheckerTest { } @Test - fun whenSdkLowerThanTiramisuThenLanguageIsNotSupported() { + fun `getAvailability - sdk tiramisu not supported - language not supported`() { val config = VoiceSearchAvailabilityConfig("Samsung", 32, "en-US", true) whenever(configProvider.get()).thenReturn(config) diff --git a/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/listeningmode/VoiceSearchViewModelTest.kt b/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/listeningmode/VoiceSearchViewModelTest.kt index 56af2bed2071..98c226e2814d 100644 --- a/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/listeningmode/VoiceSearchViewModelTest.kt +++ b/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/listeningmode/VoiceSearchViewModelTest.kt @@ -48,21 +48,21 @@ class VoiceSearchViewModelTest { } @Test - fun whenStartThenStartSpeechRecognizer() { + fun `start - start speech recognizer`() { testee.startVoiceSearch() verify(speechRecognizer).start(any()) } @Test - fun whenStopThenStopSpeechRecognizer() { + fun `stop - speech recognizer stopped`() { testee.stopVoiceSearch() verify(speechRecognizer).stop() } @Test - fun whenStartThenEmitInitialViewState() = runTest { + fun `start - view state initial - empty`() = runTest { testee.startVoiceSearch() testee.viewState().test { @@ -72,7 +72,7 @@ class VoiceSearchViewModelTest { } @Test - fun whenPartialResultsReceivedThenEmitNewViewState() = runTest { + fun `startVoiceSearch - view state updated - partial results received`() = runTest { val captor = argumentCaptor<(Event) -> Unit>() testee.startVoiceSearch() verify(speechRecognizer).start(captor.capture()) @@ -90,7 +90,7 @@ class VoiceSearchViewModelTest { } @Test - fun whenPartialResultsExceeds30WordsThenEmitNewViewStateAndEmitHandleSpeechRecognitionSuccessCommand() = runTest { + fun `startVoiceSearch - view state updated - handle speech recognition success command emitted`() = runTest { val result = "fermentum leo vel orci porta non pulvinar neque laoreet suspendisse interdum consectetur libero id faucibus nisl tincidunt " + "eget nullam non nisi est sit amet facilisis magna etiam tempor orci eu lobortis" val captor = argumentCaptor<(Event) -> Unit>() @@ -111,7 +111,7 @@ class VoiceSearchViewModelTest { } @Test - fun whenVolumeUpdateReceivedThenEmitUpdateVoiceIndicatorCommand() = runTest { + fun `whenVolumeUpdateReceived - emit update voice indicator command`() = runTest { val captor = argumentCaptor<(Event) -> Unit>() testee.startVoiceSearch() verify(speechRecognizer).start(captor.capture()) @@ -125,7 +125,7 @@ class VoiceSearchViewModelTest { } @Test - fun whenRecognitionSuccessThenEmitHandleSpeechRecognitionSuccessCommand() = runTest { + fun `startVoiceSearch - recognition success - emit handle speech recognition success command`() = runTest { val captor = argumentCaptor<(Event) -> Unit>() testee.startVoiceSearch() verify(speechRecognizer).start(captor.capture()) @@ -139,7 +139,7 @@ class VoiceSearchViewModelTest { } @Test - fun whenRecognitionTimedoutWithNoPartialResultThenEmitTerminateVoiceSearch() = runTest { + fun `startVoiceSearch - recognition timed out with no partial result - emit terminate voice search`() = runTest { val captor = argumentCaptor<(Event) -> Unit>() testee.startVoiceSearch() verify(speechRecognizer).start(captor.capture()) @@ -153,7 +153,7 @@ class VoiceSearchViewModelTest { } @Test - fun whenRecognitionFailsThenEmitTerminateVoiceSearch() = runTest { + fun `startVoiceSearch - recognition fails - emit terminate voice search`() = runTest { val captor = argumentCaptor<(Event) -> Unit>() testee.startVoiceSearch() verify(speechRecognizer).start(captor.capture()) @@ -167,7 +167,7 @@ class VoiceSearchViewModelTest { } @Test - fun whenRecognitionTimedoutWithPartialResultThenEmiHandleSpeechRecognitionSuccessCommand() = runTest { + fun `startVoiceSearch - recognition timed out with partial result - handle speech recognition success command`() = runTest { val captor = argumentCaptor<(Event) -> Unit>() testee.startVoiceSearch() verify(speechRecognizer).start(captor.capture()) @@ -182,7 +182,7 @@ class VoiceSearchViewModelTest { } @Test - fun whenViewModelRestartedWithNoPartiaLResultThenEmitViewStateWithNoUnsentResult() = runTest { + fun `startVoiceSearch - view state restarted - emits view state with no unsent result`() = runTest { val captor = argumentCaptor<(Event) -> Unit>() testee.startVoiceSearch() verify(speechRecognizer).start(captor.capture()) @@ -196,7 +196,7 @@ class VoiceSearchViewModelTest { } @Test - fun whenPartialResultReceivedAndViewModelRestartedThenEmitViewStateWithUnsentResult() = runTest { + fun `startVoiceSearch - view state updated - emits unsent result`() = runTest { val captor = argumentCaptor<(Event) -> Unit>() testee.startVoiceSearch() verify(speechRecognizer).start(captor.capture()) @@ -211,7 +211,7 @@ class VoiceSearchViewModelTest { } @Test - fun whenViewModelRestartedAndRecognitionSuccessEmittedThenEmitViewStateWithAppendedResultAndUnsentResult() = runTest { + fun `startVoiceSearch - view model restarted - emits view state with appended result and unsent result`() = runTest { val captor = argumentCaptor<(Event) -> Unit>() testee.startVoiceSearch() verify(speechRecognizer).start(captor.capture()) @@ -227,7 +227,7 @@ class VoiceSearchViewModelTest { } @Test - fun whenUserInitiatesSearchCompleteThenEmitHandleSpeechRecognitionSuccessCommand() = runTest { + fun `startVoiceSearch - user initiates search complete - emit handle speech recognition success command`() = runTest { val captor = argumentCaptor<(Event) -> Unit>() testee.startVoiceSearch() verify(speechRecognizer).start(captor.capture()) diff --git a/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/remoteconfig/RealVoiceSearchFeatureRepositoryTest.kt b/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/remoteconfig/RealVoiceSearchFeatureRepositoryTest.kt index d4959cb4bbf3..679039a15564 100644 --- a/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/remoteconfig/RealVoiceSearchFeatureRepositoryTest.kt +++ b/voice-search/voice-search-impl/src/test/java/com/duckduckgo/voice/impl/remoteconfig/RealVoiceSearchFeatureRepositoryTest.kt @@ -46,7 +46,7 @@ class RealVoiceSearchFeatureRepositoryTest { } @Test - fun whenRepositoryIsCreatedThenExceptionsLoadedIntoMemory() = runTest { + fun `whenRepositoryIsCreatedThenExceptionsLoadedIntoMemory - exceptions loaded into memory`() = runTest { givenDaoContainsExceptions() repository = RealVoiceSearchFeatureRepository(mockDatabase, TestScope(), coroutineRule.testDispatcherProvider, isMainProcess = true) @@ -61,7 +61,7 @@ class RealVoiceSearchFeatureRepositoryTest { } @Test - fun whenUpdateAllExceptionsIsCalledThenDatabaseIsUpdated() = runTest { + fun `updateAll - database updated`() = runTest { repository = RealVoiceSearchFeatureRepository(mockDatabase, TestScope(), coroutineRule.testDispatcherProvider, isMainProcess = true) val manufacturerExceptions = listOf(Manufacturer("manufacturer")) @@ -78,7 +78,7 @@ class RealVoiceSearchFeatureRepositoryTest { } @Test - fun whenUpdateAllThenPreviousExceptionsAreCleared() = runTest { + fun `updateAll - previous exceptions cleared`() = runTest { givenDaoContainsExceptions() repository = RealVoiceSearchFeatureRepository(mockDatabase, TestScope(), coroutineRule.testDispatcherProvider, isMainProcess = true) diff --git a/voice-search/voice-search-store/src/test/java/com/duckduckgo/voice/store/RealVoiceSearchRepositoryTest.kt b/voice-search/voice-search-store/src/test/java/com/duckduckgo/voice/store/RealVoiceSearchRepositoryTest.kt index 8264c5d98737..026a3d39bbfe 100644 --- a/voice-search/voice-search-store/src/test/java/com/duckduckgo/voice/store/RealVoiceSearchRepositoryTest.kt +++ b/voice-search/voice-search-store/src/test/java/com/duckduckgo/voice/store/RealVoiceSearchRepositoryTest.kt @@ -35,7 +35,7 @@ class RealVoiceSearchRepositoryTest { } @Test - fun whenRationalDialogIsAcceptedThenGetHasAcceptedRationaleDialogShouldBeTrue() { + fun `acceptRationaleDialog - has accepted rationale dialog - true`() { assertFalse(testee.getHasAcceptedRationaleDialog()) testee.acceptRationaleDialog() @@ -44,7 +44,7 @@ class RealVoiceSearchRepositoryTest { } @Test - fun whenPermissionDeclinedForeverThenGetHasPermissionDeclinedForeverShouldBeTrue() { + fun `get - permission declined forever - true`() { assertFalse(testee.getHasPermissionDeclinedForever()) testee.declinePermissionForever() @@ -53,7 +53,7 @@ class RealVoiceSearchRepositoryTest { } @Test - fun whenAvailabilityIsLoggedThengetHasLoggedAvailabilityShouldBeTrue() { + fun `saveLoggedAvailability - availability logged - has logged availability`() { assertFalse(testee.getHasLoggedAvailability()) testee.saveLoggedAvailability() @@ -62,7 +62,7 @@ class RealVoiceSearchRepositoryTest { } @Test - fun whenSetVoiceSearchEnabledThenIsVoiceSearchEnabledShouldBeTrue() { + fun `setVoiceSearchEnabled - is voice search enabled should be true`() { assertFalse(testee.isVoiceSearchUserEnabled(false)) testee.setVoiceSearchUserEnabled(true) @@ -71,14 +71,14 @@ class RealVoiceSearchRepositoryTest { } @Test - fun whenSetVoiceSearchEnabledThenListenerShouldBeCalled() { + fun `setVoiceSearchEnabled - listener should be called`() { testee.setVoiceSearchUserEnabled(true) assertTrue(voiceSearchStatusListener.statusChanged) } @Test - fun whenDismissVoiceSearchThenCountVoiceSearchDismissedValueShouldIncrease() { + fun `dismissVoiceSearch - count voice search dismissed value should increase`() { assertEquals(0, testee.countVoiceSearchDismissed()) testee.dismissVoiceSearch() diff --git a/web-compat/web-compat-impl/src/test/java/com/duckduckgo/webcompat/impl/WebCompatContentScopeConfigPluginTest.kt b/web-compat/web-compat-impl/src/test/java/com/duckduckgo/webcompat/impl/WebCompatContentScopeConfigPluginTest.kt index cb795109b274..4b349eab03d8 100644 --- a/web-compat/web-compat-impl/src/test/java/com/duckduckgo/webcompat/impl/WebCompatContentScopeConfigPluginTest.kt +++ b/web-compat/web-compat-impl/src/test/java/com/duckduckgo/webcompat/impl/WebCompatContentScopeConfigPluginTest.kt @@ -37,13 +37,13 @@ class WebCompatContentScopeConfigPluginTest { } @Test - fun whenGetConfigThenReturnCorrectlyFormattedJson() { + fun `getConfig - get config then return correctly formatted json`() { whenever(mockWebCompatRepository.getWebCompatEntity()).thenReturn(WebCompatEntity(json = config)) assertEquals("\"webCompat\":$config", testee.config()) } @Test - fun whenGetPreferencesThenReturnNull() { + fun `getPreferences - null`() { assertNull(testee.preferences()) } diff --git a/web-compat/web-compat-impl/src/test/java/com/duckduckgo/webcompat/impl/WebCompatFeaturePluginTest.kt b/web-compat/web-compat-impl/src/test/java/com/duckduckgo/webcompat/impl/WebCompatFeaturePluginTest.kt index b2aaf01d02df..2df683777539 100644 --- a/web-compat/web-compat-impl/src/test/java/com/duckduckgo/webcompat/impl/WebCompatFeaturePluginTest.kt +++ b/web-compat/web-compat-impl/src/test/java/com/duckduckgo/webcompat/impl/WebCompatFeaturePluginTest.kt @@ -36,19 +36,19 @@ class WebCompatFeaturePluginTest { } @Test - fun whenFeatureNameDoesNotMatchWebCompatThenReturnFalse() { + fun `store - feature name does not match webcompat - returns false`() { WebCompatFeatureName.values().filter { it != FEATURE_NAME }.forEach { assertFalse(testee.store(it.value, JSON_STRING)) } } @Test - fun whenFeatureNameMatchesWebCompatThenReturnTrue() { + fun `store - feature name matches web compat - true`() { assertTrue(testee.store(FEATURE_NAME_VALUE, JSON_STRING)) } @Test - fun whenFeatureNameMatchesWebCompatThenUpdateAll() { + fun `whenFeatureNameMatchesWebCompatThenUpdateAll - update all - json string`() { testee.store(FEATURE_NAME_VALUE, JSON_STRING) val captor = argumentCaptor() verify(mockWebCompatRepository).updateAll(captor.capture()) diff --git a/web-compat/web-compat-store/src/test/java/com/duckduckgo/webcompat/store/WebCompatRepositoryTest.kt b/web-compat/web-compat-store/src/test/java/com/duckduckgo/webcompat/store/WebCompatRepositoryTest.kt index 77ef963326c4..600ae72f062f 100644 --- a/web-compat/web-compat-store/src/test/java/com/duckduckgo/webcompat/store/WebCompatRepositoryTest.kt +++ b/web-compat/web-compat-store/src/test/java/com/duckduckgo/webcompat/store/WebCompatRepositoryTest.kt @@ -42,7 +42,7 @@ class WebCompatRepositoryTest { } @Test - fun whenInitializedAndDoesNotHaveStoredValueThenLoadEmptyJsonToMemory() = + fun `getWebCompatEntity - initialized and no stored value - load empty json to memory`() = runTest { testee = RealWebCompatRepository( @@ -57,7 +57,7 @@ class WebCompatRepositoryTest { } @Test - fun whenInitializedAndHasStoredValueThenLoadStoredJsonToMemory() = + fun `getWebCompatEntity - initialized and has stored value - loads stored json to memory`() = runTest { whenever(mockWebCompatDao.get()).thenReturn(webCompatEntity) testee = @@ -73,7 +73,7 @@ class WebCompatRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - update all called`() = runTest { testee = RealWebCompatRepository( diff --git a/windows/windows-impl/src/test/java/com/duckduckgo/windows/impl/ui/WindowsViewModelTest.kt b/windows/windows-impl/src/test/java/com/duckduckgo/windows/impl/ui/WindowsViewModelTest.kt index 8208000ec803..e162fda4aad3 100644 --- a/windows/windows-impl/src/test/java/com/duckduckgo/windows/impl/ui/WindowsViewModelTest.kt +++ b/windows/windows-impl/src/test/java/com/duckduckgo/windows/impl/ui/WindowsViewModelTest.kt @@ -45,7 +45,7 @@ internal class WindowsViewModelTest { } @Test - fun whenOnShareClickedThenEmitShareLinkCommand() = runTest { + fun `onShareClicked - emit share link command`() = runTest { testee.commands.test { testee.onShareClicked() assertEquals(ShareLink, awaitItem()) @@ -53,7 +53,7 @@ internal class WindowsViewModelTest { } @Test - fun whenOnGoToMacClickedThenEmitGoToMacClientSettingsCommand() = runTest { + fun `onGoToMacClicked - emit GoToMacClientSettings command`() = runTest { testee.commands.test { testee.onGoToMacClicked() assertEquals(GoToMacClientSettings, awaitItem())