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..ec5ffbad86e5 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 - return 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 - return 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 `store - feature name matches ad click attribution - 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..564983dc5813 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 - ad click feature name - return 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`() = runTest { givenAdCLickFeatureIsEnabled() @@ -62,7 +62,7 @@ class AdClickFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsAdCLickFeatureThenReturnFalseWhenDisabled() = + fun `isEnabled - ad click feature disabled - return false`() = runTest { givenAdCLickFeatureIsDisabled() @@ -72,7 +72,7 @@ class AdClickFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsAdCLickFeatureThenReturnDefaultValueIfFeatureDoesNotExist() = + fun `isEnabled - ad click feature does not exist - return default value`() = runTest { val defaultValue = true givenAdCLickFeatureReturnsDefaultValue(defaultValue) @@ -84,7 +84,7 @@ class AdClickFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsAdCLickFeatureAndAppVersionEqualToMinSupportedVersionThenReturnTrueWhenEnabled() = + fun `isEnabled - ad click feature and app version equal to min supported version - return true`() = 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 - returns true`() = runTest { givenAdCLickFeatureIsEnabled() givenAppVersionIsGreaterThanMinSupportedVersion() @@ -106,7 +106,7 @@ class AdClickFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsAdCLickFeatureAndAppVersionIsSmallerThanMinSupportedVersionThenReturnFalseWhenEnabled() = + fun `isEnabled - ad click feature and app version smaller than min supported version - return false`() = 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..3fb0a7f6f280 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 - call clearAllExpiredAsync - return 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..77ca942f529b 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 `setAdDomainTldPlusOne - same domain retrieved`() { testee.setAdDomainTldPlusOne("host") assertEquals("host", testee.getAdDomainTldPlusOne()) } @Test - fun whenRemoveAdDomainForActiveTabCalledThenAdDomainForTabIsRemoved() { + fun `removeAdDomain - active tab - ad domain removed`() { testee.setAdDomainTldPlusOne("host") assertEquals("host", testee.getAdDomainTldPlusOne()) @@ -50,7 +50,7 @@ class DuckDuckGoAdClickDataTest { } @Test - fun whenRemoveExemptionForActiveTabCalledThenAllExemptionForTabAreRemoved() { + fun `removeExemption - active tab - 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 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..c2c6e46be4ad 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 - non-null URL and not main frame - return`() { testee.detectAdClick(url = "url", isMainFrame = false) verifyNoInteractions(mockAdClickData) } @Test - fun whenDetectAdClickCalledForAdUrlAndIsMainFrameAndOnlyHeuristicDetectionEnabledThenUpdateAdDomainWithEmptyString() { + fun `detectAdClick - ad URL, main frame, 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 URL and main frame with only 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 url, main frame, detections enabled, domain present - update ad domain`() { 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 url, main frame, detections enabled, no domain - 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, main frame, 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 main frame 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 - with source tab info - 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 - exemption exists - set active tab and do not propagate exemption`() { 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 URL - 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 URL and SERP domain match - 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 URL and SERP domain mismatch - domain detection pixel sent`() { 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 - ad URL and SERP domain and broken URL domain - domain detection pixel sent with SERP only`() { whenever(mockAdClickData.getAdDomainTldPlusOne()).thenReturn("landing_page") testee.detectAdDomain(url = "https://") @@ -241,7 +241,7 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenDetectAdDomainCalledWithAdUrlAndNoSerpDomainAndUrlDomainThenDomainDetectionPixelSentWithHeuristicOnly() { + fun `detectAdDomain - ad URL with no SERP domain and URL domain - domain detection pixel sent 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 - ad URL with 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 true`() { whenever(mockAdClickData.getAdDomainTldPlusOne()).thenReturn("") whenever(mockAdClickAttribution.isHeuristicDetectionEnabled()).thenReturn(true) @@ -284,7 +284,7 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenDetectAdDomainCalledAndDomainDetectionEnabledThenDomainDetectionPixelSentWithDomainDetectionToTrue() { + fun `detectAdDomain - domain detection enabled - pixel sent with domain detection true`() { whenever(mockAdClickData.getAdDomainTldPlusOne()).thenReturn("") whenever(mockAdClickAttribution.isDomainDetectionEnabled()).thenReturn(true) @@ -299,7 +299,7 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenClearTabIdCalledForTabThenRemoveDataForTab() { + fun `clearTabId - called for tab - 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 `clearAllExpiredAsync - remove all expired data`() { testee.clearAllExpiredAsync() verify(mockAdClickData).removeAllExpired() } @Test - fun whenIsExemptionCalledWithDuckDuckGoDocumentUrlThenReturnFalse() { + fun `isExemption - DuckDuckGo document URL - return false`() { val documentUrl = "https://duckduckgo.com" val url = "https://tracker.com" @@ -332,7 +332,7 @@ class DuckDuckGoAdClickManagerTest { } @Test - fun whenIsExemptionCalledWithUrlMatchingExpiredExemptionThenReturnFalse() { + fun `isExemption - url matching expired exemption - return 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 - url not matching expired exemption and not matching tracker - return 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 - 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..e3d9753f52d4 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 - 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 - 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 and url matches link format and ad domain parameter name - 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 and only domain detection enabled and url matches link format - returns true`() { givenFeatureEnabled() givenDetectionsEnabled(domainEnabled = true, heuristicEnabled = false) whenever(mockAdClickAttributionRepository.linkFormats).thenReturn( @@ -240,7 +240,7 @@ class RealAdClickAttributionTest { } @Test - fun whenFeatureEnabledAndOnlyHeuristicDetectionEnabledAndUrlMatchesLinkFormatThenAdClickReturnsTrue() { + fun `isAdClick - heuristic detection enabled and url matches link format - returns true`() { givenFeatureEnabled() givenDetectionsEnabled(domainEnabled = false, heuristicEnabled = true) 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..8fd2bef9dbd1 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 fireCountPixel with correct param name - 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..d3a1797db7eb 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 - return false`() { val exemption = null val result = testee.fireAdClickActivePixel(exemption) @@ -65,7 +65,7 @@ class RealAdClickPixelsTest { } @Test - fun whenFireAdClickActivePixelCalledWithNonNullExemptionAndPixelAlreadyFiredThenReturnFalse() { + fun `fireAdClickActivePixel - non-null exemption and pixel already fired - return false`() { val exemption = Exemption( hostTldPlusOne = "ad_domain", navigationExemptionDeadline = 0L, @@ -79,7 +79,7 @@ class RealAdClickPixelsTest { } @Test - fun whenFireAdClickActivePixelCalledWithNonNullExemptionAndPixelNotAlreadyFiredThenFirePixelAndReturnTrue() { + fun `fireAdClickActivePixel - non-null exemption and pixel not already fired - fire pixel and return 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 - 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 - disabled heuristic detection - pixel sent with correct param`() { val savedAdDomain = "" val urlAdDomain = "" val heuristicEnabled = false @@ -208,7 +208,7 @@ class RealAdClickPixelsTest { } @Test - fun whenFireAdClickDetectedPixelCalledWithDisabledDomainDetectionThenPixelSentWithCorrectParam() { + fun `fireAdClickDetectedPixel - disabled domain detection - pixel sent with correct param`() { val savedAdDomain = "" val urlAdDomain = "" val heuristicEnabled = true @@ -227,7 +227,7 @@ class RealAdClickPixelsTest { } @Test - fun whenUpdateCountPixelCalledThenSharedPrefUpdated() { + fun `updateCountPixel - sharedPref 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 - zero count - 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 - non-zero count and 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 `fireCountPixel - non-zero count and 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 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..7df56816a3ac 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 `repository creation - 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 - update all called`() = runTest { testee.updateAll( linkFormats = listOf(), @@ -79,7 +79,7 @@ class RealAdClickAttributionRepositoryTest { } @Test - fun whenUpdateAllThenPreviousListsAreCleared() = + fun `updateAll - previous lists are 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..35b7ef936ec8 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 - exception 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 - interrupted exception - 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..7d923f2dc6cb 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 `sanitizeStackTrace - redact PII - success`() { 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..4d8f223a171f 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 `evaluate - AppTP matching attribute - correct value`() = runTest { whenever(appTrackingProtection.isOnboarded()).thenReturn(false) assertTrue(attribute.evaluate(AppTPMatchingAttribute(false))!!) @@ -42,14 +42,14 @@ class AppTPRMFMatchingAttributeTest { } @Test - fun mapAppTPMatchingAttributeKeyThenReturnAppTPMatchingAttribute() = runTest { + fun `map - AppTPMatchingAttributeKey - return AppTPMatchingAttribute`() = 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 `map - no AppTP 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/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..ac120d998410 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 - third consecutive time - restart app tracking protection`() = runTest { whenever(networkProtectionState.isEnabled()).thenReturn(false) whenever(appTrackingProtection.isEnabled()).thenReturn(true) @@ -83,7 +83,7 @@ class AppTPVpnConnectivityLossListenerTest { } @Test - fun whenRestartOnConnectivityLossIsDisabledThenNoop() = runTest { + fun `onVpnConnectivityLoss - restart on connectivity loss disabled - noop`() = 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 - NetP 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 - appTP disabled - noop`() = 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..f21b8889ab03 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 `evaluate - third party tracker - 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 - overridden system app not 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) @@ -130,7 +130,7 @@ class AppTrackerDetectorTest { } @Test - fun whenEvaluateThirdPartyTrackerAndSystemAppAndInExclusionListAndReturnNull() { + fun `evaluate - third party tracker, system app, 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) @@ -147,7 +147,7 @@ class AppTrackerDetectorTest { } @Test - fun whenEvaluateThirdPartyTrackerAndOverriddenSystemAppAndInExclusionListAndReturnNull() { + fun `evaluate - overridden system app 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) @@ -168,7 +168,7 @@ class AppTrackerDetectorTest { } @Test - fun whenEvaluateThirdPartyTrackerAndOverriddenSystemAppThenReturnTracker() { + fun `evaluate - 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 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 - manually protected third party tracker - 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 - manually protected and 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 `evaluate - third party tracker from unknown app - 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 `evaluate - third party tracker from DDG app - 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. @@ -313,7 +313,7 @@ class AppTrackerDetectorTest { } @Test - fun whenEvaluateFirstPartyTrackerThenReturnNull() { + fun `evaluate - first party tracker - 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 `evaluate - appTp disabled - return 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..20fb1c2a8a56 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 app 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..894e91f15d44 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 `registerFeature - features registered - vpn started`() = runTest { vpnFeaturesRegistry.registerFeature(TestVpnFeatures.FOO) vpnFeaturesRegistry.registerFeature(TestVpnFeatures.BAR) @@ -76,7 +76,7 @@ class VpnFeaturesRegistryImplTest { } @Test - fun whenIsFeatureRegisteredAndFeaturesAreRegisteredAndVpnIsRunningThenReturnTrue() = runTest { + fun `isFeatureRunning - features registered and VPN running - return 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 - return false`() = runTest { vpnFeaturesRegistry.registerFeature(TestVpnFeatures.FOO) } @Test - fun whenIsAnyFeatureRegisteredAndFeaturesAreRegisteredThenReturnTrue() = runTest { + fun `isAnyFeatureRunning - features are registered - return true`() = runTest { vpnFeaturesRegistry.registerFeature(TestVpnFeatures.FOO) assertTrue(vpnFeaturesRegistry.isAnyFeatureRunning()) @@ -99,7 +99,7 @@ class VpnFeaturesRegistryImplTest { } @Test - fun whenIsAnyFeatureRegisteredAndFeaturesAreRegisteredAndVpnDisabledThenReturnFalse() = runTest { + fun `isAnyFeatureRunning - features registered and VPN disabled - return false`() = runTest { vpnFeaturesRegistry.registerFeature(TestVpnFeatures.FOO) vpnServiceWrapper.stopService() @@ -108,7 +108,7 @@ class VpnFeaturesRegistryImplTest { } @Test - fun whenUnregisterFeatureThenFeatureIsUnregistered() = runTest { + fun `unregisterFeature - feature is unregistered`() = runTest { vpnFeaturesRegistry.registerFeature(TestVpnFeatures.FOO) vpnFeaturesRegistry.unregisterFeature(TestVpnFeatures.FOO) @@ -116,7 +116,7 @@ class VpnFeaturesRegistryImplTest { } @Test - fun whenUnregisterLastFeatureThenVpnIsNotRunning() = runTest { + fun `unregisterFeature - last feature - 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 `refreshFeature - 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..2cc4575b8712 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 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 `userMadeChanges - no manually excluded apps - returns false`() = runTest { manuallyExcludedApps.send(listOf()) assertFalse(viewModel.userMadeChanges()) } @Test - fun whenPackageNameIsExcludedThenProtectedAppsExcludesIt() = runTest { + fun `onAppProtectionDisabled - package name excluded - protected apps excludes it`() = runTest { val packageName = "com.package.name" val appName = "App" val report = true @@ -107,7 +107,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenAppProtectionisSubmittedAndReportIsSkippedThenSkipPixelIsSent() = runTest { + fun `onAppProtectionDisabled - report is skipped - skip pixel is sent`() = runTest { val packageName = "com.package.name" val appName = "App" val report = false @@ -118,7 +118,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenAppProtectionisSubmittedAndReportIsSentThenSubmitPixelIsSent() = runTest { + fun `onAppProtectionDisabled - report is sent - submit pixel is sent`() = runTest { val packageName = "com.package.name" val appName = "App" val report = true @@ -129,7 +129,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenAppProtectionisSubmittedAndReportIsSentThenReportCommandIsSent() = runTest { + fun `onAppProtectionDisabled - report is 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 - app has no issues - enables protection`() = runTest { val packageName = "com.package.name" viewModel.onAppProtectionEnabled(packageName) @@ -152,7 +152,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenPackageNameIsEnabledAndAppHasIssuesThenProtectedAppsEnablesItAndSendsPixel() = runTest { + fun `onAppProtectionEnabled - app has issues - enables protection and 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 and 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 - changes were made - vpn is 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 is not restarted`() = runTest { viewModel.commands().test { manuallyExcludedApps.send(listOf()) viewModel.onResume(TestLifecycleOwner()) @@ -205,7 +205,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenAppWithKnownIssuesIsEnabledThenEnableProtectionDialogIsShown() = runTest { + fun `onAppProtectionChanged - app with known issues enabled - show enable protection dialog`() = 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 - show enable protection dialog`() = 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 - app with no issues enabled - 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 disabled 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 `getProtectedApps - all apps filter applied - 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 - protected only filter applied - only protected apps returned`() = 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 with all apps unprotected - 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 - unprotected only filter applied - headers are returned`() = runTest { val protectedApps = listOf(appWithoutIssues) val unprotectedApps = emptyList() val allApps = protectedApps + unprotectedApps @@ -380,7 +380,7 @@ class ManageAppsProtectionViewModelTest { } @Test - fun whenUnprotectedOnlyFilterAppliedAndGetProtectedAppsCalledThenOnlyUnprotectedAppsAreReturnedAndUnprotectedAppsBannerShown() = + fun `getProtectedApps - unprotected only filter applied - only unprotected apps returned and banner shown`() = 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..2f37f0bae15b 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 `getExclusionAppsList - return exclusion list`() = runTest { val exclusionList = trackingProtectionAppsRepository.getExclusionAppsList() assertEquals( @@ -77,7 +77,7 @@ class TrackingProtectionAppsRepositoryTest { } @Test - fun whenIsProtectionEnabledCalledOnDisabledAppThenReturnFalse() = runTest { + fun `getAppProtectionStatus - app disabled - return 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 - enabled app - return 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 - enabled app but excluded in NetP - return 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 - return unprotected`() = runTest { whenever(packageManager.getApplicationInfo("com.example.game", 0)) .thenReturn( ApplicationInfo().apply { @@ -126,7 +126,7 @@ class TrackingProtectionAppsRepositoryTest { } @Test - fun whenGetAppProtectionStatusCalledOnDdgAppThenReturnUnprotected() = runTest { + fun `getAppProtectionStatus - ddg app - return 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 - return 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 - name not found exception - 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 - adds to exclusion list`() = 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 exclusion list - return 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 - 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..3a8a242596d3 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`() = 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..ff1e9bf05f7a 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 - cannot submit`() { assertFalse(viewState.submitAllowed) } @Test - fun whenCategorySelectedThenCanSubmit() { + fun `selectAndAcceptCategory - can submit`() { selectAndAcceptCategory() assertTrue(viewState.submitAllowed) } @Test - fun whenCategoryChangedButNotSelectedThenCannotSubmit() { + fun `onCategoryIndexChanged - category changed but not selected - cannot submit`() { viewModel.onCategoryIndexChanged(0) assertFalse(viewState.submitAllowed) } @Test - fun whenNoCategorySelectedThenCannotSubmit() { + fun `cannotSubmit - no category selected`() { selectAndAcceptCategory(-1) assertFalse(viewState.submitAllowed) } @Test - fun whenCategorySelectedButNotChangedThenReturnOldCategory() { + fun `onCategoryAccepted - category selected but not changed - return old category`() { viewModel.onCategoryIndexChanged(0) viewModel.onCategoryAccepted() viewModel.onCategoryIndexChanged(1) @@ -88,13 +88,13 @@ class ReportBreakageCategorySingleChoiceViewModelTest { } @Test - fun whenCategoryAcceptedAndIncorrectIndexThenReturnNullCategory() { + fun `selectAndAcceptCategory - incorrect index - return null category`() { selectAndAcceptCategory(-1) assertNull(viewState.categorySelected) } @Test - fun whenCategoryAcceptedAndCorrectIndexThenReturnCategory() { + fun `selectAndAcceptCategory - correct index - return category`() { val indexSelected = 0 selectAndAcceptCategory(indexSelected) @@ -102,7 +102,7 @@ class ReportBreakageCategorySingleChoiceViewModelTest { } @Test - fun whenCancelSelectionThenAssignOldIndexValue() { + fun `onCategorySelectionCancelled - assign old index value`() { 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 - emit 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..4749f1fb92c6 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 - issue description form - 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 - list of installed apps - return 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..fa7274c8ef87 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 `collectVpnRelatedState - blocklist etag not present - json etag is empty`() = runTest { val jsonObject = collector.collectVpnRelatedState(PACKAGE_ID) assertEquals("", jsonObject.get("appTrackerListEtag")) } @Test - fun whenCollectStateAndBlocklistEtagPesentThenJsonEtagHasValue() = runTest { + fun `collectVpnRelatedState - 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 `collectVpnRelatedState - 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 `collectVpnRelatedState - 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 `collectVpnRelatedState - 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 `collectVpnRelatedState - 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 `collectVpnRelatedState - 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 `collectVpnRelatedState - protection overridden - overridden 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 `collectVpnRelatedState - protection overridden - overridden 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..d0ee9b008cd2 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 `intercept - cohort not set - 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 `intercept - cohort set - pixel fired`() { val date = LocalDate.now().plusDays(3) cohortStore.setCohortLocalDate(date) @@ -92,7 +92,7 @@ class CohortPixelInterceptorTest { } @Test - fun whenCohortSetPixelFiredCohortRemovedForException() { + fun `intercept - cohort set - pixel fired and 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..c773835c4031 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 - first day of last week 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 `calculateCohortForDate - 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 - first day of 2022 - 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 - first day of last week 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 `calculateCohortForDate - first day of last week 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 - return 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 - return 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 - 26 weeks ago - return 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..53b78d03fe33 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 `getCohortStoredLocalDate - cohort not set - return 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 `onVpnStarted - store initial cohort`() = runTest { vpnFeaturesRegistry.registerFeature(AppTpVpnFeature.APPTP_VPN) (cohortStore as RealCohortStore).onVpnStarted(TestScope()) @@ -87,7 +87,7 @@ class RealCohortStoreTest { } @Test - fun whenInitialCohortSubsequentCalledThenNoop() = runTest { + fun `onVpnStarted - initial cohort subsequent called - noop`() = 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 `onVpnStarted - appTp not registered - do nothing with cohort`() { (cohortStore as RealCohortStore).onVpnStarted(TestScope()) assertNull(cohortStore.getCohortStoredLocalDate()) } @Test - fun whenVpnReconfiguredCalledThenStoreInitialCohort() = runTest { + fun `onVpnReconfigured - store initial cohort`() = 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..c3e909100e64 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 - value set`() { 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 - returns null`() { assertNull(appTpRemoteFeaturesStore.get("key")) } @Test - fun `test get when value is not present`() { + fun `get - value not present - returns null`() { val expected = Toggle.State(enable = true) appTpRemoteFeaturesStore.set("key", expected) @@ -72,7 +72,7 @@ class AppTpRemoteFeaturesStoreTest { } @Test - fun `test load values`() { + fun `get - load values`() { 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 `get - preference change - propagates correctly`() { 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..0d078b74b48a 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`() { exceptionListsSettingStore.store("") verifyNoInteractions(mockVpnDatabase) } @Test - fun whenValidJSONUpdatesDB() = runTest { + fun `store - valid JSON - updates DB`() = 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..cead11f2f8e5 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 - startWorker`() { 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 `assertStartWorker - 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..57d2045b0a0e 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 - return 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 stylus 5G - 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 and private DNS set - 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 - 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 shortlisted 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 - EmFileError - kill process`() { ngVpnNetworkStack.onError(24, "EmFileError") verify(runtime).exit(0) } @Test - fun whenOnAnyErrorOtherThanEmFileThenNoop() { + fun `onError - any error other than EmFile - 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 - kill process`() { ngVpnNetworkStack.onExit("SomeError") verify(runtime).exit(0) } @Test - fun whenIsAddressBlockedAndDomainIsTrackerThenReturnFalse() { // false because we don't want to block based on IP addresses + fun `isAddressBlocked - domain is tracker - return 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 - return 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..0e7a94453348 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 `provideNetworkStack - network stack and app tp registered - 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 - unknown feature registered - throws exception`() = runTest { vpnFeaturesRegistry.registerFeature(VpnFeature { "unknown" }) vpnNetworkStackProvider.provideNetworkStack() assertEquals(VpnNetworkStack.EmptyVpnNetworkStack, vpnNetworkStackProvider.provideNetworkStack()) } @Test - fun whenProviderNetworkStackAndFeaturesContainAppTpThenReturnNetworkStack() = runTest { + fun `provideNetworkStack - features contain AppTp - 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..523b8813f595 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 `allAppTrackingProtectionPixels - 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..ffc220e75b27 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 `deviceShieldDisabledOnSearch - fire daily pixel`() { deviceShieldPixels.deviceShieldDisabledOnSearch() deviceShieldPixels.deviceShieldDisabledOnSearch() @@ -60,7 +60,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenReportEnableThenFireUniqueAndDailyPixel() { + fun `reportEnabled - fire unique and daily pixel`() { deviceShieldPixels.reportEnabled() deviceShieldPixels.reportEnabled() @@ -70,7 +70,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenReportDisableThenFireDailyPixel() { + fun `reportDisabled - 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 `enableFromOnboarding - fire unique daily and count pixels`() { deviceShieldPixels.enableFromOnboarding() deviceShieldPixels.enableFromOnboarding() @@ -101,7 +101,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenEnableFromSettingsTileThenFireUniqueDailyAndCountPixels() { + fun `enableFromQuickSettingsTile - fire unique daily and count pixels`() { deviceShieldPixels.enableFromQuickSettingsTile() deviceShieldPixels.enableFromQuickSettingsTile() @@ -112,7 +112,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenEnableFromPrivacyReportThenFireUniqueDailyAndCountPixels() { + fun `enableFromSummaryTrackerActivity - fire unique daily and count pixels`() { deviceShieldPixels.enableFromSummaryTrackerActivity() deviceShieldPixels.enableFromSummaryTrackerActivity() @@ -123,7 +123,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenDisableFromSettingsTileThenFireDailyAndCountPixels() { + fun `disableFromQuickSettingsTile - 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 `didPressOnDailyNotification - fire daily pixel`() { 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 `didPressOnWeeklyNotification - fire daily pixel`() { 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 `fireDailyAndCountPixels - sudden kill by system`() { deviceShieldPixels.suddenKillBySystem() deviceShieldPixels.suddenKillBySystem() @@ -278,7 +278,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenSuddenKillByVpnRevokedThenFireDailyAndCountPixels() { + fun `firePixels - sudden kill by VPN revoked - daily and count`() { deviceShieldPixels.suddenKillByVpnRevoked() deviceShieldPixels.suddenKillByVpnRevoked() @@ -289,7 +289,7 @@ class RealDeviceShieldPixelsTest { } @Test - fun whenPrivacyReportArticleDisplayedThenFireCountPixel() { + fun `privacyReportArticleDisplayed - 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..208771dd1316 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 `onVpnStarted - internal build - register receiver`() { whenever(appBuildConfig.flavor).thenReturn(BuildFlavor.INTERNAL) receiver.onVpnStarted(coroutineRule.testScope) @@ -60,7 +60,7 @@ class RestartReceiverTest { } @Test - fun whenNotInternalBuildThenRegisterReceiverOnStartVpn() { + fun `onVpnStarted - not internal build - does not register receiver`() { 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`() { whenever(appBuildConfig.flavor).thenReturn(BuildFlavor.INTERNAL) receiver.onVpnStopped(coroutineRule.testScope, VpnStateMonitor.VpnStopReason.SELF_STOP()) @@ -80,7 +80,7 @@ class RestartReceiverTest { } @Test - fun whenNotInternalBuildThenUnregisterReceiverOnStopVpn() { + fun `onVpnStopped - not internal build - unregister receiver`() { 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..53625962029a 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 `getHighestPriorityPlugin - empty plugin point - return null`() { assertNull(createPluginPoint(emptyList()).getHighestPriorityPlugin()) } @Test - fun whenInactivePluginsThenReturnNull() { + fun `getHighestPriorityPlugin - inactive plugins - return null`() { assertNull( createPluginPoint( listOf( @@ -40,7 +40,7 @@ class VpnEnabledNotificationContentPluginPointKtTest { } @Test - fun whenActivePluginsThenReturnThemInPriorityOrder() { + fun `getHighestPriorityPlugin - active plugins - return them in priority order`() { 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..4675fd374978 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 - t-mobile wifi calling addresses - excluded from VPN`() { 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 - verizon wifi calling addresses - excluded from VPN`() { 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 `localIPAddresses - excluded from VPN`() { 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 - CGNAT IP addresses - excluded from VPN`() { 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 - multicast addresses between 224·0·0·0 and 239·255·255·255 - 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`() { 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 range - 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 - addresses between 0·0·0·0 and 9·255·255·255 - 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 - addresses between 10·0·0·0 and 66·94·1·255 - 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 - addresses in range 66·94·3·0 to 66·94·5·255 - go through VPN`() { val fromRange = "66.94.3.0" val toRange = "66.94.5.255" val routes = findRoutes(fromRange, toRange) @@ -110,7 +110,7 @@ class VpnRoutesTest { } @Test - fun `all addresses between 66·94·12·0 range and 66·173·255·255 range go through VPN`() { + fun `findRoutes - addresses in range 66·94·12·0 to 66·173·255·255 - go through VPN`() { val fromRange = "66.94.12.0" val toRange = "66.173.255.255" val routes = findRoutes(fromRange, toRange) @@ -120,7 +120,7 @@ class VpnRoutesTest { } @Test - fun `all addresses between 66·175·0·0 range and 69·81·255·255 range go through VPN`() { + fun `findRoutes - addresses in range 66·175·0·0 to 69·81·255·255 - go through VPN`() { val fromRange = "66.175.0.0" val toRange = "69.81.255.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 - addresses in range 69·84·0·0 to 69·95·255·255 - 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 - addresses in range 69·104·0·0 to 70·191·255·255 - 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 - addresses in range 70·224·0·0 to 71·255·255·255 - 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 - addresses in range 72·128·0·0 to 75·127·255·255 - 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 - addresses in range 76·0·0·0 to 96·255·255·255 - 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 - addresses in 97·64·0·0 to 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 - addresses in range 98·0·0·0 to 100·63·255·255 - 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 - addresses in range 100·128·0·0 to 126·255·255·255 - 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 - addresses between 128·0·0·0 and 169·253·255·255 - 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 - addresses between 169·255·0·0 and 172·15·255·255 - 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 - addresses in range 172·32·0·0 to 174·191·255·255 - 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 - addresses in range 175·0·0·0 to 192·167·255·255 - go through VPN`() { val fromRange = "175.0.0.0" val toRange = "192.167.255.255" val routes = findRoutes(fromRange, toRange) @@ -250,7 +250,7 @@ class VpnRoutesTest { } @Test - fun `all addresses between 192·169·0·0 range and 208·53·255·255 range go through VPN`() { + fun `findRoutes - addresses in range 192·169·0·0 to 208·53·255·255 - go through VPN`() { val fromRange = "192.169.0.0" val toRange = "208.53.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 - addresses in range 208·55·0·0 to 223·255·255·255 - 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 `incrementIpAddress - various cases - correct increment`() { 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..07dccdc8f35f 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 tracking protection 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 - netP 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 `getUpdatedContent - 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 `getUpdatedContent - 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 `getUpdatedContent - 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 `getUpdatedContent - 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 - no entity - returns correct updated notification content`() = runTest { whenever(networkProtectionState.serverLocation()).thenReturn("Stockholm, SE") plugin.getUpdatedContent().test { @@ -245,7 +245,7 @@ class AppTPAndNetPEnabledNotificationContentPluginTest { } @Test - fun getUpdateContentMultipleSameThenReturnsCorrectUpdatedNotificationContent() = runTest { + fun `getUpdatedContent - multiple same updates - returns correct updated notification content`() = runTest { whenever(networkProtectionState.serverLocation()).thenReturn("Stockholm, SE") plugin.getUpdatedContent().test { @@ -281,14 +281,14 @@ class AppTPAndNetPEnabledNotificationContentPluginTest { } @Test - fun isActiveWhenAppTpAndNetPEnabledThenReturnsTrue() = runTest { + fun `isActive - appTp and netP enabled - returns true`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(true) whenever(networkProtectionState.isEnabled()).thenReturn(true) assertTrue(plugin.isActive()) } @Test - fun isActiveWhenAppTpAndNetPNotEnabledThenReturnsFalse() = runTest { + fun `isActive - appTp and netP 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 `isActive - 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 `isActive - NetP 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..a1696e2b9c68 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 - returns 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 `getUpdatedContent - 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 `getUpdatedContent - 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 `getUpdatedContent - 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 `getUpdatedContent - 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 `getUpdatedContent - multiple different apps - returns correct updated notification content`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(true) whenever(networkProtectionState.isEnabled()).thenReturn(false) @@ -205,7 +205,7 @@ class AppTpEnabledNotificationContentPluginTest { } @Test - fun getUpdateContentMultipleDifferentAppsAppTpNotEnabledThenReturnsCorrectUpdatedNotificationContent() = runTest { + fun `getUpdatedContent - multiple different apps and app tracking protection not enabled - returns correct updated notification content`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(false) plugin.getUpdatedContent().test { @@ -230,7 +230,7 @@ class AppTpEnabledNotificationContentPluginTest { } @Test - fun getUpdateContentTrackersWithoutEntityThenReturnsCorrectUpdatedNotificationContent() = runTest { + fun `getUpdatedContent - trackers 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 `getUpdatedContent - multiple same updates - 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 `getUpdatedContent - 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 `isActive - app tracking protection enabled - returns true`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(true) whenever(networkProtectionState.isEnabled()).thenReturn(false) assertTrue(plugin.isActive()) } @Test - fun isActiveWhenAppTpNotEnabledThenReturnsFalse() = runTest { + fun `isActive - 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 - appTp and netP 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..05389c977ace 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 `getHighestPriorityPluginForType - empty plugin point - return null`() { assertNull(createPluginPoint(emptyList()).getHighestPriorityPluginForType(REVOKED)) } @Test - fun whenPluginForTypeAvailableThenReturnPLugin() { + fun `getHighestPriorityPluginForType - plugin for type available - return 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 `getHighestPriorityPluginForType - multiple plugins for type - 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..c3a71930f4e1 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 - default value - false`() = runTest { Assert.assertFalse(testee.isAlwaysOnEnabled()) } @Test - fun whenVpnLastDisabledByAndroidAndVpnKilledBySystemThenReturnTrue() = runTest { + fun `vpnLastDisabledByAndroid - vpn killed by system - return 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 - vpn unexpectedly disabled - return true`() = runTest { whenever(vpnServiceStateDao.getLastStateStats()).thenReturn( VpnServiceStateStats(state = DISABLED), ) @@ -84,7 +84,7 @@ class RealVpnStateMonitorTest { } @Test - fun whenVpnLastDisabledByAndroidAndVpnDisabledByUserThenReturnFalse() = runTest { + fun `vpnLastDisabledByAndroid - vpn disabled by user - return false`() = runTest { whenever(vpnServiceStateDao.getLastStateStats()).thenReturn( VpnServiceStateStats(state = DISABLED, stopReason = SELF_STOP), ) @@ -93,7 +93,7 @@ class RealVpnStateMonitorTest { } @Test - fun whenVpnLastDisabledByAndroidAndVpnEnabledThenReturnFalse() = runTest { + fun `vpnLastDisabledByAndroid - vpn enabled - return 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..4702cddb8909 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 - 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..d89011157653 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 - appTP 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 - appTP disabled - enqueue 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 - VPN starts - daily reminder 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 was enqueued - daily reminder is 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 - VPN manually stops due to snooze - daily reminder is 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 - VPN manually stops - daily reminder 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 - VPN stopped but appTP disabled was removed - nothing 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 - feature removed - nothing 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 enqueued - 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 - manually stops - 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 was scheduled - 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 shown`() = 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 onboarded and VPN manually stops with content plugin for disabled - immediate notification 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 `onVpnStopped - user not onboarded and VPN manually stops with content plugin disabled - no immediate notification`() = 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 - no content plugin for revoked - no immediate notification 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 `onVpnStopped - appTP 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 `onVpnStopped - appTP disabled and VPN revoked with content plugin for revoked - 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 `onVpnStopped - appTP not onboarded and vpn revoked - no immediate notification shown`() = 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 - VPN killed - undesired reminder enqueued`() { testee.onVpnStopped(coroutinesTestRule.testScope, REVOKED) assertWorkersAreNotEnqueued(VpnReminderNotificationWorker.WORKER_VPN_REMINDER_UNDESIRED_TAG) } @Test - fun whenVPNIsKilledAndReminderWasScheduledThenUndesiredReminderIsNoLongerScheduled() = runTest { + fun `onVpnStopped - reminder was scheduled - undesired reminder 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 - appTP disabled on VPN reconfigure - immediate notification 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 - appTP disabled - no immediate notification`() = 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 - appTP enabled - no immediate notification`() = 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..1c125fb2b52f 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 `createDailyDeviceShieldNotification - trackers found in one app - creates total trackers notification`() = runBlocking { val trackerDomain = "example.com" trackerFound(trackerDomain) @@ -76,7 +76,7 @@ class DeviceShieldDailyNotificationFactoryTest { } @Test - fun createsTotalTrackersNotificationWhenTrackersFoundInTwoApps() = runBlocking { + fun `createDailyDeviceShieldNotification - trackers found in two apps - creates 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 notification`() = runBlocking { val notification = factory.dailyNotificationFactory.createDailyDeviceShieldNotification(0) assertTrue(notification.hidden) } @Test - fun createsTopTrackerCompanyNotificationWhenTrackersFoundInOneApp() = runBlocking { + fun `createDailyDeviceShieldNotification - trackers found in one app - creates top tracker company notification`() = runBlocking { val trackerDomain = "example.com" trackerFound(trackerDomain) @@ -109,7 +109,7 @@ class DeviceShieldDailyNotificationFactoryTest { } @Test - fun createsTopTrackerCompanyNotificationWhenTrackersFoundInTwoApps() = runBlocking { + fun `createDailyDeviceShieldNotification - trackers found in two apps - creates top tracker company notification`() = 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 `createDailyDeviceShieldNotification - trackers found in zero apps - does not create top tracker company notification`() = runBlocking { val notification = factory.dailyNotificationFactory.createDailyDeviceShieldNotification(1) assertTrue(notification.hidden) } @Test - fun createsHiddenTopTrackerCompanyNotificationWhenNoTrackersFound() = runBlocking { + fun `createDailyDeviceShieldNotification - no trackers found - creates hidden top tracker company notification`() = runBlocking { val notification = factory.dailyNotificationFactory.createDailyDeviceShieldNotification(1) assertTrue(notification.hidden) } @Test - fun createsTopTrackerAppNumbersNotificationWhenTrackersFound() = runBlocking { + fun `createDailyDeviceShieldNotification - trackers found - creates top tracker app numbers notification`() = runBlocking { val trackerDomain = "example.com" trackerFound(trackerDomain, appContainingTracker = trackingApp1()) trackerFound(trackerDomain, appContainingTracker = trackingApp2()) @@ -149,14 +149,14 @@ class DeviceShieldDailyNotificationFactoryTest { } @Test - fun createsHiddenTopTrackerCompanyNumbersNotificationWhenNoTrackersFound() = runBlocking { + fun `createDailyDeviceShieldNotification - no trackers found - creates hidden notification`() = runBlocking { val notification = factory.dailyNotificationFactory.createDailyDeviceShieldNotification(2) assertTrue(notification.hidden) } @Test - fun createsLastCompanyAttemptNotificationWhenTrackersFoundInOneApp() = runBlocking { + fun `createDailyDeviceShieldNotification - trackers found in one app - creates last company attempt notification`() = runBlocking { val trackerDomain = "example.com" trackerFound(trackerDomain) @@ -167,7 +167,7 @@ class DeviceShieldDailyNotificationFactoryTest { } @Test - fun createsLastCompanyAttemptNotificationWhenTrackersFoundInTwoApps() = runBlocking { + fun `createDailyDeviceShieldNotification - trackers found in two apps - creates last company attempt notification`() = runBlocking { val trackerDomain = "example.com" trackerFound(trackerDomain, appContainingTracker = trackingApp1()) trackerFound( @@ -183,7 +183,7 @@ class DeviceShieldDailyNotificationFactoryTest { } @Test - fun createsLastCompanyAttemptNotificationWhenTrackersFoundInThreeApps() = runBlocking { + fun `createDailyDeviceShieldNotification - trackers found in three apps - creates 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..ddd43daea27a 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 `createWeeklyDeviceShieldNotification - trackers found in one app - creates weekly report notification`() = runBlocking { val trackerDomain = "example.com" trackerFound(trackerDomain) @@ -75,7 +75,7 @@ class DeviceShieldWeeklyNotificationFactoryTest { } @Test - fun createsWeeklyReportNotificationWhenTrackersFoundInTwoApps() = runBlocking { + fun `createWeeklyDeviceShieldNotification - trackers found in two apps - creates weekly report notification`() = runBlocking { val trackerDomain = "example.com" trackerFound(trackerDomain, appContainingTracker = trackingApp1()) trackerFound( @@ -90,7 +90,7 @@ class DeviceShieldWeeklyNotificationFactoryTest { } @Test - fun createsWeeklyReportNotificationWhenTrackersFoundInMoreThanTwoApps() = runBlocking { + fun `createWeeklyDeviceShieldNotification - trackers found in more than two apps - creates 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 `createWeeklyDeviceShieldNotification - multiple trackers found - correct sort order`() = runBlocking { val trackerDomain = "example.com" trackerFound(trackerDomain, appContainingTracker = trackingApp1()) trackerFound(trackerDomain, appContainingTracker = trackingApp2()) @@ -125,13 +125,13 @@ class DeviceShieldWeeklyNotificationFactoryTest { } @Test - fun createsHiddenWeeklyReportNotificationWhenNoTrackersFound() = runBlocking { + fun `createWeeklyDeviceShieldNotification - no trackers found - hidden notification`() = runBlocking { val notification = factory.weeklyNotificationFactory.createWeeklyDeviceShieldNotification(0) assertTrue(notification.hidden) } @Test - fun createsWeeklyTopTrackerCompanyNotificationWhenTrackersFoundInOneApp() = runBlocking { + fun `createWeeklyDeviceShieldNotification - trackers found in one app - creates weekly top tracker company notification`() = runBlocking { val trackerDomain = "example.com" trackerFound(trackerDomain) @@ -141,7 +141,7 @@ class DeviceShieldWeeklyNotificationFactoryTest { } @Test - fun createsWeeklyTopTrackerCompanyNotificationWhenTrackersFoundInTwoApps() = runBlocking { + fun `createWeeklyDeviceShieldNotification - trackers found in two apps - creates weekly top tracker company notification`() = runBlocking { val trackerDomain = "example.com" trackerFound("google.com", company = "Google", appContainingTracker = trackingApp1()) @@ -164,7 +164,7 @@ class DeviceShieldWeeklyNotificationFactoryTest { } @Test - fun createsHiddenWeeklyTopTrackerCompanyNotificationWhenNoTrackersFound() = runBlocking { + fun `createWeeklyDeviceShieldNotification - no trackers found - creates hidden notification`() = 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..5ec68c59df33 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 `appTpEnabledCtaDidShow - set preference value to true`() { assertFalse(sharedPreferencesVpnStore.didShowAppTpEnabledCta()) sharedPreferencesVpnStore.appTpEnabledCtaDidShow() @@ -76,7 +76,7 @@ class SharedPreferencesVpnStoreTest { } @Test - fun whenIsOnboardingSessionCalledWithoutBeingSetThenReturnFalse() { + fun `getAndSetOnboardingSession - called without being set - return 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..c250d27dfced 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 - 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 - app unprotected through netp - viewState with toggle unchecked, disabled, and 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 is protected - viewState with toggle checked, enabled, and 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 is unprotected - viewState with toggle unchecked, enabled, and 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..add268c32439 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 - 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 - 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 - 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 with five rows - 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 - less trackers than max rows and 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..d59f78dbb8e3 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 - 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 view event - command is launch app trackers`() = runBlocking { viewModel.commands().test { viewModel.onViewEvent(ViewEvent.LaunchAppTrackersFAQ) @@ -101,7 +101,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenLaunchDeviceShieldFAQViewEventThenCommandIsLaunchDeviceShieldFAQ() = runBlocking { + fun `onViewEvent - launch device shield FAQ - command is 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 - command is launch excluded apps`() = runBlocking { viewModel.commands().test { viewModel.onViewEvent(ViewEvent.LaunchExcludedApps) @@ -123,7 +123,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenLaunchMostRecentActivityViewEventThenCommandIsLaunchMostRecentActivity() = runBlocking { + fun `onViewEvent - launch most recent activity - command is launch most recent activity`() = runBlocking { viewModel.commands().test { viewModel.onViewEvent(ViewEvent.LaunchMostRecentActivity) @@ -134,7 +134,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenToggleIsSwitchedOnAndOtherVPNIsDisabledThenTrackingProtectionIsEnabled() = runBlocking { + fun `onAppTPToggleSwitched - other VPN disabled - 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 - other VPN disabled - shows confirmation dialog`() = 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 needed - 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 - result is OK - VPN is 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 - show always on promotion`() = 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 - 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 - does not send promote always on dialog command`() = runBlocking { whenever(vpnStateMonitor.isAlwaysOnEnabled()).thenReturn(true) whenever(vpnStateMonitor.vpnLastDisabledByAndroid()).thenReturn(true) @@ -211,7 +211,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenVpnPermissionResultIsDeniedAndRequestTimeWasSmallerThanNeededThenVpnConflictDialogIsShown() = runBlocking { + fun `onVPNPermissionResult - permission denied and request time too short - show VPN conflict dialog`() = runBlocking { viewModel.commands().test { val permissionIntent = Intent() viewModel.onVPNPermissionNeeded(permissionIntent) @@ -224,7 +224,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenVpnPermissionResultIsDeniedAndRequestTimeWasHigherThanNeededThenVpnIsStopped() = runBlocking { + fun `onVPNPermissionResult - request time 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 - other VPN enabled - shows VPN conflict dialog`() = 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 `onViewEvent - ask to remove feature - dialog is shown`() = runBlocking { viewModel.commands().test { viewModel.onViewEvent(ViewEvent.AskToRemoveFeature) @@ -271,7 +271,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenUserAcceptsToRemoveFeatureThenFeatureIsRemovedAndVpnAndScreenClosed() = runBlocking { + fun `onViewEvent - remove feature - 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 `onViewEvent - promote always on open settings selected - command is sent`() = runBlocking { viewModel.commands().test { viewModel.onViewEvent(ViewEvent.PromoteAlwaysOnOpenSettings) @@ -297,7 +297,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenAppTpEnabledCtaShownAndListShownThenNoCommandSent() = runBlocking { + fun `showAppTpEnabledCtaIfNeeded - AppTp enabled CTA 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 - AppTp enabled CTA not 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 - called outside onboarding session - return next session banner`() { whenever(vpnStore.getAndSetOnboardingSession()).thenReturn(false) val bannerState = viewModel.bannerState() @@ -331,7 +331,7 @@ class DeviceShieldTrackerActivityViewModelTest { } @Test - fun whenBannerStateCalledDuringOnboardingSessionThenReturnOnboardingBanner() { + fun `bannerState - during onboarding session - return 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..27e3f6cf7eb5 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 `getVpnTrackers - single tracker entry added but no related entity - 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 `getVpnTrackers - same tracker found multiple times today - all instances 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 - return 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..20d05005b93f 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 `database migrations - all migrations - 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..70b130c10969 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 - valid json - 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..161b161ee660 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 is 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..086665001201 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 `viewState - initialised - emitted with default values`() = runTest { testee.viewState().test { val value = awaitItem() @@ -78,7 +78,7 @@ internal class AboutDuckDuckGoViewModelTest { } @Test - fun whenOnLearnMoreLinkClickedThenCommandLaunchBrowserWithLearnMoreUrlIsSentAndPixelFired() = runTest { + fun `onLearnMoreLinkClicked - launch browser with learn more URL and fire pixel`() = runTest { testee.commands().test { testee.onLearnMoreLinkClicked() @@ -90,7 +90,7 @@ internal class AboutDuckDuckGoViewModelTest { } @Test - fun whenOnPrivacyPolicyClickedThenCommandLaunchWebViewWithPrivacyPolicyUrlIsSentAndPixelFired() = runTest { + fun `onPrivacyPolicyClicked - launch web view with privacy policy URL and fire pixel`() = runTest { testee.commands().test { testee.onPrivacyPolicyClicked() @@ -102,7 +102,7 @@ internal class AboutDuckDuckGoViewModelTest { } @Test - fun whenVersionClickedAndNetPWaitlistStateIsOtherThanNotUnlockedThenNoCommandIsSentAndPixelNotSent() = runTest { + fun `onVersionClicked - NetP 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) @@ -112,7 +112,7 @@ internal class AboutDuckDuckGoViewModelTest { } @Test - fun whenVersionClickedLessThanMaxTimesAndNetPWaitlistStateIsNotUnlockedThenNoCommandIsSentAndPixelNotSent() = runTest { + fun `onVersionClicked - less than max times and waitlist state not unlocked - no command and no pixel 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 is zero`() = 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..9c655c2ebff6 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 `viewModelCreated - default viewState emitted`() = runTest { val viewState = AccessibilitySettingsViewModel.ViewState( overrideSystemFontSize = false, appFontSize = 100f, @@ -60,7 +60,7 @@ class AccessibilitySettingsViewModelTest { } @Test - fun whenViewModelStartedThenViewStateEmitted() = runTest { + fun `start - viewState emitted`() = runTest { val viewState = AccessibilitySettingsViewModel.ViewState( overrideSystemFontSize = true, appFontSize = 150f, @@ -83,7 +83,7 @@ class AccessibilitySettingsViewModelTest { } @Test - fun whenForceZoomEnabledThenViewStateEmitted() = runTest { + fun `onForceZoomChanged - force zoom enabled - viewState emitted`() = runTest { val viewState = defaultViewState() whenever(accessibilitySettings.forceZoom).thenReturn(true) @@ -96,7 +96,7 @@ class AccessibilitySettingsViewModelTest { } @Test - fun whenForceZoomEnabledThenSettingsUpdated() = runTest { + fun `onForceZoomChanged - force zoom enabled - settings updated`() = runTest { whenever(accessibilitySettings.forceZoom).thenReturn(true) testee.onForceZoomChanged(true) @@ -106,7 +106,7 @@ class AccessibilitySettingsViewModelTest { } @Test - fun whenOverrideSystemFontSizeEnabledThenViewStateEmitted() = runTest { + fun `onSystemFontSizeChanged - override system font size enabled - viewState emitted`() = runTest { val viewState = defaultViewState() whenever(accessibilitySettings.overrideSystemFontSize).thenReturn(true) @@ -119,7 +119,7 @@ class AccessibilitySettingsViewModelTest { } @Test - fun whenOverrideSystemFontSizeEnabledThenSettingsUpdated() = runTest { + fun `onSystemFontSizeChanged - override system font size enabled - settings updated`() = runTest { whenever(accessibilitySettings.overrideSystemFontSize).thenReturn(true) testee.onSystemFontSizeChanged(true) @@ -129,7 +129,7 @@ class AccessibilitySettingsViewModelTest { } @Test - fun whenFontSizeChangedThenViewStateEmitted() = runTest { + fun `onFontSizeChanged - viewState 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 - voice search enabled - viewState emitted`() = runTest { val viewState = defaultViewState() whenever(voiceSearchAvailability.isVoiceSearchAvailable).thenReturn(true) @@ -165,25 +165,25 @@ class AccessibilitySettingsViewModelTest { } @Test - fun whenVoiceSearchEnabledThenSettingsUpdated() = runTest { + fun `onVoiceSearchChanged - voice search enabled - settings updated`() = runTest { testee.onVoiceSearchChanged(true) verify(voiceSearchRepository).setVoiceSearchUserEnabled(true) } @Test - fun whenVoiceSearchDisabledThenSettingsUpdated() = runTest { + fun `onVoiceSearchChanged - voice search disabled - settings updated`() = runTest { testee.onVoiceSearchChanged(false) verify(voiceSearchRepository).setVoiceSearchUserEnabled(false) } @Test - fun whenVoiceSearchEnabledThenFirePixel() = runTest { + fun `onVoiceSearchChanged - voice search enabled - 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..c7f08436b465 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 `viewState - initialised - default values emitted`() = runTest { testee.viewState().test { val value = awaitItem() @@ -85,13 +85,13 @@ internal class AppearanceViewModelTest { } @Test - fun whenThemeSettingsClickedThenPixelSent() { + fun `userRequestedToChangeTheme - pixel sent`() { testee.userRequestedToChangeTheme() verify(mockPixel).fire(AppPixelName.SETTINGS_THEME_OPENED) } @Test - fun whenThemeSettingsClickedThenCommandIsLaunchThemeSettingsIsSent() = runTest { + fun `userRequestedToChangeTheme - command is launch theme settings`() = 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 - theme changed - dataStore updated and 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 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 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 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..ab8eed972a83 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 an 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 - no match - return 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 - 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 - 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 - returns duplicated items - dedup`() { whenever(mockAutoCompleteService.autoComplete("title")).thenReturn( Observable.just( listOf( @@ -212,7 +212,7 @@ class AutoCompleteApiTest { } @Test - fun whenReturnOneBookmarkAndOneFavoriteSuggestionsThenShowBothFavoriteFirst() { + fun `autoComplete - one bookmark and one favorite - show both favorite 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 - returns 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 - bookmark title starts with query - scores higher`() { 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 `autoComplete - single token query and duplicated bookmark items - dedup`() { 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 - ignore 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 slashes - ignore 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 slashes - 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 with 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..d0fdb02645a2 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 `whenMigrationApplied - 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 `whenMigrationApplied - favorites exist - migration is successful`() = runTest { val totalFavorites = 10 givenSomeFavorites(totalFavorites) whenMigrationApplied() @@ -104,7 +104,7 @@ class BookmarksMigrationTest { } @Test - fun whenBookmarksWithoutFoldersExistThenMigrationIsSuccessful() = runTest { + fun `whenMigrationApplied - bookmarks without folders exist - migration is successful`() = runTest { val totalBookmarks = 10 givenSomeBookmarks(totalBookmarks, SavedSitesNames.BOOMARKS_ROOT_ID) @@ -124,7 +124,7 @@ class BookmarksMigrationTest { } @Test - fun whenBookmarksWithFoldersExistThenMigrationIsSuccessful() = runTest { + fun `whenMigrationApplied - bookmarks with folders exist - migration is successful`() = runTest { val totalFolder = 10 val bookmarksPerFolder = 5 createFoldersTree(totalFolder, bookmarksPerFolder) @@ -145,7 +145,7 @@ class BookmarksMigrationTest { } @Test - fun whenBookmarksWithFoldersAndFavoritesExistThenMigrationIsSuccessful() = runTest { + fun `whenMigrationApplied - bookmarks with folders and favorites exist - migration is successful`() = runTest { val totalFolder = 10 val bookmarksPerFolder = 5 createFoldersTree(totalFolder, bookmarksPerFolder) @@ -166,7 +166,7 @@ class BookmarksMigrationTest { } @Test - fun whenBookmarkAndFavoriteHaveSameUrlThenBookmarkAlsoMigratedAsFavorite() { + fun `whenMigrationApplied - bookmark and favorite have same url - bookmark also migrated as favorite`() { 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 `whenMigrationApplied - different URLs - both 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 `whenMigrationApplied - old tables are deleted`() { givenSomeFavorites(10) givenSomeBookmarks(5, SavedSitesNames.BOOMARKS_ROOT_ID) whenMigrationApplied() @@ -226,7 +226,7 @@ class BookmarksMigrationTest { } @Test - fun whenNeedsFormFactorMigrationThenFavoritesAreCopiedIntoFormFactorFavoriteFolder() { + fun `whenMigrationApplied - needs form factor migration - favorites are copied into form factor favorite folder`() { givenSomeFavoritesSavedSites(10) whenMigrationApplied() @@ -238,7 +238,7 @@ class BookmarksMigrationTest { } @Test - fun whenNeedsFormFactorMigrationThenFormFactorFolderLastModifiedUdpated() { + fun `whenMigrationApplied - needs form factor migration - form factor folder last modified updated`() { givenSomeFavoritesSavedSites(10) whenMigrationApplied() @@ -247,7 +247,7 @@ class BookmarksMigrationTest { } @Test - fun whenAnyFavoriteRootFolderHasRelationWithBookmarksRootThenRemoveRelation() = runTest { + fun `whenMigrationApplied - favorite root folder has relation with bookmarks root - 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..3bae231efeb6 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 is generated`() = runTest { val bookmark = Bookmark( id = "bookmark1", title = "example", @@ -142,7 +142,7 @@ class SavedSitesParserTest { } @Test - fun whenNoSavedSitesExistThenNothingIsGenerated() = runTest { + fun `generateHtml - no saved sites - 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 `parseHtml - firefox bookmarks - imported successfully`() = 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 `parseHtml - brave bookmarks - imports successfully`() = 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 `parseHtml - chrome bookmarks - imported successfully`() = 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 `parseHtml - DDG Android bookmarks - imports correctly`() = 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 `importBookmarks - from DDG macOS - bookmarks parsed correctly`() = 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 `parseHtml - import bookmarks from Safari - bookmarks parsed correctly`() = 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 `parseHtml - import bookmarks and favorites from DDG`() = 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 - correct counts`() { 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..a933cfa673ac 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 - folder content is empty`() = runTest { assert(repository.getFolderTreeItems(SavedSitesNames.BOOKMARKS_ROOT).isEmpty()) } @Test - fun whenRootFolderHasOnlyBookmarksThenDataIsRetrieved() = runTest { + fun `getFolderTreeItems - root folder has only bookmarks - data is 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 retrieved`() = runTest { val totalBookmarks = 10 val totalFolders = 3 @@ -155,7 +155,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenFavoriteIsAddedThenBookmarkIsAlsoAdded() { + fun `insertFavorite - bookmark is also added`() { givenEmptyDBState() repository.insertFavorite("favourite1", "https://favorite.com", "favorite", "timestamp") @@ -165,7 +165,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenBookmarkIsAddedThenFavoriteIsNotAdded() { + fun `insertBookmark - bookmark added - favorite not added`() { givenEmptyDBState() repository.insertBookmark("https://favorite.com", "favorite") @@ -175,7 +175,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenFavoriteIsAddedAndThenRemovedThenBookmarkStillExists() { + fun `favorite - added and then 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 `delete - favorite added and removed with delete bookmark true - nothing retrieved`() { givenEmptyDBState() val favorite = repository.insertFavorite("favourite1", "https://favorite.com", "favorite", "timestamp") @@ -203,7 +203,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenBookmarkIsAddedAndThenRemovedThenNothingIsRetrieved() { + fun `insertBookmark and delete - bookmark added and removed - 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 - without title - 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 - saved site 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 - favorite name updated - 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 `updateBookmark - favorite moved to another folder - still favorite`() { val favoriteone = Favorite("favorite1", "Favorite", "http://favexample.com", "timestamp", 0) givenFavoriteStored(favoriteone) @@ -285,7 +285,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenFavoritePositionUpdatedThenDataIsUpdated() = runTest { + fun `updateFavourite - favorite position updated - data is updated`() = 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) @@ -308,7 +308,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenListReceivedThenUpdateItemsWithNewPositionInDatabase() { + fun `updateWithPosition - 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 `delete - favorite deleted - database updated`() = 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 - returns 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 `getFavorite - favorite by URL requested and available - return favorite`() = runTest { givenNoFavoritesStored() val favorite = @@ -361,7 +361,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenFavoriteByUrlRequestedAndNotAvailableThenReturnNull() = runTest { + fun `getFavorite - favorite by URL not available - return 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 - return 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 - no bookmarks stored - populates DB`() = runTest { givenNoBookmarksStored() val bookmark = repository.insert( @@ -410,7 +410,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenInsertBookmarkByTitleAndUrlThenPopulateDB() = runTest { + fun `insert - bookmark by title and url - populate DB`() = runTest { val bookmark = repository.insert( Bookmark( id = "bookmark1", @@ -426,7 +426,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenUpdateBookmarkUrlThenUpdateBookmarkInDB() = runTest { + fun `updateBookmark - update bookmark URL - bookmark updated in DB`() = runTest { givenNoBookmarksStored() val bookmark = repository.insert( @@ -454,7 +454,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenUpdateBookmarkFolderThenUpdateBookmarkInDB() = runTest { + fun `updateBookmark - update bookmark folder - updates in DB`() = runTest { givenNoBookmarksStored() val bookmark = repository.insert( @@ -475,7 +475,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenDeleteBookmarkThenRemoveBookmarkFromDB() = runTest { + fun `delete - bookmark - remove from DB`() = runTest { givenNoBookmarksStored() val bookmark = repository.insert( @@ -493,7 +493,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenBookmarkAddedToRootThenGetFolderReturnsRootFolder() = runTest { + fun `getFolderTreeItems - 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 - nothing is retrieved`() = 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 `getFolderByName - 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 `getFolderTreeItems - bookmark added to folder - returns folder`() = runTest { givenNoBookmarksStored() repository.insertBookmark(title = "root", url = "foo.com") @@ -545,7 +545,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenBookmarkAndFolderAddedToFolderThenGetFolderReturnsFolder() = runTest { + fun `getFolderTreeItems - bookmark and 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 `updateBookmark - moved to another folder - root bookmarks empty`() = runTest { givenNoBookmarksStored() val bookmark = repository.insertBookmark(title = "bookmark1", url = "foo.com") @@ -584,7 +584,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenBookmarkIsMovedToAnotherFolderThenFolderReturnsBookmark() = runTest { + fun `updateBookmark - moved to another folder - 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 `update - folder moved to another folder - 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 `updateFolder - 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 `update - folder parent - repository 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 are 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 - 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 - child folders with bookmarks - 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 - 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 - branch folder deleted - 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 `delete - folder is deleted - 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 `getFolderTreeItems - root folder has bookmarks and folders - data with numbers 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 - user has bookmarks and favorites - returns subfolder`() = 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 - undo - 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 - bookmark updated - lastModified also updated`() { givenNoBookmarksStored() val bookmark = repository.insert( @@ -976,7 +976,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenFavouritesDuplicatedThenLocalDataIsReplaced() = runTest { + fun `givenFavoriteStored - favourites 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 - subfolder replaced - 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) @@ -1022,7 +1022,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenSubFolderContentIsReplacedThenLocalDataIsUpdated() = runTest { + fun `replaceFolderContent - subfolder content replaced - local data updated`() = runTest { val rootFolder = BookmarkFolder(id = SavedSitesNames.BOOKMARKS_ROOT, name = "root", lastModified = "timestamp", parentId = "") repository.insert(rootFolder) @@ -1052,7 +1052,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenFolderParentIsUpdatedThenReplacingItUpdatesData() = runTest { + fun `replaceFolderContent - folder parent updated - updates data`() = 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 - deleted bookmark folder - data permanently deleted`() { givenEmptyDBState() val bookmark = repository.insertBookmark("https://favorite.com", "Bookmark") @@ -1089,7 +1089,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenPruningDeletedBookmarkDataIsPermanentlyDeleted() { + fun `pruneDeleted - deleted bookmark data - permanently deleted`() { givenEmptyDBState() val bookmark = repository.insertBookmark("https://favorite.com", "Bookmark") @@ -1104,7 +1104,7 @@ class SavedSitesRepositoryTest { } @Test - fun whenPruningDeletedFavouriteDataIsNotPermanentlyDeleted() { + fun `pruneDeleted - deleted 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 `deleteFolder - folder with favorite - 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 - folder with favourite - data is 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 - update favorite true and bookmark is favorite - favorite is 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 - update favorite true and bookmark is not favorite - favorite is 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..7636c5a6748a 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 - folder metadata not 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 - folder metadata present and 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 `replaceBookmarkFolder - folder replaced - children updated`() { val bookmarks = BookmarkTestUtils.givenSomeBookmarks(10) savedSitesEntitiesDao.insertList(bookmarks) @@ -297,7 +297,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenFolderIsReplacedThenOrphanedChildrenAreRemoved() { + fun `replaceBookmarkFolder - folder replaced - orphaned children removed`() { val bookmarks = BookmarkTestUtils.givenSomeBookmarks(10) savedSitesEntitiesDao.insertList(bookmarks) @@ -312,7 +312,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenRemoteFolderDoesNotContainLocallyStoredChildThenOrphanIsCreated() { + fun `replaceBookmarkFolder - remote folder missing 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 - remote folder contains added children - orphans are 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 are 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 - does not affect favourites`() { // 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 - deleted entity - 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 `generateLocalChanges - metadata request updated`() { val expectedContent = listOf( getRequestEntryFromBookmarkFolder(favoritesFolder, listOf(bookmark1).map { it.id }), getRequestEntryFromSavedSite(bookmark1), @@ -475,13 +475,13 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenGeneratingLocalChangesAreEmptyThenMetadataRequestIsNotUpdated() { + fun `addRequestMetadata - local changes are empty - metadata request is not updated`() { 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 - response has no entities - metadata is not updated`() { repository.addResponseMetadata(emptyList()) assertTrue(savedSitesMetadataDao.all().isEmpty()) } @Test - fun whenResponseHasNoEntitiesAfterAPatchRequestThenMetadataIsCopiedAsResponse() { + fun `addResponseMetadata - no entities after patch request - 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 `addResponseMetadata - response has entities - metadata is 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 `discardRequestMetadataAndStoreResponseMetadata - metadata status 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 - response has only bookmarks - metadata is not updated`() { val responseEntries = listOf( getResponseEntryFromSavedSite(bookmark), ) @@ -598,7 +598,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenResponseHasNoFoldersAfterAPatchRequestThenMetadataIsCopiedAsResponse() { + fun `addResponseMetadata - no folders after patch request - 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 - 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 is 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 - deduplicating bookmark - remote bookmark replaces local`() { // given a local bookmark repository.insert(bookmark1, favouritesRoot.entityId) @@ -662,7 +662,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenBookmarkIsReplacedWithDifferentIdThenDataIsUpdated() { + fun `replaceBookmark - different id - data is 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 - same id - data is updated`() { val rootFolder = BookmarkFolder(id = SavedSitesNames.BOOKMARKS_ROOT, name = "root", lastModified = "timestamp", parentId = "") savedSitesRepository.insert(rootFolder) @@ -714,7 +714,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenReplacingBookmarThenDataIsUpdated() { + fun `replaceBookmark - data is updated`() { 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) @@ -741,7 +741,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenReplacingBookmarkWithBookmarkFromAnotherFolderThenDataIsUpdated() { + fun `replaceBookmark - bookmark from another folder - data is updated`() { 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) @@ -770,7 +770,7 @@ class SyncSavedSitesRepositoryTest { } @Test - fun whenMovingBookmarkToAnotherFolderThenBookmarkOnlyHasOnlyBelongsToOneFolder() { + fun `replaceBookmarkFolder - move bookmark to another folder - belongs to one folder`() { 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 - move favourite to another folder - belongs to favourites and folder`() { 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 - 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 - modified before threshold - 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 - replacing favourites folder - only current 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 are kept`() { // 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 - 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..096884b75c19 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 is 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 - return 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..175fc4e07c3e 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 `undoDelete - bookmark delete undo - repository not updated`() = runTest { testee.onDeleteSavedSiteRequested(bookmark) testee.undoDelete(bookmark) @@ -133,7 +133,7 @@ class BookmarksViewModelTest { } @Test - fun whenBookmarkDeleteThenRepositoryUpdated() = runTest { + fun `onDeleteSavedSiteRequested - 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 `undoDelete - favorite delete - repository not updated`() = runTest { testee.onDeleteSavedSiteRequested(favorite) testee.undoDelete(favorite) @@ -160,7 +160,7 @@ class BookmarksViewModelTest { } @Test - fun whenFavoriteDeleteThenRepositoryUpdated() = runTest { + fun `onDeleteSavedSiteRequested - favorite delete - repository updated`() = runTest { testee.onDeleteSavedSiteRequested(favorite) testee.onDeleteSavedSiteSnackbarDismissed(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 `onDeleteSavedSiteRequested - confirm command`() { testee.onDeleteSavedSiteRequested(bookmark) verify(commandObserver).onChanged(commandCaptor.capture()) @@ -217,7 +217,7 @@ class BookmarksViewModelTest { } @Test - fun whenBookmarkFolderSelectedThenIssueOpenBookmarkFolderCommand() { + fun `onBookmarkFolderSelected - bookmark folder selected - 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 - update state with collected bookmarks and folders`() = runTest { val parentId = "folder1" testee.fetchBookmarksAndFolders(parentId = parentId) @@ -246,7 +246,7 @@ class BookmarksViewModelTest { } @Test - fun whenFetchEverythingThenUpdateStateWithData() = runTest { + fun `fetchAllBookmarksAndFolders - fetch everything - 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 - call insert on repository`() = 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,21 +287,21 @@ class BookmarksViewModelTest { } @Test - fun whenBookmarkFolderUpdatedThenCallUpdateOnRepository() = runTest { + fun `onBookmarkFolderUpdated - call update on repository`() = runTest { testee.onBookmarkFolderUpdated(bookmarkFolder) verify(savedSitesRepository).update(bookmarkFolder) } @Test - fun whenDeleteEmptyFolderRequestedThenCommandIssued() = runTest { + fun `onDeleteBookmarkFolderRequested - empty folder - command issued`() = runTest { testee.onDeleteBookmarkFolderRequested(bookmarkFolder) verify(commandObserver).onChanged(commandCaptor.capture()) assertEquals(bookmarkFolder, (commandCaptor.value as BookmarksViewModel.Command.ConfirmDeleteBookmarkFolder).bookmarkFolder) } @Test - fun whenDeleteFolderRequestedThenCommandIssued() = runTest { + fun `onDeleteBookmarkFolderRequested - command issued`() = runTest { val bookmarkFolder = BookmarkFolder(id = "folder1", name = "folder", parentId = SavedSitesNames.BOOKMARKS_ROOT, 1, 1, "timestamp") testee.onDeleteBookmarkFolderRequested(bookmarkFolder) @@ -310,7 +310,7 @@ class BookmarksViewModelTest { } @Test - fun whenDeleteBookmarkFolderUndoThenRepositoryNotUpdated() = runTest { + fun `undoDelete - delete bookmark folder - 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") @@ -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 - open saved site command sent`() { val savedSiteUrl = "https://www.example.com" testee.onBookmarkFoldersActivityResult(savedSiteUrl) @@ -369,7 +369,7 @@ class BookmarksViewModelTest { } @Test - fun whenUpdateBookmarksCalledThenUpdateFolderRelation() { + fun `updateBookmarks - updates 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..1130365e27ae 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 - call repo and update viewState`() = 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 - call repo and update viewState`() = 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..4b34394c007a 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 `fromSite - site is null - data is 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 - data contains url`() { val site = buildSite(SITE_URL) val data = BrokenSiteData.fromSite(site, reportFlow = MENU) assertEquals(SITE_URL, data.url) } @Test - fun whenSiteUpgradedThenHttpsUpgradedIsTrue() { + fun `fromSite - site upgraded - https upgraded is true`() { val site = buildSite(SITE_URL, httpsUpgraded = true) val data = BrokenSiteData.fromSite(site, reportFlow = MENU) assertTrue(data.upgradedToHttps) } @Test - fun whenSiteNotUpgradedThenHttpsUpgradedIsFalse() { + fun `fromSite - 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 `fromSite - url parameters removed - 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 `fromSite - url parameters not removed - urlParametersRemoved is false`() { val site = buildSite(SITE_URL) val data = BrokenSiteData.fromSite(site, reportFlow = MENU) assertFalse(data.urlParametersRemoved) } @Test - fun whenSiteHasNoTrackersThenBlockedTrackersIsEmpty() { + fun `fromSite - site has no trackers - blocked trackers is empty`() { val site = buildSite(SITE_URL) val data = BrokenSiteData.fromSite(site, reportFlow = MENU) assertTrue(data.blockedTrackers.isEmpty()) } @Test - fun whenSiteHasBlockedTrackersThenBlockedTrackersExist() { + fun `fromSite - site has blocked trackers - blocked trackers exist`() { val site = buildSite(SITE_URL) val event = TrackingEvent( documentUrl = "http://www.example.com", @@ -125,7 +125,7 @@ class BrokenSiteDataTest { } @Test - fun whenSiteHasSameHostBlockedTrackersThenOnlyUniqueTrackersIncludedInData() { + fun `fromSite - same host blocked trackers - only unique trackers included`() { val site = buildSite(SITE_URL) val event = TrackingEvent( documentUrl = "http://www.example.com", @@ -151,7 +151,7 @@ class BrokenSiteDataTest { } @Test - fun whenSiteHasBlockedCnamedTrackersThenBlockedTrackersExist() { + fun `fromSite - site has blocked CNAMEd trackers - 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 `fromSite - site has no surrogates - surrogates is empty`() { val site = buildSite(SITE_URL) val data = BrokenSiteData.fromSite(site, reportFlow = MENU) assertTrue(data.surrogates.isEmpty()) } @Test - fun whenSiteHasSurrogatesThenSurrogatesExist() { + fun `fromSite - site has surrogates - 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 `fromSite - same host surrogates - 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..4a975e519317 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 `submitBrokenSiteFeedback - VPN disabled - report false`() = runTest { whenever(networkProtectionState.isRunning()).thenReturn(false) val brokenSite = getBrokenSite() @@ -129,7 +129,7 @@ class BrokenSiteSubmitterTest { } @Test - fun whenVpnEnabledReportTrue() = runTest { + fun `submitBrokenSiteFeedback - vpn enabled - report true`() = 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 `submitBrokenSiteFeedback - 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 `submitBrokenSiteFeedback - site allowed - protections are 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 - successfully submitted - param sent and setLastSentDay called`() = 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 `submitBrokenSiteFeedback - device is English - include 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 `submitBrokenSiteFeedback - device is not English - do not include 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 is 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 - reportFlow is 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 - included 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..e5e454586d5f 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 added to repository`() = 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 added to repository`() = 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 - with source tabId - tab added to repository with source tabId`() = 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 - with tabs - 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 `viewStateCreated - webView content 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 `onOpenFavoriteFromWidget - 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 - with pixel name - pixel fired`() { val pixelName = "pixel_name" testee.onLaunchedFromNotification(pixelName) @@ -240,7 +240,7 @@ class BrowserViewModelTest { } @Test - fun whenOnBookmarksActivityResultCalledThenOpenSavedSiteCommandTriggered() { + fun `onBookmarksActivityResult - 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..b780cb9521ec 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 - less than max requests count with 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 with same URL - last call 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 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 `isUrlGeneratingDos - more than max requests with delay greater than limit - count is 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 - return 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 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..34c07cc057c4 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 - 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 - store missing atb - atb is 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 - url is serp query - return true`() { val uri = "http://duckduckgo.com/?q=weather".toUri() assertTrue(testee.shouldRewriteRequest(uri)) } @Test - fun whenShouldRewriteRequestAndUrlIsSerpQueryWithSourceAndAtbThenReturnFalse() { + fun `shouldRewriteRequest - URL is 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 - DuckDuckGo static URL - return 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..cab857f957a0 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 - not DDG URL`() { assertFalse(testee.isDuckDuckGoUrl("foo")) } @Test - fun whenCheckingNonDDGUrlThenIdentifiedAsNotDDGUrl() { + fun `isDuckDuckGoUrl - non-DDG URL - identified as not DDG URL`() { assertFalse(testee.isDuckDuckGoUrl("example.com")) } @Test - fun whenCheckingFullDDGUrlThenIdentifiedAsDDGUrl() { + fun `isDuckDuckGoUrl - 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 - subdomain and ETL is DDG - return true`() { assertTrue(testee.isDuckDuckGoUrl("https://test.duckduckgo.com")) } @Test - fun whenCheckingSubdomainAndETLDisNotDDGThenReturnFalse() { + fun `isDuckDuckGoUrl - subdomain and ETL is not DDG - return false`() { assertFalse(testee.isDuckDuckGoUrl("https://test.duckduckgo.test.com")) } @Test - fun whenDDGUrlContainsQueryThenQueryCanBeExtracted() { + fun `extractQuery - DDG URL contains query - query can be 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 - query is null`() { val query = testee.extractQuery("https://duckduckgo.com") assertNull(query) } @Test - fun whenDDGUrlContainsQueryThenQueryDetected() { + fun `isDuckDuckGoQueryUrl - DDG URL contains query - query detected`() { assertTrue(testee.isDuckDuckGoQueryUrl("https://duckduckgo.com?q=test%20search")) } @Test - fun whenDDGUrlDoesNotContainsQueryThenQueryIsNotDetected() { + fun `isDuckDuckGoQueryUrl - URL does not contain query - query not detected`() { assertFalse(testee.isDuckDuckGoQueryUrl("https://duckduckgo.com")) } @Test - fun whenNonDDGUrlContainsQueryThenQueryIsNotDetected() { + fun `isDuckDuckGoQueryUrl - non-DDG URL contains query - query is not detected`() { assertFalse(testee.isDuckDuckGoQueryUrl("https://example.com?q=test%20search")) } @Test - fun whenDDGUrlContainsVerticalThenVerticalCanBeExtracted() { + fun `extractVertical - DDG URL contains vertical - vertical can be extracted`() { 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 - vertical is null`() { val vertical = testee.extractVertical("https://duckduckgo.com") assertNull(vertical) } @Test - fun whenDDGUrlContainsVerticalThenVerticalUrlDetected() { + fun `isDuckDuckGoVerticalUrl - vertical URL detected`() { assertTrue(testee.isDuckDuckGoVerticalUrl("https://duckduckgo.com?ia=images")) } @Test - fun whenDDGUrlDoesNotContainsVerticalThenVerticalUrlIsNotDetected() { + fun `isDuckDuckGoVerticalUrl - URL does not contain vertical - 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 - DDG params page - static page detected`() { assertTrue(testee.isDuckDuckGoStaticUrl("https://duckduckgo.com/params")) } @Test - fun whenDDGIsNotStaticPageThenStaticPageIsNotDetected() { + fun `isDuckDuckGoStaticUrl - non-static page - not detected`() { assertFalse(testee.isDuckDuckGoStaticUrl("https://duckduckgo.com/something")) } @Test - fun whenNonDDGThenStaticPageIsDetected() { + fun `isDuckDuckGoStaticUrl - non DDG - static page detected`() { assertFalse(testee.isDuckDuckGoStaticUrl("https://example.com/settings")) } @Test - fun whenIsNotDuckDuckGoEmailUrlThenReturnFalse() { + fun `isDuckDuckGoEmailUrl - not DuckDuckGo email URL - return false`() { assertFalse(testee.isDuckDuckGoEmailUrl("https://example.com")) } @Test - fun whenIsDuckDuckEmailUrlGoThenReturnTrue() { + fun `isDuckDuckGoEmailUrl - DuckDuckGo email URL - return true`() { assertTrue(testee.isDuckDuckGoEmailUrl("https://duckduckgo.com/email")) } @Test - fun whenUrlContainsSubdomainAndIsETLDForDuckDuckGoEmailUrlThenReturnTrue() { + fun `isDuckDuckGoEmailUrl - url contains subdomain and is eTLD - return true`() { assertTrue(testee.isDuckDuckGoEmailUrl("https://test.duckduckgo.com/email")) } @Test - fun whenUrlContainsSubdomainAndIsNotETLDForDuckDuckGoEmailUrlThenReturnTrue() { + fun `isDuckDuckGoEmailUrl - url contains subdomain and is not eTLD - return true`() { assertFalse(testee.isDuckDuckGoEmailUrl("https://test.duckduckgo.test.com/email")) } @Test - fun whenUrlHasNoSchemeAndIsFromDuckDuckGoUrlThenReturnsFalse() { + fun `isDuckDuckGoEmailUrl - no scheme - 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..087be87484e6 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 `EmptyNavigationState - empty navigation state - browser properties are the same`() { val previousState = buildState("originalUrl", "currentUrl", "titlle") val emptyNavigationState = EmptyNavigationState(previousState) @@ -33,7 +33,7 @@ class EmptyNavigationStateTest { } @Test - fun whenEmptyNavigationStateFromNavigationStateThenNavigationPropertiesAreCleared() { + fun `EmptyNavigationState - from navigation state - navigation properties are 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..f7f691eab23e 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 - webView version is empty - return unknown`() { whenever(webViewVersionSource.get()).thenReturn("") assertEquals("unknown", testee.getFullVersion()) } @Test - fun whenWebViewVersionIsAvailableThenReturnFullVersion() { + fun `getFullVersion - webView version available - return full version`() { whenever(webViewVersionSource.get()).thenReturn("91.1.12.1234.423") assertEquals("91.1.12.1234.423", testee.getFullVersion()) } @Test - fun whenWebViewVersionIsBlankThenReturnFullVersion() { + fun `getFullVersion - webView version is blank - return full version`() { whenever(webViewVersionSource.get()).thenReturn(" ") assertEquals("unknown", testee.getFullVersion()) } @Test - fun whenWebViewVersionIsEmptyThenReturnUnknownMajorVersion() { + fun `getMajorVersion - webView version is empty - return unknown`() { whenever(webViewVersionSource.get()).thenReturn("") assertEquals("unknown", testee.getMajorVersion()) } @Test - fun whenWebViewVersionAvailableThenReturnMajorVersionOnly() { + fun `getMajorVersion - webView version available - return major version only`() { whenever(webViewVersionSource.get()).thenReturn("91.1.12.1234.423") assertEquals("91", testee.getMajorVersion()) } @Test - fun whenWebViewVersionHasNonNumericValuesThenReturnMajorVersionOnly() { + fun `getMajorVersion - webview version has non-numeric values - return major version only`() { whenever(webViewVersionSource.get()).thenReturn("59.amazon-webview-v59-3071.3071.125.462") assertEquals("59", testee.getMajorVersion()) } @Test - fun whenWebViewVersionHasNoValidDelimiterThenReturnUnknownMajorVersion() { + fun `getMajorVersion - no valid delimiter - return unknown`() { whenever(webViewVersionSource.get()).thenReturn("37%20%281448693564-arm%29") assertEquals("unknown", testee.getMajorVersion()) } @Test - fun whenWebViewVersionHasNonNumericMajorThenReturnUnknownMajorVersion() { + fun `getMajorVersion - non-numeric major version - unknown`() { whenever(webViewVersionSource.get()).thenReturn("37%20%28eng.jenkinswh-arm64%29") assertEquals("unknown", testee.getMajorVersion()) } @Test - fun whenWebViewVersionStartsWithDelimiterThenReturnUnknownMajorVersion() { + fun `getMajorVersion - webView version starts with delimiter - return unknown`() { whenever(webViewVersionSource.get()).thenReturn(".91.1.12.1234.423") assertEquals("unknown", testee.getMajorVersion()) } @Test - fun whenWebViewVersionIsBlankThenReturnUnknownMajorVersion() { + fun `getMajorVersion - webView version is blank - return unknown`() { 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..52f2bb6e719c 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 - 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 - 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 - missing scheme - http added`() { val input = "example.com" val expected = "http://$input" val result = testee.convertQueryToUrl(input) @@ -89,42 +89,42 @@ class QueryUrlConverterTest { } @Test - fun whenQueryOriginIsFromUserAndIsQueryThenSearchQueryBuilt() { + fun `convertQueryToUrl - query origin from user - search query built`() { val input = "foo" val result = testee.convertQueryToUrl(input, queryOrigin = QueryOrigin.FromUser) assertDuckDuckGoSearchQuery("foo", result) } @Test - fun whenQueryOriginIsFromUserAndIsUrlThenUrlReturned() { + fun `convertQueryToUrl - query origin 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 - query origin from autocomplete and isNav is 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 - query origin from autocomplete and isNav 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 - query origin from autocomplete and isNav is 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 a 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 - non-major vertical - vertical not added 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..56394e91c8da 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 - url is http - 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 - url is 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 URISyntaxException - return 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 - tel URL 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 smsto - 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 smsto - scheme removed`() { val type = testee.determineType("smsto:123-555-12323") as Sms assertEquals("123-555-12323", type.telephoneNumber) } @Test - fun whenUrlIsCustomUriSchemeThenNonHttpAppLinkTypeDetected() { + fun `determineType - custom URI scheme - non-http app link type detected`() { val type = testee.determineType("myapp:foo bar") as NonHttpAppLink assertEquals("myapp:foo bar", type.uriString) } @Test - fun whenUrlIsNotPrivacyProThenQueryTypeDetected() { + fun `determineType - url is 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 - privacy pro type detected`() { whenever(subscriptions.shouldLaunchPrivacyProForUrl(any())).thenReturn(true) val result = testee.determineType("duckduckgo.com") assertTrue(result is ShouldLaunchPrivacyProLink) } @Test - fun whenUrlIsParametrizedQueryThenSearchQueryTypeDetected() { + fun `determineType - parametrized query - search query type detected`() { val type = testee.determineType("foo site:duckduckgo.com") as SearchQuery assertEquals("foo site:duckduckgo.com", type.query) } @Test - fun whenUrlIsJavascriptSchemeThenWebSearchTypeDetected() { + fun `determineType - javascript scheme URL - web search type detected`() { val expected = SearchQuery::class val actual = testee.determineType("javascript:alert(0)") assertEquals(expected, actual::class) } @Test - fun whenUrlIsJavascriptSchemeThenFullQueryRetained() { + fun `determineType - javascript scheme URL - full query retained`() { val type = testee.determineType("javascript:alert(0)") as SearchQuery assertEquals("javascript:alert(0)", type.query) } @Test - fun whenUrlIsAboutSchemeThenWebSearchTypeDetected() { + fun `determineType - URL is 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 - file scheme URL - full query retained`() { val type = testee.determineType("file:///sdcard/") as SearchQuery assertEquals("file:///sdcard/", type.query) } @Test - fun whenUrlIsSiteSchemeThenWebSearchTypeDetected() { + fun `determineType - site scheme URL - web search type detected`() { val expected = SearchQuery::class val actual = testee.determineType("site:example.com") assertEquals(expected, actual::class) } @Test - fun whenUrlIsSiteSchemeThenFullQueryRetained() { + fun `determineType - site scheme URL - full query retained`() { val type = testee.determineType("site:example.com") as SearchQuery assertEquals("site:example.com", type.query) } @Test - fun whenUrlIsBlobSchemeThenFullQueryRetained() { + fun `determineType - blob scheme URL - 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 - truncate 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 longer than max allowed - truncate 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 - truncate 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 - truncate 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 - truncate 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 - AMP link - extracted AMP link type 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 - 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 - url is privacy pro - privacy pro link detected`() { 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..279a7a3ca6f9 100644 --- a/app/src/test/java/com/duckduckgo/app/browser/WebNavigationStateComparisonTest.kt +++ b/app/src/test/java/com/duckduckgo/app/browser/WebNavigationStateComparisonTest.kt @@ -31,104 +31,104 @@ import org.junit.runner.RunWith class WebNavigationStateComparisonTest { @Test - fun whenPreviousStateAndLatestStateSameThenCompareReturnsUnchanged() { + fun `compare - previous state and latest state same - returns 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 - returns 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 and latest contains original URL, current URL, and title - returns 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 and latest contains original URL and no title - returns 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 both - returns 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 state no original URL and current URL, latest state original and current URL - returns 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, latest contains original and current URL - returns 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 - different original url - returns 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 - same original URL different current URL domain - returns 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 - same original url and different current url 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 and current URL, latest contains none - returns page cleared`() { val previousState = buildState("http://previous.com", "http://subdomain.previous.com") val latestState = buildState(null, null) assertEquals(PageCleared, latestState.compare(previousState)) } @Test - fun whenPreviousContainsAnOriginalUrlAndCurrentUrlAndLatestStateContainsNoOriginalUrlAndACurrentUrlThenCompareReturnsPageCleared() { + fun `compare - previous contains original URL and current URL, latest contains no original URL and a current URL - returns page cleared`() { val previousState = buildState("http://previous.com", "http://subdomain.previous.com") val latestState = buildState(null, "http://subdomain.latest.com") assertEquals(PageCleared, latestState.compare(previousState)) } @Test - fun whenLatestStateIsEmptyNavigationCompareReturnsPageNavigationCleared() { + fun `compare - latest state is empty navigation - 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 - 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 - returns 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..249e54e56099 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 with image type 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 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() @@ -188,7 +188,7 @@ class WebViewLongPressHandlerTest { } @Test - fun whenInCustomTabAndUserLongPressesWithAnchorTypeAndHttpsThenCorrectOptionsAddedToMenu() { + fun `handleLongPress - custom tab with anchor type and https - correct options added to menu`() { whenever(mockCustomTabDetector.isCustomTab()).thenReturn(true) testee.handleLongPress(HitTestResult.SRC_ANCHOR_TYPE, HTTPS_IMAGE_URL, mockMenu) // Show "Copy Link Address", "Share Link" @@ -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 `userSelectedMenuItem - download image option - download file action 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 `userSelectedMenuItem - 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 `userSelectedMenuItem - download image option - 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 `userSelectedMenuItem - unknown option - no action required`() { 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..b867e817ee30 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 `navigationHistory - web history is empty - navigation history is empty`() { val stack = webViewState(stack).navigationHistory assertEquals(0, stack.size) } @Test - fun whenWebHistoryHasSinglePageThenNavigationHistoryRetrieved() { + fun `navigationHistory - single page - 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 `navigationHistory - multiple pages - 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..84f7992010b4 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 - return 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 - return false`() { assertFalse( testee.handleAppLink( isForMainFrame = false, @@ -82,7 +82,7 @@ class DuckDuckGoAppLinksHandlerTest { } @Test - fun whenAppLinkHandledOnApiLessThan24ThenReturnFalse() { + fun `handleAppLink - API less than 24 - return false`() { assertFalse( testee.handleAppLink( isForMainFrame = false, @@ -96,20 +96,20 @@ class DuckDuckGoAppLinksHandlerTest { } @Test - fun whenPreviousUrlUpdatedThenUpdatePreviousUrl() { + fun `updatePreviousUrl - previousUrl updated`() { testee.updatePreviousUrl("foo.com") assertEquals("foo.com", testee.previousUrl) } @Test - fun whenPreviousUrlUpdatedAndIsNullThenResetTriggerState() { + fun `updatePreviousUrl - previous URL is null - reset trigger state`() { testee.hasTriggeredForDomain = true testee.updatePreviousUrl(null) assertFalse(testee.hasTriggeredForDomain) } @Test - fun whenPreviousUrlUpdatedAndPreviousUrlIsNullThenDoNotResetTriggerState() { + fun `updatePreviousUrl - previousUrl 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 - 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 - return false`() { assertFalse( testee.handleAppLink( isForMainFrame = true, @@ -146,7 +146,7 @@ class DuckDuckGoAppLinksHandlerTest { } @Test - fun whenPreviousUrlIsSameThenReturnFalse() { + fun `handleAppLink - previous URL is same - return false`() { testee.previousUrl = "example.com" assertFalse( testee.handleAppLink( @@ -160,7 +160,7 @@ class DuckDuckGoAppLinksHandlerTest { } @Test - fun whenPreviousUrlIsSubdomainThenReturnFalse() { + fun `handleAppLink - previous URL is subdomain - return false`() { testee.previousUrl = "foo.example.com" assertFalse( testee.handleAppLink( @@ -174,7 +174,7 @@ class DuckDuckGoAppLinksHandlerTest { } @Test - fun whenNextUrlIsSubdomainThenReturnFalse() { + fun `handleAppLink - next URL is subdomain - return false`() { testee.previousUrl = "example.com" assertFalse( testee.handleAppLink( @@ -188,7 +188,7 @@ class DuckDuckGoAppLinksHandlerTest { } @Test - fun whenAppLinkIsSameOrSubdomainAndIsUserQueryThenReturnFalseAndSetPreviousUrlAndLaunchAppLink() { + fun `handleAppLink - same or subdomain and user query - return false and 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 not triggered for domain - return false and 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 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 triggered for domain and not in always trigger list - return 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..36ffb067a492 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,25 +35,25 @@ 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 `autofillSaveOrUpdateDialogVisibilityChanged - dismissed recently - preventing prompts`() { testee.autofillSaveOrUpdateDialogVisibilityChanged(true) testee.autofillSaveOrUpdateDialogVisibilityChanged(false) assertTrue(testee.isAutofillPreventingFireproofPrompts()) } @Test - fun whenSaveOrUpdateDialogDismissedAWhileBackThenPreventingPrompts() { + fun `autofillSaveOrUpdateDialogVisibilityChanged - dismissed a while back - preventing prompts`() { testee.autofillSaveOrUpdateDialogVisibilityChanged(true) testee.autofillSaveOrUpdateDialogVisibilityChanged(false) configureTimeNow(System.currentTimeMillis() + 20_000) 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..b71035f3d39a 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 - pixel fired`() = runTest { testee.onCustomTabCreated("url", 100) testee.viewState.test { @@ -44,14 +44,14 @@ class CustomTabViewModelTest { } @Test - fun whenCustomTabShownThenCustomTabDetectorSetToTrue() { + fun `onShowCustomTab - custom tab shown - custom tab detector set to true`() { testee.onShowCustomTab() verify(mockCustomTabDetector).setCustomTab(true) } @Test - fun whenCustomTabClosedThenCustomTabDetectorSetToFalse() { + fun `onCloseCustomTab - custom tab closed - 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..ce1f53fa0173 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 is requested`() = runTest { val text = "url" val toolbarColor = 100 configureHasSession(true) @@ -56,7 +56,7 @@ class IntentDispatcherViewModelTest { } @Test - fun whenIntentReceivedWithoutSessionThenCustomTabIsNotRequested() = runTest { + fun `onIntentReceived - without session - custom tab is 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 - email protection verification link - custom tab not requested`() = runTest { configureHasSession(true) configureIsEmailProtectionLink(true) @@ -85,7 +85,7 @@ class IntentDispatcherViewModelTest { } @Test - fun whenIntentReceivedWithSessionAndLinkIsNotEmailProtectionVerificationThenCustomTabIsRequested() = runTest { + fun `onIntentReceived - link is not email protection verification - custom tab requested`() = runTest { configureHasSession(true) configureIsEmailProtectionLink(false) @@ -98,7 +98,7 @@ class IntentDispatcherViewModelTest { } @Test - fun whenIntentReceivedWithSessionAndUrlContainingSpacesThenSpacesAreReplacedAndCustomTabIsRequested() = runTest { + fun `onIntentReceived - url containing spaces - spaces are replaced and 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 and intent text with spaces not starting with http - no changes to 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 text with spaces and no http schema - no changes to 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..33be1b8b7282 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 set as default browser - 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 is not default browser and 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 `onResume - DDG is default browser - do 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 was default browser but now is not - 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..c2c0f9388bfc 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`() { 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..2ec835806a61 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 - should 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 - should add mime type extra`() { val output = testee.intent(arrayOf("image/png", "image/gif")) assertTrue(output.hasExtra(Intent.EXTRA_MIME_TYPES)) } @Test - fun whenUpperCaseTypesGivenThenNormalisedToLowercase() { + fun `intent - uppercase types given - normalised to lowercase`() { 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 - single URI non-empty clip - URI returned`() { 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`() { val intent = buildIntent("a", listOf("b", "c")) val extractedUris = testee.extractSelectedFileUris(intent) @@ -119,7 +119,7 @@ class FileChooserIntentBuilderTest { } @Test - fun whenExtractingSingleUriMissingButClipDataAvailableThenUriReturnedFromClip() { + fun `extractSelectedFileUris - single URI missing but 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..67de73d98bdc 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 `loginDetected - 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..ee4ccde242d6 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 `onEvent - login attempted and user forwarded to new page - 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 `onEvent - login attempted inside OAuth flow - login detected when 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 `onEvent - login attempted inside SSO flow - login detected when forwarded to different domain`() = runTest { givenLoginDetector(enabled = true) fullyLoadSite("https://app.asana.com/-/login") giveLoginDetectorChanceToExecute() @@ -108,7 +108,7 @@ class NextPageLoginDetectionTest { } @Test - fun whenLoginAttemptedSkip2FAUrlsThenLoginDetectedForLatestOne() = runTest { + fun `onEvent - skip 2FA URLs - 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 `onEvent - multiple new pages - 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 - 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 `giveLoginDetectorChanceToExecute - forwarded to new page - login not detected`() = runTest { givenLoginDetector(enabled = true) fullyLoadSite("http://example.com") giveLoginDetectorChanceToExecute() @@ -161,7 +161,7 @@ class NextPageLoginDetectionTest { } @Test - fun whenLoginAttemptedAndUserForwardedToNewUrlThenLoginDetected() = runTest { + fun `onEvent - user forwarded to new URL - login detected`() = runTest { givenLoginDetector(enabled = true) loginDetector.onEvent(NavigationEvent.LoginAttempt("http://example.com/login")) @@ -173,7 +173,7 @@ class NextPageLoginDetectionTest { } @Test - fun whenLoginAttemptedAndUserForwardedToSameUrlThenLoginNotDetected() = runTest { + fun `onEvent - 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 `onEvent - forwarded to new URL - 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 `onEvent - login attempted and next page finished - does not detect login`() = 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 `onEvent - user navigates back after login attempt - new page does not detect login`() = 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 `onEvent - user navigates forward after login attempt - new page does not detect login`() = 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 `onEvent - user reloads website after login attempt - new page does not detect login`() = 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 `onEvent - user submits new query after login attempt - new page 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 `onEvent - 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 `onEvent - forwarded to invalid new page - login detected`() = 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..c83f91c51893 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 `isOAuthUrl - valid auth URL - return true`() { 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 `is2FAUrl - valid 2FA URL - return 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 - return 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..b085145ed9d5 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 - values loaded into memory`() { givenMediaPlaybackDaoContainsEntities() initRepository() @@ -38,7 +38,7 @@ class RealMediaPlaybackRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = runTest { + fun `updateAll - updateAll 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..f79d612a97ad 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 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 - 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..12155c1aab1b 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 `onActivityStarted - first activity created - notify fresh app launch`() { browserApplicationStateInfo.onActivityCreated(activity, null) browserApplicationStateInfo.onActivityStarted(activity) @@ -62,7 +62,7 @@ class BrowserApplicationStateInfoTest { } @Test - fun whenAllActivitiesStopAndRestartThenNotifyAppOpen() { + fun `onActivityStateChange - all activities stop and restart - notify app open`() { browserApplicationStateInfo.onActivityCreated(activity, null) browserApplicationStateInfo.onActivityCreated(activity, null) @@ -82,7 +82,7 @@ class BrowserApplicationStateInfoTest { } @Test - fun whenAllActivitiesAreDestroyedAndRecreatedThenNotifyFreshAppLaunch() { + fun `onActivityCreated - all activities destroyed and recreated - notify fresh app launch`() { browserApplicationStateInfo.onActivityCreated(activity, null) browserApplicationStateInfo.onActivityCreated(activity, null) @@ -106,7 +106,7 @@ class BrowserApplicationStateInfoTest { } @Test - fun whenAllActivitiesAreDestroyedByBackPressAndRecreatedThenDoNotNotifyFreshAppLaunch() { + fun `onActivityDestroyed - all activities destroyed by back press and recreated - do not notify fresh app launch`() { activity.destroyedByBackPress = true browserApplicationStateInfo.onActivityCreated(activity, null) @@ -132,7 +132,7 @@ class BrowserApplicationStateInfoTest { } @Test - fun whenAllActivitiesAreDestroyedByConfigChangeAndRecreatedThenDoNotNotifyFreshAppLaunch() { + fun `onActivityLifecycle - config change and recreate - 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..7e37361bb7d6 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 - url is 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..1c673959a397 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 `createIntent - title and url and text empty - 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 `createIntent - title and url and text null - 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 `createIntent - title empty and url - parse correct data`() { val data = JsCallbackData( params = JSONObject("""{"title":"","url":"https://example.com/"}"""), featureName = "featureName", @@ -75,7 +75,7 @@ class WebShareChooserTest { } @Test - fun whenTitleAndUrlAndTextThenParseCorrectData() { + fun `createIntent - title and url and text - 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 `createIntent - title and text and url empty - 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 `createIntent - title and text and url null - 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 - 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 - result is 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 - result 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 - result 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..934120d373b9 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`() { 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`() { 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`() { val testee = HomePanelCta.Survey(Survey("abc", "http://example.com", 1, Survey.Status.SCHEDULED)) assertTrue(testee.pixelShownParameters().isEmpty()) } @Test - fun whenCtaIsAddWidgetAutoReturnEmptyOkParameters() { + fun `pixelOkParameters - add widget auto - return empty`() { val testee = HomePanelCta.AddWidgetAuto assertTrue(testee.pixelOkParameters().isEmpty()) } @Test - fun whenCtaIsAddWidgetAutoReturnEmptyCancelParameters() { + fun `pixelCancelParameters - cta is add widget auto - return empty cancel parameters`() { val testee = HomePanelCta.AddWidgetAuto assertTrue(testee.pixelCancelParameters().isEmpty()) } @Test - fun whenCtaIsAddWidgetAutoReturnEmptyShownParameters() { + fun `pixelShownParameters - add widget auto - return empty`() { val testee = HomePanelCta.AddWidgetAuto assertTrue(testee.pixelShownParameters().isEmpty()) } @Test - fun whenCtaIsAddWidgetInstructionsReturnEmptyOkParameters() { + fun `pixelOkParameters - cta is add widget instructions - return empty`() { val testee = HomePanelCta.AddWidgetInstructions assertTrue(testee.pixelOkParameters().isEmpty()) } @Test - fun whenCtaIsAddWidgetInstructionsReturnEmptyCancelParameters() { + fun `pixelCancelParameters - cta is add widget instructions - return empty`() { val testee = HomePanelCta.AddWidgetInstructions assertTrue(testee.pixelCancelParameters().isEmpty()) } @Test - fun whenCtaIsAddWidgetInstructionsReturnEmptyShownParameters() { + fun `pixelShownParameters - add widget instructions - return empty`() { val testee = HomePanelCta.AddWidgetInstructions assertTrue(testee.pixelShownParameters().isEmpty()) } @Test - fun whenCtaIsBubbleTypeReturnCorrectCancelParameters() { + fun `pixelCancelParameters - cta is bubble type - return 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 - return 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 - return 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 - return 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`() { 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 `canSendShownPixel - cta not part of history - return true`() { whenever(mockOnboardingStore.onboardingDialogJourney).thenReturn("s:0") val testee = DaxBubbleCta.DaxEndCta(mockOnboardingStore, mockAppInstallStore) assertTrue(testee.canSendShownPixel()) } @Test - fun whenCanSendPixelAndCtaNotPartOfHistoryButIsASubstringThenReturnTrue() { + fun `canSendShownPixel - cta not part of history but is a substring - return true`() { whenever(mockOnboardingStore.onboardingDialogJourney).thenReturn("s:0-te:0") val testee = DaxBubbleCta.DaxEndCta(mockOnboardingStore, mockAppInstallStore) assertTrue(testee.canSendShownPixel()) } @Test - fun whenCanSendPixelAndCtaIsPartOfHistoryThenReturnFalse() { + fun `canSendShownPixel - cta is part of history - return 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 - return 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 - concatenate journey stored value`() { 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 - return 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 - return them 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 - return sorted by prevalence`() { val trackers = listOf( TrackingEvent( documentUrl = "facebook.com", @@ -338,7 +338,7 @@ class CtaTest { } @Test - fun whenTrackersBlockedReturnOnlyTrackersWithDisplayName() { + fun `getDaxText - trackers blocked - return only trackers with display name`() { val trackers = listOf( TrackingEvent( documentUrl = "facebook.com", @@ -373,7 +373,7 @@ class CtaTest { } @Test - fun whenTrackersBlockedReturnOnlyTrackersBlocked() { + fun `getDaxText - trackers blocked - return 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 - return only 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 `pixelShownParameters - try clear data CTA shown - concatenate journey stored value`() { 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..44983fa17349 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 - no downloads and visibility false - viewState 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 - no downloads and visibility true - viewState 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 - visibility false - viewState 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 - visibility true - viewState emitted with notify me, 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 false - viewState 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 `deleteAllDownloadedItems - repository deleteAll 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 insertAll called`() = runTest { val firstItem = oneItem() val secondItem = otherItem() @@ -239,7 +239,7 @@ class DownloadsViewModelTest { } @Test - fun whenOnQueryTextChangeThenViewStateEmittedWithTwoFilteredItems() = runTest { + fun `onQueryTextChange - viewState 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 - no matching items - viewState 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 - open file command sent`() = 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 - removes it`() = 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..0c424a5a16d0 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 - fetch alias from service - store alias with 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 - returns next alias`() = runTest { givenNextAliasExists() assertEquals("alias", testee.getAlias()) } @Test - fun whenGetAliasIfNextAliasDoesNotExistThenReturnNull() { + fun `getAlias - next alias does not exist - return null`() { assertNull(testee.getAlias()) } @Test - fun whenGetAliasThenClearNextAlias() { + fun `getAlias - clear next alias`() { testee.getAlias() assertNull(mockEmailDataStore.nextAlias) } @Test - fun whenIsSignedInAndTokenDoesNotExistThenReturnFalse() { + fun `isSignedIn - token does not exist - return false`() { mockEmailDataStore.emailUsername = "username" mockEmailDataStore.nextAlias = "alias" @@ -128,7 +128,7 @@ class AppEmailManagerTest { } @Test - fun whenIsSignedInAndUsernameDoesNotExistThenReturnFalse() { + fun `isSignedIn - username does not exist - return false`() { mockEmailDataStore.emailToken = "token" mockEmailDataStore.nextAlias = "alias" @@ -136,7 +136,7 @@ class AppEmailManagerTest { } @Test - fun whenIsSignedInAndTokenAndUsernameExistThenReturnTrue() { + fun `isSignedIn - token and username exist - return true`() { mockEmailDataStore.emailToken = "token" mockEmailDataStore.emailUsername = "username" @@ -144,7 +144,7 @@ class AppEmailManagerTest { } @Test - fun whenStoreCredentialsThenGenerateNewAlias() = runTest { + fun `storeCredentials - 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 - 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 - send pixel`() = runTest { mockEmailDataStore.emailToken = "token" whenever(mockEmailService.newAlias(any())).thenReturn(EmailAlias("")) @@ -174,7 +174,7 @@ class AppEmailManagerTest { } @Test - fun whenStoreCredentialsThenCredentialsAreStoredInDataStore() { + fun `storeCredentials - credentials are stored in data store`() { testee.storeCredentials("token", "username", "cohort") assertEquals("username", mockEmailDataStore.emailUsername) @@ -183,21 +183,21 @@ class AppEmailManagerTest { } @Test - fun whenStoreCredentialsIfCredentialsWereCorrectlyStoredThenIsSignedInChannelSendsTrue() = runTest { + fun `storeCredentials - credentials correctly stored - isSignedInChannel sends true`() = runTest { testee.storeCredentials("token", "username", "cohort") assertTrue(testee.signedInFlow().first()) } @Test - fun whenStoreCredentialsIfCredentialsAreBlankThenIsSignedInChannelSendsFalse() = runTest { + fun `storeCredentials - credentials are blank - sends false`() = runTest { testee.storeCredentials("", "", "cohort") assertFalse(testee.signedInFlow().first()) } @Test - fun whenSignedOutThenClearEmailDataAndAliasIsNull() { + fun `signedOut - 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 - isSignedInChannel sends false`() = runTest { testee.signOut() assertFalse(testee.signedInFlow().first()) } @Test - fun whenGetEmailAddressThenDuckEmailDomainIsAppended() { + fun `getEmailAddress - duck email domain appended`() { mockEmailDataStore.emailUsername = "username" assertEquals("username$DUCK_EMAIL_DOMAIN", testee.getEmailAddress()) } @Test - fun whenGetCohortThenReturnCohort() { + fun `getCohort - return cohort`() { 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 - return unknown`() { mockEmailDataStore.cohort = "" assertEquals(UNKNOWN_COHORT, testee.getCohort()) } @Test - fun whenIsEmailFeatureSupportedAndEncryptionCanBeUsedThenReturnTrue() { + fun `isEmailFeatureSupported - encryption can be used - return true`() { (mockEmailDataStore as FakeEmailDataStore).canUseEncryption = true assertTrue(testee.isEmailFeatureSupported()) } @Test - fun whenGetLastUsedDateIfNullThenReturnEmpty() { + fun `getLastUsedDate - null - return empty`() { assertEquals("", testee.getLastUsedDate()) } @Test - fun whenGetLastUsedDateIfNotNullThenReturnValueFromStore() { + fun `getLastUsedDate - not null - return value from store`() { mockEmailDataStore.lastUsedDate = "2021-01-01" assertEquals("2021-01-01", testee.getLastUsedDate()) } @Test - fun whenIsEmailFeatureSupportedAndEncryptionCannotBeUsedThenReturnFalse() { + fun `isEmailFeatureSupported - encryption cannot be used - return 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 `signedInFlow - syncable setting 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..e1c9d00b19d1 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 - url is DuckDuckGo email - isSignedIn called`() { whenever(mockWebView.url).thenReturn(DUCKDUCKGO_EMAIL_URL) testee.isSignedIn() @@ -75,7 +75,7 @@ class EmailJavascriptInterfaceTest { } @Test - fun whenIsSignedInAndUrlIsNotDuckDuckGoEmailThenIsSignedInNotCalled() { + fun `isSignedIn - url is not DuckDuckGo email - isSignedIn not called`() { whenever(mockWebView.url).thenReturn(NON_EMAIL_URL) testee.isSignedIn() @@ -84,7 +84,7 @@ class EmailJavascriptInterfaceTest { } @Test - fun whenStoreCredentialsAndUrlIsDuckDuckGoEmailThenStoreCredentialsCalledWithCorrectParameters() { + fun `storeCredentials - DuckDuckGo email URL - 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 - getUserData 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 - getUserData 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 - DuckDuckGo email URL - 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 - return 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..77a575055c32 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 - return account info`() { whenever(emailDataStoreMock.emailUsername).thenReturn("username") whenever(emailDataStoreMock.emailToken).thenReturn("token") @@ -34,7 +34,7 @@ class EmailSyncTest { } @Test - fun whenUserSignedOutThenReturnNull() { + fun `getValue - user signed out - return null`() { whenever(emailDataStoreMock.emailUsername).thenReturn(null) whenever(emailDataStoreMock.emailToken).thenReturn(null) @@ -44,7 +44,7 @@ class EmailSyncTest { } @Test - fun whenSaveValueThenStoreCredentials() { + fun `save - store credentials`() { 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..233b2da2b9b2 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 - can submit`() { assertTrue(viewState.submitAllowed) } @Test - fun whenNoCategorySelectedThenCanSubmit() { + fun `canSubmit - no category selected`() { selectAndAcceptCategory(-1) assertTrue(viewState.submitAllowed) } @Test - fun whenCategorySelectedButNotChangedThenReturnOldCategory() { + fun `onCategoryAccepted - category selected but not changed - return old category`() { testee.onCategoryIndexChanged(0) testee.onCategoryAccepted() testee.onCategoryIndexChanged(1) @@ -141,13 +141,13 @@ class BrokenSiteViewModelTest { } @Test - fun whenCategoryAcceptedAndIncorrectIndexThenReturnNullCategory() { + fun `selectAndAcceptCategory - incorrect index - return null category`() { selectAndAcceptCategory(-1) assertNull(viewState.categorySelected) } @Test - fun whenCategoryAcceptedAndCorrectIndexThenReturnCategory() { + fun `selectAndAcceptCategory - correct index - return category`() { val indexSelected = 0 selectAndAcceptCategory(indexSelected) @@ -156,7 +156,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenCanSubmitBrokenSiteAndUrlNotNullAndSubmitPressedThenReportAndPixelSubmitted() { + fun `onSubmitPressed - url not null - report and pixel submitted`() { testee.setInitialBrokenSite( url = url, blockedTrackers = "", @@ -199,7 +199,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenCanSubmitBrokenSiteAndUrlIsEmptyAndSubmitPressedThenDoNotSubmit() { + fun `onSubmitPressed - url is empty - do not submit`() { val nullUrl = "" testee.setInitialBrokenSite( url = nullUrl, @@ -243,7 +243,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenCanSubmitBrokenSiteAndLastAmpLinkIsNullAndSubmitPressedThenReportUrlAndPixelSubmitted() { + fun `onSubmitPressed - last AMP link is null - report URL and pixel submitted`() { whenever(mockAmpLinks.lastAmpLinkInfo).thenReturn(null) testee.setInitialBrokenSite( @@ -288,7 +288,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenCanSubmitBrokenSiteAndUrlHasAssociatedAmpLinkAndSubmitPressedThenAmpLinkReportedAndPixelSubmitted() { + fun `onSubmitPressed - url has associated amp link - 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 `onSubmitPressed - url not null - 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 - is desktop mode true - send desktop parameter`() { testee.setInitialBrokenSite( url = url, blockedTrackers = "", @@ -384,7 +384,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenDesktopModeIsFalseThenSendMobileParameter() { + fun `setInitialBrokenSite - desktop mode false - send mobile parameter`() { testee.setInitialBrokenSite( url = url, blockedTrackers = "", @@ -406,7 +406,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenGetBrokenSiteThenReturnCorrectCategory() { + fun `getBrokenSite - return 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 `onSubmitPressed - category logins - use login site`() { val categoryIndex = testee.shuffledCategories.indexOfFirst { it.key == BrokenSiteCategory.LOGIN_CATEGORY_KEY } testee.setInitialBrokenSite( @@ -521,7 +521,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenCategoryIsNotLoginsThenDoNotUseLoginSite() { + fun `onSubmitPressed - category is not logins - 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 - site protections toggled - allowlist is updated`() = runTest { val url = "https://stuff.example.com" testee.setInitialBrokenSite( @@ -598,7 +598,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenContentBlockingIsDisabledThenSiteProtectionsAreDisabled() { + fun `setInitialBrokenSite - content blocking disabled - site protections disabled`() { whenever(mockFeatureToggle.isFeatureEnabled(PrivacyFeatureName.ContentBlockingFeatureName.value)) .thenReturn(false) @@ -621,7 +621,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenUrlIsInUnprotectedTemporaryExceptionsThenSiteProtectionsAreDisabled() { + fun `setInitialBrokenSite - url in unprotected temporary exceptions - site protections disabled`() { whenever(mockFeatureToggle.isFeatureEnabled(PrivacyFeatureName.ContentBlockingFeatureName.value)) .thenReturn(true) @@ -647,7 +647,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenUrlIsInContentBlockingExceptionsThenSiteProtectionsAreDisabled() { + fun `setInitialBrokenSite - url in content blocking exceptions - site protections disabled`() { whenever(mockFeatureToggle.isFeatureEnabled(PrivacyFeatureName.ContentBlockingFeatureName.value)) .thenReturn(true) @@ -673,7 +673,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenUrlIsInUserAllowlistThenSiteProtectionsAreDisabled() { + fun `setInitialBrokenSite - url in user allowlist - site protections are disabled`() { whenever(mockFeatureToggle.isFeatureEnabled(PrivacyFeatureName.ContentBlockingFeatureName.value)) .thenReturn(true) @@ -698,7 +698,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenUrlIsNotInUserAllowlistThenSiteProtectionsAreEnabled() { + fun `setInitialBrokenSite - url not in user allowlist - site protections enabled`() { whenever(mockFeatureToggle.isFeatureEnabled(PrivacyFeatureName.ContentBlockingFeatureName.value)) .thenReturn(true) @@ -723,7 +723,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenUrlIsAddedToUserAllowlistThenPixelIsFired() = runTest { + fun `onProtectionsToggled - url added to user allowlist - pixel fired`() = runTest { testee.setInitialBrokenSite( url = url, blockedTrackers = "", @@ -744,7 +744,7 @@ class BrokenSiteViewModelTest { } @Test - fun whenUrlIsRemovedFromUserAllowlistThenPixelIsFired() = runTest { + fun `onProtectionsToggled - url removed from user allowlist - 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..75b9de435c09 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 `initialised - fragment state is for first step`() { assertTrue(updateViewCommand is InitialAppEnjoymentClarifier) } @Test - fun whenCanRateAppAndUserSelectsInitialHappyFaceThenFragmentStateIsFirstStepOfHappyFlow() { + fun `userSelectedPositiveFeedback - can rate app - first step of happy flow`() { configureRatingCanBeGiven() testee.userSelectedPositiveFeedback() assertTrue(updateViewCommand is FragmentState.PositiveFeedbackFirstStep) @@ -96,7 +96,7 @@ class FeedbackViewModelTest { } @Test - fun whenCannotRateAppAndUserSelectsInitialHappyFaceThenFragmentStateSkipsStraightToSharingFeedback() { + fun `userSelectedPositiveFeedback - cannot rate app - skips to sharing feedback`() { configureRatingCannotBeGiven() testee.userSelectedPositiveFeedback() assertTrue(updateViewCommand is FragmentState.PositiveShareFeedback) @@ -104,7 +104,7 @@ class FeedbackViewModelTest { } @Test - fun whenCanRateAppAndUserNavigatesBackFromPositiveInitialFragmentThenFragmentStateIsInitialFragment() { + fun `onBackPressed - user navigates back from positive initial fragment - fragment state is initial fragment`() { configureRatingCanBeGiven() testee.userSelectedPositiveFeedback() testee.onBackPressed() @@ -114,7 +114,7 @@ class FeedbackViewModelTest { } @Test - fun whenCannotRateAppAndUserNavigatesBackFromPositiveInitialFragmentThenFragmentStateIsInitialFragment() { + fun `onBackPressed - cannot rate app and user navigates back from positive initial fragment - fragment state is initial fragment`() { configureRatingCannotBeGiven() testee.userSelectedPositiveFeedback() testee.onBackPressed() @@ -123,14 +123,14 @@ class FeedbackViewModelTest { } @Test - fun whenUserChoosesNotToProvideFurtherDetailsForPositiveFeedbackThenSubmitted() = runTest { + fun `userGavePositiveFeedbackNoDetails - submitted`() = runTest { testee.userGavePositiveFeedbackNoDetails() verify(feedbackSubmitter).sendPositiveFeedback(null) } @Test - fun whenUserChoosesNotToProvideFurtherDetailsForPositiveFeedbackThenExitCommandIssued() = runTest { + fun `userGavePositiveFeedbackNoDetails - exit command issued`() = runTest { testee.userGavePositiveFeedbackNoDetails() val command = captureCommand() as Command.Exit @@ -138,14 +138,14 @@ class FeedbackViewModelTest { } @Test - fun whenUserProvidesFurtherDetailsForPositiveFeedbackThenFeedbackSubmitted() = runTest { + fun `userProvidedPositiveOpenEndedFeedback - feedback submitted`() = runTest { testee.userProvidedPositiveOpenEndedFeedback("foo") verify(feedbackSubmitter).sendPositiveFeedback("foo") } @Test - fun whenUserProvidesFurtherDetailsForPositiveFeedbackThenExitCommandIssued() = runTest { + fun `userProvidedPositiveOpenEndedFeedback - exit command issued`() = runTest { testee.userProvidedPositiveOpenEndedFeedback("foo") val command = captureCommand() as Command.Exit @@ -153,39 +153,39 @@ class FeedbackViewModelTest { } @Test - fun whenUserProvidesNegativeFeedbackThenFeedbackSubmitted() = runTest { + fun `userProvidedNegativeOpenEndedFeedback - 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 `userProvidedNegativeOpenEndedFeedback - 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 `userProvidedNegativeOpenEndedFeedback - 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`() { testee.userWantsToCancel() val command = captureCommand() as Command.Exit assertFalse(command.feedbackSubmitted) } @Test - fun whenUserSelectsInitialSadFaceThenFragmentStateIsFirstStepOfUnhappyFlow() { + fun `userSelectedNegativeFeedback - initial sad face - first step of unhappy flow`() { testee.userSelectedNegativeFeedback() assertTrue(updateViewCommand is NegativeFeedbackMainReason) verifyForwardsNavigation(updateViewCommand) } @Test - fun whenUserNavigatesBackFromNegativeMainReasonFragmentThenFragmentStateIsInitialFragment() { + fun `onBackPressed - navigates back from negative main reason fragment - fragment state is initial fragment`() { testee.userSelectedNegativeFeedback() testee.onBackPressed() assertTrue(updateViewCommand is InitialAppEnjoymentClarifier) @@ -193,56 +193,56 @@ class FeedbackViewModelTest { } @Test - fun whenUserSelectsMainNegativeReasonMissingBrowserFeaturesThenFragmentStateIsSubReasonSelection() { + fun `userSelectedNegativeFeedbackMainReason - missing browser features - fragment state is sub reason selection`() { testee.userSelectedNegativeFeedbackMainReason(MISSING_BROWSING_FEATURES) assertTrue(updateViewCommand is NegativeFeedbackSubReason) verifyForwardsNavigation(updateViewCommand) } @Test - fun whenUserSelectsMainNegativeReasonNotEnoughCustomizationsThenFragmentStateIsSubReasonSelection() { + fun `userSelectedNegativeFeedbackMainReason - not enough customizations - fragment state is sub reason selection`() { testee.userSelectedNegativeFeedbackMainReason(NOT_ENOUGH_CUSTOMIZATIONS) assertTrue(updateViewCommand is NegativeFeedbackSubReason) verifyForwardsNavigation(updateViewCommand) } @Test - fun whenUserSelectsMainNegativeReasonSearchNotGoodEnoughThenFragmentStateIsSubReasonSelection() { + fun `userSelectedNegativeFeedbackMainReason - search not good enough - fragment state is sub reason selection`() { testee.userSelectedNegativeFeedbackMainReason(SEARCH_NOT_GOOD_ENOUGH) assertTrue(updateViewCommand is NegativeFeedbackSubReason) verifyForwardsNavigation(updateViewCommand) } @Test - fun whenUserSelectsMainNegativeReasonAppIsSlowOrBuggyThenFragmentStateIsSubReasonSelection() { + fun `userSelectedNegativeFeedbackMainReason - app is slow or buggy - fragment state is sub reason selection`() { testee.userSelectedNegativeFeedbackMainReason(APP_IS_SLOW_OR_BUGGY) assertTrue(updateViewCommand is NegativeFeedbackSubReason) verifyForwardsNavigation(updateViewCommand) } @Test - fun whenUserSelectsMainNegativeReasonOtherThenFragmentStateIsOpenEndedFeedback() { + fun `userSelectedNegativeFeedbackMainReason - selects other - fragment state is open ended feedback`() { testee.userSelectedNegativeFeedbackMainReason(OTHER) assertTrue(updateViewCommand is NegativeOpenEndedFeedback) verifyForwardsNavigation(updateViewCommand) } @Test - fun whenUserSelectsMainNegativeReasonBrokenSiteThenFragmentStateIsSubReasonSelection() { + fun `userSelectedNegativeFeedbackMainReason - main reason broken site - fragment state is sub reason selection`() { testee.userSelectedNegativeFeedbackMainReason(WEBSITES_NOT_LOADING) assertTrue(updateViewCommand is NegativeWebSitesBrokenFeedback) verifyForwardsNavigation(updateViewCommand) } @Test - fun whenUserSelectsSubNegativeReasonThenFragmentStateIsOpenEndedFeedback() { + fun `userSelectedSubReasonMissingBrowserFeatures - fragment state is open-ended feedback`() { testee.userSelectedSubReasonMissingBrowserFeatures(MISSING_BROWSING_FEATURES, TAB_MANAGEMENT) assertTrue(updateViewCommand is NegativeOpenEndedFeedback) verifyForwardsNavigation(updateViewCommand) } @Test - fun whenUserNavigatesBackFromSubReasonSelectionThenFragmentStateIsMainReasonSelection() { + fun `onBackPressed - navigates back from sub reason selection - fragment state is 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 - valid sub reason - 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 - sub reason not a valid step - 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 - navigates back from open-ended feedback - fragment state is sub reason selection`() { 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..ddb2a6e366d6 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 - drop prefix`() { val fireproofWebsiteEntity = FireproofWebsiteEntity("www.example.com") val website = fireproofWebsiteEntity.website() assertEquals("example.com", website) } @Test - fun whenDomainStartsWithWWWUppercaseThenDropPrefix() { + fun `website - domain starts with WWW uppercase - drop 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 - domain 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..85298ce5a964 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 `viewState - initialised - 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 - new option - 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 - new option - 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 `userRequestedToChangeFireAnimation - command is launch fire animation settings`() = runTest { testee.commands().test { testee.userRequestedToChangeFireAnimation() @@ -189,14 +189,14 @@ internal class FireButtonViewModelTest { } @Test - fun whenFireAnimationSettingClickedThenPixelSent() { + fun `userRequestedToChangeFireAnimation - pixel sent`() { testee.userRequestedToChangeFireAnimation() verify(mockPixel).fire(AppPixelName.FIRE_ANIMATION_SETTINGS_OPENED) } @Test - fun whenNewFireAnimationSelectedThenUpdateViewState() = runTest { + fun `onFireAnimationSelected - update viewState`() = runTest { val expectedAnimation = FireAnimation.HeroWater testee.viewState().test { @@ -211,21 +211,21 @@ internal class FireButtonViewModelTest { } @Test - fun whenNewFireAnimationSelectedThenStoreNewSelectedAnimation() { + fun `onFireAnimationSelected - new fire animation - store new selected animation`() { testee.onFireAnimationSelected(FireAnimation.HeroWater) verify(mockAppSettingsDataStore).selectedFireAnimation = FireAnimation.HeroWater } @Test - fun whenNewFireAnimationSelectedThenPreLoadAnimation() { + fun `onFireAnimationSelected - new fire animation - pre load animation`() { testee.onFireAnimationSelected(FireAnimation.HeroWater) verify(mockFireAnimationLoader).preloadSelectedAnimation() } @Test - fun whenNewFireAnimationSelectedThenPixelSent() { + fun `onFireAnimationSelected - new fire animation - 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..5d115d721f90 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 - result is correct`() { val result = helloWorldText.sha1 assertEquals(helloWorldSha1, result) } @Test - fun whenSha256HashCalledOnBytesThenResultIsCorrect() { + fun `sha256Hash - bytes - result is correct`() { val result = helloWorldText.toByteArray().sha256 assertEquals(helloWorldSha256, result) } @Test - fun whenSha256HashCalledOnStringThenResultIsCorrect() { + fun `sha256Hash - result is correct`() { val result = helloWorldText.sha256 assertEquals(helloWorldSha256, result) } @Test - fun whenCorrectSha256HashUsedThenVerifyIsTrue() { + fun `verifySha256 - correct hash used - verify is true`() { assertTrue(helloWorldText.toByteArray().verifySha256(helloWorldSha256)) } @Test - fun whenIncorrectByteSha256HashUsedThenVerifyIsFalse() { + fun `verifySha256 - incorrect byte hash - 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..fb3793809581 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 - uri does not have a scheme - appends http`() { val url = "someurl" assertEquals("http://$url", Uri.parse(url).withScheme().toString()) } @Test - fun whenUriHasASchemeThenWithSchemeHasNoEffect() { + fun `withScheme - uri has a scheme - no effect`() { val url = "http://someurl" assertEquals(url, Uri.parse(url).withScheme().toString()) } @Test - fun whenUriBeginsWithWwwThenBaseHostReturnsWithoutWww() { + fun `baseHost - uri begins with www - returns without www`() { val url = "http://www.example.com" assertEquals("example.com", Uri.parse(url).baseHost) } @Test - fun whenUriDoesNotBeginWithWwwThenBaseHosReturnsWithSameHost() { + fun `baseHost - uri does not begin with www - returns same host`() { val url = "http://example.com" assertEquals("example.com", Uri.parse(url).baseHost) } @Test - fun whenUriDoesNotHaveASchemeThenBaseHostStillResolvesHost() { + fun `baseHost - uri without scheme - resolves host`() { val url = "www.example.com" assertEquals("example.com", Uri.parse(url).baseHost) } @Test - fun whenUriContainsInvalidHostThenBaseHostIsNull() { + fun `baseHost - invalid host in URI - is null`() { val url = "about:blank" assertNull(Uri.parse(url).baseHost) } @Test - fun whenUriIsHttpIrrespectiveOfCaseThenIsHttpIsTrue() { + fun `isHttp - uri is http irrespective of case - true`() { assertTrue(Uri.parse("http://example.com").isHttp) assertTrue(Uri.parse("HTTP://example.com").isHttp) } @Test - fun whenUriIsHttpsThenIsHttpIsFalse() { + fun `isHttp - uri is https - false`() { assertFalse(Uri.parse("https://example.com").isHttp) } @Test - fun whenUriIsMalformedThenIsHttpIsFalse() { + fun `isHttp - malformed URI - is false`() { assertFalse(Uri.parse("[example com]").isHttp) } @Test - fun whenUriIsHttpsIrrespectiveOfCaseThenIsHttpsIsTrue() { + fun `isHttps - uri is https irrespective of case - true`() { assertTrue(Uri.parse("https://example.com").isHttps) assertTrue(Uri.parse("HTTPS://example.com").isHttps) } @Test - fun whenUriIsHttpThenIsHttpsIsFalse() { + fun `isHttps - uri is http - false`() { assertFalse(Uri.parse("http://example.com").isHttps) } @Test - fun whenUriIsHttpsAndOtherIsHttpButOtherwiseIdenticalThenIsHttpsVersionOfOtherIsTrue() { + fun `isHttpsVersionOfUri - https and http identical - true`() { val uri = Uri.parse("https://example.com") val other = Uri.parse("http://example.com") assertTrue(uri.isHttpsVersionOfUri(other)) } @Test - fun whenUriIsHttpsAndOtherIsHttpButNotOtherwiseIdenticalThenIsHttpsVersionOfOtherIsFalse() { + fun `isHttpsVersionOfUri - https and http but not identical - 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 uri - false`() { val uri = Uri.parse("http://example.com") val other = Uri.parse("http://example.com") assertFalse(uri.isHttpsVersionOfUri(other)) } @Test - fun whenUriIsHttpsAndOtherIsHttpsThenIsHttpsVersionOfOtherIsFalse() { + fun `isHttpsVersionOfUri - both URIs are https - false`() { val uri = Uri.parse("https://example.com") val other = Uri.parse("https://example.com") assertFalse(uri.isHttpsVersionOfUri(other)) } @Test - fun whenUriIsMalformedThenIsHtpsIsFalse() { + fun `isHttps - malformed URI - false`() { assertFalse(Uri.parse("[example com]").isHttps) } @Test - fun whenIpUriThenHasIpHostIsTrue() { + fun `hasIpHost - IP URI - true`() { assertTrue(Uri.parse("https://54.229.105.203/something").hasIpHost) assertTrue(Uri.parse("54.229.105.203/something").hasIpHost) } @Test - fun whenIpWithPortUriThenHasIpHostIsTrue() { + fun `hasIpHost - IP with port URI - true`() { 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 `parse - IP with port URI - port number parsed successfully`() { assertEquals(999, Uri.parse("https://54.229.105.203:999/something").port) } @Test - fun whenValidIpAddressWithPortParsedWithSchemeThenPortNumberParsedSuccessfully() { + fun `withScheme - valid IP address with port - port number parsed successfully`() { assertEquals(999, Uri.parse("121.33.2.11:999").withScheme().port) } @Test - fun whenStandardUriThenHasIpHostIsFalse() { + fun `hasIpHost - standard URI - false`() { assertFalse(Uri.parse("http://example.com").hasIpHost) } @Test - fun whenUrlStartsMDotThenIdentifiedAsMobileSite() { + fun `isMobileSite - url starts with m dot - identified as mobile site`() { assertTrue(Uri.parse("https://m.example.com").isMobileSite) } @Test - fun whenUrlStartsMobileDotThenIdentifiedAsMobileSite() { + fun `isMobileSite - url starts with mobile dot - identified as mobile site`() { assertTrue(Uri.parse("https://mobile.example.com").isMobileSite) } @Test - fun whenUrlSubdomainEndsWithMThenNotIdentifiedAsMobileSite() { + fun `isMobileSite - url subdomain ends with m - not identified as mobile site`() { assertFalse(Uri.parse("https://adam.example.com").isMobileSite) } @Test - fun whenUrlDoesNotStartWithMDotThenNotIdentifiedAsMobileSite() { + fun `isMobileSite - url does not start with m dot - not identified as mobile site`() { assertFalse(Uri.parse("https://example.com").isMobileSite) } @Test - fun whenConvertingMobileSiteToDesktopSiteThenShortMobilePrefixStripped() { + fun `toDesktopUri - mobile site - short mobile prefix stripped`() { val converted = Uri.parse("https://m.example.com").toDesktopUri() assertEquals("https://example.com", converted.toString()) } @Test - fun whenConvertingMobileSiteToDesktopSiteThenLongMobilePrefixStripped() { + fun `toDesktopUri - mobile site - long mobile prefix stripped`() { val converted = Uri.parse("https://mobile.example.com").toDesktopUri() assertEquals("https://example.com", converted.toString()) } @Test - fun whenConvertingMobileSiteToDesktopSiteThenMultipleMobilePrefixesStripped() { + fun `toDesktopUri - mobile site - 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 - desktop site - url unchanged`() { val converted = Uri.parse("https://example.com").toDesktopUri() assertEquals("https://example.com", converted.toString()) } @Test - fun whenGettingAbsoluteStringThenDoNotReturnQueryParameters() { + fun `absoluteString - query parameters - not returned`() { val absoluteString = Uri.parse("https://example.com/test?q=example/#1/anotherrandomcode").absoluteString assertEquals("https://example.com/test", absoluteString) } @Test - fun whenNullUrlThenNullFaviconUrl() { + fun `faviconLocation - null URL - null favicon URL`() { assertNull("".toUri().faviconLocation()) } @Test - fun whenHttpRequestThenFaviconLocationAlsoHttp() { + fun `faviconLocation - http request - also http`() { val favicon = "http://example.com".toUri().faviconLocation() assertTrue(favicon!!.isHttp) } @Test - fun whenHttpsRequestThenFaviconLocationAlsoHttps() { + fun `faviconLocation - https request - also https`() { val favicon = "https://example.com".toUri().faviconLocation() assertTrue(favicon!!.isHttps) } @Test - fun whenUrlContainsASubdomainThenSubdomainReturnedInFavicon() { + fun `faviconLocation - url contains subdomain - subdomain returned`() { val favicon = "https://sub.example.com".toUri().faviconLocation() assertEquals("https://sub.example.com/favicon.ico", favicon.toString()) } @Test - fun whenUrlIsIpAddressThenIpReturnedInFaviconUrl() { + fun `faviconLocation - 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 `domain - url does not have scheme - return null`() { assertNull("www.example.com".toUri().domain()) } @Test - fun whenUrlHasSchemeReturnDomain() { + fun `domain - url has scheme - return domain`() { assertEquals("www.example.com", "http://www.example.com".toUri().domain()) } @Test - fun whenUriHasResourceNameThenDropSchemeReturnResourceName() { + fun `toStringDropScheme - uri has resource name - return resource name`() { assertEquals("www.foo.com", "https://www.foo.com".toUri().toStringDropScheme()) assertEquals("www.foo.com", "http://www.foo.com".toUri().toStringDropScheme()) } @Test - fun whenUriHasResourceNameAndPathThenDropSchemeReturnResourceNameAndPath() { + fun `toStringDropScheme - uri has resource name and path - return resource name and path`() { 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 `toStringDropScheme - uri has resource name path and params - 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 - 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..c5f14f291a5d 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,7 +49,7 @@ 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")) } @@ -59,27 +59,27 @@ class UriStringTest { } @Test - fun whenChildUrlIsMalformedThenSameOrSubdomainIsFalse() { + fun `sameOrSubdomain - child URL malformed - false`() { assertFalse(sameOrSubdomain("??.example.com/index.html", "http://example.com/home.html")) } @Test - fun whenChildUrlIsMalformedThenSameOrSubdomainIsFalse2() { + fun `sameOrSubdomain - malformed child URL - false`() { assertFalse(sameOrSubdomain("??.example.com/index.html".toUri(), "http://example.com/home.html")) } @Test - fun whenParentUrlIsMalformedThenSameOrSubdomainIsFalse() { + fun `sameOrSubdomain - parent URL is malformed - false`() { assertFalse(sameOrSubdomain("http://example.com/index.html", "??.example.com/home.html")) } @Test - fun whenParentUrlIsMalformedThenSameOrSubdomainIsFalse2() { + fun `sameOrSubdomain - malformed parent URL - false`() { assertFalse(sameOrSubdomain("http://example.com/index.html".toUri(), "??.example.com/home.html")) } @Test - fun whenUrlsHaveSameDomainThenSafeSameOrSubdomainIsTrue() { + fun `sameOrSubdomain - urls have same domain - true`() { assertTrue(sameOrSubdomain("http://example.com/index.html", "http://example.com/home.html")) } @@ -109,7 +109,7 @@ class UriStringTest { } @Test - fun whenChildUrlIsMalformedThenSafeSameOrSubdomainIsFalse() { + fun `sameOrSubdomain - child URL is malformed - false`() { assertFalse(sameOrSubdomain("??.example.com/index.html", "http://example.com/home.html")) } @@ -124,64 +124,64 @@ class UriStringTest { } @Test - fun whenParentUrlIsMalformedThenSafeSameOrSubdomainIsFalse2() { + fun `sameOrSubdomain - parent URL malformed - false`() { assertFalse(sameOrSubdomain("http://example.com/index.html".toUri(), "??.example.com/home.html")) } @Test - fun whenUserIsPresentThenIsWebUrlIsFalse() { + fun `isWebUrl - user is present - false`() { val input = "http://example.com@sample.com" assertFalse(isWebUrl(input)) } @Test - fun whenGivenLongWellFormedUrlThenIsWebUrlIsTrue() { + fun `isWebUrl - long well-formed URL - 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 - valid host - true`() { assertTrue(isWebUrl("test.com")) } @Test - fun whenHostIsValidIpAddressThenIsWebUrlIsTrue() { + fun `isWebUrl - valid IP address - true`() { assertTrue(isWebUrl("121.33.2.11")) } @Test - fun whenHostIsValidIpAddressWithPortThenIsWebUrlIsTrue() { + fun `isWebUrl - valid IP address with port - true`() { assertTrue(isWebUrl("121.33.2.11:999")) } @Test - fun whenHostIsLocalhostThenIsWebUrlIsTrue() { + fun `isWebUrl - localhost - true`() { assertTrue(isWebUrl("localhost")) } @Test - fun whenHostIsInvalidContainsSpaceThenIsWebUrlIsFalse() { + fun `isWebUrl - host contains space - false`() { assertFalse(isWebUrl("t est.com")) } @Test - fun whenHostIsInvalidContainsExclamationMarkThenIsWebUrlIsFalse() { + fun `isWebUrl - invalid host with exclamation mark - false`() { assertFalse(isWebUrl("test!com.com")) } @Test - fun whenHostIsInvalidIpThenIsWebUrlIsFalse() { + fun `isWebUrl - invalid IP - false`() { assertFalse(isWebUrl("121.33.33.")) } @Test - fun whenHostIsInvalidMisspelledLocalhostContainsSpaceThenIsWebUrlIsFalse() { + fun `isWebUrl - invalid host - false`() { assertFalse(isWebUrl("localhostt")) } @Test - fun whenSchemeIsValidNormalUrlThenIsWebUrlIsTrue() { + fun `isWebUrl - valid normal URL - true`() { assertTrue(isWebUrl("http://test.com")) } @@ -196,52 +196,52 @@ class UriStringTest { } @Test - fun whenSchemeIsValidLocalhostUrlThenIsWebUrlIsTrue() { + fun `isWebUrl - valid localhost URL - true`() { assertTrue(isWebUrl("http://localhost")) } @Test - fun whenSchemeIsInvalidNormalUrlThenIsWebUrlIsFalse() { + fun `isWebUrl - invalid normal url - false`() { assertFalse(isWebUrl("asdas://test.com")) } @Test - fun whenSchemeIsInvalidIpAddressThenIsWebUrlIsFalse() { + fun `isWebUrl - invalid IP address scheme - false`() { assertFalse(isWebUrl("asdas://121.33.2.11")) } @Test - fun whenSchemeIsInvalidLocalhostThenIsWebUrlIsFalse() { + fun `isWebUrl - invalid localhost scheme - false`() { assertFalse(isWebUrl("asdas://localhost")) } @Test - fun whenTextIsIncompleteHttpSchemeLettersOnlyThenIsWebUrlIsFalse() { + fun `isWebUrl - incomplete http scheme letters only - false`() { assertFalse(isWebUrl("http")) } @Test - fun whenTextIsIncompleteHttpSchemeMissingBothSlashesThenIsWebUrlIsFalse() { + fun `isWebUrl - incomplete http scheme missing both slashes - false`() { assertFalse(isWebUrl("http:")) } @Test - fun whenTextIsIncompleteHttpSchemeMissingOneSlashThenIsWebUrlIsFalse() { + fun `isWebUrl - incomplete HTTP scheme missing one slash - false`() { assertFalse(isWebUrl("http:/")) } @Test - fun whenTextIsIncompleteHttpsSchemeLettersOnlyThenIsWebUrlIsFalse() { + fun `isWebUrl - incomplete https scheme letters only - false`() { assertFalse(isWebUrl("https")) } @Test - fun whenTextIsIncompleteHttpsSchemeMissingBothSlashesThenIsWebUrlIsFalse() { + fun `isWebUrl - incomplete https scheme missing slashes - false`() { assertFalse(isWebUrl("https:")) } @Test - fun whenTextIsIncompleteHttpsSchemeMissingOneSlashThenIsWebUrlIsFalse() { + fun `isWebUrl - incomplete https scheme missing one slash - false`() { assertFalse(isWebUrl("https:/")) } @@ -261,42 +261,42 @@ class UriStringTest { } @Test - fun whenPathIsValidLocalhostThenIsWebUrlIsTrue() { + fun `isWebUrl - valid localhost path - true`() { assertTrue(isWebUrl("http://localhost/path")) } @Test - fun whenPathIsValidMissingSchemeNormalUrlThenIsWebUrlIsTrue() { + fun `isWebUrl - valid missing scheme normal URL - true`() { assertTrue(isWebUrl("test.com/path")) } @Test - fun whenPathIsValidMissingSchemeIpAddressThenIsWebUrlIsTrue() { + fun `isWebUrl - valid missing scheme IP address - true`() { assertTrue(isWebUrl("121.33.2.11/path")) } @Test - fun whenPathIsValidMissingSchemeLocalhostThenIsWebUrlIsTrue() { + fun `isWebUrl - valid missing scheme localhost - true`() { assertTrue(isWebUrl("localhost/path")) } @Test - fun whenPathIsInvalidContainsSpaceNormalUrlThenIsWebUrlIsFalse() { + fun `isWebUrl - invalid path with space - false`() { assertFalse(isWebUrl("http://test.com/pa th")) } @Test - fun whenPathIsInvalidContainsSpaceIpAddressThenIsWebUrlIsFalse() { + fun `isWebUrl - invalid path with space in IP address - false`() { assertFalse(isWebUrl("http://121.33.2.11/pa th")) } @Test - fun whenPathIsInvalidContainsSpaceLocalhostThenIsWebUrlIsFalse() { + fun `isWebUrl - invalid path with space in localhost - false`() { assertFalse(isWebUrl("http://localhost/pa th")) } @Test - fun whenPathIsInvalidContainsSpaceMissingSchemeNormalUrlThenIsWebUrlIsFalse() { + fun `isWebUrl - invalid path with space and missing scheme - false`() { assertFalse(isWebUrl("test.com/pa th")) } @@ -311,7 +311,7 @@ class UriStringTest { } @Test - fun whenPathIsValidContainsEncodedSpaceNormalUrlThenIsWebUrlIsTrue() { + fun `isWebUrl - valid URL with encoded space - true`() { assertTrue(isWebUrl("http://www.example.com/pa%20th")) } @@ -326,72 +326,72 @@ class UriStringTest { } @Test - fun whenParamsAreValidLocalhostThenIsWebUrlIsTrue() { + fun `isWebUrl - valid localhost params - true`() { assertTrue(isWebUrl("http://localhost?s=dafas&d=342")) } @Test - fun whenParamsAreValidNormalUrlMissingSchemeThenIsWebUrlIsTrue() { + fun `isWebUrl - valid normal URL missing scheme - true`() { assertTrue(isWebUrl("test.com?s=dafas&d=342")) } @Test - fun whenParamsAreValidIpAddressMissingSchemeThenIsWebUrlIsTrue() { + fun `isWebUrl - valid IP address missing scheme - true`() { assertTrue(isWebUrl("121.33.2.11?s=dafas&d=342")) } @Test - fun whenParamsAreValidLocalhostMissingSchemeThenIsWebUrlIsTrue() { + fun `isWebUrl - valid localhost missing scheme - true`() { assertTrue(isWebUrl("localhost?s=dafas&d=342")) } @Test - fun whenParamsAreValidContainsEncodedUriThenIsWebUrlIsTrue() { + fun `isWebUrl - valid params with encoded URI - true`() { assertTrue(isWebUrl("https://m.facebook.com/?refsrc=https%3A%2F%2Fwww.facebook.com%2F&_rdr")) } @Test - fun whenGivenSimpleStringThenIsWebUrlIsFalse() { + fun `isWebUrl - simple string - false`() { assertFalse(isWebUrl("randomtext")) } @Test - fun whenGivenStringWithDotPrefixThenIsWebUrlIsFalse() { + fun `isWebUrl - string with dot prefix - false`() { assertFalse(isWebUrl(".randomtext")) } @Test - fun whenGivenStringWithDotSuffixThenIsWebUrlIsFalse() { + fun `isWebUrl - string with dot suffix - 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 - site specific search - is false`() { assertFalse(isWebUrl("site:example.com")) } @Test - fun whenSchemeIsValidFtpButNotHttpThenNot() { + fun `isWebUrl - valid FTP scheme - not HTTP`() { 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..167320bb4689 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`() { 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 `sendPixel - redact atb`() { 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`() { 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 `sendPixel - redact atb and app and OS version`() { 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..b1fdee1a3347 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 - RQ0 pixel sent - 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 - rq1 pixel sent - 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 - pixel other than rq - do 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..b7c5538145c2 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 `daysInstalled - installation today - day installed is zero`() { whenever(testee.installTimestamp).thenReturn(System.currentTimeMillis()) assertEquals(0, testee.daysInstalled()) } @Test - fun whenDayAfterInstallationThenDayInstalledIsOne() { + fun `daysInstalled - day after installation - day installed is one`() { val timeSinceInstallation = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1) whenever(testee.installTimestamp).thenReturn(timeSinceInstallation) assertEquals(1, testee.daysInstalled()) } @Test - fun whenAWeekAfterInstallationThenDayInstalledIsSeven() { + fun `daysInstalled - a week after installation - day installed is 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..975e477074b8 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..690c21a7d54d 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 `onCreate - stored version lower than current - run migrations`() { whenever(mockMigrationStore.version).thenReturn(CURRENT_VERSION - 1) testee.onCreate(mockOwner) @@ -51,7 +51,7 @@ class MigrationLifecycleObserverTest { } @Test - fun whenMigrateIfStoredVersionIsLowerThanCurrentThenStoreCurrentVersion() { + fun `onCreate - stored version is lower than current - store current version`() { whenever(mockMigrationStore.version).thenReturn(CURRENT_VERSION - 1) testee.onCreate(mockOwner) @@ -60,7 +60,7 @@ class MigrationLifecycleObserverTest { } @Test - fun whenMigrateIfStoredVersionIsHigherThanCurrentThenDoNotRunMigrations() { + fun `onCreate - stored version 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..5750de765c32 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 `https - url is https - status is secure`() { val testee = SiteMonitor( url = httpsDocument, title = null, @@ -85,7 +85,7 @@ class SiteMonitorTest { } @Test - fun whenUrlIsHttpThenHttpsStatusIsNone() { + fun `https - url is http - status is none`() { val testee = SiteMonitor( url = httpDocument, title = null, @@ -99,7 +99,7 @@ class SiteMonitorTest { } @Test - fun whenUrlIsHttpsWithHttpResourcesThenHttpsStatusIsMixed() { + fun `https - url with http resources - mixed status`() { val testee = SiteMonitor( url = httpsDocument, title = null, @@ -114,7 +114,7 @@ class SiteMonitorTest { } @Test - fun whenUrlIsMalformedThenHttpsStatusIsNone() { + fun `SiteMonitor - url is malformed - https status is none`() { val testee = SiteMonitor( url = malformedDocument, title = null, @@ -128,7 +128,7 @@ class SiteMonitorTest { } @Test - fun whenSiteMonitorCreatedThenUrlIsCorrect() { + fun `SiteMonitor - created - url is correct`() { val testee = SiteMonitor( url = document, title = null, @@ -142,7 +142,7 @@ class SiteMonitorTest { } @Test - fun whenSiteMonitorCreatedThenTrackerCountIsZero() { + fun `SiteMonitor - created - tracker count is zero`() { val testee = SiteMonitor( url = document, title = null, @@ -156,7 +156,7 @@ class SiteMonitorTest { } @Test - fun whenTrackersBlockedOrAllowedByUserAreDetectedThenTrackerCountIsIncremented() { + fun `trackerDetected - trackers blocked or allowed by user - tracker count incremented`() { val testee = SiteMonitor( url = document, title = null, @@ -203,7 +203,7 @@ class SiteMonitorTest { } @Test - fun whenNoTrackersAllowedByUserAreDetectedThenAllTrackersBlockedIsTrue() { + fun `allTrackersBlocked - no trackers allowed by user detected - 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 - non-major network tracker - major network count is zero`() { val testee = SiteMonitor( url = document, title = null, @@ -322,7 +322,7 @@ class SiteMonitorTest { } @Test - fun whenMajorNetworkTrackerIsDetectedThenMajorNetworkCountIsOne() { + fun `trackerDetected - major network tracker detected - major network count is one`() { val testee = SiteMonitor( url = document, title = null, @@ -347,7 +347,7 @@ class SiteMonitorTest { } @Test - fun whenDuplicateMajorNetworkIsDetectedThenMajorNetworkCountIsStillOne() { + fun `trackerDetected - duplicate major network - major network count is still one`() { val testee = SiteMonitor( url = document, title = null, @@ -383,7 +383,7 @@ class SiteMonitorTest { } @Test - fun whenSiteCreatedThenUpgradedHttpsIsFalse() { + fun `SiteMonitor - site created - upgradedHttps is false`() { val testee = SiteMonitor( url = document, title = null, @@ -397,7 +397,7 @@ class SiteMonitorTest { } @Test - fun whenSiteCreatedThenSurrogatesSizeIsZero() { + fun `SiteMonitor - site created - surrogates size is zero`() { val testee = SiteMonitor( url = document, title = null, @@ -411,7 +411,7 @@ class SiteMonitorTest { } @Test - fun whenSurrogatesAreDetectedThenSurrogatesListIsIncremented() { + fun `surrogateDetected - surrogates detected - 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 `privacyProtection - site in user allow list - unprotected`() { val testee = givenASiteMonitor(url = document) whenever(mockAllowListRepository.isDomainInUserAllowList(document)).thenReturn(true) @@ -561,21 +561,21 @@ class SiteMonitorTest { } @Test - fun whenSiteIsHttptThenPrivacyShieldIsUnprotected() { + fun `privacyProtection - site is http - unprotected`() { val testee = givenASiteMonitor(url = httpDocument) assertEquals(UNPROTECTED, testee.privacyProtection()) } @Test - fun whenSiteIsNotExceptionOrHttpButFullDetailsNotAvailableThenReturnUnkown() { + fun `privacyProtection - site not exception or http and full details not available - return unknown`() { val testee = givenASiteMonitor(url = httpsDocument) assertEquals(UNKNOWN, testee.privacyProtection()) } @Test - fun whenSiteIsMajorNetworkThenPrivacyShieldIsProtected() { + fun `updatePrivacyData - site is major network - privacy shield is 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 is protected`() { val testee = givenASiteMonitor(url = httpsDocument) testee.updatePrivacyData(givenSitePrivacyData(entity = network)) @@ -593,7 +593,7 @@ class SiteMonitorTest { } @Test - fun whenUserBypassedSslCertificateThenPrivacyShieldIsUnprotected() { + fun `privacyProtection - user bypassed SSL certificate - 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..f7aa34f6d27f 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 - not seen prompt before and not used 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 the 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 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 - seen prompt before and not enough app usage - 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..8c5ba9a3006c 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 - should 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..fae16fd16bf9 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 - lots of app usage - see second prompt`() = runTest { configureLotsOfAppUsage() assertTrue(testee.shouldShowPrompt()) } @Test - fun whenUserHasNotUsedTheAppMuchSinceSeeingFirstPromptThenTheyDoNotSeeSecondPrompt() = runTest { + fun `shouldShowPrompt - not a lot of app usage - does not see second prompt`() = runTest { whenever(mockAppEnjoymentRepository.canUserBeShownSecondPrompt()).thenReturn(true) configureNotALotOfAppUsage() assertFalse(testee.shouldShowPrompt()) } @Test - fun whenUserHasAlreadyRatedOrGaveFeedbackThenTheyDoNoSeeASecondPromptEvenAfterALotOfUsage() = runTest { + fun `shouldShowPrompt - already rated or gave feedback - no second 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..e7d3ce2cb89f 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 - one is 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 - can keep 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 exists - returns null`() { val converted = Uri.parse("https://example.com").removeSubdomain() assertNull(converted) } @Test - fun whenRemovingASubdomainWhenOnlyOneExistsButHasMultipartTldCoUkThenReturnsNull() { + fun `removeSubdomain - only one exists with multipart TLD co·uk - returns null`() { val converted = Uri.parse("https://co.uk").removeSubdomain() assertNull(converted) } @Test - fun whenRemovingASubdomainWhenOnlyOneExistsButHasMultipartTldCoNzThenReturnsMultipartTld() { + fun `removeSubdomain - only one exists with multipart TLD - returns multipart TLD`() { val converted = Uri.parse("https://co.za").removeSubdomain() assertNull(converted) } @Test - fun whenRemovingASubdomainWhenOnlyOneExistsButHasRecentTldThenReturnsNull() { + fun `removeSubdomain - only one exists with 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 `removeSubdomain - uri is IP address - 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..a56fd0fe48b1 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 `create - initialised with default viewState`() { val defaultViewState = GlobalPrivacyControlViewModel.ViewState() verify(mockViewStateObserver, atLeastOnce()).onChanged(viewStateCaptor.capture()) assertEquals(defaultViewState, viewStateCaptor.value) } @Test - fun whenViewModelCreateThenPixelSent() { + fun `onCreate - pixel sent`() { verify(mockPixel).fire(AppPixelName.SETTINGS_DO_NOT_SELL_SHOWN) } @Test - fun whenOnLearnMoreSelectedThenOpenLearnMoreCommandIssuedWithCorrectUrl() { + fun `onLearnMoreSelected - open learn more command issued with correct url`() { 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 - switched on - value stored in settings`() { testee.onUserToggleGlobalPrivacyControl(true) verify(mockGpc).enableGpc() } @Test - fun whenOnUserToggleGlobalPrivacyControlSwitchedOffThenValueStoredInSettings() { + fun `onUserToggleGlobalPrivacyControl - switched off - value stored in settings`() { testee.onUserToggleGlobalPrivacyControl(false) verify(mockGpc).disableGpc() } @Test - fun whenOnUserToggleGlobalPrivacyControlSwitchedOnThenViewStateUpdatedToTrue() { + fun `onUserToggleGlobalPrivacyControl - switched on - viewState updated to true`() { testee.onUserToggleGlobalPrivacyControl(true) verify(mockViewStateObserver, atLeastOnce()).onChanged(viewStateCaptor.capture()) @@ -121,7 +121,7 @@ class GlobalPrivacyControlViewModelTest { } @Test - fun whenOnUserToggleGlobalPrivacyControlSwitchedOnThenViewStateUpdatedToFalse() { + fun `onUserToggleGlobalPrivacyControl - switched on - viewState updated to 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..b13b86bdeeab 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 `onResume - schedules next notification and 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..3f9d22efb86c 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 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 with delayed referrer data - 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 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 with quick referrer data - 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 with delayed referrer data - 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 and referrer data 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..c009abc87380 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 `forFireproofing - domain starts with https - drop prefix`() { val locationPermissionEntity = LocationPermissionEntity("https://www.example.com/", LocationPermissionType.ALLOW_ONCE) val host = locationPermissionEntity.forFireproofing() Assert.assertEquals("www.example.com", host) } @Test - fun whenDomainStartsWithHttpsUppercaseThenDropPrefix() { + fun `forFireproofing - domain starts with HTTPS uppercase - drop prefix`() { val locationPermissionEntity = LocationPermissionEntity("HTTPS://www.example.com/", LocationPermissionType.ALLOW_ONCE) val host = locationPermissionEntity.forFireproofing() Assert.assertEquals("www.example.com", host) } @Test - fun whenDomainDoesNotStartWithHttpsThenDomainUnchanged() { + fun `forFireproofing - domain does not start with https - domain 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..1b16ae1eb9a7 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 - clear data can show - privacy notification 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 - privacy notification 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 notification 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..d5fb50de1040 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 - return current stage`() = runTest { givenCurrentStage(AppStage.DAX_ONBOARDING) val userAppStage = testee.getUserAppStage() @@ -43,7 +43,7 @@ class AppUserStageStoreTest { } @Test - fun whenStageNewCompletedThenStageDaxOnboardingReturned() = runTest { + fun `stageCompleted - new 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 - Dax onboarding completed - stage 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 - 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..6ad7a553d8a9 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 is 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 is 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 - DDG as 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 - DDG as default browser and should show browser 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..f559b0739e2e 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 - complete 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..9e61f8d796a3 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 `init - default browser exists - show settings UI`() { whenever(mockDefaultBrowserDetector.hasDefaultBrowser()).thenReturn(true) testee = DefaultBrowserPageViewModel(mockDefaultBrowserDetector, mockPixel, mockInstallStore) @@ -84,7 +84,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenInitializingIfThereIsNotADefaultBrowserThenShowDialogUI() { + fun `init - 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 - default browser is true - show settings UI`() { whenever(mockDefaultBrowserDetector.hasDefaultBrowser()).thenReturn(true) testee.loadUI() @@ -102,7 +102,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenLoadUiThenShowDialogUiIfDefaultBrowserIsFalse() { + fun `loadUI - default browser is false - show dialog UI`() { whenever(mockDefaultBrowserDetector.hasDefaultBrowser()).thenReturn(false) testee.loadUI() @@ -111,7 +111,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenLoadUIAfterDefaultButtonClickedThenSameState() { + fun `loadUI - after default button clicked - same state`() { whenever(mockDefaultBrowserDetector.hasDefaultBrowser()).thenReturn(false) testee.loadUI() testee.onDefaultBrowserClicked() @@ -123,7 +123,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenContinueButtonClickedWithoutTryingToSetDDGAsDefaultThenSendPixelAndExecuteContinueToBrowserCommand() { + fun `onContinueToBrowser - not default browser - 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 - execute open settings command`() { 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 `onDefaultBrowserClicked - no 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 `handleResult - set DDG as default 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 `handleResult - set DDG as just once for first time - show instructions, open dialog, fire pixel`() { whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(false) testee.loadUI() testee.onDefaultBrowserClicked() @@ -186,7 +186,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenUserSetDDGAsJustOnceTheMaxAllowedTimesThenTakeUserToBrowser() { + fun `handleResult - set DDG as just once max times - 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 `handleResult - user dismissed dialog - 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 `handleResult - another browser set as default - 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 `handleResult - set DDG as default - 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 `handleResult - 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 `handleResult - not default browser - show settings UI`() { whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(false) whenever(mockDefaultBrowserDetector.hasDefaultBrowser()).thenReturn(true) testee.loadUI() @@ -276,7 +276,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenUserSelectedDDGAsDefaultInSettingsScreenThenFirePixel() { + fun `handleResult - user selected DDG as default in 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 `handleResult - DDG not selected as default in settings - 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 is settings - reset timesPressedJustOnce`() { testee.loadUI() testee.timesPressedJustOnce = 1 @@ -317,7 +317,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenOriginReceivedIsDialogDismissedThenResetTimesPressedJustOnce() { + fun `handleResult - origin 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 is external browser - reset timesPressedJustOnce`() { testee.timesPressedJustOnce = 1 testee.handleResult(Origin.ExternalBrowser) @@ -336,7 +336,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenOriginReceivedIsInternalBrowserAndDDGIsTheDefaultBrowserThenResetTimesPressedJustOnce() { + fun `handleResult - internal browser and DDG is default - reset times pressed just once`() { whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(true) testee.timesPressedJustOnce = 1 @@ -346,7 +346,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenOriginReceivedIsInternalBrowserAndDDGIsNotTheDefaultBrowserThenIncreaseTimesPressedJustOnceIfIsLessThanTheMaxNumberOfAttempts() { + fun `handleResult - internal browser and DDG not default - increase times pressed just once`() { whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(false) testee.timesPressedJustOnce = 1 @@ -356,7 +356,7 @@ class DefaultBrowserPageViewModelTest { } @Test - fun whenOriginReceivedIsInternalBrowserAndDDGIsNotTheDefaultBrowserThenResetTimesPressedJustOnceIfIsGreaterOrEqualThanTheMaxNumberOfAttempts() { + fun `handleResult - internal browser and DDG not default - reset times pressed just once if max attempts reached`() { 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..8b3227f8d840 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 - 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 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 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..041a22c01c92 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 - start not called - initialised with 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 enabled - notifications setting subtitle set correctly`() = 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 as disabled`() = runTest { testee.start(notificationsEnabled = false) testee.viewState().test { @@ -99,7 +99,7 @@ class PermissionsViewModelTest { } @Test - fun whenAppLinksSetToAskEverytimeThenDataStoreIsUpdatedAndPixelIsSent() { + fun `onAppLinksSettingChanged - set to ask every time - data store updated and pixel sent`() { testee.onAppLinksSettingChanged(AppLinkSettingType.ASK_EVERYTIME) verify(mockAppSettingsDataStore).appLinksEnabled = true @@ -108,7 +108,7 @@ class PermissionsViewModelTest { } @Test - fun whenAppLinksSetToAlwaysThenDataStoreIsUpdatedAndPixelIsSent() { + fun `onAppLinksSettingChanged - set to always - data store updated and pixel sent`() { testee.onAppLinksSettingChanged(AppLinkSettingType.ALWAYS) verify(mockAppSettingsDataStore).appLinksEnabled = true @@ -117,7 +117,7 @@ class PermissionsViewModelTest { } @Test - fun whenAppLinksSetToNeverThenDataStoreIsUpdatedAndPixelIsSent() { + fun `onAppLinksSettingChanged - set to never - data store updated and pixel sent`() { testee.onAppLinksSettingChanged(AppLinkSettingType.NEVER) verify(mockAppSettingsDataStore).appLinksEnabled = false @@ -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 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..9a747549fdc4 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`() { whenever(unsentForgetAllPixelStore.pendingPixelCountClearData).thenReturn(2) enqueuedPixelWorker.onCreate(lifecycleOwner) @@ -81,7 +81,7 @@ class EnqueuedPixelWorkerTest { } @Test - fun whenOnCreateAndPendingPixelCountClearDataIsZeroThenDoNotFireMf() { + fun `onCreate - pending pixel count clear data is 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 webview 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 webView 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 `sendingAppLaunchPixel - 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..935469425b2a 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 `updateUserAllowList - db contains user allow listed domains - user allow list updated`() { 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 allow listed domain - returns false`() { dao.insert("example.com") assertFalse(repository.isUrlInUserAllowList("https://foo.com")) } @Test - fun whenDomainIsAddedToUserAllowListThenItGetsInsertedIntoDb() = runTest { + fun `addDomainToUserAllowList - domain added - inserted into db`() = runTest { assertFalse(dao.contains("example.com")) repository.addDomainToUserAllowList("example.com") assertTrue(dao.contains("example.com")) } @Test - fun whenDomainIsRemovedFromUserAllowListThenItGetsDeletedFromDb() = runTest { + fun `removeDomainFromUserAllowList - domain removed - deleted 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 `domainsInUserAllowListFlow - allowlist 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..1b56b62804b5 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 `isMajor - entity prevalence greater than major network prevalence - true`() { assertTrue(TdsEntity("", "", MAJOR_NETWORK_PREVALENCE + 1).isMajor) } @Test - fun whenEntityPrevalenceLessOrEqualThanMajorNetworkPrevalenceThenIsMajorIsFalse() { + fun `isMajor - entity prevalence less or equal to major network prevalence - 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..395271ad0598 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 - true`() { assertTrue(TrustedSites.isTrusted("https://www.duckduckgo.com")) } @Test - fun whenSiteIsNotInTrustedListThenIsTrustedIsFalse() { + fun `isTrusted - site not in trusted list - 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..411152ecc519 100644 --- a/app/src/test/java/com/duckduckgo/app/privatesearch/PrivateSearchViewModelTest.kt +++ b/app/src/test/java/com/duckduckgo/app/privatesearch/PrivateSearchViewModelTest.kt @@ -60,21 +60,21 @@ internal class PrivateSearchViewModelTest { } @Test - fun whenAutocompleteSwitchedOnThenDataStoreIsUpdated() { + fun `onAutocompleteSettingChanged - switched on - dataStore updated`() { testee.onAutocompleteSettingChanged(true) verify(mockAppSettingsDataStore).autoCompleteSuggestionsEnabled = true } @Test - fun whenAutocompleteSwitchedOffThenDataStoreIsUpdated() { + fun `onAutocompleteSettingChanged - switched off - data store updated`() { testee.onAutocompleteSettingChanged(false) verify(mockAppSettingsDataStore).autoCompleteSuggestionsEnabled = false } @Test - fun whenMoreSearchSettingsClickedThenCommandLaunchCustomizeSearchWebPageAndPixelIsSent() = runTest { + fun `onPrivateSearchMoreSearchSettingsClicked - command launch customize search web page - pixel is 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..a157a425f4a1 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 is 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 auction 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 both EU auction search choice and campaign referrer data - EU auction 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 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 auction 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 both EU auction browser choice and campaign referrer data - EU auction 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..2647bbbd72b1 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 - pixel fired`() { testee // init verify(mockPixel).fire(AppPixelName.SETTINGS_OPENED) } @Test - fun whenStartCalledThenEmailAddressSetCorrectly() = runTest { + fun `start - email address 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 - default browser app already set - is default browser flag is true`() = runTest { whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(true) testee.start() @@ -163,7 +163,7 @@ class SettingsViewModelTest { } @Test - fun whenDefaultBrowserAppNotSetToOursThenIsDefaultBrowserFlagIsFalse() = runTest { + fun `start - default browser app not set to ours - isDefaultBrowser 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 - default cannot be set - showDefaultBrowserSetting 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 - default browser can be set - 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 `userRequestedToAddHomeScreenWidget - 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 - showAutofill false`() = runTest { whenever(autofillCapabilityChecker.canAccessCredentialManagementScreen()).thenReturn(false) testee.start() @@ -267,7 +267,7 @@ class SettingsViewModelTest { } @Test - fun whenAppTPOnboardingNotShownThenViewStateIsCorrect() = runTest { + fun `start - appTP onboarding not shown - viewState is correct`() = runTest { whenever(appTrackingProtection.isOnboarded()).thenReturn(false) testee.start() @@ -277,7 +277,7 @@ class SettingsViewModelTest { } @Test - fun whenAppTPOnboardingShownThenViewStateIsCorrect() = runTest { + fun `start - appTP onboarding shown - viewState is correct`() = 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 - sync feature disabled - viewState is correct`() = 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 - 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 - with pixel name - 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 web page and pixel fired`() = runTest { testee.commands().test { testee.onPrivateSearchSettingClicked() @@ -342,7 +342,7 @@ class SettingsViewModelTest { } @Test - fun whenWebTrackingProtectionSettingClickedThenEmitCommandLaunchWebTrackingProtectionWebPageAndPixelFired() = runTest { + fun `onWebTrackingProtectionSettingClicked - emit command and fire pixel`() = 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 - appTP onboarded - emit command launch appTP 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 - appTP not onboarded - emit command launch appTP 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 and fire pixel`() = 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 and fire pixel`() = runTest { testee.commands().test { testee.onCookiePopupProtectionSettingClicked() @@ -463,7 +463,7 @@ class SettingsViewModelTest { } @Test - fun whenAutoconsentEnabledThenAutoconsentEnabledIsTrue() = runTest { + fun `start - autoconsent enabled - autoconsentEnabled is true`() = runTest { whenever(mockAutoconsent.isSettingEnabled()).thenReturn(true) testee.start() @@ -474,7 +474,7 @@ class SettingsViewModelTest { } @Test - fun whenAutoconsentDisabledThenAutoconsentEnabledIsFalse() = runTest { + fun `start - autoconsent disabled - autoconsent enabled is 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..abb74362349a 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 `websitePermissionSettings - permissions settings loaded - viewState emitted settings`() = runTest { loadAskForPermissionsPrefs() loadWebsitePermissionsSettings() @@ -72,7 +72,7 @@ class PermissionsPerWebsiteViewModelTest { } @Test - fun whenSitePermissionIsAllowAlwaysThenShowSettingAsAllow() = runTest { + fun `websitePermissionSettings - 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 `websitePermissionSettings - site permission is 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 `websitePermissionSettings - 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 `websitePermissionSettings - ask for site permission prefs disabled and setting is ask - show setting as ask disabled`() = runTest { loadAskForPermissionsPrefs(cameraEnabled = false) loadWebsitePermissionsSettings() @@ -124,7 +124,7 @@ class PermissionsPerWebsiteViewModelTest { } @Test - fun whenAskForSitePermissionPrefsIsDisabledAndSettingIsDenyThenShowSettingAsDeny() = runTest { + fun `websitePermissionSettings - ask for site permission prefs disabled and setting is 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 `websitePermissionSettings - ask for site permission prefs disabled and setting is allow - 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 `permissionSettingSelected - show settings selection dialog`() = runTest { loadAskForPermissionsPrefs() loadWebsitePermissionsSettings() @@ -165,7 +165,7 @@ class PermissionsPerWebsiteViewModelTest { } @Test - fun whenPermissionSettingIsChangedThenSave() = runTest { + fun `onPermissionSettingSelected - permission setting changed - save`() = runTest { loadAskForPermissionsPrefs() loadWebsitePermissionsSettings() @@ -184,7 +184,7 @@ class PermissionsPerWebsiteViewModelTest { } @Test - fun whenWebsitePermissionsAreRemovedThenDeleteFromDB() = runTest { + fun `removeWebsitePermissionsSettings - website permissions removed - delete from DB`() = runTest { loadAskForPermissionsPrefs() loadWebsitePermissionsSettings() @@ -195,7 +195,7 @@ class PermissionsPerWebsiteViewModelTest { } @Test - fun whenWebsitePermissionsAreRemovedThenNavigateBackToSitePermissionsScreen() = runTest { + fun `removeWebsitePermissionsSettings - 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..0a4fabd21c10 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 `viewState - allowed sites loaded - 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 `viewState - allowed sites loaded - location websites emitted`() = runTest { viewModel.viewState.test { val sitePermissions = awaitItem().locationPermissionsAllowed assertEquals(1, sitePermissions.size) @@ -82,21 +82,21 @@ class SitePermissionsViewModelTest { } @Test - fun whenRemoveAllWebsitesThenClearAllLocationWebsitesIsCalled() = runTest { + fun `removeAllSitesSelected - clear all location websites is called`() = runTest { viewModel.removeAllSitesSelected() verify(mockGeoLocationPermissions).clearAll() } @Test - fun whenRemoveAllWebsitesThenDeleteAllSitePermissionsIsCalled() = runTest { + fun `removeAllSitesSelected - delete all site permissions`() = runTest { viewModel.removeAllSitesSelected() verify(mockSitePermissionsRepository).deleteAll() } @Test - fun whenRemoveAllWebsitesThenShowRemoveAllSnackBar() = runTest { + fun `removeAllSitesSelected - show remove all snackbar`() = runTest { viewModel.removeAllSitesSelected() viewModel.commands.test { @@ -105,7 +105,7 @@ class SitePermissionsViewModelTest { } @Test - fun whenPermissionsSettingsAreLoadedThenViewStateEmittedForAskLocationEnabled() = runTest { + fun `loadPermissionsSettings - viewState emitted for ask location disabled`() = runTest { loadPermissionsSettings(locationEnabled = false) viewModel.viewState.test { val askLocationEnabled = awaitItem().askLocationEnabled @@ -114,7 +114,7 @@ class SitePermissionsViewModelTest { } @Test - fun whenPermissionsSettingsAreLoadedThenViewStateEmittedForAskCameraEnabled() = runTest { + fun `loadPermissionsSettings - viewState emitted for ask camera enabled`() = runTest { loadPermissionsSettings(cameraEnabled = false) viewModel.viewState.test { @@ -124,7 +124,7 @@ class SitePermissionsViewModelTest { } @Test - fun whenPermissionsSettingsAreLoadedThenViewStateEmittedForAskMicEnabled() = runTest { + fun `loadPermissionsSettings - viewState emitted for ask mic enabled`() = runTest { loadPermissionsSettings(micEnabled = false) viewModel.viewState.test { @@ -134,7 +134,7 @@ class SitePermissionsViewModelTest { } @Test - fun whenToggleOffAskForLocationThenViewStateEmitted() = runTest { + fun `permissionToggleSelected - toggle off ask for location - viewState emitted`() = runTest { viewModel.permissionToggleSelected(false, R.string.sitePermissionsSettingsLocation) viewModel.viewState.test { @@ -144,7 +144,7 @@ class SitePermissionsViewModelTest { } @Test - fun whenToggleOffAskForCameraThenViewStateEmitted() = runTest { + fun `permissionToggleSelected - toggle off ask for camera - viewState emitted`() = runTest { viewModel.permissionToggleSelected(false, R.string.sitePermissionsSettingsCamera) viewModel.viewState.test { @@ -154,7 +154,7 @@ class SitePermissionsViewModelTest { } @Test - fun whenToggleOffAskForMicThenViewStateEmitted() = runTest { + fun `permissionToggleSelected - toggle off ask for mic - viewState emitted`() = runTest { viewModel.permissionToggleSelected(false, R.string.sitePermissionsSettingsMicrophone) viewModel.viewState.test { @@ -164,7 +164,7 @@ class SitePermissionsViewModelTest { } @Test - fun whenWebsiteIsTappedThenNavigateToPermissionsPerWebsiteScreen() = runTest { + fun `allowedSiteSelected - website tapped - 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..7ad2d60fbce7 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`() { 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..8899cbe40c4d 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 `getAll - initialised - has no surrogates loaded`() { assertEquals(0, testee.getAll().size) } @Test - fun whenOneSurrogateLoadedThenOneReturnedFromFullList() { + fun `getAll - one surrogate loaded - one returned`() { val surrogate = SurrogateResponse() testee.loadSurrogates(listOf(surrogate)) assertEquals(1, testee.getAll().size) } @Test - fun whenMultipleSurrogatesLoadedThenAllReturnedFromFullList() { + fun `loadSurrogates - multiple surrogates - all returned from full list`() { val surrogate = SurrogateResponse() testee.loadSurrogates(listOf(surrogate, surrogate, surrogate)) assertEquals(3, testee.getAll().size) } @Test - fun whenSearchingForExactMatchingExistingSurrogateThenCanFindByScriptId() { + fun `get - exact matching existing surrogate - can find by scriptId`() { 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 `get - 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..72d3c0cc8e3d 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 `download - survey for email received and user is signed in - 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 - user not eligible for new survey - 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..5ceb10e09660 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 - survey is 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 - user is eligible`() { 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 `isUserEligibleForSurvey - locale is Canada and required days installed met - survey 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 `isUserEligibleForSurvey - UK locale and required days installed met - survey 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 `remainingDaysForShowingSurvey - required days installed is null and retention days below default - return minus 1`() { whenever(userBrowserProperties.daysSinceInstalled()).thenReturn(4) val survey = Survey( surveyId = "id", @@ -156,7 +156,7 @@ class SurveyRepositoryTest { } @Test - fun whenRequiredDaysInstalledIsNullAndRetentionDaysAboveDefaultDaysThenReturn0() { + fun `remainingDaysForShowingSurvey - required days installed is null and retention days above default - return 0`() { whenever(userBrowserProperties.daysSinceInstalled()).thenReturn(31) val survey = Survey( surveyId = "id", @@ -170,7 +170,7 @@ class SurveyRepositoryTest { } @Test - fun whenRequiredDaysInstalledIsMinus1AndNotFirstDayThenRemainingDaysToSurveyIsZero() { + fun `remainingDaysForShowingSurvey - required days installed is minus 1 and not first day - remaining days is zero`() { whenever(userBrowserProperties.daysSinceInstalled()).thenReturn(4) val survey = Survey( surveyId = "id", @@ -184,7 +184,7 @@ class SurveyRepositoryTest { } @Test - fun whenRequiredDaysInstalledAndDaysInstallNotEnoughThenShouldNotShowSurvey() { + fun `shouldShowSurvey - days installed not enough - should not show survey`() { whenever(userBrowserProperties.daysSinceInstalled()).thenReturn(2) val survey = Survey( surveyId = "id", @@ -198,7 +198,7 @@ class SurveyRepositoryTest { } @Test - fun whenRetentionDaysIsAboveRequiredDaysInstalledThenShouldNotShowSurvey() { + fun `shouldShowSurvey - retention days above required - 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 is 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 survey`() { val survey = Survey( surveyId = "1", status = Survey.Status.SCHEDULED, @@ -242,7 +242,7 @@ class SurveyRepositoryTest { } @Test - fun givenExistingSurveyWhenCheckingIfSurveyExistThenReturnTrue() { + fun `surveyExists - existing survey - return true`() { val survey = Survey( surveyId = "id", status = Survey.Status.SCHEDULED, @@ -255,7 +255,7 @@ class SurveyRepositoryTest { } @Test - fun givenNonExistingSurveyWhenCheckingIfSurveyExistThenReturnFalse() { + fun `surveyExists - non-existing survey - return 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..d7e68a79a5f0 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 is 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 is 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 - type is survey but unknown params - return null`() { val jsonMessageAction = JsonMessageAction( type = "survey", value = "value", @@ -87,7 +87,7 @@ class SurveyActionMapperTest { } @Test - fun whenEvaluateAndQueryParamsInPayloadThenReturnActionSurveyWithQueryParams() = runTest { + fun `evaluate - 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 - type is 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..1c4e545b2d8d 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 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 - 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 is shown`() { testee.onSurveyLoaded() verify(mockCommandObserver).onChanged(Command.ShowSurvey) } @Test - fun whenSurveyCompletedThenViewIsClosedAndRecordIsUpdatedAnd() { + fun `onSurveyCompleted - 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 `onSurveyCompleted - survey notification is cleared`() { testee.start(Survey("", "https://survey.com", null, SCHEDULED), testSource) testee.onSurveyCompleted() verify(mockSurveyRepository).clearSurveyNotification() } @Test - fun whenSurveyDismissedThenViewIsClosedAndRecordIsNotUpdated() { + fun `onSurveyDismissed - view closed - 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..5f367fd46df4 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 - sync enabled - favorite folders created`() { testee.onFormFactorFavouritesEnabled() assertNotNull(savedSitesEntitiesDao.entityById(SavedSitesNames.FAVORITES_ROOT)) @@ -87,7 +87,7 @@ class RealSavedSitesFormFactorSyncMigrationTest { } @Test - fun whenSyncEnabledThenAllFavoritesCopiedToNativeFolder() = runTest { + fun `onFormFactorFavouritesEnabled - sync enabled - 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 `onFormFactorFavouritesDisabled - display mode native and favorites in all form factor folder - 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 - unified display mode and favorites in all form factor folder - 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 - sync disabled and display mode unified - new display mode is native`() { savedSiteSettingsRepository.favoritesDisplayMode = FavoritesDisplayMode.UNIFIED testee.onFormFactorFavouritesDisabled() @@ -150,7 +150,7 @@ class RealSavedSitesFormFactorSyncMigrationTest { } @Test - fun whenSyncDisabledAndDisplayModeNativeThenNewDisplayModeIsNative() { + fun `onFormFactorFavouritesDisabled - sync disabled and display mode native - new display mode is native`() { savedSiteSettingsRepository.favoritesDisplayMode = FavoritesDisplayMode.NATIVE testee.onFormFactorFavouritesDisabled() @@ -159,7 +159,7 @@ class RealSavedSitesFormFactorSyncMigrationTest { } @Test - fun whenSyncDisabledThenOnlyFavoritesRootFolderExist() { + fun `onFormFactorFavouritesDisabled - sync disabled - 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..b3381de4935d 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 - user has no bookmarks - changes are empty`() { val syncChanges = parser.allContent() assertTrue(syncChanges.isEmpty()) } @Test - fun whenGettingAllContentAndUsersHasFavoritesThenChangesAreNotEmpty() { + fun `allContent - users have favorites - changes are not empty`() { repository.insert(favourite1) repository.insert(bookmark1) repository.insert(bookmark3) @@ -201,7 +201,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenFirstSyncAndUsersHasFavoritesThenFormFactorFolderPresent() { + fun `getChanges - first sync with favorites - 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 - first sync invalid bookmark - changes do not contain invalid entity`() { repository.insert(invalidBookmark) val syncChanges = parser.getChanges() @@ -247,7 +247,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenOnFirstSyncFolderIsInvalidThenChangesContainDataFixed() { + fun `getChanges - first sync folder is invalid - data fixed`() { repository.insert(invalidBookmark) repository.insert(invalidFolder) @@ -262,7 +262,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenNewBookmarkIsInvalidThenChangesDoesNotContainInvalidEntity() { + fun `getChanges - new bookmark is 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 `getChanges - invalid bookmark present and valid bookmark added - 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 `getChanges - new folders and bookmarks and favourites since last sync - changes contain data`() { val modificationTimestamp = DatabaseDateFormatter.iso8601() val lastSyncTimestamp = DatabaseDateFormatter.iso8601(twoHoursAgo) setLastSyncTime(lastSyncTimestamp) @@ -335,7 +335,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenNewFavouritesSinceLastSyncThenChangesContainData() { + fun `changesSince - new favourites since last sync - 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 - changes are empty`() { val modificationTimestamp = DatabaseDateFormatter.iso8601(twoHoursAgo) val lastSyncTimestamp = DatabaseDateFormatter.iso8601() setLastSyncTime(lastSyncTimestamp) @@ -379,7 +379,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenBookmarkDeletedAfterLastSyncThenChangesContainData() { + fun `changesSince - bookmark deleted after last sync - changes contain data`() { val modificationTimestamp = DatabaseDateFormatter.iso8601() val lastSyncTimestamp = DatabaseDateFormatter.iso8601(twoHoursAgo) setLastSyncTime(lastSyncTimestamp) @@ -403,7 +403,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenFolderDeletedAfterLastSyncThenChangesContainData() { + fun `changesSince - folder deleted after last sync - changes contain data`() { val lastSyncTimestamp = DatabaseDateFormatter.iso8601(twoHoursAgo) setLastSyncTime(lastSyncTimestamp) @@ -429,7 +429,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenFavouriteDeletedAfterLastSyncThenChangesContainData() { + fun `changesSince - favourite deleted after last sync - changes contain data`() { val lastSyncTimestamp = DatabaseDateFormatter.iso8601(twoHoursAgo) setLastSyncTime(lastSyncTimestamp) @@ -445,7 +445,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenFavouritesAndBookmarksDeletedAfterLastSyncThenChangesContainData() { + fun `changesSince - favourites and bookmarks deleted after last sync - contain data`() { val lastSyncTimestamp = DatabaseDateFormatter.iso8601(twoHoursAgo) setLastSyncTime(lastSyncTimestamp) @@ -466,7 +466,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenFolderMovedToAnotherFolderAfterLastSyncThenChangesContainData() { + fun `changesSince - folder moved to another folder after last sync - 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 `allContent - no changes need sync - children request not added to metadata`() { val syncChanges = parser.allContent() assertTrue(syncChanges.isEmpty()) @@ -496,7 +496,7 @@ class SavedSitesSyncDataProviderTest { } @Test - fun whenChangesNeedSyncThenChildrenRequestIsAddedToMetadata() { + fun `getChanges - changes need sync - children request 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..62af2e2227c8 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 - bookmark is 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 - deleted bookmark not present locally - bookmark is 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 - bookmark duplicate - bookmark id is replaced`() { 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 - not empty favourite folders - 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 is 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 - deleted folder not present locally - folder is 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 - folder present locally - folder is 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..42a1ad726014 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 `findBookmarkDuplicate - bookmark already exists - duplicate is 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 - duplicate is not found`() { 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 - same URLs different IDs - 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 `findBookmarkDuplicate - bookmark already exists with different url - duplicate is not found`() { 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 - duplicate is not found`() { 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 - duplicate is not found`() { 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 exists with different parent id - duplicate not found`() { 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 parentId and ids - duplicate not found`() { 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 `findBookmarkDuplicate - bookmark not present - duplicate is not found`() { 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 `findFolderDuplicate - folder not present - duplicate 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 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 with different parent id - duplicate not found`() { 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 - same title different parent id - duplicate not found`() { 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 with same title and parentId - duplicate is 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..f330d546b6d3 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 - bookmark is 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 - deleted bookmark not present locally - bookmark is 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 - remote bookmark present locally - bookmark is 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 - 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 - not empty favourite folders - favourites are 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 is 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 - 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 - processing folder - folder is 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..563d9a6df707 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 - bookmark is 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 - deleted bookmark not present locally - bookmark is 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 - 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 - 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 - not empty favourite folders - favourites are 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 is 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 - 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 is 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..de0595b6fa9c 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 - bookmark is 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 - deleted bookmark not present locally - bookmark is 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 - remote 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 - bookmark is 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 - deleted remote bookmark - 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 - not empty favourite folders - favourites are 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 is 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 - 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 is 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 - folder is 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 is 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..289b343ee14d 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 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 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 - matches past short name word boundary to next prefix - matches 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 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 - 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 match for app name - no apps returned`() { 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 is empty - no apps returned`() { whenever(mockAppProvider.get()).thenReturn(noApps) val result = testee.query("DDG") assertTrue(result.isEmpty()) } @Test - fun whenQueryMatchesAppNameWithSpecialRegexCharactersThenAppReturnedWithoutCrashing() { + fun `query - 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..9bea756ec4ec 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 `resetViewState - onboarding should not show - view 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 `onboardingViewState - onboarding should show - 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 `userTappedOnboardingToggle - onboarding unexpanded - expanded and pixel sent`() = runTest { whenOnboardingShowing() testee.userTappedOnboardingToggle() @@ -134,7 +134,7 @@ class SystemSearchViewModelTest { } @Test - fun whenOnboardingIsExpandedAndUserPressesToggleThenItIsUnexpandedAndPixelSent() = runTest { + fun `userTappedOnboardingToggle - onboarding expanded - 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 `userDismissedOnboarding - onboarding dismissed - view hidden, pixel sent, 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 - adds space to query - viewState matches and space trimmed from autocomplete`() = runTest { testee.userUpdatedQuery(QUERY) testee.userUpdatedQuery("$QUERY ") @@ -177,7 +177,7 @@ class SystemSearchViewModelTest { } @Test - fun whenUsersUpdatesWithAutoCompleteEnabledThenAutoCompleteSuggestionsIsNotEmpty() = runTest { + fun `userUpdatedQuery - autoComplete enabled - suggestions not empty`() = runTest { doReturn(true).whenever(mockSettingsStore).autoCompleteSuggestionsEnabled testee.userUpdatedQuery(QUERY) @@ -188,7 +188,7 @@ class SystemSearchViewModelTest { } @Test - fun whenUsersUpdatesWithAutoCompleteDisabledThenViewStateReset() = runTest { + fun `userUpdatedQuery - autoComplete disabled - viewState reset`() = runTest { doReturn(false).whenever(mockSettingsStore).autoCompleteSuggestionsEnabled testee.userUpdatedQuery(QUERY) @@ -196,7 +196,7 @@ class SystemSearchViewModelTest { } @Test - fun whenUserClearsQueryThenViewStateReset() = runTest { + fun `userRequestedClear - viewState reset`() = runTest { testee.userUpdatedQuery(QUERY) testee.userRequestedClear() @@ -204,7 +204,7 @@ class SystemSearchViewModelTest { } @Test - fun whenUsersUpdatesWithBlankQueryThenViewStateReset() = runTest { + fun `userUpdatedQuery - blank query - viewState 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 `userSubmittedQuery - query with space - 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 `userSubmittedQuery - blank query - ignored`() { 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`() = runTest { testee.userSubmittedQuery(QUERY) verify(mockUserStageStore).stageCompleted(AppStage.NEW) } @Test - fun whenUserSubmitsAutocompleteResultThenBrowserLaunchedAndPixelSent() { + fun `userSubmittedAutocompleteResult - 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 `userSelectedApp - 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 `userTappedDax - 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`() = runTest { testee.userTappedDax() verify(mockUserStageStore).stageCompleted(AppStage.NEW) } @Test - fun whenViewModelCreatedThenAppsRefreshed() = runTest { + fun `onViewModelCreated - apps refreshed`() = runTest { verify(mockDeviceAppLookup).refreshAppList() } @Test - fun whenUserSelectsAppThatCannotBeFoundThenAppsRefreshedAndUserMessageShown() = runTest { + fun `appNotFound - app cannot be found - apps refreshed and user message shown`() = 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 - quick access delete requested - favorite deleted from viewState`() = 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 - quick access delete - viewState 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 `deleteFavoriteSnackbarDismissed - 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 `deleteSavedSiteSnackbarDismissed - associated bookmark deleted - 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 `SystemSearchViewModel - user has favorites - initial state 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..58f03fdc2995 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 `displayTitle - tab is blank - DuckDuckGo`() { whenever(context.getString(R.string.homeTab)).thenReturn("DuckDuckGo") assertEquals("DuckDuckGo", TabEntity("", position = 0).displayTitle(context)) } @Test - fun whenTabHasTitleThenDisplayTitleIsSame() { + fun `displayTitle - tab has title - same`() { assertEquals(TITLE, TabEntity("", URL, TITLE, position = 0).displayTitle(context)) } @Test - fun whenTabDoesNotHaveTitleThenDisplayTitleIsUrlHost() { + fun `displayTitle - tab does not have title - display title is URL host`() { assertEquals("example.com", TabEntity("", URL, null, position = 0).displayTitle(context)) } @Test - fun whenTabDoesNotHaveTitleAndUrlIsInvalidThenTitleIsBlank() { + fun `displayTitle - tab without title and invalid URL - title is blank`() { assertEquals("", TabEntity("", INVALID_URL, null, position = 0).displayTitle(context)) } @Test - fun whenTabIsBlankThenUrlIsDuckDuckGo() { + fun `displayUrl - tab is blank - url is DuckDuckGo`() { assertEquals("https://duckduckgo.com", TabEntity("", position = 0).displayUrl()) } @Test - fun whenTabHasUrlThenDisplayUrlIsSame() { + fun `displayUrl - tab has URL - same URL`() { assertEquals(URL, TabEntity("", URL, TITLE, position = 0).displayUrl()) } @Test - fun whenTabDoesNotHaveAUrlThenDisplayUrlIsBlank() { + fun `displayUrl - tab does not have a URL - 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..aeed63f5f935 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 - tab selected - 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 markDeletable`() = runTest { val entity = TabEntity("abc", "", "", position = 0) testee.onMarkTabAsDeletable(entity) @@ -129,7 +129,7 @@ class TabSwitcherViewModelTest { } @Test - fun whenUndoDeletableTabThenUndoDeletable() = runTest { + fun `undoDeletableTab - 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`() = runTest { testee.purgeDeletableTabs() verify(mockTabRepository).purgeDeletableTabs() } @Test - fun whenRepositoryDeletableTabsUpdatesThenDeletableTabsEmits() = runTest { + fun `deletableTabs - repository 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 `deletableTabs - repository 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 tabId cleared and session deleted`() = 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..b5370b262431 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 `detectCnameCloakedHost - host is null - return null`() { whenever(mockUri.host).thenReturn(null) assertNull(testee.detectCnameCloakedHost("foo.com", mockUri)) } @Test - fun whenDetectCnameAndCnameDetectedThenReturnUncloakedHost() { + fun `detectCnameCloakedHost - 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 `detectCnameCloakedHost - cname detected with scheme - return 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 `detectCnameCloakedHost - 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 `detectCnameCloakedHost - cname detected with 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 `detectCnameCloakedHost - cname detected with scheme and path - return 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 - url in 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..27b1601b46c2 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 - 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 - one matching domain - value is returned`() { 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 - one matching domain - domain is searched for`() { val url = "a.com" testee.entityForUrl("https://$url") verify(mockDomainEntityDao).get("a.com") @@ -65,7 +65,7 @@ class EntityLookupTest { } @Test - fun whenUrlContainsOneUnmatchedSubDomainAndOneMatchingDomainThenValueIsReturned() { + fun `entityForUrl - unmatched subdomain and matching domain - value is returned`() { 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 - TLD is searched 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 - many unmatched subdomains - all intermediate values are searched`() { 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 - 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..82d3f6110e09 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 `test - url has same domain as tracker entry and default action block - matches is true`() { test(url = "http://tracker.com/script.js", trackerDomain = trackerDomain, action = BLOCK, expected = true) } @Test - fun whenUrlHasSameDomainAsTrackerEntryAndDefaultActionIgnoreThenMatchesIsFalse() { + fun `matches - 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 `test - url is subdomain of tracker entry and default action block - matches is true`() { test(url = "http://subdomian.tracker.com/script.js", trackerDomain = trackerDomain, action = BLOCK, expected = true) } @Test - fun whenUrlIsNotDomainOrSubDomainOfTrackerEntryThenMatchesIsFalse() { + fun `matches - url is not domain or subdomain of tracker entry - 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 - false`() { test(url = "http://tracker.com/script.js", trackerDomain = Domain("subdomain.tracker.com"), action = BLOCK, expected = false) } @Test - fun whenUrlContainsButIsNotSubdomainOfATrackerEntryThenMatchesIsFalse() { + fun `test - url not subdomain of tracker entry - matches is false`() { test(url = "http://notsubdomainoftracker.com", trackerDomain = trackerDomain, action = BLOCK, expected = false) } @Test - fun whenUrlMatchesRuleWithNoExceptionsAndRuleActionBlockThenMatchesIsTrue() { + fun `test - rule with no exceptions and action block - matches is true`() { test(rule = ruleBlockNullExceptions, url = url, trackerDomain = trackerDomain, action = BLOCK, expected = true) } @Test - fun whenUrlMatchesRuleWithNoExceptionsAndRuleActionIgnoreThenMatchesIsFalse() { + fun `test - rule action ignore with no exceptions - 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 `test - url matches domain with default ignore and rule with no exceptions and no action - matches is true`() { test(rule = ruleNullExceptions, url = url, trackerDomain = trackerDomain, action = IGNORE, expected = true) } @Test - fun whenUrlMatchesRuleWithExceptionsAndExceptionDomainMatchesDocumentThenMatchesIsFalseIrrespectiveOfAction() { + fun `matches - rule with exceptions and exception domain matches document - 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 `matchesBehavior - rule with exceptions and exception domain does not match document - 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 `matches - rule with exceptions and type matches exception - 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 `matches - rule with surrogate - true irrespective of action 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 `test - url matches rule with type exception and 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 `test - url matches rule with type exception and domains empty - matches 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 `test - url matches rule with 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 `test - url matches rule with domain exception and types empty - matches is false`() { test( mapResult = image, rule = Rule( @@ -219,7 +219,7 @@ class TdsClientTest { } @Test - fun whenUrlMatchesRuleWithDomainAndTypeExceptionThenMatchesIsFalse() { + fun `test - url matches rule with domain and type exception - matches 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 `test - url matches rule with 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 `test - url matches rule with 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 `matches - blocked tracker with matching exception and empty option domain - 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 `test - blocked tracker with matching exception 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 `matches - blocked tracker with matching exception and option domain but not option type - 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 - blocked tracker with matching exception but not option domain and type - 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 `test - options don't match domain or type - 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 - surrogate script id returned`() { 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..ce533a641937 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 - persist entities`() { 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..c1a6e85ed2c1 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 - returns 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..74e71a6c0f0f 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 `clientCount - no clients - 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 `addClient - different names - count is two`() { trackerDetector.addClient(alwaysMatchingClient(CLIENT_A)) trackerDetector.addClient(alwaysMatchingClient(CLIENT_B)) assertEquals(2, trackerDetector.clientCount) } @Test - fun whenTwoClientsWithSameNameAddedThenClientIsReplacedAndCountIsStillOne() { + fun `addClient - same name - client replaced and count is 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 is third party - returns non tracking event`() { 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 - returns same entity non tracking event`() { 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 - third party but ignored - returns 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 - third party but ignored - returns non-tracking event`() { 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 - returns blocked tracking event`() { 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 - user allow listed and all clients match - returns unblocked tracking event`() { 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 - returns blocked tracking event`() { 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 - returns 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 - user allow listed and some clients match - returns unblocked tracking event`() { 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 - returns unblocked tracking event`() { 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 clients match with surrogate - returns 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 - request in allowlist and some clients match - returns unblocked tracking event`() { 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 - request in ad click allow list and some clients match - returns unblocked tracking event`() { 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 as document - 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..a4732d385669 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 `jsonToDomainEntities - valid format - 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 `jsonToDomainEntities - valid format - 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 `jsonToDomainEntities - 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..1bbac9612e86 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 `jsonToEntities - valid format - 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 `jsonToEntities - valid format - 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 `jsonToEntities - entity 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 `jsonToEntities - entity missing display name - display name is 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 `jsonToEntities - entity has blank display name - display name is 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..58baaf6df82d 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 `jsonToTrackers - valid format - trackers are created`() { val json = loadText(javaClass.classLoader!!, "json/tds_trackers.json") val trackers = jsonAdapter.fromJson(json)!!.jsonToTrackers() assertEquals(3, trackers.count()) } @Test - fun whenFormatIsValidThenBasicElementsAreConvertedCorrectly() { + fun `jsonToTrackers - valid format - 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 `jsonToTrackers - invalid default action - 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 `jsonToTrackers - tracker missing default action - 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..8bcd5837df37 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 - return ETag`() { val headers = Headers.headersOf("eTag", "W/\"123456789\"") assertEquals(ETAG, headers.extractETag()) } @Test - fun whenExtractETagAndContainsQuotesThenReturnETag() { + fun `extractETag - contains quotes - return eTag`() { val headers = Headers.headersOf("eTag", "\"123456789\"") assertEquals(ETAG, headers.extractETag()) } @Test - fun whenExtractETagAndDoesNotContainsQuotesAndPrefixThenReturnETag() { + fun `extractETag - no quotes and prefix - return 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..b2adb5616751 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 `viewState - initialised - GPG disabled`() = 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 `viewState - Gpc toggle enabled and Gpc disabled - Gpc 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 `viewState - Gpc toggle enabled and Gpc enabled - Gpc enabled`() = 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..b306cca87d46 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 `launchAddWidget - automatic widget add supported - delegate to app widget manager`() { 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..d9264630fad1 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 - sharedPreferences 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 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..5caa730503ce 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 - 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 - keeps correct positions`() = runTest { val initialEntities = listOf("A", "Inv1", "C", "Inv2", "D") initialEntities.forEachIndexed { index, entityId -> @@ -88,7 +88,7 @@ class MissingEntitiesRelationReconcilerTest { } @Test - fun whenInvalidEntitiesAndValidItemRemovedThenResultListKeepsCorrectPositions() = runTest { + fun `reconcileRelations - invalid entities and valid item removed - 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 end - 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 in the middle - 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 - 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 - items reordered - 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 - invalid multiple entities start 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 - return 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..a8602881b1dc 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 - return 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 - return 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 - return 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 - return 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 - return 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 - return 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 checks 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 - 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 - 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 - items on root folder - 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 items 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 - native mode - update items on root 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) @@ -320,7 +320,7 @@ class RealFavoritesDelegateTest { } @Test - fun whenInsertFavoriteThenUpdateItemsOnRootFolder() { + fun `insertFavorite - update items on root folder`() { 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 - delete 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 non-desktop favorite - delete 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..b891a8e161c3 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 - observer added - current viewState emitted`() = runTest { testee.favoritesDisplayModeFlow().test { assertEquals(NATIVE, awaitItem()) } } @Test - fun whenDisplayModeChangedThenViewStateIsUpdated() = runTest { + fun `favoritesDisplayModeFlow - display mode changed - viewState updated`() = runTest { testee.favoritesDisplayModeFlow().test { awaitItem() testee.favoritesDisplayMode = UNIFIED @@ -96,20 +96,20 @@ class RealFavoritesDisplayModeSettingsRepositoryTest { } @Test - fun whenDisplayModeChangedThenNotifySyncableSetting() = runTest { + fun `favoritesDisplayMode - changed - notify syncable setting`() = runTest { testee.favoritesDisplayMode = UNIFIED verify(syncSettingsListener).onSettingChanged(syncableSetting.key) } @Test - fun whenSyncDisabledThenQueryFolderIsFavoritesRoot() = runTest { + fun `getQueryFolder - sync disabled - is 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 - is 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 - is mobile root`() = runTest { syncStateFlow.value = SyncState.READY savedSitesSettingsStore.favoritesDisplayMode = UNIFIED assertEquals(SavedSitesNames.FAVORITES_ROOT, testee.getQueryFolder()) } @Test - fun whenSyncDisabledThenInsertFolderIsFavoritesRoot() = runTest { + fun `getInsertFolder - sync disabled - is 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 - is 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 - folder is 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 - 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 - is 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, native mode, 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 - is 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..0ee194f9823e 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 `intercept - survey url enabled - custom environment url used`() { 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 - unknown URL enabled - ignored`() { surveyEndpointDataStore.useSurveyCustomEnvironmentUrl = true val chain = FakeChain(UNKNOWN_URL) @@ -47,7 +47,7 @@ class SurveyEndpointInterceptorTest { } @Test - fun ignoreUnknownUrlWhenDisabled() { + fun `intercept - unknown URL disabled - ignored`() { 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..62ac0add03e8 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 - type matches - call process`() { val message = """{"type":"fake"}""" autoconsentInterface.process(message) @@ -48,7 +48,7 @@ class AutoconsentInterfaceTest { } @Test - fun whenMessagedParsedIfTypeDoesNotMatchThenDoNotCallProcess() { + fun `process - 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..10c14f4a61f5 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 - return value from repo`() { settingsRepository.userSetting = false assertFalse(autoconsent.isSettingEnabled()) @@ -116,7 +116,7 @@ class RealAutoconsentTest { } @Test - fun whenSetAutoconsentOptOutThenEvaluateJavascriptCalled() { + fun `setAutoconsentOptOut - evaluateJavascript called`() { val expected = """ javascript:(function() { window.autoconsentMessageCallback({ "type": "optOut" }, window.origin); @@ -128,25 +128,25 @@ class RealAutoconsentTest { } @Test - fun whenSetAutoconsentOptOutThenTrueValueStored() { + fun `setAutoconsentOptOut - true value stored`() { autoconsent.setAutoconsentOptOut(webView) assertTrue(settingsRepository.userSetting) } @Test - fun whenSetAutoconsentOptInThenFalseValueStored() { + fun `setAutoconsentOptIn - false value stored`() { autoconsent.setAutoconsentOptIn() assertFalse(settingsRepository.userSetting) } @Test - fun whenFirstPopUpHandledThenFalseValueStored() { + fun `firstPopUpHandled - 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..e871b68e6fe1 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 `process - type not eval - do nothing`() { evalMessageHandlerPlugin.process("noMatching", "", webView, mockCallback) assertNull(shadowOf(webView).lastEvaluatedJavascript) } @Test - fun whenProcessMessageIfDoesNotParseDoNothing() { + fun `process - message 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 - message - call evaluate with correct code`() { val expected = """ javascript:(function() { try { @@ -81,7 +81,7 @@ class EvalMessageHandlerPluginTest { } @Test - fun whenProcessMessageThenAndEvalTrueThenCorrectEvalRespSent() { + fun `process - eval true - correct eval response 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 - eval false - correct eval response 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..624cb0a7aaa6 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 - message type is not init - do nothing`() { initHandlerPlugin.process("noMatching", "", webView, mockCallback) assertNull(shadowOf(webView).lastEvaluatedJavascript) } @Test - fun whenProcessIfCannotParseMessageThenDoNothing() { + fun `process - cannot parse message - do nothing`() { val message = """ {"type":"${initHandlerPlugin.supportedTypes.first()}", url: "http://www.example.com"} """.trimIndent() @@ -73,7 +73,7 @@ class InitMessageHandlerPluginTest { } @Test - fun whenProcessIfNotUrlSchemaThenDoNothing() { + fun `process - not url schema - do nothing`() { val message = """ {"type":"${initHandlerPlugin.supportedTypes.first()}", "url": "ftp://www.example.com"} """.trimIndent() @@ -84,7 +84,7 @@ class InitMessageHandlerPluginTest { } @Test - fun whenProcessIfAutoconsentIsDisabledAndAlreadyHandledThenDoNothing() { + fun `process - autoconsent disabled and already handled - do nothing`() { settingsRepository.userSetting = false settingsRepository.firstPopupHandled = true @@ -94,7 +94,7 @@ class InitMessageHandlerPluginTest { } @Test - fun whenProcessIfAutoconsentIsDisabledAndNotHandledThenDoNotCallEvaluate() { + fun `process - autoconsent disabled and not handled - do not call evaluate`() { settingsRepository.userSetting = false settingsRepository.firstPopupHandled = false @@ -104,7 +104,7 @@ class InitMessageHandlerPluginTest { } @Test - fun whenProcessMessageForFirstTimeThenDoNotCallEvaluate() { + fun `process - message for first time - do not call evaluate`() { whenever(repository.disabledCMPs).thenReturn(CopyOnWriteArrayList().apply { add("MyCmp") }) settingsRepository.userSetting = false settingsRepository.firstPopupHandled = false @@ -117,7 +117,7 @@ class InitMessageHandlerPluginTest { } @Test - fun whenProcessMessageResponseSentIsCorrect() { + fun `process - message response sent - correct`() { settingsRepository.userSetting = true settingsRepository.firstPopupHandled = true whenever(repository.disabledCMPs).thenReturn(CopyOnWriteArrayList()) @@ -136,7 +136,7 @@ class InitMessageHandlerPluginTest { } @Test - fun whenProcessMessageThenOnResultReceivedCalled() { + fun `process - message - onResultReceived called`() { 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..ea3e1bc9434a 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 - message type not included - do nothing`() { handler.process("noMatching", "", webView, mockCallback) verifyNoInteractions(mockCallback) @@ -50,7 +50,7 @@ class OptOutAndAutoconsentDoneMessageHandlerPluginTest { } @Test - fun whenProcessIfCannotParseMessageThenDoNothing() { + fun `process - cannot parse message - 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 `process - opt out result fails - 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 `process - autoconsent done cosmetic - result sent with cosmetic true`() { handler.process(getAutoconsentType(), autoconsentDoneMessage(cosmetic = true), webView, mockCallback) verify(mockCallback).onResultReceived(consentManaged = true, optOutFailed = false, selfTestFailed = false, isCosmetic = true) } @Test - fun whenProcessAutoconsentDoneIfNotCosmeticThenResultSentWithCosmeticSetToFalse() { + fun `process - autoconsent done 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 `process - autoconsent done with no host - do nothing`() { handler.process(getAutoconsentType(), autoconsentDoneMessage("noHost"), webView, mockCallback) verifyNoInteractions(mockCallback) @@ -91,7 +91,7 @@ class OptOutAndAutoconsentDoneMessageHandlerPluginTest { } @Test - fun whenProcessOptOutWithSelfTestThenAutoconsentCallsEvaluateJavascript() { + fun `process - self test - autoconsent calls evaluateJavascript`() { 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..21002daa7f38 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 `process - message type is not popup - do nothing`() { popupFoundHandler.process("noMatching", "", webView, mockCallback) verify(mockCallback, never()).onFirstPopUpHandled() } @Test - fun whenProcessIfSettingEnabledThenDoNothing() { + fun `process - setting enabled - do nothing`() { repository.userSetting = true popupFoundHandler.process(popupFoundHandler.supportedTypes.first(), "", webView, mockCallback) @@ -53,7 +53,7 @@ class PopUpFoundMessageHandlerPluginTest { } @Test - fun whenProcessIfSettingDisabledAndCmpIsNotTopThenCallCallback() { + fun `process - setting disabled and CMP is not top - call callback`() { 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..b12661593e15 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 - message type is not self test - do nothing`() { selfTestPlugin.process("noMatching", "", webView, mockCallback) verifyNoInteractions(mockCallback) } @Test - fun whenProcessIfCannotParseMessageThenDoNothing() { + fun `process - cannot parse message - 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 - call dashboard with correct parameters`() { 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..d0bd53bb954c 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 `RealAutoconsentExceptionsRepository - repository created - exceptions loaded into memory`() { givenDaoContainsExceptions() repository = RealAutoconsentExceptionsRepository(TestScope(), coroutineRule.testDispatcherProvider, mockDatabase, isMainProcess = true) @@ -58,7 +58,7 @@ class RealAutoconsentExceptionsRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = runTest { + fun `insertAllExceptions - 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 `insertAllExceptions - 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..a1f8e8922cb3 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 `RealAutoconsentFeatureSettingsRepository - repository created - exceptions loaded into memory`() { givenDaoContainsDisabledCmps() repository = RealAutoconsentFeatureSettingsRepository(TestScope(), coroutineRule.testDispatcherProvider, mockDatabase, isMainProcess = true) @@ -58,7 +58,7 @@ class RealAutoconsentFeatureSettingsRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = runTest { + fun `updateAllSettings - update all called`() = runTest { repository = RealAutoconsentFeatureSettingsRepository(TestScope(), coroutineRule.testDispatcherProvider, mockDatabase, isMainProcess = true) repository.updateAllSettings(AutoconsentSettings(listOf())) @@ -67,7 +67,7 @@ class RealAutoconsentFeatureSettingsRepositoryTest { } @Test - fun whenUpdateAllThenPreviousExceptionsAreCleared() = runTest { + fun `updateAllSettings - previous exceptions are 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..7e9df835e95a 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 `viewModelCreated - emit viewState`() = runTest { viewModel.viewState.test { assertFalse(awaitItem().autoconsentEnabled) cancelAndIgnoreRemainingEvents() @@ -44,7 +44,7 @@ class AutoconsentSettingsViewModelTest { } @Test - fun whenOnLearnMoreSelectedCalledThenLaunchLearnMoreWebPageCommandIsSent() = runTest { + fun `onLearnMoreSelected - launch learn more web page 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 - 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 - autoconsentEnabled 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..31e8a29eedba 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 `assertAllSubFeaturesDisabled - top level feature disabled and disabled by user - cannot access any sub features`() = runTest { setupConfig(topLevelFeatureEnabled = false, autofillEnabledByUser = false) assertAllSubFeaturesDisabled() } @Test - fun whenTopLevelFeatureDisabledButEnabledByUserThenCannotAccessAnySubFeatures() = runTest { + fun `assertAllSubFeaturesDisabled - 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 `canInjectCredentialsToWebView - autofill enabled - inject credentials dictated by config`() = runTest { setupConfig(topLevelFeatureEnabled = true, autofillEnabledByUser = true, canInjectCredentials = true) assertTrue(testee.canInjectCredentialsToWebView(URL)) @@ -64,7 +64,7 @@ class AutofillCapabilityCheckerImplTest { } @Test - fun whenUserHasAutofillEnabledThenCanSaveCredentialsDictatedByConfig() = runTest { + fun `canSaveCredentialsFromWebView - autofill enabled - dictated by config`() = 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 - access dictated by config`() = 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 - dictated by config`() = runTest { setupConfig(topLevelFeatureEnabled = true, autofillEnabledByUser = true, canGeneratePassword = true) assertTrue(testee.canGeneratePasswordFromWebView(URL)) @@ -95,25 +95,25 @@ class AutofillCapabilityCheckerImplTest { */ @Test - fun whenUserHasAutofillEnabledButTopLevelFeatureDisabledThenCanInjectCredentialsIsFalse() = runTest { + fun `canInjectCredentialsToWebView - top level feature disabled and autofill enabled - false`() = runTest { setupConfig(topLevelFeatureEnabled = false, autofillEnabledByUser = true) assertFalse(testee.canInjectCredentialsToWebView(URL)) } @Test - fun whenUserHasAutofillEnabledThenCanSaveCredentialsIsFalse() = runTest { + fun `canSaveCredentialsFromWebView - autofill enabled - false`() = runTest { setupConfig(topLevelFeatureEnabled = false, autofillEnabledByUser = true) assertFalse(testee.canSaveCredentialsFromWebView(URL)) } @Test - fun whenUserHasAutofillEnabledThenCanAccessCredentialManagementScreenIsFalse() = runTest { + fun `canAccessCredentialManagementScreen - autofill enabled - false`() = runTest { setupConfig(topLevelFeatureEnabled = false, autofillEnabledByUser = true) assertFalse(testee.canAccessCredentialManagementScreen()) } @Test - fun whenUserHasAutofillEnabledThenCanGeneratePasswordFromWebViewIsFalse() = runTest { + fun `canGeneratePasswordFromWebView - autofill enabled - false`() = 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..70a47aa71094 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 `injectNoCredentials - correct JsonWriter invoked`() = runTest { testee.injectNoCredentials() verify(autofillResponseWriter).generateEmptyResponseGetAutofillData() verifyMessageSent() } @Test - fun whenInjectingCredentialResponseThenCorrectJsonWriterInvoked() = runTest { + fun `injectCredentials - correct JsonWriter 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 - 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 with null username - 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 - subtype username and no entries - 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 - subtype username with single entry - credentials available callback invoked`() = runTest { setupRequestForSubTypeUsername() whenever(autofillStore.getCredentials(any())).thenReturn( listOf( @@ -204,7 +204,7 @@ class AutofillStoredBackJavascriptInterfaceTest { } @Test - fun whenRequestSpecifiesSubtypeUsernameAndMultipleEntriesWithAUsernameThenCredentialsAvailableCallbackInvoked() = runTest { + fun `initiateGetAutofillDataRequest - subtype username with multiple entries - credentials available callback invoked`() = runTest { setupRequestForSubTypeUsername() whenever(autofillStore.getCredentials(any())).thenReturn( listOf( @@ -221,7 +221,7 @@ class AutofillStoredBackJavascriptInterfaceTest { } @Test - fun whenRequestSpecifiesSubtypePasswordAndNoEntriesThenNoCredentialsCallbackInvoked() = runTest { + fun `initiateGetAutofillDataRequest - 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 - subtype password with no entries - no credentials callback invoked`() = runTest { setupRequestForSubTypePassword() whenever(autofillStore.getCredentials(any())).thenReturn( listOf( @@ -242,7 +242,7 @@ class AutofillStoredBackJavascriptInterfaceTest { } @Test - fun whenRequestSpecifiesSubtypePasswordAndSingleEntryWithAPasswordThenCredentialsAvailableCallbackInvoked() = runTest { + fun `initiateGetAutofillDataRequest - subtype password with single entry - credentials available callback invoked`() = runTest { setupRequestForSubTypePassword() whenever(autofillStore.getCredentials(any())).thenReturn( listOf( @@ -257,7 +257,7 @@ class AutofillStoredBackJavascriptInterfaceTest { } @Test - fun whenRequestSpecifiesSubtypePasswordAndMultipleEntriesWithAPasswordThenCredentialsAvailableCallbackInvoked() = runTest { + fun `initiateGetAutofillDataRequest - subtype password with multiple entries - credentials available callback invoked`() = 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 - null username and password - callback not invoked`() = runTest { configureRequestParserToReturnSaveCredentialRequestType(username = null, password = null) testee.storeFormData("") assertNull(testCallback.credentialsToSave) } @Test - fun whenStoreFormDataCalledWithBlankUsernameThenCallbackInvoked() = runTest { + fun `storeFormData - 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 - 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 - blank username and password - callback not invoked`() = runTest { configureRequestParserToReturnSaveCredentialRequestType(username = " ", password = " ") testee.storeFormData("") assertNull(testCallback.credentialsToSave) } @Test - fun whenStoreFormDataCalledAndParsingErrorThenExceptionIsContained() = runTest { + fun `storeFormData - parsing error - exception is 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..8b1c944a79e2 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 - removes 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 - 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..8a6921e62042 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 - domain listed in exceptions - return true`() { givenThereAreExceptions() assertTrue(testee.isAnException("http://www.example.com")) } @Test - fun whenIsAnExceptionWithSubdomainAndDomainIsListedInTheExceptionsListThenReturnTrue() { + fun `isAnException - subdomain and domain listed in exceptions - return true`() { givenThereAreExceptions() assertTrue(testee.isAnException("http://test.example.com")) } @Test - fun whenIsAnExceptionAndDomainIsNotListedInTheExceptionsListThenReturnFalse() { + fun `isAnException - domain not listed in exceptions - return false`() { whenever(mockAutofillRepository.exceptions).thenReturn(CopyOnWriteArrayList()) assertFalse(testee.isAnException("http://test.example.com")) } @Test - fun whenIsAnExceptionAndDomainIsListedInTheUnprotectedTemporaryListThenReturnTrue() { + fun `isAnException - domain in unprotected temporary list - return 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..7261a46859a0 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 `createLoginForPrivateDuckAddress - 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 `createLoginForPrivateDuckAddress - no auto-saved login id - new login saved`() = runTest { configureReadyToAutoSave() testee.createLoginForPrivateDuckAddress(DUCK_ADDRESS, TAB_ID, URL) verifyLoginSaved() } @Test - fun whenAutoSavedLoginIdSetButNoMatchingLoginFoundThenNewLoginSaved() = runTest { + fun `createLoginForPrivateDuckAddress - no matching login found - new login saved`() = runTest { configureReadyToAutoSave() testee.createLoginForPrivateDuckAddress(DUCK_ADDRESS, TAB_ID, URL) verifyLoginSaved() } @Test - fun whenAutoSavedLoginFoundAndDetailsAlreadyMatchThenNotSavedOrUpdated() = runTest { + fun `createLoginForPrivateDuckAddress - auto-saved login found and details 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 `createLoginForPrivateDuckAddress - 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 `createLoginForPrivateDuckAddress - site not in never save list - auto save 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..76457d44c6da 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 `autofillEnabled - autofill unavailable and prefs are all true - returns true`() { setupTestee(canAccessSecureStorage = false) assertTrue(testee.autofillEnabled) } @Test - fun whenAutofillAvailableAndPrefsAreAllFalseThenReturnFalseForAutofillEnabled() = runTest { + fun `autofillEnabled - autofill available and prefs are all false - return false`() = runTest { setupTesteeWithAutofillAvailable() whenever(autofillPrefsStore.isEnabled).thenReturn(false) @@ -95,19 +95,19 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenSecureStorageAvailableThenReturnAutofillAvailable() = runTest { + fun `autofillAvailable - secure storage available - autofill available`() = runTest { setupTesteeWithAutofillAvailable() assertTrue(testee.autofillAvailable) } @Test - fun whenSecureStorageNotAvailableThenReturnAutofillAvailableFalse() { + fun `autofillAvailable - secure storage not available - false`() { setupTestee(canAccessSecureStorage = false) assertFalse(testee.autofillAvailable) } @Test - fun whenAutofillEnabledButCannotAccessSecureStorageThenGetCredentialsWithDomainReturnsEmpty() = runTest { + fun `getCredentials - 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 - matching username but not 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 - 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 - 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 for site with no username - 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 - store contains domain and username but different password - username match`() = 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 - matching domain, username, and password - exact match`() = 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 for URL stored - return nothing`() = runTest { setupTesteeWithAutofillAvailable() storeCredentials(1, "url.com", "username1", "password123") @@ -179,13 +179,13 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenNoCredentialsSavedThenGetAllCredentialsReturnNothing() = runTest { + fun `getAllCredentials - no credentials saved - return nothing`() = runTest { setupTesteeWithAutofillAvailable() assertEquals(0, testee.getAllCredentials().first().size) } @Test - fun whenStoredCredentialMissingUsernameAndStoringACredentialWithNoUsernameThenUrlOnlyMatch() = runTest { + fun `containsCredentials - missing 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 is updated for URL - updated only matching credential`() = 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 is updated - updated only matching credential`() = runTest { setupTesteeWithAutofillAvailable() val url = "example.com" storeCredentials(1, url, "username1", "password123") @@ -239,7 +239,7 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenDomainIsUpdatedTheCleanRawUrl() = runTest { + fun `updateCredentials - domain updated - 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 `updateCredentials - username is updated for url - updated only matching credential`() = 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 - returns saved on getCredentials`() = runTest { setupTesteeWithAutofillAvailable() val url = "example.com" val credentials = LoginCredentials( @@ -312,7 +312,7 @@ class SecureStoreBackedAutofillStoreTest { } @Test - fun whenPasswordIsDeletedThenRemoveCredentialFromStore() = runTest { + fun `deleteCredentials - password is deleted - 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 is stored - returns credentials`() = 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 - return 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 - credential matched`() = 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 - saved credential has no subdomain and visited page does - 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 - 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 - default - lastUpdatedTimestamp 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 - specify not to 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..13fcda61ea33 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 `configureAutofillForCurrentPage - 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 `configureAutofillForCurrentPage - 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..d3141de51149 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 - user prefs credentials is false`() = runTest { configureAutofillCapabilities(enabled = false) testee.getRuntimeConfiguration("", EXAMPLE_URL) verifyAutofillCredentialsReturnedAs(false) } @Test - fun whenAutofillEnabledThenConfigurationUserPrefsCredentialsIsTrue() = runTest { + fun `getRuntimeConfiguration - autofill enabled - user prefs credentials 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 - 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 - shareable credentials for URL - 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 - username only for url - 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 - empty username only for URL - 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 - password only for URL - input type credentials username is false`() = 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 - empty password only for URL - input type credentials username is false`() = 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 - autofill disabled with credentials - 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 - autofill unavailable with credentials for url - 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 is signed in - 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 - 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 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..caece594d888 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 `generateResponseGetAvailableInputTypes - 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 - return 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..ce231a02d74b 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 - multiple credentials with 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 - multiple 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 - multiple credentials 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..c799b979eb45 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+1 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..76f083b87359 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 - returns 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..3d5128f3ad05 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 - single entry out`() { val input = listOf( creds("username", "password"), ) @@ -24,7 +24,7 @@ class RealLoginDeduplicatorUsernameAndPasswordMatcherTest { } @Test - fun whenMultipleEntriesWithNoDuplicationAtAllThenNumberOfGroupsReturnedMatchesNumberOfEntriesInputted() { + fun `groupDuplicateCredentials - no duplication - number of groups matches number of entries`() { 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..213e5a4ead8b 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 is 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 is 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 - 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 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 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..6734bdd03a1e 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 - auth not required`() { recordAuthorizationWithinGracePeriod() timeProvider.reset() assertFalse(testee.isAuthRequired()) } @Test - fun whenLastSuccessfulAuthWasWithinGracePeriodButInvalidatedThenAuthRequired() { + fun `isAuthRequired - last successful auth within grace period but invalidated - 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..fffb1091d617 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 is 28 - checks legacy authentication`() { whenever(appBuildConfig.sdkInt).thenReturn(28) testee.hasValidDeviceAuthentication() @@ -74,7 +74,7 @@ class RealDeviceAuthenticatorTest { } @Test - fun whenSdkIs29ThenValidAuthenticationShouldCheckLegacy() { + fun `hasValidDeviceAuthentication - SDK is 29 - checks legacy authentication`() { whenever(appBuildConfig.sdkInt).thenReturn(29) testee.hasValidDeviceAuthentication() @@ -83,7 +83,7 @@ class RealDeviceAuthenticatorTest { } @Test - fun whenSdkIsNot28Or29ThenValidAuthenticationShouldCheckLegacy() { + fun `hasValidDeviceAuthentication - sdk is not 28 or 29 - check legacy`() { whenever(appBuildConfig.sdkInt).thenReturn(30) testee.hasValidDeviceAuthentication() @@ -92,13 +92,13 @@ class RealDeviceAuthenticatorTest { } @Test - fun whenAuthenticateToAccessCredentialsIsCalledWithFragmentThenLaunchAuthLauncher() { + fun `authenticate - called with fragment - launch auth launcher`() { testee.authenticate(fragment) {} verifyAuthDialogLaunched() } @Test - fun whenAuthenticateToAccessCredentialsIsCalledWithActivityThenLaunchAuthLauncher() { + fun `authenticate - called with 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..f753d7180d72 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 `viewState - initial 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 `viewState - initial state - 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 - webView cannot go back - cancel in context sign up state`() = runTest { testee.onBackButtonPressed("", false) testee.viewState.test { awaitItem() as CancellingInContextSignUp @@ -55,7 +55,7 @@ class EmailProtectionInContextSignupViewModelTest { } @Test - fun whenUrlNotKnownAndBackButtonPressedThenDefaultBackActionTaken() = runTest { + fun `onBackButtonPressed - url not known - 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 - 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 - back navigation consumed - 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 - URL in allowed back navigation list - 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 - url requires exit confirmation - 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 - url is landing page and 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 `onUserDecidedNotToCancelInContextSignUp - pixel fired`() { testee.onUserDecidedNotToCancelInContextSignUp() verify(pixel).fire(EMAIL_PROTECTION_IN_CONTEXT_MODAL_EXIT_EARLY_CANCEL) } @Test - fun whenUserConfirmsEarlyExitThenPixelFired() { + fun `onUserConfirmedCancellationOfInContextSignUp - pixel fired`() { testee.onUserConfirmedCancellationOfInContextSignUp() verify(pixel).fire(EMAIL_PROTECTION_IN_CONTEXT_MODAL_EXIT_EARLY_CONFIRM) } @Test - fun whenUserCancelsWithoutConfirmationThenPixelFired() { + fun `userCancelledSignupWithoutConfirmation - pixel fired`() { testee.userCancelledSignupWithoutConfirmation() verify(pixel).fire(EMAIL_PROTECTION_IN_CONTEXT_MODAL_DISMISSED) } @Test - fun whenUserCancelsWithoutConfirmationThenCancellationViewStateSent() = runTest { + fun `userCancelledSignupWithoutConfirmation - cancellation viewState 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..14bb93aa3ef7 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 to use 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 - use 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 - use 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 - use 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 - use 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..2ddd8e8f001b 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 `permittedToShow - locale not English - not permitted`() = runTest { configureNonEnglishLocale() assertFalse(testee.permittedToShow(ALLOWED_URL)) } @Test - fun whenInstalledALongTimeAgoThenNotPermitted() = runTest { + fun `permittedToShow - installed a long time ago - not permitted`() = runTest { configureAsNotRecentInstall() assertFalse(testee.permittedToShow(ALLOWED_URL)) } @Test - fun whenInstalledRecentlyThenPermitted() = runTest { + fun `permittedToShow - installed recently - permitted`() = runTest { configureAsRecentInstall() assertTrue(testee.permittedToShow(ALLOWED_URL)) } @Test - fun whenSecureAutofillUnavailableThenNotPermitted() = runTest { + fun `permittedToShow - secure autofill unavailable - not permitted`() = runTest { whenever(autofillGlobalCapabilityChecker.isSecureAutofillAvailable()).thenReturn(false) assertFalse(testee.permittedToShow(ALLOWED_URL)) } @Test - fun whenFeatureDisabledInRemoteConfigThenNotPermitted() = runTest { + fun `permittedToShow - feature disabled in remote config - not permitted`() = runTest { emailProtectionInContextSignupFeature.enabled = false assertFalse(testee.permittedToShow(ALLOWED_URL)) } @Test - fun whenUrlOnExceptionListThenNotPermitted() = runTest { + fun `permittedToShow - 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..423b36724ed2 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 - allows`() = runTest { configureInstallationDaysLessThanMaximum() assertTrue(testee.isRecentInstall()) } @Test - fun whenInstalledForSameTimeAsMaxDaysAllowsThenIsRecentInstall() = runTest { + fun `isRecentInstall - installed for same time as max days - recent install`() = runTest { configureInstallationDayToMatchMaximum() assertTrue(testee.isRecentInstall()) } @Test - fun whenInstalledForMoreTimeThanMaxDaysAllowsThenIsRecentInstall() = runTest { + fun `isRecentInstall - installed for more time than max days - 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..57e61f7fd724 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 - correct pixel sent`() { testee.onProtectEmailButtonPressed() verify(pixel).fire(EMAIL_PROTECTION_IN_CONTEXT_PROMPT_CONFIRMED) } @Test - fun whenUserPressesToProtectEmailThenCorrectResultTypeReturned() = runTest { + fun `onProtectEmailButtonPressed - correct result type returned`() = runTest { testee.onProtectEmailButtonPressed() testee.commands.test { assertTrue((awaitItem() as FinishWithResult).result is SignUp) @@ -44,13 +44,13 @@ class EmailProtectionInContextSignUpPromptViewModelTest { } @Test - fun whenUserPressesToDismissPromptThenCorrectPixelSent() { + fun `onCloseButtonPressed - correct pixel sent`() { testee.onCloseButtonPressed() verify(pixel).fire(EMAIL_PROTECTION_IN_CONTEXT_PROMPT_DISMISSED) } @Test - fun whenUserPressesToDismissPromptThenCorrectResultTypeReturned() = runTest { + fun `onCloseButtonPressed - dismiss prompt - correct result type returned`() = runTest { testee.onCloseButtonPressed() testee.commands.test { assertTrue((awaitItem() as FinishWithResult).result is Cancel) @@ -59,13 +59,13 @@ class EmailProtectionInContextSignUpPromptViewModelTest { } @Test - fun whenUserPressesToDismissPromptPermanentlyThenCorrectPixelSent() { + fun `onDoNotShowAgainButtonPressed - correct pixel sent`() { testee.onDoNotShowAgainButtonPressed() verify(pixel).fire(EMAIL_PROTECTION_IN_CONTEXT_PROMPT_NEVER_AGAIN) } @Test - fun whenUserPressesToDismissPromptPermanentlyThenCorrectResultTypeReturned() = runTest { + fun `onDoNotShowAgainButtonPressed - correct result type returned`() = 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..b686dab3f9cf 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 - url does not contain verification link - do not consume link`() { assertFalse(NOT_VERIFICATION_URL.testUrl()) } @Test - fun whenUrlBeginsWithVerificationLinkThenConsumeLink() { + fun `testUrl - url begins with verification link - consume link`() { assertTrue(VERIFICATION_URL.testUrl()) } @Test - fun whenUrlContainsVerificationLinkThenConsumeLink() { + fun `testUrl - url contains verification link - consume link`() { assertTrue(VERIFICATION_PREPENDED_WITH_ANOTHER_DOMAIN.testUrl()) } @Test - fun whenInContextViewNotShowingThenNeverConsumeLink() { + fun `shouldDelegateToInContextView - in context view 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..c08811ac2308 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 - output idna encoded`() { assertEquals("xn--7ca.com", testee.normalizeAscii("ç.com")) } @Test - fun whenNormalizingToAsciiAndOnlyContainsAsciiThenThenInputAndOutputIdentical() { + fun `normalizeAscii - only contains ascii - input and output identical`() { 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 - input and output 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..0ab0bcc476f4 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 - bucket is none`() { assertEquals(NONE, testee.bucketNumberOfSavedPasswords(0)) } @Test - fun whenBetweenOneAndThreeSavedPasswordThenBucketIsFew() { + fun `bucketNumberOfSavedPasswords - between one and three saved passwords - bucket is few`() { assertEquals(FEW, testee.bucketNumberOfSavedPasswords(1)) assertEquals(FEW, testee.bucketNumberOfSavedPasswords(2)) assertEquals(FEW, testee.bucketNumberOfSavedPasswords(3)) } @Test - fun whenBetweenFourAndTenSavedPasswordThenBucketIsSome() { + fun `bucketNumberOfSavedPasswords - between four and ten saved passwords - bucket is some`() { assertEquals(SOME, testee.bucketNumberOfSavedPasswords(4)) assertEquals(SOME, testee.bucketNumberOfSavedPasswords(10)) } @Test - fun whenBetweenElevenAndFortyNineSavedPasswordThenBucketIsMany() { + fun `bucketNumberOfSavedPasswords - between eleven and forty-nine saved passwords - bucket is many`() { assertEquals(MANY, testee.bucketNumberOfSavedPasswords(11)) assertEquals(MANY, testee.bucketNumberOfSavedPasswords(49)) } @Test - fun whenFiftyOrOverThenBucketIsMany() { + fun `bucketNumberOfSavedPasswords - fifty or over - bucket is 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..6f0b5c62743e 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 `recordAutofilledToday - not searched - active user pixel not sent`() = runTest { testee.recordAutofilledToday() AUTOFILL_ENGAGEMENT_ACTIVE_USER.verifyNotSent() } @Test - fun whenSearchedButNotNotAutofilledThenActiveUserPixelNotSent() = runTest { + fun `recordSearchedToday - not autofilled - active user pixel not sent`() = runTest { testee.recordSearchedToday() AUTOFILL_ENGAGEMENT_ACTIVE_USER.verifyNotSent() } @Test - fun whenSearchedAndAutofilledThenActiveUserPixelSent() = runTest { + fun `recordAutofilledToday - searched and autofilled - 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..490de8f95dbb 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 but 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..8990a6986dc8 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 - invalid URL - is 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 - invalid URL - is not internal test user`() { testee.verifyVerificationCompleted(INVALID_TEST_URL) assertFalse(testee.isInternalTestUser) } @Test - fun whenErrorForValidButHttpUrlThenisNotInternalTestUser() { + fun `verifyVerificationErrorReceived - valid but 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 - valid URL - 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 - valid URL - is internal test user`() { testee.verifyVerificationCompleted(VALID_TEST_HTTPS_URL) assertTrue(testee.isInternalTestUser) } @Test - fun whenCompletedForValidButHttpUrlThenisInternalTestUser() { + fun `verifyVerificationCompleted - valid but http url - is internal test user`() { testee.verifyVerificationCompleted(VALID_TEST_HTTP_URL) assertTrue(testee.isInternalTestUser) } @Test - fun whenUserBuildIsInternalNoValidationThenIsInternalTestUser() { + fun `isInternalTestUser - user build is internal - is internal test user`() { whenever(appBuildConfig.flavor).thenReturn(INTERNAL) assertTrue(testee.isInternalTestUser) } @Test - fun whenUserBuildIsInternalAndErrorReceivedWhenValidatingThenIsInternalTestUser() { + fun `verifyVerificationErrorReceived - user build is internal 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..4c132f7aee2b 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 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 - both are null`() = runTest { val parsed = "storeFormData_usernameAndPasswordMissing".parseStoreFormDataJson() assertNull(parsed.credentials!!.username) assertNull(parsed.credentials!!.password) } @Test - fun whenUsernameAndPasswordBothNullThenBothAreNullInParsedObject() = runTest { + fun `parseStoreFormDataJson - username and password 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 - request is empty - 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..c3f07cf4bfed 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 - returns autofill data JSON`() { val expectedJson = "{\n" + " \"success\": {\n" + " \"action\": \"fill\",\n" + @@ -48,7 +48,7 @@ class AutofillJsonResponseWriterTest { } @Test - fun whenGenerateEmptyResponseGetAutofillDataThenReturnEmptyResponseJson() { + fun `generateEmptyResponseGetAutofillData - return 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..73b70d8eb575 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 false`() { whenever(secureStorageKeyProvider.canAccessKeyStore()).thenReturn(false) assertFalse(testee.canProcessData()) } @Test - fun whenDataIsEncryptedThenDelegateEncryptionToEncryptionHelper() { + fun `encrypt - data is 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 is decrypted - delegate 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..ddea6fd2999b 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 - algorithm should be AES`() { assertEquals("AES", testee.generateKey().algorithm) } @Test - fun whenKeyIsGeneratedFromKeyMaterialThenAlgorithmShouldBeAES() { + fun `generateKeyFromKeyMaterial - algorithm is AES`() { val keyMaterial = randomBytes assertEquals("AES", testee.generateKeyFromKeyMaterial(keyMaterial).algorithm) } @Test - fun whenKeyIsGeneratedFromPasswordForSDK26MaterialThenUseDerivedKeySecretFactoryAndAlgorithmShouldBeAES() { + fun `generateKeyFromPassword - SDK 26 - uses derived key secret factory and algorithm is AES`() { 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..25f31c06643e 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 - 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 - return 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 - use 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..f83cb3f0dc56 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 `addWebsiteLoginDetailsWithCredentials - 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 - returns true`() { whenever(l2DataTransformer.canProcessData()).thenReturn(true) assertTrue(testee.canAccessSecureStorage()) } @Test - fun whenCredentialsDeletedThenDeleteEntityWithIdFromSecureStorageRepository() = runTest { + fun `deleteWebsiteLoginDetailsWithCredentials - credentials deleted - delete entity with id from secure storage repository`() = runTest { testee.deleteWebsiteLoginDetailsWithCredentials(1) verify(secureStorageRepository).deleteWebsiteLoginCredentials(1) } @Test - fun whenCredentialsUpdatedThenUpdateEntityInSecureStorageRepository() = runTest { + fun `updateWebsiteLoginDetailsWithCredentials - credentials updated - update entity in secure storage repository`() = runTest { testee.updateWebsiteLoginDetailsWithCredentials(testCredentials) verify(secureStorageRepository).updateWebsiteLoginCredentials(testEntity) } @Test - fun whenGetCredentialsWIthIdThenGetEntityWithIdFromSecureStorageRepository() = runTest { + fun `getWebsiteLoginDetailsWithCredentials - get credentials with id - get 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 - 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 - returns including decrypted password`() = runTest { whenever(secureStorageRepository.websiteLoginCredentials()).thenReturn( MutableStateFlow(listOf(testEntity)), ) @@ -163,7 +163,7 @@ class RealSecureStorageTest { } @Test - fun whenWebsiteLoginCredentialsForDomainRequestedThenGetEntityForDomainAndReturnIncludingDecryptedPassword() = runTest { + fun `websiteLoginDetailsWithCredentialsForDomain - get entity for domain - return including decrypted password`() = runTest { whenever(secureStorageRepository.websiteLoginCredentialsForDomain("test.com")).thenReturn( MutableStateFlow(listOf(testEntity)), ) @@ -174,14 +174,14 @@ class RealSecureStorageTest { } @Test - fun whenNoSecureStorageRepositoryThenCanAccessSecureStorageFalse() { + fun `canAccessSecureStorage - no secure storage repository - false`() { setUpNoSecureStorageRepository() assertFalse(testee.canAccessSecureStorage()) } @Test - fun whenNoSecureStorageRepositoryAddCredentialsThenDoNothing() = runTest { + fun `addWebsiteLoginDetailsWithCredentials - 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 `updateWebsiteLoginDetailsWithCredentials - no secure storage repository - do nothing`() = runTest { setUpNoSecureStorageRepository() testee.updateWebsiteLoginDetailsWithCredentials(testCredentials) @@ -206,7 +206,7 @@ class RealSecureStorageTest { } @Test - fun whenNoSecureStorageRepositoryDeleteCredentialsThenDoNothing() = runTest { + fun `deleteWebsiteLoginDetailsWithCredentials - 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 `websiteLoginDetailsWithCredentialsForDomain - 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 - mass deleting credentials - bulk deletion function 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..951514c23f15 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 shareable 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 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 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..c771db2da122 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 is corrupt - 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..67601d674f6e 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 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 from 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 - multiple sites in unidirectional list - all returned`() = runTest { val config = config( unidirectionalRules = listOf( unidirectionalRule( @@ -169,7 +169,7 @@ class RealShareableCredentialsUrlGeneratorTest { } @Test - fun whenMatchesFromOmnidirectionalAndUnidirectionalThenReturnedOnce() = runTest { + fun `generateShareableUrls - matches from omnidirectional and unidirectional - 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 - 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..96ab0ec5a5b2 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 - eTld+1 is used`() = runTest { testee.addToNeverSaveList("foo.example.com") verify(secureStorage).addToNeverSaveList("example.com") } @Test - fun whenDomainAddedToNeverSaveListContainsQueryParamsThenOnlyETldPlus1IsUsed() = runTest { + fun `addToNeverSaveList - domain with query params - only eTld+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..51865a60d43b 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 - viewState 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 - correct pixel fired`() { testee.onEnableAutofill() verify(pixel).fire(AUTOFILL_ENABLE_AUTOFILL_TOGGLE_MANUALLY_ENABLED) } @Test - fun whenUserDisablesAutofillThenCorrectPixelFired() { + fun `onDisableAutofill - correct 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 - viewed credentials - store deletion called`() = runTest { val credentials = someCredentials() testee.onDeleteCredentials(credentials) verify(mockStore).deleteCredentials(credentials.id!!) } @Test - fun whenUserDeletesViewedCredentialsLaunchedDirectlyThenCredentialsDeleted() = runTest { + fun `onDeleteCredentials - 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 - called from list - show credential viewing mode`() = runTest { val credentials = someCredentials() testee.onViewCredentials(credentials) @@ -205,7 +205,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenOnViewCredentialsCalledFirstThenShowCredentialViewingMode() = runTest { + fun `onViewCredentials - first call - show credential viewing mode`() = runTest { val credentials = someCredentials() testee.onViewCredentials(credentials) @@ -220,7 +220,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenOnViewCredentialsCalledWithWebsiteThenShowLinkButton() = runTest { + fun `onViewCredentials - called with 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 - without 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 - show credential editing mode`() = runTest { val credentials = someCredentials() testee.onViewCredentials(credentials) testee.onEditCurrentCredentials() @@ -267,7 +267,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenOnEditCredentialsCalledDirectlyThenShowCredentialEditingMode() = runTest { + fun `onEditCredentials - 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 - viewState 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 - called more than once - 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 `saveOrUpdateCredentials - update credentials called - update autofill store`() = runTest { val credentials = someCredentials() testee.onEditCredentials(credentials) @@ -382,7 +382,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenUpdateCredentialsCalledFromManualCreationThenSaveAutofillStore() = runTest { + fun `saveOrUpdateCredentials - called from manual creation - save autofill store`() = runTest { val credentials = someCredentials() testee.onCreateNewCredentials() testee.saveOrUpdateCredentials(credentials) @@ -390,7 +390,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenOnExitEditModeThenUpdateCredentialModeStateToViewing() = runTest { + fun `onCancelEditMode - update credential mode state to viewing`() = runTest { val credentials = someCredentials() testee.onViewCredentials(credentials) testee.onEditCurrentCredentials() @@ -404,7 +404,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenOnExitEditModeButNotFromViewThenExitCredentialMode() = runTest { + fun `onCancelEditMode - not from view - 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 `unlock - was list mode - previous viewState restored`() = runTest { testee.onInitialiseListMode() testee.lock() testee.unlock() @@ -439,7 +439,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenLockingAndUnlockingPreviousViewStateRestoredIfWasCredentialViewingMode() = runTest { + fun `unlock - was credential viewing mode - previous view state restored`() = runTest { testee.onViewCredentials(someCredentials()) testee.lock() testee.unlock() @@ -451,7 +451,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenInEditModeAndChangedToDisabledThenUpdateNotInCredentialModeAndShowDisabledMode() = runTest { + fun `disabled - in edit mode - 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 `allowSaveInEditMode - set to false - update viewState to 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 - update state to is authenticating - 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 twice - 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 `onViewCreated - autofill disabled - autofill enabled state returned`() = runTest { whenever(mockStore.autofillEnabled).thenReturn(false) configureDeviceToHaveValidAuthentication(true) @@ -585,7 +585,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenObserveCredentialsCalledWithAutofillEnabledThenAutofillEnabledStateIsReturned() = runTest { + fun `onViewCreated - autofill enabled - autofill enabled state returned`() = runTest { whenever(mockStore.autofillEnabled).thenReturn(true) configureDeviceToHaveValidAuthentication(true) @@ -597,7 +597,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenSearchQueryChangesEmptyThenShouldShowEnableToggle() = runTest { + fun `onSearchQueryChanged - empty query - show enable toggle`() = runTest { testee.onSearchQueryChanged("") testee.onViewCreated() @@ -608,7 +608,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenSearchQueryChangesNonEmptyThenShouldNotShowEnableToggle() = runTest { + fun `onSearchQueryChanged - non-empty query - should not show enable toggle`() = runTest { testee.onSearchQueryChanged("foo") testee.onViewCreated() @@ -619,7 +619,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenScreenLaunchedDirectlyIntoCredentialViewThenNoLaunchPixelSent() { + fun `sendLaunchPixel - launched directly into credential view - 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 from browser and direct link to credentials - 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 - launched from browser and 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 `onResetNeverSavedSitesInitialSelection - 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 - 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 `onDeleteAllPasswordsInitialSelection - one saved login - show 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 - passwords saved - issue command to show undo snackbar`() = runTest { testee.onDeleteAllPasswordsConfirmed() testee.commandsListView.test { awaitItem().verifyHasCommandToAuthenticateMassDeletion() @@ -716,7 +716,7 @@ class AutofillSettingsViewModelTest { } @Test - fun whenAuthenticationSucceedsToMassDeletePasswordsThenDoesIssueCommandToShowUndoSnackbar() = runTest { + fun `onAuthenticatedToDeleteAllPasswords - authentication succeeds - issues 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 `onDeleteAllPasswordsInitialSelection - many saved logins - show confirmation dialog`() = runTest { configureStoreToHaveThisManyCredentialsStored(100) testee.onViewCreated() testee.onDeleteAllPasswordsInitialSelection() @@ -737,38 +737,38 @@ class AutofillSettingsViewModelTest { } @Test - fun whenNoSurveysAvailableThenNoSurveyInViewState() = runTest { + fun `onViewStarted - no surveys available - no survey in viewState`() = runTest { testee.onViewStarted() verifySurveyNotAvailable() } @Test - fun whenUnusedSurveyAvailableThenSurveyInViewState() = runTest { + fun `onInitialiseListMode - unused survey available - survey in viewState`() = runTest { whenever(autofillSurvey.firstUnusedSurvey()).thenReturn(SurveyDetails("surveyId-1", "example.com")) testee.onInitialiseListMode() "surveyId-1".verifySurveyAvailable() } @Test - fun whenSurveyShownThenNoSurveyInViewState() = runTest { + fun `onSurveyShown - no survey in viewState`() = 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 - no survey in viewState`() = 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..e61aa48df7e4 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 - only 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 with 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 can be deconstructed - do not get their 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`() { val credentials = listOf( creds(title = "😅"), ) @@ -177,7 +177,7 @@ class CredentialGrouperTest { } @Test - fun whenNumberThenGroupedIntoPlaceholder() { + fun `group - number - grouped into placeholder`() { val credentials = listOf( creds(title = "8"), creds(title = "5"), @@ -193,7 +193,7 @@ class CredentialGrouperTest { } @Test - fun whenListMixtureOfAccentedCharactersThenAccentedCharactersDoNotGetTheirOwnGroups() { + fun `group - list with accented characters - accented characters do not get their own groups`() { 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..8d4d14917028 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 - placeholder char`() { val result = testee.extractInitial(creds(title = null, domain = null)) result.assertIsPlaceholder() } @Test - fun whenEmptyStringTitleAndEmptyStringDomainThenPlaceholderChar() { + fun `extractInitial - empty string title and domain - placeholder char`() { val result = testee.extractInitial(creds(title = "", domain = "")) result.assertIsPlaceholder() } @Test - fun whenMissingTitleThenDomainInitialUsed() { + fun `extractInitial - missing title - domain initial used`() { val loginCredentials = creds(title = null, domain = "example.com") val result = testee.extractInitial(loginCredentials) assertEquals("E", result) } @Test - fun whenTitleIsPresentThenTitleInitialIsUsedAndDomainIsIgnored() { + fun `extractInitial - title is present - title initial is used and domain is 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 - placeholder used`() { val loginCredentials = creds(title = "123 website") testee.extractInitial(loginCredentials).assertIsPlaceholder() } @Test - fun whenTitleStartsWithASpecialCharacterThenPlaceholderUsed() { + fun `extractInitial - title starts with special character - placeholder used`() { val loginCredentials = creds(title = "$123 website") testee.extractInitial(loginCredentials).assertIsPlaceholder() } @Test - fun whenTitleStartsWithANonLatinLetterThatCannotBeDecomposedThenOriginalLetterIsUsed() { + fun `extractInitial - title starts with non-Latin letter - original letter used`() { val loginCredentials = creds(title = "ß website") assertEquals("ß", testee.extractInitial(loginCredentials)) } @Test - fun whenDomainStartsWithANonLatinLetterThatCannotBeDecomposedThenOriginalLetterIsUsed() { + fun `extractInitial - domain starts with non-Latin letter - original letter used`() { val loginCredentials = creds(title = "ß.com") assertEquals("ß", testee.extractInitial(loginCredentials)) } @Test - fun whenTitleStartsWithAnAccentedLetterThenThatBaseLetterIsUsed() { + fun `extractInitial - title starts with accented letter - base letter is used`() { val loginCredentials = creds(title = "Ça va website") assertEquals("C", testee.extractInitial(loginCredentials)) } @Test - fun whenDomainStartsWithAnAccentedLetterThenThatBaseLetterIsUsed() { + fun `extractInitial - domain starts with accented letter - base letter is used`() { 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 - non-Latin letter used`() { val loginCredentials = creds(title = "あ") assertEquals("あ", testee.extractInitial(loginCredentials)) } @Test - fun whenSubdomainIsPresentThenNotUsedForInitialExtraction() { + fun `extractInitial - subdomain present - not used`() { 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..982992f6eded 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 is empty - return empty list`() { val result = testee.sort(emptyList()) assertTrue(result.isEmpty()) } @Test - fun whenComparingTitlesCaseIsIgnored() { + fun `sort - comparing titles - case is ignored`() { val sorted = testee.sort( list.also { it.add(credsWithTitle("C")) @@ -54,7 +54,7 @@ class CredentialListSorterTest { } @Test - fun whenComparingDomainsCaseIsIgnored() { + fun `sort - domains case ignored`() { val sorted = testee.sort( list.also { it.add(credsWithDomain("C.COM")) @@ -66,7 +66,7 @@ class CredentialListSorterTest { } @Test - fun whenComparingSubdomainsCaseIsIgnored() { + fun `sort - subdomains case ignored`() { val sorted = testee.sort( list.also { it.add(credsWithDomain("C.example.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 - 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 - subdomains - www not treated as special`() { 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 - invalid domain initial - used 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 - correct sorting`() { 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 - correct order`() { val sorted = testee.sort( list.also { it.add(credsWithDomain("a")) @@ -284,7 +284,7 @@ class CredentialListSorterTest { } @Test - fun whenComparingSubdomainsWithSitesFromSameDomainWithoutSubdomainThenTopSiteSortedFirst() { + fun `sort - subdomains with 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 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..1aa3b77737aa 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 - empty string - not classed as url`() { assertFalse(testee.isLikelyAUrl("")) } @Test - fun whenUrlIsBlankStringThenNotClassedAsUrl() { + fun `isLikelyAUrl - blank string - not classed as url`() { assertFalse(testee.isLikelyAUrl(" ")) } @Test - fun whenUrlIsAnIpAddressThenIsClassedAsUrl() { + fun `isLikelyAUrl - IP address - classed as URL`() { assertTrue(testee.isLikelyAUrl("192.168.1.100")) } @Test - fun whenUrlIsSimpleUrlThenIsClassedAsUrl() { + fun `isLikelyAUrl - simple URL - classed as URL`() { assertTrue(testee.isLikelyAUrl("example.com")) } @Test - fun whenUrlHasPortThenIsClassedAsUrl() { + fun `isLikelyAUrl - url has port - is classed 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..8189d3a9f67d 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 - matches credential`() { 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 - matches credential`() { 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..4793c74002a1 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 empty query - empty list returned`() = 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 with query - 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..03a75da69852 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 is 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..24773399be35 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 - 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 - 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 - 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 in 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 differs - 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 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..d1d0c41f2aee 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 - survey not shown before - returns 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 - locale not English and survey not shown - does not return survey`() = 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 shown before - does not return`() = runTest { whenever(autofillSurveyStore.hasSurveyBeenTaken("autofill-2024-04-26")).thenReturn(true) assertNull(testee.firstUnusedSurvey()) } @Test - fun whenSurveyRecordedAsUsedThenPersisted() = runTest { + fun `recordSurveyAsUsed - survey recorded as used - persisted`() = runTest { testee.recordSurveyAsUsed("surveyId-1") verify(autofillSurveyStore).recordSurveyWasShown("surveyId-1") } @Test - fun whenSavedPasswordsLowestInNoneBucketThenCorrectQueryParamValueAdded() = runTest { + fun `savedPasswordsLowestInNoneBucket - 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 `savedPasswordsHighestInSomeBucket - 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 `savedPasswordsLowestInManyBucket - 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 `savedPasswordsLowestInLotsBucket - 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 `savedPasswordsIsExtremelyLarge - 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..d260d8e77d15 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 `hasSurveyBeenTaken - another survey id recorded - returns false`() = runTest { testee.recordSurveyWasShown("surveyId-1") assertFalse(testee.hasSurveyBeenTaken("surveyId-2")) } @Test - fun whenSurveyRecordedBeforeThenReturnsTrue() = runTest { + fun `hasSurveyBeenTaken - survey recorded before - returns true`() = runTest { testee.recordSurveyWasShown("surveyId-1") assertTrue(testee.hasSurveyBeenTaken("surveyId-1")) } @Test - fun whenMultipleSurveysRecordedAndQueriedOneInListThenReturnsTrue() = runTest { + fun `hasSurveyBeenTaken - multiple surveys recorded - 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..8ce6cf58bd85 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 - 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 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 - main address missing suffix - not a private address`() { assertFalse(testee.isPrivateDuckAddress("test@duck.com", MAIN_ADDRESS)) } @Test - fun whenInputHasDifferentDuckAddressFromMainAddressThenIsAPrivateAddress() { + fun `isPrivateDuckAddress - different 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..71be05a225fe 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 - value set - returned from get function`() { val loginId: Long = 1 val tabId = "abc" testee.setAutoSavedLoginId(loginId, tabId) @@ -31,7 +31,7 @@ class InMemoryAutoSavedLoginsMonitorTest { } @Test - fun whenValueSetThenClearedThenNotReturnedFromGetFunction() { + fun `getAutoSavedLoginId - value set then cleared - not returned`() { 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..9030866510eb 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 autogenerated 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 autogenerated 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 autogenerated - 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..12cb3052c1f6 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 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 - accepted to use password no auto login - 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 - 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 - 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 - 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 - auto login id 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 - 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 - 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 - 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..947a4619dbe4 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 is 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 is activated - activated`() = runTest { configureEmailProtectionSignedIn() configureNetworkResponseActivatedIsTrue() val status = testee.getActivationStatus("foo@example.com") @@ -68,7 +68,7 @@ class RemoteDuckAddressStatusRepositoryTest { } @Test - fun whenStatusRequestFailsGeneralErrorActivatedThenReturnTypeIsError() = runTest { + fun `getActivationStatus - request fails with general error - 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,27 +84,27 @@ class RemoteDuckAddressStatusRepositoryTest { } @Test - fun whenNotSignedAndTryingToUpdateStatusThenReturnFalse() = runTest { + fun `setActivationStatus - email protection not signed in - return false`() = runTest { configureEmailProtectionNotSignedIn() assertFalse(testee.setActivationStatus("foo@example.com", true)) } @Test - fun whenUpdatingStatusToActivatedAndNewUpdateMatchesThenReturnTrue() = runTest { + fun `setActivationStatus - status activated and matches - return true`() = runTest { configureEmailProtectionSignedIn() configureNetworkResponseAfterSettingStatusToBeActivated() assertTrue(testee.setActivationStatus("foo@example.com", true)) } @Test - fun whenUpdatingStatusToActivatedAndNewUpdateDoesNotMatchThenReturnFalse() = runTest { + fun `setActivationStatus - new update does not match - return false`() = runTest { configureEmailProtectionSignedIn() configureNetworkResponseAfterSettingStatusToBeDeactivated() assertFalse(testee.setActivationStatus("foo@example.com", true)) } @Test - fun whenUpdatingStatusToDeactivatedAndNewUpdateMatchesThenReturnTrue() = runTest { + fun `setActivationStatus - new update matches deactivated - return true`() = runTest { configureEmailProtectionSignedIn() configureNetworkResponseAfterSettingStatusToBeDeactivated() assertTrue(testee.setActivationStatus("foo@example.com", false)) @@ -118,7 +118,7 @@ class RemoteDuckAddressStatusRepositoryTest { } @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..e19f0b971d25 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 `userPromptedToSaveCredentials - flag set`() = 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..679681632dbb 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 `savingAcceptedWithUsernameAndPassword - correct pixel used`() { assertEquals(pixelNameDialogAccepted(UsernameAndPassword), AUTOFILL_SAVE_LOGIN_PROMPT_SAVED) } @Test - fun whenSavingAcceptedWithPasswordOnlyThenCorrectPixelUsed() { + fun `savingAcceptedWithPasswordOnly - correct pixel used`() { assertEquals(pixelNameDialogAccepted(PasswordOnly), AUTOFILL_SAVE_PASSWORD_PROMPT_SAVED) } @Test - fun whenDialogShownWithUsernameAndPasswordThenCorrectPixelUsed() { + fun `pixelNameDialogShown - username and password - correct pixel used`() { assertEquals(pixelNameDialogShown(UsernameAndPassword), AUTOFILL_SAVE_LOGIN_PROMPT_SHOWN) } @Test - fun whenDialogShownWithPasswordOnlyThenCorrectPixelUsed() { + fun `pixelNameDialogShown - password only - correct pixel used`() { assertEquals(pixelNameDialogShown(PasswordOnly), AUTOFILL_SAVE_PASSWORD_PROMPT_SHOWN) } @Test - fun whenDialogDismissedWithUsernameAndPasswordThenCorrectPixelUsed() { + fun `pixelNameDialogDismissed - username and password - correct pixel used`() { assertEquals(pixelNameDialogDismissed(UsernameAndPassword), AUTOFILL_SAVE_LOGIN_PROMPT_DISMISSED) } @Test - fun whenDialogDismissedWithPasswordOnlyThenCorrectPixelUsed() { + fun `pixelNameDialogDismissed - password only - correct pixel used`() { assertEquals(pixelNameDialogDismissed(PasswordOnly), AUTOFILL_SAVE_PASSWORD_PROMPT_DISMISSED) } @Test - fun whenUsernameAndPasswordProvidedThenSaveTypeIsUsernameAndPassword() { + fun `saveType - 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..80cd3495bfe7 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..7827d32ecba0 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 - 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 - 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 are 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..9e71c8e71b3f 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 `userDeclinedToSaveCredentials - 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 `userDeclinedToSaveCredentials - monitoring decline counts - records new declines`() = runTest { whenever(autofillStore.monitorDeclineCounts).thenReturn(true) initialiseDeclineCounter() @@ -74,7 +74,7 @@ class AutofillDisablingDeclineCounterTest { } @Test - fun whenNewDomainMatchesOldDomainThenDeclineNotRecorded() = runTest { + fun `userDeclinedToSaveCredentials - new 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 - new domain does not match old domain - decline recorded`() = runTest { initialiseDeclineCounter() testee.currentSessionPreviousDeclinedDomain = "foo.com" testee.userDeclinedToSaveCredentials("example.com") @@ -90,7 +90,7 @@ class AutofillDisablingDeclineCounterTest { } @Test - fun whenDeclineOnNewDomainWithNoPreviousDomainThenDomainStored() = runTest { + fun `userDeclinedToSaveCredentials - no previous domain - domain stored`() = runTest { initialiseDeclineCounter() testee.currentSessionPreviousDeclinedDomain = null testee.userDeclinedToSaveCredentials("example.com") @@ -98,7 +98,7 @@ class AutofillDisablingDeclineCounterTest { } @Test - fun whenDeclineOnNewDomainWithAPreviousDomainThenDomainStored() = runTest { + fun `userDeclinedToSaveCredentials - decline on new domain with previous domain - domain stored`() = runTest { initialiseDeclineCounter() testee.currentSessionPreviousDeclinedDomain = "foo.com" testee.userDeclinedToSaveCredentials("example.com") @@ -106,7 +106,7 @@ class AutofillDisablingDeclineCounterTest { } @Test - fun whenDeclineTotalCountBelowThresholdThenShouldNotOfferToDisable() = runTest { + fun `userDeclinedToSaveCredentials - decline count below threshold - should not offer to disable`() = runTest { initialiseDeclineCounter() whenever(autofillStore.autofillDeclineCount).thenReturn(0) testee.userDeclinedToSaveCredentials("example.com") @@ -114,7 +114,7 @@ class AutofillDisablingDeclineCounterTest { } @Test - fun whenDeclineIncreasesTotalCountAtThresholdThenShouldOfferToDisable() = runTest { + fun `userDeclinedToSaveCredentials - decline count at threshold - should offer to disable`() = runTest { initialiseDeclineCounter() configureGlobalDeclineCountAtThreshold() testee.userDeclinedToSaveCredentials("a.com") @@ -122,7 +122,7 @@ class AutofillDisablingDeclineCounterTest { } @Test - fun whenCounterNotActiveThenShouldNeverPromptToDisableAutofill() = runTest { + fun `shouldPromptToDisableAutofill - counter not active - never prompts`() = 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..eadfd52ab955 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 - domain used in string`() { val result = testee.usernameOrPlaceholder(missingUsername()) assertEquals("Password for example.com", result) } @Test - fun whenMissingUsernameAndMissingDomainThenPlaceholderUsedString() { + fun `usernameOrPlaceholder - missing username and domain - placeholder used`() { 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..90de9e40a804 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 are 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 - login1 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 - login2 timestamp lower - sorted before other login`() { val login1 = aLogin(lastUpdatedTimestamp = 2) val login2 = aLogin(lastUpdatedTimestamp = 1) val result = testee.compare(login1, login2) @@ -49,7 +49,7 @@ class LastUpdatedCredentialSorterTest { } @Test - fun whenLogin2IsMissingATimestampThenSortedBeforeOtherLogin() { + fun `compare - login missing timestamp - sorted before other login`() { val login1 = aLogin(lastUpdatedTimestamp = 1) val login2 = aLogin(lastUpdatedTimestamp = null) val result = testee.compare(login1, login2) @@ -57,21 +57,21 @@ class LastUpdatedCredentialSorterTest { } @Test - fun whenLogin1IsNullThenSortedBeforeOtherLogin() { + fun `compare - login1 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 - login2 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 are null - treated as 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..c66bb5a32603 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 are 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 - login1 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 - login2 timestamp is lower - sorted before other login`() { val login1 = aLogin(lastUsedTimestamp = 2) val login2 = aLogin(lastUsedTimestamp = 1) val result = testee.compare(login1, login2) @@ -49,7 +49,7 @@ class LastUsedCredentialSorterTest { } @Test - fun whenLogin2IsMissingATimestampThenSortedBeforeOtherLogin() { + fun `compare - login missing timestamp - sorted before other login`() { val login1 = aLogin(lastUsedTimestamp = 1) val login2 = aLogin(lastUsedTimestamp = null) val result = testee.compare(login1, login2) @@ -57,21 +57,21 @@ class LastUsedCredentialSorterTest { } @Test - fun whenLogin1IsNullThenSortedBeforeOtherLogin() { + fun `compare - login1 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 - login2 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 are null - treated as 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..d41073d576cf 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 - 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 - 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 - 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 - 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..be78f435cfed 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 - perfect match and 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 - button is primary type`() { 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 - 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 - list output 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..b19b0ceafb56 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 and 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 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 - authentication fails - correct callback invoked`() = 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 - missing credentials 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..a12e073f49e4 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 - short username - no ellipsizing`() { val result = testee.ellipsizeIfNecessary("foo") result.assertDoesNotEndInEllipsis() assertEquals("foo", result) } @Test - fun whenUsernameIsExactlyOnLimitThenNoEllipsizing() { + fun `ellipsizeIfNecessary - username exactly on 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 - ellipsizing`() { 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..3169d766e4e7 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 `processResult - 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 `processResult - 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 are 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..749b27c39d3f 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 eTldPlus1`() { val inputUrl = "duckduckgo.com" val result = testee.extractUrlPartsForAutofill(inputUrl) assertEquals(inputUrl, result.eTldPlus1) } @Test - fun whenUrlIsInvalidMissingTldThenEtldPlusOneIsNull() { + fun `extractUrlPartsForAutofill - invalid URL missing TLD - eTldPlus1 is null`() { val inputUrl = "duckduckgo" val result = testee.extractUrlPartsForAutofill(inputUrl) assertNull(result.eTldPlus1) } @Test - fun whenUrlIsInvalidMissingTldThenSubdomainIsNull() { + fun `extractUrlPartsForAutofill - invalid URL missing TLD - subdomain is null`() { val inputUrl = "duckduckgo" val result = testee.extractUrlPartsForAutofill(inputUrl) assertNull(result.subdomain) } @Test - fun whenContainsHttpSchemeThenEtldPlus1Returned() { + fun `extractUrlPartsForAutofill - contains http scheme - eTldPlus1 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 - eTldPlus1 returned`() { val inputUrl = "www.duckduckgo.com" val result = testee.extractUrlPartsForAutofill(inputUrl) assertEquals("duckduckgo.com", result.eTldPlus1) } @Test - fun whenContainsAnotherSubdomainThenEtldPlus1Returned() { + fun `extractUrlPartsForAutofill - contains another subdomain - eTldPlus1 returned`() { val inputUrl = "foo.duckduckgo.com" val result = testee.extractUrlPartsForAutofill(inputUrl) assertEquals("duckduckgo.com", result.eTldPlus1) } @Test - fun whenTwoPartTldWithNoSubdomainThenEtldPlus1Returned() { + fun `extractUrlPartsForAutofill - two-part TLD with no subdomain - eTldPlus1 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 - eTldPlus1 returned`() { val inputUrl = "www.duckduckgo.co.uk" val result = testee.extractUrlPartsForAutofill(inputUrl) assertEquals("duckduckgo.co.uk", result.eTldPlus1) } @Test - fun whenSubdomainIsWwwThenCorrectlyIdentifiedAsSubdomain() { + fun `extractUrlPartsForAutofill - subdomain is www - correctly identified`() { 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 with two levels - correctly identified`() { val inputUrl = "foo.bar.duckduckgo.co.uk" val result = testee.extractUrlPartsForAutofill(inputUrl) assertEquals("foo.bar", result.subdomain) } @Test - fun whenUrlsAreIdenticalThenMatchingForAutofill() { + fun `matchingForAutofill - identical URLs`() { val savedSite = testee.extractUrlPartsForAutofill("https://example.com") val visitedSite = testee.extractUrlPartsForAutofill("https://example.com") assertTrue(testee.matchingForAutofill(visitedSite, savedSite)) } @Test - fun whenUrlsAreIdenticalExceptForUppercaseVisitedSiteThenMatchingForAutofill() { + fun `matchingForAutofill - identical URLs except for uppercase - matching`() { val savedSite = testee.extractUrlPartsForAutofill("https://example.com") val visitedSite = testee.extractUrlPartsForAutofill("https://EXAMPLE.com") assertTrue(testee.matchingForAutofill(visitedSite, savedSite)) @@ -137,126 +137,126 @@ class AutofillDomainNameUrlMatcherTest { } @Test - fun whenBothUrlsContainSameSubdomainThenMatchingForAutofill() { + fun `matchingForAutofill - same subdomain - matching`() { val savedSite = testee.extractUrlPartsForAutofill("test.example.com") val visitedSite = testee.extractUrlPartsForAutofill("test.example.com") assertTrue(testee.matchingForAutofill(visitedSite, savedSite)) } @Test - fun whenBothUrlsContainWwwSubdomainThenMatchingForAutofill() { + fun `matchingForAutofill - both URLs contain www subdomain`() { val savedSite = testee.extractUrlPartsForAutofill("www.example.com") val visitedSite = testee.extractUrlPartsForAutofill("www.example.com") assertTrue(testee.matchingForAutofill(visitedSite, savedSite)) } @Test - fun whenSavedSiteContainsSubdomainAndVisitedSiteDoesNotThenMatchingForAutofill() { + fun `matchingForAutofill - saved site contains subdomain and visited site does not`() { val savedSite = testee.extractUrlPartsForAutofill("foo.example.com") val visitedSite = testee.extractUrlPartsForAutofill("example.com") assertTrue(testee.matchingForAutofill(visitedSite, savedSite)) } @Test - fun whenSavedSiteDoesNotContainSubdomainAndVisitedSiteDoesThenMatchingForAutofill() { + fun `matchingForAutofill - saved site does not contain subdomain and visited site does`() { val savedSite = testee.extractUrlPartsForAutofill("example.com") val visitedSite = testee.extractUrlPartsForAutofill("foo.example.com") assertTrue(testee.matchingForAutofill(visitedSite, savedSite)) } @Test - fun whenUrlsHaveDifferentSubdomainsThenMatchingForAutofill() { + fun `matchingForAutofill - different subdomains - matching`() { val savedSite = testee.extractUrlPartsForAutofill("bar.example.com") val visitedSite = testee.extractUrlPartsForAutofill("foo.example.com") assertTrue(testee.matchingForAutofill(visitedSite, savedSite)) } @Test - fun whenSavedSiteContainsWwwSubdomainAndVisitedSiteDoesNotThenMatchingForAutofill() { + fun `matchingForAutofill - saved site contains www subdomain and visited site does not`() { val savedSite = testee.extractUrlPartsForAutofill("www.example.com") val visitedSite = testee.extractUrlPartsForAutofill("example.com") assertTrue(testee.matchingForAutofill(visitedSite, savedSite)) } @Test - fun whenSavedSiteMatchesVisitedExceptForPortThenNotMatchingForAutofill() { + fun `matchingForAutofill - saved site matches visited except for port - not matching`() { 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`() { 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`() { 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 - visited site missing port - not matching`() { 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 `matchingForAutofill - saved site contains uppercase www subdomain and visited site does not`() { val savedSite = testee.extractUrlPartsForAutofill("WWW.example.com") val visitedSite = testee.extractUrlPartsForAutofill("example.com") assertTrue(testee.matchingForAutofill(visitedSite, savedSite)) } @Test - fun whenSavedSiteDoesNotContainSubdomainAndVisitedSiteDoesContainWwwSubdomainThenMatchingForAutofill() { + fun `matchingForAutofill - saved site without subdomain and visited site with www subdomain - matches`() { val savedSite = testee.extractUrlPartsForAutofill("example.com") val visitedSite = testee.extractUrlPartsForAutofill("www.example.com") assertTrue(testee.matchingForAutofill(visitedSite, savedSite)) } @Test - fun whenSavedSiteDoesNotContainSubdomainAndVisitedSiteDoesContainUppercaseWwwSubdomainThenMatchingForAutofill() { + fun `matchingForAutofill - saved site without subdomain and visited site with uppercase www subdomain - matches`() { val savedSite = testee.extractUrlPartsForAutofill("example.com") val visitedSite = testee.extractUrlPartsForAutofill("WWW.example.com") assertTrue(testee.matchingForAutofill(visitedSite, savedSite)) } @Test - fun whenSavedSiteContainNestedSubdomainsAndVisitedSiteContainsMatchingRootSubdomainThenMatchingForAutofill() { + fun `matchingForAutofill - nested subdomains - matching`() { val savedSite = testee.extractUrlPartsForAutofill("a.b.example.com") val visitedSite = testee.extractUrlPartsForAutofill("b.example.com") assertTrue(testee.matchingForAutofill(visitedSite, savedSite)) } @Test - fun whenSavedSiteContainSubdomainAndVisitedSiteContainsNestedSubdomainsThenMatchingForAutofill() { + fun `matchingForAutofill - saved site contains subdomain and visited site contains nested subdomains`() { val savedSite = testee.extractUrlPartsForAutofill("b.example.com") val visitedSite = testee.extractUrlPartsForAutofill("a.b.example.com") assertTrue(testee.matchingForAutofill(visitedSite, savedSite)) } @Test - fun whenSavedSiteHasNoSubdomainAndVisitedMaliciousSitePartiallyContainSavedSiteThenNoMatchingForAutofill() { + fun `savedSiteHasNoSubdomainAndVisitedSitePartiallyContainsSavedSite - 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 `matchingForAutofill - saved malicious site partially contains visited site - no matching`() { 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 - eTldPlus1 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..d87a32050d13 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 `isEnabled - manually set to enabled - default state decider not used`() { testee.isEnabled = true testee.isEnabled verify(defaultStateDecider, never()).defaultState() } @Test - fun whenAutofillStateWasManuallySetToDisabledThenDefaultStateDeciderNotUsed() { + fun `isEnabled - manually set to disabled - default state decider not used`() { testee.isEnabled = false testee.isEnabled verify(defaultStateDecider, never()).defaultState() } @Test - fun whenDeterminedEnabledByDefaultOnceThenNotDecidedAgain() { + fun `isEnabled - determined enabled by default once - not decided again`() { // 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 `isEnabled - not enabled by default once - calls 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..740214f32a72 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 `defaultState - remote feature disabled - number of days installed irrelevant`() { configureRemoteFeatureEnabled(false) configureDaysInstalled(0) @@ -31,7 +31,7 @@ class RealAutofillDefaultStateDeciderTest { } @Test - fun whenNumberOfDaysInstalledIsNotZeroThenFeatureFlagIsIrrelevant() { + fun `defaultState - number of days installed is not zero - feature flag is irrelevant`() { configureDaysInstalled(0) configureRemoteFeatureEnabled(false) @@ -42,7 +42,7 @@ class RealAutofillDefaultStateDeciderTest { } @Test - fun whenInternalTesterThenAlwaysEnabledByDefault() { + fun `defaultState - internal tester - always enabled by default`() { 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..f40896ac3b85 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 - false`() { assertFalse(credentialsSyncStore.isSyncPaused) } @Test - fun whenSyncPausedAndOnSuccessWithChangesThenIsSyncPausedIsFalse() { + fun `onSuccess - sync paused with changes - isSyncPaused is 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 without changes - sync paused`() { credentialsSyncStore.isSyncPaused = true val validChanges = SyncChangesResponse.empty(BOOKMARKS) @@ -81,7 +81,7 @@ class AppCredentialsSyncFeatureListenerTest { } @Test - fun whenSyncPausedAndOnErrorThenSyncPaused() { + fun `onError - sync paused and collection limit reached - sync paused`() { credentialsSyncStore.isSyncPaused = true testee.onError(FeatureSyncError.COLLECTION_LIMIT_REACHED) @@ -90,7 +90,7 @@ class AppCredentialsSyncFeatureListenerTest { } @Test - fun whenSyncActiveAndOnErrorThenSyncPaused() { + fun `onError - sync active - 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..b3de15ffa425 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 - invalid credentials - 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..327cb03fb9dc 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 - corrupted data - result is 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 - result is 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 - result is 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 - result is 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 - persist with another type - return false`() { val result = syncPersister.onSuccess( SyncChangesResponse(BOOKMARKS, ""), DEDUPLICATION, @@ -137,7 +137,7 @@ internal class CredentialsSyncDataPersisterTest { } @Test - fun whenPersistFinishesThenPruneLocalDeletedEntities() { + fun `onSuccess - persist finishes - 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 `onError - 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..156c5a1cb708 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 `toLoginCredential - map remote login credential - login credentials`() { val syncCrypto = FakeCrypto() val credentialsSyncMapper = CredentialsSyncMapper(syncCrypto) val toLoginCredentialEntryResponse = twitterCredentials.toLoginCredentialEntryResponse() @@ -53,7 +53,7 @@ internal class CredentialsSyncMapperTest { } @Test - fun whenMapRemoteLoginCredentialThenEnsureFieldsDecrypted() { + fun `toLoginCredential - map remote login credential - 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..b2abfc75ccd9 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 - new entity - 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 - 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 - update existing entity by local id - 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 - loginId exists - return 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 - return new sync id`() { val syncId = testee.createSyncId(123L) assertNotNull(syncId) } @Test - fun whenCreateSyncIdForExistingIdThenReturnExistingSyncId() { + fun `createSyncId - existing id - return existing syncId`() { 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 - return null`() { val localId = testee.getLocalId("syncId") assertNull(localId) } @Test - fun whenLocalIdExistsThenReturnLocalId() { + fun `getLocalId - localId exists - return localId`() { 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 `getRemovedEntitiesSince - entities with deleted_at - return entities`() { 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 `getRemovedEntitiesSince - entities previous to since - do not return`() { 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 deletedAt 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 - entities removed - 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`() { 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 - localId - 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 - syncId - remove entity`() { 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 - entity in list - 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 - entity does not exist - inserted with modifiedAt`() { val loginId = 123L testee.onEntityChanged(loginId) @@ -260,7 +260,7 @@ internal class CredentialsSyncMetadataTest { } @Test - fun whenEntityChangedInAListDoesNotExistThenInsertedWithModifiedAt() { + fun `onEntitiesChanged - entity does not exist - inserted with modifiedAt`() { 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 `getAllCredentials - returns all`() { 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..ccab6d4fae86 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 `getUpdatesSince - start time updates`() = runTest { credentialsSync.getUpdatesSince("0") assertNotNull(credentialsSyncStore.startTimeStamp) } @Test - fun whenGetUpdatesSinceZeroTimeThenReturnAllContent() = runTest { + fun `getUpdatesSince - zero time - 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 - entities with modifiedAt null not returned`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -136,7 +136,7 @@ internal class CredentialsSyncTest { } @Test - fun whenUpdatesContainDeletedItemsThenReturnIncludeDeletedItemsInUpdate() = runTest { + fun `getUpdatesSince - updates contain deleted items - include deleted items in update`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials.copy(lastUpdatedMillis = 1689592358516), @@ -155,7 +155,7 @@ internal class CredentialsSyncTest { } @Test - fun whenOnFirstWithInvalidCredentialsThenChangesDoesNotContainInvalidEntities() = runTest { + fun `getUpdatesSince - 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 - changes does not contain invalid entity`() = runTest { givenLocalCredentials( spotifyCredentials, invalidCredentials.copy(lastUpdatedMillis = 1689592358516), @@ -180,7 +180,7 @@ internal class CredentialsSyncTest { } @Test - fun whenInvalidCredentialsPresentThenAlwaysRetryItemsAndUpdateInvalidList() = runTest { + fun `getUpdatesSince - invalid credentials present - 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 - invalid credentials - return invalid credentials`() = runTest { givenLocalCredentials( invalidCredentials, ) @@ -208,7 +208,7 @@ internal class CredentialsSyncTest { } @Test - fun whenGetCredentialWithSyncIdThenReturnCredentials() = runTest { + fun `getCredentialWithSyncId - return credentials`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -220,7 +220,7 @@ internal class CredentialsSyncTest { } @Test - fun whenGetCredentialsWithSyncIdNotFoundThenReturnNull() = runTest { + fun `getCredentialWithSyncId - not found - return null`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -232,7 +232,7 @@ internal class CredentialsSyncTest { } @Test - fun whenGetCredentialsWithLocalIdThenReturnCredentials() = runTest { + fun `getCredentialWithId - local id - return 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 - saves credential and syncs 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 - save to autofill store and override 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..c03bca6efec9 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 `isSyncPausedFlow - isSyncPaused updated - 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..04d2bbde1548 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 - credential recently removed - cancel delete operation and 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 `onCredentialRemoved - credential not reinserted - 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 - multiple credentials - 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 `onCredentialsAdded - reinsert recently removed credentials - cancel delete operation and do 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 `onCredentialRemoved - credentials not reinserted - 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..741c8b7855a0 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 - remote wins`() = 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 - 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 is 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 - remote wins`() = 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..fb85aa3fa1a5 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 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 is 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..b9c04766064e 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 are more recent - remote wins`() = runTest { givenLocalCredentials( twitterCredentials, spotifyCredentials, @@ -122,7 +122,7 @@ internal class CredentialsRemoteWinsStrategyTest { } @Test - fun whenLocalIsMoreRecentThenRemoteWins() = runTest { + fun `processEntries - local 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 is 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..7026fdfff5ae 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 more recent - 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 is 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..963f729d3a11 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 - return 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 - sending data - 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..66a1c7e7a1ca 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 `password - set - update key in keyStore`() { testee.password = testValue verify(keyStore).updateKey("KEY_GENERATED_PASSWORD", testValue) } @Test - fun whenGettingPasswordThenGetKeyForPasswordInKeyStore() { + fun `password - get key for password in key store`() { whenever(keyStore.getKey("KEY_GENERATED_PASSWORD")).thenReturn(testValue) assertEquals(testValue, testee.password) } @Test - fun whenL1KeyIsSetThenUpdateKeyForL1KeyInKeyStore() { + fun `l1Key - set - update key in keyStore`() { testee.l1Key = testValue verify(keyStore).updateKey("KEY_L1KEY", testValue) } @Test - fun whenGettingL1KeyThenGetKeyForL1KeyInKeyStore() { + fun `l1Key - get key for L1 key in key store`() { whenever(keyStore.getKey("KEY_L1KEY")).thenReturn(testValue) assertEquals(testValue, testee.l1Key) } @Test - fun whenPasswordSaltIsSetThenUpdateKeyForPasswordSaltInKeyStore() { + fun `passwordSalt - set - update key in keyStore`() { testee.passwordSalt = testValue verify(keyStore).updateKey("KEY_PASSWORD_SALT", testValue) } @Test - fun whenGettingPasswordSaltThenGetKeyForPasswordSaltKeyInKeyStore() { + fun `passwordSalt - get key for password salt key in key store`() { whenever(keyStore.getKey("KEY_PASSWORD_SALT")).thenReturn(testValue) assertEquals(testValue, testee.passwordSalt) } @Test - fun whenEncryptedL2KeyIsSetThenUpdateKeyForEncryptedL2KeyInKeyStore() { + fun `encryptedL2Key - set - update key in keyStore`() { testee.encryptedL2Key = testValue verify(keyStore).updateKey("KEY_ENCRYPTED_L2KEY", testValue) } @Test - fun whenGettingEncryptedL2KeyThenGetKeyForEncryptedL2KeyInKeyStore() { + fun `encryptedL2Key - get key from keystore`() { whenever(keyStore.getKey("KEY_ENCRYPTED_L2KEY")).thenReturn(testValue) assertEquals(testValue, testee.encryptedL2Key) } @Test - fun whenEncryptedL2KeyIVIsSetThenUpdateKeyForEncryptedL2KeyIVInKeyStore() { + fun `encryptedL2KeyIV - update key in keyStore`() { testee.encryptedL2KeyIV = testValue verify(keyStore).updateKey("KEY_ENCRYPTED_L2KEY_IV", testValue) } @Test - fun whenGettingEncryptedL2KeyIVThenGetKeyForEncryptedL2KeyIVInKeyStore() { + fun `encryptedL2KeyIV - get key from keystore`() { 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..0c856b550605 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 - id not exists - null returned`() = runTest { assertNull(websiteLoginCredentialsDao.getWebsiteLoginCredentialsById(entity().id)) } @Test - fun whenRetrievingLoginCredentialByIdThenReturnedIfExists() = runTest { + fun `getWebsiteLoginCredentialsForId - credential exists - returned`() = 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 - direct match - returned`() = 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 - null domain - 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 - no matches - empty list returned`() = 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 `websiteLoginCredentials - with sites - empty list returned`() = runTest { val result: List = testee.websiteLoginCredentials().first() assertTrue(result.isEmpty()) } @Test - fun whenGetAllWebsiteLoginCredentialsWithASingleSiteThenThatOneIsReturned() = runTest { + fun `websiteLoginCredentials - single site - one 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 `websiteLoginCredentials - 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 - no sites added - count is 0`() = runTest { testee.neverSaveListCount().test { assertEquals(0, awaitItem()) cancelAndIgnoreRemainingEvents() @@ -166,7 +166,7 @@ class RealSecureStorageRepositoryTest { } @Test - fun whenNeverSavedSiteAddedThenCountIncreases() = runTest { + fun `neverSaveListCount - never saved 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 - 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..ceca708ecf00 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 - call cleanup old entries - 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..1693ac037288 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 - with hostname - repository is called`() = runTest { val hostname = "www.example.com" testee.getLastSentDay(hostname) @@ -48,7 +48,7 @@ class RealBrokenSiteLastSentReportTest { } @Test - fun whenSetLastSentDayCalledWithHostnameThenSetLastSentDayFromRepositoryIsCalled() = runTest { + fun `setLastSentDay - with hostname - repository is called`() = 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..a5420c30ccc5 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 - return null`() = runTest { val hostname = "" val result = testee.getLastSentDay(hostname) @@ -61,7 +61,7 @@ class RealBrokenSiteReportRepositoryTest { } @Test - fun whenGetLastSentDayCalledWithNewHostnameThenReturnNull() = runTest { + fun `getLastSentDay - new hostname - return 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 - return 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 - upsertBrokenSiteReport is never called`() = runTest { val hostname = "" testee.setLastSentDay(hostname) @@ -95,7 +95,7 @@ class RealBrokenSiteReportRepositoryTest { } @Test - fun whenSetLastSentDayCalledWithNonEmptyHostnameThenUpsertBrokenSiteReportIsCalled() = runTest { + fun `setLastSentDay - non-empty hostname - upsertBrokenSiteReport 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..99e6485c961e 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 `viewState - notifications not allowed and dismiss not called and view not dismissed - view is visible`() = runTest { setup( notificationsAllowed = false, dismissCalled = false, @@ -73,7 +73,7 @@ class NotifyMeViewModelTest { } @Test - fun whenNotificationsNotAllowedAndDismissNotCalledAndViewIsDismissedThenViewIsNotVisible() = runTest { + fun `viewState - notifications not allowed and view dismissed - view is not visible`() = runTest { setup( notificationsAllowed = false, dismissCalled = false, @@ -87,7 +87,7 @@ class NotifyMeViewModelTest { } @Test - fun whenNotificationsNotAllowedAndDismissCalledAndViewIsNotDismissedThenViewIsNotVisible() = runTest { + fun `viewState - notifications not allowed and dismiss called and view not dismissed - view not visible`() = runTest { setup( notificationsAllowed = false, dismissCalled = true, @@ -101,7 +101,7 @@ class NotifyMeViewModelTest { } @Test - fun whenNotificationsNotAllowedAndDismissCalledAndViewIsDismissedThenViewIsNotVisible() = runTest { + fun `viewState - notifications not allowed and dismiss called and view dismissed - view is not visible`() = runTest { setup( notificationsAllowed = false, dismissCalled = true, @@ -115,7 +115,7 @@ class NotifyMeViewModelTest { } @Test - fun whenNotificationsAllowedAndDismissNotCalledAndViewIsNotDismissedThenViewIsNotVisible() = runTest { + fun `viewState - notifications allowed and dismiss not called and view not dismissed - view not visible`() = runTest { setup( notificationsAllowed = true, dismissCalled = false, @@ -129,7 +129,7 @@ class NotifyMeViewModelTest { } @Test - fun whenNotificationsAllowedAndDismissNotCalledAndViewIsDismissedThenViewIsNotVisible() = runTest { + fun `viewState - notifications allowed and view dismissed - view is not visible`() = runTest { setup( notificationsAllowed = true, dismissCalled = false, @@ -143,7 +143,7 @@ class NotifyMeViewModelTest { } @Test - fun whenNotificationsAllowedAndDismissCalledAndViewIsNotDismissedThenViewIsNotVisible() = runTest { + fun `viewState - notifications allowed and dismiss called and view not dismissed - view not visible`() = runTest { setup( notificationsAllowed = true, dismissCalled = true, @@ -171,7 +171,7 @@ class NotifyMeViewModelTest { } @Test - fun whenOnResumeCalledThenCheckPermissionsCommandIsSent() = runTest { + fun `onResume - check permissions command sent`() = runTest { testee.onResume(mockLifecycleOwner) testee.commands().test { @@ -183,7 +183,7 @@ class NotifyMeViewModelTest { } @Test - fun whenOnNotifyMeButtonClickedOnAndroid13ThenCheckPermissionRationaleCommandIsSent() = runTest { + fun `onNotifyMeButtonClicked - Android 13 - check permission rationale command sent`() = runTest { whenever(mockAppBuildConfig.sdkInt).thenReturn(Build.VERSION_CODES.TIRAMISU) testee.onNotifyMeButtonClicked() @@ -196,7 +196,7 @@ class NotifyMeViewModelTest { } @Test - fun whenOnNotifyMeButtonClickedOnAndroid8ThenOpenSettingsOnAndroid8PlusCommandIsSent() = runTest { + fun `onNotifyMeButtonClicked - Android 8 - open settings command sent`() = runTest { whenever(mockAppBuildConfig.sdkInt).thenReturn(Build.VERSION_CODES.O) testee.onNotifyMeButtonClicked() @@ -210,7 +210,7 @@ class NotifyMeViewModelTest { } @Test - fun whenOnCloseButtonClickedThenCloseCommandIsSentAndSetDismissedIsCalled() = runTest { + fun `onCloseButtonClicked - close command sent and set dismissed called`() = runTest { testee.onCloseButtonClicked() testee.commands().test { @@ -223,7 +223,7 @@ class NotifyMeViewModelTest { } @Test - fun whenHandleRequestPermissionRationaleWithShouldShowRationaleTrueThenShowPermissionRationaleIsSent() = runTest { + fun `handleRequestPermissionRationale - should show rationale true - show permission rationale sent`() = runTest { val shouldShowRationale = true testee.handleRequestPermissionRationale(shouldShowRationale) @@ -237,7 +237,7 @@ class NotifyMeViewModelTest { } @Test - fun whenHandleRequestPermissionRationaleOnAndroid8WithShouldShowRationaleFalseThenOpenSettingsOnAndroid8PlusCommandIsSent() = runTest { + fun `handleRequestPermissionRationale - Android 8 with shouldShowRationale false - open settings command 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+ - update notifications state command 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..15884c6af9d4 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 `toSanitizedLanguageTag - has unicode locale extension - removes unicode locale extension`() { val locale = Locale.Builder() .setLanguage("en") .setRegion("US") @@ -19,7 +19,7 @@ class LocaleExtensionsTest { } @Test - fun whenDoesNotHaveUnicodeLocaleExtensionThenLanguageTagIsUnchanged() { + fun `toSanitizedLanguageTag - does not have unicode locale extension - 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..1536b46592e6 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 on 1 KB - KB returned`() { assertEquals("1 KB", testee.format(1000)) } @Test - fun whenNotAWholeNumberOfKilobytesThenKbReturned() { + fun `format - not a whole number of kilobytes - kb returned`() { assertEquals("1.5 KB", testee.format(1501)) } @Test - fun whenExactly1MegabyteThenMbReturned() { + fun `format - exactly 1 megabyte - MB returned`() { assertEquals("1 MB", testee.format(1_000_000)) } @Test - fun whenExactly1GigabyteThenGbReturned() { + fun `format - exactly 1 gigabyte - GB returned`() { 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..b549f23b3aef 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 is used`() { val formatted = DatabaseDateFormatter.bucketByHour(fixedTime()) assertEquals("2020-12-25T13:00:00", formatted) } @Test - fun whenBucketingByTimestampOnlySecondsPrecisionIsUsed() { + fun `timestamp - fixed time - only seconds precision used`() { val formatted = DatabaseDateFormatter.timestamp(fixedTime()) assertEquals("2020-12-25T13:14:15", formatted) } @Test - fun whenIso8601isUsedThenDateIsFormatted() { + fun `iso8601 - date is formatted`() { val formatted = DatabaseDateFormatter.iso8601(fixedUTCTime()) assertEquals("2020-12-25T13:14:15.000000016Z", formatted) } @Test - fun whenIso8601isParsedThenDateIsCorrect() { + fun `parseMillisIso8601 - iso8601 parsed - 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 `parseMillisIso8601 - system time millis - string represents expected date time`() { val timeInMillisNow = System.currentTimeMillis() val formattedMillis = DatabaseDateFormatter.parseMillisIso8601(timeInMillisNow) @@ -70,7 +70,7 @@ class DatabaseDateFormatterTest { } @Test - fun whenParsingIso8601ToMillisThenMillisRepresentsExpectedDateTime() { + fun `parseIso8601ToMillis - 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..b94073a77ee6 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 `shortFormat - only hours passed - proper time`() { val timePassed = TimePassed(1, 0, 0) assertEquals("1h ago", timePassed.shortFormat(resources)) } @Test - fun whenOnlyMinutesPassedThenShortFormatsProperTime() { + fun `shortFormat - only minutes passed - proper time`() { val timePassed = TimePassed(0, 10, 0) assertEquals("10m ago", timePassed.shortFormat(resources)) } @Test - fun whenOnlySecondsPassedThenShortFormatsProperTime() { + fun `shortFormat - only seconds passed - proper time`() { val timePassed = TimePassed(0, 0, 45) assertEquals("Just Now", timePassed.shortFormat(resources)) } @Test - fun whenOnlyFewSecondsPassedThenShortFormatsProperTime() { + fun `shortFormat - few seconds passed - proper time`() { val timePassed = TimePassed(0, 0, 25) assertEquals("Just Now", timePassed.shortFormat(resources)) } @Test - fun whenHoursAndMinutesPassedThenShortFormatsProperTime() { + fun `shortFormat - hours and minutes passed - proper time`() { val timePassed = TimePassed(1, 10, 0) assertEquals("1h ago", timePassed.shortFormat(resources)) } @Test - fun whenHoursAndSecondsPassedThenShortFormatsProperTime() { + fun `shortFormat - hours and seconds passed - proper time`() { val timePassed = TimePassed(1, 0, 30) assertEquals("1h ago", timePassed.shortFormat(resources)) } @Test - fun whenMinutesAndSecondsPassedShortThenFormatsProperTime() { + fun `shortFormat - minutes and seconds passed - 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..c46125337aa1 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 `isCGNAT - various IP ranges - correct identification`() { // 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..c22e89d6cd7f 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 and inject content scope scripts - 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..d7235abc9457 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 - unprotected temporary changed - use new unprotected temporary 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 - return true`() { whenever(mockContentScopeScriptsFeature.self()).thenReturn(EnabledToggle()) assertTrue(testee.isEnabled()) } @Test - fun whenContentScopeScriptsIsDisabledThenReturnFalse() { + fun `isEnabled - content scope scripts disabled - return 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..69b24d336118 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 `process - unknown message - do nothing`() = runTest { givenInterfaceIsRegistered() contentScopeScriptsJsMessaging.process("", contentScopeScriptsJsMessaging.secret) @@ -66,7 +66,7 @@ class ContentScopeScriptsJsMessagingTest { } @Test - fun whenProcessUnknownSecretDoNothing() = runTest { + fun `process - unknown secret - do nothing`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -79,7 +79,7 @@ class ContentScopeScriptsJsMessagingTest { } @Test - fun whenProcessInterfaceNotRegisteredDoNothing() = runTest { + fun `process - interface not registered - 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 `process - webShare - callback executed and not response sent`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -112,7 +112,7 @@ class ContentScopeScriptsJsMessagingTest { } @Test - fun whenProcessAndWebShareIfFeatureNameDoesNotMatchDoNothing() = runTest { + fun `process - feature name does not match - do nothing`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -125,7 +125,7 @@ class ContentScopeScriptsJsMessagingTest { } @Test - fun whenProcessAndWebShareIfIdDoesNotExistThenDoNothing() = runTest { + fun `process - web share id does not exist - do nothing`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -138,7 +138,7 @@ class ContentScopeScriptsJsMessagingTest { } @Test - fun whenProcessAndPermissionsQueryThenCallbackExecutedAndNotResponseSent() = runTest { + fun `process - permissions query - callback executed and no response sent`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -151,7 +151,7 @@ class ContentScopeScriptsJsMessagingTest { } @Test - fun whenProcessAndPermissionsQueryIfIdDoesNotExistThenDoNothing() = runTest { + fun `process - 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..a48f1f71e868 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 `config - return correctly formatted json`() { whenever(mockContentScopeScriptsCookieRepository.getCookieEntity()).thenReturn(CookieEntity(json = config)) assertEquals("\"cookie\":$config", testee.config()) } @Test - fun whenGetPreferencesThenReturnNull() { + fun `preferences - return 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..f01039b8cb58 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 `redactStacktraceInBase64 - query has when - return redacted base64 stacktrace`() { val ss = redactStacktraceInBase64(WITH_WHEN) assertEquals(WITH_WHEN_BASE634, ss) } @Test - fun whenQueryDoesNotHaveWhenThenReturnBase64Stacktrace() { + fun `redactStacktraceInBase64 - query does not have when - return base64 stacktrace`() { val ss = redactStacktraceInBase64(WITHOUT_WHEN) assertEquals(WITHOUT_WHEN_BASE64, ss) } @Test - fun whenQueryOneLineThenReturnBase64Stacktrace() { + fun `redactStacktraceInBase64 - one line query - return base64 stacktrace`() { 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..dff88d28e632 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 `removeCookies - selective cookie remover succeeds - no more interactions`() = runTest { selectiveCookieRemover.succeeds() removeCookies.removeCookies() @@ -40,7 +40,7 @@ class RemoveCookiesTest { } @Test - fun whenSelectiveCookieRemoverFailsThenFallbackToCookieManagerRemover() = runTest { + fun `removeCookies - selective cookie remover fails - 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..d9fa27733194 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 - cookies removed - 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 - cookies stored - 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..c015b6a7a59f 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 - return 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 - return 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 `store - feature name matches cookies - update all existing values`() { 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..ca4d549a8cf8 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 - feature is not a cookie feature - return null`() = runTest { assertNull(testee.isEnabled(NonPrivacyFeature().value, true)) } @Test - fun whenIsEnabledAndFeatureIsCookieFeatureThenReturnTrueWhenEnabled() = + fun `isEnabled - cookie feature enabled - returns true`() = runTest { giveCookieFeatureIsEnabled() @@ -60,7 +60,7 @@ class CookiesFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsCookieFeatureThenReturnFalseWhenDisabled() = + fun `isEnabled - cookie feature disabled - return false`() = 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 - return true`() = runTest { giveCookieFeatureIsEnabled() givenAppVersionIsEqualToMinSupportedVersion() @@ -93,7 +93,7 @@ class CookiesFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsCookieFeatureAndAppVersionIsGreaterThanMinSupportedVersionThenReturnTrueWhenEnabled() = + fun `isEnabled - cookie feature enabled and app version greater than min supported - returns true`() = runTest { giveCookieFeatureIsEnabled() givenAppVersionIsGreaterThanMinSupportedVersion() @@ -104,7 +104,7 @@ class CookiesFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsCookieFeatureAndAppVersionIsSmallerThanMinSupportedVersionThenReturnFalseWhenEnabled() = + fun `isEnabled - cookie feature and app version smaller than min supported - return false`() = 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..b242d8605312 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 - enqueues 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 - enqueues 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..c7465c66e1c6 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 `RealCookieRepository - repository created - 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..c88961f2b69a 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 - deleteAll called`() { testee.deleteAll() verify(mockCookiesFeatureToggleStore).deleteAll() } @Test - fun whenGetThenGetCalled() { + fun `get - get called`() { testee.get(Cookie, true) verify(mockCookiesFeatureToggleStore).get(Cookie, true) } @Test - fun whenInsertThenInsertCalled() { + fun `insert - insert called`() { 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..d799082d0d5d 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 `getSharedPreferences - multiprocess - migrate to harmony`() { 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 `SafeSharedPreferences - store and retrieve values - values match`() { 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..dd8cb3155d77 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 - mimeType 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 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 - arbitrary image type - no suffix generated`() { val parsed = testee.generate("data:image/foo;base64,AAAA") as ParsedDataUri assertEquals("", parsed.filename.fileType) } @Test - fun whenMimeTypeNotProvidedThenNoSuffixAdded() { + fun `generate - mime type not 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 - invalid type returned`() { val parsed = testee.generate("AAAA") assertTrue(parsed === Invalid) } @Test - fun whenInvalidDataUriContainingCommaIsProvidedTheInvalidTypeTurned() { + fun `generate - invalid data URI containing comma - invalid type returned`() { val parsed = testee.generate("data:,") assertTrue(parsed === Invalid) } @Test - fun whenKnownMimeTypeProvidedAsNonImageTypeThenSuffixStillGenerated() { + fun `generate - known non-image mime type - suffix generated`() { val parsed = testee.generate("data:text/plain;base64,AAAA") as ParsedDataUri assertEquals("txt", parsed.filename.fileType) } @Test - fun whenMimeTypeNotProvidedThenNoSuffixAddedInToString() { + fun `generate - mime type not provided - no suffix added in toString`() { val filename = testee.generate("data:,AAAA") as ParsedDataUri assertFalse(filename.toString().contains(".")) } @Test - fun whenMimeTypeIsTextPlainAndDataIsBase64AndIsPngThenSuffixIsPng() { + fun `generate - text·plain base64 data 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 base64 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 - text·plain base64 SVG data - suffix is svg`() { val parsed = testee.generate("data:text/plain;base64,PHN2ZyB2ZXJzaW9uPSIxLjIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy") as ParsedDataUri assertEquals("svg", parsed.filename.fileType) } @Test - fun whenMimeTypeIsTextPlainAndDataIsBase64AndIsGifThenSuffixIsGif() { + fun `generate - text plain base64 gif data - suffix is gif`() { val parsed = testee.generate("data:text/plain;base64,R0lGODlhAAXQAocAAP") as ParsedDataUri assertEquals("gif", parsed.filename.fileType) } @Test - fun whenMimeTypeIsTextPlainAndDataIsBase64AndIsPdfThenSuffixIsPdf() { + fun `generate - text·plain base64 PDF data - suffix is pdf`() { val parsed = testee.generate("data:text/plain;base64,JVBERi0xLjEKMSAwIG9iag") as ParsedDataUri assertEquals("pdf", parsed.filename.fileType) } @Test - fun whenMimeTypeIsTextPlainAndDataIsBase64AndIsWebpThenSuffixIsWebp() { + fun `generate - text·plain base64 webp data - suffix is webp`() { val parsed = testee.generate("data:text/plain;base64,UklGRs4IAABXRUJQVlA4WAo") as ParsedDataUri assertEquals("webp", parsed.filename.fileType) } @Test - fun whenMimeTypeIsTextPlainAndDataIsBase64AndIsBpThenSuffixIsBmp() { + fun `generate - text·plain base64 data - suffix is bmp`() { val parsed = testee.generate("data:text/plain;base64,Qk1AwgEA") as ParsedDataUri assertEquals("bmp", parsed.filename.fileType) } @Test - fun whenMimeTypeIsTextPlainAndDataIsBase64AndIsUnknownThenSuffixIsTxt() { + fun `generate - text·plain base64 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..b6caaaa9fd20 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 - insert called`() = runTest { val item = oneItem() val entity = oneEntity() @@ -60,7 +60,7 @@ class DefaultDownloadsRepositoryTest { } @Test - fun whenInsertAllDownloadItemsThenInsertAllCalled() = runTest { + fun `insertAll - download items - insertAll called`() = runTest { val firstItem = oneItem() val secondItem = otherItem() val firstEntity = oneEntity() @@ -73,7 +73,7 @@ class DefaultDownloadsRepositoryTest { } @Test - fun whenUpdateDownloadItemByIdWithDownloadStatusFinishedAndContentLengthThenUpdateCalledWithSameParams() = + fun `update - download status finished and content length - update called with same params`() = runTest { val item = oneItem() val updatedStatus = FINISHED @@ -95,7 +95,7 @@ class DefaultDownloadsRepositoryTest { } @Test - fun whenUpdateDownloadItemByIdWithDownloadStatusStartedAndContentLengthThenUpdateCalledWithSameParams() = + fun `update - download item by id with status started and content length - update called with same params`() = runTest { val item = oneItem() val updatedStatus = STARTED @@ -117,7 +117,7 @@ class DefaultDownloadsRepositoryTest { } @Test - fun whenUpdateDownloadItemByFileNameWithDownloadStatusFinishedAndContentLengthThenUpdateCalledWithSameParams() = + fun `update - download item by file name with finished status 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 item by file name with 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 - delete called`() = runTest { val item = oneItem() repository.delete(item.downloadId) @@ -171,7 +171,7 @@ class DefaultDownloadsRepositoryTest { } @Test - fun whenDeleteListOfDownloadItemsThenDeleteCalled() = runTest { + fun `delete - list of download items - 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 - calls getDownloadItem`() = 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 `getDownloads - getDownloadItems called - getDownloads 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..4b1e91a351ce 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 and unsupported chars in filename - correct filename extracted`() { assertEquals( "0_BRkMUINdhCYPk1KM.jpg", DownloaderUtil.guessFileName( @@ -71,7 +71,7 @@ class DownloaderUtilTest { } @Test - fun whenAttachmentWithFilenameContentDispositionAndApplicationOctetStreamContentTypeAndCorrectFileExtensionInUrlThenCorrectFilenameExtracted() { + fun `guessFileName - attachment with filename and correct file extension in URL - correct filename extracted`() { assertEquals( "Telegram.apk", DownloaderUtil.guessFileName( @@ -99,7 +99,7 @@ class DownloaderUtilTest { } @Test - fun whenInlineWithFilenameContentDispositionAndApplicationPdfContentTypeAndCorrectFileExtensionInUrlThenCorrectFilenameExtracted() { + fun `guessFileName - inline content disposition and application·pdf - correct filename extracted`() { assertEquals( "Monitoraggio_Fase_2__report_nazionale_83_finale.pdf", 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·pdf content type - correct filename extracted`() { assertEquals( "ahc01_learn_to_play_web.pdf", DownloaderUtil.guessFileName( @@ -162,7 +162,7 @@ class DownloaderUtilTest { } @Test - fun whenEmptyContentDispositionAndApplicationVndApplePkPassContentTypeAndCorrectFileExtensionInUrlThenCorrectFilenameExtracted() { + fun `guessFileName - empty content disposition 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-python3 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 - attachment with filename in quotes and space after semicolon - correct filename extracted`() { assertEquals("filename.jpg", DownloaderUtil.fileNameFromContentDisposition("""attachment; filename="filename.jpg"""")) } @Test - fun whenContentDispositionWithAttachmentAndFilenameBetweenQuotesAndSpacesBeforeAndAfterSemicolonThenCorrectFilenameExtracted() { + fun `fileNameFromContentDisposition - attachment with quoted filename and spaces - correct filename extracted`() { assertEquals("filename.jpg", DownloaderUtil.fileNameFromContentDisposition("""attachment ; filename="filename.jpg"""")) } @Test - fun whenContentDispositionWithAttachmentAndFilenameBetweenQuotesAndNoSpacesThenCorrectFilenameExtracted() { + fun `fileNameFromContentDisposition - attachment with quoted filename - correct filename extracted`() { assertEquals("filename.jpg", DownloaderUtil.fileNameFromContentDisposition("""attachment;filename="filename.jpg"""")) } @Test - fun whenContentDispositionWithAttachmentAndFilenameWithoutQuotesAndWithSpaceAfterSemicolonThenCorrectFilenameExtracted() { + fun `fileNameFromContentDisposition - attachment and filename without quotes and space after semicolon - correct filename extracted`() { assertEquals("filename.jpg", DownloaderUtil.fileNameFromContentDisposition("""attachment; filename=filename.jpg""")) } @Test - fun whenContentDispositionWithInlineAndFilenameBetweenQuotesAndSpaceAfterSemicolonThenCorrectFilenameExtracted() { + fun `fileNameFromContentDisposition - inline and filename between quotes with space after semicolon - correct filename extracted`() { assertEquals("filename.jpg", DownloaderUtil.fileNameFromContentDisposition("""inline; filename="filename.jpg"""")) } @Test - fun whenContentDispositionWithAttachmentAndFilenameEncodedThenEncodedFilenameExtracted() { + fun `fileNameFromContentDisposition - attachment with encoded filename - 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 - attachment and filename star encoded - decoded filename extracted`() { assertEquals( "中文文件名测试.txt", DownloaderUtil.fileNameFromContentDisposition( @@ -235,7 +235,7 @@ class DownloaderUtilTest { } @Test - fun whenContentDispositionWithAttachmentAndFilenameStarEncodedAndFilenameThenDecodedFilenameExtracted() { + fun `fileNameFromContentDisposition - attachment with encoded filename - decoded filename extracted`() { assertEquals( "中文文件名测试.txt", DownloaderUtil.fileNameFromContentDisposition( @@ -263,7 +263,7 @@ class DownloaderUtilTest { } @Test - fun whenContentDispositionWithAttachmentAndFilenameStarEncodedWithNoEncodingAndFilenameThenDecodedFilenameExtractedFallback() { + fun `fileNameFromContentDisposition - attachment and filename star encoded with no encoding and filename - 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 - inline and encoded 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..ccb0520d4c08 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 and 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 - download id - pixel fired and item updated and 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 - 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 - connection refused - 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 - 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, notification sent, 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..894b4f73d150 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,7 @@ import org.junit.runner.RunWith class PendingFileDownloadCompressTest { @Test - fun whenDownloadUrlIsTooLargeAndToInputDataCalledThenAddCompressedUrl() { + fun `toInputData - download URL too large - add compressed URL`() { 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 +55,7 @@ class PendingFileDownloadCompressTest { } @Test - fun whenDownloadUrlIsSmallAndToInputDataCalledThenUrlNotCompressed() { + fun `toInputData - small 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 +65,7 @@ class PendingFileDownloadCompressTest { } @Test - fun whenDownloadUrlIsCompressedAndToPendingFileDownloadCalledThenUrlIsDecompressed() { + fun `toPendingFileDownload - compressed url - url decompressed`() { 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 +79,7 @@ class PendingFileDownloadCompressTest { } @Test - fun whenDownloadUrlIsNotCompressedAndToPendingFileDownloadCalledThenUrlIsNotDecompressed() { + fun `toPendingFileDownload - url is not compressed - url is not decompressed`() { 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..b2603f587769 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 - not added download id - noop`() { RealUrlFileDownloadCallManager().remove(0L) verifyNoInteractions(call) } @Test - fun whenRemovingAddedDownloadIdThenCancelDownloadAndRemove() { + fun `remove - added download id - cancel download and remove`() { val downloadManager = RealUrlFileDownloadCallManager() downloadManager.add(0L, call) @@ -49,7 +49,7 @@ class RealUrlFileDownloadCallManagerTest { } @Test - fun whenAddingDownloadIdTwiceThenOnlyLatestCallIsReplaced() { + fun `add - download id added 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..7ce48cf4e41f 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 - filename should be 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 with additional path segments - filename should be 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 with additional path segments and query params - filename 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 with path segments resembling filename - 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 - ambiguous filename with path segments and mime type - 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 with filename and multiple path segments and mimeType provided - filename extracted`() { val url = "https://foo.example.com/path/images/b/b1/realFilename.jpg" val mimeType = "image/jpeg" val contentDisposition: String? = null @@ -127,7 +127,7 @@ class UriUtilsFilenameExtractorTest { } @Test - fun whenUrlContainsFilenameButContentDispositionSaysOtherwiseThenExtractFromContentDisposition() { + fun `extract - url contains filename but content disposition says otherwise - extract 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 with no file name but many 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 - empty url and no data - 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 - empty url and mime type provided - default name and filetype returned`() { shadowOf(MimeTypeMap.getSingleton()).addExtensionMimeTypMapping("jpg", "image/jpeg") val url = "" @@ -225,7 +225,7 @@ class UriUtilsFilenameExtractorTest { } @Test - fun whenUrlIsEmptyStringAndContentDispositionProvidedThenExtractFromContentDisposition() { + fun `extract - empty url and content disposition provided - extract from content disposition`() { 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 - path name file is returned`() { 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 is text·x-python3 and content disposition is empty - filename is 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..2fbdffa54b17 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 - download successful - call onStart, inProgress, 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 - download cancelled - call onCancel 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 - write error - call onCancel 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 file failed as error - call onError 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 - download succeeds as cancelled - call onCancel 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 - failed to write - call onError 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..d64db9e80487 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 `insert - download item added - it is in list`() = runTest { val downloadItem = oneItem() dao.insert(downloadItem) @@ -69,7 +69,7 @@ class DownloadsDaoTest { } @Test - fun whenDownloadItemsAddedThenTheyAreInTheList() = runTest { + fun `insertAll - download items added - they are in the list`() = runTest { val downloadItems = listOf( oneItem(), otherItem(), @@ -82,7 +82,7 @@ class DownloadsDaoTest { } @Test - fun whenDownloadItemUpdatedByIdThenItIsInListWithNewValue() = runTest { + fun `update - download item 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 `update - download item 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 `delete - download item - no longer in the list`() = runTest { val downloadItem = oneItem() dao.insert(downloadItem) @@ -131,7 +131,7 @@ class DownloadsDaoTest { } @Test - fun whenDownloadItemsDeletedThenTheyAreNoLongerInTheList() = runTest { + fun `delete - download items deleted - no longer in the list`() = runTest { val downloadItems = listOf( oneItem(), otherItem(), @@ -145,7 +145,7 @@ class DownloadsDaoTest { } @Test - fun whenDownloadItemsRetrievedThenTheCorrectItemIsReturned() = runTest { + fun `getDownloadItem - 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..2d62f80d0939 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 `config - return correctly formatted json`() { whenever(mockElementHidingRepository.elementHidingEntity).thenReturn(ElementHidingEntity(json = config)) assertEquals("\"elementHiding\":$config", testee.config()) } @Test - fun whenGetPreferencesThenReturnNull() { + fun `preferences - return 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..5878c5ad1639 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 - return 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 - return true`() { assertTrue(testee.store(FEATURE_NAME_VALUE, JSON_STRING)) } @Test - fun whenFeatureNameMatchesElementHidingThenUpdateAll() { + fun `store - feature name matches element hiding - update all`() { 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..2ac7165dafe2 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 `init - no stored value - load empty json to memory`() = runTest { testee = RealElementHidingRepository( @@ -57,7 +57,7 @@ class ElementHidingRepositoryTest { } @Test - fun whenInitializedAndHasStoredValueThenLoadStoredJsonToMemory() = + fun `init - has stored value - load stored json to memory`() = runTest { whenever(mockElementHidingDao.get()).thenReturn(elementHidingEntity) testee = @@ -73,7 +73,7 @@ class ElementHidingRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - updateAll 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..59722499a21a 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 complies 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 complies 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 complies with both filters - returns true`() { val locale = Locale("en", "US") Locale.setDefault(locale) whenever(mockAppBuildConfig.sdkInt).thenReturn(33) @@ -85,7 +85,7 @@ class ExperimentFiltersManagerImplTest { } @Test - fun whenVariantComplyWithLocaleFiltersAndDoesNotComplyWithAndroidVersionFilterThenAddFiltersReturnsFalse() { + fun `addFilters - locale complies and android version does not - returns false`() { val locale = Locale("en", "US") Locale.setDefault(locale) whenever(mockAppBuildConfig.sdkInt).thenReturn(32) @@ -95,7 +95,7 @@ class ExperimentFiltersManagerImplTest { } @Test - fun whenVariantComplyWithAndroidVersionFiltersAndDoesNotComplyWithLocaleFilterThenAddFiltersReturnsFalse() { + fun `addFilters - complies with android version but not locale - returns false`() { 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..097a2369ddc0 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 - variant allocator 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 `updateVariants - 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 - return user variant - no new variant 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 `updateVariants - persisted variant not found - restored to default`() { whenever(mockExperimentVariantRepository.getUserVariant()).thenReturn("variantKey") testee.updateVariants(emptyList()) @@ -121,7 +121,7 @@ class VariantManagerImplTest { } @Test - fun whenVariantPersistedHasWeightEqualToZeroInActiveVariantListThenVariantIsNotRestored() { + fun `updateVariants - weight equal to zero - variant is 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 - 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 - dataStore 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..de68082ca8d7 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 `serpControlVariant - has expected weight and no features`() { val variant = variants.first { it.key == "sc" } assertEqualsDouble(0.0, variant.weight) } @Test - fun serpExperimentalVariantHasExpectedWeightAndNoFeatures() { + fun `serpExperimentalVariant - has expected weight and no features`() { val variant = variants.first { it.key == "se" } assertEqualsDouble(0.0, variant.weight) } @Test - fun verifyNoDuplicateVariantNames() { + fun `verifyNoDuplicateVariantNames - duplicate variant name found`() { 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..4b4890d56277 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 - don't 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 already checked - don't check for 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 `beforeAtbInit - DDG 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..d0b7a0bf7d51 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 `setEnabled - disable by default - 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 `setEnabled - enabled by default - 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 - wrong return value - throw IllegalArgumentException`() { feature.wrongReturnValue() } @Test - fun whenNotAllowedMinVersionThenReturnDisabled() { + fun `enabledByDefault - min version not allowed - 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 `internal - always enabled annotation`() { assertFalse(feature.internal().isEnabled()) provider.flavorName = BuildFlavor.PLAY.name @@ -133,7 +133,7 @@ class FeatureTogglesTest { } @Test - fun testForcesDefaultVariantIfNullOnExperiment() { + fun `experimentDisabledByDefault - null variant - forces default`() { toggleStore.set( "test_forcesDefaultVariant", State( @@ -146,38 +146,38 @@ class FeatureTogglesTest { } @Test - fun testForcesDefaultVariantOnExperiment() { + fun `experimentDisabledByDefault - forces default variant`() { assertNull(provider.variantKey) assertFalse(feature.experimentDisabledByDefault().isEnabled()) assertEquals("", provider.variantKey) } @Test - fun testDoesNotForcesDefaultVariantOnFeatureFlag() { + fun `disableByDefault - does not force default variant`() { assertNull(provider.variantKey) assertFalse(feature.disableByDefault().isEnabled()) assertNull(provider.variantKey) } @Test - fun testSkipForcesDefaultVariantWhenNotNull() { + fun `experimentDisabledByDefault - variant not null - forces default variant`() { provider.variantKey = "ma" assertFalse(feature.experimentDisabledByDefault().isEnabled()) assertEquals("ma", provider.variantKey) } @Test(expected = java.lang.IllegalArgumentException::class) - fun whenMethodWithArgumentsThenThrow() { + fun `methodWithArguments - empty argument - throws IllegalArgumentException`() { feature.methodWithArguments("") } @Test(expected = java.lang.IllegalArgumentException::class) - fun whenSuspendFunctionThenThrow() = runTest { + fun `suspendFun - throws IllegalArgumentException`() = runTest { feature.suspendFun() } @Test(expected = IllegalArgumentException::class) - fun whenValidFeatureAndMissingFeatureNameBuilderParameterThenThrow() { + fun `create - missing feature name builder parameter - throws IllegalArgumentException`() { FeatureToggles.Builder() .store(FakeToggleStore()) .appVersionProvider { provider.version } @@ -187,7 +187,7 @@ class FeatureTogglesTest { } @Test(expected = IllegalArgumentException::class) - fun whenValidFeatureAndMissingStoreBuilderParameterThenThrow() { + fun `create - missing store builder parameter - throws IllegalArgumentException`() { FeatureToggles.Builder() .featureName("test") .appVersionProvider { provider.version } @@ -197,7 +197,7 @@ class FeatureTogglesTest { } @Test - fun whenEnabledAndInvalidOrValidRolloutThenIsEnableReturnsTrue() { + fun `isEnabled - enabled and invalid or valid rollout - 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 `determineRolloutValue - disabled and valid rollout`() { val state = Toggle.State( enable = false, rollout = listOf(100.0), @@ -250,7 +250,7 @@ class FeatureTogglesTest { } @Test - fun whenDisabledAndValidRolloutWithMultipleStepsThenDetermineRolloutValue() { + fun `determineRolloutValue - disabled and valid rollout with multiple steps`() { 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 `setEnabled - incremental rollout threshold set only once`() { var state = Toggle.State( enable = false, rollout = listOf(0.0), @@ -289,7 +289,7 @@ class FeatureTogglesTest { } @Test - fun whenDisabledWithPreviousStepsAndValidRolloutWithMultipleStepsThenDetermineRolloutValue() { + fun `setEnabled - valid rollout with multiple steps - determine rollout value`() { 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 `isEnabled - valid rollout steps and not supported version - return disabled`() { provider.version = 10 val state = Toggle.State( enable = false, @@ -323,7 +323,7 @@ class FeatureTogglesTest { } @Test - fun whenRemoteEnableStateIsNullThenHonourLocalEnableStateAndUpdate() { + fun `setEnabled - remote enable state is null - honour local enable state and update`() { val state = Toggle.State(enable = false) feature.self().setEnabled(state) @@ -336,7 +336,7 @@ class FeatureTogglesTest { } @Test - fun whenRemoteStateDisabledThenIgnoreLocalState() { + fun `setEnabled - remote state disabled - ignore local state`() { val state = Toggle.State( remoteEnableState = false, enable = true, @@ -347,7 +347,7 @@ class FeatureTogglesTest { } @Test - fun whenRemoteStateDisabledAndValidRolloutThenIgnoreRollout() { + fun `setEnabled - remote state disabled and valid rollout - ignore rollout`() { val state = Toggle.State( remoteEnableState = false, enable = true, @@ -360,7 +360,7 @@ class FeatureTogglesTest { } @Test - fun whenRemoteStateEnabledAndLocalStateEnabledWithValidRolloutThenIgnoreRollout() { + fun `setEnabled - remote and local state enabled with valid rollout - ignore rollout`() { val state = Toggle.State( remoteEnableState = true, enable = true, @@ -374,7 +374,7 @@ class FeatureTogglesTest { } @Test - fun whenRemoteStateEnabledAndLocalStateDisabledWithValidRolloutThenDoRollout() { + fun `setEnabled - remote state enabled and local state disabled with valid rollout - do rollout`() { val state = Toggle.State( remoteEnableState = true, enable = false, @@ -388,7 +388,7 @@ class FeatureTogglesTest { } @Test - fun whenAppUpdateThenEvaluatePreviousState() { + fun `evaluatePreviousState - app update`() { // when remoteEnableState is null it means app update val state = Toggle.State( remoteEnableState = null, @@ -405,7 +405,7 @@ class FeatureTogglesTest { } @Test - fun whenNoMatchingVariantThenFeatureIsDisabled() { + fun `experimentDisabledByDefault - no matching variant - feature is disabled`() { val state = Toggle.State( remoteEnableState = null, enable = true, @@ -422,7 +422,7 @@ class FeatureTogglesTest { } @Test - fun whenMatchingVariantThenReturnFeatureState() { + fun `experimentDisabledByDefault - matching variant - feature state enabled`() { provider.variantKey = "ma" val state = Toggle.State( remoteEnableState = null, @@ -440,7 +440,7 @@ class FeatureTogglesTest { } @Test - fun testVariantsAreIgnoredInFeatureFlags() { + fun `featureFlags - variants ignored`() { provider.variantKey = "ma" val state = Toggle.State( remoteEnableState = null, @@ -466,7 +466,7 @@ class FeatureTogglesTest { } @Test - fun whenMultipleNotMatchingVariantThenReturnFeatureState() { + fun `experimentDisabledByDefault - multiple not matching variant - feature state`() { provider.variantKey = "zz" val state = Toggle.State( remoteEnableState = null, @@ -487,7 +487,7 @@ class FeatureTogglesTest { } @Test - fun whenAnyMatchingVariantThenReturnFeatureState() { + fun `disableByDefault - matching variant - feature state enabled`() { 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..91f823057982 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 `class generation - class is generated`() { 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 `generatedClass - implements Toggle Store and PrivacyFeaturePlugin`() { 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 `class factory - is generated`() { 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 `generatedClass - singleInstance annotated in right 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 `generatedClass - annotated with RemoteFeatureStoreNamed in right scope`() { 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 `generatedClass - contributes toggle store binding`() { 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 `generated class - contributes privacy plugin multibinding`() { 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 hash is null - re-evaluate feature state`() { 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 - hash unchanged - does not re-evaluate feature state`() { 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 - hash changed - feature state re-evaluated`() { 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 `store - feature already present in remote config but just added to client - re-evaluate feature`() { 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 `store - sub-feature present remotely but missing locally - continue without error`() { 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 `generatedFeatureNewInstance - 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 `store - internal always enabled annotation`() { 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`() { 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 `store - default-enabled feature flag - staged rollout`() { 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 - feature state disabled - feature and subfeature 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 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 not interfered`() { val jsonFeature = """ { "state": "disabled", @@ -751,7 +751,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `the features have the right state for internal builds`() { + fun `store - internal build - features have the right state`() { 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 - incremental steps ignored`() { 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 enabled - incremental steps executed`() { 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 and not executed`() { 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 - feature disabled`() { val jsonFeature = """ { "state": "enabled", @@ -941,7 +941,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `re-enable a previously disabled incremental rollout`() { + fun `store - re-enable previously disabled incremental rollout - rollout re-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 `store - feature enabled with rollout threshold - remains enabled`() { whenever(appBuildConfig.versionCode).thenReturn(1) val feature = generatedFeatureNewInstance() @@ -1151,7 +1151,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `full feature lifecycle`() { + fun `generatedFeatureNewInstance - full feature lifecycle - expected states`() { whenever(appBuildConfig.versionCode).thenReturn(1) val feature = generatedFeatureNewInstance() @@ -1506,7 +1506,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `test variant parsing when no remote variant provided`() { + fun `variant parsing - no remote variant provided`() { val feature = generatedFeatureNewInstance() val privacyPlugin = (feature as PrivacyFeaturePlugin) @@ -1534,7 +1534,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `test variant parsing`() { + fun `variant parsing - feature states - correct states`() { variantManager.variant = "mc" val feature = generatedFeatureNewInstance() @@ -1614,7 +1614,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `test variant when assigned variant key is null`() { + fun `generatedFeatureNewInstance - assigned variant key is null - default variant assigned`() { variantManager.variant = null val feature = generatedFeatureNewInstance() @@ -1682,7 +1682,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `test variant when assigned variant key is not null`() { + fun `store - assigned variant key is not null - features enabled`() { variantManager.variant = "na" val feature = generatedFeatureNewInstance() @@ -1747,7 +1747,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `test feature disabled and forces variant when variant is null`() { + fun `generatedFeatureNewInstance - variant is null - feature disabled and forces variant`() { variantManager.variant = null val feature = generatedFeatureNewInstance() @@ -1788,7 +1788,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `test feature enabled and forces variant when variant is null`() { + fun `generatedFeatureNewInstance - variant is null - feature enabled and forces variant`() { variantManager.variant = null val feature = generatedFeatureNewInstance() @@ -1829,7 +1829,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `test feature does not force variant when already assigned`() { + fun `store - feature already assigned - does not force variant`() { variantManager.variant = "mc" val feature = generatedFeatureNewInstance() @@ -1870,7 +1870,7 @@ class ContributesRemoteFeatureCodeGeneratorTest { } @Test - fun `test rollout roll back`() { + fun `store - rollout and rollback - feature state transitions correctly`() { 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..0ade0a7c8a0b 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 - return correct value`() { 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 - throw 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..7b8d0f83daad 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 - enqueues 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..7c900d9d9ada 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 - return 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..4cfe91ff2038 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 `config - return correctly formatted json`() { whenever(mockFingerprintingBatteryRepository.fingerprintingBatteryEntity).thenReturn(FingerprintingBatteryEntity(json = config)) assertEquals("\"fingerprintingBattery\":$config", testee.config()) } @Test - fun whenGetPreferencesThenReturnNull() { + fun `preferences - return 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..7c27a4b37359 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 - return 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 - return true`() { assertTrue(testee.store(FEATURE_NAME_VALUE, JSON_STRING)) } @Test - fun whenFeatureNameMatchesFingerprintingBatteryThenUpdateAll() { + fun `store - feature name matches fingerprinting battery - update all`() { 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..e35d31662c0c 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 `config - return correctly formatted json`() { whenever(mockFingerprintingCanvasRepository.fingerprintingCanvasEntity).thenReturn(FingerprintingCanvasEntity(json = config)) assertEquals("\"fingerprintingCanvas\":$config", testee.config()) } @Test - fun whenGetPreferencesThenReturnNull() { + fun `preferences - return 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..e73caa4b6d9d 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 - return 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 - return true`() { assertTrue(testee.store(FEATURE_NAME_VALUE, JSON_STRING)) } @Test - fun whenFeatureNameMatchesFingerprintingCanvasThenUpdateAll() { + fun `store - feature name matches fingerprinting canvas - 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..d2e8c69a7ea7 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 `config - return correctly formatted json`() { whenever(mockFingerprintingHardwareRepository.fingerprintingHardwareEntity).thenReturn(FingerprintingHardwareEntity(json = config)) assertEquals("\"fingerprintingHardware\":$config", testee.config()) } @Test - fun whenGetPreferencesThenReturnNull() { + fun `preferences - return 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..0a421531c745 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 - return 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 - return true`() { assertTrue(testee.store(FEATURE_NAME_VALUE, JSON_STRING)) } @Test - fun whenFeatureNameMatchesFingerprintingHardwareThenUpdateAll() { + fun `store - feature name matches fingerprinting hardware - update all`() { 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..4c446cd34f7e 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 `config - get config - return correctly formatted json`() { whenever(mockFingerprintingScreenSizeRepository.fingerprintingScreenSizeEntity).thenReturn(FingerprintingScreenSizeEntity(json = config)) assertEquals("\"fingerprintingScreenSize\":$config", testee.config()) } @Test - fun whenGetPreferencesThenReturnNull() { + fun `preferences - return 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..b460e3e61f02 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 - return 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 - return true`() { assertTrue(testee.store(FEATURE_NAME_VALUE, JSON_STRING)) } @Test - fun whenFeatureNameMatchesFingerprintingScreenSizeThenUpdateAll() { + fun `store - feature name matches fingerprinting screen size - 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..1a5971bc5c9a 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 `config - return correctly formatted json`() { whenever(mockFingerprintingTemporaryStorageRepository.fingerprintingTemporaryStorageEntity) .thenReturn(FingerprintingTemporaryStorageEntity(json = config)) assertEquals("\"fingerprintingTemporaryStorage\":$config", testee.config()) } @Test - fun whenGetPreferencesThenReturnNull() { + fun `preferences - return 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..719617fa0da5 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 - return 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 - return true`() { assertTrue(testee.store(FEATURE_NAME_VALUE, JSON_STRING)) } @Test - fun whenFeatureNameMatchesFingerprintingTemporaryStorageThenUpdateAll() { + fun `store - feature name matches fingerprinting temporary storage - 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..e908485dc7b5 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 `init - no stored value - load empty JSON to memory`() = runTest { testee = RealFingerprintingBatteryRepository( @@ -59,7 +59,7 @@ class RealFingerprintingBatteryRepositoryTest { } @Test - fun whenInitializedAndHasStoredValueThenLoadStoredJsonToMemory() = + fun `RealFingerprintingBatteryRepository - initialized with stored value - load stored JSON to memory`() = runTest { whenever(mockFingerprintingBatteryDao.get()).thenReturn(fingerprintingBatteryEntity) testee = @@ -75,7 +75,7 @@ class RealFingerprintingBatteryRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - updateAll 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..b092c75de363 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 `init - no stored value - load empty JSON to memory`() = runTest { testee = RealFingerprintingCanvasRepository( @@ -59,7 +59,7 @@ class RealFingerprintingCanvasRepositoryTest { } @Test - fun whenInitializedAndHasStoredValueThenLoadStoredJsonToMemory() = + fun `init - has stored value - load stored json to memory`() = runTest { whenever(mockFingerprintingCanvasDao.get()).thenReturn(fingerprintingCanvasEntity) testee = @@ -75,7 +75,7 @@ class RealFingerprintingCanvasRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - updateAll 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..ac71776ddb8d 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 `RealFingerprintingHardwareRepository - no stored value - load empty JSON to memory`() = runTest { testee = RealFingerprintingHardwareRepository( @@ -59,7 +59,7 @@ class RealFingerprintingHardwareRepositoryTest { } @Test - fun whenInitializedAndHasStoredValueThenLoadStoredJsonToMemory() = + fun `RealFingerprintingHardwareRepository - initialized with stored value - load stored JSON to memory`() = runTest { whenever(mockFingerprintingHardwareDao.get()).thenReturn(fingerprintingHardwareEntity) testee = @@ -75,7 +75,7 @@ class RealFingerprintingHardwareRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - updateAll 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..385c740c6b1a 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 `init - no stored value - load empty JSON to memory`() = runTest { testee = RealFingerprintingScreenSizeRepository( @@ -59,7 +59,7 @@ class RealFingerprintingScreenSizeRepositoryTest { } @Test - fun whenInitializedAndHasStoredValueThenLoadStoredJsonToMemory() = + fun `init - has stored value - load stored json to memory`() = runTest { whenever(mockFingerprintingScreenSizeDao.get()).thenReturn(fingerprintingScreenSizeEntity) testee = @@ -75,7 +75,7 @@ class RealFingerprintingScreenSizeRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - updateAll 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..100a1a6009c6 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 `init - no stored value - load empty json to memory`() = runTest { testee = RealFingerprintingTemporaryStorageRepository( @@ -59,7 +59,7 @@ class RealFingerprintingTemporaryStorageRepositoryTest { } @Test - fun whenInitializedAndHasStoredValueThenLoadStoredJsonToMemory() = + fun `RealFingerprintingTemporaryStorageRepository - initialized with stored value - load stored JSON to memory`() = runTest { whenever(mockFingerprintingTemporaryStorageDao.get()).thenReturn(fingerprintingTemporaryStorageEntity) testee = @@ -75,7 +75,7 @@ class RealFingerprintingTemporaryStorageRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - updateAll 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..09e1d5a566c8 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 `init - random seed is set`() { assertFalse(testee.seed.isBlank()) } @Test - fun whenStoredNewSeedThenSeedIsRefreshed() { + fun `storeNewSeed - seed is 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..dd6792db974f 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 - 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..514bb6812837 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 - 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..9fc8964b3235 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 is empty - is null`() = runTest { assertNull(dao.get()) } @Test - fun whenModelIsInsertedThenGetIsNotNull() = runTest { + fun `insert - model - 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 update`() = 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..e7d180c5d3b9 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,43 +56,43 @@ class HttpsFalsePositivesDaoTest { } @Test - fun whenModelIsEmptyThenCountIsZero() = runTest { + fun `count - model is empty - is zero`() = runTest { assertEquals(0, dao.count()) } @Test - fun whenModelIsEmptyThenContainsDomainIsFalse() = runTest { + fun `contains - model is empty - false`() = runTest { assertFalse(dao.contains(domain)) } @Test - fun whenDomainInsertedThenContainsDomainIsTrue() = runTest { + fun `contains - domain inserted - true`() = runTest { dao.insertAll(listOf(HttpsFalsePositiveDomain(domain))) assertTrue(dao.contains(domain)) } @Test - fun whenDomainInsertedThenCountIsOne() = runTest { + fun `insertAll - domain inserted - count is one`() = runTest { dao.insertAll(listOf(HttpsFalsePositiveDomain(domain))) assertEquals(1, dao.count()) } @Test - fun whenSecondUniqueDomainInsertedThenCountIsTwo() = runTest { + fun `insertAll - second unique domain - count is two`() = runTest { dao.insertAll(listOf(HttpsFalsePositiveDomain(domain))) dao.insertAll(listOf(HttpsFalsePositiveDomain(anotherDomain))) assertEquals(2, dao.count()) } @Test - fun whenSecondDuplicateDomainInsertedThenCountIsOne() = runTest { + fun `insertAll - second duplicate domain - count is one`() = runTest { dao.insertAll(listOf(HttpsFalsePositiveDomain(domain))) dao.insertAll(listOf(HttpsFalsePositiveDomain(domain))) assertEquals(1, dao.count()) } @Test - fun whenAllUpdatedThenPreviousValuesAreReplaced() = runTest { + fun `updateAll - all updated - 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 `contains - all deleted - false`() = 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..6b2859a98dda 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 `onCreate - previously processed - 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..1713f4496606 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 - 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 - 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..17e5a6e1110c 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`() = 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..b16ffe4ef256 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 - return intent`() { val intent = globalActivityStarter.startIntent(context, TestParams("test")) assertNotNull(intent) @@ -60,7 +60,7 @@ class GlobalActivityStarterImplTest { } @Test - fun whenStartIntentWithDeeplinkNoParamsFindsActivityThenReturnIntent() { + fun `startIntent - deeplink no params finds activity - return intent`() { val intent = globalActivityStarter.startIntent(context, DeeplinkActivityParams("screenTest")) assertNotNull(intent) @@ -68,7 +68,7 @@ class GlobalActivityStarterImplTest { } @Test - fun whenStartIntentWithDeeplinkParamsFindsActivityThenReturnIntent() { + fun `startIntent - deeplink params finds activity - return intent`() { 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 - not found activity - throw`() { globalActivityStarter.start(context, NotFoundParams) } @Test(expected = IllegalArgumentException::class) - fun whenStartNotFoundDeeplinkActivityThenThrow() { + fun `start - not found deeplink activity - throw IllegalArgumentException`() { globalActivityStarter.start(context, notFoundDeeplinkParams) } @Test - fun whenStartWithParamsFindsActivityThenSucceeds() { + fun `start - with params finds activity - succeeds`() { val context: Context = mock() globalActivityStarter.start(context, TestParams("test")) @@ -94,7 +94,7 @@ class GlobalActivityStarterImplTest { } @Test - fun whenStartWithDeeplinkParamsArgumentsFindsActivityThenSucceeds() { + fun `start - deeplink params arguments finds activity - succeeds`() { val context: Context = mock() globalActivityStarter.start(context, DeeplinkActivityParams("screenTest", jsonArguments = "{\"value\": \"test\"}")) @@ -102,7 +102,7 @@ class GlobalActivityStarterImplTest { } @Test - fun whenStartWithDeeplinkNoParamsArgumentsFindsActivityThenSucceeds() { + fun `start - deeplink with no params - finds activity and succeeds`() { 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..a70328eae83b 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 - returns vpn tunnel config and stores 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 millis`() = 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 has been 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 - with restart - reset enabled time in millis and server details`() = runTest { assertEquals( Result.success(Unit), wgVpnNetworkStack.onStopVpn(RESTART), @@ -229,7 +229,7 @@ class WgVpnNetworkStackTest { } @Test - fun whenWgTunnelDataProviderThrowsExceptionThenOnPrepareShouldReturnFailure() = runTest { + fun `onPrepareVpn - wgTunnel data provider throws exception - 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 - wgProtocol startWg returns failure - 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 returns success - should return 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..a9265fe32c52 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 - NetP 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 - NetP registered and 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 - NetP registered and 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 - NetP enabled and cohort not 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 - NetP enabled and 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..e7e5eb3833a0 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 - drop NetP pixel URL`() { 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 is 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 and pixel URL 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..8efb1011cd62 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 NetP 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 `intercept - servers call - 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 `intercept - register call - 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 `intercept - internal build - add auth and debug headers`() { whenever(appBuildConfig.flavor).thenReturn(BuildFlavor.INTERNAL) val chain = FakeChain("https://staging.netp.duckduckgo.com/servers") @@ -95,7 +95,7 @@ class NetpControllerRequestInterceptorTest { } @Test - fun whenInterceptServersCallPlayBuildThenAddAuthHeader() { + fun `intercept - play build - add auth header`() { whenever(appBuildConfig.flavor).thenReturn(BuildFlavor.PLAY) val chain = FakeChain("https://staging.netp.duckduckgo.com/servers") @@ -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 is not NetP and flavor is 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 netp 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..f791b5ed5d44 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 `registerPublicKey - production - returns first server`() = runTest { assertEquals( WgServerData( serverName = "egress.usw.1", @@ -81,7 +81,7 @@ class RealWgServerApiTest { } @Test - fun whenRegisterInInternalAndServerSelectedThenReturnSelectedServer() = runTest { + fun `registerPublicKey - internal and server selected - 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 - internal and server selected with no server 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 - return first server`() = runTest { internalWgServerDebugProvider.selectedServer = "egress.wrong" assertEquals( @@ -134,14 +134,14 @@ class RealWgServerApiTest { } @Test - fun whenRegisterInProductionThenDoNotCacheServers() = runTest { + fun `registerPublicKey - production - do not cache servers`() = runTest { productionApi.registerPublicKey("testpublickey") assertTrue(internalWgServerDebugProvider.cachedServers.isEmpty()) } @Test - fun whenInternalFlavorGetWgServerDataThenStoreReturnedServers() = runTest { + fun `getWgServerData - internal flavor - store returned servers`() = runTest { whenever(appBuildConfig.flavor).thenReturn(INTERNAL) internalApi.registerPublicKey("testpublickey") @@ -149,21 +149,21 @@ class RealWgServerApiTest { } @Test - fun whenRegisterInProductionThenDownloadGeoswitchingData() = runTest { + fun `registerPublicKey - production - download geoswitching data`() = runTest { productionApi.registerPublicKey("testpublickey") verify(netpEgressServersProvider).updateServerLocationsAndReturnPreferred() } @Test - fun whenRegisterInInternalThenDownloadGeoswitchingData() = runTest { + fun `registerPublicKey - internal - 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 - user preferred location set - request for 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 - 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..742d629a2498 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 `createWgConfig - returns WgTunnel data`() = 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 `createWgConfig - error - log error`() = runTest { whenever(wgServerApi.registerPublicKey(any(), isNull())).thenReturn(serverData) assertNull(wgTunnel.createWgConfig(keys).getOrNull()) } @Test - fun withNoKeysEstablishErrorThenLogError() = runTest { + fun `createWgConfig - no keys - log error`() = runTest { whenever(wgServerApi.registerPublicKey(any(), isNull())).thenReturn(serverData) assertNull(wgTunnel.createWgConfig().getOrNull()) } @Test - fun whenTunnelIsMarkedAsUnhealthyAndCreateWgConfigThenUpdateStateToFailureRecovery() = runTest { + fun `createWgConfig - tunnel marked as unhealthy - 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 `createAndSetWgConfig - tunnel marked as unhealthy - reset tunnel health`() = runTest { whenever(wgServerApi.registerPublicKey(any(), isNull())).thenReturn(serverData) wgTunnel.markTunnelUnhealthy() @@ -108,7 +108,7 @@ class WgTunnelTest { } @Test - fun whenTunnelIsMarkedAsUnhealthyTheHealthyAndCreateWgConfigThenResetTunnelHealth() = runTest { + fun `createWgConfig - tunnel marked unhealthy then healthy - 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..7b541469c61b 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 - getLatency - correct average`() = runTest { connectionClassManager.addLatency(100.0) assertEquals(100.0, connectionClassManager.getLatencyAverage(), 0.1) } @Test - fun addLatencyThenGetConnectionQuality() = runTest { + fun `addLatency - various latencies - getConnectionQuality`() = 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..0c32448acb88 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 - connection 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..043f83e268bc 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 - returns 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 - 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 - return 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 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..bd4e1896ffe9 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 - return 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 is protected only - return correct viewState`() = runTest { whenever(systemAppsExclusionRepository.getAvailableCategories()).thenReturn(emptySet()) testee.applyAppsFilter(AppsFilter.PROTECTED_ONLY) @@ -156,7 +156,7 @@ class NetpAppExclusionListViewModelTest { } @Test - fun whenFilterIsUnprotectedOnlyAndGetAppsThenReturnCorrectViewState() = runTest { + fun `getApps - filter is unprotected only - 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 in 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 - return 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 - changed to protected - 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 - to unprotected - 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 - only 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 - 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`() = 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 `onPause - changes to exclusion list - restart VPN`() = runTest { testee.onResume(mock()) exclusionListFlow.emit( listOf( @@ -349,7 +349,7 @@ class NetpAppExclusionListViewModelTest { } @Test - fun whenUserMadeNoChangesToExclusionListThenOnPauseDoNothing() = runTest { + fun `onPause - no changes to exclusion list - do nothing`() = runTest { testee.onResume(mock()) testee.onPause(mock()) @@ -359,7 +359,7 @@ class NetpAppExclusionListViewModelTest { } @Test - fun whenExclusionListResetToOriginalThenOnPauseDoNothing() = runTest { + fun `onPause - exclusion list 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 `onSystemAppCategoryStateChanged - warning shown and category set to disabled - exclude category`() = runTest { whenever(systemAppsExclusionRepository.hasShownWarning()).thenReturn(true) val category = NetpExclusionListSystemAppCategory( @@ -422,7 +422,7 @@ class NetpAppExclusionListViewModelTest { } @Test - fun whenWarningShownAndCategorySetToEnabledOnSystemAppCategoryStateChangedThenIncludeCategory() = runTest { + fun `onSystemAppCategoryStateChanged - warning shown and category set to enabled - 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..e4c931179eaa 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 - server changed - set config and refresh NetP`() = 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 - tunnel address changed - set config and refresh NetP`() = 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 - 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 - called twice with 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 address - 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..8ba53979173c 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 - enabled - emit CheckVPNPermission command`() = runTest { whenever(externalVpnDetector.isExternalVpnDetected()).thenReturn(false) testee.commands().test { @@ -163,21 +163,21 @@ class NetworkProtectionManagementViewModelTest { } @Test - fun whenOnStartVpnThenRegisterFeature() = runTest { + fun `onStartVpn - register feature`() = runTest { testee.onStartVpn() verify(networkProtectionState).start() } @Test - fun whenOnNetpToggleClickedToDisabledThenUnregisterFeature() = runTest { + fun `onNetpToggleClicked - disabled - unregister feature`() = runTest { testee.onNetpToggleClicked(false) verify(networkProtectionState).clearVPNConfigurationAndStop() } @Test - fun whenExternalVPNDetectedAndOnNetpToggleClickedTrueThenEmitShowVpnConflictDialog() = runTest { + fun `onNetpToggleClicked - external VPN detected and toggle true - 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 and toggle true - 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 - vpn state is enabling - viewState emits connecting`() = runTest { whenever(vpnStateMonitor.getStateFlow(NetPVpnFeature.NETP_VPN)).thenReturn( flowOf( VpnState( @@ -262,7 +262,7 @@ class NetworkProtectionManagementViewModelTest { } @Test - fun whenVpnStateIsDisabledThenViewStateEmitsDisconnected() = runTest { + fun `viewState - VPN state disabled - emits disconnected`() = runTest { whenever(vpnStateMonitor.getStateFlow(NetPVpnFeature.NETP_VPN)).thenReturn( flowOf( VpnState( @@ -295,7 +295,7 @@ class NetworkProtectionManagementViewModelTest { } @Test - fun whenEnabledAndServerDetailsAvailableThenEmitViewStateConnectedWithDetails() = runTest { + fun `viewState - enabled and server details available - emit viewState 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 viewState - 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 time string`() { assertEquals("00:00:00", 0L.toDisplayableTimerText()) } @Test - fun whenTimeDifferenceHasHoursOnlyThenSetMinsAndSecondsToDefault() { + fun `toDisplayableTimerText - time difference has hours only - set mins and seconds to default`() { assertEquals("27:00:00", 97_200_000L.toDisplayableTimerText()) } @Test - fun whenTimeDifferenceHasMinsOnlyThenSetHoursAndSecondsToDefault() { + fun `toDisplayableTimerText - time difference has mins only - set hours and seconds to default`() { assertEquals("00:38:00", 2_280_000L.toDisplayableTimerText()) } @Test - fun whenTimeDifferenceHasSecondsOnlyThenSetHoursAndMinutesToDefault() { + fun `toDisplayableTimerText - time difference has seconds only - set hours and minutes to default`() { assertEquals("00:00:32", 32_000L.toDisplayableTimerText()) } @Test - fun whenTimeDifferenceThenSetHoursAndMinutesToDefault() { + fun `toDisplayableTimerText - time difference - 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 is enabling and none stop reason - none`() { assertEquals(None, testee.getAlertState(ENABLING, null, AlwaysOnState.DEFAULT)) } @Test - fun whenVpnStateIsEnabledAndAlwaysOnStateIsLockdownThenAlertStateIsShowAlwaysOnLockdownEnabled() { + fun `getAlertState - VPN enabled and always on lockdown - show always on lockdown enabled`() { assertEquals(ShowAlwaysOnLockdownEnabled, testee.getAlertState(ENABLED, null, AlwaysOnState.ALWAYS_ON_LOCKED_DOWN)) } @Test - fun whenNotReconnectingThenAlertStateIsNone() { + fun `getAlertState - not reconnecting - alert state is none`() { assertEquals(None, testee.getAlertState(DISABLED, UNKNOWN, AlwaysOnState.DEFAULT)) } @Test - fun whenStopReasonIsRevokedAndNotReconnectingThenAlertStateIsShowRevoked() { + fun `getAlertState - stop reason is revoked and not reconnecting - show revoked`() { assertEquals(ShowRevoked, testee.getAlertState(DISABLED, REVOKED, AlwaysOnState.DEFAULT)) } @Test - fun whenOnAlwaysOnOpenSettingsClickedFromPromotionThenEmitOpenVPNSettingsCommandAndEmitPixels() = runTest { + fun `onOpenSettingsFromAlwaysOnPromotionClicked - emit OpenVPNSettings command and emit pixels`() = runTest { testee.commands().test { testee.onOpenSettingsFromAlwaysOnPromotionClicked() assertEquals(OpenVPNSettings, this.awaitItem()) @@ -438,7 +438,7 @@ class NetworkProtectionManagementViewModelTest { } @Test - fun whenOnAlwaysOnOpenSettingsClickedFromLockdownThenEmitOpenVPNSettingsCommandAndEmitPixels() = runTest { + fun `onOpenSettingsFromAlwaysOnLockdownClicked - emit OpenVPN settings command and emit 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 and 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..56aba918e227 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 - vpn manually stopped - do not show snooze`() = 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 - manually stopped with snooze but 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 `onVpnStopped - vpn snoozed - 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..c86757cf593d 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 protection disabled - return 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 - netP disabled - return 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 - return 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 - network protection 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 protection disabled - return false`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(false) whenever(networkProtectionState.isEnabled()).thenReturn(false) assertFalse(plugin.isActive()) } @Test - fun isActiveNetPEnabledReturnTrue() = runTest { + fun `isActive - net protection enabled - return true`() = runTest { whenever(appTrackingProtection.isEnabled()).thenReturn(false) whenever(networkProtectionState.isEnabled()).thenReturn(true) assertTrue(plugin.isActive()) } @Test - fun isActiveNetPEnabledAppTPEnabledReturnFalse() = runTest { + fun `isActive - netP enabled and appTP 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..b4c51afcc4c2 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 `NetworkProtectionPixelNames - all 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..ca92867b22d1 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 `onSearchRetentionAtbRefreshed - search retention enabled - report enabled`() = 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..74fa10fe05b2 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 - 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 - called twice - fire count pixel twice and daily pixel once`() { testee.reportErrorWgInvalidState() testee.reportErrorWgInvalidState() @@ -84,7 +84,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportErrorWgBackendCantStartIsCalledTwiceThenFireCountPixelTwiceAndDailyPixelOnce() { + fun `reportErrorWgBackendCantStart - 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 - called twice - 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 `reportEnabled - 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 - cohort at boundary - do not coalesce`() { 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 - past the week boundary - coalesce cohort`() { 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 - called twice - fire count pixel twice and daily pixel once`() { testee.reportWireguardLibraryLoadFailed() testee.reportWireguardLibraryLoadFailed() @@ -175,7 +175,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportRekeyCompletedCalledTwiceThenFireDailyPixelOnce() { + fun `reportRekeyCompleted - called twice - fire daily pixel once`() { testee.reportRekeyCompleted() testee.reportRekeyCompleted() @@ -184,7 +184,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportVpnConflictDialogShownCalledTwiceThenFireDailyPixelOnce() { + fun `reportVpnConflictDialogShown - called twice - fire daily pixel once`() { testee.reportVpnConflictDialogShown() testee.reportVpnConflictDialogShown() @@ -193,7 +193,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportAlwaysOnConflictDialogShownCalledTwiceThenFireDailyPixelOnce() { + fun `reportAlwaysOnConflictDialogShown - called twice - fire daily pixel once`() { testee.reportAlwaysOnConflictDialogShown() testee.reportAlwaysOnConflictDialogShown() @@ -202,7 +202,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportAlwaysOnPromotionDialogShownCalledTwiceThenFireDailyPixelOnce() { + fun `reportAlwaysOnPromotionDialogShown - called twice - fire daily pixel once`() { testee.reportAlwaysOnPromotionDialogShown() testee.reportAlwaysOnPromotionDialogShown() @@ -211,7 +211,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportAlwaysOnLockdownDialogShownCalledTwiceThenFireDailyPixelOnce() { + fun `reportAlwaysOnLockdownDialogShown - called twice - fire daily pixel once`() { testee.reportAlwaysOnLockdownDialogShown() testee.reportAlwaysOnLockdownDialogShown() @@ -220,7 +220,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportOpenSettingsFromAlwaysOnPromotionCalledTwiceThenFireDailyPixelOnce() { + fun `reportOpenSettingsFromAlwaysOnPromotion - called twice - fire daily pixel once`() { testee.reportOpenSettingsFromAlwaysOnPromotion() testee.reportOpenSettingsFromAlwaysOnPromotion() @@ -229,7 +229,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportOpenSettingsFromAlwaysOnLockdownCalledTwiceThenFireDailyPixelOnce() { + fun `reportOpenSettingsFromAlwaysOnLockdown - called twice - fire daily pixel once`() { testee.reportOpenSettingsFromAlwaysOnLockdown() testee.reportOpenSettingsFromAlwaysOnLockdown() @@ -238,7 +238,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportExclusionListShownCalledTwiceThenFireDailyPixelOnce() { + fun `reportExclusionListShown - called twice - fire daily pixel once`() { testee.reportExclusionListShown() testee.reportExclusionListShown() @@ -247,7 +247,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportAppAddedToExclusionListCalledTwiceThenFirePixelTwice() { + fun `reportAppAddedToExclusionList - called twice - fire pixel twice`() { testee.reportAppAddedToExclusionList() testee.reportAppAddedToExclusionList() @@ -255,7 +255,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportAppRemovedFromExclusionListCalledTwiceThenFirePixelTwice() { + fun `reportAppRemovedFromExclusionList - called twice - fire pixel twice`() { testee.reportAppRemovedFromExclusionList() testee.reportAppRemovedFromExclusionList() @@ -263,7 +263,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportSkippedReportAfterExcludingAppCalledTwiceThenFireDailyPixelOnce() { + fun `reportSkippedReportAfterExcludingApp - called twice - fire daily pixel once`() { testee.reportSkippedReportAfterExcludingApp() testee.reportSkippedReportAfterExcludingApp() @@ -272,7 +272,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportExclusionListRestoreDefaultsCalledTwiceThenFireDailyPixelOnce() { + fun `reportExclusionListRestoreDefaults - called twice - fire daily pixel once`() { testee.reportExclusionListRestoreDefaults() testee.reportExclusionListRestoreDefaults() @@ -281,7 +281,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportExclusionListLaunchBreakageReportCalledTwiceThenFireDailyPixelOnce() { + fun `reportExclusionListLaunchBreakageReport - called twice - fire daily pixel once`() { testee.reportExclusionListLaunchBreakageReport() testee.reportExclusionListLaunchBreakageReport() @@ -290,7 +290,7 @@ class RealNetworkProtectionPixelTest { } @Test - fun whenReportFaqsShownCalledTwiceThenFireDailyPixelOnce() { + fun `reportFaqsShown - 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..ab62a5e6cdc1 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 - do not rekey in production`() = 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 - do not 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 is 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 - no 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 - rekey performed`() = 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 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 `doRekey - production build - 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 - no 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..2381ae54ac39 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 `onActivityResumed - VPN state is inactive - don't show dialogs`() { coroutineTestRule.testScope.launch { whenever(netpSubscriptionManager.getVpnStatus()).thenReturn(INACTIVE) @@ -79,7 +79,7 @@ class NetpVpnAccessRevokedDialogMonitorTest { } @Test - fun whenVPNStateIsActiveThenDontShowDialogs() { + fun `onActivityResumed - VPN state is active - don't show dialogs`() { coroutineTestRule.testScope.launch { whenever(netpSubscriptionManager.getVpnStatus()).thenReturn(ACTIVE) @@ -91,7 +91,7 @@ class NetpVpnAccessRevokedDialogMonitorTest { } @Test - fun whenVPNEnabledAndStateIsActiveThenDontShowDialogs() { + fun `onActivityResumed - VPN enabled and state is active - don't 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 `onActivityResumed - VPN enabled and state is inactive - don't 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 `onActivityResumed - VPN state is signed out - don't show dialogs`() { coroutineTestRule.testScope.launch { whenever(netpSubscriptionManager.getVpnStatus()).thenReturn(SIGNED_OUT) @@ -129,7 +129,7 @@ class NetpVpnAccessRevokedDialogMonitorTest { } @Test - fun whenVPNEnabledAndStateIsSignedOutThenDontShowDialogs() { + fun `onActivityResumed - VPN enabled and signed out - don't 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 `onActivityResumed - 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 `onActivityResumed - VPN enabled state expired - 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 `onActivityResumed - VPN not onboarded and state is expired - don't 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 `onActivityResumed - VPN enabled not onboarded and state is expired - don't 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..e5b55b1993f7 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 - emit 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 - emit correct state`() = 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 - emits correct state`() = 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 disable on call not enabled - do not restart vpn`() = runTest { whenever(vpnDisableOnCall.isEnabled()).thenReturn(false) viewModel.onStart(mock()) verify(networkProtectionState, never()).restart() } @Test - fun onPauseDoNotRestartVpnWhenNothingChanges() = runTest { + fun `onPause - nothing changes - do not restart VPN`() = runTest { viewModel.onExcludeLocalRoutes(false) viewModel.onPause(mock()) @@ -133,21 +133,21 @@ class NetPVpnSettingsViewModelTest { } @Test - fun onPauseRestartVpnWhenSettingChanged() = runTest { + fun `onPause - setting changed - restart VPN`() = 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..f63f76464b23 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 - valid and invalid codes - correct emoji returned`() { 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..7a82d0e6a03d 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 - viewModel initialized - viewState emits 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 - viewState 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 - preferred country and city changed - 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 - chosen preferred country and city are same - stored data should be 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 `onCountrySelected - 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 `onCountrySelected - 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 - NetP 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 and preferred location changed to nearest - 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 and preferred location changed to custom - 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 `onCountrySelected - 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..2c4bff12af44 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 only 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 `getDisplayablePreferredLocation - 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 - return city and country`() = 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 `getDisplayablePreferredLocation - 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 `getDisplayablePreferredLocation - 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..b19dcd2ac3bd 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 - download date - parse and replace stored locations`() = runTest { assertNull(testee.updateServerLocationsAndReturnPreferred()) val expectedResult = listOf( NetPGeoswitchingLocation( @@ -74,7 +74,7 @@ class RealNetpEgressServersProviderTest { } @Test - fun whenUpdateLocationsUpdateUserPreferredIfNotPresent() = runTest { + fun `updateServerLocationsAndReturnPreferred - user preferred location not present - updates user preferred location`() = runTest { netPGeoswitchingRepository.setUserPreferredLocation( UserPreferredLocation( countryCode = "se", @@ -104,7 +104,7 @@ class RealNetpEgressServersProviderTest { } @Test - fun whenUpdateLocationsUpdateUserPreferredIfNotPresentGoneCity() = runTest { + fun `updateServerLocationsAndReturnPreferred - user preferred location not present - update user preferred`() = runTest { netPGeoswitchingRepository.setUserPreferredLocation( UserPreferredLocation( countryCode = "se", @@ -134,7 +134,7 @@ class RealNetpEgressServersProviderTest { } @Test - fun whenUpdateLocationsUpdateUserPreferredIfNotPresentGoneCountry() = runTest { + fun `updateServerLocationsAndReturnPreferred - user preferred location not present - returns null`() = runTest { netPGeoswitchingRepository.setUserPreferredLocation( UserPreferredLocation( countryCode = "zz", @@ -164,7 +164,7 @@ class RealNetpEgressServersProviderTest { } @Test - fun whenUpdateLocationsUpdateUserPreferredIfNotPresentGoneCountryAndCity() = runTest { + fun `updateServerLocationsAndReturnPreferred - user preferred not present - gone country and city`() = runTest { netPGeoswitchingRepository.setUserPreferredLocation( UserPreferredLocation( countryCode = "zz", @@ -194,7 +194,7 @@ class RealNetpEgressServersProviderTest { } @Test - fun whenUpdateLocationsKeepUserPreferredIfPresent() = runTest { + fun `updateServerLocationsAndReturnPreferred - user preferred location present - keeps user preferred`() = runTest { netPGeoswitchingRepository.setUserPreferredLocation( UserPreferredLocation( countryCode = "se", @@ -224,7 +224,7 @@ class RealNetpEgressServersProviderTest { } @Test - fun whenGetDownloadedDataThenReturnDataFromRepository() = runTest { + fun `getServerLocations - 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..25e1469c7451 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 `enabledTimeInMillis - no enabled time millis - return default value`() { assertEquals(-1, testee.enabledTimeInMillis) } @Test - fun whenSettingEnabledTimeMillisThenPutLongInPrefs() { + fun `enabledTimeInMillis - set - 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..886f6e279f47 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 - return 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, vpn expired, netp disabled - return 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 - return 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, VPN inactive, NETP enabled - return 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 - return 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 - return 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, netp disabled - emits 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, netp disabled - emits 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, netp disabled - emits 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, vpn inactive, netp enabled - 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 - vpn expired and netp enabled - emit not unlocked and reset vpn state`() = runTest { whenever(netpSubscriptionManager.vpnStatus()).thenReturn(flowOf(EXPIRED)) whenever(networkProtectionState.isEnabled()).thenReturn(true) testee.getStateFlow().test { @@ -175,7 +175,7 @@ class NetworkProtectionAccessStateImplTest { } @Test - fun whenSubscriptionsEnabledAndVpnSignedOutAndNetpEnabledThenReturnFlowEmitNotUnlockedAndResetVpnState() = runTest { + fun `getStateFlow - subscriptions enabled, vpn signed out, netp enabled - emit not unlocked and reset vpn state`() = runTest { whenever(netpSubscriptionManager.vpnStatus()).thenReturn(flowOf(SIGNED_OUT)) 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..20732b6b6246 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 - NetP is not unlocked - network protection entry state shows 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 - NetP in beta but terms not accepted - entry state 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 - NetP 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) @@ -131,7 +131,7 @@ class ProSettingNetPViewModelTest { } @Test - fun whenNetPStateIsInBetaAndNotOnboardedAndEnabledThenNetPEntryStateShouldCorrectShowState() = runTest { + fun `onStart - NetP in beta, not onboarded, enabled - correct entry state`() = 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 - NetP 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 - NetP state in beta and connecting - correct show 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 - NetP in beta and disabled - correct show 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..dcdd7cd1f56c 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 `defaultValues - correct toggles enabled`() { 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..4caaf9e7b74e 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 - delegates to NetPExclusionListDao`() { testee.getManualAppExclusionList() verify(exclusionListDao).getManualAppExclusionList() } @Test - fun whenGetManualAppExclusionListFlowThenDelegateToNetPExclusionListDao() { + fun `getManualAppExclusionListFlow - delegate to NetPExclusionListDao`() { 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 NetPExclusionListDao`() { testee.manuallyExcludeApp("test") verify(exclusionListDao).insertIntoManualAppExclusionList(NetPManuallyExcludedApp(packageId = "test", isProtected = false)) } @Test - fun whenManuallyExcludeAppsThenDelegateToNetPExclusionListDao() { + fun `manuallyExcludeApps - delegate to NetPExclusionListDao`() { testee.manuallyExcludeApps( listOf( "test1", @@ -87,14 +87,14 @@ class RealNetPExclusionListRepositoryTest { } @Test - fun whenManuallyEnableAppThenDelegateToNetPExclusionListDao() { + fun `manuallyEnableApp - delegate to NetPExclusionListDao`() { testee.manuallyEnableApp("test") verify(exclusionListDao).insertIntoManualAppExclusionList(NetPManuallyExcludedApp(packageId = "test", isProtected = true)) } @Test - fun whenRestoreDefaultProtectedListThenDelegateToNetPExclusionListDao() { + fun `restoreDefaultProtectedList - delegates to NetPExclusionListDao`() { 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..144cb0d81b96 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 - return true`() = runTest { assertTrue(testee.download() is Success) } @Test - fun whenDownloadIsSuccessfulThenPersistPrivacyConfigCalled() = + fun `download - successful - persistPrivacyConfig called`() = 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..abc22dea044c 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 `signature - hash is null - returns feature name`() { val expected = pluginPoint.getPlugins().sumOf { it.featureName.hashCode() } assertEquals(expected, pluginPoint.signature()) } @Test - fun whenHashIsNotNullSignatureReturnsHash() { + fun `signature - 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 `signature - different plugin points - return 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 - plugin matches feature name - store called`() = runTest { testee.persistPrivacyConfig(getJsonPrivacyConfig()) @@ -156,7 +156,7 @@ class RealPrivacyConfigPersisterTest { } @Test - fun whenPersistPrivacyConfigAndVersionIsLowerThanPreviousOneStoredThenDoNothing() = + fun `persistPrivacyConfig - version is lower than previous one - 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 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 - 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 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 is higher - 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 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..fc0a4e36a078 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 - return 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 - return 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 `store - feature name matches amp links - 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..c2fe92942dd7 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 - domain in user allow list - return 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 - extracted URL 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..f942ed01f3b5 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 - return 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 - return 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 - store 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..087c95a09b80 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 - domain listed in exceptions - return true`() { givenThereAreExceptions() assertTrue(testee.isAnException("http://www.example.com")) } @Test - fun whenIsAnExceptionWithSubdomainAndDomainIsListedInTheExceptionsListThenReturnTrue() { + fun `isAnException - subdomain and domain listed in exceptions - return true`() { givenThereAreExceptions() assertTrue(testee.isAnException("http://test.example.com")) } @Test - fun whenIsAnExceptionAndDomainIsNotListedInTheExceptionsListThenReturnFalse() { + fun `isAnException - domain not listed in exceptions - return false`() { whenever(mockContentBlockingRepository.exceptions).thenReturn(CopyOnWriteArrayList()) assertFalse(testee.isAnException("http://test.example.com")) } @Test - fun whenIsAnExceptionAndDomainIsInTheUnprotectedTemporaryListThenReturnTrue() { + fun `isAnException - domain in unprotected temporary list - return 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 - feature is disabled - return 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..eacf2aab4030 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 - return 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 - return 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 - 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..1e30a62aaf91 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 returned`() { val url = "https://open.spotify.com" assertFalse(testee.isDrmAllowedForUrl(url)) } @Test - fun whenIsDrmAllowedForUrlAndIsInUserAllowListThenTrueIsReturned() { + fun `isDrmAllowedForUrl - in user allow list - true returned`() { giveFeatureIsEnabled() givenUrlIsNotInExceptionList() givenUriIsInUserAllowList() @@ -78,7 +78,7 @@ class RealDrmTest { } @Test - fun whenIsDrmAllowedForUrlAndIsInUnprotectedTemporaryThenTrueIsReturned() { + fun `isDrmAllowedForUrl - in unprotected temporary - true is 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..1fccb59c6278 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 `config - return correctly formatted json`() { whenever(mockGpcRepository.gpcContentScopeConfig).thenReturn(config) assertEquals("\"gpc\":$config", testee.config()) } @Test - fun whenGetPreferencesThenReturnCorrectlyFormattedJsonWhenGpcIsEnabled() { + fun `preferences - GPC enabled - correctly formatted JSON`() { whenever(mockGpcRepository.isGpcEnabled()).thenReturn(true) assertEquals(testee.preferences(), "\"globalPrivacyControlValue\":true") } @Test - fun whenGetPreferencesThenReturnCorrectlyFormattedJsonWhenGpcIsDisabled() { + fun `preferences - 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..a83f1c272ba0 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 - return 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 - return 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 - feature name matches Gpc - 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..0109cab79688 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 - isGpcEnabled called`() { testee.isEnabled() verify(mockGpcRepository).isGpcEnabled() } @Test - fun whenEnableGpcThenEnableGpcCalled() { + fun `enableGpc - enableGpc called`() { testee.enableGpc() verify(mockGpcRepository).enableGpc() } @Test - fun whenDisableGpcThenDisableGpcCalled() { + fun `disableGpc - disableGpc called`() { testee.disableGpc() verify(mockGpcRepository).disableGpc() } @Test - fun whenGetHeadersIfFeatureAndGpcAreEnabledAndUrlIsInExceptionsThenReturnEmptyMap() { + fun `getHeaders - feature and GPC enabled and 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 and URL not in exceptions - return 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 - return 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 enabled and URL not in exceptions - 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 and URL in exceptions - return false`() { givenFeatureAndGpcAreEnabled() assertFalse(testee.canUrlAddHeaders(EXCEPTION_URL, emptyMap())) } @Test - fun whenCanUrlAddHeadersIfFeatureAndGpcAreEnabledAndAndUrlIsInConsumersListsAndHeaderAlreadyExistsThenReturnFalse() { + fun `canUrlAddHeaders - feature and GPC enabled, URL in consumer lists, header exists - return false`() { givenFeatureAndGpcAreEnabled() assertFalse( @@ -129,21 +129,21 @@ class RealGpcTest { } @Test - fun whenCanUrlAddHeadersIfFeatureAndGpcAreEnabledAndAndUrlIsInConsumersListAndHeaderDoNotExistsThenReturnTrue() { + fun `canUrlAddHeaders - feature and GPC enabled, URL in consumers list, header does not exist - return true`() { givenFeatureAndGpcAreEnabled() assertTrue(testee.canUrlAddHeaders(VALID_CONSUMER_URL, emptyMap())) } @Test - fun whenCanUrlAddHeadersIfFeatureAndGpcAreEnabledAndAndUrlIsInNotInConsumersListAndHeaderDoNotExistsThenReturnFalse() { + fun `canUrlAddHeaders - feature and GPC enabled, URL not in consumers list, header does not exist - return false`() { givenFeatureAndGpcAreEnabled() assertFalse(testee.canUrlAddHeaders("test.com", emptyMap())) } @Test - fun whenCanUrlAddHeadersIfFeatureAndGpcAreEnabledAndUrlIsInConsumersButInTheExceptionListThenReturnFalse() { + fun `canUrlAddHeaders - feature and GPC enabled, URL in consumers but in exception list - return 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, GPC enabled, URL in consumer list, header does not exist - return false`() { givenFeatureIsNotEnabledButGpcIsEnabled() assertFalse(testee.canUrlAddHeaders(VALID_CONSUMER_URL, emptyMap())) } @Test - fun whenCanUrlAddHeadersIfFeatureIsEnabledAndGpcIsNotEnabledAndAndUrlIsInConsumersListAndHeaderDoNotExistsThenReturnFalse() { + fun `canUrlAddHeaders - feature enabled, Gpc not enabled, URL in consumer list, header does not exist - return false`() { givenFeatureIsEnabledButGpcIsNot() assertFalse(testee.canUrlAddHeaders(VALID_CONSUMER_URL, emptyMap())) } @Test - fun whenCanGpcBeUsedByUrlIfFeatureAndGpcAreEnabledAnUrlIsNotAnExceptionThenReturnTrue() { + fun `canGpcBeUsedByUrl - feature and GPC enabled, URL not an exception - returns true`() { givenFeatureAndGpcAreEnabled() assertTrue(testee.canGpcBeUsedByUrl("test.com")) } @Test - fun whenCanGpcBeUsedByUrlIfFeatureAndGpcAreEnabledAnUrlIsAnExceptionThenReturnFalse() { + fun `canGpcBeUsedByUrl - feature and Gpc enabled and URL is an exception - return false`() { givenFeatureAndGpcAreEnabled() assertFalse(testee.canGpcBeUsedByUrl(EXCEPTION_URL)) } @Test - fun whenCanGpcBeUsedByUrlIfFeatureIsEnabledAndGpcIsNotEnabledAnUrlIsNotAnExceptionThenReturnFalse() { + fun `canGpcBeUsedByUrl - feature enabled and Gpc not enabled and url not exception - return false`() { givenFeatureIsEnabledButGpcIsNot() assertFalse(testee.canGpcBeUsedByUrl("test.com")) } @Test - fun whenCanGpcBeUsedByUrlIfFeatureIsNotEnabledAndGpcIsEnabledAnUrlIsNotAnExceptionThenReturnFalse() { + fun `canGpcBeUsedByUrl - feature not enabled and Gpc enabled and URL not exception - return false`() { givenFeatureIsNotEnabledButGpcIsEnabled() assertFalse(testee.canGpcBeUsedByUrl("test.com")) } @Test - fun whenCanGpcBeUsedByUrlIfFeatureAndGpcAreEnabledAnUrlIsInUnprotectedTemporaryThenReturnFalse() { + fun `canGpcBeUsedByUrl - feature and Gpc enabled and URL in unprotected temporary - return false`() { givenFeatureAndGpcAreEnabled() whenever(mockUnprotectedTemporary.isAnException(VALID_CONSUMER_URL)).thenReturn(true) @@ -203,7 +203,7 @@ class RealGpcTest { } @Test - fun whenIsExceptionCalledAndDomainIsInUserAllowListThenReturnTrue() { + fun `isAnException - domain in user allow list - return 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..859d00694a24 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 - return 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 - store 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 - feature name matches https - 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..5e2d36a5cdd0 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 - domain listed in exceptions - return true`() { givenThereAreExceptions() assertTrue(testee.isAnException("http://www.example.com")) } @Test - fun whenIsAnExceptionWithSubdomainAndDomainIsListedInTheExceptionsListThenReturnTrue() { + fun `isAnException - subdomain and domain listed in exceptions - return true`() { givenThereAreExceptions() assertTrue(testee.isAnException("http://test.example.com")) } @Test - fun whenIsAnExceptionAndDomainIsNotListedInTheExceptionsListThenReturnFalse() { + fun `isAnException - domain not listed in exceptions - return false`() { whenever(mockHttpsRepository.exceptions).thenReturn(CopyOnWriteArrayList()) assertFalse(testee.isAnException("http://test.example.com")) } @Test - fun whenIsAnExceptionAndDomainIsListedInTheUnprotectedTemporaryListThenReturnTrue() { + fun `isAnException - domain in unprotected temporary list - return 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 in user allow list - return 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..afa235d39ed2 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 - do not throw an 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..9d7b6fbdac8b 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 - return 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 `store - feature name matches tracker allowlist - 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..99dd3c9a6b3c 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 - domain in user allow list - return 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..1cafeaa73693 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 - return 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 - return 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 `store - feature name matches tracking parameters - 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..c8bf344b9a23 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 - domain listed in exceptions - return true`() { givenThereAreExceptions() assertTrue(testee.isAnException("http://www.example.com")) } @Test - fun whenIsAnExceptionWithSubdomainAndDomainIsListedInTheExceptionsListThenReturnTrue() { + fun `isAnException - subdomain and domain listed in exceptions - return true`() { givenThereAreExceptions() assertTrue(testee.isAnException("http://test.example.com")) } @Test - fun whenIsAnExceptionAndDomainIsNotListedInTheExceptionsListThenReturnFalse() { + fun `isAnException - domain not listed in exceptions - return 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..c9cd30dd21b6 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 `onCreate - 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..81b5566c8be0 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 - feature is not a privacy feature - return null`() = runTest { assertNull(testee.isEnabled(NonPrivacyFeature().value, true)) } @Test - fun whenIsEnabledAndFeatureIsPrivacyFeatureThenReturnTrueWhenEnabled() = + fun `isEnabled - privacy feature enabled - returns true`() = runTest { givenPrivacyFeatureIsEnabled() @@ -60,7 +60,7 @@ class PrivacyFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsPrivacyFeatureThenReturnFalseWhenDisabled() = + fun `isEnabled - privacy feature disabled - return false`() = runTest { givenPrivacyFeatureIsDisabled() @@ -70,7 +70,7 @@ class PrivacyFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsPrivacyFeatureThenReturnDefaultValueIfFeatureDoesNotExist() = + fun `isEnabled - privacy feature does not exist - return default value`() = runTest { val defaultValue = true givenPrivacyFeatureReturnsDefaultValue(defaultValue) @@ -82,7 +82,7 @@ class PrivacyFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsPrivacyFeatureAndAppVersionEqualToMinSupportedVersionThenReturnTrueWhenEnabled() = + fun `isEnabled - privacy feature and app version equal to min supported version - return true`() = runTest { givenPrivacyFeatureIsEnabled() givenAppVersionIsEqualToMinSupportedVersion() @@ -93,7 +93,7 @@ class PrivacyFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsPrivacyFeatureAndAppVersionIsGreaterThanMinSupportedVersionThenReturnTrueWhenEnabled() = + fun `isEnabled - privacy feature enabled and app version greater than min supported - returns true`() = runTest { givenPrivacyFeatureIsEnabled() givenAppVersionIsGreaterThanMinSupportedVersion() @@ -104,7 +104,7 @@ class PrivacyFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsPrivacyFeatureAndAppVersionIsSmallerThanMinSupportedVersionThenReturnFalseWhenEnabled() = + fun `isEnabled - privacy feature and app version smaller than min supported version - return false`() = 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..a88ca653b218 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 `insert - privacy config - 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 - calls delete`() { testee.delete() verify(mockPrivacyConfigDao).delete() } @Test - fun whenGetThenCallGet() { + fun `get - calls get`() { 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..2a821f6f2adb 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 - deleteAll 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 - insert called`() { 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..56b8fe4ea036 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 `RealAmpLinksRepository - repository created - values loaded into memory`() { givenAmpLinksDaoContainsEntities() testee = RealAmpLinksRepository( @@ -68,7 +68,7 @@ class RealAmpLinksRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = runTest { + fun `updateAll - updateAll 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..a8c87deb00c0 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 `RealContentBlockingRepository - repository created - exceptions loaded into memory`() { givenContentBlockingDaoContainsExceptions() testee = @@ -65,7 +65,7 @@ class RealContentBlockingRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - updateAll 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..62443b46eaca 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 `RealDrmRepository - repository created - exceptions loaded into memory`() = runTest { givenDrmDaoContainsExceptions() testee = RealDrmRepository(mockDatabase, this, coroutineRule.testDispatcherProvider, true) @@ -56,7 +56,7 @@ class RealDrmRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = runTest { + fun `updateAll - updateAll 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..f0dda5e68ab7 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 `RealGpcRepository - repository created - exceptions loaded into memory`() { givenGpcDaoContainsExceptions() testee = @@ -77,7 +77,7 @@ class RealGpcRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - calls updateAll on DAOs`() = 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 gpcEnabled to true`() { testee.enableGpc() verify(mockGpcDataStore).gpcEnabled = true } @Test - fun whenDisableGpcThenSetGpcEnabledToFalse() { + fun `disableGpc - gpcEnabled set to false`() { testee.disableGpc() verify(mockGpcDataStore).gpcEnabled = false } @Test - fun whenIsGpcEnabledThenReturnGpcEnabledValue() { + fun `isGpcEnabled - return 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..c0e3a4a6451b 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 `RealHttpsRepository - repository created - exceptions loaded into memory`() { givenHttpsDaoContainsExceptions() testee = @@ -69,7 +69,7 @@ class RealHttpsRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - updateAll 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..2baf425acfbc 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 `RealTrackerAllowlistRepository - repository created - exceptions loaded into memory`() { givenHttpsDaoContainsExceptions() testee = @@ -69,7 +69,7 @@ class RealTrackerAllowlistRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - updateAll 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..309fc839b57b 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 `RealTrackingParametersRepository - repository created - values loaded into memory`() { givenTrackingParametersDaoContainsEntities() testee = RealTrackingParametersRepository( @@ -67,7 +67,7 @@ class RealTrackingParametersRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = runTest { + fun `updateAll - updateAll called`() = runTest { testee = RealTrackingParametersRepository( mockDatabase, TestScope(), @@ -81,7 +81,7 @@ class RealTrackingParametersRepositoryTest { } @Test - fun whenUpdateAllThenPreviousValuesAreCleared() = runTest { + fun `updateAll - previous values are 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..d39eb9a41dbd 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 `RealUnprotectedTemporaryRepository - repository created - exceptions loaded into memory`() { givenUnprotectedTemporaryDaoContainsExceptions() testee = @@ -69,7 +69,7 @@ class RealUnprotectedTemporaryRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - updateAll 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..b71f442b9c57 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 - allowListed is true`() { val viewState = testee.mapFromSite(site(allowListed = true)) assertTrue(viewState.allowlisted) } @Test - fun whenSiteIsUnprotectedTemporaryThenUnprotectedIsTrue() { + fun `mapFromSite - site is unprotected temporary - unprotected is 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 - viewState 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..df91c321fb5c 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 viewState contains 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 viewState 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 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 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 has 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 a 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 - trackers from same domain and state - request data 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 - trackers from same domain different entity - contains both events`() { 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 - trackers from same domain different state - request data viewState contains both`() { 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..c73e6ba7789d 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 - viewState 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 - viewState parent entity null`() { val site = site() val siteProtectionsViewState = testee.mapFromSite(site) @@ -62,7 +62,7 @@ class AppSiteViewStateMapperTest { } @Test - fun whenMappingSiteThenViewStateHasSiteInfo() { + fun `mapFromSite - viewState 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 - viewState 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 - viewState 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..afafb15c4446 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 - command emitted`() = runTest { testee.onReportBrokenSiteSelected() testee.commands().test { @@ -106,7 +106,7 @@ class PrivacyDashboardHybridViewModelTest { } @Test - fun whenSiteChangesThenViewStateUpdates() = runTest { + fun `onSiteChanged - viewState updates`() = runTest { testee.onSiteChanged(site()) testee.viewState.test { @@ -117,7 +117,7 @@ class PrivacyDashboardHybridViewModelTest { } @Test - fun whenOnPrivacyProtectionClickedThenUpdateViewState() = runTest { + fun `onPrivacyProtectionsClicked - update viewState`() = 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 - allowlist changed - viewState updated`() = runTest { val site = site(siteAllowed = false) testee.onSiteChanged(site) @@ -156,7 +156,7 @@ class PrivacyDashboardHybridViewModelTest { } @Test - fun whenOnPrivacyProtectionClickedThenListenerIsNotified() = runTest { + fun `onPrivacyProtectionsClicked - listener notified`() = runTest { val site = site(siteAllowed = false) testee.onSiteChanged(site) @@ -166,7 +166,7 @@ class PrivacyDashboardHybridViewModelTest { } @Test - fun whenPrivacyProtectionsPopupExperimentParamsArePresentThenTheyShouldBeIncludedInPixels() = runTest { + fun `onPrivacyProtectionsClicked - experiment params present - included in pixels`() = 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 and opened from custom tab - 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 and opened from custom tab - 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..fb699a5f4fcb 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..6ec52cf046bb 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 - return 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 - return 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 - EC 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..dfa24d2551fa 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 - clean up old entries from popupDismissDomainRepository`() = 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..9872b4394c73 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 - 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 - 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 `onPageRefreshTriggeredByUser - url is DuckDuckGo - popup is not shown`() = 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 `onPageRefreshTriggeredByUser - 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 `onPageRefreshTriggeredByUser - protections disabled - popup not shown`() = runTest { protectionsStateProvider.protectionsEnabled = false subject.viewState.test { @@ -162,7 +162,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenUrlIsMissingThenPopupIsNotShown() = runTest { + fun `onPageRefreshTriggeredByUser - url is missing - popup is 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 - 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 - browser error - popup is 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 `onPageLoaded - page changed - 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 - dismiss event - viewState updated`() = 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 - dismiss button clicked - popup is 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 `onUiEvent - disable protections clicked - popup is 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 `onUiEvent - disable protections clicked - 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 `onPageRefreshTriggeredByUser - popup dismissed recently for same domain - popup not shown`() = 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 `onPageRefreshTriggeredByUser - popup dismissed more than 24 hours ago - 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 `onPageRefreshTriggeredByUser - popup dismissed recently - shown 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 - data not loaded - popup not shown`() = runTest { val protectionsEnabledFlow = MutableSharedFlow() protectionsStateProvider.overrideProtectionsEnabledFlow(protectionsEnabledFlow) @@ -335,7 +335,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenRefreshIsTriggeredThenPopupIsNotShownEvenIfOtherConditionsAreMetAfterAFewSeconds() = runTest { + fun `onPageRefreshTriggeredByUser - after a few seconds - 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 not shown`() = 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 shown`() = runTest { val toggleUsedAt = timeProvider.time - Duration.ofDays(32) dataStore.setToggleUsageTimestamp(toggleUsedAt) @@ -375,7 +375,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenPageReloadsOnRefreshWithHttpErrorThenPopupIsNotDismissed() = runTest { + fun `onPageLoaded - page reloads 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 `onPageRefreshTriggeredByUser - 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 `onPageRefreshTriggeredByUser - popup trigger count is zero - do not show again option is not available`() = runTest { dataStore.setPopupTriggerCount(0) subject.viewState.test { @@ -423,7 +423,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenPopupTriggerCountIsGreaterThanZeroThenDoNotShowAgainOptionIsAvailable() = runTest { + fun `onPageRefreshTriggeredByUser - 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 `onPageRefreshTriggeredByUser - experiment variant is control - popup is 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 `onPageRefreshTriggeredByUser - experiment variant is null - initializes variant with random value`() = runTest { variantRandomizer.variant = CONTROL assertNull(dataStore.getExperimentVariant()) @@ -482,7 +482,7 @@ class PrivacyProtectionsPopupManagerImplTest { } @Test - fun whenExperimentVariantIsAssignedThenPixelIsSent() = runTest { + fun `onPageRefreshTriggeredByUser - 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 `onPageRefreshTriggeredByUser - 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 is triggered - pixel is 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 - disable protections clicked - pixel is 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 is 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 is 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 clicked - pixel is 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 `onPageRefreshTriggeredByUser - conditions met - pixel is 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 `onPageRefreshTriggeredByUser - feature disabled and no experiment variant - pixel is 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..6b64e1486f51 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 and domain not an exception - protections enabled`() = runTest { assertTrue(areProtectionsEnabled(domain = "www.example.com")) } @Test - fun whenContentBlockingFeatureIsDisabledThenProtectionsAreDisabled() = runTest { + fun `areProtectionsEnabled - content blocking feature disabled - protections are 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 `areProtectionsEnabled - domain on content blocking exception list - protections are disabled`() = runTest { val domain = "www.example.com" whenever(contentBlocking.isAnException(domain)).thenReturn(true) @@ -83,7 +83,7 @@ class ProtectionsStateProviderTest { } @Test - fun whenDomainIsOnUnprotectedTemporaryExceptionListThenProtectionsAreDisabled() = runTest { + fun `areProtectionsEnabled - domain on unprotected temporary exception list - 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 `areProtectionsEnabled - domain in user allowlist - protections are 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..c28df55a994f 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 is empty - returns null dismiss timestamp`() = runTest { val dismissedAt = subject.getPopupDismissTime("www.example.com").first() assertNull(dismissedAt) } @Test - fun whenDismissTimeIsStoredThenQueryReturnsCorrectValue() = runTest { + fun `getPopupDismissTime - dismiss time stored - 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 `getPopupDismissTime - dismiss time set multiple times - 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 `getPopupDismissTime - 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 `removeEntriesOlderThan - correct data is 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 is 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..15aa7238421e 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 is empty - returns null`() = runTest { assertNull(subject.getToggleUsageTimestamp()) } @Test - fun whenDismissTimeIsStoredThenQueryReturnsCorrectValue() = runTest { + fun `getToggleUsageTimestamp - dismiss time stored - 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 `getToggleUsageTimestamp - multiple times set - returns most recent 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 `getPopupTriggerCount - popup trigger count stored - 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 `getDoNotShowAgainClicked - not initialized - returns false`() = runTest { assertFalse(subject.getDoNotShowAgainClicked()) } @Test - fun whenDoNotShowAgainIsStoredThenReturnsCorrectValue() = runTest { + fun `getDoNotShowAgainClicked - do not show again is stored - returns correct value`() = runTest { subject.setDoNotShowAgainClicked(clicked = true) assertTrue(subject.getDoNotShowAgainClicked()) } @Test - fun whenExperimentVariantIsNotInitializedThenReturnsNull() = runTest { + fun `getExperimentVariant - experiment variant not initialized - returns null`() = runTest { assertNull(subject.getExperimentVariant()) } @Test - fun whenExperimentVariantIsStoredThenReturnsCorrectValue() = runTest { + fun `getExperimentVariant - experiment variant stored - 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..1b11dec5248f 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 `activeMessage - add medium message - message stored`() = runTest { testee.activeMessage( RemoteMessage( id = "id", @@ -111,7 +111,7 @@ class AppRemoteMessagingRepositoryTest { } @Test - fun whenAddSmallMessageThenMessageStored() = runTest { + fun `activeMessage - add small message - message stored`() = runTest { testee.activeMessage( RemoteMessage( id = "id", @@ -144,7 +144,7 @@ class AppRemoteMessagingRepositoryTest { } @Test - fun whenAddBigSingleActionMessageThenMessageStored() = runTest { + fun `activeMessage - add big single action message - message stored`() = runTest { testee.activeMessage( RemoteMessage( id = "id", @@ -183,7 +183,7 @@ class AppRemoteMessagingRepositoryTest { } @Test - fun whenAddBigTwoActionMessageThenMessageStored() = runTest { + fun `activeMessage - add BigTwoAction message - message stored`() = runTest { testee.activeMessage( RemoteMessage( id = "id", @@ -226,7 +226,7 @@ class AppRemoteMessagingRepositoryTest { } @Test - fun whenAddPromoSingleActionMessageThenMessageStored() = runTest { + fun `activeMessage - add promo single action message - message stored`() = runTest { testee.activeMessage( RemoteMessage( id = "id", @@ -265,7 +265,7 @@ class AppRemoteMessagingRepositoryTest { } @Test - fun whenDismissMessageThenUpdateState() = runTest { + fun `dismissMessage - update state`() = runTest { testee.activeMessage( RemoteMessage( id = "id", @@ -294,7 +294,7 @@ class AppRemoteMessagingRepositoryTest { } @Test - fun whenGetDismissedMessagesThenReturnDismissedMessageIds() = runTest { + fun `dismissedMessages - after dismissing message - return dismissed message ids`() = runTest { testee.activeMessage( RemoteMessage( id = "id", @@ -319,7 +319,7 @@ class AppRemoteMessagingRepositoryTest { } @Test - fun whenNewMessageAddedThenPreviousNonDismissedMessagesRemoved() = runTest { + fun `activeMessage - new message added - previous non-dismissed messages 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..6ab330f20df8 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 but 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..d91788c0c005 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 `map - 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 `map - valid json parsed - rules mapped into remote config`() = 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 - messages 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 `map - json messages malformed or missing information - messages 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 matching attributes 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 without 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..8e7ec0abf7be 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 - empty config - return 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 - not existing rule - return 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 - matching message should be excluded - 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 - matching message excluded by multiple rules - return 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 with 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 - return 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 message rules - return 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 one of multiple message rules - 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 first message and device matches multiple messages - return 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 does not match 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 - return 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)) @@ -402,7 +402,7 @@ class RemoteMessagingConfigMatcherTest { } @Test - fun whenMatchingMessageShouldBeExcludedAndUserPartOfPercentileThenReturnNull() = runBlocking { + fun `evaluate - matching message excluded and user part of percentile - return null`() = runBlocking { givenDeviceMatches(Locale(value = listOf("en-US"))) cohortDao.insert(RemoteMessagingCohort(messageId = "message1", percentile = 0.1f)) @@ -419,7 +419,7 @@ class RemoteMessagingConfigMatcherTest { } @Test - fun whenMatchingMessageShouldBeExcludedButOutOfPercentileThenReturnMessage() = runBlocking { + fun `evaluate - matching message 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..50ab45f46308 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 - return 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 - return 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 - return 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 to device - 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 - return 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 - searchAtb matches - return 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 - return match`() = runTest { givenDeviceProperties(installedGPlay = true) val result = testee.evaluate( @@ -266,7 +266,7 @@ class AndroidAppAttributeMatcherTest { } @Test - fun whenInstalledGPlayDoesNotMatchThenReturnFail() = runTest { + fun `evaluate - installed GPlay 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..c5e76e8cdeaf 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 - return 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 - return 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 is 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 - different 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 - return 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 - return 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 - return false`() = 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 - return 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 - return 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 WebView max version - return 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 WebView min version - return 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 - return 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 - return 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 has unknown format - return fail`() = runTest { givenDeviceProperties(webView = "test93.91.0") val result = testee.evaluate(WebView(min = "91")) @@ -285,7 +285,7 @@ class DeviceAttributeMatcherTest { } @Test - fun whenEmptyWebViewMatchingAttributeThenReturnFail() = runTest { + fun `evaluate - empty WebView 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..7ae2adc290d9 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 - interacted with message - return 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 value is 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 - dismissed message id matches - return 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 - return 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 - return 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 `evaluate - empty list in matching attribute - throws 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..d5fc3719216a 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 - return 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 match - return match`() = runTest { givenBrowserProperties(bookmarks = 10L) val result = testee.evaluate( @@ -67,7 +67,7 @@ class UserAttributeMatcherTest { } @Test - fun whenBookmarksDoesNotMatchThenReturnFail() = runTest { + fun `evaluate - bookmarks do 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 - return 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 - return match`() = runTest { givenBrowserProperties(favorites = 10L) val result = testee.evaluate( @@ -156,7 +156,7 @@ class UserAttributeMatcherTest { } @Test - fun whenFavoritesDoesNotMatchThenReturnFail() = runTest { + fun `evaluate - favorites do 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 false`() = 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 - return 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 - return 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 - return 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..474d76fc2d7e 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 `intercept - endpoint enabled - uses staging URL`() { rmfInternalSettings.useStatingEndpoint().setEnabled(State(enable = true)) val chain = FakeChain(RMF_URL_V1) @@ -28,7 +28,7 @@ class RmfStagingEnvInterceptorTest { } @Test - fun interceptNoopWhenDisabled() { + fun `intercept - disabled - noop`() { rmfInternalSettings.useStatingEndpoint().setEnabled(State(enable = false)) val chain = FakeChain(RMF_URL_V1) @@ -43,7 +43,7 @@ class RmfStagingEnvInterceptorTest { } @Test - fun interceptIgnoreUnknownEndpointWhenEnabled() { + fun `intercept - unknown endpoint enabled - ignored`() { rmfInternalSettings.useStatingEndpoint().setEnabled(State(enable = true)) val chain = FakeChain(UNKNOWN_URL) @@ -53,7 +53,7 @@ class RmfStagingEnvInterceptorTest { } @Test - fun interceptIgnoreUnknownEndpointWhenDisabled() { + fun `intercept - unknown endpoint disabled - 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..9a731ff766b7 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 `expired - remote config timestamp 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 `expired - timestamp less than 1 day - config is 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..9af2d47b9b42 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 - percentile set for message - returns same value`() = runTest { cohortDao.insert(RemoteMessagingCohort(messageId = "message1", percentile = 0.5f)) assertEquals(0.5f, testee.getPercentile("message1")) } @Test - fun whenPercentileIsNotSetForMessageThenItIsCalculated() = runTest { + fun `getPercentile - percentile not set for message - 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 - return 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..7cac300d6d4f 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 is disabled - return 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 - return 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 `shouldFilterOutRequest - referer header matches previous url - return 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 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 `shouldFilterOutRequest - origin header matches previous URL and no referer header - return 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 eTLD+1 - 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 `shouldFilterOutRequest - 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 `shouldFilterOutRequest - 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 `shouldFilterOutRequest - 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`() { 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 `shouldFilterOutRequest - document URL is malformed - return false`() { requestFilterer.registerOnPageCreated("http://foo.com") assertFalse(requestFilterer.shouldFilterOutRequest(mockRequest, "abc123")) } @Test - fun whenPreviousUrlIsMalformedThenReturnFalse() { + fun `shouldFilterOutRequest - previous URL is 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..2e40b785d303 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 - return 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 - return 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 `store - feature name matches request filterer - 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..638694c4d16e 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 - feature is not request filterer - return null`() = runTest { assertNull(testee.isEnabled(NonRequestFiltererFeature().value, true)) } @Test - fun whenIsEnabledAndFeatureIsRequestFiltererFeatureThenReturnTrueWhenEnabled() = + fun `isEnabled - request filterer feature enabled - return true`() = runTest { givenRequestFiltererFeatureIsEnabled() @@ -60,7 +60,7 @@ class RequestFiltererFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsRequestFiltererFeatureThenReturnFalseWhenDisabled() = + fun `isEnabled - request filterer feature disabled - return false`() = 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 - return true`() = 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 - return true`() = runTest { givenRequestFiltererFeatureIsEnabled() givenAppVersionIsGreaterThanMinSupportedVersion() @@ -104,7 +104,7 @@ class RequestFiltererFeatureTogglesPluginTest { } @Test - fun whenIsEnabledAndFeatureIsRequestFiltererFeatureAndAppVersionIsSmallerThanMinSupportedVersionThenReturnFalseWhenEnabled() = + fun `isEnabled - request filterer feature and app version smaller than min supported version - return false`() = 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..68e429a84fd5 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 - deleteAll 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 - insert called`() { 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..be4074d4bfd1 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 `RealRequestFiltererRepository - 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 - updates all`() { val policy = SettingsEntity(2, 600) testee = RealRequestFiltererRepository( @@ -89,7 +89,7 @@ class RealRequestFiltererRepositoryTest { } @Test - fun whenUpdateAllThenPreviousValuesAreCleared() { + fun `updateAll - previous values are 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..13e89386e1a6 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 `config - return correctly formatted json`() { whenever(mockRuntimeChecksRepository.getRuntimeChecksEntity()).thenReturn(RuntimeChecksEntity(json = config)) assertEquals("\"runtimeChecks\":$config", testee.config()) } @Test - fun whenGetPreferencesThenReturnNull() { + fun `preferences - return 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..4a4e45a2a4fb 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 - return 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 - return true`() { assertTrue(testee.store(FEATURE_NAME_VALUE, JSON_STRING)) } @Test - fun whenFeatureNameMatchesRuntimeChecksThenUpdateAll() { + fun `store - feature name matches runtime checks - update all`() { 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..d262c16c38ce 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 `init - no stored value - load empty JSON to memory`() = runTest { testee = RealRuntimeChecksRepository( @@ -57,7 +57,7 @@ class RuntimeChecksRepositoryTest { } @Test - fun whenInitializedAndHasStoredValueThenLoadStoredJsonToMemory() = + fun `init - has stored value - load stored json to memory`() = runTest { whenever(mockRuntimeChecksDao.get()).thenReturn(runtimeChecksEntity) testee = @@ -73,7 +73,7 @@ class RuntimeChecksRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - updateAll 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..252fc4e62bad 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 is 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 import succeeds - pixel is 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 is 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 is 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 is 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..56757988f9b2 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 - false`() { assertFalse(savedSitesSyncStore.isSyncPaused) } @Test - fun whenSyncPausedAndOnSuccessWithChangesThenIsSyncPausedIsFalse() { + fun `onSuccess - sync paused with changes - isSyncPaused is 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 without changes - sync paused`() { savedSitesSyncStore.isSyncPaused = true val validChanges = SyncChangesResponse.empty(BOOKMARKS) @@ -80,7 +80,7 @@ class AppSavedSitesSyncFeatureListenerTest { } @Test - fun whenSyncPausedAndOnErrorThenSyncPaused() { + fun `onError - sync paused and collection limit reached - sync paused`() { savedSitesSyncStore.isSyncPaused = true testee.onError(FeatureSyncError.COLLECTION_LIMIT_REACHED) @@ -89,7 +89,7 @@ class AppSavedSitesSyncFeatureListenerTest { } @Test - fun whenSyncActiveAndOnErrorThenSyncPaused() { + fun `onError - sync active - 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..313b3f20e17d 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 - return stored value`() = runTest { savedSitesSettingsStore.favoritesDisplayMode = FavoritesDisplayMode.NATIVE assertEquals(FavoritesDisplayMode.NATIVE.value, testee.getValue()) } @Test - fun whenSaveWithValidValueThenReturnTrue() = runTest { + fun `save - valid value - return true`() = runTest { assertTrue(testee.save(FavoritesDisplayMode.NATIVE.value)) } @Test - fun whenSaveWithInvalidValidValueThenReturnFalse() = runTest { + fun `save - invalid value - return false`() = runTest { assertFalse(testee.save("unknown_value")) } @Test - fun whenDeduplicateWithValidValueThenReturnTrue() = runTest { + fun `deduplicate - valid value - return true`() = runTest { assertTrue(testee.deduplicate(FavoritesDisplayMode.NATIVE.value)) } @Test - fun whenDeduplicateWithInvalidValidValueThenReturnFalse() = runTest { + fun `deduplicate - invalid value - return 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..ee31b6707d44 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 viewState emitted`() = runTest { testee.viewState().test { assertEquals(ViewState(), awaitItem()) } } @Test - fun whenDisplayModeChangedThenViewStateIsUpdated() = runTest { + fun `onDisplayModeChanged - viewState 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..fc9ef7d58620 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 `isSyncPausedFlow - isSyncPaused updated - 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..dc560575febd 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 - result is 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 - null entries - result is 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 - 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 - result is 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 `onError - notify listener`() { syncPersister.onError(SyncErrorResponse(BOOKMARKS, COLLECTION_LIMIT_REACHED)) verify(savedSitesSyncFeatureListener).onError(COLLECTION_LIMIT_REACHED) } @Test - fun whenOnSyncDisabledTheNotifyListener() { + fun `onSyncDisabled - notify listener`() { 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..96008bcd252b 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 - deduplication persister is 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 - timestamp persister is 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 - remote persister is 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 - local persister is used`() { val rootFolder = BookmarkFolder( id = SavedSitesNames.BOOKMARKS_ROOT, name = SavedSitesNames.BOOKMARKS_NAME, @@ -199,7 +199,7 @@ class SavedSitesSyncPersisterAlgorithmTest { } @Test - fun whenProcessingOrphansThenResultIsSuccess() { + fun `processEntries - processing orphans - 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..30e3ec5b7e3c 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 `favoritesDisplayMode - return stored value`() = runTest { prefs.edit().putString(KEY_FAVORITES_DISPLAY_MODE, NATIVE.value).commit() assertEquals(NATIVE, testee.favoritesDisplayMode) } @Test - fun whenNoValueThenReturnNative() = runTest { + fun `favoritesDisplayMode - no value - return 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..7cb46157f672 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 - 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 - list of permissions should auto accept - 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 - filter not supported - 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 - 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 - 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 - fireproof list - don't delete entities`() = 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 - domain not in fireproof list - delete entities`() = 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 - returns 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 - returns 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 - returns 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 - returns 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 - returns 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..3bfc53e48705 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 `isDomainAllowedToAsk - permission not supported - domain is not allowed`() { setInitialSettings() val permission = PermissionRequest.RESOURCE_MIDI_SYSEX @@ -71,7 +71,7 @@ class SitePermissionsRepositoryTest { } @Test - fun givenPermissionSupportedThenDomainIsAllowedToAsk() { + fun `isDomainAllowedToAsk - permission supported - domain is allowed`() { setInitialSettings() val permission = PermissionRequest.RESOURCE_AUDIO_CAPTURE @@ -79,7 +79,7 @@ class SitePermissionsRepositoryTest { } @Test - fun whenAskForPermissionIsDisabledThenDomainIsNotAllowedToAsk() { + fun `isDomainAllowedToAsk - permission disabled - domain is not allowed`() { setInitialSettings(cameraEnabled = false) val permission = PermissionRequest.RESOURCE_VIDEO_CAPTURE @@ -87,7 +87,7 @@ class SitePermissionsRepositoryTest { } @Test - fun whenAskForPermissionDisabledButSitePermissionSettingIsAlwaysAllowThenIsAllowedToAsk() { + fun `isDomainAllowedToAsk - permission disabled but site permission always allow - is allowed`() { 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 - domain is 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 - not allowed`() { val permission = PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID whenever(mockDrmBlock.isDrmBlockedForUrl(url)).thenReturn(true) @@ -114,7 +114,7 @@ class SitePermissionsRepositoryTest { } @Test - fun whenSitePermissionSettingIsAskAndDrmBlockedThenDomainIsAllowedToAsk() { + fun `isDomainAllowedToAsk - DRM blocked - domain is 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 - permission granted within 24h - permission granted`() { setInitialSettings() val permission = PermissionRequest.RESOURCE_VIDEO_CAPTURE val tabId = "tabId" @@ -136,7 +136,7 @@ class SitePermissionsRepositoryTest { } @Test - fun whenSitePermissionsWasMoreThen24hAgoThenReturnPermissionNotGranted() { + fun `isDomainGranted - site permissions more than 24h ago - permission not granted`() { setInitialSettings() val permission = PermissionRequest.RESOURCE_VIDEO_CAPTURE val tabId = "tabId" @@ -147,7 +147,7 @@ class SitePermissionsRepositoryTest { } @Test - fun whenSitePermissionsSettingIsAllowAlwaysThenReturnPermissionGranted() { + fun `isDomainGranted - site permissions setting is 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 `sitePermissionGranted - first time - 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 `sitePermissionGranted - permission already in db - 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 `sitePermissionGranted - user grants site permission - 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 - calls getAllSitesPermissionsAsFlow`() = runTest { repository.sitePermissionsWebsitesFlow() verify(mockSitePermissionsDao).getAllSitesPermissionsAsFlow() } @Test - fun whenSitePermissionsForAllWebsitesIsCalledThenGetSitePermissionsForAllWebsites() = runTest { + fun `sitePermissionsForAllWebsites - calls getAllSitesPermissions`() = runTest { repository.sitePermissionsForAllWebsites() verify(mockSitePermissionsDao).getAllSitesPermissions() } @Test - fun whenSitePermissionsAllowedFlowIsCalledThenGetSitePermissionsAllowedFlow() = runTest { + fun `sitePermissionsAllowedFlow - calls getSitePermissionsAllowedFlow`() = runTest { repository.sitePermissionsAllowedFlow() verify(mockSitePermissionsAllowedDao).getAllSitesPermissionsAllowedAsFlow() } @Test - fun whenUndoDeleteAllThenInsertSitePermissionsBackToAllowedDao() = runTest { + fun `undoDeleteAll - insert site permissions back to allowed dao`() = 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 - inserts site permissions back`() = runTest { val testEntity = SitePermissionsEntity(domain) val sitePermissions = listOf(testEntity) @@ -227,7 +227,7 @@ class SitePermissionsRepositoryTest { } @Test - fun whenDeleteAllThenDeleteEntitiesFromDatabases() = runTest { + fun `deleteAll - deletes entities from databases`() = runTest { repository.deleteAll() verify(mockSitePermissionsDao).deleteAll() @@ -235,14 +235,14 @@ class SitePermissionsRepositoryTest { } @Test - fun whenGetSitePermissionsForWebsiteCalledThenGetSitePermissionsByDomain() = runTest { + fun `getSitePermissionsForWebsite - getSitePermissionsByDomain`() = runTest { repository.getSitePermissionsForWebsite(url) verify(mockSitePermissionsDao).getSitePermissionsByDomain(domain) } @Test - fun whenDeletePermissionForSiteThenDeleteItFromDbs() = runTest { + fun `deletePermissionsForSite - deletes 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 - inserts 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..21fe39530240 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 returned`() { assertFalse(testee.isDrmBlockedForUrl(url)) } @Test - fun whenFeatureEnabledUrlNotBlockedThenFalseIsReturned() { + fun `isDrmBlockedForUrl - feature enabled and URL not blocked - false returned`() { givenFeatureIsEnabled() givenUrlIsNotInExceptionList() @@ -63,7 +63,7 @@ class RealDrmBlockTest { } @Test - fun whenFeatureEnabledUrlBlockedUserAllowedThenFalseIsReturned() { + fun `isDrmBlockedForUrl - feature enabled, 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 and url blocked - 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..0e94fd358f9b 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 - referrer information instantly available - atb initialized`() = runTest { configureNeverInitialized() testee.onPrivacyConfigDownloaded() @@ -50,7 +50,7 @@ class AtbInitializerTest { } @Test - fun whenReferrerInformationQuicklyAvailableThenAtbInitialized() = runTest { + fun `onPrivacyConfigDownloaded - referrer information quickly available - atb initialized`() = runTest { whenever(statisticsDataStore.hasInstallationStatistics).thenReturn(false) atbInitializerListener.delay = 1.seconds testee = AtbInitializer( @@ -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 - 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..38ebc61b3740 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 - 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 - with additional parameters - pixel service called with default and additional parameters`() { givenPixelApiSucceeds() givenAtbVariant(Atb("atb")) givenVariant("variant") @@ -163,7 +163,7 @@ class RxPixelSenderTest { } @Test - fun whenPixelFiredWithoutAdditionalParametersThenPixelServiceCalledWithOnlyDefaultParameters() { + fun `sendPixel - without additional parameters - called with only default parameters`() { givenPixelApiSucceeds() givenAtbVariant(Atb("atb")) givenVariant("variant") @@ -178,7 +178,7 @@ class RxPixelSenderTest { } @Test - fun whenPixelEnqueuedWitAdditionalParametersThenPixelEnqueuedWithParameters() { + fun `enqueuePixel - with additional parameters - pixel enqueued with parameters`() { givenAtbVariant(Atb("atb")) givenVariant("variant") givenFormFactor(DeviceInfo.FormFactor.PHONE) @@ -203,7 +203,7 @@ class RxPixelSenderTest { } @Test - fun whenPixelEnqueuedWithoutAdditionalParametersThenPixelEnqueuedWithOnlyDefaultParameters() { + fun `enqueuePixel - without additional parameters - enqueued with only 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 - 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 - pixel name 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..2a22f6519985 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 - previous atb replaced`() { 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 - 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 `refreshAppRetentionAtb - update version present - previous atb replaced`() { 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 `refreshAppRetentionAtb - update version present - 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 `refreshSearchRetentionAtb - 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 `refreshAppRetentionAtb - 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 - includes refreshed atb`() { configureStoredStatistics() val retentionAtb = "foo" whenever(mockStatisticsStore.searchRetentionAtb).thenReturn(retentionAtb) @@ -161,7 +161,7 @@ class StatisticsRequesterTest { } @Test - fun whenStatisticsStoredThenRefreshUpdatesAtb() { + fun `refreshSearchRetentionAtb - 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 `refreshSearchRetentionAtb - 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 `refreshAppRetentionAtb - 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..63e00b206514 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 `fromJson - valid format - data is 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 is 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..e17c3b4c8ecc 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 `fire - pixel without query params - sent with default params`() { givenSendPixelSucceeds() val pixel = RxBasedPixel(mockPixelSender) @@ -52,7 +52,7 @@ class RxBasedPixelTest { } @Test - fun whenPixelWithoutQueryParamsFiredFailsThenErrorHandled() { + fun `fire - pixel without query params fails - error handled`() { givenSendPixelFails() val pixel = RxBasedPixel(mockPixelSender) @@ -62,7 +62,7 @@ class RxBasedPixelTest { } @Test - fun whenPixelWithQueryParamsFiredThenPixelSentWithParams() { + fun `fire - pixel with query params - pixel sent with params`() { givenSendPixelSucceeds() val pixel = RxBasedPixel(mockPixelSender) @@ -73,7 +73,7 @@ class RxBasedPixelTest { } @Test - fun whenPixelWithoutQueryParamsEnqueuedThenPixelEnqueuedWithDefaultParams() { + fun `enqueueFire - pixel without query params - enqueued with default params`() { givenEnqueuePixelSucceeds() val pixel = RxBasedPixel(mockPixelSender) @@ -83,7 +83,7 @@ class RxBasedPixelTest { } @Test - fun whenPixelWithoutQueryParamsEnqueuedThenErrorHandled() { + fun `enqueueFire - pixel without query params - error handled`() { givenEnqueuePixelFails() val pixel = RxBasedPixel(mockPixelSender) @@ -93,7 +93,7 @@ class RxBasedPixelTest { } @Test - fun whenPixelWithQueryParamsEnqueuedThenPixelEnqueuedWithParams() { + fun `enqueueFire - pixel with query params - 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..303e4b900950 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 `hasDailyPixelFiredToday - database is empty - pixel fired is false`() = runTest { assertFalse(subject.hasDailyPixelFiredToday("pixel_d")) assertFalse(subject.hasUniquePixelFired("pixel_u")) } @Test - fun whenPixelWasFiredThenPixelFiredIsTrue() = runTest { + fun `storeDailyPixelFiredToday - pixel fired - true`() = runTest { subject.storeDailyPixelFiredToday("pixel_d") subject.storeUniquePixelFired("pixel_u") @@ -82,7 +82,7 @@ class PixelFiredRepositoryTest { } @Test - fun whenADayHasPassedThenDailyPixelFiredIsFalse() = runTest { + fun `hasDailyPixelFiredToday - a day has passed - 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 - daily pixel fired again - date 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..6a19ac5a6857 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 - return 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 - return failure`() = runTest { givenPurchaseStored() givenStoreLoginSucceeds() givenSubscriptionExists(EXPIRED) @@ -164,7 +164,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenRecoverSubscriptionFromStoreIfValidateTokenFailsReturnFailure() = runTest { + fun `recoverSubscriptionFromStore - validate token fails - return failure`() = runTest { givenUserIsAuthenticated() givenValidateTokenFails("failure") @@ -174,7 +174,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenRecoverSubscriptionFromStoreIfPurchaseHistoryRetrievedThenSignInUserAndSetToken() = runTest { + fun `recoverSubscriptionFromStore - purchase history retrieved - sign in user and set 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 is valid - return subscription`() = runTest { givenUserIsAuthenticated() givenSubscriptionSucceedsWithEntitlements() @@ -209,7 +209,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenFetchAndStoreAllDataIfTokenIsValidThenReturnEmitEntitlements() = runTest { + fun `fetchAndStoreAllData - token is valid - emit entitlements`() = 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 `purchase - user not authenticated and no purchase stored and signed in email - 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 - billing flow 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 - billing flow uses correct external id and emit states`() = runTest { givenUserIsAuthenticated() givenSubscriptionSucceedsWithoutEntitlements(status = "Expired") @@ -354,7 +354,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseFlowIfNullSubscriptionAndAuthenticatedThenDoNotCreateAccount() = runTest { + fun `purchase - null subscription and authenticated - do not create account`() = runTest { givenUserIsAuthenticated() givenValidateTokenFails("failure") @@ -364,7 +364,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseFlowIfAccountCreatedThenSetTokens() = runTest { + fun `purchase - 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 exchange fails - throws exception`() = runTest { givenAccessTokenFails() subscriptionsManager.exchangeAuthToken("authToken") } @Test - fun whenExchangeTokenIfAccessTokenThenExchangeTokenAndStore() = runTest { + fun `exchangeAuthToken - access token - exchange token and store`() = runTest { givenAccessTokenSucceeds() val result = subscriptionsManager.exchangeAuthToken("authToken") @@ -409,7 +409,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenSubscribedToSubscriptionStatusThenEmit() = runTest { + fun `subscriptionStatus - emit`() = runTest { val manager = RealSubscriptionsManager( authService, subscriptionsService, @@ -429,7 +429,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenSubscribedToSubscriptionStatusAndSubscriptionExistsThenEmit() = runTest { + fun `subscriptionStatus - subscription exists - emit`() = runTest { givenUserIsAuthenticated() givenSubscriptionExists() val manager = RealSubscriptionsManager( @@ -451,7 +451,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseSuccessfulThenPurchaseCheckedAndSuccessEmit() = runTest { + fun `currentPurchaseState - purchase successful - success emit`() = runTest { givenUserIsAuthenticated() givenConfirmPurchaseSucceeds() @@ -491,7 +491,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseFailedThenPurchaseCheckedAndWaitingEmit() = runTest { + fun `currentPurchaseState - purchase failed - checked and waiting emit`() = runTest { givenUserIsAuthenticated() givenValidateTokenFails("failure") givenConfirmPurchaseFails() @@ -526,7 +526,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseCanceledThenEmitCanceled() = runTest { + fun `currentPurchaseState - purchase canceled - emit canceled`() = runTest { val flowTest: MutableSharedFlow = MutableSharedFlow() whenever(playBillingManager.purchaseState).thenReturn(flowTest) @@ -550,7 +550,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenGetAccessTokenIfUserIsAuthenticatedThenReturnSuccess() = runTest { + fun `getAccessToken - user is authenticated - return success`() = runTest { givenUserIsAuthenticated() val result = subscriptionsManager.getAccessToken() @@ -560,7 +560,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenGetAccessTokenIfUserIsAuthenticatedThenReturnFailure() = runTest { + fun `getAccessToken - user not authenticated - return failure`() = runTest { givenUserIsNotAuthenticated() val result = subscriptionsManager.getAccessToken() @@ -569,7 +569,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenGetAuthTokenIfUserAuthenticatedAndValidTokenThenReturnSuccess() = runTest { + fun `getAuthToken - user authenticated and valid token - return success`() = runTest { givenUserIsAuthenticated() givenValidateTokenSucceedsWithEntitlements() @@ -580,7 +580,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenGetAuthTokenIfUserNotAuthenticatedThenReturnFailure() = runTest { + fun `getAuthToken - user not authenticated - return failure`() = runTest { givenUserIsNotAuthenticated() val result = subscriptionsManager.getAuthToken() @@ -589,7 +589,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenGetAuthTokenIfUserAuthenticatedWithSubscriptionAndTokenExpiredAndEntitlementsExistsThenReturnSuccess() = runTest { + fun `getAuthToken - token expired and entitlements exist - return success`() = runTest { authDataStore.externalId = "1234" givenUserIsAuthenticated() givenSubscriptionSucceedsWithEntitlements() @@ -606,7 +606,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenGetAuthTokenIfUserAuthenticatedWithSubscriptionAndTokenExpiredAndEntitlementsExistsAndExternalIdDifferentThenReturnFailure() = runTest { + fun `getAuthToken - 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 - token expired and no entitlements - return failure`() = runTest { givenUserIsAuthenticated() givenValidateTokenSucceedsNoEntitlements() givenValidateTokenFailsAndThenSucceedsWithNoEntitlements("""{ "error": "expired_token" }""") @@ -637,7 +637,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenGetAuthTokenIfUserAuthenticatedAndTokenExpiredAndNoPurchaseInTheStoreThenReturnFailure() = runTest { + fun `getAuthToken - token expired and no purchase - return failure`() = runTest { givenUserIsAuthenticated() givenValidateTokenFailsAndThenSucceeds("""{ "error": "expired_token" }""") @@ -648,7 +648,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenGetAuthTokenIfUserAuthenticatedAndTokenExpiredAndPurchaseNotValidThenReturnFailure() = runTest { + fun `getAuthToken - 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 - authenticated user - return correct status`() = runTest { givenUserIsAuthenticated() givenValidateTokenSucceedsWithEntitlements() @@ -691,7 +691,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenGetPortalAndUserAuthenticatedReturnUrl() = runTest { + fun `getPortalUrl - user authenticated - return url`() = runTest { givenUserIsAuthenticated() givenUrlPortalSucceeds() @@ -699,14 +699,14 @@ class RealSubscriptionsManagerTest { } @Test - fun whenGetPortalAndUserIsNotAuthenticatedReturnNull() = runTest { + fun `getPortalUrl - user not authenticated - return null`() = runTest { givenUserIsNotAuthenticated() assertNull(subscriptionsManager.getPortalUrl()) } @Test - fun whenGetPortalFailsReturnNull() = runTest { + fun `getPortalUrl - portal fails - return 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 - emit false for isSignedIn`() = runTest { givenSubscriptionExists() givenUserIsAuthenticated() @@ -746,7 +746,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenSignOutThenEmitUnknown() = runTest { + fun `signOut - emit unknown`() = runTest { givenUserIsAuthenticated() givenSubscriptionExists() @@ -771,7 +771,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseIsSuccessfulThenPixelIsSent() = runTest { + fun `currentPurchaseState - purchase successful - pixel is sent`() = runTest { givenUserIsAuthenticated() givenValidateTokenSucceedsWithEntitlements() givenConfirmPurchaseSucceeds() @@ -791,7 +791,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenSubscriptionIsRestoredOnPurchaseAttemptThenPixelIsSent() = runTest { + fun `purchase - subscription restored - pixel sent`() = runTest { givenUserIsNotAuthenticated() givenPurchaseStored() givenStoreLoginSucceeds() @@ -812,7 +812,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseFailsThenPixelIsSent() = runTest { + fun `currentPurchaseState - purchase fails - pixel is sent`() = runTest { givenUserIsAuthenticated() givenValidateTokenFails("failure") givenConfirmPurchaseFails() @@ -831,7 +831,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenPurchaseFlowIfCreateAccountFailsThenPixelIsSent() = runTest { + fun `purchase - create account fails - pixel is sent`() = runTest { givenUserIsNotAuthenticated() givenCreateAccountFails() @@ -849,7 +849,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenGetSubscriptionOfferThenReturnValue() = runTest { + fun `getSubscriptionOffer - return value`() = 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 - return true`() = runTest { assertTrue(subscriptionsManager.canSupportEncryption()) } @Test - fun whenCanSupportEncryptionIfCannotThenReturnFalse() = runTest { + fun `canSupportEncryption - cannot support - return 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 - user authenticated and valid token - return true`() = runTest { givenUserIsAuthenticated() givenValidateTokenSucceedsWithEntitlements() givenDeleteAccountSucceeds() @@ -922,7 +922,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenDeleteAccountIfUserNotAuthenticatedThenReturnFalse() = runTest { + fun `deleteAccount - user not authenticated - return false`() = runTest { givenUserIsNotAuthenticated() givenDeleteAccountFails() @@ -930,7 +930,7 @@ class RealSubscriptionsManagerTest { } @Test - fun whenDeleteAccountIfUserAuthenticatedWithSubscriptionAndTokenExpiredAndEntitlementsExistsThenReturnTrue() = runTest { + fun `deleteAccount - user authenticated with subscription, token expired, entitlements exist - return 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..637c97fc67dc 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 - success - return access token`() = runTest { whenever(mockSubscriptionsManager.getAccessToken()).thenReturn(AccessToken.Success("accessToken")) val result = subscriptions.getAccessToken() assertEquals("accessToken", result) } @Test - fun whenGetAccessTokenFailsThenReturnNull() = runTest { + fun `getAccessToken - access token fails - return null`() = runTest { whenever(mockSubscriptionsManager.getAccessToken()).thenReturn(AccessToken.Failure("error")) assertNull(subscriptions.getAccessToken()) } @Test - fun whenGetEntitlementStatusHasEntitlementAndEnabledAndActiveThenReturnList() = runTest { + fun `getEntitlementStatus - has entitlement and enabled and active - return 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 - return 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 - no offers returned - return false if not active or waiting`() = runTest { whenever(mockSubscriptionsManager.subscriptionStatus()).thenReturn(UNKNOWN) whenever(mockSubscriptionsManager.getSubscriptionOffer()).thenReturn(null) assertFalse(subscriptions.isEligible()) } @Test - fun whenIsEligibleIfNotOffersReturnedThenReturnTrueIfWaiting() = runTest { + fun `isEligible - no offers returned - return true if waiting`() = runTest { whenever(mockSubscriptionsManager.subscriptionStatus()).thenReturn(WAITING) whenever(mockSubscriptionsManager.getSubscriptionOffer()).thenReturn(null) assertTrue(subscriptions.isEligible()) } @Test - fun whenIsEligibleIfNotOffersReturnedThenReturnTrueIfActive() = runTest { + fun `isEligible - no offers returned - returns true if active`() = runTest { whenever(mockSubscriptionsManager.subscriptionStatus()).thenReturn(AUTO_RENEWABLE) whenever(mockSubscriptionsManager.getSubscriptionOffer()).thenReturn(null) assertTrue(subscriptions.isEligible()) } @Test - fun whenIsEligibleIfNotEncryptionThenReturnTrueIfActive() = runTest { + fun `isEligible - not encryption - return 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 - return correct value`() = 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 - return 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 - not eligible - return false`() = runTest { whenever(mockSubscriptionsManager.subscriptionStatus()).thenReturn(UNKNOWN) assertFalse(subscriptions.shouldLaunchPrivacyProForUrl("https://duckduckgo.com/pro")) } @Test - fun whenLaunchPrivacyProWithOriginThenPassTheOriginToActivity() = runTest { + fun `launchPrivacyPro - with origin - pass the origin 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..90614727a7ef 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 `process created - 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 `processLifecycleOwner - connection failed - does not attempt loading anything`() = 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 `getProducts - connected - returns products`() = 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 `launchBillingFlow - service not ready - attempts to connect`() = 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 `disconnectionListener - service disconnected - attempt to connect`() = 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 `connect - recoverable error - retry with exponential backoff`() = 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 ProductDetails 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..22ed991a2969 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 `retry - block returns true - does not retry`() = 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 `retry - block returns false - does retry`() = 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 `retry - block returns true - stops retrying`() = 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 `retry - 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..3ec967310039 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 `process - unknown message - do nothing`() = runTest { givenInterfaceIsRegistered() messagingInterface.process("", "secret") @@ -56,7 +56,7 @@ class ItrMessagingInterfaceTest { } @Test - fun whenProcessUnknownSecretDoNothing() = runTest { + fun `process - unknown secret - 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 `process - interface not registered - do nothing`() = runTest { whenever(webView.url).thenReturn("https://duckduckgo.com/test") val message = """ @@ -95,7 +95,7 @@ class ItrMessagingInterfaceTest { } @Test - fun whenProcessIfMethodDoesNotMatchDoNothing() = runTest { + fun `process - method does not match - do nothing`() = runTest { givenInterfaceIsRegistered() givenAccessTokenIsSuccess() @@ -109,7 +109,7 @@ class ItrMessagingInterfaceTest { } @Test - fun whenProcessAndGetAccessTokenIfNoIdDoNothing() = runTest { + fun `process - no id - do nothing`() = runTest { givenInterfaceIsRegistered() givenAccessTokenIsSuccess() @@ -123,7 +123,7 @@ class ItrMessagingInterfaceTest { } @Test - fun whenProcessAndGetAccessTokenMessageThenReturnResponse() = runTest { + fun `process - get access token message - return response`() = runTest { givenInterfaceIsRegistered() givenAccessTokenIsSuccess() @@ -150,7 +150,7 @@ class ItrMessagingInterfaceTest { } @Test - fun whenProcessAndGetAccessTokenMessageErrorThenReturnResponse() = runTest { + fun `process - get access token message error - return response`() = runTest { givenInterfaceIsRegistered() givenAccessTokenIsFailure() @@ -177,7 +177,7 @@ class ItrMessagingInterfaceTest { } @Test - fun whenProcessAndGetAccessTokenMessageIfUrlNotInAllowListedDomainsThenDoNothing() = runTest { + fun `process - 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..adbb33fe3d14 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 `process - unknown message - do nothing`() = runTest { givenInterfaceIsRegistered() messagingInterface.process("", "secret") @@ -68,7 +68,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessUnknownSecretDoNothing() = runTest { + fun `process - unknown secret - do nothing`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -82,7 +82,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessNoUrlDoNothing() = runTest { + fun `process - no URL - do nothing`() = runTest { messagingInterface.register(webView, callback) val message = """ @@ -96,7 +96,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessInterfaceNotRegisteredDoNothing() = runTest { + fun `process - interface not registered - do nothing`() = runTest { whenever(webView.url).thenReturn("https://duckduckgo.com/test") val message = """ @@ -110,7 +110,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessIfMethodDoesNotMatchDoNothing() = runTest { + fun `process - method does not match - do nothing`() = runTest { givenInterfaceIsRegistered() givenAuthTokenIsSuccess() @@ -124,7 +124,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndGetSubscriptionsMessageIfActiveThenReturnResponse() = runTest { + fun `process - subscription active - return response`() = runTest { givenInterfaceIsRegistered() givenAuthTokenIsSuccess() givenSubscriptionIsActive() @@ -152,7 +152,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndGetSubscriptionsMessageIfNotActiveThenReturnError() = runTest { + fun `process - not active subscription - return error`() = runTest { givenInterfaceIsRegistered() givenAuthTokenIsSuccess() @@ -179,7 +179,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndGetSubscriptionsMessageErrorThenReturnResponse() = runTest { + fun `process - auth token failure - return response`() = runTest { givenInterfaceIsRegistered() givenAuthTokenIsFailure() @@ -206,7 +206,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndGetSubscriptionsIfFeatureNameDoesNotMatchDoNothing() = runTest { + fun `process - feature name does not match - do nothing`() = runTest { givenInterfaceIsRegistered() givenAuthTokenIsSuccess() @@ -220,7 +220,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndGetSubscriptionIfNoIdDoNothing() = runTest { + fun `process - no subscription id - do nothing`() = runTest { givenInterfaceIsRegistered() givenAuthTokenIsSuccess() @@ -247,7 +247,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndBackToSettingsThenCallbackExecuted() = runTest { + fun `process - back to settings - callback executed`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -274,7 +274,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndSetSubscriptionMessageThenAuthenticate() = runTest { + fun `process - set subscription message - authenticate`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -290,7 +290,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndSetSubscriptionMessageAndNoTokenThenDoNothing() = runTest { + fun `process - no token - do nothing`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -317,7 +317,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndGetSubscriptionOptionsMessageThenCallbackCalled() = runTest { + fun `process - getSubscriptionOptions message - callback called`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -330,7 +330,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndGetSubscriptionOptionsMessageAndNoIdThenDoNothing() = runTest { + fun `process - getSubscriptionOptions message with no id - do nothing`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -357,7 +357,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndSubscriptionSelectedMessageThenCallbackCalled() = runTest { + fun `process - subscription selected message - callback called`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -383,7 +383,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndActivateSubscriptionThenCallbackExecuted() = runTest { + fun `process - activate subscription - callback executed`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -409,7 +409,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndFeatureSelectedThenCallbackExecuted() = runTest { + fun `process - feature selected - callback executed`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -422,7 +422,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndFeatureSelectedMessageIfUrlNotInAllowListedDomainsThenDoNothing() = runTest { + fun `process - 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 `process - backToSettingsActivateSuccess - callback executed`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -462,7 +462,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndMonthlyPriceClickedThenPixelSent() = runTest { + fun `process - monthly price clicked - pixel sent`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -476,7 +476,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndYearlyPriceClickedThenPixelSent() = runTest { + fun `process - yearly price clicked - pixel sent`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -490,7 +490,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndAddEmailSuccessThenPixelSent() = runTest { + fun `process - add email success - pixel sent`() = runTest { givenInterfaceIsRegistered() val message = """ @@ -504,7 +504,7 @@ class SubscriptionMessagingInterfaceTest { } @Test - fun whenProcessAndFaqClickedThenCallbackExecuted() = runTest { + fun `process - faq clicked - 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 `process - add email clicked - 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..be2f8f3cd5b4 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 - no access token - return false`() = runTest { authStore.authToken = "authToken" assertFalse(authRepository.isUserAuthenticated()) } @Test - fun whenIsAuthenticatedAndNoAuthTokenThenReturnFalse() = runTest { + fun `isUserAuthenticated - no auth token - return false`() = runTest { authStore.accessToken = "accessToken" assertFalse(authRepository.isUserAuthenticated()) } @Test - fun whenIsAuthenticatedAndNoAuthTokenAndAccessTokenThenReturnFalse() = runTest { + fun `isUserAuthenticated - no auth token and access token - return false`() = runTest { assertFalse(authRepository.isUserAuthenticated()) } @Test - fun whenIsAuthenticatedThenReturnTrue() = runTest { + fun `isUserAuthenticated - authenticated - returns 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`() = runTest { assertNull(authStore.authToken) assertNull(authStore.externalId) @@ -90,7 +90,7 @@ class RealAuthRepositoryTest { } @Test - fun whenTokensThenReturnTokens() = runTest { + fun `getAuthToken - returns tokens`() = runTest { assertNull(authStore.authToken) assertNull(authStore.accessToken) @@ -102,13 +102,13 @@ class RealAuthRepositoryTest { } @Test - fun whenPurchaseToWaitingStatusThenStoreWaiting() = runTest { + fun `purchaseToWaitingStatus - store waiting`() = runTest { authRepository.purchaseToWaitingStatus() assertEquals(WAITING.statusName, authStore.status) } @Test - fun whenGetStatusReturnCorrectStatus() = runTest { + fun `getStatus - return correct status`() = 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 - support encryption false - 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..203735915b8d 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 - pro eligible matching attribute - correct 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..1c291428d9f0 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 `evaluate - pro eligible matching attribute - correct value`() = 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 `map - no pro eligible matching attribute key - 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..6a6f2510b6e1 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 `onCreate - subscription emit - viewState updated`() = runTest { whenever(subscriptions.getEntitlementStatus()).thenReturn( flowOf( listOf(ITR), @@ -62,7 +62,7 @@ class ItrSettingViewModelTest { } @Test - fun whenOnResumeIfNotSubscriptionEmitViewState() = runTest { + fun `onResume - not subscription - emit viewState`() = 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..bd29de0f10c1 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 `onCreate - entitlement present - emit viewState`() = 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 viewState`() = 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..2eabb89eae28 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 - emit viewState`() = 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..e35a27c026f7 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 - subscription failure - emit error`() = 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 AddEmail`() = runTest { whenever(subscriptionsManager.getAccount()).thenReturn( Account(email = "", externalId = "externalId"), ) @@ -63,7 +63,7 @@ class AddDeviceViewModelTest { } @Test - fun whenUseEmailIEmailNullThenEmitAddEmail() = runTest { + fun `useEmail - email null - emit AddEmail`() = runTest { whenever(subscriptionsManager.getAccount()).thenReturn( Account(email = null, externalId = "externalId"), ) @@ -74,7 +74,7 @@ class AddDeviceViewModelTest { } @Test - fun whenUseEmailIfEmailThenEmitManage() = runTest { + fun `useEmail - email present - 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 - emit 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 is 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..1390fcf74d51 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`() = runTest { viewModel.commands().test { viewModel.restoreFromEmail() assertTrue(awaitItem() is RestoreFromEmail) @@ -53,7 +53,7 @@ class RestoreSubscriptionViewModelTest { } @Test - fun whenRestoreFromStoreIfFailureThenReturnError() = runTest { + fun `restoreFromStore - 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 - return 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 - subscription not active - return not found`() = runTest { whenever(subscriptionsManager.recoverSubscriptionFromStore()).thenReturn( RecoverSubscriptionResult.Success(subscriptionNotActive()), ) @@ -92,7 +92,7 @@ class RestoreSubscriptionViewModelTest { } @Test - fun whenRestoreFromStoreIfActiveThenReturnSuccess() = runTest { + fun `restoreFromStore - active subscription - 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 is sent`() = runTest { whenever(subscriptionsManager.recoverSubscriptionFromStore()).thenReturn( RecoverSubscriptionResult.Success(subscriptionActive()), ) @@ -127,7 +127,7 @@ class RestoreSubscriptionViewModelTest { } @Test - fun whenRestoreFromStoreFailsBecauseThereAreNoEntitlementsThenPixelIsSent() = runTest { + fun `restoreFromStore - no entitlements - pixel sent`() = runTest { whenever(subscriptionsManager.recoverSubscriptionFromStore()).thenReturn( RecoverSubscriptionResult.Success(subscriptionNotActive()), ) @@ -137,7 +137,7 @@ class RestoreSubscriptionViewModelTest { } @Test - fun whenRestoreFromStoreFailsBecauseThereIsNoSubscriptionThenPixelIsSent() = runTest { + fun `restoreFromStore - no subscription - pixel is sent`() = runTest { whenever(subscriptionsManager.recoverSubscriptionFromStore()).thenReturn( RecoverSubscriptionResult.Failure(SUBSCRIPTION_NOT_FOUND_ERROR), ) @@ -147,7 +147,7 @@ class RestoreSubscriptionViewModelTest { } @Test - fun whenRestoreFromStoreFailsForOtherReasonThenPixelIsSent() = runTest { + fun `restoreFromStore - failure for other reason - pixel is 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..ebf9c95e3486 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 `onCreate - subscription - format date correctly`() = runTest { whenever(subscriptionsManager.getSubscription()).thenReturn( Subscription( productId = SubscriptionsConstants.MONTHLY_PLAN, @@ -67,7 +67,7 @@ class SubscriptionSettingsViewModelTest { } @Test - fun whenSubscriptionMonthlyThenReturnMonthly() = runTest { + fun `onCreate - subscription monthly - return monthly`() = runTest { whenever(subscriptionsManager.getSubscription()).thenReturn( Subscription( productId = SubscriptionsConstants.MONTHLY_PLAN, @@ -89,7 +89,7 @@ class SubscriptionSettingsViewModelTest { } @Test - fun whenSubscriptionYearlyThenReturnYearly() = runTest { + fun `onCreate - subscription yearly - return 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 - 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 is 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..65b8b7f604d4 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 `start - purchase state changes - return correct state`() = 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 - 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 null - return 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 - backToSettings - 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 - backToSettingsActivateSuccess - 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 `processJsCallbackMessage - getSubscriptionOptions - 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 `processJsCallbackMessage - no subscription offer - 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 - 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 - 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 - 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 - 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 - invalid feature selected - 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 is NetP - 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 feature is 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 `processJsCallbackMessage - in purchase flow - pixel is 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 - add email clicked and 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 `processJsCallbackMessage - feature selected and feature is NetP and in purchase flow - pixel is 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 feature is NetP and not in purchase flow - pixel is not sent`() = runTest { whenever(subscriptionsManager.subscriptionStatus()).thenReturn(AUTO_RENEWABLE) viewModel.processJsCallbackMessage( @@ -450,7 +450,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenFeatureSelectedAndFeatureIsItrAndInPurchaseFlowThenPixelIsSent() = runTest { + fun `processJsCallbackMessage - feature selected and feature is ITR and in purchase flow - pixel is sent`() = runTest { whenever(subscriptionsManager.subscriptionStatus()).thenReturn(AUTO_RENEWABLE) whenever(subscriptionsManager.currentPurchaseState).thenReturn(flowOf(CurrentPurchase.Success)) viewModel.start() @@ -465,7 +465,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenFeatureSelectedAndFeatureIsItrAndNotInPurchaseFlowThenPixelIsNotSent() = 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 `processJsCallbackMessage - feature selected and feature is PIR and in purchase flow - pixel is sent`() = runTest { whenever(subscriptionsManager.subscriptionStatus()).thenReturn(AUTO_RENEWABLE) whenever(subscriptionsManager.currentPurchaseState).thenReturn(flowOf(CurrentPurchase.Success)) viewModel.start() @@ -493,7 +493,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenFeatureSelectedAndFeatureIsPirAndNotInPurchaseFlowThenPixelIsNotSent() = runTest { + fun `processJsCallbackMessage - feature selected and feature is PIR and not in purchase flow - pixel is not sent`() = runTest { whenever(subscriptionsManager.subscriptionStatus()).thenReturn(AUTO_RENEWABLE) viewModel.processJsCallbackMessage( @@ -521,7 +521,7 @@ class SubscriptionWebViewViewModelTest { } @Test - fun whenSubscriptionsWelcomeFaqClickedAndNotInPurchaseFlowThenPixelIsNotSent() = runTest { + fun `processJsCallbackMessage - subscriptions welcome FAQ clicked not in purchase flow - pixel 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..432e56f5c96e 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 `userId - userId exists in store - returns stored value`() { val syncStore = getFakeSyncStore() val appSyncDeviceIds = AppSyncDeviceIds(syncStore, deviceInfo) assertEquals(syncStore.userId, appSyncDeviceIds.userId()) } @Test - fun whenDeviceIdExistsInStoreThenReturnsStoredValue() { + fun `deviceId - 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 `deviceName - 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 `userId - 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 - device id 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 - device name does not exist in store - new id returned`() { val emptySyncStore = getFakeEmptySyncStore() assertNull(emptySyncStore.deviceName) val appSyncDeviceIds = AppSyncDeviceIds(emptySyncStore, deviceInfo) @@ -89,7 +89,7 @@ class AppSyncDeviceIdsTest { } @Test - fun whenPlatformTypeIsAndroidPhoneThenDeviceTypeMobile() { + fun `deviceType - platform type is android phone - device type 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..3b4e677024ad 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 - user signed in - device sync enabled`() { whenever(syncAccountRepository.isSignedIn()).thenReturn(true) assertTrue(appDeviceSyncState.isUserSignedInOnDevice()) } @Test - fun whenShowSyncDisabledThenFeatureDisabled() { + fun `isFeatureEnabled - feature flag disabled - feature disabled`() { givenFeatureFlag(enabled = false) assertFalse(appDeviceSyncState.isFeatureEnabled()) } @Test - fun whenShowSyncEnabledThenFeatureEnabled() { + fun `isFeatureEnabled - sync enabled - 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..fe2e8da6fa58 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 - success - account 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 - create account 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 - return data`() { givenAuthenticatedDevice() val result = syncRepo.getAccountInfo() @@ -168,7 +168,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenAccountNotCreatedThenAccountInfoEmpty() { + fun `getAccountInfo - account not created - account info empty`() { whenever(syncStore.primaryKey).thenReturn("") val result = syncRepo.getAccountInfo() @@ -180,7 +180,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenLogoutSucceedsThenReturnSuccessAndRemoveData() { + fun `logout - 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 - remote device 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 - delete account succeeds - return success and remove data`() { givenAuthenticatedDevice() whenever(syncApi.deleteAccount(token)).thenReturn(deleteAccountSuccess) @@ -214,7 +214,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenProcessJsonRecoveryCodeSucceedsThenAccountPersisted() { + fun `processCode - json recovery code succeeds - account persisted`() { prepareForLoginSuccess() val result = syncRepo.processCode(jsonRecoveryKeyEncoded) @@ -231,7 +231,7 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenGenerateKeysFromRecoveryCodeFailsThenReturnLoginFailedError() { + fun `processCode - generate keys from recovery code 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 `processCode - decrypt secret key fails - return 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 - return invalid code error`() { val result = syncRepo.processCode("invalidCode") as Error assertEquals(INVALID_CODE.code, result.code) } @Test - fun getConnectedDevicesSucceedsThenReturnSuccess() { + fun `getConnectedDevices - succeeds - return 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 - generate recovery code as string - return expected json`() { whenever(syncStore.primaryKey).thenReturn(primaryKey) whenever(syncStore.userId).thenReturn(userId) @@ -340,14 +340,14 @@ class AppSyncAccountRepositoryTest { } @Test - fun whenGenerateRecoveryCodeWithoutAccountThenReturnGenericError() { + fun `getRecoveryCode - without account - return 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 `processCode - authenticated device - 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 `processCode - unauthenticated device - 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 - keys expired - return 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 - authenticated device - returns 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 - return 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 - sync 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..30d36e8081c4 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 - sync disabled - 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 - sync enabled - state is READY`() = runTest { testee.syncState().test { signedInFlow.emit(true) val state = expectMostRecentItem() @@ -77,7 +77,7 @@ class RealSyncStateMonitorTest { } @Test - fun whenSyncEnabledAndAttemptSuccessThenStateIsReady() = runTest { + fun `syncState - sync enabled and 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 `syncState - sync enabled and 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 - sync enabled and attempt in progress - state is 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..b1c29d9502e6 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 - 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 - 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 - decrypt fails - result is empty`() { 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 - 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 is empty - result is 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..e64f3f19fc3d 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 `showSync - feature disabled - internal build shows 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 `showSync - feature disabled - 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 - allowDataSyncing false - false`() { val syncFeature = TestSyncFeature(appBuildConfig).apply { allowDataSyncing = false } @@ -100,7 +100,7 @@ class SyncRemoteFeatureToggleTest { } @Test - fun whenAllowDataSyncEnabledButNotForThisVersionThenAllowDataSyncingOnNewerVersionTrue() { + fun `allowDataSyncing - 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 `allowSetupFlows - allow data syncing false - setup flows and create account disabled`() { val syncFeature = TestSyncFeature(appBuildConfig).apply { allowDataSyncing = false } @@ -124,7 +124,7 @@ class SyncRemoteFeatureToggleTest { } @Test - fun whenAllowSetupFlowsFalseThenAllowDataSyncingEnabled() { + fun `allowDataSyncing - setup flows false - enabled`() { val syncFeature = TestSyncFeature(appBuildConfig).apply { allowSetupFlows = false } @@ -134,7 +134,7 @@ class SyncRemoteFeatureToggleTest { } @Test - fun whenAllowSetupFlowsEnabledButNotForThisVersionThenAllowSetupFlowsOnNewerVersionTrue() { + fun `allowSetupFlows - enabled but 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 disabled - setup flows and create account disabled`() { val syncFeature = TestSyncFeature(appBuildConfig).apply { allowSetupFlows = false } @@ -158,7 +158,7 @@ class SyncRemoteFeatureToggleTest { } @Test - fun whenAllowCreateAccountFalseThenAllowCreateAccountFalse() { + fun `allowCreateAccount - allowCreateAccount false - false`() { val syncFeature = TestSyncFeature(appBuildConfig).apply { allowCreateAccount = false } @@ -168,7 +168,7 @@ class SyncRemoteFeatureToggleTest { } @Test - fun whenAllowCreateAccountTrueButNotForThisVersionThenAllowCreateAccountOnNewerVersionTrue() { + fun `allowCreateAccount - not for this version - allowCreateAccountOnNewerVersion true`() { whenever(appBuildConfig.versionCode).thenReturn(1) val syncFeature = TestSyncFeature(appBuildConfig).apply { allowCreateAccount = true @@ -181,7 +181,7 @@ class SyncRemoteFeatureToggleTest { } @Test - fun whenAllowCreateAccountFalseThenDataSyncingAndSetupFlowsEnabled() { + fun `allowDataSyncing and allowSetupFlows - allowCreateAccount false - 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..b95041dcf6cd 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 - success - account created`() { 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 - invalid account - 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 - 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 - 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 account - 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 - login succeeds - return 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 credentials - return 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 - return 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 - connect fails - return 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 - connect device 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..6f8ec56dff89 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 `patch - bookmark changes - api is 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 `patch - bookmark changes - 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 `getBookmarks - token empty - return error`() { whenever(syncStore.token).thenReturn("") val result = apiClient.get(BOOKMARKS, "") @@ -118,7 +118,7 @@ internal class SyncApiClientTest { } @Test - fun whenGetCredentialsBookmarksAndTokenEmptyThenReturnError() { + fun `get - credentials bookmarks and token empty - return error`() { whenever(syncStore.token).thenReturn("") val result = apiClient.get(CREDENTIALS, "") @@ -128,7 +128,7 @@ internal class SyncApiClientTest { } @Test - fun whenGetBookmarksAndApiFailsThenResultIsErrorAndErrorIsRecorded() { + fun `getBookmarks - API fails - result is error and error is 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 - result is error and error is 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 `getBookmarks - API count limit fails - result is error and error is 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 `getCredentials - api count limit fails - result is error and error is 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..a9c74e05774e 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 `triggerSync - sync is disabled - no sync operation is 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`() { whenever(syncStore.isSignedIn()).thenReturn(false) syncEngine.triggerSync(APP_OPEN) verifyNoInteractions(syncApiClient) @@ -108,7 +108,7 @@ internal class SyncEngineTest { } @Test - fun whenDataChangesAndSyncIsDisabledNoSyncOperationIsTriggered() { + fun `triggerSync - sync is 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 - creating sync account - data sent and 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 `triggerSync - account creation - data sent and state updated with error`() { givenLocalChanges() givenPatchError() @@ -164,7 +164,7 @@ internal class SyncEngineTest { } @Test - fun whenAppOpenWithoutChangesAndGetRemoteSucceedsThenStateIsUpdated() { + fun `triggerSync - app open without changes and get remote succeeds - state is updated`() { givenNoLocalChanges() givenGetSuccess() @@ -177,7 +177,7 @@ internal class SyncEngineTest { @Test @Ignore // https://app.asana.com/0/1204842202586359/1205158805627400/f - fun whenAppOpenWithoutChangesAndGetRemoteFailsThenStateIsUpdated() { + fun `triggerSync - app open without changes and get remote fails - state is updated`() { givenNoLocalChanges() givenGetError() @@ -188,7 +188,7 @@ internal class SyncEngineTest { } @Test - fun whenAppOpenWithChangesAndPatchRemoteSucceedsThenStateIsUpdated() { + fun `triggerSync - app open with changes and patch remote succeeds - state is updated`() { givenLocalChanges() givenPatchSuccess() @@ -199,7 +199,7 @@ internal class SyncEngineTest { } @Test - fun whenAppOpenWithChangesAndFeatureFirstSyncThenPerformGetAndPatch() { + fun `triggerSync - app open with changes and feature first sync - 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 `triggerSync - patch remote fails - state is updated`() { givenLocalChanges() givenPatchError() @@ -225,7 +225,7 @@ internal class SyncEngineTest { } @Test - fun whenFeatureReadWithoutChangesAndGetRemoteSucceedsThenStateIsUpdated() { + fun `triggerSync - no local changes and get remote succeeds - state is updated`() { givenNoLocalChanges() givenGetSuccess() @@ -238,7 +238,7 @@ internal class SyncEngineTest { @Test @Ignore // https://app.asana.com/0/1204842202586359/1205158805627400/f - fun whenFeatureReadWithoutChangesAndGetRemoteFailsThenStateIsUpdated() { + fun `triggerSync - get remote fails - state is updated`() { givenNoLocalChanges() givenGetError() @@ -249,7 +249,7 @@ internal class SyncEngineTest { } @Test - fun whenFeatureReadWithChangesAndPatchRemoteSucceedsThenStateIsUpdated() { + fun `triggerSync - patch remote succeeds - state is updated`() { givenLocalChanges() givenPatchSuccess() @@ -286,7 +286,7 @@ internal class SyncEngineTest { @Test @Ignore // https://app.asana.com/0/1204842202586359/1205158805627400/f - fun whenDataChangeWithoutChangesAndGetRemoteFailsThenStateIsUpdated() { + fun `triggerSync - no local changes and get remote fails - state is updated`() { givenNoLocalChanges() givenGetError() @@ -297,7 +297,7 @@ internal class SyncEngineTest { } @Test - fun whenDataChangeWithChangesAndPatchRemoteSucceedsThenStateIsUpdated() { + fun `triggerSync - data change with changes and patch remote succeeds - state is updated`() { givenLocalChanges() givenPatchSuccess() @@ -308,7 +308,7 @@ internal class SyncEngineTest { } @Test - fun whenDataChangeWithChangesForFirstSyncThenStateIsUpdated() { + fun `triggerSync - data change with changes for first sync - state is updated`() { givenFirstSyncLocalChanges() givenPatchSuccess() givenGetSuccess() @@ -334,7 +334,7 @@ internal class SyncEngineTest { } @Test - fun whenBackgroundSyncCantBeScheduledThenNothingHappens() { + fun `scheduleOperation - background sync can't be scheduled - nothing happens`() { whenever(syncScheduler.scheduleOperation()).thenReturn(DISCARD) verifyNoInteractions(syncApiClient) @@ -342,7 +342,7 @@ internal class SyncEngineTest { } @Test - fun whenBackgroundSyncWithoutChangesAndGetRemoteSucceedsThenStateIsUpdated() { + fun `triggerSync - background sync without changes and get remote succeeds - state is 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 `triggerSync - background sync without changes and get remote fails - state is updated`() { whenever(syncScheduler.scheduleOperation()).thenReturn(EXECUTE) givenNoLocalChanges() givenGetError() @@ -368,7 +368,7 @@ internal class SyncEngineTest { } @Test - fun whenBackgroundSyncWithChangesAndPatchRemoteSucceedsThenStateIsUpdated() { + fun `triggerSync - background sync with changes and patch remote succeeds - state is updated`() { whenever(syncScheduler.scheduleOperation()).thenReturn(EXECUTE) givenLocalChanges() givenPatchSuccess() @@ -396,7 +396,7 @@ internal class SyncEngineTest { @Test @Ignore // https://app.asana.com/0/1204842202586359/1205158805627400/f - fun whenBackgroundSyncWithChangesAndPatchRemoteFailsThenStateIsUpdated() { + fun `triggerSync - background sync with changes and patch remote fails - state is 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 `triggerSync - account login get remote fails - state is updated`() { givenLocalChanges() givenGetError() @@ -421,7 +421,7 @@ internal class SyncEngineTest { } @Test - fun whenAccountLoginSucceedsThenStateIsUpdated() { + fun `triggerSync - account login succeeds - state is updated`() { givenFirstSyncLocalChanges() givenPatchSuccess() givenGetSuccess() @@ -434,14 +434,14 @@ internal class SyncEngineTest { } @Test - fun whenTriggeringSyncAndSyncAlreadyInProgressThenSyncIsDismissed() { + fun `triggerSync - sync already in progress - sync is dismissed`() { whenever(syncStateRepository.current()).thenReturn(SyncAttempt(state = IN_PROGRESS)) syncEngine.triggerSync(DATA_CHANGE) verifyNoInteractions(syncApiClient) } @Test - fun whenPatchNewDataFailsBecauseCountLimitThenNotifyFeature() { + fun `triggerSync - 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 `triggerSync - patch content too large - notify feature`() { givenLocalChanges() givenPatchContentTooLargeError() val persisterPluginMock = mock() @@ -465,7 +465,7 @@ internal class SyncEngineTest { } @Test - fun whenPatchNewDataFailsBecauseNonFeatureErrorThenDoNotNotifyFeature() { + fun `triggerSync - 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 `triggerSync - daily - pixel is sent`() { givenLocalChanges() givenPatchSuccess() @@ -490,7 +490,7 @@ internal class SyncEngineTest { } @Test - fun whenSyncTriggeredWithChangesAndPatchRemoteSucceedsWithTimestampConflictThenStateIsUpdatedAndPixelIsFired() { + fun `triggerSync - patch remote succeeds with timestamp conflict - state updated and pixel fired`() { givenLocalChangesWithTimestampConflict() givenPatchSuccess() @@ -504,7 +504,7 @@ internal class SyncEngineTest { } @Test - fun whenSyncTriggeredWithChangesAndPatchRemoteSucceedsWithOrphansThenStateIsUpdatedAndPixelIsFired() { + fun `triggerSync - changes with orphans and patch remote succeeds - 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..c86095015bb6 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 `scheduleOperation - first sync - can be executed`() { whenever(syncStateRepository.current()).thenReturn(null) val syncOperation = syncScheduler.scheduleOperation() @@ -50,7 +50,7 @@ class SyncSchedulerTest { } @Test - fun whenLastSyncFailedThenSyncIsExecuted() { + fun `scheduleOperation - last sync failed - sync is executed`() { 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 `scheduleOperation - last sync in progress - sync is discarded`() { 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 `scheduleOperation - last sync before debounce period - sync discarded`() { 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 `scheduleOperation - 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..8dc4c6c21d29 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 `signedOut - first event drops - 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 `onCreate - signed in and signed 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..ffaba593b8de 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 is empty - returns null`() { val currentSync = repository.current() assertTrue(currentSync == null) } @Test - fun whenSyncInProgressThenCurrentReturnsAttempt() { + fun `current - sync in progress - returns attempt`() { val sync = SyncAttempt(state = SyncAttemptState.IN_PROGRESS) repository.store(sync) @@ -64,7 +64,7 @@ class SyncStateRepositoryTest { } @Test - fun whenSyncStateIsUpdatedThenDaoIsUpdated() { + fun `updateSyncState - sync state updated - 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..c70748580e4a 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 - 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 - 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 - repository adds error`() { 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 - repository adds error`() { 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..982d606d104a 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 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 `getErrorsByDate - no errors stored - returns 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 `getErrorsByDate - errors stored - 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..9e67aeb2f7b3 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 - encrypt error reported - repository adds error`() { val error = SyncOperationErrorType.DATA_ENCRYPT recorder.record(error) @@ -39,7 +39,7 @@ internal class SyncOperationErrorRecorderTest { } @Test - fun wheneverDecryptErrorReportedThenRepositoryAddsError() { + fun `record - decrypt error reported - repository adds error`() { val error = SyncOperationErrorType.DATA_DECRYPT 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..62c65faea2a1 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 - error not present - new entry added`() { val errorType = SyncOperationErrorType.DATA_ENCRYPT val date = DatabaseDateFormatter.getUtcIsoLocalDate() @@ -89,7 +89,7 @@ class SyncOperationErrorRepositoryTest { } @Test - fun whenOperationErrorAddedAndPresentThenCountUpdated() { + fun `addError - error present - count updated`() { val errorType = SyncOperationErrorType.DATA_ENCRYPT val date = DatabaseDateFormatter.getUtcIsoLocalDate() @@ -103,7 +103,7 @@ class SyncOperationErrorRepositoryTest { } @Test - fun whenNoErrorsStoredThenGettingErrorsReturnsEmpty() { + fun `getErrorsByDate - no errors stored - returns 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 `getErrorsByDate - errors stored - returns data`() { 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 `getErrorsByDate - provider errors stored - returns data`() { val feature = SyncableType.BOOKMARKS val errorType = SyncOperationErrorType.DATA_PROVIDER_ERROR val today = DatabaseDateFormatter.getUtcIsoLocalDate() @@ -173,7 +173,7 @@ class SyncOperationErrorRepositoryTest { } @Test - fun whenTimestampErrorsStoredThenGettingErrorsReturnsData() { + fun `getErrorsByDate - timestamp errors stored - 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..b2d45a8ae401 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 - only one 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 `shouldShow - more than one device 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 - should show`() { 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..2a9356367fd1 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 - daily stats - pixel fired`() { val dailyStats = givenSomeDailyStats() testee.fireDailySuccessRatePixel() @@ -69,7 +69,7 @@ class SyncPixelsTest { } @Test - fun whenDailyPixelCalledTwiceThenPixelFiredOnce() { + fun `fireDailySuccessRatePixel - called twice - 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..067f94027fa9 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 is 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 - 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 - 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 - 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 - 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 - 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 - 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..48971c095de4 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 - sync is triggered`() = 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..88c332b2a927 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 is 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..2f10edf006b9 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 - sync triggered and 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 - sync not triggered and 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..2f86d7613c2b 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 - is 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 is pasted`() = runTest { whenever(clipboard.pasteFromClipboard()).thenReturn(jsonRecoveryKeyEncoded) testee.onPasteCodeClicked() @@ -78,7 +78,7 @@ internal class EnterCodeViewModelTest { } @Test - fun whenUserClicksOnPasteCodeWithRecoveryCodeThenProcessCode() = runTest { + fun `onPasteCodeClicked - recovery code in clipboard - process code`() = 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 - paste code with connect code - process code`() = 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 - pasted invalid code - authState 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..ef558db4f1d6 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 - device sync enabled`() = runTest { givenAuthenticatedUser() testee.viewState().test { @@ -114,7 +114,7 @@ class SyncActivityViewModelTest { } @Test - fun whenUserSignedInThenShowAccount() = runTest { + fun `viewState - user signed in - 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 `viewState - multiple connected devices - show devices`() = runTest { givenAuthenticatedUser() val connectedDevices = listOf(connectedDevice, connectedDevice) @@ -154,7 +154,7 @@ class SyncActivityViewModelTest { } @Test - fun whenSyncWithAnotherDeviceThenEmitCommandSyncWithAnotherDevice() = runTest { + fun `onSyncWithAnotherDevice - emit command`() = 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 - scan another device QR code - 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 - without 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 - recover data command sent`() = runTest { givenUserHasDeviceAuthentication(true) testee.onRecoverYourSyncedData() @@ -229,7 +229,7 @@ class SyncActivityViewModelTest { } @Test - fun whenRecoverDataWithoutDeviceAuthenticationThenEmitCommandRequestSetupAuthentication() = runTest { + fun `onRecoverYourSyncedData - without device authentication - 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 `onTurnOffSyncConfirmed - logout success - update viewState`() = runTest { givenAuthenticatedUser() whenever(syncAccountRepository.logout(deviceId)).thenReturn(Result.Success(true)) @@ -278,7 +278,7 @@ class SyncActivityViewModelTest { } @Test - fun whenLogoutErrorThenUpdateViewState() = runTest { + fun `onTurnOffSyncConfirmed - logout error - update viewState`() = 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 `onDeleteAccountConfirmed - delete account success - update viewState`() = runTest { givenAuthenticatedUser() whenever(syncAccountRepository.deleteAccount()).thenReturn(Result.Success(true)) @@ -331,7 +331,7 @@ class SyncActivityViewModelTest { } @Test - fun whenDeleteAccountErrorThenUpdateViewState() = runTest { + fun `onDeleteAccountConfirmed - delete account error - update viewState`() = runTest { givenAuthenticatedUser() whenever(syncAccountRepository.deleteAccount()).thenReturn(Result.Error(reason = "error")) @@ -346,7 +346,7 @@ class SyncActivityViewModelTest { } @Test - fun whenDeleteAccountConfirmedThenDeleteAccount() = runTest { + fun `onDeleteAccountConfirmed - 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 - authenticated user - remove device`() = runTest { givenAuthenticatedUser() whenever(syncAccountRepository.logout(deviceId)).thenReturn(Result.Success(true)) @@ -389,7 +389,7 @@ class SyncActivityViewModelTest { } @Test - fun whenOnRemoveDeviceSucceedsThenFetchRemoteDevices() = runTest { + fun `onRemoveDeviceConfirmed - remove device succeeds - fetch remote devices`() = runTest { givenAuthenticatedUser() whenever(syncAccountRepository.logout(deviceId)).thenReturn(Result.Success(true)) @@ -400,7 +400,7 @@ class SyncActivityViewModelTest { } @Test - fun whenOnRemoveDeviceSucceedsThenReturnUpdateDevices() = runTest { + fun `onRemoveDeviceConfirmed - remove device succeeds - return update devices`() = runTest { givenAuthenticatedUser() whenever(syncAccountRepository.logout(deviceId)).thenReturn(Result.Success(true)) @@ -417,7 +417,7 @@ class SyncActivityViewModelTest { } @Test - fun whenOnRemoveDeviceFailsThenRestorePreviousList() = runTest { + fun `onRemoveDeviceConfirmed - remove device fails - restore previous list`() = runTest { givenAuthenticatedUser() whenever(syncAccountRepository.logout(deviceId)).thenReturn(Result.Error(reason = "error")) @@ -431,7 +431,7 @@ class SyncActivityViewModelTest { } @Test - fun whenOnDeviceEditedThenUpdateDevice() = runTest { + fun `onDeviceEdited - authenticated user - update device`() = 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 - 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 - fetch remote devices`() = runTest { givenAuthenticatedUser() val connectedDevices = listOf(connectedDevice, connectedDevice) @@ -501,7 +501,7 @@ class SyncActivityViewModelTest { } @Test - fun whenSyncStateIsDisabledThenViewStateChanges() = runTest { + fun `viewState - sync state disabled - viewState changes`() = runTest { givenAuthenticatedUser() testee.viewState().test { @@ -515,7 +515,7 @@ class SyncActivityViewModelTest { } @Test - fun whenSyncStateIsEnabledThenViewStateChanges() = runTest { + fun `viewState - sync state enabled - viewState changes`() = runTest { givenAuthenticatedUser() stateFlow.value = SyncState.OFF @@ -530,7 +530,7 @@ class SyncActivityViewModelTest { } @Test - fun whenSyncStateIsInProgressEnabledThenViewStateDoesNotChange() = runTest { + fun `viewState - sync state in progress enabled - does not change`() = runTest { givenAuthenticatedUser() testee.viewState().test { @@ -543,7 +543,7 @@ class SyncActivityViewModelTest { } @Test - fun whenUserSignedAndSetupFlowsDisabledThenAllSetupFlowsDisabledViewState() = runTest { + fun `viewState - user signed and setup flows disabled - 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 `viewState - user signed in and create account disabled - 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 `viewState - setup flows disabled - all setup flows disabled`() = runTest { whenever(syncFeatureToggle.allowSetupFlows()).thenReturn(false) whenever(syncFeatureToggle.allowCreateAccount()).thenReturn(true) @@ -584,7 +584,7 @@ class SyncActivityViewModelTest { } @Test - fun whenCreateAccountDisabledThenOnlySignInFlowDisabledViewState() = runTest { + fun `viewState - create account disabled - 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 `commands - sync not supported - 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..cbb5d4226b64 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 `viewState - screen started - show QR code`() = 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 `viewState - generate connect QR 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 `viewState - connection keys success - 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 - copy code to clipboard`() = runTest { whenever(syncRepository.getConnectQR()).thenReturn(Result.Success(jsonConnectKeyEncoded)) testee.onCopyCodeClicked() @@ -133,7 +133,7 @@ class SyncConnectViewModelTest { } @Test - fun whenUserClicksOnReadTextCodeThenCommandIsReadTextCode() = runTest { + fun `onReadTextCodeClicked - command is 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 - command is 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 - command is 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 - command is error`() = 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 - login succeeds - command is login success`() = runTest { testee.commands().test { testee.onLoginSuccess() val command = awaitItem() @@ -190,7 +190,7 @@ class SyncConnectViewModelTest { } @Test - fun whenPollingIfConnectFailsThenShowError() = runTest { + fun `pollConnectionKeys - connect fails - 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 `pollConnectionKeys - login fails - 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..bb7998cbb2c2 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 user 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 user 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 - 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 - message is 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 - message displayed`() = runTest { givenAllowSetupFlows(enabledOnNewerVersion = true) syncStateFlow.emit(READY) testee.onResume(mock()) @@ -160,7 +160,7 @@ class SyncDisabledViewModelTest { } @Test - fun whenUnauthenticatedCreateAccountDisabledThenMessageIsDisplayed() = runTest { + fun `onResume - 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 displayed`() = runTest { givenCreateAccountFlows(enabled = false) syncStateFlow.emit(READY) testee.onResume(mock()) @@ -199,7 +199,7 @@ class SyncDisabledViewModelTest { } @Test - fun whenAuthenticatedCreateAccountEnabledOnNewerVersionThenMessageIsDisplayed() = runTest { + fun `onResume - authenticated and create account enabled on newer version - message is 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..634caf09bd92 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 is ReadTextCode`() = runTest { testee.commands().test { testee.onReadTextCodeClicked() val command = awaitItem() @@ -59,7 +59,7 @@ class SyncLoginViewModelTest { } @Test - fun whenProcessRecoveryCodeThenPerformLoginAndEmitResult() = runTest { + fun `onQRCodeScanned - process recovery code - 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 is 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..33efe458546a 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 `viewState - screen started - show QR code`() = 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 `viewState - generate recovery QR 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 - command is 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 - command is 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 - command is error`() = 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 is 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..d64865caeda6 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 - camera unavailable - viewState camera unavailable`() = runTest { testee.handleCameraAvailability(false) testee.viewState.test { @@ -73,7 +73,7 @@ class SyncBarcodeViewModelTest { } @Test - fun whenHandlePermissionsWithPermissionGrantedThenViewStatePermissionsGranted() = runTest { + fun `handlePermissions - permission granted - viewState 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 - viewState 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 - viewState 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`() = runTest { testee.goToSettings() testee.viewState.test { @@ -135,7 +135,7 @@ class SyncBarcodeViewModelTest { } @Test - fun whenOnResumeThenCommandCheckCameraAvailable() = runTest { + fun `onResume - command 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 - viewState 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..d3d4ac75d9b5 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 `viewState - user not signed in - account created and 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 `viewState - user signed in - show view state`() = 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 - fails - 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 - 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..9261088c79c1 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 `viewState - sync setup screen - 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 `viewState - sync intro view mode - 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 - 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 screen - device connected`() = 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 - viewMode 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 `viewState - started from connection screen - 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 - setup started and account created - 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 - setup started and device connected - sync setup completed command sent`() = runTest { testee.viewState(Screen.SYNC_SETUP).test { testee.onDeviceConnected() val viewState = expectMostRecentItem() @@ -119,7 +119,7 @@ class SetupAccountViewModelTest { } @Test - fun whenSetupStartedAndRecoveryCodeProDeviceConnectedThenAskSaveRecoveryCodeCommandSent() = runTest { + fun `onRecoveryCodePrompt - recovery code pro device connected - 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..a80e0f35d726 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 `viewState - user not signed in - account created and view state updated`() = 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..08c54ff4c319 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 `viewState - sync intro argument - 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 `viewState - recovery intro argument - 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 - recover data flow command sent`() = runTest { testee.onStartRecoverDataClicked() testee.commands().test { @@ -78,7 +78,7 @@ class SyncSetupIntroViewModelTest { } @Test - fun whenOnAbortCLickedThenAbortFlowCommandSent() = runTest { + fun `onAbortClicked - abort flow command sent`() = 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..f185068ab579 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 - 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 - call save with null`() { val result = testee.onSuccess( changes = SyncChangesResponse( type = SyncableType.SETTINGS, @@ -124,7 +124,7 @@ class SettingsSyncDataPersisterTest { } @Test - fun whenPersistChangesTimestampButRecentlyModifiedThenSkip() { + fun `onSuccess - 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 - persist changes succeeds - 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..131c6976159f 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 - first time - metadata is initialized`() = runTest { assertTrue(metadataDao.getAllObservable().first().isEmpty()) testee.getChanges() @@ -77,7 +77,7 @@ class SettingsSyncDataProviderTest { } @Test - fun whenGetChangesForFirstTimeThenExistingMetadataUpdated() = runTest { + fun `getChanges - first time - existing 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 - 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 - first sync with data - 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 for first sync - send as deleted`() { duckAddressSetting.save(null) val changes = testee.getChanges() @@ -173,7 +173,7 @@ class SettingsSyncDataProviderTest { } @Test - fun whenGetChangesSubsequentCallsAndSettingNullThenSendAsDeleted() { + fun `getChanges - 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 - syncable 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..d9ea94967251 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 `userId - stored - 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 `deviceName - stored - 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 `deviceId - stored - 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 - user has auth keys - return true`() { store.storeCredentials("userId", "deviceId", "deviceName", "primaryKey", "secretKey", "token") assertTrue(store.isSignedIn()) } @Test - fun whenClearAllThenReturnRemoveAllKeys() { + fun `clearAll - 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..27dc824db8e2 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 `featureErrorByDate - 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 `incrementCount - 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..77989894fad0 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 - return true`() { givenThereAreExceptions() assertTrue(testee.isException("http://www.example.com")) } @Test - fun whenIsExceptionWithSubdomainAndDomainIsListedInTheExceptionsListThenReturnTrue() { + fun `isException - subdomain and domain listed in exceptions - return true`() { givenThereAreExceptions() assertTrue(testee.isException("http://test.example.com")) } @Test - fun whenIsExceptionAndDomainIsNotListedInTheExceptionsListThenReturnFalse() { + fun `isException - domain not in exceptions list - return false`() { whenever(mockUserAgentRepository.exceptions).thenReturn(CopyOnWriteArrayList()) assertFalse(testee.isException("http://test.example.com")) } @Test - fun whenIsExceptionAndDomainIsListedInTheUnprotectedTemporaryListThenReturnTrue() { + fun `isException - domain in unprotected temporary list - return 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 - use legacy user agent`() { val url = "http://duckduckgo.com" assertTrue(testee.useLegacyUserAgent(url)) } @Test - fun whenSubdomainInLegacySitesListThenUseLegacyUserAgent() { + fun `useLegacyUserAgent - subdomain in legacy sites list - use legacy user agent`() { val url = "http://test.duckduckgo.com" assertTrue(testee.useLegacyUserAgent(url)) } @Test - fun whenSiteNotInLegacySitesListThenDoNotUseLegacyUserAgent() { + fun `useLegacyUserAgent - site not in legacy sites list - do not use`() { 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..cb88d239e1cb 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 - return 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 - return 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 `store - feature name matches user agent and has min supported version - 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 `store - feature name matches user agent - 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..1c458c7feefc 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 `userAgent - no params - 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 `userAgent - mobile UA retrieved - device stripped and application component added before Safari`() { 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 `userAgent - desktop UA retrieved - device stripped and application component added before Safari`() { 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 `userAgent - missing AppleWebKit component - contains Mozilla 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 `userAgent - missing Safari component - 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 `userAgent - missing version component - 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 `userAgent - domain supports application - 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 `userAgent - domain has exception - ua is default`() { 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 `userAgent - subdomain has exception - ua is default`() { 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 - ua is default`() { 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 - ua is default`() { 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 `userAgent - feature disabled - 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 `userAgent - domain supports version - includes version component`() { 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 `userAgent - site should use desktop agent - return 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 `userAgent - site should use desktop agent but contains exclusion - do 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 `userAgent - default and use desktop agent - 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 `userAgent - url allowed by user - 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 `userAgent - allowed URL and is desktop - return 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 `userAgent - legacy site - 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 `userAgent - legacy site and 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 `userAgent - no exceptions - return 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 `userAgent - is desktop - 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 `userAgent - is desktop and is 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..24852b26aca3 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 - deleteAll called`() { testee.deleteAll() verify(mockPrivacyFeatureTogglesStore).deleteAll() } @Test - fun whenGetThenGetCalled() { + fun `get - called`() { testee.get(UserAgentFeatureName.UserAgent, true) verify(mockPrivacyFeatureTogglesStore).get(UserAgentFeatureName.UserAgent, true) } @Test - fun whenInsertThenInsertCalled() { + fun `insert - 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..cac11f2b644f 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 `RealUserAgentRepository - repository created - exceptions loaded into memory`() { givenUserAgentExceptionsDaoContainExceptions() testee = RealUserAgentRepository( @@ -65,7 +65,7 @@ class RealUserAgentRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = runTest { + fun `updateAll - updateAll called`() = runTest { testee = RealUserAgentRepository( mockDatabase, @@ -80,7 +80,7 @@ class RealUserAgentRepositoryTest { } @Test - fun whenUpdateAllThenPreviousExceptionsAreCleared() = runTest { + fun `updateAll - previous exceptions are 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..d314b8fd6ae6 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 `isProductionPackage - debug version - 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 - unrelated package - 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..8e14dfbb8c9c 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 `isPlayReleaseBuild - play release - identified correctly`() { configureFlavor(PLAY) configureAsReleaseBuild() assertTrue(testee.isPlayReleaseBuild()) } @Test - fun whenIsPlayAndNotReleaseThenIdentifiedCorrectly() { + fun `isPlayReleaseBuild - play and not release - identified correctly`() { configureFlavor(PLAY) configureAsDebugBuild() assertFalse(testee.isPlayReleaseBuild()) } @Test - fun whenIsNotPlayFlavorThenIdentifiedCorrectly() { + fun `isPlayReleaseBuild - not play flavor - identified correctly`() { configureFlavor(FDROID) configureAsReleaseBuild() assertFalse(testee.isPlayReleaseBuild()) } @Test - fun whenIsNotPlayFlavorAndNotReleaseThenIdentifiedCorrectly() { + fun `isPlayReleaseBuild - not play flavor and not release - 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..97d3ac2c70c3 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 `builtWithVerifiedCertificate - extracted hash is null - not a match`() { whenever(certHashExtractor.sha256Hash()).thenReturn(null) assertFalse(testee.builtWithVerifiedCertificate()) } @Test - fun whenExtractedHashIsNotProductionHashThenNotAMatch() { + fun `builtWithVerifiedCertificate - extracted hash is not production hash - not a match`() { whenever(certHashExtractor.sha256Hash()).thenReturn("ABC-123") assertFalse(testee.builtWithVerifiedCertificate()) } @Test - fun whenExtractedHashIsProductionHashThenIsAMatch() { + fun `builtWithVerifiedCertificate - extracted hash is 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..d2fe6880491a 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 `installedFromPlayStore - 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 `installedFromPlayStore - install source 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..890aa580f25d 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 onPermissionsGranted`() { var permissionGranted = false testee.registerResultsCallback( mock(), @@ -84,7 +84,7 @@ class MicrophonePermissionRequestTest { } @Test - fun whenPermissionRequestResultIsFalseThenOnPermissionsGrantedNotInvokedAndDeclinePermissionForever() { + fun `registerResultsCallback - permission request result is false - onPermissionsGranted 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 - onPermissionsGranted 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 `launch - permission declined forever - no mic access dialog shown`() { 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 `launch - rationale dialog not yet accepted - launch rationale dialog`() { whenever(voiceSearchRepository.getHasPermissionDeclinedForever()).thenReturn(false) whenever(voiceSearchRepository.getHasAcceptedRationaleDialog()).thenReturn(false) @@ -148,7 +148,7 @@ class MicrophonePermissionRequestTest { } @Test - fun whenRationalDialogAcceptedThenLaunchPermisionRequestFlow() { + fun `launch - rationale 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 `registerResultsCallback - rationale dialog shown - rationale accepted and 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 `registerResultsCallback - rationale dialog shown - rationale cancelled and file pixel`() { 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 `registerResultsCallback - rationale cancelled - 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 `registerResultsCallback - no mic access dialog accepted - disable voice search`() { 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..d21fb25125e8 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 `launch - permissions not granted - launch permission request`() { whenever(voiceSearchPermissionCheck.hasRequiredPermissionsGranted()).thenReturn(false) whenever(voiceSearchAvailability.isVoiceSearchAvailable).thenReturn(true) @@ -61,7 +61,7 @@ class PermissionAwareVoiceSearchLauncherTest { } @Test - fun whenPermissionsNotGrantedAndVoiceSearchNotAvailableThenLaunchPermissionRequest() { + fun `launch - permissions not granted and voice search not available - launch permission request`() { whenever(voiceSearchPermissionCheck.hasRequiredPermissionsGranted()).thenReturn(false) whenever(voiceSearchAvailability.isVoiceSearchAvailable).thenReturn(false) @@ -72,7 +72,7 @@ class PermissionAwareVoiceSearchLauncherTest { } @Test - fun whenPermissionsGrantedThenLaunchVoiceSearchActivity() { + fun `launch - permissions granted - launch voice search activity`() { whenever(voiceSearchPermissionCheck.hasRequiredPermissionsGranted()).thenReturn(true) whenever(voiceSearchAvailability.isVoiceSearchAvailable).thenReturn(true) @@ -83,7 +83,7 @@ class PermissionAwareVoiceSearchLauncherTest { } @Test - fun whenPermissionsGrantedAndVoiceSearchNotAvailableThenLaunchVoiceSearchActivity() { + fun `launch - permissions granted and voice search not available - does not 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..41adb8a731d4 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 `registerResultsCallback - 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 `registerResultsCallback - result from voice search browser is error - 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 `registerResultsCallback - 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 `registerResultsCallback - result from voice search is OK and empty - emit search cancelled`() { var lastKnownEvent: Event? = null testee.registerResultsCallback(mock(), mock(), BROWSER) { lastKnownEvent = it @@ -125,7 +125,7 @@ class RealVoiceSearchActivityLauncherTest { } @Test - fun whenResultFromVoiceSearchIsCancelledThenEmitSearchCancelled() { + fun `registerResultsCallback - result from voice search cancelled - emit search cancelled`() { var lastKnownEvent: Event? = null testee.registerResultsCallback(mock(), mock(), BROWSER) { lastKnownEvent = it @@ -140,7 +140,7 @@ class RealVoiceSearchActivityLauncherTest { } @Test - fun whenResultFromVoiceSearchIsCancelledSeveralTimesThenShowDialog() { + fun `registerResultsCallback - result from voice search cancelled several times - show dialog`() { var lastKnownEvent: Event? = null testee.registerResultsCallback(mock(), mock(), BROWSER) { lastKnownEvent = it @@ -156,7 +156,7 @@ class RealVoiceSearchActivityLauncherTest { } @Test - fun whenResultFromVoiceSearchIsCancelledLessThanTwoTimesThenDoNotShowDialog() { + fun `registerResultsCallback - voice search cancelled less than two times - 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 `registerResultsCallback - result from voice search is OK - 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 - 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 - 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..a25923d1082e 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 `isVoiceSearchSupported - valid config - 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 `isVoiceSearchSupported - language not 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 `isVoiceSearchSupported - valid config and min version is null - 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 `isVoiceSearchSupported - device has invalid language - 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 `isVoiceSearchSupported - device has invalid SDK - false`() { 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 `isVoiceSearchSupported - no support for on-device speech recognition - 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 `isVoiceSearchSupported - manufacturer in excluded list - 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 - 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 - 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 and editing unchanged url - true`() { setupRemoteConfig(voiceSearchEnabled = true, minSdk = 30, excludedManufacturers = emptyArray(), excludedLocales = emptyArray()) setupDeviceConfig(manufacturer = "Google", sdkInt = 31, languageTag = "en-US", isOnDeviceSpeechRecognitionAvailable = true) @@ -182,7 +182,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenVoiceSearchSupportedAndIsEditingUrlWithEmptyQueryThenShouldShowVoiceSearchTrue() { + fun `shouldShowVoiceSearch - editing URL with empty query - true`() { setupRemoteConfig(voiceSearchEnabled = true, minSdk = 30, excludedManufacturers = emptyArray(), excludedLocales = emptyArray()) setupDeviceConfig(manufacturer = "Google", sdkInt = 31, languageTag = "en-US", isOnDeviceSpeechRecognitionAvailable = true) setupUserSettings(true) @@ -198,7 +198,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenVoiceSearchSupportedAndIsEditingUrlWithChangedQueryThenShouldShowVoiceSearchTrue() { + fun `shouldShowVoiceSearch - voice search supported and editing url with changed 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) @@ -215,7 +215,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenVoiceSearchSupportedAndUrlShownInAddressBarWithNoFocusThenShouldShowVoiceSearchFalse() { + fun `shouldShowVoiceSearch - voice search supported and url shown in address bar with no focus - 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(true) @@ -231,7 +231,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenVoiceSearchSupportedAndUrlShownInAddressBarWithFocusAndEmptyUnchangedQueryThenShouldShowVoiceSearchTrue() { + fun `shouldShowVoiceSearch - voice search supported and url shown with focus and empty unchanged query - true`() { setupRemoteConfig(voiceSearchEnabled = true, minSdk = 30, excludedManufacturers = emptyArray(), excludedLocales = emptyArray()) setupDeviceConfig(manufacturer = "Google", sdkInt = 31, languageTag = "en-US", isOnDeviceSpeechRecognitionAvailable = true) setupUserSettings(true) @@ -247,7 +247,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenVoiceSearchSupportedAndUrlShownInAddressBarWithFocusAndEmptyChangedQueryThenShouldShowVoiceSearchTrue() { + fun `shouldShowVoiceSearch - voice search supported and url shown with focus and empty changed query - true`() { setupRemoteConfig(voiceSearchEnabled = true, minSdk = 30, excludedManufacturers = emptyArray(), excludedLocales = emptyArray()) setupDeviceConfig(manufacturer = "Google", sdkInt = 31, languageTag = "en-US", isOnDeviceSpeechRecognitionAvailable = true) setupUserSettings(true) @@ -263,7 +263,7 @@ class RealVoiceSearchAvailabilityTest { } @Test - fun whenVoiceSearchSupportedAndUrlShownInAddressBarWithFocusAndNonEmptyChangedQueryThenShouldShowVoiceSearchFalse() { + fun `shouldShowVoiceSearch - voice search supported and url shown with focus and non-empty changed query - 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 - 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 - 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 editing SERP with unchanged query - 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 - editing SERP with changed query - false`() { 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 - editing SERP with empty query - shows voice search`() { 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 `isVoiceSearchAvailable - model is 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 `isVoiceSearchAvailable - not accepted voice rationale - 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..630b62dffd6f 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 `isLanguageSupported - language installed - language is supported`() { instantiate() val callbackCaptor = argumentCaptor() @@ -74,7 +74,7 @@ class RealLanguageSupportCheckerTest { } @Test - fun whenLanguageNotInstalledThenLanguageIsNotSupported() { + fun `isLanguageSupported - language not installed - language is not supported`() { instantiate() val callbackCaptor = argumentCaptor() @@ -89,7 +89,7 @@ class RealLanguageSupportCheckerTest { } @Test - fun whenSpeechRecognizerErrorThenLanguageIsNotSupported() { + fun `onError - speech recognizer error - language is not supported`() { instantiate() val callbackCaptor = argumentCaptor() @@ -101,7 +101,7 @@ class RealLanguageSupportCheckerTest { } @Test - fun whenSdkLowerThanTiramisuThenLanguageIsNotSupported() { + fun `isLanguageSupported - SDK lower than Tiramisu - 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..63c26e020cf5 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 `startVoiceSearch - starts speech recognizer`() { testee.startVoiceSearch() verify(speechRecognizer).start(any()) } @Test - fun whenStopThenStopSpeechRecognizer() { + fun `stopVoiceSearch - stop speech recognizer`() { testee.stopVoiceSearch() verify(speechRecognizer).stop() } @Test - fun whenStartThenEmitInitialViewState() = runTest { + fun `startVoiceSearch - emit initial viewState`() = runTest { testee.startVoiceSearch() testee.viewState().test { @@ -72,7 +72,7 @@ class VoiceSearchViewModelTest { } @Test - fun whenPartialResultsReceivedThenEmitNewViewState() = runTest { + fun `startVoiceSearch - partial results received - emit new viewState`() = 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 - partial results exceed 30 words - emit new view state and handle speech recognition success`() = 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 `startVoiceSearch - volume update received - 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 - no partial result - emit viewState 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 - partial result received and view model restarted - emit view state with 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 - recognition success emitted - emit viewState 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 `userInitiatesSearchComplete - 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..5ad12b8c5a32 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 `RealVoiceSearchFeatureRepository - created - 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 `updateAllExceptions - database is 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 `updateAllExceptions - 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..c14da9fcfb22 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 - rationale dialog accepted - getHasAcceptedRationaleDialog is true`() { assertFalse(testee.getHasAcceptedRationaleDialog()) testee.acceptRationaleDialog() @@ -44,7 +44,7 @@ class RealVoiceSearchRepositoryTest { } @Test - fun whenPermissionDeclinedForeverThenGetHasPermissionDeclinedForeverShouldBeTrue() { + fun `getHasPermissionDeclinedForever - permission declined forever - should be true`() { assertFalse(testee.getHasPermissionDeclinedForever()) testee.declinePermissionForever() @@ -53,7 +53,7 @@ class RealVoiceSearchRepositoryTest { } @Test - fun whenAvailabilityIsLoggedThengetHasLoggedAvailabilityShouldBeTrue() { + fun `getHasLoggedAvailability - availability is logged - should be true`() { assertFalse(testee.getHasLoggedAvailability()) testee.saveLoggedAvailability() @@ -62,7 +62,7 @@ class RealVoiceSearchRepositoryTest { } @Test - fun whenSetVoiceSearchEnabledThenIsVoiceSearchEnabledShouldBeTrue() { + fun `setVoiceSearchUserEnabled - isVoiceSearchUserEnabled should be true`() { assertFalse(testee.isVoiceSearchUserEnabled(false)) testee.setVoiceSearchUserEnabled(true) @@ -71,14 +71,14 @@ class RealVoiceSearchRepositoryTest { } @Test - fun whenSetVoiceSearchEnabledThenListenerShouldBeCalled() { + fun `setVoiceSearchUserEnabled - listener called`() { testee.setVoiceSearchUserEnabled(true) assertTrue(voiceSearchStatusListener.statusChanged) } @Test - fun whenDismissVoiceSearchThenCountVoiceSearchDismissedValueShouldIncrease() { + fun `dismissVoiceSearch - countVoiceSearchDismissed increases`() { 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..5b3627328366 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 `config - return correctly formatted json`() { whenever(mockWebCompatRepository.getWebCompatEntity()).thenReturn(WebCompatEntity(json = config)) assertEquals("\"webCompat\":$config", testee.config()) } @Test - fun whenGetPreferencesThenReturnNull() { + fun `preferences - return 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..d2d35b46cc37 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 web compat - return 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 - return true`() { assertTrue(testee.store(FEATURE_NAME_VALUE, JSON_STRING)) } @Test - fun whenFeatureNameMatchesWebCompatThenUpdateAll() { + fun `store - feature name matches web compat - update all`() { 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..a8381e647ae6 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 `init - no stored value - load empty JSON to memory`() = runTest { testee = RealWebCompatRepository( @@ -57,7 +57,7 @@ class WebCompatRepositoryTest { } @Test - fun whenInitializedAndHasStoredValueThenLoadStoredJsonToMemory() = + fun `RealWebCompatRepository - initialized with stored value - load stored JSON to memory`() = runTest { whenever(mockWebCompatDao.get()).thenReturn(webCompatEntity) testee = @@ -73,7 +73,7 @@ class WebCompatRepositoryTest { } @Test - fun whenUpdateAllThenUpdateAllCalled() = + fun `updateAll - updateAll 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())