From 6f7b3bbf255b0be4d5ff1bd994aad0d61b8cca8d Mon Sep 17 00:00:00 2001 From: cyBerta Date: Thu, 25 Jan 2024 23:55:52 +0100 Subject: fix ProviderApiManagerTest, sneaking in some missing changes from previous commits as well --- .../bitmaskclient/eip/ProviderApiManagerTest.java | 529 ++++++++++----------- .../BackendMockResponses/BackendMockProvider.java | 82 ++-- .../BackendMockResponses/BaseBackendResponse.java | 75 --- ...rivceJsonInvalidCertificateBackendResponse.java | 94 ---- ...rviceJsonInvalidCertificateBackendResponse.java | 66 +++ .../GeoIpServiceIsDownBackendResponse.java | 85 ++-- ...viceNotReachableTorFallbackBackendResponse.java | 81 ++-- .../MisconfiguredProviderBackendResponse.java | 85 ++-- .../NoErrorBackendResponse.java | 85 ++-- .../NoErrorBackendResponseAPIv4.java | 92 ++-- .../TorFallbackBackendResponse.java | 131 +++-- .../UpdatedCertificateBackendResponse.java | 95 ++-- .../leap/bitmaskclient/testutils/MockHelper.java | 508 +++++--------------- 13 files changed, 694 insertions(+), 1314 deletions(-) delete mode 100644 app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/BaseBackendResponse.java delete mode 100644 app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/EipSerivceJsonInvalidCertificateBackendResponse.java create mode 100644 app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/EipServiceJsonInvalidCertificateBackendResponse.java (limited to 'app/src/test/java/se') diff --git a/app/src/test/java/se/leap/bitmaskclient/eip/ProviderApiManagerTest.java b/app/src/test/java/se/leap/bitmaskclient/eip/ProviderApiManagerTest.java index 4af0d072..c6e548ce 100644 --- a/app/src/test/java/se/leap/bitmaskclient/eip/ProviderApiManagerTest.java +++ b/app/src/test/java/se/leap/bitmaskclient/eip/ProviderApiManagerTest.java @@ -19,12 +19,11 @@ package se.leap.bitmaskclient.eip; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.powermock.api.mockito.PowerMockito.mockStatic; import static se.leap.bitmaskclient.base.models.Constants.BROADCAST_RESULT_KEY; import static se.leap.bitmaskclient.base.models.Constants.EIP_ACTION_START; import static se.leap.bitmaskclient.base.models.Constants.PROVIDER_KEY; +import static se.leap.bitmaskclient.base.models.Constants.USE_BRIDGES; +import static se.leap.bitmaskclient.base.models.Constants.USE_SNOWFLAKE; import static se.leap.bitmaskclient.providersetup.ProviderAPI.CORRECTLY_DOWNLOADED_GEOIP_JSON; import static se.leap.bitmaskclient.providersetup.ProviderAPI.CORRECTLY_UPDATED_INVALID_VPN_CERTIFICATE; import static se.leap.bitmaskclient.providersetup.ProviderAPI.ERRORS; @@ -44,27 +43,25 @@ import static se.leap.bitmaskclient.testutils.BackendMockResponses.BackendMockPr import static se.leap.bitmaskclient.testutils.BackendMockResponses.BackendMockProvider.TestBackendErrorCase.ERROR_GEOIP_SERVICE_IS_DOWN_TOR_FALLBACK; import static se.leap.bitmaskclient.testutils.BackendMockResponses.BackendMockProvider.TestBackendErrorCase.NO_ERROR; import static se.leap.bitmaskclient.testutils.BackendMockResponses.BackendMockProvider.TestBackendErrorCase.NO_ERROR_API_V4; -import static se.leap.bitmaskclient.testutils.MockHelper.mockBase64; -import static se.leap.bitmaskclient.testutils.MockHelper.mockBundle; +import static se.leap.bitmaskclient.testutils.MockHelper.mockBuildConfigHelper; +import static se.leap.bitmaskclient.testutils.MockHelper.mockCertificateHelper; import static se.leap.bitmaskclient.testutils.MockHelper.mockClientGenerator; -import static se.leap.bitmaskclient.testutils.MockHelper.mockConfigHelper; -import static se.leap.bitmaskclient.testutils.MockHelper.mockIntent; +import static se.leap.bitmaskclient.testutils.MockHelper.mockContext; import static se.leap.bitmaskclient.testutils.MockHelper.mockPreferenceHelper; import static se.leap.bitmaskclient.testutils.MockHelper.mockProviderApiConnector; import static se.leap.bitmaskclient.testutils.MockHelper.mockRSAHelper; import static se.leap.bitmaskclient.testutils.MockHelper.mockResources; import static se.leap.bitmaskclient.testutils.MockHelper.mockResultReceiver; -import static se.leap.bitmaskclient.testutils.MockHelper.mockTextUtils; -import static se.leap.bitmaskclient.testutils.MockHelper.mockTorStatusObservable; import static se.leap.bitmaskclient.testutils.TestSetupHelper.getConfiguredProvider; import static se.leap.bitmaskclient.testutils.TestSetupHelper.getConfiguredProviderAPIv4; import static se.leap.bitmaskclient.testutils.TestSetupHelper.getProvider; import android.content.Context; import android.content.Intent; +import android.content.SharedPreferences; +import android.content.pm.PackageManager; import android.content.res.Resources; import android.os.Bundle; -import android.text.TextUtils; import androidx.annotation.Nullable; @@ -72,12 +69,6 @@ import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Answers; -import org.mockito.Mock; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException; import java.security.NoSuchAlgorithmException; @@ -86,13 +77,16 @@ import java.util.concurrent.TimeoutException; import se.leap.bitmaskclient.BuildConfig; import se.leap.bitmaskclient.base.models.Provider; -import se.leap.bitmaskclient.base.utils.ConfigHelper; +import se.leap.bitmaskclient.base.utils.BuildConfigHelper; +import se.leap.bitmaskclient.base.utils.CertificateHelper; +import se.leap.bitmaskclient.base.utils.HandlerProvider; import se.leap.bitmaskclient.base.utils.PreferenceHelper; +import se.leap.bitmaskclient.base.utils.RSAHelper; import se.leap.bitmaskclient.providersetup.ProviderAPI; import se.leap.bitmaskclient.providersetup.ProviderApiConnector; import se.leap.bitmaskclient.providersetup.ProviderApiManager; import se.leap.bitmaskclient.providersetup.ProviderApiManagerBase; -import se.leap.bitmaskclient.providersetup.ProviderSetupObservable; +import se.leap.bitmaskclient.testutils.MockSharedPreferences; import se.leap.bitmaskclient.tor.TorStatusObservable; @@ -100,13 +94,9 @@ import se.leap.bitmaskclient.tor.TorStatusObservable; * Created by cyberta on 04.01.18. */ -@RunWith(PowerMockRunner.class) -@PrepareForTest({ProviderApiManager.class, TextUtils.class, ConfigHelper.RSAHelper.class, ConfigHelper.class, ProviderApiConnector.class, PreferenceHelper.class, TorStatusObservable.class, android.util.Base64.class, ProviderSetupObservable.class}) public class ProviderApiManagerTest { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) private Resources mockResources; - @Mock(answer = Answers.RETURNS_DEEP_STUBS) private Context mockContext; private ProviderApiManager providerApiManager; @@ -114,12 +104,22 @@ public class ProviderApiManagerTest { static class TestProviderApiServiceCallback implements ProviderApiManagerBase.ProviderApiServiceCallback { Throwable startTorServiceException; boolean hasNetworkConnection; + boolean torTimeout; + TorStatusObservable torStatusObservable; + TestProviderApiServiceCallback() { this(null, true); } TestProviderApiServiceCallback(@Nullable Throwable startTorServiceException, boolean hasNetworkConnection) { this.startTorServiceException = startTorServiceException; this.hasNetworkConnection = hasNetworkConnection; + this.torStatusObservable = TorStatusObservable.getInstance(); + } + + TestProviderApiServiceCallback(boolean torTimeout, boolean hasNetworkConnection) { + this.hasNetworkConnection = hasNetworkConnection; + this.torStatusObservable = TorStatusObservable.getInstance(); + this.torTimeout = torTimeout; } @Override @@ -136,6 +136,13 @@ public class ProviderApiManagerTest { throw (IllegalStateException) startTorServiceException; } } + if (!torTimeout) { + try { + TorStatusObservable.updateState(mockContext(), TorStatusObservable.TorStatus.ON.toString()); + } catch (PackageManager.NameNotFoundException e) { + throw new RuntimeException(e); + } + } return true; } @@ -145,7 +152,7 @@ public class ProviderApiManagerTest { @Override public int getTorHttpTunnelPort() { - return 0; + return 8118; } @Override @@ -157,31 +164,32 @@ public class ProviderApiManagerTest { @Before public void setUp() throws Exception { - - Bundle bundle = mockBundle(); - PowerMockito.whenNew(Bundle.class).withAnyArguments().thenReturn(bundle); - Intent intent = mockIntent(); - PowerMockito.whenNew(Intent.class).withAnyArguments().thenReturn(intent); - mockTextUtils(); + mockContext = mockContext(); mockResources = mockResources(getClass().getClassLoader().getResourceAsStream("error_messages.json")); + HandlerProvider handlerProvider = new HandlerProvider((r, delay) -> new Thread(r).start()); + BuildConfigHelper buildConfigHelper = mockBuildConfigHelper(true, true); + TorStatusObservable torStatusObservable = TorStatusObservable.getInstance(); + TorStatusObservable.setProxyPort(-1); + TorStatusObservable.setLastError(null); + TorStatusObservable.updateState(mockContext, TorStatusObservable.TorStatus.OFF.toString()); } @Test public void test_handleIntentSetupProvider_noProviderMainURL() throws IOException, JSONException { Provider provider = new Provider(""); - mockPreferenceHelper(provider); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Bundle expectedResult = mockBundle(); + Bundle expectedResult = new Bundle(); expectedResult.putBoolean(BROADCAST_RESULT_KEY, false); expectedResult.putString(ERRORS, "{\"errors\":\"It doesn't seem to be a Bitmask provider.\"}"); expectedResult.putParcelable(PROVIDER_KEY, provider); - Intent providerApiCommand = mockIntent(); + Intent providerApiCommand = new Intent(); providerApiCommand.setAction(ProviderAPI.SET_UP_PROVIDER); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_NOK, expectedResult)); providerApiCommand.putExtra(PROVIDER_KEY, provider); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiManager.handleIntent(providerApiCommand); } @@ -189,47 +197,42 @@ public class ProviderApiManagerTest { @Test public void test_handleIntentSetupProvider_happyPath_preseededProviderAndCA() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, JSONException { Provider provider = getConfiguredProvider(); - mockPreferenceHelper(provider); - mockConfigHelper(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); - mockProviderApiConnector(NO_ERROR); - mockStatic(ProviderSetupObservable.class); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider); + CertificateHelper certHelper = mockCertificateHelper(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + ProviderApiConnector providerApiConnector = mockProviderApiConnector(NO_ERROR); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Bundle expectedResult = mockBundle(); - + Bundle expectedResult = new Bundle(); expectedResult.putBoolean(BROADCAST_RESULT_KEY, true); expectedResult.putParcelable(PROVIDER_KEY, provider); - Intent providerApiCommand = mockIntent(); - + Intent providerApiCommand = new Intent(); providerApiCommand.putExtra(PROVIDER_KEY, provider); providerApiCommand.setAction(ProviderAPI.SET_UP_PROVIDER); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_OK, expectedResult)); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); - + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiManager.handleIntent(providerApiCommand); } @Test public void test_handleIntentSetupProvider_happyPath_no_preseededProviderAndCA() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, JSONException { Provider provider = getConfiguredProvider(); - mockPreferenceHelper(provider); - mockConfigHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); - mockProviderApiConnector(NO_ERROR); - mockStatic(ProviderSetupObservable.class); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider); + CertificateHelper certHelper = mockCertificateHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(NO_ERROR); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Bundle expectedResult = mockBundle(); + Bundle expectedResult = new Bundle(); expectedResult.putBoolean(BROADCAST_RESULT_KEY, true); expectedResult.putParcelable(PROVIDER_KEY, provider); - Intent providerApiCommand = mockIntent(); + Intent providerApiCommand = new Intent(); providerApiCommand.setAction(ProviderAPI.SET_UP_PROVIDER); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_OK, expectedResult)); providerApiCommand.putExtra(PROVIDER_KEY, provider); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiManager.handleIntent(providerApiCommand); } @@ -237,21 +240,20 @@ public class ProviderApiManagerTest { @Test public void test_handleIntentSetupProvider_happyPath_storedProviderAndCAFromPreviousSetup() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, JSONException { Provider provider = new Provider("https://riseup.net"); - mockPreferenceHelper(getConfiguredProvider()); - mockConfigHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); - mockProviderApiConnector(NO_ERROR); - mockStatic(ProviderSetupObservable.class); + PreferenceHelper preferenceHelper = mockPreferenceHelper(getConfiguredProvider()); + CertificateHelper certHelper = mockCertificateHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(NO_ERROR); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Bundle expectedResult = mockBundle(); + Bundle expectedResult = new Bundle(); expectedResult.putBoolean(BROADCAST_RESULT_KEY, true); expectedResult.putParcelable(PROVIDER_KEY, provider); - Intent providerApiCommand = mockIntent(); + Intent providerApiCommand = new Intent(); providerApiCommand.setAction(ProviderAPI.SET_UP_PROVIDER); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_OK, expectedResult)); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiCommand.putExtra(PROVIDER_KEY, provider); providerApiManager.handleIntent(providerApiCommand); @@ -261,21 +263,19 @@ public class ProviderApiManagerTest { public void test_handleIntentSetupProvider_preseededProviderAndCA_failedCAPinning() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, JSONException { Provider provider = getConfiguredProvider(); - mockPreferenceHelper(provider); - mockConfigHelper(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29495"); - mockProviderApiConnector(NO_ERROR); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider); + CertificateHelper certHelper = mockCertificateHelper(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29495"); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(NO_ERROR); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Bundle expectedResult = mockBundle(); + Bundle expectedResult = new Bundle(); expectedResult.putBoolean(BROADCAST_RESULT_KEY, false); expectedResult.putString(ERRORS, "{\"errorId\":\"ERROR_CERTIFICATE_PINNING\",\"errors\":\"Stored provider certificate is invalid. You can either update Bitmask (recommended) or update the provider certificate using a commercial CA certificate.\"}"); expectedResult.putParcelable(PROVIDER_KEY, provider); - Intent providerApiCommand = mockIntent(); - + Intent providerApiCommand = new Intent(); providerApiCommand.setAction(ProviderAPI.SET_UP_PROVIDER); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_NOK, expectedResult)); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); - + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiCommand.putExtra(PROVIDER_KEY, provider); providerApiManager.handleIntent(providerApiCommand); @@ -284,24 +284,21 @@ public class ProviderApiManagerTest { @Test public void test_handleIntentSetupProvider_no_preseededProviderAndCA_failedPinning() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, JSONException { Provider provider = new Provider("https://riseup.net"); - mockPreferenceHelper(provider); - mockConfigHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29495"); - mockProviderApiConnector(NO_ERROR); - mockStatic(ProviderSetupObservable.class); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider); + CertificateHelper certHelper = mockCertificateHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29495"); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(NO_ERROR); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Bundle expectedResult = mockBundle(); + Bundle expectedResult = new Bundle(); expectedResult.putBoolean(BROADCAST_RESULT_KEY, false); expectedResult.putString(ERRORS, "{\"errorId\":\"ERROR_CERTIFICATE_PINNING\",\"errors\":\"Stored provider certificate is invalid. You can either update Bitmask (recommended) or update the provider certificate using a commercial CA certificate.\"}"); expectedResult.putParcelable(PROVIDER_KEY, provider); - Intent providerApiCommand = mockIntent(); - + Intent providerApiCommand = new Intent(); providerApiCommand.setAction(ProviderAPI.SET_UP_PROVIDER); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_NOK, expectedResult)); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); - + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiCommand.putExtra(PROVIDER_KEY, provider); providerApiManager.handleIntent(providerApiCommand); @@ -311,21 +308,20 @@ public class ProviderApiManagerTest { public void test_handleIntentSetupProvider_storedProviderAndCAFromPreviousSetup_failedPinning() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, JSONException { Provider provider = new Provider("https://riseup.net"); mockPreferenceHelper(getConfiguredProvider()); - mockConfigHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29495"); + CertificateHelper certHelper = mockCertificateHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29495"); - mockProviderApiConnector(NO_ERROR); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(NO_ERROR); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Bundle expectedResult = mockBundle(); + Bundle expectedResult = new Bundle(); expectedResult.putBoolean(BROADCAST_RESULT_KEY, false); expectedResult.putString(ERRORS, "{\"errorId\":\"ERROR_CERTIFICATE_PINNING\",\"errors\":\"Stored provider certificate is invalid. You can either update Bitmask (recommended) or update the provider certificate using a commercial CA certificate.\"}"); expectedResult.putParcelable(PROVIDER_KEY, provider); - Intent providerApiCommand = mockIntent(); - + Intent providerApiCommand = new Intent(); providerApiCommand.setAction(ProviderAPI.SET_UP_PROVIDER); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_NOK, expectedResult)); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiCommand.putExtra(PROVIDER_KEY, provider); providerApiManager.handleIntent(providerApiCommand); @@ -335,21 +331,20 @@ public class ProviderApiManagerTest { @Test public void test_handleIntentSetupProvider_preseededProviderAndCA_outdatedCertificate() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, JSONException { Provider provider = getProvider(null ,null, null, null, "outdated_cert.pem", null, null, null); - mockPreferenceHelper(provider); - mockProviderApiConnector(NO_ERROR); - mockConfigHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(NO_ERROR); + CertificateHelper certHelper = mockCertificateHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Bundle expectedResult = mockBundle(); + Bundle expectedResult = new Bundle(); expectedResult.putBoolean(BROADCAST_RESULT_KEY, false); expectedResult.putString(ERRORS, "{\"errorId\":\"ERROR_INVALID_CERTIFICATE\",\"errors\":\"Stored provider certificate is expired. You can either update Bitmask (recommended) or update the provider certificate using a commercial CA certificate.\"}"); expectedResult.putParcelable(PROVIDER_KEY, provider); - Intent providerApiCommand = mockIntent(); - + Intent providerApiCommand = new Intent(); providerApiCommand.setAction(ProviderAPI.SET_UP_PROVIDER); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_NOK, expectedResult)); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiCommand.putExtra(PROVIDER_KEY, provider); providerApiManager.handleIntent(providerApiCommand); @@ -358,22 +353,21 @@ public class ProviderApiManagerTest { @Test public void test_handleIntentSetupProvider_storedProviderAndCAFromPreviousSetup_outdatedCertificate() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, JSONException { Provider provider = getProvider(null, null, null, null, "outdated_cert.pem", "riseup.net.json", null, null); - mockPreferenceHelper(provider); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider); PreferenceHelper.getEipDefinitionFromPreferences(); - mockProviderApiConnector(NO_ERROR); - mockConfigHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(NO_ERROR); + CertificateHelper certHelper = mockCertificateHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Bundle expectedResult = mockBundle(); + Bundle expectedResult = new Bundle(); expectedResult.putBoolean(BROADCAST_RESULT_KEY, false); expectedResult.putString(ERRORS, "{\"errorId\":\"ERROR_INVALID_CERTIFICATE\",\"errors\":\"Stored provider certificate is expired. You can either update Bitmask (recommended) or update the provider certificate using a commercial CA certificate.\"}"); expectedResult.putParcelable(PROVIDER_KEY, provider); - Intent providerApiCommand = mockIntent(); - + Intent providerApiCommand = new Intent(); providerApiCommand.setAction(ProviderAPI.SET_UP_PROVIDER); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_NOK, expectedResult)); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiCommand.putExtra(PROVIDER_KEY, provider); providerApiManager.handleIntent(providerApiCommand); @@ -382,22 +376,21 @@ public class ProviderApiManagerTest { @Test public void test_handleIntentSetupProvider_preseededProviderAndCA_ValidCertificateButUpdatedCertificateOnServerSide() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, JSONException { Provider provider = getConfiguredProvider(); - mockPreferenceHelper(provider); - mockConfigHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); - mockProviderApiConnector(ERROR_CASE_UPDATED_CERTIFICATE); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider); + CertificateHelper certHelper = mockCertificateHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(ERROR_CASE_UPDATED_CERTIFICATE); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Bundle expectedResult = mockBundle(); + Bundle expectedResult = new Bundle(); expectedResult.putBoolean(BROADCAST_RESULT_KEY, false); expectedResult.putString(ERRORS, "{\"errorId\":\"ERROR_INVALID_CERTIFICATE\",\"errors\":\"Stored provider certificate is invalid. You can either update Bitmask (recommended) or update the provider certificate using a commercial CA certificate.\"}"); expectedResult.putParcelable(PROVIDER_KEY, provider); - Intent providerApiCommand = mockIntent(); + Intent providerApiCommand = new Intent(); providerApiCommand.setAction(ProviderAPI.SET_UP_PROVIDER); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_NOK, expectedResult)); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); - + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiCommand.putExtra(PROVIDER_KEY, provider); providerApiManager.handleIntent(providerApiCommand); @@ -406,22 +399,21 @@ public class ProviderApiManagerTest { @Test public void test_handleIntentSetupProvider_storedProviderAndCAFromPreviousSetup_ValidCertificateButUpdatedCertificateOnServerSide() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, JSONException { Provider provider = new Provider("https://riseup.net"); - mockPreferenceHelper(getConfiguredProvider()); - mockConfigHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); - mockProviderApiConnector(ERROR_CASE_UPDATED_CERTIFICATE); + PreferenceHelper preferenceHelper = mockPreferenceHelper(getConfiguredProvider()); + CertificateHelper certHelper = mockCertificateHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(ERROR_CASE_UPDATED_CERTIFICATE); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Bundle expectedResult = mockBundle(); + Bundle expectedResult = new Bundle(); expectedResult.putBoolean(BROADCAST_RESULT_KEY, false); expectedResult.putString(ERRORS, "{\"errorId\":\"ERROR_INVALID_CERTIFICATE\",\"errors\":\"Stored provider certificate is invalid. You can either update Bitmask (recommended) or update the provider certificate using a commercial CA certificate.\"}"); expectedResult.putParcelable(PROVIDER_KEY, provider); - Intent providerApiCommand = mockIntent(); + Intent providerApiCommand = new Intent(); providerApiCommand.setAction(ProviderAPI.SET_UP_PROVIDER); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_NOK, expectedResult)); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); - + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiCommand.putExtra(PROVIDER_KEY, provider); providerApiManager.handleIntent(providerApiCommand); @@ -431,55 +423,54 @@ public class ProviderApiManagerTest { public void test_handleIntentSetupProvider_preseededProviderAndCA_failedConfiguration() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, JSONException { Provider provider = getConfiguredProvider(); - mockPreferenceHelper(provider); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider); - mockConfigHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); - mockProviderApiConnector(ERROR_CASE_MICONFIGURED_PROVIDER); - mockStatic(ProviderSetupObservable.class); + CertificateHelper certHelper = mockCertificateHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(ERROR_CASE_MICONFIGURED_PROVIDER); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Bundle expectedResult = mockBundle(); + Bundle expectedResult = new Bundle(); expectedResult.putBoolean(BROADCAST_RESULT_KEY, false); expectedResult.putString(ERRORS, "{\"errors\":\"There was an error configuring Bitmask with your chosen provider.\"}"); expectedResult.putParcelable(PROVIDER_KEY, provider); - Intent providerApiCommand = mockIntent(); + Intent providerApiCommand = new Intent(); providerApiCommand.putExtra(PROVIDER_KEY, provider); providerApiCommand.setAction(ProviderAPI.SET_UP_PROVIDER); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_NOK, expectedResult)); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiManager.handleIntent(providerApiCommand); } + @Test public void test_handleIntentSetupProvider_preseededCustomProviderAndCA_failedConfiguration() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, JSONException { if ("insecure".equals(BuildConfig.FLAVOR_implementation )) { return; } Provider provider = getConfiguredProvider(); - mockPreferenceHelper(provider); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider); - mockProviderApiConnector(ERROR_CASE_MICONFIGURED_PROVIDER); - mockConfigHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); - when(ConfigHelper.isDefaultBitmask()).thenReturn(false); - mockStatic(ProviderSetupObservable.class); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(ERROR_CASE_MICONFIGURED_PROVIDER); + CertificateHelper certHelper = mockCertificateHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + BuildConfigHelper buildConfigHelper = mockBuildConfigHelper(true, false); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Bundle expectedResult = mockBundle(); + Bundle expectedResult = new Bundle(); expectedResult.putBoolean(BROADCAST_RESULT_KEY, false); expectedResult.putString(ERRORS, "{\"errors\":\"There was an error configuring RiseupVPN.\"}"); expectedResult.putParcelable(PROVIDER_KEY, provider); - Intent providerApiCommand = mockIntent(); + Intent providerApiCommand = new Intent(); providerApiCommand.putExtra(PROVIDER_KEY, provider); providerApiCommand.setAction(ProviderAPI.SET_UP_PROVIDER); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_NOK, expectedResult)); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiManager.handleIntent(providerApiCommand); } @@ -488,23 +479,22 @@ public class ProviderApiManagerTest { public void test_handleIntentSetupProvider_outdatedPreseededProviderAndCA_successfulConfiguration() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, JSONException { Provider provider = getProvider(null, null, null, null, null, "riseup_net_outdated_config.json", null, null); - mockPreferenceHelper(provider); - mockConfigHelper(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); - mockProviderApiConnector(NO_ERROR); - mockStatic(ProviderSetupObservable.class); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider); + CertificateHelper certHelper = mockCertificateHelper(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(NO_ERROR); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Bundle expectedResult = mockBundle(); + Bundle expectedResult = new Bundle(); expectedResult.putBoolean(BROADCAST_RESULT_KEY, true); expectedResult.putParcelable(PROVIDER_KEY, provider); - Intent providerApiCommand = mockIntent(); + Intent providerApiCommand = new Intent(); providerApiCommand.putExtra(PROVIDER_KEY, provider); providerApiCommand.setAction(ProviderAPI.SET_UP_PROVIDER); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_OK, expectedResult)); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiManager.handleIntent(providerApiCommand); } @@ -516,29 +506,26 @@ public class ProviderApiManagerTest { } Provider provider = new Provider("https://riseup.net"); - mockPreferenceHelper(provider); - - mockConfigHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); - mockProviderApiConnector(ERROR_CASE_FETCH_EIP_SERVICE_CERTIFICATE_INVALID); - mockStatic(ProviderSetupObservable.class); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider); + CertificateHelper certHelper = mockCertificateHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(ERROR_CASE_FETCH_EIP_SERVICE_CERTIFICATE_INVALID); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Bundle expectedResult = mockBundle(); + Bundle expectedResult = new Bundle(); expectedResult.putBoolean(BROADCAST_RESULT_KEY, false); expectedResult.putParcelable(PROVIDER_KEY, provider); expectedResult.putString(ERRORS, "This is not a trusted Bitmask provider."); - Intent providerApiCommand = mockIntent(); + Intent providerApiCommand = new Intent(); providerApiCommand.setAction(ProviderAPI.SET_UP_PROVIDER); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_NOK, expectedResult)); providerApiCommand.putExtra(PROVIDER_KEY, provider); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiManager.handleIntent(providerApiCommand); } - @Test public void test_handleIntentGetGeoip_happyPath() throws IOException, NoSuchAlgorithmException, CertificateEncodingException, JSONException { if ("insecure".equals(BuildConfig.FLAVOR_implementation )) { @@ -546,22 +533,22 @@ public class ProviderApiManagerTest { } Provider inputProvider = getConfiguredProvider(); - mockPreferenceHelper(inputProvider); inputProvider.setGeoIpJson(new JSONObject()); + PreferenceHelper preferenceHelper = mockPreferenceHelper(inputProvider); Provider expectedProvider = getConfiguredProvider(); - mockConfigHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); - mockProviderApiConnector(NO_ERROR); + CertificateHelper certHelper = mockCertificateHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(NO_ERROR); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Bundle expectedResult = mockBundle(); + Bundle expectedResult = new Bundle(); expectedResult.putBoolean(EIP_ACTION_START, true); expectedResult.putBoolean(BROADCAST_RESULT_KEY, true); expectedResult.putParcelable(PROVIDER_KEY, expectedProvider); - Intent providerApiCommand = mockIntent(); + Intent providerApiCommand = new Intent(); providerApiCommand.setAction(ProviderAPI.DOWNLOAD_GEOIP_JSON); - Bundle extrasBundle = mockBundle(); + Bundle extrasBundle = new Bundle(); extrasBundle.putBoolean(EIP_ACTION_START, true); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(CORRECTLY_DOWNLOADED_GEOIP_JSON, expectedResult)); providerApiCommand.putExtra(PROVIDER_KEY, inputProvider); @@ -579,24 +566,24 @@ public class ProviderApiManagerTest { } Provider provider = getConfiguredProvider(); - mockPreferenceHelper(provider); - mockConfigHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); - mockProviderApiConnector(ERROR_GEOIP_SERVICE_IS_DOWN); - when(PreferenceHelper.getUseBridges()).thenReturn(false); - when(PreferenceHelper.getUseSnowflake()).thenReturn(false); - when(PreferenceHelper.hasSnowflakePrefs()).thenReturn(true); - + SharedPreferences mockSharedPref = new MockSharedPreferences(); + mockSharedPref.edit(). + putBoolean(USE_BRIDGES, false). + putBoolean(USE_SNOWFLAKE, false).commit(); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider, mockSharedPref); + CertificateHelper certHelper = mockCertificateHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(ERROR_GEOIP_SERVICE_IS_DOWN); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Bundle expectedResult = mockBundle(); + Bundle expectedResult = new Bundle(); expectedResult.putBoolean(EIP_ACTION_START, true); expectedResult.putBoolean(BROADCAST_RESULT_KEY, false); expectedResult.putParcelable(PROVIDER_KEY, provider); - Intent providerApiCommand = mockIntent(); + Intent providerApiCommand = new Intent(); providerApiCommand.setAction(ProviderAPI.DOWNLOAD_GEOIP_JSON); - Bundle extrasBundle = mockBundle(); + Bundle extrasBundle = new Bundle(); extrasBundle.putBoolean(EIP_ACTION_START, true); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(INCORRECTLY_DOWNLOADED_GEOIP_JSON, expectedResult)); providerApiCommand.putExtra(PROVIDER_KEY, provider); @@ -612,22 +599,21 @@ public class ProviderApiManagerTest { return; } - mockTorStatusObservable(null); Provider provider = getConfiguredProvider(); - mockPreferenceHelper(provider); - mockConfigHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); - mockProviderApiConnector(ERROR_GEOIP_SERVICE_IS_DOWN_TOR_FALLBACK); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider); + CertificateHelper certHelper = mockCertificateHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(ERROR_GEOIP_SERVICE_IS_DOWN_TOR_FALLBACK); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Bundle expectedResult = mockBundle(); + Bundle expectedResult = new Bundle(); expectedResult.putBoolean(EIP_ACTION_START, true); expectedResult.putBoolean(BROADCAST_RESULT_KEY, false); expectedResult.putParcelable(PROVIDER_KEY, provider); - Intent providerApiCommand = mockIntent(); + Intent providerApiCommand = new Intent(); providerApiCommand.setAction(ProviderAPI.DOWNLOAD_GEOIP_JSON); - Bundle extrasBundle = mockBundle(); + Bundle extrasBundle = new Bundle(); extrasBundle.putBoolean(EIP_ACTION_START, true); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(INCORRECTLY_DOWNLOADED_GEOIP_JSON, expectedResult)); providerApiCommand.putExtra(PROVIDER_KEY, provider); @@ -647,20 +633,20 @@ public class ProviderApiManagerTest { Provider provider = getConfiguredProvider(); provider.setLastGeoIpUpdate(System.currentTimeMillis()); - mockPreferenceHelper(provider); - mockConfigHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); - mockProviderApiConnector(NO_ERROR); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider); + CertificateHelper certHelper = mockCertificateHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(NO_ERROR); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Bundle expectedResult = mockBundle(); + Bundle expectedResult = new Bundle(); expectedResult.putBoolean(EIP_ACTION_START, true); expectedResult.putBoolean(BROADCAST_RESULT_KEY, false); expectedResult.putParcelable(PROVIDER_KEY, provider); - Intent providerApiCommand = mockIntent(); + Intent providerApiCommand = new Intent(); providerApiCommand.setAction(ProviderAPI.DOWNLOAD_GEOIP_JSON); - Bundle extrasBundle = mockBundle(); + Bundle extrasBundle = new Bundle(); extrasBundle.putBoolean(EIP_ACTION_START, true); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(INCORRECTLY_DOWNLOADED_GEOIP_JSON, expectedResult)); providerApiCommand.putExtra(PROVIDER_KEY, provider); @@ -678,20 +664,20 @@ public class ProviderApiManagerTest { Provider provider = getConfiguredProvider(); provider.setGeoipUrl(null); provider.setGeoIpJson(new JSONObject()); - mockPreferenceHelper(provider); - mockConfigHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); - mockProviderApiConnector(NO_ERROR); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider); + CertificateHelper certHelper = mockCertificateHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(NO_ERROR); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Bundle expectedResult = mockBundle(); + Bundle expectedResult = new Bundle(); expectedResult.putBoolean(EIP_ACTION_START, true); expectedResult.putBoolean(BROADCAST_RESULT_KEY, false); expectedResult.putParcelable(PROVIDER_KEY, provider); - Intent providerApiCommand = mockIntent(); + Intent providerApiCommand = new Intent(); providerApiCommand.setAction(ProviderAPI.DOWNLOAD_GEOIP_JSON); - Bundle extrasBundle = mockBundle(); + Bundle extrasBundle = new Bundle(); extrasBundle.putBoolean(EIP_ACTION_START, true); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(INCORRECTLY_DOWNLOADED_GEOIP_JSON, expectedResult)); providerApiCommand.putExtra(PROVIDER_KEY, provider); @@ -703,22 +689,20 @@ public class ProviderApiManagerTest { @Test public void test_handleIntentSetupProvider_APIv4_happyPath() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, JSONException { Provider provider = getConfiguredProviderAPIv4(); - mockPreferenceHelper(provider); - mockConfigHelper(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); - mockProviderApiConnector(NO_ERROR_API_V4); - mockStatic(ProviderSetupObservable.class); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider); + CertificateHelper certHelper = mockCertificateHelper(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(NO_ERROR_API_V4); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Bundle expectedResult = mockBundle(); - + Bundle expectedResult = new Bundle(); expectedResult.putBoolean(BROADCAST_RESULT_KEY, true); expectedResult.putParcelable(PROVIDER_KEY, provider); - Intent providerApiCommand = mockIntent(); + Intent providerApiCommand = new Intent(); providerApiCommand.putExtra(PROVIDER_KEY, provider); providerApiCommand.setAction(ProviderAPI.SET_UP_PROVIDER); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_OK, expectedResult)); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiManager.handleIntent(providerApiCommand); } @@ -727,41 +711,35 @@ public class ProviderApiManagerTest { public void test_handleIntentSetupProvider_TorFallback_SecondTryHappyPath() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, TimeoutException, InterruptedException { Provider provider = getConfiguredProviderAPIv4(); - mockPreferenceHelper(provider); - when(PreferenceHelper.hasSnowflakePrefs()).thenReturn(false); - when(PreferenceHelper.getUseSnowflake()).thenReturn(true); // getUseSnowflake() defaults to true if not set - mockStatic(ProviderSetupObservable.class); - - mockConfigHelper(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); - mockProviderApiConnector(ERROR_DNS_RESUOLUTION_TOR_FALLBACK); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider); + CertificateHelper certHelper = mockCertificateHelper(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(ERROR_DNS_RESUOLUTION_TOR_FALLBACK); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Intent providerApiCommand = mockIntent(); + Intent providerApiCommand = new Intent(); providerApiCommand.putExtra(PROVIDER_KEY, provider); providerApiCommand.setAction(ProviderAPI.SET_UP_PROVIDER); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_OK)); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); - mockTorStatusObservable(null); + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiManager.handleIntent(providerApiCommand); - assertEquals(8118, TorStatusObservable.getProxyPort()); + assertNotEquals(-1, TorStatusObservable.getProxyPort()); } @Test public void test_handleIntentSetupProvider_TorFallbackStartServiceException_SecondTryFailed() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, TimeoutException, InterruptedException { Provider provider = getConfiguredProviderAPIv4(); - mockPreferenceHelper(provider); - mockConfigHelper(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); - mockProviderApiConnector(ERROR_DNS_RESUOLUTION_TOR_FALLBACK); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider); + CertificateHelper certHelper = mockCertificateHelper(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(ERROR_DNS_RESUOLUTION_TOR_FALLBACK); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback(new IllegalStateException("Tor service start not failed."), true)); - Intent providerApiCommand = mockIntent(); + Intent providerApiCommand = new Intent(); providerApiCommand.putExtra(PROVIDER_KEY, provider); providerApiCommand.setAction(ProviderAPI.SET_UP_PROVIDER); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_NOK)); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); - mockTorStatusObservable(null); + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiManager.handleIntent(providerApiCommand); assertEquals(-1, TorStatusObservable.getProxyPort()); @@ -770,17 +748,16 @@ public class ProviderApiManagerTest { @Test public void test_handleIntentSetupProvider_TorFallbackTimeoutException_SecondTryFailed() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, TimeoutException, InterruptedException { Provider provider = getConfiguredProviderAPIv4(); - mockPreferenceHelper(provider); - mockConfigHelper(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); - mockProviderApiConnector(ERROR_DNS_RESUOLUTION_TOR_FALLBACK); - providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider); + CertificateHelper certHelper = mockCertificateHelper(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(ERROR_DNS_RESUOLUTION_TOR_FALLBACK); + providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback(true, true)); - Intent providerApiCommand = mockIntent(); + Intent providerApiCommand = new Intent(); providerApiCommand.putExtra(PROVIDER_KEY, provider); providerApiCommand.setAction(ProviderAPI.SET_UP_PROVIDER); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_NOK)); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); - mockTorStatusObservable(new TimeoutException("Tor took too long to start.")); + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiManager.handleIntent(providerApiCommand); assertEquals(-1, TorStatusObservable.getProxyPort()); @@ -790,23 +767,19 @@ public class ProviderApiManagerTest { public void test_handleIntentSetupProvider_TorBridgesPreferenceEnabled_Success() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, TimeoutException, InterruptedException { Provider provider = getConfiguredProviderAPIv4(); - mockPreferenceHelper(provider); - mockConfigHelper(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); - mockProviderApiConnector(NO_ERROR_API_V4); - mockStatic(ProviderSetupObservable.class); - - when(PreferenceHelper.getUseBridges()).thenReturn(true); - when(PreferenceHelper.getUseSnowflake()).thenReturn(true); - when(PreferenceHelper.hasSnowflakePrefs()).thenReturn(true); + SharedPreferences sharedPreferences = new MockSharedPreferences(); + sharedPreferences.edit().putBoolean(USE_BRIDGES, true).putBoolean(USE_SNOWFLAKE, true).commit(); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider, sharedPreferences); + CertificateHelper certHelper = mockCertificateHelper(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(NO_ERROR_API_V4); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Intent providerApiCommand = mockIntent(); + Intent providerApiCommand = new Intent(); providerApiCommand.putExtra(PROVIDER_KEY, provider); providerApiCommand.setAction(ProviderAPI.SET_UP_PROVIDER); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_OK)); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); - mockTorStatusObservable(null); + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiManager.handleIntent(providerApiCommand); assertEquals(8118, TorStatusObservable.getProxyPort()); @@ -816,23 +789,19 @@ public class ProviderApiManagerTest { public void test_handleIntentSetupProvider_TorBridgesDisabled_TorNotStarted() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, TimeoutException, InterruptedException { Provider provider = getConfiguredProviderAPIv4(); - mockPreferenceHelper(provider); - mockConfigHelper(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); - mockProviderApiConnector(NO_ERROR_API_V4); - - mockStatic(ProviderSetupObservable.class); - when(PreferenceHelper.getUseBridges()).thenReturn(false); - when(PreferenceHelper.getUseSnowflake()).thenReturn(false); - when(PreferenceHelper.hasSnowflakePrefs()).thenReturn(true); + SharedPreferences sharedPreferences = new MockSharedPreferences(); + sharedPreferences.edit().putBoolean(USE_BRIDGES, false).putBoolean(USE_SNOWFLAKE, false).commit(); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider, sharedPreferences); + CertificateHelper certHelper = mockCertificateHelper(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(NO_ERROR_API_V4); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Intent providerApiCommand = mockIntent(); + Intent providerApiCommand = new Intent(); providerApiCommand.putExtra(PROVIDER_KEY, provider); providerApiCommand.setAction(ProviderAPI.SET_UP_PROVIDER); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_OK)); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); - mockTorStatusObservable(new TimeoutException("This timeout exception is never thrown")); + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiManager.handleIntent(providerApiCommand); assertEquals(-1, TorStatusObservable.getProxyPort()); @@ -841,47 +810,40 @@ public class ProviderApiManagerTest { @Test public void test_handleIntentUpdateVPNCertificate_TorBridgesPreferencesNotConfigured_TorStartedAndSuccess() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, TimeoutException, InterruptedException { Provider provider = getConfiguredProviderAPIv4(); - mockPreferenceHelper(provider); - when(PreferenceHelper.hasSnowflakePrefs()).thenReturn(false); - when(PreferenceHelper.getUseSnowflake()).thenReturn(true); - mockConfigHelper(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); - mockRSAHelper(); - mockBase64(); - mockProviderApiConnector(ERROR_DNS_RESUOLUTION_TOR_FALLBACK); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider); + CertificateHelper certHelper = mockCertificateHelper(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + RSAHelper rsaHelper = mockRSAHelper(); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(ERROR_DNS_RESUOLUTION_TOR_FALLBACK); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Intent providerApiCommand = mockIntent(); + Intent providerApiCommand = new Intent(); providerApiCommand.putExtra(PROVIDER_KEY, provider); providerApiCommand.setAction(ProviderAPI.UPDATE_INVALID_VPN_CERTIFICATE); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(CORRECTLY_UPDATED_INVALID_VPN_CERTIFICATE)); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); - mockTorStatusObservable(null); + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiManager.handleIntent(providerApiCommand); - assertNotEquals(-1, TorStatusObservable.getProxyPort()); + assertEquals(8118, TorStatusObservable.getProxyPort()); } @Test public void test_handleIntentUpdateVPNCertificate_TorBridgesPreferencesFalse_TorNotStartedAndFailure() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, TimeoutException, InterruptedException { Provider provider = getConfiguredProviderAPIv4(); - mockPreferenceHelper(provider); - mockConfigHelper(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); - mockBase64(); - mockProviderApiConnector(ERROR_DNS_RESUOLUTION_TOR_FALLBACK); - when(PreferenceHelper.getUseBridges()).thenReturn(false); - when(PreferenceHelper.getUseSnowflake()).thenReturn(false); - when(PreferenceHelper.hasSnowflakePrefs()).thenReturn(true); + SharedPreferences sharedPreferences = new MockSharedPreferences(); + sharedPreferences.edit().putBoolean(USE_BRIDGES, false).putBoolean(USE_SNOWFLAKE, false).commit(); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider, sharedPreferences); + CertificateHelper certHelper = mockCertificateHelper(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(ERROR_DNS_RESUOLUTION_TOR_FALLBACK); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Intent providerApiCommand = mockIntent(); + Intent providerApiCommand = new Intent(); providerApiCommand.putExtra(PROVIDER_KEY, provider); providerApiCommand.setAction(ProviderAPI.UPDATE_INVALID_VPN_CERTIFICATE); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(INCORRECTLY_UPDATED_INVALID_VPN_CERTIFICATE)); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); - mockTorStatusObservable(new TimeoutException("This timeout exception is never thrown")); + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiManager.handleIntent(providerApiCommand); assertEquals(-1, TorStatusObservable.getProxyPort()); @@ -891,23 +853,20 @@ public class ProviderApiManagerTest { public void test_handleIntentUpdateVPNCertificate_TorBridgesPreferencesTrue_TorStartedAndSuccess() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, TimeoutException, InterruptedException { Provider provider = getConfiguredProviderAPIv4(); - mockPreferenceHelper(provider); - mockConfigHelper(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); - mockBase64(); - mockRSAHelper(); - mockProviderApiConnector(NO_ERROR_API_V4); - when(PreferenceHelper.getUseBridges()).thenReturn(true); - when(PreferenceHelper.getUseSnowflake()).thenReturn(true); - when(PreferenceHelper.hasSnowflakePrefs()).thenReturn(true); + SharedPreferences sharedPreferences = new MockSharedPreferences(); + sharedPreferences.edit().putBoolean(USE_BRIDGES, true).putBoolean(USE_SNOWFLAKE, true).commit(); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider, sharedPreferences); + CertificateHelper certHelper = mockCertificateHelper(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + RSAHelper rsaHelper = mockRSAHelper(); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(NO_ERROR_API_V4); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); - Intent providerApiCommand = mockIntent(); + Intent providerApiCommand = new Intent(); providerApiCommand.putExtra(PROVIDER_KEY, provider); providerApiCommand.setAction(ProviderAPI.UPDATE_INVALID_VPN_CERTIFICATE); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(CORRECTLY_UPDATED_INVALID_VPN_CERTIFICATE)); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); - mockTorStatusObservable(null); + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiManager.handleIntent(providerApiCommand); assertNotEquals(-1, TorStatusObservable.getProxyPort()); @@ -917,27 +876,24 @@ public class ProviderApiManagerTest { public void test_handleIntentUpdateVPNCertificate_TorBridgesPreferencesTrue_TorException_Failure() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, TimeoutException, InterruptedException { Provider provider = getConfiguredProviderAPIv4(); - mockPreferenceHelper(provider); - mockConfigHelper(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); - mockBase64(); - mockProviderApiConnector(NO_ERROR_API_V4); - when(PreferenceHelper.getUseBridges()).thenReturn(true); - when(PreferenceHelper.getUseSnowflake()).thenReturn(true); - when(PreferenceHelper.hasSnowflakePrefs()).thenReturn(true); + SharedPreferences sharedPreferences = new MockSharedPreferences(); + sharedPreferences.edit().putBoolean(USE_BRIDGES, true).putBoolean(USE_SNOWFLAKE, true).commit(); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider, sharedPreferences); + CertificateHelper certHelper = mockCertificateHelper(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(NO_ERROR_API_V4); - providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); + providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback(new IllegalStateException("Nothing works always."), true)); - Bundle expectedResult = mockBundle(); + Bundle expectedResult = new Bundle(); expectedResult.putBoolean(BROADCAST_RESULT_KEY, false); expectedResult.putString(ERRORS, "{\"initalAction\":\"ProviderAPI.UPDATE_INVALID_VPN_CERTIFICATE\"}"); expectedResult.putParcelable(PROVIDER_KEY, provider); - Intent providerApiCommand = mockIntent(); + Intent providerApiCommand = new Intent(); providerApiCommand.putExtra(PROVIDER_KEY, provider); providerApiCommand.setAction(ProviderAPI.UPDATE_INVALID_VPN_CERTIFICATE); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(TOR_EXCEPTION, expectedResult)); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); - mockTorStatusObservable(new InterruptedException("Tor thread was interrupted.")); + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiManager.handleIntent(providerApiCommand); assertEquals(-1, TorStatusObservable.getProxyPort()); @@ -946,25 +902,23 @@ public class ProviderApiManagerTest { @Test public void test_handleIntentSetupProvider_TorBridgesPreferencesEnabledTimeout_TimeoutError() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, TimeoutException, InterruptedException { Provider provider = getConfiguredProviderAPIv4(); + SharedPreferences sharedPreferences = new MockSharedPreferences(); + sharedPreferences.edit().putBoolean(USE_BRIDGES, true).putBoolean(USE_SNOWFLAKE, true).commit(); + PreferenceHelper preferenceHelper = mockPreferenceHelper(provider, sharedPreferences); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(NO_ERROR_API_V4); - mockPreferenceHelper(provider); - when(PreferenceHelper.getUseBridges()).thenReturn(true); - when(PreferenceHelper.getUseSnowflake()).thenReturn(true); - when(PreferenceHelper.hasSnowflakePrefs()).thenReturn(true); - - providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback()); + providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback(true, true)); - Bundle expectedResult = mockBundle(); + Bundle expectedResult = new Bundle(); expectedResult.putBoolean(BROADCAST_RESULT_KEY, false); expectedResult.putString(ERRORS, "{\"errorId\":\"ERROR_TOR_TIMEOUT\",\"initalAction\":\"setUpProvider\",\"errors\":\"Starting bridges failed. Do you want to retry or continue with an unobfuscated secure connection to configure Bitmask?\"}"); expectedResult.putParcelable(PROVIDER_KEY, provider); - Intent providerApiCommand = mockIntent(); + Intent providerApiCommand = new Intent(); providerApiCommand.putExtra(PROVIDER_KEY, provider); providerApiCommand.setAction(ProviderAPI.SET_UP_PROVIDER); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(TOR_TIMEOUT, expectedResult)); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); - mockTorStatusObservable(new TimeoutException("Tor took too long to start.")); + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiManager.handleIntent(providerApiCommand); assertEquals(-1, TorStatusObservable.getProxyPort()); @@ -974,22 +928,21 @@ public class ProviderApiManagerTest { public void test_handleIntentSetupProvider_noNetwork_NetworkError() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, JSONException { Provider provider = getConfiguredProvider(); - mockConfigHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); - mockProviderApiConnector(NO_ERROR); + CertificateHelper certHelper = mockCertificateHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494"); + ProviderApiConnector mockedApiConnector = mockProviderApiConnector(NO_ERROR); providerApiManager = new ProviderApiManager(mockResources, mockClientGenerator(), new TestProviderApiServiceCallback(null, false)); - Bundle expectedResult = mockBundle(); + Bundle expectedResult = new Bundle(); expectedResult.putBoolean(BROADCAST_RESULT_KEY, false); expectedResult.putString(ERRORS, "{\"errors\":\"Bitmask has no internet connection. Please check your WiFi and cellular data settings.\"}"); expectedResult.putParcelable(PROVIDER_KEY, provider); - Intent providerApiCommand = mockIntent(); + Intent providerApiCommand = new Intent(); providerApiCommand.setAction(ProviderAPI.SET_UP_PROVIDER); providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(MISSING_NETWORK_CONNECTION, expectedResult)); providerApiCommand.putExtra(PROVIDER_KEY, provider); - providerApiCommand.putExtra(PARAMETERS, mockBundle()); + providerApiCommand.putExtra(PARAMETERS, new Bundle()); providerApiManager.handleIntent(providerApiCommand); } - } diff --git a/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/BackendMockProvider.java b/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/BackendMockProvider.java index 280aa5a1..4ef41619 100644 --- a/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/BackendMockProvider.java +++ b/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/BackendMockProvider.java @@ -18,6 +18,8 @@ package se.leap.bitmaskclient.testutils.BackendMockResponses; import java.io.IOException; +import se.leap.bitmaskclient.providersetup.ProviderApiConnector; + /** * Created by cyberta on 10.01.18. */ @@ -43,67 +45,43 @@ public class BackendMockProvider { ERROR_PAYLOAD_MISSING, // => IllegalArgumentException ERROR_TLS_1_2_NOT_SUPPORTED, // => UnknownServiceException ERROR_UNKNOWN_IO_EXCEPTION, // => IOException - ERROR_NO_ACCESS, ERROR_INVALID_SESSION_TOKEN, ERROR_NO_CONNECTION, - ERROR_WRONG_SRP_CREDENTIALS, NO_ERROR_API_V4, ERROR_DNS_RESUOLUTION_TOR_FALLBACK } - public static void provideBackendResponsesFor(TestBackendErrorCase errorCase) throws IOException { + public static ProviderApiConnector.ProviderApiConnectorInterface provideBackendResponsesFor(TestBackendErrorCase errorCase) throws IOException { switch (errorCase) { + case NO_ERROR -> { + return new NoErrorBackendResponse(); + } + case NO_ERROR_API_V4 -> { + return new NoErrorBackendResponseAPIv4(); + } + case ERROR_CASE_UPDATED_CERTIFICATE -> { + return new UpdatedCertificateBackendResponse(); + } + case ERROR_CASE_MICONFIGURED_PROVIDER -> { + return new MisconfiguredProviderBackendResponse(); + } + case ERROR_CASE_FETCH_EIP_SERVICE_CERTIFICATE_INVALID -> { + return new EipServiceJsonInvalidCertificateBackendResponse(); + } + case ERROR_GEOIP_SERVICE_IS_DOWN -> { + return new GeoIpServiceIsDownBackendResponse(); + } + case ERROR_GEOIP_SERVICE_IS_DOWN_TOR_FALLBACK -> { + return new GeoIpServiceNotReachableTorFallbackBackendResponse(); + } + case ERROR_DNS_RESUOLUTION_TOR_FALLBACK -> { + return new TorFallbackBackendResponse(); + } - case NO_ERROR: - new NoErrorBackendResponse(); - break; - case NO_ERROR_API_V4: - new NoErrorBackendResponseAPIv4(); - break; - case ERROR_CASE_UPDATED_CERTIFICATE: - new UpdatedCertificateBackendResponse(); - break; - case ERROR_CASE_MICONFIGURED_PROVIDER: - new MisconfiguredProviderBackendResponse(); - break; - case ERROR_CASE_FETCH_EIP_SERVICE_CERTIFICATE_INVALID: - new EipSerivceJsonInvalidCertificateBackendResponse(); - break; - case ERROR_GEOIP_SERVICE_IS_DOWN: - new GeoIpServiceIsDownBackendResponse(); - break; - case ERROR_GEOIP_SERVICE_IS_DOWN_TOR_FALLBACK: - new GeoIpServiceNotReachableTorFallbackBackendResponse(); - case ERROR_DNS_RESUOLUTION_TOR_FALLBACK: - new TorFallbackBackendResponse(); - break; - case ERROR_NO_RESPONSE_BODY: - break; - case ERROR_DNS_RESOLUTION_ERROR: - break; - case ERROR_SOCKET_TIMEOUT: - break; - case ERROR_WRONG_PROTOCOL: - break; - case ERROR_CERTIFICATE_INVALID: - break; - case ERROR_WRONG_PORT: - break; - case ERROR_PAYLOAD_MISSING: - break; - case ERROR_TLS_1_2_NOT_SUPPORTED: - break; - case ERROR_UNKNOWN_IO_EXCEPTION: - break; - case ERROR_NO_ACCESS: - break; - case ERROR_INVALID_SESSION_TOKEN: - break; - case ERROR_NO_CONNECTION: - break; - case ERROR_WRONG_SRP_CREDENTIALS: - break; + default -> { + return new NoErrorBackendResponse(); + } } } } diff --git a/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/BaseBackendResponse.java b/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/BaseBackendResponse.java deleted file mode 100644 index 9a538d3c..00000000 --- a/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/BaseBackendResponse.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Copyright (c) 2018 LEAP Encryption Access Project and contributers - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package se.leap.bitmaskclient.testutils.BackendMockResponses; - -import android.util.Pair; - -import org.mockito.ArgumentMatchers; -import org.mockito.Mockito; -import org.mockito.stubbing.Answer; - -import java.io.IOException; - -import okhttp3.OkHttpClient; -import se.leap.bitmaskclient.providersetup.ProviderApiConnector; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.nullable; -import static org.powermock.api.mockito.PowerMockito.mockStatic; - -/** - * Created by cyberta on 10.01.18. - */ - -public abstract class BaseBackendResponse { - - private Answer answerRequestStringFromServer; - private Answer answerCanConnect; - private Answer answerDelete; - - public BaseBackendResponse() throws IOException { - mockStatic(ProviderApiConnector.class); - this.answerRequestStringFromServer = getAnswerForRequestStringFromServer(); - this.answerCanConnect = getAnswerForCanConnect(); - this.answerDelete = getAnswerForDelete(); - - responseOnRequestStringFromServer(); - responseOnCanConnect(); - responseOnDelete(); - - } - - public abstract Answer getAnswerForRequestStringFromServer(); - public abstract Answer getAnswerForCanConnect(); - public abstract Answer getAnswerForDelete(); - - - public void responseOnRequestStringFromServer() throws IOException, RuntimeException { - Mockito.when(ProviderApiConnector.requestStringFromServer(anyString(), anyString(), nullable(String.class), ArgumentMatchers.>anyList(), any(OkHttpClient.class))). - thenAnswer(answerRequestStringFromServer); - } - - public void responseOnCanConnect() throws IOException, RuntimeException { - Mockito.when(ProviderApiConnector.canConnect(any(OkHttpClient.class), anyString())).thenAnswer(answerCanConnect); - } - - public void responseOnDelete() throws IOException, RuntimeException { - Mockito.when(ProviderApiConnector.delete(any(OkHttpClient.class), anyString())).thenAnswer(answerDelete); - } - -} diff --git a/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/EipSerivceJsonInvalidCertificateBackendResponse.java b/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/EipSerivceJsonInvalidCertificateBackendResponse.java deleted file mode 100644 index 7c2d49cc..00000000 --- a/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/EipSerivceJsonInvalidCertificateBackendResponse.java +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Copyright (c) 2018 LEAP Encryption Access Project and contributers - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package se.leap.bitmaskclient.testutils.BackendMockResponses; - -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.io.IOException; - -import javax.net.ssl.SSLHandshakeException; - -import static se.leap.bitmaskclient.testutils.TestSetupHelper.getInputAsString; - -/** - * Created by cyberta on 10.01.18. - */ - -public class EipSerivceJsonInvalidCertificateBackendResponse extends BaseBackendResponse { - public EipSerivceJsonInvalidCertificateBackendResponse() throws IOException { - super(); - } - - @Override - public Answer getAnswerForRequestStringFromServer() { - return new Answer() { - @Override - public String answer(InvocationOnMock invocation) throws Throwable { - String url = (String) invocation.getArguments()[0]; - String requestMethod = (String) invocation.getArguments()[1]; - String jsonPayload = (String) invocation.getArguments()[2]; - - if (url.contains("/provider.json")) { - //download provider json - return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.json")); - } else if (url.contains("/ca.crt")) { - //download provider ca cert - return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.pem")); - } else if (url.contains("config/eip-service.json")) { - // download provider service json containing gateways, locations and openvpn settings - throw new SSLHandshakeException("Invalid provider CA certificate"); - } else if (url.contains(":9001/json")) { - // download geoip json, containing a sorted list of gateways - return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.geoip.json")); - } else if (url.contains("/users.json")) { - //create new user - //TODO: implement me - } else if (url.contains("/sessions.json")) { - //srp auth: sendAToSRPServer - //TODO: implement me - } else if (url.contains("/sessions/parmegvtest10.json")){ - //srp auth: sendM1ToSRPServer - //TODO: implement me - } - - return null; - } - }; - } - - @Override - public Answer getAnswerForCanConnect() { - return new Answer() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - return true; - } - }; - } - - @Override - public Answer getAnswerForDelete() { - return new Answer() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - return true; - } - }; - } - -} diff --git a/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/EipServiceJsonInvalidCertificateBackendResponse.java b/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/EipServiceJsonInvalidCertificateBackendResponse.java new file mode 100644 index 00000000..15df00cb --- /dev/null +++ b/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/EipServiceJsonInvalidCertificateBackendResponse.java @@ -0,0 +1,66 @@ +/** + * Copyright (c) 2018 LEAP Encryption Access Project and contributers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package se.leap.bitmaskclient.testutils.BackendMockResponses; + +import java.io.IOException; +import java.util.List; + +import javax.net.ssl.SSLHandshakeException; + +import static se.leap.bitmaskclient.testutils.TestSetupHelper.getInputAsString; + +import android.util.Pair; + +import androidx.annotation.NonNull; + +import okhttp3.OkHttpClient; +import se.leap.bitmaskclient.providersetup.ProviderApiConnector; + +/** + * Created by cyberta on 10.01.18. + */ + +public class EipServiceJsonInvalidCertificateBackendResponse implements ProviderApiConnector.ProviderApiConnectorInterface { + + @Override + public boolean delete(OkHttpClient okHttpClient, String deleteUrl) { + return true; + } + + @Override + public boolean canConnect(@NonNull OkHttpClient okHttpClient, String url) throws RuntimeException, IOException { + return true; + } + + @Override + public String requestStringFromServer(@NonNull String url, @NonNull String requestMethod, String jsonString, @NonNull List> headerArgs, @NonNull OkHttpClient okHttpClient) throws RuntimeException, IOException { + if (url.contains("/provider.json")) { + //download provider json + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.json")); + } else if (url.contains("/ca.crt")) { + //download provider ca cert + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.pem")); + } else if (url.contains("config/eip-service.json")) { + // download provider service json containing gateways, locations and openvpn settings + throw new SSLHandshakeException("Invalid provider CA certificate"); + } else if (url.contains(":9001/json")) { + // download geoip json, containing a sorted list of gateways + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.geoip.json")); + } + return null; + } +} diff --git a/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/GeoIpServiceIsDownBackendResponse.java b/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/GeoIpServiceIsDownBackendResponse.java index 3a08d8da..482276a6 100644 --- a/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/GeoIpServiceIsDownBackendResponse.java +++ b/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/GeoIpServiceIsDownBackendResponse.java @@ -16,78 +16,51 @@ */ package se.leap.bitmaskclient.testutils.BackendMockResponses; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; +import static se.leap.bitmaskclient.testutils.TestSetupHelper.getInputAsString; + +import android.util.Pair; + +import androidx.annotation.NonNull; import java.io.IOException; import java.net.ConnectException; +import java.util.List; -import static se.leap.bitmaskclient.testutils.TestSetupHelper.getInputAsString; +import okhttp3.OkHttpClient; +import se.leap.bitmaskclient.providersetup.ProviderApiConnector; /** * Created by cyberta on 10.01.18. */ -public class GeoIpServiceIsDownBackendResponse extends BaseBackendResponse { - public GeoIpServiceIsDownBackendResponse() throws IOException { - super(); - } +public class GeoIpServiceIsDownBackendResponse implements ProviderApiConnector.ProviderApiConnectorInterface { @Override - public Answer getAnswerForRequestStringFromServer() { - return new Answer() { - @Override - public String answer(InvocationOnMock invocation) throws Throwable { - String url = (String) invocation.getArguments()[0]; - String requestMethod = (String) invocation.getArguments()[1]; - String jsonPayload = (String) invocation.getArguments()[2]; - - if (url.contains("/provider.json")) { - //download provider json - return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.json")); - } else if (url.contains("/ca.crt")) { - //download provider ca cert - return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.pem")); - } else if (url.contains("config/eip-service.json")) { - // download provider service json containing gateways, locations and openvpn settings - return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.service.json")); - } else if (url.contains(":9001/json")) { - // download geoip json, containing a sorted list of gateways - throw new ConnectException("Failed to connect to api.black.riseup.net/198.252.153.107:9001"); - } else if (url.contains("/users.json")) { - //create new user - //TODO: implement me - } else if (url.contains("/sessions.json")) { - //srp auth: sendAToSRPServer - //TODO: implement me - } else if (url.contains("/sessions/parmegvtest10.json")){ - //srp auth: sendM1ToSRPServer - //TODO: implement me - } - - return null; - } - }; + public boolean delete(OkHttpClient okHttpClient, String deleteUrl) throws RuntimeException, IOException { + return true; } @Override - public Answer getAnswerForCanConnect() { - return new Answer() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - return true; - } - }; + public boolean canConnect(@NonNull OkHttpClient okHttpClient, String url) throws RuntimeException, IOException { + return true; } @Override - public Answer getAnswerForDelete() { - return new Answer() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - return true; - } - }; - } + public String requestStringFromServer(@NonNull String url, @NonNull String requestMethod, String jsonString, @NonNull List> headerArgs, @NonNull OkHttpClient okHttpClient) throws RuntimeException, IOException { + if (url.contains("/provider.json")) { + //download provider json + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.json")); + } else if (url.contains("/ca.crt")) { + //download provider ca cert + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.pem")); + } else if (url.contains("config/eip-service.json")) { + // download provider service json containing gateways, locations and openvpn settings + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.service.json")); + } else if (url.contains(":9001/json")) { + // download geoip json, containing a sorted list of gateways + throw new ConnectException("Failed to connect to api.black.riseup.net/198.252.153.107:9001"); + } + return null; + } } diff --git a/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/GeoIpServiceNotReachableTorFallbackBackendResponse.java b/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/GeoIpServiceNotReachableTorFallbackBackendResponse.java index 02aa31fa..d11c21f8 100644 --- a/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/GeoIpServiceNotReachableTorFallbackBackendResponse.java +++ b/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/GeoIpServiceNotReachableTorFallbackBackendResponse.java @@ -16,74 +16,61 @@ */ package se.leap.bitmaskclient.testutils.BackendMockResponses; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; +import static se.leap.bitmaskclient.testutils.TestSetupHelper.getInputAsString; + +import android.util.Pair; + +import androidx.annotation.NonNull; import java.io.IOException; import java.net.ConnectException; +import java.util.List; -import static se.leap.bitmaskclient.testutils.TestSetupHelper.getInputAsString; +import okhttp3.OkHttpClient; +import se.leap.bitmaskclient.providersetup.ProviderApiConnector; /** * Created by cyberta on 10.01.18. */ -public class GeoIpServiceNotReachableTorFallbackBackendResponse extends BaseBackendResponse { +public class GeoIpServiceNotReachableTorFallbackBackendResponse implements ProviderApiConnector.ProviderApiConnectorInterface { public GeoIpServiceNotReachableTorFallbackBackendResponse() throws IOException { super(); } int requestAttempt = 0; @Override - public Answer getAnswerForRequestStringFromServer() { - return new Answer() { - @Override - public String answer(InvocationOnMock invocation) throws Throwable { - String url = (String) invocation.getArguments()[0]; - - if (url.contains("/provider.json")) { - //download provider json - return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.json")); - } else if (url.contains("/ca.crt")) { - //download provider ca cert - return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.pem")); - } else if (url.contains("config/eip-service.json")) { - // download provider service json containing gateways, locations and openvpn settings - return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.service.json")); - } else if (url.contains(":9001/json")) { - if (requestAttempt == 0) { - // download geoip json, containing a sorted list of gateways - requestAttempt++; - throw new ConnectException("Failed to connect to api.black.riseup.net/198.252.153.107:9001"); - } else { - // assumtion: 2. connection attempt has been made with proxy on, which is not allowed - // this branch should never be called otherwise you have found a bug - return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.geoip.json")); - } - } - return null; - } - }; + public boolean delete(OkHttpClient okHttpClient, String deleteUrl) throws RuntimeException, IOException { + return true; } @Override - public Answer getAnswerForCanConnect() { - return new Answer() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - return true; - } - }; + public boolean canConnect(@NonNull OkHttpClient okHttpClient, String url) throws RuntimeException, IOException { + return true; } @Override - public Answer getAnswerForDelete() { - return new Answer() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - return true; + public String requestStringFromServer(@NonNull String url, @NonNull String requestMethod, String jsonString, @NonNull List> headerArgs, @NonNull OkHttpClient okHttpClient) throws RuntimeException, IOException { + if (url.contains("/provider.json")) { + //download provider json + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.json")); + } else if (url.contains("/ca.crt")) { + //download provider ca cert + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.pem")); + } else if (url.contains("config/eip-service.json")) { + // download provider service json containing gateways, locations and openvpn settings + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.service.json")); + } else if (url.contains(":9001/json")) { + if (requestAttempt == 0) { + // download geoip json, containing a sorted list of gateways + requestAttempt++; + throw new ConnectException("Failed to connect to api.black.riseup.net/198.252.153.107:9001"); + } else { + // assumtion: 2. connection attempt has been made with proxy on, which is not allowed + // this branch should never be called otherwise you have found a bug + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.geoip.json")); } - }; + } + return null; } - } diff --git a/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/MisconfiguredProviderBackendResponse.java b/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/MisconfiguredProviderBackendResponse.java index 10e69bc3..301f1a75 100644 --- a/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/MisconfiguredProviderBackendResponse.java +++ b/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/MisconfiguredProviderBackendResponse.java @@ -16,77 +16,50 @@ */ package se.leap.bitmaskclient.testutils.BackendMockResponses; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; +import static se.leap.bitmaskclient.testutils.TestSetupHelper.getInputAsString; + +import android.util.Pair; + +import androidx.annotation.NonNull; import java.io.IOException; +import java.util.List; -import static se.leap.bitmaskclient.testutils.TestSetupHelper.getInputAsString; +import okhttp3.OkHttpClient; +import se.leap.bitmaskclient.providersetup.ProviderApiConnector; /** * Created by cyberta on 10.01.18. */ -public class MisconfiguredProviderBackendResponse extends BaseBackendResponse { - public MisconfiguredProviderBackendResponse() throws IOException { - super(); - } +public class MisconfiguredProviderBackendResponse implements ProviderApiConnector.ProviderApiConnectorInterface { @Override - public Answer getAnswerForRequestStringFromServer() { - return new Answer() { - @Override - public String answer(InvocationOnMock invocation) throws Throwable { - String url = (String) invocation.getArguments()[0]; - String requestMethod = (String) invocation.getArguments()[1]; - String jsonPayload = (String) invocation.getArguments()[2]; - - if (url.contains("/provider.json")) { - //download provider json - return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup_net_invalid_config.json")); - } else if (url.contains("/ca.crt")) { - //download provider ca cert - return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.pem")); - } else if (url.contains("config/eip-service.json")) { - // download provider service json containing gateways, locations and openvpn settings - return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.service.json")); - } else if (url.contains(":9001/json")) { - // download geoip json, containing a sorted list of gateways - return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.geoip.json")); - } else if (url.contains("/users.json")) { - //create new user - //TODO: implement me - } else if (url.contains("/sessions.json")) { - //srp auth: sendAToSRPServer - //TODO: implement me - } else if (url.contains("/sessions/parmegvtest10.json")){ - //srp auth: sendM1ToSRPServer - //TODO: implement me - } - - return null; - } - }; + public boolean delete(OkHttpClient okHttpClient, String deleteUrl) throws RuntimeException, IOException { + return true; } @Override - public Answer getAnswerForCanConnect() { - return new Answer() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - return true; - } - }; + public boolean canConnect(@NonNull OkHttpClient okHttpClient, String url) throws RuntimeException, IOException { + return true; } @Override - public Answer getAnswerForDelete() { - return new Answer() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - return true; - } - }; - } + public String requestStringFromServer(@NonNull String url, @NonNull String requestMethod, String jsonString, @NonNull List> headerArgs, @NonNull OkHttpClient okHttpClient) throws RuntimeException, IOException { + if (url.contains("/provider.json")) { + //download provider json + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup_net_invalid_config.json")); + } else if (url.contains("/ca.crt")) { + //download provider ca cert + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.pem")); + } else if (url.contains("config/eip-service.json")) { + // download provider service json containing gateways, locations and openvpn settings + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.service.json")); + } else if (url.contains(":9001/json")) { + // download geoip json, containing a sorted list of gateways + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.geoip.json")); + } + return null; + } } diff --git a/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/NoErrorBackendResponse.java b/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/NoErrorBackendResponse.java index 3c3a8ffa..44067139 100644 --- a/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/NoErrorBackendResponse.java +++ b/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/NoErrorBackendResponse.java @@ -16,77 +16,50 @@ */ package se.leap.bitmaskclient.testutils.BackendMockResponses; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; +import static se.leap.bitmaskclient.testutils.TestSetupHelper.getInputAsString; + +import android.util.Pair; + +import androidx.annotation.NonNull; import java.io.IOException; +import java.util.List; -import static se.leap.bitmaskclient.testutils.TestSetupHelper.getInputAsString; +import okhttp3.OkHttpClient; +import se.leap.bitmaskclient.providersetup.ProviderApiConnector; /** * Created by cyberta on 10.01.18. */ -public class NoErrorBackendResponse extends BaseBackendResponse { - public NoErrorBackendResponse() throws IOException { - super(); - } +public class NoErrorBackendResponse implements ProviderApiConnector.ProviderApiConnectorInterface { @Override - public Answer getAnswerForRequestStringFromServer() { - return new Answer() { - @Override - public String answer(InvocationOnMock invocation) throws Throwable { - String url = (String) invocation.getArguments()[0]; - String requestMethod = (String) invocation.getArguments()[1]; - String jsonPayload = (String) invocation.getArguments()[2]; - - if (url.contains("/provider.json")) { - //download provider json - return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.json")); - } else if (url.contains("/ca.crt")) { - //download provider ca cert - return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.pem")); - } else if (url.contains("config/eip-service.json")) { - // download provider service json containing gateways, locations and openvpn settings - return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.service.json")); - } else if (url.contains(":9001/json")) { - // download geoip json, containing a sorted list of gateways - return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.geoip.json")); - } else if (url.contains("/users.json")) { - //create new user - //TODO: implement me - } else if (url.contains("/sessions.json")) { - //srp auth: sendAToSRPServer - //TODO: implement me - } else if (url.contains("/sessions/parmegvtest10.json")){ - //srp auth: sendM1ToSRPServer - //TODO: implement me - } - - return null; - } - }; + public boolean delete(OkHttpClient okHttpClient, String deleteUrl) { + return true; } @Override - public Answer getAnswerForCanConnect() { - return new Answer() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - return true; - } - }; + public boolean canConnect(@NonNull OkHttpClient okHttpClient, String url) throws RuntimeException, IOException { + return true; } @Override - public Answer getAnswerForDelete() { - return new Answer() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - return true; - } - }; - } + public String requestStringFromServer(@NonNull String url, @NonNull String requestMethod, String jsonString, @NonNull List> headerArgs, @NonNull OkHttpClient okHttpClient) throws RuntimeException, IOException { + if (url.contains("/provider.json")) { + //download provider json + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.json")); + } else if (url.contains("/ca.crt")) { + //download provider ca cert + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.pem")); + } else if (url.contains("config/eip-service.json")) { + // download provider service json containing gateways, locations and openvpn settings + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.service.json")); + } else if (url.contains(":9001/json")) { + // download geoip json, containing a sorted list of gateways + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.geoip.json")); + } + return null; + } } diff --git a/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/NoErrorBackendResponseAPIv4.java b/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/NoErrorBackendResponseAPIv4.java index b9dc26b1..bbbed821 100644 --- a/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/NoErrorBackendResponseAPIv4.java +++ b/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/NoErrorBackendResponseAPIv4.java @@ -16,80 +16,52 @@ */ package se.leap.bitmaskclient.testutils.BackendMockResponses; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; +import static se.leap.bitmaskclient.testutils.TestSetupHelper.getInputAsString; + +import android.util.Pair; + +import androidx.annotation.NonNull; import java.io.IOException; +import java.util.List; -import static se.leap.bitmaskclient.testutils.TestSetupHelper.getInputAsString; +import okhttp3.OkHttpClient; +import se.leap.bitmaskclient.providersetup.ProviderApiConnector; /** * Created by cyberta on 10.01.18. */ -public class NoErrorBackendResponseAPIv4 extends BaseBackendResponse { - public NoErrorBackendResponseAPIv4() throws IOException { - super(); - } - +public class NoErrorBackendResponseAPIv4 implements ProviderApiConnector.ProviderApiConnectorInterface { @Override - public Answer getAnswerForRequestStringFromServer() { - return new Answer() { - @Override - public String answer(InvocationOnMock invocation) throws Throwable { - String url = (String) invocation.getArguments()[0]; - String requestMethod = (String) invocation.getArguments()[1]; - String jsonPayload = (String) invocation.getArguments()[2]; - - if (url.contains("/provider.json")) { - //download provider json - return getInputAsString(getClass().getClassLoader().getResourceAsStream("v4/riseup.net.json")); - } else if (url.contains("/ca.crt")) { - //download provider ca cert - return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.pem")); - } else if (url.contains("config/eip-service.json")) { - // download provider service json containing gateways, locations and openvpn settings - return getInputAsString(getClass().getClassLoader().getResourceAsStream("v4/riseup.service.json")); - } else if (url.contains(":9001/json")) { - // download geoip json, containing a sorted list of gateways - return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.geoip.json")); - } else if (url.contains("/cert")) { - // download vpn key and cert - return getInputAsString(getClass().getClassLoader().getResourceAsStream("v4/riseup.net.cert")); - } else if (url.contains("/users.json")) { - //create new user - //TODO: implement me - } else if (url.contains("/sessions.json")) { - //srp auth: sendAToSRPServer - //TODO: implement me - } else if (url.contains("/sessions/parmegvtest10.json")){ - //srp auth: sendM1ToSRPServer - //TODO: implement me - } - - return null; - } - }; + public boolean delete(OkHttpClient okHttpClient, String deleteUrl) { + return true; } @Override - public Answer getAnswerForCanConnect() { - return new Answer() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - return true; - } - }; + public boolean canConnect(@NonNull OkHttpClient okHttpClient, String url) throws RuntimeException, IOException { + return true; } @Override - public Answer getAnswerForDelete() { - return new Answer() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - return true; - } - }; - } + public String requestStringFromServer(@NonNull String url, @NonNull String requestMethod, String jsonString, @NonNull List> headerArgs, @NonNull OkHttpClient okHttpClient) throws RuntimeException, IOException { + if (url.contains("/provider.json")) { + //download provider json + return getInputAsString(getClass().getClassLoader().getResourceAsStream("v4/riseup.net.json")); + } else if (url.contains("/ca.crt")) { + //download provider ca cert + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.pem")); + } else if (url.contains("config/eip-service.json")) { + // download provider service json containing gateways, locations and openvpn settings + return getInputAsString(getClass().getClassLoader().getResourceAsStream("v4/riseup.service.json")); + } else if (url.contains(":9001/json")) { + // download geoip json, containing a sorted list of gateways + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.geoip.json")); + } else if (url.contains("/cert")) { + // download vpn key and cert + return getInputAsString(getClass().getClassLoader().getResourceAsStream("v4/riseup.net.cert")); + } + return null; + } } diff --git a/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/TorFallbackBackendResponse.java b/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/TorFallbackBackendResponse.java index c3779a21..45dd36e4 100644 --- a/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/TorFallbackBackendResponse.java +++ b/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/TorFallbackBackendResponse.java @@ -1,94 +1,81 @@ package se.leap.bitmaskclient.testutils.BackendMockResponses; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; +import static se.leap.bitmaskclient.testutils.TestSetupHelper.getInputAsString; + +import android.util.Pair; + +import androidx.annotation.NonNull; import java.io.IOException; import java.net.UnknownHostException; +import java.util.List; -import static se.leap.bitmaskclient.testutils.TestSetupHelper.getInputAsString; +import okhttp3.OkHttpClient; +import se.leap.bitmaskclient.providersetup.ProviderApiConnector; -public class TorFallbackBackendResponse extends BaseBackendResponse { +public class TorFallbackBackendResponse implements ProviderApiConnector.ProviderApiConnectorInterface { public TorFallbackBackendResponse() throws IOException { super(); } int requestAttempt = 0; @Override - public Answer getAnswerForRequestStringFromServer() { - return new Answer() { - @Override - public String answer(InvocationOnMock invocation) throws Throwable { - String url = (String) invocation.getArguments()[0]; - - if (url.contains("/provider.json")) { - if (requestAttempt == 0) { - requestAttempt++; - throw new UnknownHostException(); - } - //download provider json - return getInputAsString(getClass().getClassLoader().getResourceAsStream("v4/riseup.net.json")); - } else if (url.contains("/ca.crt")) { - if (requestAttempt == 0) { - requestAttempt++; - throw new UnknownHostException("DNS blocked by censor ;)"); - } - //download provider ca cert - return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.pem")); - } else if (url.contains("config/eip-service.json")) { - if (requestAttempt == 0) { - requestAttempt++; - throw new UnknownHostException("DNS blocked by censor ;)"); - } - // download provider service json containing gateways, locations and openvpn settings - return getInputAsString(getClass().getClassLoader().getResourceAsStream("v4/riseup.service.json")); - } else if (url.contains(":9001/json")) { - if (requestAttempt == 0) { - requestAttempt++; - throw new UnknownHostException("DNS blocked by censor ;)"); - } - // download geoip json, containing a sorted list of gateways - return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.geoip.json")); - } else if (url.contains("/cert")) { - if (requestAttempt == 0) { - requestAttempt++; - throw new UnknownHostException("DNS blocked by censor ;)"); - } - // download vpn certificate for authentication - return getInputAsString(getClass().getClassLoader().getResourceAsStream("v4/riseup.net.cert")); - - } - - return null; - } - }; + public boolean delete(OkHttpClient okHttpClient, String deleteUrl) throws RuntimeException, IOException { + if (requestAttempt == 0) { + requestAttempt++; + throw new UnknownHostException("DNS blocked by censor ;)"); + } + return true; } @Override - public Answer getAnswerForCanConnect() { - return new Answer() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - if (requestAttempt == 0) { - requestAttempt++; - throw new UnknownHostException("DNS blocked by censor ;)"); - } - return true; - } - }; + public boolean canConnect(@NonNull OkHttpClient okHttpClient, String url) throws RuntimeException, IOException { + if (requestAttempt == 0) { + requestAttempt++; + throw new UnknownHostException("DNS blocked by censor ;)"); + } + return true; } @Override - public Answer getAnswerForDelete() { - return new Answer() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - if (requestAttempt == 0) { - requestAttempt++; - throw new UnknownHostException("DNS blocked by censor ;)"); - } - return true; + public String requestStringFromServer(@NonNull String url, @NonNull String requestMethod, String jsonString, @NonNull List> headerArgs, @NonNull OkHttpClient okHttpClient) throws RuntimeException, IOException { + if (url.contains("/provider.json")) { + if (requestAttempt == 0) { + requestAttempt++; + throw new UnknownHostException(); + } + //download provider json + return getInputAsString(getClass().getClassLoader().getResourceAsStream("v4/riseup.net.json")); + } else if (url.contains("/ca.crt")) { + if (requestAttempt == 0) { + requestAttempt++; + throw new UnknownHostException("DNS blocked by censor ;)"); + } + //download provider ca cert + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.pem")); + } else if (url.contains("config/eip-service.json")) { + if (requestAttempt == 0) { + requestAttempt++; + throw new UnknownHostException("DNS blocked by censor ;)"); } - }; + // download provider service json containing gateways, locations and openvpn settings + return getInputAsString(getClass().getClassLoader().getResourceAsStream("v4/riseup.service.json")); + } else if (url.contains(":9001/json")) { + if (requestAttempt == 0) { + requestAttempt++; + throw new UnknownHostException("DNS blocked by censor ;)"); + } + // download geoip json, containing a sorted list of gateways + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.geoip.json")); + } else if (url.contains("/cert")) { + if (requestAttempt == 0) { + requestAttempt++; + throw new UnknownHostException("DNS blocked by censor ;)"); + } + // download vpn certificate for authentication + return getInputAsString(getClass().getClassLoader().getResourceAsStream("v4/riseup.net.cert")); + + } + return null; } } diff --git a/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/UpdatedCertificateBackendResponse.java b/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/UpdatedCertificateBackendResponse.java index 232649a1..1da18f76 100644 --- a/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/UpdatedCertificateBackendResponse.java +++ b/app/src/test/java/se/leap/bitmaskclient/testutils/BackendMockResponses/UpdatedCertificateBackendResponse.java @@ -16,82 +16,63 @@ */ package se.leap.bitmaskclient.testutils.BackendMockResponses; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; +import static se.leap.bitmaskclient.testutils.TestSetupHelper.getInputAsString; + +import android.util.Pair; + +import androidx.annotation.NonNull; import java.io.IOException; +import java.util.List; import javax.net.ssl.SSLHandshakeException; -import static se.leap.bitmaskclient.testutils.TestSetupHelper.getInputAsString; +import okhttp3.OkHttpClient; +import se.leap.bitmaskclient.providersetup.ProviderApiConnector; /** * Created by cyberta on 10.01.18. */ -public class UpdatedCertificateBackendResponse extends BaseBackendResponse { +public class UpdatedCertificateBackendResponse implements ProviderApiConnector.ProviderApiConnectorInterface { static volatile boolean wasCACertCalled = false; - - public UpdatedCertificateBackendResponse() throws IOException { - super(); - } - @Override - public Answer getAnswerForRequestStringFromServer() { - return new Answer() { - - @Override - public String answer(InvocationOnMock invocation) throws Throwable { - String url = (String) invocation.getArguments()[0]; - - if (url.contains("/provider.json")) { - if (!wasCACertCalled) { - throw new SSLHandshakeException("Updated certificate on server side"); - } - //download provider json - return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.json")); - } else if (url.contains("/ca.crt")) { - //download provider ca cert - wasCACertCalled = true; - return getInputAsString(getClass().getClassLoader().getResourceAsStream("updated_cert.pem")); - } else if (url.contains("config/eip-service.json")) { - // download provider service json containing gateways, locations and openvpn settings - if (!wasCACertCalled) { - throw new SSLHandshakeException("Updated certificate on server side"); - } - return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.service.json")); - } - - return null; - } - }; + public boolean delete(OkHttpClient okHttpClient, String deleteUrl) throws RuntimeException, IOException { + if (!wasCACertCalled) { + throw new SSLHandshakeException("Updated certificate on server side"); + } + return true; } @Override - public Answer getAnswerForCanConnect() { - return new Answer() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - if (!wasCACertCalled) { - throw new SSLHandshakeException("Updated certificate on server side"); - } - return true; - } - }; + public boolean canConnect(@NonNull OkHttpClient okHttpClient, String url) throws RuntimeException, IOException { + if (!wasCACertCalled) { + throw new SSLHandshakeException("Updated certificate on server side"); + } + return true; } @Override - public Answer getAnswerForDelete() { - return new Answer() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - if (!wasCACertCalled) { - throw new SSLHandshakeException("Updated certificate on server side"); - } - return true; + public String requestStringFromServer(@NonNull String url, @NonNull String requestMethod, String jsonString, @NonNull List> headerArgs, @NonNull OkHttpClient okHttpClient) throws RuntimeException, IOException { + if (url.contains("/provider.json")) { + if (!wasCACertCalled) { + throw new SSLHandshakeException("Updated certificate on server side"); } - }; - } + //download provider json + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.json")); + } else if (url.contains("/ca.crt")) { + //download provider ca cert + wasCACertCalled = true; + return getInputAsString(getClass().getClassLoader().getResourceAsStream("updated_cert.pem")); + } else if (url.contains("config/eip-service.json")) { + // download provider service json containing gateways, locations and openvpn settings + if (!wasCACertCalled) { + throw new SSLHandshakeException("Updated certificate on server side"); + } + return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.service.json")); + } + return null; + } } diff --git a/app/src/test/java/se/leap/bitmaskclient/testutils/MockHelper.java b/app/src/test/java/se/leap/bitmaskclient/testutils/MockHelper.java index 33e2c056..3175b0ad 100644 --- a/app/src/test/java/se/leap/bitmaskclient/testutils/MockHelper.java +++ b/app/src/test/java/se/leap/bitmaskclient/testutils/MockHelper.java @@ -3,42 +3,39 @@ package se.leap.bitmaskclient.testutils; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.mockStatic; +import static se.leap.bitmaskclient.base.models.Constants.PROVIDER_CONFIGURED; +import static se.leap.bitmaskclient.base.models.Constants.PROVIDER_EIP_DEFINITION; import static se.leap.bitmaskclient.base.models.Constants.PROVIDER_MOTD; import static se.leap.bitmaskclient.base.models.Constants.PROVIDER_MOTD_HASHES; import static se.leap.bitmaskclient.base.models.Constants.PROVIDER_MOTD_LAST_SEEN; import static se.leap.bitmaskclient.base.models.Constants.PROVIDER_MOTD_LAST_UPDATED; import static se.leap.bitmaskclient.base.models.Constants.PROVIDER_PRIVATE_KEY; import static se.leap.bitmaskclient.base.models.Constants.PROVIDER_VPN_CERTIFICATE; -import static se.leap.bitmaskclient.base.utils.FileHelper.createFile; import static se.leap.bitmaskclient.base.utils.PreferenceHelper.getEipDefinitionFromPreferences; -import static se.leap.bitmaskclient.base.utils.PreferenceHelper.getFromPersistedProvider; -import static se.leap.bitmaskclient.base.utils.PreferenceHelper.getLongFromPersistedProvider; -import static se.leap.bitmaskclient.base.utils.PreferenceHelper.getStringSetFromPersistedProvider; import android.content.Context; import android.content.Intent; +import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.Resources; import android.os.Bundle; import android.os.Parcelable; import android.os.ResultReceiver; -import android.text.TextUtils; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import org.json.JSONException; import org.json.JSONObject; +import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @@ -48,8 +45,6 @@ import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.net.UnknownHostException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateEncodingException; import java.security.interfaces.RSAPrivateKey; import java.util.ArrayList; import java.util.Arrays; @@ -74,6 +69,7 @@ import se.leap.bitmaskclient.base.utils.InputStreamHelper; import se.leap.bitmaskclient.base.utils.BuildConfigHelper; import se.leap.bitmaskclient.base.utils.PreferenceHelper; import se.leap.bitmaskclient.base.utils.RSAHelper; +import se.leap.bitmaskclient.providersetup.ProviderApiConnector; import se.leap.bitmaskclient.providersetup.connectivity.DnsResolver; import se.leap.bitmaskclient.providersetup.connectivity.OkHttpClientGenerator; import se.leap.bitmaskclient.testutils.BackendMockResponses.BackendMockProvider; @@ -85,235 +81,6 @@ import se.leap.bitmaskclient.tor.TorStatusObservable; */ public class MockHelper { - @NonNull - public static Bundle mockBundle() { - final Map fakeBooleanBundle = new HashMap<>(); - final Map fakeStringBundle = new HashMap<>(); - final Map fakeIntBundle = new HashMap<>(); - final Map fakeParcelableBundle = new HashMap<>(); - - Bundle bundle = mock(Bundle.class); - - //mock String values in Bundle - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - Object[] arguments = invocation.getArguments(); - String key = ((String) arguments[0]); - String value = ((String) arguments[1]); - fakeStringBundle.put(key, value); - return null; - } - }).when(bundle).putString(anyString(), anyString()); - when(bundle.getString(anyString())).thenAnswer(new Answer() { - @Override - public String answer(InvocationOnMock invocation) throws Throwable { - Object[] arguments = invocation.getArguments(); - String key = ((String) arguments[0]); - return fakeStringBundle.get(key); - } - }); - - //mock Boolean values in Bundle - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - Object[] arguments = invocation.getArguments(); - String key = ((String) arguments[0]); - Boolean value = ((boolean) arguments[1]); - fakeBooleanBundle.put(key, value); - return null; - } - }).when(bundle).putBoolean(anyString(), anyBoolean()); - when(bundle.getBoolean(anyString())).thenAnswer(new Answer() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - Object[] arguments = invocation.getArguments(); - String key = ((String) arguments[0]); - return fakeBooleanBundle.get(key); - } - }); - - //mock Integer values in Bundle - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - Object[] arguments = invocation.getArguments(); - String key = ((String) arguments[0]); - Integer value = ((int) arguments[1]); - fakeIntBundle.put(key, value); - return null; - } - }).when(bundle).putInt(anyString(), anyInt()); - when(bundle.getInt(anyString())).thenAnswer(new Answer() { - @Override - public Integer answer(InvocationOnMock invocation) throws Throwable { - Object[] arguments = invocation.getArguments(); - String key = ((String) arguments[0]); - return fakeIntBundle.get(key); - } - }); - - //mock Parcelable values in Bundle - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - Object[] arguments = invocation.getArguments(); - String key = ((String) arguments[0]); - Parcelable value = ((Parcelable) arguments[1]); - fakeParcelableBundle.put(key, value); - return null; - } - }).when(bundle).putParcelable(anyString(), any(Parcelable.class)); - when(bundle.getParcelable(anyString())).thenAnswer(new Answer() { - @Override - public Parcelable answer(InvocationOnMock invocation) throws Throwable { - Object[] arguments = invocation.getArguments(); - String key = ((String) arguments[0]); - return fakeParcelableBundle.get(key); - } - }); - - //mock get - when(bundle.get(anyString())).thenAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - Object[] arguments = invocation.getArguments(); - String key = ((String) arguments[0]); - if (fakeBooleanBundle.containsKey(key)) { - return fakeBooleanBundle.get(key); - } else if (fakeIntBundle.containsKey(key)) { - return fakeIntBundle.get(key); - } else if (fakeStringBundle.containsKey(key)) { - return fakeStringBundle.get(key); - } else { - return fakeParcelableBundle.get(key); - } - } - }); - - //mock getKeySet - when(bundle.keySet()).thenAnswer(new Answer>() { - @Override - public Set answer(InvocationOnMock invocation) throws Throwable { - //this whole approach as a drawback: - //you should not add the same keys for values of different types - HashSet keys = new HashSet(); - keys.addAll(fakeBooleanBundle.keySet()); - keys.addAll(fakeIntBundle.keySet()); - keys.addAll(fakeStringBundle.keySet()); - keys.addAll(fakeParcelableBundle.keySet()); - return keys; - } - }); - - //mock containsKey - when(bundle.containsKey(anyString())).thenAnswer(new Answer() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - String key = (String) invocation.getArguments()[0]; - return fakeBooleanBundle.containsKey(key) || - fakeStringBundle.containsKey(key) || - fakeIntBundle.containsKey(key) || - fakeParcelableBundle.containsKey(key); - } - }); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - String key = (String) invocation.getArguments()[0]; - fakeBooleanBundle.remove(key); - fakeIntBundle.remove(key); - fakeParcelableBundle.remove(key); - fakeStringBundle.remove(key); - return null; - } - }).when(bundle).remove(anyString()); - - return bundle; - } - - public static Intent mockIntent() { - Intent intent = mock(Intent.class); - final String[] action = new String[1]; - final Map fakeExtras = new HashMap<>(); - final List categories = new ArrayList<>(); - - - //mock Action in intent - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - Object[] arguments = invocation.getArguments(); - action[0] = ((String) arguments[0]); - return null; - } - }).when(intent).setAction(anyString()); - when(intent.getAction()).thenAnswer(new Answer() { - @Override - public String answer(InvocationOnMock invocation) throws Throwable { - return action[0]; - } - }); - - //mock Bundle in intent extras - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - Object[] arguments = invocation.getArguments(); - String key = ((String) arguments[0]); - Bundle value = ((Bundle) arguments[1]); - fakeExtras.put(key, value); - return null; - } - }).when(intent).putExtra(anyString(), any(Bundle.class)); - when(intent.getBundleExtra(anyString())).thenAnswer(new Answer() { - @Override - public Bundle answer(InvocationOnMock invocation) throws Throwable { - Object[] arguments = invocation.getArguments(); - String key = ((String) arguments[0]); - return (Bundle) fakeExtras.get(key); - } - }); - - //mock Parcelable in intent extras - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - Object[] arguments = invocation.getArguments(); - String key = ((String) arguments[0]); - Parcelable value = ((Parcelable) arguments[1]); - fakeExtras.put(key, value); - return null; - } - }).when(intent).putExtra(anyString(), any(Parcelable.class)); - when(intent.getParcelableExtra(anyString())).thenAnswer(new Answer() { - @Override - public Parcelable answer(InvocationOnMock invocation) throws Throwable { - Object[] arguments = invocation.getArguments(); - String key = ((String) arguments[0]); - return (Parcelable) fakeExtras.get(key); - } - }); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - Object[] arguments = invocation.getArguments(); - categories.add(((String) arguments[0])); - return null; - } - }).when(intent).addCategory(anyString()); - - when(intent.getCategories()).thenAnswer(new Answer>() { - @Override - public Set answer(InvocationOnMock invocation) throws Throwable { - return new HashSet<>(categories); - } - }); - - return intent; - } public static ResultReceiver mockResultReceiver(final int expectedResultCode) { ResultReceiver resultReceiver = mock(ResultReceiver.class); @@ -403,43 +170,42 @@ public class MockHelper { return new FileHelper(new MockFileHelper(mockedFile)); } - public static void mockBase64() { - mockStatic(android.util.Base64.class); - when(android.util.Base64.encodeToString(any(), anyInt())).thenAnswer(invocation -> Arrays.toString(Base64.getEncoder().encode((byte[]) invocation.getArguments()[0]))); - } - public static RSAHelper mockRSAHelper() { return new RSAHelper(rsaKeyString -> new RSAPrivateKey() { - @Override - public BigInteger getPrivateExponent() { - return BigInteger.TEN; - } - - @Override - public String getAlgorithm() { - return "RSA"; - } - - @Override - public String getFormat() { - return null; - } - - @Override - public byte[] getEncoded() { - return new byte[0]; - } - - @Override - public BigInteger getModulus() { - return BigInteger.ONE; - } - }); + @Override + public BigInteger getPrivateExponent() { + return BigInteger.TEN; + } + @Override + public String getAlgorithm() { + return "RSA"; + } + + @Override + public String getFormat() { + return null; + } + + @Override + public byte[] getEncoded() { + return new byte[0]; + } + + @Override + public BigInteger getModulus() { + return BigInteger.ONE; + } + }); + + } + + public static BuildConfigHelper mockBuildConfigHelper(boolean useObfsvpn) { + return mockBuildConfigHelper(useObfsvpn, true); } - public static ObfsVpnHelper mockObfsVpnHelper(boolean useObfsvpn) { - return new ObfsVpnHelper(new ObfsVpnHelper.ObfsVpnHelperInterface() { + public static BuildConfigHelper mockBuildConfigHelper(boolean useObfsvpn, boolean isDefaultBitmask) { + return new BuildConfigHelper(new BuildConfigHelper.BuildConfigHelperInterface() { @Override public boolean useObfsVpn() { return useObfsvpn; @@ -469,6 +235,11 @@ public class MockHelper { public boolean useKcp() { return false; } + + @Override + public boolean isDefaultBitmask() { + return isDefaultBitmask; + } }); } @@ -476,87 +247,61 @@ public class MockHelper { return new CertificateHelper((certificate, encoding) -> mockedFingerprint); } - public static void mockPreferenceHelper(final Provider providerFromPrefs) { - // FIXME use MockSharedPreferences instead of provider - mockStatic(PreferenceHelper.class); - when(getFromPersistedProvider(anyString(), anyString())).thenAnswer(new Answer() { - @Override - public String answer(InvocationOnMock invocation) throws Throwable { - String key = (String) invocation.getArguments()[0]; - switch (key) { - case PROVIDER_PRIVATE_KEY: - return providerFromPrefs.getPrivateKey(); - case PROVIDER_VPN_CERTIFICATE: - return providerFromPrefs.getVpnCertificate(); - case Provider.KEY: - return providerFromPrefs.getDefinition().toString(); - case Provider.CA_CERT_FINGERPRINT: - return providerFromPrefs.getCaCertFingerprint(); - case Provider.CA_CERT: - return providerFromPrefs.getCaCert(); - case Provider.GEOIP_URL: - return providerFromPrefs.getGeoipUrl().toString(); - case Provider.MOTD_URL: - return providerFromPrefs.getMotdUrl().toString(); - case PROVIDER_MOTD: - return providerFromPrefs.getMotdJsonString(); + public static PreferenceHelper mockPreferenceHelper(final Provider providerFromPrefs, SharedPreferences sharedPreferences) { + PreferenceHelper preferenceHelper = new PreferenceHelper(sharedPreferences); + + sharedPreferences.edit(). + putString(PROVIDER_PRIVATE_KEY, providerFromPrefs.getPrivateKey()). + putString(PROVIDER_VPN_CERTIFICATE, providerFromPrefs.getVpnCertificate()). + putString(Provider.KEY, providerFromPrefs.getDefinitionString()). + putString(Provider.CA_CERT_FINGERPRINT, providerFromPrefs.getCaCertFingerprint()). + putString(Provider.GEOIP_URL, providerFromPrefs.getGeoipUrl().toString()). + putString(Provider.MOTD_URL, providerFromPrefs.getMotdUrl().toString()). + putString(PROVIDER_MOTD, providerFromPrefs.getMotdJsonString()). + putLong(PROVIDER_MOTD_LAST_SEEN, providerFromPrefs.getLastMotdSeen()). + putLong(PROVIDER_MOTD_LAST_UPDATED, providerFromPrefs.getLastMotdUpdate()). + putStringSet(PROVIDER_MOTD_HASHES, providerFromPrefs.getMotdLastSeenHashes()). + commit(); + + return preferenceHelper; + } - } - return null; - } - }); - when(getLongFromPersistedProvider(anyString(), anyString())).thenAnswer(new Answer() { - @Override - public Long answer(InvocationOnMock invocation) throws Throwable { - String key = (String) invocation.getArguments()[0]; - switch (key) { - case PROVIDER_MOTD_LAST_SEEN: - return providerFromPrefs.getLastMotdSeen(); - case PROVIDER_MOTD_LAST_UPDATED: - return providerFromPrefs.getLastMotdUpdate(); - } - return 0L; - } - }); - when(getStringSetFromPersistedProvider(anyString(), anyString())).thenAnswer(new Answer>() { - @Override - public Set answer(InvocationOnMock invocation) throws Throwable { - String key = (String) invocation.getArguments()[0]; - switch (key) { - case PROVIDER_MOTD_HASHES: - return providerFromPrefs.getMotdLastSeenHashes(); - } - return null; - } - }); - when(PreferenceHelper.hasKey(anyString())).then(new Answer() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - String key = (String) invocation.getArguments()[0]; - if (key!= null && key.contains(providerFromPrefs.getDomain()) && !providerFromPrefs.getDomain().isEmpty()) { - key = key.substring(0, key.indexOf(providerFromPrefs.getDomain()) - 1 /* -1 -> "." at the end */); - } - switch (key) { - case PROVIDER_PRIVATE_KEY: - return providerFromPrefs.getPrivateKey() != null; - case PROVIDER_VPN_CERTIFICATE: - return providerFromPrefs.getVpnCertificate() != null; - case Provider.KEY: - return providerFromPrefs.getDefinition().keys().hasNext(); - case Provider.CA_CERT_FINGERPRINT: - return providerFromPrefs.getCaCertFingerprint().length() > 1; - case Provider.CA_CERT: - return providerFromPrefs.getCaCert() != null; - case Provider.GEOIP_URL: - return !providerFromPrefs.getGeoipUrl().isDefault(); - case Provider.MOTD_URL: - return !providerFromPrefs.getMotdUrl().isDefault(); - case PROVIDER_MOTD: - return providerFromPrefs.getMotdJson().keys().hasNext(); - } - return false; - } - }); + public static PreferenceHelper mockPreferenceHelper(final Provider provider) { + SharedPreferences sharedPreferences = new MockSharedPreferences(); + PreferenceHelper preferenceHelper = new PreferenceHelper(sharedPreferences); + + sharedPreferences.edit(). + putString(PROVIDER_PRIVATE_KEY, provider.getPrivateKey()). + putString(PROVIDER_VPN_CERTIFICATE, provider.getVpnCertificate()). + putString(Provider.KEY, provider.getDefinitionString()). + putString(Provider.CA_CERT_FINGERPRINT, provider.getCaCertFingerprint()). + putString(Provider.GEOIP_URL, provider.getGeoipUrl().toString()). + putString(Provider.MOTD_URL, provider.getMotdUrl().toString()). + putString(PROVIDER_MOTD, provider.getMotdJsonString()). + putLong(PROVIDER_MOTD_LAST_SEEN, provider.getLastMotdSeen()). + putLong(PROVIDER_MOTD_LAST_UPDATED, provider.getLastMotdUpdate()). + putStringSet(PROVIDER_MOTD_HASHES, provider.getMotdLastSeenHashes()). + commit(); + + if (!provider.getDomain().isBlank()) { + String providerDomain = provider.getDomain(); + sharedPreferences.edit(). + putString(Provider.PROVIDER_IP + "." + providerDomain, provider.getProviderIp()). + putString(Provider.PROVIDER_API_IP + "." + providerDomain, provider.getProviderApiIp()). + putString(Provider.MAIN_URL + "." + providerDomain, provider.getMainUrlString()). + putString(Provider.GEOIP_URL + "." + providerDomain, provider.getGeoipUrl().toString()). + putString(Provider.MOTD_URL + "." + providerDomain, provider.getMotdUrl().toString()). + putString(Provider.KEY + "." + providerDomain, provider.getDefinitionString()). + putString(Provider.CA_CERT + "." + providerDomain, provider.getCaCert()). + putString(PROVIDER_EIP_DEFINITION + "." + providerDomain, provider.getEipServiceJsonString()). + putString(PROVIDER_MOTD + "." + providerDomain, provider.getMotdJsonString()). + putStringSet(PROVIDER_MOTD_HASHES + "." + providerDomain, provider.getMotdLastSeenHashes()). + putLong(PROVIDER_MOTD_LAST_SEEN + "." + providerDomain, provider.getLastMotdSeen()). + putLong(PROVIDER_MOTD_LAST_UPDATED + "." + providerDomain, provider.getLastMotdUpdate()). + commit(); + } + + return preferenceHelper; } public static void mockPreferenceHelper(MockSharedPreferences preferences) { @@ -571,53 +316,14 @@ public class MockHelper { }); } - public static void mockTorStatusObservable(@Nullable Throwable exception) throws TimeoutException, InterruptedException { - TorStatusObservable observable = TorStatusObservable.getInstance(); - mockStatic(TorStatusObservable.class); - when(TorStatusObservable.getInstance()).thenAnswer((Answer) invocation -> observable); - - when(TorStatusObservable.getBootstrapProgress()).thenReturn(0); - when(TorStatusObservable.getLastLogs()).thenReturn(new Vector<>()); - when(TorStatusObservable.getLastTorLog()).thenReturn(""); - when(TorStatusObservable.getLastSnowflakeLog()).thenReturn(""); - AtomicBoolean waitUntilSuccess = new AtomicBoolean(false); - when(TorStatusObservable.getProxyPort()).thenAnswer((Answer) invocation -> { - if (waitUntilSuccess.get()) { - return 8118; - } - return -1; - }); - when(TorStatusObservable.getStatus()).thenAnswer((Answer) invocation -> { - if (waitUntilSuccess.get()) { - return TorStatusObservable.TorStatus.ON; - } - return TorStatusObservable.TorStatus.OFF; - }); - when(TorStatusObservable.getSnowflakeStatus()).thenAnswer((Answer) invocation -> { - if (waitUntilSuccess.get()) { - return TorStatusObservable.SnowflakeStatus.STARTED; - } - return TorStatusObservable.SnowflakeStatus.STOPPED; - }); - - if (exception != null) { - when(TorStatusObservable.waitUntil(any(TorStatusObservable.StatusCondition.class), anyInt())).thenThrow(exception); - } else { - when(TorStatusObservable.waitUntil(any(TorStatusObservable.StatusCondition.class), anyInt())).thenAnswer((Answer) invocation -> { - waitUntilSuccess.set(true); - return true; - }); - } - } - public static ProviderObservable mockProviderObservable(Provider provider) { ProviderObservable observable = ProviderObservable.getInstance(); observable.updateProvider(provider); return observable; } - public static void mockProviderApiConnector(final BackendMockProvider.TestBackendErrorCase errorCase) throws IOException { - BackendMockProvider.provideBackendResponsesFor(errorCase); + public static ProviderApiConnector mockProviderApiConnector(final BackendMockProvider.TestBackendErrorCase errorCase) throws IOException { + return new ProviderApiConnector(BackendMockProvider.provideBackendResponsesFor(errorCase)); } public static OkHttpClientGenerator mockClientGenerator(boolean resolveDNS) throws UnknownHostException { @@ -643,15 +349,15 @@ public class MockHelper { JSONObject errorMessages = new JSONObject(TestSetupHelper.getInputAsString(inputStream)); - when(mockedResources.getString(eq(R.string.warning_corrupted_provider_details), anyString())). + when(mockedResources.getString(Mockito.eq(R.string.warning_corrupted_provider_details), anyString())). thenReturn(String.format(errorMessages.getString("warning_corrupted_provider_details"), "Bitmask")); when(mockedResources.getString(R.string.server_unreachable_message)). thenReturn(errorMessages.getString("server_unreachable_message")); when(mockedResources.getString(R.string.error_security_pinnedcertificate)). thenReturn(errorMessages.getString("error.security.pinnedcertificate")); - when(mockedResources.getString(eq(R.string.malformed_url), anyString())). + when(mockedResources.getString(Mockito.eq(R.string.malformed_url), anyString())). thenReturn(String.format(errorMessages.getString("malformed_url"), "Bitmask")); - when(mockedResources.getString(eq(R.string.certificate_error), anyString())). + when(mockedResources.getString(Mockito.eq(R.string.certificate_error), anyString())). thenReturn(String.format(errorMessages.getString("certificate_error"), "Bitmask")); when(mockedResources.getString(R.string.error_srp_math_error_user_message)). thenReturn(errorMessages.getString("error_srp_math_error_user_message")); @@ -667,21 +373,21 @@ public class MockHelper { thenReturn(errorMessages.getString("error_json_exception_user_message")); when(mockedResources.getString(R.string.error_no_such_algorithm_exception_user_message)). thenReturn(errorMessages.getString("error_no_such_algorithm_exception_user_message")); - when(mockedResources.getString(eq(R.string.warning_corrupted_provider_details), anyString())). + when(mockedResources.getString(Mockito.eq(R.string.warning_corrupted_provider_details), anyString())). thenReturn(String.format(errorMessages.getString("warning_corrupted_provider_details"), "Bitmask")); - when(mockedResources.getString(eq(R.string.warning_corrupted_provider_cert), anyString())). + when(mockedResources.getString(Mockito.eq(R.string.warning_corrupted_provider_cert), anyString())). thenReturn(String.format(errorMessages.getString("warning_corrupted_provider_cert"), "Bitmask")); - when(mockedResources.getString(eq(R.string.warning_expired_provider_cert), anyString())). + when(mockedResources.getString(Mockito.eq(R.string.warning_expired_provider_cert), anyString())). thenReturn(String.format(errorMessages.getString("warning_expired_provider_cert"), "Bitmask")); - when(mockedResources.getString(eq(R.string.setup_error_text), anyString())). + when(mockedResources.getString(Mockito.eq(R.string.setup_error_text), anyString())). thenReturn(String.format(errorMessages.getString("setup_error_text"), "Bitmask")); - when(mockedResources.getString(eq(R.string.setup_error_text_custom), anyString())). + when(mockedResources.getString(Mockito.eq(R.string.setup_error_text_custom), anyString())). thenReturn(String.format(errorMessages.getString("setup_error_text_custom"), "RiseupVPN")); when(mockedResources.getString(R.string.app_name)). thenReturn("Bitmask"); - when(mockedResources.getString(eq(R.string.error_tor_timeout), anyString())). + when(mockedResources.getString(Mockito.eq(R.string.error_tor_timeout), anyString())). thenReturn(String.format(errorMessages.getString("error_tor_timeout"), "Bitmask")); - when(mockedResources.getString(eq(R.string.error_network_connection), anyString())). + when(mockedResources.getString(Mockito.eq(R.string.error_network_connection), anyString())). thenReturn(String.format(errorMessages.getString("error_network_connection"), "Bitmask")); return mockedResources; } -- cgit v1.2.3