From ed8a28962675b540389fc9280ab1122613230fa8 Mon Sep 17 00:00:00 2001 From: cyBerta Date: Thu, 25 Jan 2024 01:26:05 +0100 Subject: fix ProviderManagerTest, adapt InputStreamHelper and Filehelper to be mockable by injection --- .../leap/bitmaskclient/testutils/MockHelper.java | 74 +++++++++------------- 1 file changed, 29 insertions(+), 45 deletions(-) (limited to 'app/src/test/java/se/leap/bitmaskclient/testutils') 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 1f8a18f4..01af9591 100644 --- a/app/src/test/java/se/leap/bitmaskclient/testutils/MockHelper.java +++ b/app/src/test/java/se/leap/bitmaskclient/testutils/MockHelper.java @@ -314,39 +314,6 @@ public class MockHelper { return intent; } - public static void mockTextUtils() { - mockStatic(TextUtils.class); - - when(TextUtils.equals(any(CharSequence.class), any(CharSequence.class))).thenAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - CharSequence a = (CharSequence) invocation.getArguments()[0]; - CharSequence b = (CharSequence) invocation.getArguments()[1]; - if (a == b) return true; - int length; - if (a != null && b != null && (length = a.length()) == b.length()) { - if (a instanceof String && b instanceof String) { - return a.equals(b); - } else { - for (int i = 0; i < length; i++) { - if (a.charAt(i) != b.charAt(i)) return false; - } - return true; - } - } - return false; - } - }); - - when(TextUtils.isEmpty(any(CharSequence.class))).thenAnswer(new Answer() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - CharSequence param = (CharSequence) invocation.getArguments()[0]; - return param == null || param.length() == 0; - } - }); - } - public static ResultReceiver mockResultReceiver(final int expectedResultCode) { ResultReceiver resultReceiver = mock(ResultReceiver.class); doAnswer(new Answer() { @@ -398,23 +365,41 @@ public class MockHelper { return resultReceiver; } - public static void mockInputStreamHelper() throws FileNotFoundException { - mockStatic(InputStreamHelper.class); - when(InputStreamHelper.loadInputStreamAsString(any(InputStream.class))).thenCallRealMethod(); - when(InputStreamHelper.getInputStreamFrom(anyString())).thenAnswer(new Answer() { + + public static InputStreamHelper mockInputStreamHelper() { + return new InputStreamHelper(new InputStreamHelper.InputStreamHelperInterface() { @Override - public InputStream answer(InvocationOnMock invocation) throws Throwable { - String filename = (String) invocation.getArguments()[0]; - return getClass().getClassLoader().getResourceAsStream(filename); + public InputStream getInputStreamFrom(String filePath) { + return getClass().getClassLoader().getResourceAsStream(filePath); } }); - when(InputStreamHelper.inputStreamToJson(any(InputStream.class))).thenCallRealMethod(); + } + + public static class MockFileHelper implements FileHelper.FileHelperInterface { + private final File file; + private int persistFileCounter = 0; + public MockFileHelper(File file) { + this.file = file; + } + + @Override + public File createFile(File dir, String fileName) { + return file; + } + + @Override + public void persistFile(File file, String content) throws IOException { + persistFileCounter++; + } + + public int getPersistFileCounter() { + return persistFileCounter; + } } - public static void mockFileHelper(final File mockedFile) throws FileNotFoundException { - mockStatic(FileHelper.class); - when(createFile(any(File.class), anyString())).thenReturn(mockedFile); + public static FileHelper mockFileHelper(final File mockedFile) throws FileNotFoundException { + return new FileHelper(new MockFileHelper(mockedFile)); } public static void mockBase64() { @@ -459,7 +444,6 @@ public class MockHelper { when(ConfigHelper.checkErroneousDownload(anyString())).thenCallRealMethod(); when(ConfigHelper.parseX509CertificatesFromString(anyString())).thenCallRealMethod(); when(ConfigHelper.getProviderFormattedString(any(Resources.class), anyInt())).thenCallRealMethod(); - when(ConfigHelper.timezoneDistance(anyInt(), anyInt())).thenCallRealMethod(); when(ConfigHelper.isIPv4(anyString())).thenCallRealMethod(); when(ConfigHelper.isDefaultBitmask()).thenReturn(true); when(ConfigHelper.getDomainFromMainURL(anyString())).thenCallRealMethod(); -- cgit v1.2.3 From 23278cefe308043228c9da9b4937d27888146206 Mon Sep 17 00:00:00 2001 From: cyBerta Date: Thu, 25 Jan 2024 02:32:55 +0100 Subject: fix VpnConfigGenerator Test, move RSAHelper and ObfsVpnHelper out of ConfigHelper, use injection pattern for these helpers --- .../leap/bitmaskclient/testutils/MockHelper.java | 64 +++++++++++++++++----- 1 file changed, 49 insertions(+), 15 deletions(-) (limited to 'app/src/test/java/se/leap/bitmaskclient/testutils') 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 01af9591..daa67282 100644 --- a/app/src/test/java/se/leap/bitmaskclient/testutils/MockHelper.java +++ b/app/src/test/java/se/leap/bitmaskclient/testutils/MockHelper.java @@ -72,7 +72,9 @@ import se.leap.bitmaskclient.base.models.ProviderObservable; import se.leap.bitmaskclient.base.utils.ConfigHelper; import se.leap.bitmaskclient.base.utils.FileHelper; import se.leap.bitmaskclient.base.utils.InputStreamHelper; +import se.leap.bitmaskclient.base.utils.ObfsVpnHelper; import se.leap.bitmaskclient.base.utils.PreferenceHelper; +import se.leap.bitmaskclient.base.utils.RSAHelper; import se.leap.bitmaskclient.providersetup.connectivity.DnsResolver; import se.leap.bitmaskclient.providersetup.connectivity.OkHttpClientGenerator; import se.leap.bitmaskclient.testutils.BackendMockResponses.BackendMockProvider; @@ -407,33 +409,66 @@ public class MockHelper { when(android.util.Base64.encodeToString(any(), anyInt())).thenAnswer(invocation -> Arrays.toString(Base64.getEncoder().encode((byte[]) invocation.getArguments()[0]))); } - public static void mockRSAHelper() { - mockStatic(ConfigHelper.RSAHelper.class); + 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; + } + }); - when(ConfigHelper.RSAHelper.parseRsaKeyFromString(anyString())).thenReturn(new RSAPrivateKey() { + } + + public static ObfsVpnHelper mockObfsVpnHelper(boolean useObfsvpn) { + return new ObfsVpnHelper(new ObfsVpnHelper.ObfsVpnHelperInterface() { @Override - public BigInteger getPrivateExponent() { - return BigInteger.TEN; + public boolean useObfsVpn() { + return useObfsvpn; } @Override - public String getAlgorithm() { - return "RSA"; + public boolean hasObfuscationPinningDefaults() { + return false; } @Override - public String getFormat() { + public String obfsvpnIP() { return null; } @Override - public byte[] getEncoded() { - return new byte[0]; + public String obfsvpnPort() { + return null; } @Override - public BigInteger getModulus() { - return BigInteger.ONE; + public String obfsvpnCert() { + return null; + } + + @Override + public boolean useKcp() { + return false; } }); } @@ -583,11 +618,10 @@ public class MockHelper { } } - public static void mockProviderObservable(Provider provider) { + public static ProviderObservable mockProviderObservable(Provider provider) { ProviderObservable observable = ProviderObservable.getInstance(); observable.updateProvider(provider); - mockStatic(ProviderObservable.class); - when(ProviderObservable.getInstance()).thenAnswer((Answer) invocation -> observable); + return observable; } public static void mockProviderApiConnector(final BackendMockProvider.TestBackendErrorCase errorCase) throws IOException { -- cgit v1.2.3 From b85dc1b2ea68ab7ca7e11ab545bb88f4dbb59bdb Mon Sep 17 00:00:00 2001 From: cyBerta Date: Thu, 25 Jan 2024 03:01:21 +0100 Subject: fix VpnCertificateValidatorTest, extract CertificateHelper (returns a fingerprint for a x509 cert) from ConfigHelper --- .../java/se/leap/bitmaskclient/testutils/MockHelper.java | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) (limited to 'app/src/test/java/se/leap/bitmaskclient/testutils') 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 daa67282..869e3190 100644 --- a/app/src/test/java/se/leap/bitmaskclient/testutils/MockHelper.java +++ b/app/src/test/java/se/leap/bitmaskclient/testutils/MockHelper.java @@ -50,7 +50,6 @@ import java.math.BigInteger; import java.net.UnknownHostException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; import java.security.interfaces.RSAPrivateKey; import java.util.ArrayList; import java.util.Arrays; @@ -69,7 +68,7 @@ import okhttp3.OkHttpClient; import se.leap.bitmaskclient.R; import se.leap.bitmaskclient.base.models.Provider; import se.leap.bitmaskclient.base.models.ProviderObservable; -import se.leap.bitmaskclient.base.utils.ConfigHelper; +import se.leap.bitmaskclient.base.utils.CertificateHelper; import se.leap.bitmaskclient.base.utils.FileHelper; import se.leap.bitmaskclient.base.utils.InputStreamHelper; import se.leap.bitmaskclient.base.utils.ObfsVpnHelper; @@ -473,15 +472,8 @@ public class MockHelper { }); } - public static void mockConfigHelper(String mockedFingerprint) throws CertificateEncodingException, NoSuchAlgorithmException { - mockStatic(ConfigHelper.class); - when(ConfigHelper.getFingerprintFromCertificate(any(X509Certificate.class), anyString())).thenReturn(mockedFingerprint); - when(ConfigHelper.checkErroneousDownload(anyString())).thenCallRealMethod(); - when(ConfigHelper.parseX509CertificatesFromString(anyString())).thenCallRealMethod(); - when(ConfigHelper.getProviderFormattedString(any(Resources.class), anyInt())).thenCallRealMethod(); - when(ConfigHelper.isIPv4(anyString())).thenCallRealMethod(); - when(ConfigHelper.isDefaultBitmask()).thenReturn(true); - when(ConfigHelper.getDomainFromMainURL(anyString())).thenCallRealMethod(); + public static CertificateHelper mockCertificateHelper(String mockedFingerprint) { + return new CertificateHelper((certificate, encoding) -> mockedFingerprint); } public static void mockPreferenceHelper(final Provider providerFromPrefs) { -- cgit v1.2.3 From b6c2c7c8ffbcf87110c33e179f1506285dffd949 Mon Sep 17 00:00:00 2001 From: cyBerta Date: Thu, 25 Jan 2024 23:17:16 +0100 Subject: rename ObfsvpnHelper to BuildConfigHelper, adding other BuildConfig properties there --- app/src/test/java/se/leap/bitmaskclient/testutils/MockHelper.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'app/src/test/java/se/leap/bitmaskclient/testutils') 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 869e3190..33e2c056 100644 --- a/app/src/test/java/se/leap/bitmaskclient/testutils/MockHelper.java +++ b/app/src/test/java/se/leap/bitmaskclient/testutils/MockHelper.java @@ -71,7 +71,7 @@ import se.leap.bitmaskclient.base.models.ProviderObservable; import se.leap.bitmaskclient.base.utils.CertificateHelper; import se.leap.bitmaskclient.base.utils.FileHelper; import se.leap.bitmaskclient.base.utils.InputStreamHelper; -import se.leap.bitmaskclient.base.utils.ObfsVpnHelper; +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.connectivity.DnsResolver; -- cgit v1.2.3 From 8b3a140602108f66d5183623a7788dc35c121e59 Mon Sep 17 00:00:00 2001 From: cyBerta Date: Thu, 25 Jan 2024 23:19:22 +0100 Subject: improve MockSharedPreferences, adding implementations for put/get Long and put/get StringSet --- .../bitmaskclient/testutils/MockSharedPreferences.java | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) (limited to 'app/src/test/java/se/leap/bitmaskclient/testutils') diff --git a/app/src/test/java/se/leap/bitmaskclient/testutils/MockSharedPreferences.java b/app/src/test/java/se/leap/bitmaskclient/testutils/MockSharedPreferences.java index 4fabc2c0..30ced782 100644 --- a/app/src/test/java/se/leap/bitmaskclient/testutils/MockSharedPreferences.java +++ b/app/src/test/java/se/leap/bitmaskclient/testutils/MockSharedPreferences.java @@ -33,6 +33,8 @@ public class MockSharedPreferences implements SharedPreferences { HashMap mockedStringPrefs = new HashMap<>(); HashMap mockedIntPrefs = new HashMap<>(); HashMap mockedBooleanPrefs = new HashMap<>(); + HashMap mockedLongPrefs = new HashMap<>(); + HashMap> mockedStringSetPrefs = new HashMap<>(); @Override public Map getAll() { @@ -49,7 +51,7 @@ public class MockSharedPreferences implements SharedPreferences { @Nullable @Override public Set getStringSet(String key, @Nullable Set defValues) { - return new HashSet<>(); + return mockedStringSetPrefs.getOrDefault(key, new HashSet<>()); } @Override @@ -60,7 +62,7 @@ public class MockSharedPreferences implements SharedPreferences { @Override public long getLong(String key, long defValue) { - return 0; + return mockedLongPrefs.getOrDefault(key, defValue); } @Override @@ -78,7 +80,9 @@ public class MockSharedPreferences implements SharedPreferences { public boolean contains(String key) { return mockedStringPrefs.containsKey(key) || mockedBooleanPrefs.containsKey(key) || - mockedIntPrefs.containsKey(key); + mockedIntPrefs.containsKey(key) || + mockedStringSetPrefs.containsKey(key) || + mockedLongPrefs.containsKey(key); } @Override @@ -87,6 +91,8 @@ public class MockSharedPreferences implements SharedPreferences { private HashMap tempStrings = new HashMap<>(mockedStringPrefs); private HashMap tempIntegers = new HashMap<>(mockedIntPrefs); private HashMap tempBoolean = new HashMap<>(mockedBooleanPrefs); + private HashMap tempLongs = new HashMap<>(mockedLongPrefs); + private HashMap> tempStringSets = new HashMap<>(mockedStringSetPrefs); @Override public Editor putString(String key, @Nullable String value) { @@ -96,7 +102,8 @@ public class MockSharedPreferences implements SharedPreferences { @Override public Editor putStringSet(String key, @Nullable Set values) { - return null; + tempStringSets.put(key, values); + return this; } @Override @@ -107,7 +114,8 @@ public class MockSharedPreferences implements SharedPreferences { @Override public Editor putLong(String key, long value) { - return null; + tempLongs.put(key, value); + return this; } @Override -- cgit v1.2.3 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 --- .../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 +++++---------------- 12 files changed, 453 insertions(+), 1026 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/leap/bitmaskclient/testutils') 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