diff options
Diffstat (limited to 'app/src/test/java/se')
22 files changed, 994 insertions, 1890 deletions
diff --git a/app/src/test/java/se/leap/bitmaskclient/base/models/ProviderTest.java b/app/src/test/java/se/leap/bitmaskclient/base/models/ProviderTest.java index 8bff690b..4fcc6bac 100644 --- a/app/src/test/java/se/leap/bitmaskclient/base/models/ProviderTest.java +++ b/app/src/test/java/se/leap/bitmaskclient/base/models/ProviderTest.java @@ -1,34 +1,26 @@ package se.leap.bitmaskclient.base.models; import static junit.framework.Assert.assertFalse; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; -import static org.powermock.api.mockito.PowerMockito.mockStatic; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import java.util.HashSet; -import java.util.Set; - -import se.leap.bitmaskclient.base.utils.ConfigHelper; +import se.leap.bitmaskclient.base.utils.BuildConfigHelper; +import se.leap.bitmaskclient.testutils.MockHelper; import se.leap.bitmaskclient.testutils.TestSetupHelper; /** * Created by cyberta on 12.02.18. */ -@RunWith(PowerMockRunner.class) -@PrepareForTest({ConfigHelper.ObfsVpnHelper.class}) public class ProviderTest { @Before public void setup() { - mockStatic(ConfigHelper.ObfsVpnHelper.class); - when(ConfigHelper.ObfsVpnHelper.useObfsVpn()).thenReturn(false); + BuildConfigHelper buildConfigHelper = MockHelper.mockBuildConfigHelper(false); } @Test @@ -61,14 +53,12 @@ public class ProviderTest { Provider p2 = TestSetupHelper.getConfiguredProvider(); p2.setMainUrl("http://somethingsdiffer.org"); Provider p3 = new Provider("https://anotherprovider.net"); + Provider p4 = TestSetupHelper.getConfiguredProvider(); - Set<Provider> defaultProviders = new HashSet<>(); - defaultProviders.add(p1); - defaultProviders.add(p2); + assertEquals(p1, p4); + assertNotEquals(p1, p2); + assertNotEquals(p1, p3); - assertTrue(defaultProviders.contains(p1)); - assertTrue(defaultProviders.contains(p2)); - assertFalse(defaultProviders.contains(p3)); } @Test @@ -129,8 +119,6 @@ public class ProviderTest { @Test public void testSupportsPluggableTransports_Obfs4Kcp_noObsvpn_returnsFalse() throws Exception { - when(ConfigHelper.ObfsVpnHelper.useObfsVpn()).thenReturn(false); - Provider p1 = TestSetupHelper.getProvider( "https://pt.demo.bitmask.net", null, @@ -145,7 +133,7 @@ public class ProviderTest { @Test public void testSupportsPluggableTransports_Obfs4Kcp_obsvpn_returnsTrue() throws Exception { - when(ConfigHelper.ObfsVpnHelper.useObfsVpn()).thenReturn(true); + BuildConfigHelper helper = MockHelper.mockBuildConfigHelper(true); Provider p1 = TestSetupHelper.getProvider( "https://pt.demo.bitmask.net", diff --git a/app/src/test/java/se/leap/bitmaskclient/eip/GatewaySelectorTest.java b/app/src/test/java/se/leap/bitmaskclient/eip/GatewaySelectorTest.java index 74762813..0175745e 100644 --- a/app/src/test/java/se/leap/bitmaskclient/eip/GatewaySelectorTest.java +++ b/app/src/test/java/se/leap/bitmaskclient/eip/GatewaySelectorTest.java @@ -1,8 +1,10 @@ package se.leap.bitmaskclient.eip; -import android.preference.PreferenceManager; -import android.text.TextUtils; -import android.util.Log; +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertTrue; +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.testutils.TestSetupHelper.getInputAsString; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; @@ -14,35 +16,22 @@ import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.modules.junit4.PowerMockRunnerDelegate; import java.io.IOException; import java.util.ArrayList; +import java.util.List; +import java.util.Vector; import de.blinkt.openvpn.core.ConfigParser; import se.leap.bitmaskclient.base.models.Provider; -import se.leap.bitmaskclient.base.utils.ConfigHelper; import se.leap.bitmaskclient.base.utils.PreferenceHelper; +import se.leap.bitmaskclient.base.utils.TimezoneHelper; import se.leap.bitmaskclient.testutils.MockSharedPreferences; -import static junit.framework.Assert.assertEquals; -import static junit.framework.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; -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.testutils.MockHelper.mockTextUtils; -import static se.leap.bitmaskclient.testutils.TestSetupHelper.getInputAsString; - /** * Created by cyberta on 18.12.18. */ -@RunWith(PowerMockRunner.class) -@PowerMockRunnerDelegate(DataProviderRunner.class) -@PrepareForTest({ConfigHelper.class, TextUtils.class}) +@RunWith(DataProviderRunner.class) public class GatewaySelectorTest { public static final String TAG = GatewaySelectorTest.class.getSimpleName(); @@ -72,23 +61,26 @@ public class GatewaySelectorTest { PreferenceHelper preferenceHelper; - GatewaySelector gatewaySelector; JSONObject eipDefinition; - ArrayList<Gateway> gatewayList = new ArrayList<>(); - @Before - public void setup() throws IOException, JSONException, ConfigParser.ConfigParseError { - mockStatic(ConfigHelper.class); - when(ConfigHelper.timezoneDistance(anyInt(), anyInt())).thenCallRealMethod(); - mockTextUtils(); + public void setup() throws IOException, JSONException { preferenceHelper = new PreferenceHelper(new MockSharedPreferences()); eipDefinition = new JSONObject(getInputAsString(getClass().getClassLoader().getResourceAsStream("eip-service-four-gateways.json"))); - JSONArray gateways = eipDefinition.getJSONArray("gateways"); - for (int i = 0; i < gateways.length(); i++) { - JSONObject gw = gateways.getJSONObject(i); - JSONObject secrets = secretsConfiguration(); - Gateway aux = new Gateway(eipDefinition, secrets, gw, null); - gatewayList.add(aux); + } + + private List<Gateway> getGateways() { + try { + Vector<Gateway> gatewayList = new Vector<>(); + JSONArray gateways = eipDefinition.getJSONArray("gateways"); + for (int i = 0; i < gateways.length(); i++) { + JSONObject gw = gateways.getJSONObject(i); + JSONObject secrets = secretsConfiguration(); + Gateway aux = new Gateway(eipDefinition, secrets, gw, null); + gatewayList.add(aux); + } + return gatewayList; + } catch (JSONException | IOException | ConfigParser.ConfigParseError e) { + return new ArrayList<>(); } } @@ -149,24 +141,24 @@ public class GatewaySelectorTest { @Test @UseDataProvider("dataProviderTimezones") public void testSelect(int timezone, String expected) { - when(ConfigHelper.getCurrentTimezone()).thenReturn(timezone); - gatewaySelector = new GatewaySelector(gatewayList); + TimezoneHelper timezoneHelper = new TimezoneHelper(() -> timezone); + GatewaySelector gatewaySelector = new GatewaySelector(getGateways()); assertEquals(expected, gatewaySelector.select().getName()); } @Test @UseDataProvider("dataProviderSameDistanceTimezones") public void testSelectSameTimezoneDistance(int timezone, String expected1, String expected2) { - when(ConfigHelper.getCurrentTimezone()).thenReturn(timezone); - gatewaySelector = new GatewaySelector(gatewayList); + TimezoneHelper timezoneHelper = new TimezoneHelper(() -> timezone); + GatewaySelector gatewaySelector = new GatewaySelector(getGateways()); assertTrue(gatewaySelector.select().getName().equals(expected1) || gatewaySelector.select().getName().equals(expected2)); } @Test @UseDataProvider("dataProviderSameDistanceTimezones") public void testNClostest_SameTimezoneDistance_chooseGatewayWithSameDistance(int timezone, String expected1, String expected2) { - when(ConfigHelper.getCurrentTimezone()).thenReturn(timezone); - gatewaySelector = new GatewaySelector(gatewayList); + TimezoneHelper timezoneHelper = new TimezoneHelper(() -> timezone); + GatewaySelector gatewaySelector = new GatewaySelector(getGateways()); ArrayList<String> gateways = new ArrayList<>(); gateways.add(gatewaySelector.select(0).getName()); gateways.add(gatewaySelector.select(1).getName()); @@ -177,8 +169,8 @@ public class GatewaySelectorTest { @Test public void testNClostest_OneTimezonePerSet_choseSecondClosestTimezone() { - when(ConfigHelper.getCurrentTimezone()).thenReturn(-4); - gatewaySelector = new GatewaySelector(gatewayList); + TimezoneHelper timezoneHelper = new TimezoneHelper(() -> -4); + GatewaySelector gatewaySelector = new GatewaySelector(getGateways()); assertTrue("Frankfurt".equals(gatewaySelector.select(1).getName())); } diff --git a/app/src/test/java/se/leap/bitmaskclient/eip/GatewaysManagerTest.java b/app/src/test/java/se/leap/bitmaskclient/eip/GatewaysManagerTest.java index 86373ff6..d66fedbe 100644 --- a/app/src/test/java/se/leap/bitmaskclient/eip/GatewaysManagerTest.java +++ b/app/src/test/java/se/leap/bitmaskclient/eip/GatewaysManagerTest.java @@ -1,19 +1,30 @@ package se.leap.bitmaskclient.eip; +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertNull; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static de.blinkt.openvpn.core.connection.Connection.TransportType.OBFS4; +import static de.blinkt.openvpn.core.connection.Connection.TransportType.OPENVPN; +import static se.leap.bitmaskclient.base.models.Constants.ALLOW_EXPERIMENTAL_TRANSPORTS; +import static se.leap.bitmaskclient.base.models.Constants.GATEWAYS; +import static se.leap.bitmaskclient.base.models.Constants.PREFERRED_CITY; +import static se.leap.bitmaskclient.base.models.Constants.PROVIDER_EIP_DEFINITION; +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.models.Constants.USE_BRIDGES; +import static se.leap.bitmaskclient.base.models.Provider.CA_CERT; +import static se.leap.bitmaskclient.testutils.TestSetupHelper.getProvider; + import android.content.Context; import android.content.SharedPreferences; -import android.text.TextUtils; -import android.util.Log; 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.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException; import java.util.ArrayList; @@ -21,42 +32,17 @@ import java.util.List; import de.blinkt.openvpn.VpnProfile; import de.blinkt.openvpn.core.ConfigParser; -import de.blinkt.openvpn.core.connection.Connection; import se.leap.bitmaskclient.base.models.Location; -import se.leap.bitmaskclient.base.models.Pair; 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.PreferenceHelper; -import se.leap.bitmaskclient.testutils.MockHelper; +import se.leap.bitmaskclient.base.utils.TimezoneHelper; import se.leap.bitmaskclient.testutils.MockSharedPreferences; import se.leap.bitmaskclient.testutils.TestSetupHelper; -import static de.blinkt.openvpn.core.connection.Connection.TransportType.OBFS4; -import static de.blinkt.openvpn.core.connection.Connection.TransportType.OPENVPN; -import static junit.framework.Assert.assertEquals; -import static junit.framework.Assert.assertNull; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.when; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static se.leap.bitmaskclient.base.models.Constants.GATEWAYS; -import static se.leap.bitmaskclient.base.models.Constants.PROVIDER_EIP_DEFINITION; -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.models.Constants.USE_BRIDGES; -import static se.leap.bitmaskclient.base.models.Provider.CA_CERT; -import static se.leap.bitmaskclient.testutils.MockHelper.mockTextUtils; -import static se.leap.bitmaskclient.testutils.TestSetupHelper.getProvider; - /** * Created by cyberta on 09.10.17. */ -@RunWith(PowerMockRunner.class) -@PrepareForTest({ProviderObservable.class, Log.class, PreferenceHelper.class, ConfigHelper.class, TextUtils.class}) public class GatewaysManagerTest { @Mock(answer = Answers.RETURNS_DEEP_STUBS) @@ -65,17 +51,15 @@ public class GatewaysManagerTest { private SharedPreferences sharedPreferences; private JSONObject secrets; + private TimezoneHelper timezoneHelper; + ProviderObservable providerObservable; + @Before public void setUp() throws IOException, JSONException { - mockStatic(Log.class); - mockStatic(ConfigHelper.class); - mockTextUtils(); - when(ConfigHelper.getCurrentTimezone()).thenReturn(-1); - when(ConfigHelper.stringEqual(anyString(), anyString())).thenCallRealMethod(); - when(ConfigHelper.getConnectionQualityFromTimezoneDistance(anyInt())).thenCallRealMethod(); - when(ConfigHelper.isIPv4(anyString())).thenCallRealMethod(); - when(ConfigHelper.timezoneDistance(anyInt(), anyInt())).thenCallRealMethod(); + timezoneHelper = new TimezoneHelper(() -> -1); + providerObservable = ProviderObservable.getInstance(); + secrets = new JSONObject(getJsonStringFor("secrets.json")); sharedPreferences = new MockSharedPreferences(); sharedPreferences.edit(). @@ -83,22 +67,20 @@ public class GatewaysManagerTest { putString(CA_CERT, secrets.getString(CA_CERT)). putString(PROVIDER_VPN_CERTIFICATE, secrets.getString(PROVIDER_VPN_CERTIFICATE)) .commit(); - mockStatic(PreferenceHelper.class); PreferenceHelper preferenceHelper = new PreferenceHelper(sharedPreferences); } @Test public void testGatewayManagerFromCurrentProvider_noProvider_noGateways() { - MockHelper.mockProviderObservable(null); + providerObservable.updateProvider(null); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals(0, gatewaysManager.size()); } @Test public void testGatewayManagerFromCurrentProvider_threeGateways() { - Provider provider = getProvider(null, null, null, null,null, null, "ptdemo_three_mixed_gateways.json", null); - MockHelper.mockProviderObservable(provider); + providerObservable.updateProvider(getProvider(null, null, null, null,null, null, "ptdemo_three_mixed_gateways.json", null)); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals(3, gatewaysManager.size()); } @@ -108,7 +90,7 @@ public class GatewaysManagerTest { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_three_mixed_gateways.json", null); JSONObject eipServiceJson = provider.getEipServiceJson(); JSONObject gateway1 = eipServiceJson.getJSONArray(GATEWAYS).getJSONObject(0); - MockHelper.mockProviderObservable(provider); + providerObservable.updateProvider(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); VpnConfigGenerator.Configuration configuration = new VpnConfigGenerator.Configuration(); @@ -125,7 +107,7 @@ public class GatewaysManagerTest { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_three_mixed_gateways.json", null); JSONObject eipServiceJson = provider.getEipServiceJson(); JSONObject gateway1 = eipServiceJson.getJSONArray(GATEWAYS).getJSONObject(0); - MockHelper.mockProviderObservable(provider); + providerObservable.updateProvider(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); VpnConfigGenerator.Configuration configuration = new VpnConfigGenerator.Configuration(); @@ -142,7 +124,7 @@ public class GatewaysManagerTest { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_three_mixed_gateways.json", "ptdemo_three_mixed_gateways.geoip.json"); JSONObject eipServiceJson = provider.getEipServiceJson(); JSONObject gateway1 = eipServiceJson.getJSONArray(GATEWAYS).getJSONObject(0); - MockHelper.mockProviderObservable(provider); + providerObservable.updateProvider(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); VpnConfigGenerator.Configuration configuration = new VpnConfigGenerator.Configuration(); @@ -159,7 +141,7 @@ public class GatewaysManagerTest { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_three_mixed_gateways.json", "ptdemo_three_mixed_gateways.geoip.json"); JSONObject eipServiceJson = provider.getEipServiceJson(); JSONObject gateway1 = eipServiceJson.getJSONArray(GATEWAYS).getJSONObject(0); - MockHelper.mockProviderObservable(provider); + providerObservable.updateProvider(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); VpnConfigGenerator.Configuration configuration = new VpnConfigGenerator.Configuration(); @@ -176,7 +158,7 @@ public class GatewaysManagerTest { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_three_mixed_gateways.json", null); JSONObject eipServiceJson = provider.getEipServiceJson(); JSONObject gateway1 = eipServiceJson.getJSONArray(GATEWAYS).getJSONObject(0); - MockHelper.mockProviderObservable(provider); + providerObservable.updateProvider(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); VpnConfigGenerator.Configuration configuration = new VpnConfigGenerator.Configuration(); @@ -193,7 +175,7 @@ public class GatewaysManagerTest { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_three_mixed_gateways.json", null); JSONObject eipServiceJson = provider.getEipServiceJson(); JSONObject gateway1 = eipServiceJson.getJSONArray(GATEWAYS).getJSONObject(1); - MockHelper.mockProviderObservable(provider); + providerObservable.updateProvider(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); VpnConfigGenerator.Configuration configuration = new VpnConfigGenerator.Configuration(); @@ -209,9 +191,8 @@ public class GatewaysManagerTest { public void TestSelectN_selectFirstObfs4Connection_returnThirdGateway() { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_two_openvpn_one_pt_gateways.json", null); - MockHelper.mockProviderObservable(provider); - mockStatic(PreferenceHelper.class); - when(PreferenceHelper.getUseBridges()).thenReturn(true); + providerObservable.updateProvider(provider); + sharedPreferences.edit().putBoolean(USE_BRIDGES, true).commit(); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals("37.12.247.10", gatewaysManager.select(0).gateway.getRemoteIP()); @@ -221,10 +202,11 @@ public class GatewaysManagerTest { public void TestSelectN_select_includeExperimentalTransport_DecoupledPortHoppingGW() { Provider provider = getProvider(null, null, null, null, null, null, "decoupled_pt_portHopping.eip-service.json", null); - MockHelper.mockProviderObservable(provider); - mockStatic(PreferenceHelper.class); - when(PreferenceHelper.getUseBridges()).thenReturn(true); - when(PreferenceHelper.allowExperimentalTransports()).thenReturn(true); + providerObservable.updateProvider(provider); + sharedPreferences.edit(). + putBoolean(USE_BRIDGES, true). + putBoolean(ALLOW_EXPERIMENTAL_TRANSPORTS, true). + commit(); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); ArrayList<String> hosts = new ArrayList<>(); hosts.add(gatewaysManager.select(0).gateway.getHost()); @@ -239,10 +221,11 @@ public class GatewaysManagerTest { public void TestSelectN_select_includeExperimentalTransport_DecoupledPortAndIPHoppingGW() { Provider provider = getProvider(null, null, null, null, null, null, "decoupled_pt.eip-service.json", null); - MockHelper.mockProviderObservable(provider); - mockStatic(PreferenceHelper.class); - when(PreferenceHelper.getUseBridges()).thenReturn(true); - when(PreferenceHelper.allowExperimentalTransports()).thenReturn(true); + providerObservable.updateProvider(provider); + sharedPreferences.edit(). + putBoolean(USE_BRIDGES, true). + putBoolean(ALLOW_EXPERIMENTAL_TRANSPORTS, true). + commit(); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); ArrayList<String> hosts = new ArrayList<>(); @@ -256,10 +239,11 @@ public class GatewaysManagerTest { public void TestSelectN_select_excludeExperimentalTransport_DecoupledPortHoppingGW() { Provider provider = getProvider(null, null, null, null, null, null, "decoupled_pt_portHopping.eip-service.json", null); - MockHelper.mockProviderObservable(provider); - mockStatic(PreferenceHelper.class); - when(PreferenceHelper.getUseBridges()).thenReturn(true); - when(PreferenceHelper.allowExperimentalTransports()).thenReturn(false); + providerObservable.updateProvider(provider); + sharedPreferences.edit(). + putBoolean(USE_BRIDGES, true). + putBoolean(ALLOW_EXPERIMENTAL_TRANSPORTS, false). + commit(); for (int i = 0; i < 1000; i++) { GatewaysManager gatewaysManager = new GatewaysManager(mockContext); @@ -271,10 +255,11 @@ public class GatewaysManagerTest { public void TestSelectN_select_excludeExperimentalTransport_DecoupledPortAndIPHoppingGW() { Provider provider = getProvider(null, null, null, null, null, null, "decoupled_pt.eip-service.json", null); - MockHelper.mockProviderObservable(provider); - mockStatic(PreferenceHelper.class); - when(PreferenceHelper.getUseBridges()).thenReturn(true); - when(PreferenceHelper.allowExperimentalTransports()).thenReturn(false); + providerObservable.updateProvider(provider); + sharedPreferences.edit(). + putBoolean(USE_BRIDGES, true). + putBoolean(ALLOW_EXPERIMENTAL_TRANSPORTS, false). + commit(); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals("bridge-nyc1-01.bitmask-dev.leapvpn.net", gatewaysManager.select(0).gateway.getHost()); @@ -285,10 +270,11 @@ public class GatewaysManagerTest { public void TestSelectN_select_excludeExperimentalTransport_InGatewayHoppingPTBridge() { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_obfs4hop_tcp_gateways.json", null); - MockHelper.mockProviderObservable(provider); - mockStatic(PreferenceHelper.class); - when(PreferenceHelper.getUseBridges()).thenReturn(true); - when(PreferenceHelper.allowExperimentalTransports()).thenReturn(false); + providerObservable.updateProvider(provider); + sharedPreferences.edit(). + putBoolean(USE_BRIDGES, true). + putBoolean(ALLOW_EXPERIMENTAL_TRANSPORTS, false). + commit(); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); ArrayList<String> hosts = new ArrayList<>(); @@ -303,10 +289,7 @@ public class GatewaysManagerTest { public void testSelectN_selectFromPresortedGateways_returnsGatewaysInPresortedOrder() { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_three_mixed_gateways.json", "ptdemo_three_mixed_gateways.geoip.json"); - MockHelper.mockProviderObservable(provider); - //use openvpn, not pluggable transports - mockStatic(PreferenceHelper.class); - when(PreferenceHelper.getUseBridges()).thenReturn(false); + providerObservable.updateProvider(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals("manila.bitmask.net", gatewaysManager.select(0).gateway.getHost()); @@ -318,10 +301,11 @@ public class GatewaysManagerTest { public void testSelectN_selectObfs4FromPresortedGateways_returnsObfs4GatewaysInPresortedOrder() { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_three_mixed_gateways.json", "ptdemo_three_mixed_gateways.geoip.json"); - MockHelper.mockProviderObservable(provider); + providerObservable.updateProvider(provider); //use openvpn, not pluggable transports - mockStatic(PreferenceHelper.class); - when(PreferenceHelper.getUseBridges()).thenReturn(true); + sharedPreferences.edit(). + putBoolean(USE_BRIDGES, true). + commit(); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals("moscow.bitmask.net", gatewaysManager.select(0).gateway.getHost()); @@ -334,11 +318,11 @@ public class GatewaysManagerTest { public void testSelectN_selectFromCity_returnsGatewaysInPresortedOrder() { Provider provider = getProvider(null, null, null, null, null, null, "v4/riseup_eipservice_for_geoip_v4.json", "v4/riseup_geoip_v4.json"); - MockHelper.mockProviderObservable(provider); + providerObservable.updateProvider(provider); //use openvpn, not pluggable transports - mockStatic(PreferenceHelper.class); - when(PreferenceHelper.getUseBridges()).thenReturn(false); - when(PreferenceHelper.getPreferredCity()).thenReturn("Paris"); + sharedPreferences.edit(). + putString(PREFERRED_CITY, "Paris"). + commit(); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals("mouette.riseup.net", gatewaysManager.select(0).gateway.getHost()); @@ -350,11 +334,11 @@ public class GatewaysManagerTest { public void testSelectN_selectFromCityWithGeoIpServiceV1_returnsGatewaysInPresortedOrder() { Provider provider = getProvider(null, null, null, null, null, null, "v4/riseup_eipservice_for_geoip_v4.json", "v4/riseup_geoip_v1.json"); - MockHelper.mockProviderObservable(provider); + providerObservable.updateProvider(provider); //use openvpn, not pluggable transports - mockStatic(PreferenceHelper.class); - when(PreferenceHelper.getUseBridges()).thenReturn(false); - when(PreferenceHelper.getPreferredCity()).thenReturn("Paris"); + sharedPreferences.edit(). + putString(PREFERRED_CITY, "Paris"). + commit(); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals("mouette.riseup.net", gatewaysManager.select(0).gateway.getHost()); @@ -367,11 +351,11 @@ public class GatewaysManagerTest { Provider provider = getProvider(null, null, null, null, null, null, "v4/riseup_eipservice_for_geoip_v4.json", null); provider.setGeoIpJson(new JSONObject()); - MockHelper.mockProviderObservable(provider); + providerObservable.updateProvider(provider); //use openvpn, not pluggable transports - mockStatic(PreferenceHelper.class); - when(PreferenceHelper.getUseBridges()).thenReturn(false); - when(PreferenceHelper.getPreferredCity()).thenReturn("Paris"); + sharedPreferences.edit(). + putString(PREFERRED_CITY, "Paris"). + commit(); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals("Paris", gatewaysManager.select(0).gateway.getName()); @@ -384,10 +368,7 @@ public class GatewaysManagerTest { public void testSelectN_selectNAndCity_returnsGatewaysInPresortedOrder() { Provider provider = getProvider(null, null, null, null, null, null, "v4/riseup_eipservice_for_geoip_v4.json", "v4/riseup_geoip_v4.json"); - MockHelper.mockProviderObservable(provider); - //use openvpn, not pluggable transports - mockStatic(PreferenceHelper.class); - when(PreferenceHelper.getUseBridges()).thenReturn(false); + providerObservable.updateProvider(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals("mouette.riseup.net", gatewaysManager.select(0, "Paris").gateway.getHost()); @@ -399,10 +380,7 @@ public class GatewaysManagerTest { public void testSelectN_selectNAndCityWithGeoIpServiceV1_returnsGatewaysInPresortedOrder() { Provider provider = getProvider(null, null, null, null, null, null, "v4/riseup_eipservice_for_geoip_v4.json", "v4/riseup_geoip_v1.json"); - MockHelper.mockProviderObservable(provider); - //use openvpn, not pluggable transports - mockStatic(PreferenceHelper.class); - when(PreferenceHelper.getUseBridges()).thenReturn(false); + providerObservable.updateProvider(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals("mouette.riseup.net", gatewaysManager.select(0, "Paris").gateway.getHost()); @@ -415,10 +393,7 @@ public class GatewaysManagerTest { Provider provider = getProvider(null, null, null, null, null, null, "v4/riseup_eipservice_for_geoip_v4.json", null); provider.setGeoIpJson(new JSONObject()); - MockHelper.mockProviderObservable(provider); - //use openvpn, not pluggable transports - mockStatic(PreferenceHelper.class); - when(PreferenceHelper.getUseBridges()).thenReturn(false); + providerObservable.updateProvider(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals("Paris", gatewaysManager.select(0, "Paris").gateway.getName()); @@ -432,10 +407,7 @@ public class GatewaysManagerTest { Provider provider = getProvider(null, null, null, null, null, null, "v4/riseup_eipservice_for_geoip_v4.json", "v4/riseup_geoip_v4.json"); provider.setGeoIpJson(new JSONObject()); - MockHelper.mockProviderObservable(provider); - //use openvpn, not pluggable transports - mockStatic(PreferenceHelper.class); - when(PreferenceHelper.getUseBridges()).thenReturn(false); + providerObservable.updateProvider(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertNull(gatewaysManager.select(0, "Stockholm")); } @@ -444,9 +416,10 @@ public class GatewaysManagerTest { public void testGetLocations_openvpn() { Provider provider = getProvider(null, null, null, null, null, null, "v4/riseup_eipservice_for_geoip_v4.json", "v4/riseup_geoip_v4.json"); - MockHelper.mockProviderObservable(provider); - mockStatic(PreferenceHelper.class); - when(PreferenceHelper.getUseBridges()).thenReturn(false); + providerObservable.updateProvider(provider); + sharedPreferences.edit(). + putString(PREFERRED_CITY, "Paris"). + commit(); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); List<Location> locations = gatewaysManager.getGatewayLocations(); @@ -465,9 +438,7 @@ public class GatewaysManagerTest { public void testGetLocations_obfs4() { Provider provider = getProvider(null, null, null, null, null, null, "v4/riseup_eipservice_for_geoip_v4.json", "v4/riseup_geoip_v4.json"); - MockHelper.mockProviderObservable(provider); - mockStatic(PreferenceHelper.class); - when(PreferenceHelper.getUseBridges()).thenReturn(true); + providerObservable.updateProvider(provider); sharedPreferences.edit().putBoolean(USE_BRIDGES, true).commit(); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); List<Location> locations = gatewaysManager.getGatewayLocations(); @@ -496,9 +467,7 @@ public class GatewaysManagerTest { public void testGetLocations_noMenshen_obfs4_calculateAverageLoadFromTimezoneDistance() { Provider provider = getProvider(null, null, null, null, null, null, "v4/riseup_eipservice_for_geoip_v4.json", "v4/riseup_geoip_v1.json"); - MockHelper.mockProviderObservable(provider); - mockStatic(PreferenceHelper.class); - when(PreferenceHelper.getUseBridges()).thenReturn(true); + providerObservable.updateProvider(provider); sharedPreferences.edit().putBoolean(USE_BRIDGES, true).commit(); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); List<Location> locations = gatewaysManager.getGatewayLocations(); @@ -521,10 +490,7 @@ public class GatewaysManagerTest { public void testGetLocations_noMenshen_openvpn_calculateAverageLoadFromTimezoneDistance() { Provider provider = getProvider(null, null, null, null, null, null, "v4/riseup_eipservice_for_geoip_v4.json", "v4/riseup_geoip_v1.json"); - MockHelper.mockProviderObservable(provider); - mockStatic(PreferenceHelper.class); - when(PreferenceHelper.getUseBridges()).thenReturn(false); - sharedPreferences.edit().putBoolean(USE_BRIDGES, false).commit(); + providerObservable.updateProvider(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); List<Location> locations = gatewaysManager.getGatewayLocations(); @@ -547,9 +513,7 @@ public class GatewaysManagerTest { public void testGetSortedLocations_openvpn() { Provider provider = getProvider(null, null, null, null, null, null, "v4/riseup_eipservice_for_geoip_v4.json", "v4/riseup_geoip_v4_bad_obfs4_gateway.json"); - MockHelper.mockProviderObservable(provider); - mockStatic(PreferenceHelper.class); - when(PreferenceHelper.getUseBridges()).thenReturn(false); + providerObservable.updateProvider(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); List<Location> locations = gatewaysManager.getSortedGatewayLocations(OPENVPN); @@ -576,9 +540,7 @@ public class GatewaysManagerTest { public void testGetSortedLocations_obfs4() { Provider provider = getProvider(null, null, null, null, null, null, "v4/riseup_eipservice_for_geoip_v4.json", "v4/riseup_geoip_v4_bad_obfs4_gateway.json"); - MockHelper.mockProviderObservable(provider); - mockStatic(PreferenceHelper.class); - when(PreferenceHelper.getUseBridges()).thenReturn(false); + providerObservable.updateProvider(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); List<Location> locations = gatewaysManager.getSortedGatewayLocations(OBFS4); @@ -606,9 +568,7 @@ public class GatewaysManagerTest { public void testGetSortedLocations_obfs4kcp_generalizedAsPT() { Provider provider = getProvider(null, null, null, null, null, null, "v4/riseup_eipservice_for_geoip_v4.json", "v4/riseup_geoip_v4_bad_obfs4_gateway.json"); - MockHelper.mockProviderObservable(provider); - mockStatic(PreferenceHelper.class); - when(PreferenceHelper.getUseBridges()).thenReturn(false); + providerObservable.updateProvider(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); List<Location> locations = gatewaysManager.getSortedGatewayLocations(OBFS4); @@ -619,9 +579,10 @@ public class GatewaysManagerTest { public void testgetAverageLoad_isSameForAllTransports() { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_kcp_gateways.json", "ptdemo_kcp_gateways_geoip.json"); - MockHelper.mockProviderObservable(provider); - mockStatic(PreferenceHelper.class); - when(PreferenceHelper.getUseBridges()).thenReturn(false); + providerObservable.updateProvider(provider); + sharedPreferences.edit(). + putString(PREFERRED_CITY, "Paris"). + commit(); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals(0.3, gatewaysManager.getLocation("Amsterdam").getAverageLoad(OBFS4)); @@ -630,7 +591,7 @@ public class GatewaysManagerTest { @Test public void testGetLoadForLocation_() { - MockHelper.mockProviderObservable(null); + providerObservable.updateProvider(null); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals(GatewaysManager.Load.UNKNOWN, gatewaysManager.getLoadForLocation("unknown city", OPENVPN)); } @@ -638,7 +599,7 @@ public class GatewaysManagerTest { @Test public void testGatewayManagerFromCurrentProvider_decoupledBridges_twoGateways() throws IOException, NullPointerException { Provider provider = getProvider(null, null, null, null, null, null, "decoupled_pt.eip-service.json", null); - MockHelper.mockProviderObservable(provider); + providerObservable.updateProvider(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals(2, gatewaysManager.size()); } @@ -646,9 +607,11 @@ public class GatewaysManagerTest { @Test public void testGatewayManagerFromCurrentProvider_decoupledBridgesIncludingExperimental_threeGateways() throws IOException, NullPointerException { Provider provider = getProvider(null, null, null, null, null, null, "decoupled_pt.eip-service.json", null); - MockHelper.mockProviderObservable(provider); - mockStatic(PreferenceHelper.class); - when(PreferenceHelper.allowExperimentalTransports()).thenReturn(true); + providerObservable.updateProvider(provider); + sharedPreferences.edit(). + putBoolean(USE_BRIDGES, true). + putBoolean(ALLOW_EXPERIMENTAL_TRANSPORTS, true). + commit(); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals(3, gatewaysManager.size()); } 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/eip/VpnCertificateValidatorTest.java b/app/src/test/java/se/leap/bitmaskclient/eip/VpnCertificateValidatorTest.java index 1cb47f43..a951f144 100644 --- a/app/src/test/java/se/leap/bitmaskclient/eip/VpnCertificateValidatorTest.java +++ b/app/src/test/java/se/leap/bitmaskclient/eip/VpnCertificateValidatorTest.java @@ -2,25 +2,20 @@ package se.leap.bitmaskclient.eip; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateEncodingException; import java.util.Calendar; -import se.leap.bitmaskclient.base.utils.ConfigHelper; +import se.leap.bitmaskclient.base.utils.CertificateHelper; import se.leap.bitmaskclient.testutils.TestCalendarProvider; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static se.leap.bitmaskclient.testutils.MockHelper.mockConfigHelper; +import static se.leap.bitmaskclient.testutils.MockHelper.mockCertificateHelper; import static se.leap.bitmaskclient.testutils.TestSetupHelper.getInputAsString; -@RunWith(PowerMockRunner.class) -@PrepareForTest({ConfigHelper.class}) public class VpnCertificateValidatorTest { @Before @@ -31,7 +26,7 @@ public class VpnCertificateValidatorTest { public void test_isValid() throws NoSuchAlgorithmException, CertificateEncodingException, IOException { String cert = getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.pem")); Calendar c = new Calendar.Builder().setDate(2018, 1, 1).setCalendarType("gregorian").build(); - mockConfigHelper("falseFingerPrint"); + CertificateHelper helper = mockCertificateHelper("falseFingerPrint"); VpnCertificateValidator validator = new VpnCertificateValidator(cert); validator.setCalendarProvider(new TestCalendarProvider(c.getTimeInMillis())); assertTrue( validator.isValid()); @@ -41,7 +36,7 @@ public class VpnCertificateValidatorTest { public void test_isValid_lessThan1day_returnFalse() throws NoSuchAlgorithmException, CertificateEncodingException, IOException { String cert = getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.pem")); Calendar c = new Calendar.Builder().setDate(2024, 3, 28).setCalendarType("gregorian").build(); - mockConfigHelper("falseFingerPrint"); + CertificateHelper helper = mockCertificateHelper("falseFingerPrint"); VpnCertificateValidator validator = new VpnCertificateValidator(cert); validator.setCalendarProvider(new TestCalendarProvider(c.getTimeInMillis())); assertFalse( validator.isValid()); @@ -51,7 +46,7 @@ public class VpnCertificateValidatorTest { public void test_isValid_multipleCerts_failIfOneExpires() throws NoSuchAlgorithmException, CertificateEncodingException, IOException { String cert = getInputAsString(getClass().getClassLoader().getResourceAsStream("float.hexacab.org.pem")); Calendar c = new Calendar.Builder().setDate(2024, 3, 28).setCalendarType("gregorian").build(); - mockConfigHelper("falseFingerPrint"); + CertificateHelper helper = mockCertificateHelper("falseFingerPrint"); VpnCertificateValidator validator = new VpnCertificateValidator(cert); validator.setCalendarProvider(new TestCalendarProvider(c.getTimeInMillis())); assertFalse(validator.isValid()); @@ -61,7 +56,7 @@ public class VpnCertificateValidatorTest { public void test_isValid_multipleCerts_allValid() throws NoSuchAlgorithmException, CertificateEncodingException, IOException { String cert = getInputAsString(getClass().getClassLoader().getResourceAsStream("float.hexacab.org.pem")); Calendar c = new Calendar.Builder().setDate(2024, 3, 27).setCalendarType("gregorian").build(); - mockConfigHelper("falseFingerPrint"); + CertificateHelper helper = mockCertificateHelper("falseFingerPrint"); VpnCertificateValidator validator = new VpnCertificateValidator(cert); validator.setCalendarProvider(new TestCalendarProvider(c.getTimeInMillis())); assertTrue(validator.isValid()); @@ -71,7 +66,7 @@ public class VpnCertificateValidatorTest { public void test_shouldBeUpdated_lessThan8days_returnTrue() throws NoSuchAlgorithmException, CertificateEncodingException, IOException { String cert = getInputAsString(getClass().getClassLoader().getResourceAsStream("float.hexacab.org.pem")); Calendar c = new Calendar.Builder().setDate(2024, 3, 21).setCalendarType("gregorian").build(); - mockConfigHelper("falseFingerPrint"); + CertificateHelper helper = mockCertificateHelper("falseFingerPrint"); VpnCertificateValidator validator = new VpnCertificateValidator(cert); validator.setCalendarProvider(new TestCalendarProvider(c.getTimeInMillis())); assertTrue(validator.shouldBeUpdated()); @@ -81,7 +76,7 @@ public class VpnCertificateValidatorTest { public void test_shouldBeUpdated_moreThan8days_returnFalse() throws NoSuchAlgorithmException, CertificateEncodingException, IOException { String cert = getInputAsString(getClass().getClassLoader().getResourceAsStream("float.hexacab.org.pem")); Calendar c = new Calendar.Builder().setDate(2024, 3, 20).setCalendarType("gregorian").build(); - mockConfigHelper("falseFingerPrint"); + CertificateHelper helper = mockCertificateHelper("falseFingerPrint"); VpnCertificateValidator validator = new VpnCertificateValidator(cert); validator.setCalendarProvider(new TestCalendarProvider(c.getTimeInMillis())); assertFalse(validator.shouldBeUpdated()); diff --git a/app/src/test/java/se/leap/bitmaskclient/eip/VpnConfigGeneratorTest.java b/app/src/test/java/se/leap/bitmaskclient/eip/VpnConfigGeneratorTest.java index 3f011a65..4b9e5d65 100644 --- a/app/src/test/java/se/leap/bitmaskclient/eip/VpnConfigGeneratorTest.java +++ b/app/src/test/java/se/leap/bitmaskclient/eip/VpnConfigGeneratorTest.java @@ -4,32 +4,18 @@ import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.RETURNS_DEEP_STUBS; -import static org.mockito.Mockito.mock; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; +import static org.mockito.Mockito.when; import static de.blinkt.openvpn.core.connection.Connection.TransportType.OBFS4; import static de.blinkt.openvpn.core.connection.Connection.TransportType.OBFS4_HOP; import static de.blinkt.openvpn.core.connection.Connection.TransportType.OPENVPN; import static se.leap.bitmaskclient.base.models.Constants.OPENVPN_CONFIGURATION; -import static se.leap.bitmaskclient.testutils.MockHelper.mockRSAHelper; -import static se.leap.bitmaskclient.testutils.MockHelper.mockTextUtils; import android.content.Context; import android.content.SharedPreferences; -import android.preference.PreferenceManager; -import android.text.TextUtils; -import android.util.Log; 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.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; import java.io.File; import java.util.HashMap; @@ -40,19 +26,21 @@ import de.blinkt.openvpn.core.connection.Connection; import de.blinkt.openvpn.core.connection.Obfs4Connection; import de.blinkt.openvpn.core.connection.Obfs4HopConnection; import se.leap.bitmaskclient.base.models.ProviderObservable; -import se.leap.bitmaskclient.base.utils.ConfigHelper; +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.testutils.MockHelper; +import se.leap.bitmaskclient.testutils.MockSharedPreferences; import se.leap.bitmaskclient.testutils.TestSetupHelper; /** * Created by cyberta on 03.10.17. */ -@RunWith(PowerMockRunner.class) -@PrepareForTest({Log.class, TextUtils.class, PreferenceManager.class, ProviderObservable.class, ConfigHelper.RSAHelper.class, ConfigHelper.ObfsVpnHelper.class}) public class VpnConfigGeneratorTest { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) Context context; + PreferenceHelper preferenceHelper; + private SharedPreferences sharedPreferences; private VpnConfigGenerator vpnConfigGenerator; private JSONObject generalConfig; @@ -139,7 +127,7 @@ public class VpnConfigGeneratorTest { "-----END CERTIFICATE-----\n" + "</cert>\n" + "management-external-key nopadding pkcs1 pss digest\n" + - "# crl-verify file missing in config profile\n" + + //"# crl-verify file missing in config profile\n" + "remote-cert-tls server\n" + "data-ciphers AES-128-CBC\n" + "cipher AES-128-CBC\n" + @@ -235,7 +223,7 @@ public class VpnConfigGeneratorTest { "-----END CERTIFICATE-----\n" + "</cert>\n" + "management-external-key nopadding pkcs1 pss digest\n" + - "# crl-verify file missing in config profile\n" + + //"# crl-verify file missing in config profile\n" + "remote-cert-tls server\n" + "data-ciphers AES-128-CBC\n" + "cipher AES-128-CBC\n" + @@ -330,7 +318,7 @@ public class VpnConfigGeneratorTest { "-----END CERTIFICATE-----\n" + "</cert>\n" + "management-external-key nopadding pkcs1 pss digest\n" + - "# crl-verify file missing in config profile\n" + + //"# crl-verify file missing in config profile\n" + "route 37.218.247.60 255.255.255.255 net_gateway\n"+ "remote-cert-tls server\n" + "data-ciphers AES-128-CBC\n" + @@ -426,7 +414,7 @@ public class VpnConfigGeneratorTest { "-----END CERTIFICATE-----\n" + "</cert>\n" + "management-external-key nopadding pkcs1 pss digest\n" + - "# crl-verify file missing in config profile\n" + + //"# crl-verify file missing in config profile\n" + "route 37.218.247.60 255.255.255.255 net_gateway\n"+ "remote-cert-tls server\n" + "data-ciphers AES-128-CBC\n" + @@ -523,7 +511,7 @@ public class VpnConfigGeneratorTest { "-----END CERTIFICATE-----\n" + "</cert>\n" + "management-external-key nopadding pkcs1 pss digest\n" + - "# crl-verify file missing in config profile\n" + + //"# crl-verify file missing in config profile\n" + "remote-cert-tls server\n" + "data-ciphers AES-128-CBC\n" + "cipher AES-128-CBC\n" + @@ -619,7 +607,7 @@ public class VpnConfigGeneratorTest { "-----END CERTIFICATE-----\n" + "</cert>\n" + "management-external-key nopadding pkcs1 pss digest\n" + - "# crl-verify file missing in config profile\n" + + //"# crl-verify file missing in config profile\n" + "remote-cert-tls server\n" + "data-ciphers AES-128-CBC\n" + "cipher AES-128-CBC\n" + @@ -715,7 +703,7 @@ public class VpnConfigGeneratorTest { "-----END CERTIFICATE-----\n" + "</cert>\n" + "management-external-key nopadding pkcs1 pss digest\n" + - "# crl-verify file missing in config profile\n" + + //"# crl-verify file missing in config profile\n" + "remote-cert-tls server\n" + "data-ciphers AES-256-GCM:AES-128-GCM:AES-128-CBC\n" + "cipher AES-128-CBC\n" + @@ -813,7 +801,7 @@ public class VpnConfigGeneratorTest { "-----END CERTIFICATE-----\n" + "</cert>\n" + "management-external-key nopadding pkcs1 pss digest\n" + - "# crl-verify file missing in config profile\n" + + //"# crl-verify file missing in config profile\n" + "comp-lzo\n" + "nobind\n"+ "remote-cert-tls server\n" + @@ -915,7 +903,7 @@ public class VpnConfigGeneratorTest { "-----END CERTIFICATE-----\n" + "</cert>\n" + "management-external-key nopadding pkcs1 pss digest\n" + - "# crl-verify file missing in config profile\n" + + //"# crl-verify file missing in config profile\n" + "comp-lzo\n" + "nobind\n"+ "remote-cert-tls server\n" + @@ -1025,7 +1013,7 @@ public class VpnConfigGeneratorTest { "-----END CERTIFICATE-----\n" + "</cert>\n" + "management-external-key nopadding pkcs1 pss digest\n" + - "# crl-verify file missing in config profile\n" + + //"# crl-verify file missing in config profile\n" + "comp-lzo\n" + "nobind\n"+ "remote-cert-tls server\n" + @@ -1128,7 +1116,7 @@ public class VpnConfigGeneratorTest { "-----END CERTIFICATE-----\n" + "</cert>\n" + "management-external-key nopadding pkcs1 pss digest\n" + - "# crl-verify file missing in config profile\n" + + //"# crl-verify file missing in config profile\n" + "nobind\n"+ "remote-cert-tls server\n" + "data-ciphers AES-256-GCM:AES-128-CBC\n" + @@ -1228,7 +1216,7 @@ public class VpnConfigGeneratorTest { "-----END CERTIFICATE-----\n" + "</cert>\n" + "management-external-key nopadding pkcs1 pss digest\n" + - "# crl-verify file missing in config profile\n" + + //"# crl-verify file missing in config profile\n" + "route 192.81.208.164 255.255.255.255 net_gateway\n"+ "tun-mtu 48000\n"+ "nobind\n"+ @@ -1332,7 +1320,7 @@ public class VpnConfigGeneratorTest { "-----END CERTIFICATE-----\n" + "</cert>\n" + "management-external-key nopadding pkcs1 pss digest\n" + - "# crl-verify file missing in config profile\n" + + //"# crl-verify file missing in config profile\n" + "route 192.81.208.164 255.255.255.255 net_gateway\n"+ "route 192.81.208.165 255.255.255.255 net_gateway\n"+ "route 192.81.208.166 255.255.255.255 net_gateway\n"+ @@ -1364,17 +1352,13 @@ public class VpnConfigGeneratorTest { public void setUp() throws Exception { generalConfig = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("general_configuration.json"))); secrets = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("secrets.json"))); - mockStatic(Log.class); context = MockHelper.mockContext(); - mockTextUtils(); - mockStatic(PreferenceManager.class); - MockHelper.mockProviderObservable(TestSetupHelper.getConfiguredProvider()); - MockHelper.mockRSAHelper(); - SharedPreferences preferences = mock(SharedPreferences.class, RETURNS_DEEP_STUBS); - when(PreferenceManager.getDefaultSharedPreferences(any(Context.class))).thenReturn(preferences); - when(preferences.getBoolean("usesystemproxy", true)).thenReturn(true); + + ProviderObservable providerObservable = MockHelper.mockProviderObservable(TestSetupHelper.getConfiguredProvider()); + RSAHelper rsaHelper = MockHelper.mockRSAHelper(); + sharedPreferences = new MockSharedPreferences(); + preferenceHelper = new PreferenceHelper(new MockSharedPreferences()); when(context.getCacheDir()).thenReturn(new File("/data/data/se.leap.bitmask")); - mockStatic(ConfigHelper.ObfsVpnHelper.class); } @Test @@ -1424,7 +1408,7 @@ public class VpnConfigGeneratorTest { @Test public void testGenerateVpnProfile_v3_obfs4() throws Exception { - when(ConfigHelper.ObfsVpnHelper.useObfsVpn()).thenReturn(false); + BuildConfigHelper buildConfigHelper = MockHelper.mockBuildConfigHelper(false); gateway = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("ptdemo.bitmask.eip-service.json"))).getJSONArray("gateways").getJSONObject(0); VpnConfigGenerator.Configuration configuration = new VpnConfigGenerator.Configuration(); configuration.apiVersion = 3; @@ -1438,7 +1422,7 @@ public class VpnConfigGeneratorTest { @Test public void testGenerateVpnProfile_v3_obfs4_obfsvpn() throws Exception { - when(ConfigHelper.ObfsVpnHelper.useObfsVpn()).thenReturn(true); + BuildConfigHelper buildConfigHelper = MockHelper.mockBuildConfigHelper(true); gateway = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("ptdemo.bitmask.eip-service.json"))).getJSONArray("gateways").getJSONObject(0); VpnConfigGenerator.Configuration configuration = new VpnConfigGenerator.Configuration(); configuration.apiVersion = 3; @@ -1744,7 +1728,7 @@ public class VpnConfigGeneratorTest { @Test public void testGetConfigFile_testHoppingPtPortHopping_decoupled() throws Exception { - when(ConfigHelper.ObfsVpnHelper.useObfsVpn()).thenReturn(true); + BuildConfigHelper buildConfigHelper = MockHelper.mockBuildConfigHelper(true); gateway = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("decoupled_pt_portHopping.eip-service.json"))).getJSONArray("gateways").getJSONObject(2); generalConfig = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("decoupled_pt_portHopping.eip-service.json"))).getJSONObject(OPENVPN_CONFIGURATION); VpnConfigGenerator.Configuration configuration = new VpnConfigGenerator.Configuration(); @@ -1758,7 +1742,7 @@ public class VpnConfigGeneratorTest { @Test public void testGetConfigFile_testHoppingPtPortAndIPHopping_decoupled() throws Exception { - when(ConfigHelper.ObfsVpnHelper.useObfsVpn()).thenReturn(true); + BuildConfigHelper buildConfigHelper = MockHelper.mockBuildConfigHelper(true); gateway = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("decoupled_pt_portHopping.eip-service.json"))).getJSONArray("gateways").getJSONObject(2); generalConfig = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("decoupled_pt_portHopping.eip-service.json"))).getJSONObject(OPENVPN_CONFIGURATION); VpnConfigGenerator.Configuration configuration = new VpnConfigGenerator.Configuration(); @@ -1771,7 +1755,7 @@ public class VpnConfigGeneratorTest { } @Test public void testGenerateVpnProfile_obfs4_decoupled() throws Exception { - when(ConfigHelper.ObfsVpnHelper.useObfsVpn()).thenReturn(true); + BuildConfigHelper buildConfigHelper = MockHelper.mockBuildConfigHelper(true); gateway = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("decoupled_pt.eip-service.json"))).getJSONArray("gateways").getJSONObject(1); generalConfig = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("decoupled_pt.eip-service.json"))).getJSONObject(OPENVPN_CONFIGURATION); VpnConfigGenerator.Configuration configuration = new VpnConfigGenerator.Configuration(); @@ -1786,7 +1770,7 @@ public class VpnConfigGeneratorTest { @Test public void testGenerateVpnProfile_obfs4hop_decoupled() throws Exception { - when(ConfigHelper.ObfsVpnHelper.useObfsVpn()).thenReturn(true); + BuildConfigHelper buildConfigHelper = MockHelper.mockBuildConfigHelper(true); gateway = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("decoupled_pt.eip-service.json"))).getJSONArray("gateways").getJSONObject(2); generalConfig = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("decoupled_pt.eip-service.json"))).getJSONObject(OPENVPN_CONFIGURATION); VpnConfigGenerator.Configuration configuration = new VpnConfigGenerator.Configuration(); @@ -1802,7 +1786,7 @@ public class VpnConfigGeneratorTest { @Test public void testGenerateVpnProfile_noExperimental_skipObfs4Hop() throws Exception { - when(ConfigHelper.ObfsVpnHelper.useObfsVpn()).thenReturn(true); + BuildConfigHelper buildConfigHelper = MockHelper.mockBuildConfigHelper(true); gateway = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("decoupled_pt.eip-service.json"))).getJSONArray("gateways").getJSONObject(2); generalConfig = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("decoupled_pt.eip-service.json"))).getJSONObject(OPENVPN_CONFIGURATION); VpnConfigGenerator.Configuration configuration = new VpnConfigGenerator.Configuration(); @@ -1820,7 +1804,7 @@ public class VpnConfigGeneratorTest { @Test public void testGenerateVpnProfile_obfs4hop_onlyPortHopping_decoupled() throws Exception { - when(ConfigHelper.ObfsVpnHelper.useObfsVpn()).thenReturn(true); + BuildConfigHelper buildConfigHelper = MockHelper.mockBuildConfigHelper(true); gateway = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("decoupled_pt_portHopping.eip-service.json"))).getJSONArray("gateways").getJSONObject(2); generalConfig = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("decoupled_pt_portHopping.eip-service.json"))).getJSONObject(OPENVPN_CONFIGURATION); VpnConfigGenerator.Configuration configuration = new VpnConfigGenerator.Configuration(); diff --git a/app/src/test/java/se/leap/bitmaskclient/providersetup/ProviderManagerTest.java b/app/src/test/java/se/leap/bitmaskclient/providersetup/ProviderManagerTest.java index e7295452..7584fb3f 100644 --- a/app/src/test/java/se/leap/bitmaskclient/providersetup/ProviderManagerTest.java +++ b/app/src/test/java/se/leap/bitmaskclient/providersetup/ProviderManagerTest.java @@ -1,56 +1,49 @@ package se.leap.bitmaskclient.providersetup; +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertFalse; +import static junit.framework.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static se.leap.bitmaskclient.testutils.MockHelper.mockInputStreamHelper; + import android.content.res.AssetManager; import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; import java.io.File; import java.io.InputStream; import java.util.ArrayList; import se.leap.bitmaskclient.base.models.Provider; -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.providersetup.ProviderManager; - -import static junit.framework.Assert.assertEquals; -import static junit.framework.Assert.assertFalse; -import static junit.framework.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.powermock.api.mockito.PowerMockito.verifyStatic; -import static se.leap.bitmaskclient.testutils.MockHelper.mockFileHelper; -import static se.leap.bitmaskclient.testutils.MockHelper.mockInputStreamHelper; +import se.leap.bitmaskclient.testutils.MockHelper; /** * Created by cyberta on 20.02.18. */ -@RunWith(PowerMockRunner.class) -@PrepareForTest({ConfigHelper.class, FileHelper.class, InputStreamHelper.class}) public class ProviderManagerTest { - @Mock private AssetManager assetManager; - @Mock private File file; private ProviderManager providerManager; + InputStreamHelper inputStreamHelper; + FileHelper fileHelper; + MockHelper.MockFileHelper mockedFileHelperInterface; @Before public void setup() throws Exception { - //mock assetManager methods - //-------------------------- + assetManager = mock(AssetManager.class); + file = mock(File.class); + when(assetManager.open(anyString())).thenAnswer(new Answer<InputStream>() { @Override public InputStream answer(InvocationOnMock invocation) throws Throwable { @@ -85,11 +78,9 @@ public class ProviderManagerTest { when(file.getAbsolutePath()).thenReturn("externalDir"); when(file.getPath()).thenReturn("externalDir"); - mockFileHelper(file); - - // mock inputStream - //----------------------------------- - mockInputStreamHelper(); + mockedFileHelperInterface = new MockHelper.MockFileHelper(file); + fileHelper = new FileHelper(mockedFileHelperInterface); + inputStreamHelper = mockInputStreamHelper(); } @@ -217,8 +208,7 @@ public class ProviderManagerTest { providerManager.add(secondCustomProvider); providerManager.saveCustomProvidersToFile(); - verifyStatic(FileHelper.class, times(2)); - FileHelper.persistFile(any(File.class), anyString()); + assertEquals("persist was called twice", 2, mockedFileHelperInterface.getPersistFileCounter()); } 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 <http://www.gnu.org/licenses/>. - */ -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<String> answerRequestStringFromServer; - private Answer<Boolean> answerCanConnect; - private Answer<Boolean> answerDelete; - - public BaseBackendResponse() throws IOException { - mockStatic(ProviderApiConnector.class); - this.answerRequestStringFromServer = getAnswerForRequestStringFromServer(); - this.answerCanConnect = getAnswerForCanConnect(); - this.answerDelete = getAnswerForDelete(); - - responseOnRequestStringFromServer(); - responseOnCanConnect(); - responseOnDelete(); - - } - - public abstract Answer<String> getAnswerForRequestStringFromServer(); - public abstract Answer<Boolean> getAnswerForCanConnect(); - public abstract Answer<Boolean> getAnswerForDelete(); - - - public void responseOnRequestStringFromServer() throws IOException, RuntimeException { - Mockito.when(ProviderApiConnector.requestStringFromServer(anyString(), anyString(), nullable(String.class), ArgumentMatchers.<Pair<String,String>>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 <http://www.gnu.org/licenses/>. - */ -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<String> getAnswerForRequestStringFromServer() { - return new Answer<String>() { - @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<Boolean> getAnswerForCanConnect() { - return new Answer<Boolean>() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - return true; - } - }; - } - - @Override - public Answer<Boolean> getAnswerForDelete() { - return new Answer<Boolean>() { - @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 <http://www.gnu.org/licenses/>. + */ +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<Pair<String, String>> 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<String> getAnswerForRequestStringFromServer() { - return new Answer<String>() { - @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<Boolean> getAnswerForCanConnect() { - return new Answer<Boolean>() { - @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<Boolean> getAnswerForDelete() { - return new Answer<Boolean>() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - return true; - } - }; - } + public String requestStringFromServer(@NonNull String url, @NonNull String requestMethod, String jsonString, @NonNull List<Pair<String, String>> 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<String> getAnswerForRequestStringFromServer() { - return new Answer<String>() { - @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<Boolean> getAnswerForCanConnect() { - return new Answer<Boolean>() { - @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<Boolean> getAnswerForDelete() { - return new Answer<Boolean>() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - return true; + public String requestStringFromServer(@NonNull String url, @NonNull String requestMethod, String jsonString, @NonNull List<Pair<String, String>> 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<String> getAnswerForRequestStringFromServer() { - return new Answer<String>() { - @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<Boolean> getAnswerForCanConnect() { - return new Answer<Boolean>() { - @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<Boolean> getAnswerForDelete() { - return new Answer<Boolean>() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - return true; - } - }; - } + public String requestStringFromServer(@NonNull String url, @NonNull String requestMethod, String jsonString, @NonNull List<Pair<String, String>> 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<String> getAnswerForRequestStringFromServer() { - return new Answer<String>() { - @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<Boolean> getAnswerForCanConnect() { - return new Answer<Boolean>() { - @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<Boolean> getAnswerForDelete() { - return new Answer<Boolean>() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - return true; - } - }; - } + public String requestStringFromServer(@NonNull String url, @NonNull String requestMethod, String jsonString, @NonNull List<Pair<String, String>> 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<String> getAnswerForRequestStringFromServer() { - return new Answer<String>() { - @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<Boolean> getAnswerForCanConnect() { - return new Answer<Boolean>() { - @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<Boolean> getAnswerForDelete() { - return new Answer<Boolean>() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - return true; - } - }; - } + public String requestStringFromServer(@NonNull String url, @NonNull String requestMethod, String jsonString, @NonNull List<Pair<String, String>> 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<String> getAnswerForRequestStringFromServer() { - return new Answer<String>() { - @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<Boolean> getAnswerForCanConnect() { - return new Answer<Boolean>() { - @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<Boolean> getAnswerForDelete() { - return new Answer<Boolean>() { - @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<Pair<String, String>> 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<String> getAnswerForRequestStringFromServer() { - return new Answer<String>() { - - @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<Boolean> getAnswerForCanConnect() { - return new Answer<Boolean>() { - @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<Boolean> getAnswerForDelete() { - return new Answer<Boolean>() { - @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<Pair<String, String>> 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 1f8a18f4..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,9 +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.cert.X509Certificate; import java.security.interfaces.RSAPrivateKey; import java.util.ArrayList; import java.util.Arrays; @@ -69,10 +63,13 @@ 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.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; @@ -84,268 +81,6 @@ import se.leap.bitmaskclient.tor.TorStatusObservable; */ public class MockHelper { - @NonNull - public static Bundle mockBundle() { - final Map<String, Boolean> fakeBooleanBundle = new HashMap<>(); - final Map<String, String> fakeStringBundle = new HashMap<>(); - final Map<String, Integer> fakeIntBundle = new HashMap<>(); - final Map<String, Parcelable> 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<String>() { - @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<Boolean>() { - @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<Integer>() { - @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<Parcelable>() { - @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<Object>() { - @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<Set<String>>() { - @Override - public Set<String> answer(InvocationOnMock invocation) throws Throwable { - //this whole approach as a drawback: - //you should not add the same keys for values of different types - HashSet<String> keys = new HashSet<String>(); - 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<Boolean>() { - @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<String, Object> fakeExtras = new HashMap<>(); - final List<String> 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<String>() { - @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<Bundle>() { - @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<Parcelable>() { - @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<Set<String>>() { - @Override - public Set<String> answer(InvocationOnMock invocation) throws Throwable { - return new HashSet<>(categories); - } - }); - - return intent; - } - - public static void mockTextUtils() { - mockStatic(TextUtils.class); - - when(TextUtils.equals(any(CharSequence.class), any(CharSequence.class))).thenAnswer(new Answer<Object>() { - @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<Boolean>() { - @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); @@ -398,34 +133,45 @@ 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<InputStream>() { + + 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 void mockFileHelper(final File mockedFile) throws FileNotFoundException { - mockStatic(FileHelper.class); - when(createFile(any(File.class), anyString())).thenReturn(mockedFile); - } + 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 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 int getPersistFileCounter() { + return persistFileCounter; + } } - public static void mockRSAHelper() { - mockStatic(ConfigHelper.RSAHelper.class); + public static FileHelper mockFileHelper(final File mockedFile) throws FileNotFoundException { + return new FileHelper(new MockFileHelper(mockedFile)); + } - when(ConfigHelper.RSAHelper.parseRsaKeyFromString(anyString())).thenReturn(new RSAPrivateKey() { + public static RSAHelper mockRSAHelper() { + return new RSAHelper(rsaKeyString -> new RSAPrivateKey() { @Override public BigInteger getPrivateExponent() { return BigInteger.TEN; @@ -451,103 +197,113 @@ public class MockHelper { return BigInteger.ONE; } }); + } - 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.timezoneDistance(anyInt(), anyInt())).thenCallRealMethod(); - when(ConfigHelper.isIPv4(anyString())).thenCallRealMethod(); - when(ConfigHelper.isDefaultBitmask()).thenReturn(true); - when(ConfigHelper.getDomainFromMainURL(anyString())).thenCallRealMethod(); + public static BuildConfigHelper mockBuildConfigHelper(boolean useObfsvpn) { + return mockBuildConfigHelper(useObfsvpn, true); } - public static void mockPreferenceHelper(final Provider providerFromPrefs) { - // FIXME use MockSharedPreferences instead of provider - mockStatic(PreferenceHelper.class); - when(getFromPersistedProvider(anyString(), anyString())).thenAnswer(new Answer<String>() { + public static BuildConfigHelper mockBuildConfigHelper(boolean useObfsvpn, boolean isDefaultBitmask) { + return new BuildConfigHelper(new BuildConfigHelper.BuildConfigHelperInterface() { @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 boolean useObfsVpn() { + return useObfsvpn; + } - } + @Override + public boolean hasObfuscationPinningDefaults() { + return false; + } + + @Override + public String obfsvpnIP() { return null; } - }); - when(getLongFromPersistedProvider(anyString(), anyString())).thenAnswer(new Answer<Long>() { + @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; + public String obfsvpnPort() { + return null; } - }); - when(getStringSetFromPersistedProvider(anyString(), anyString())).thenAnswer(new Answer<Set<String>>() { + @Override - public Set<String> answer(InvocationOnMock invocation) throws Throwable { - String key = (String) invocation.getArguments()[0]; - switch (key) { - case PROVIDER_MOTD_HASHES: - return providerFromPrefs.getMotdLastSeenHashes(); - } + public String obfsvpnCert() { return null; } - }); - when(PreferenceHelper.hasKey(anyString())).then(new Answer<Boolean>() { + @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(); - } + public boolean useKcp() { return false; } + + @Override + public boolean isDefaultBitmask() { + return isDefaultBitmask; + } }); } + public static CertificateHelper mockCertificateHelper(String mockedFingerprint) { + return new CertificateHelper((certificate, encoding) -> mockedFingerprint); + } + + 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; + } + + 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) { mockStatic(PreferenceHelper.class); @@ -560,54 +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<TorStatusObservable>) 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<Integer>) invocation -> { - if (waitUntilSuccess.get()) { - return 8118; - } - return -1; - }); - when(TorStatusObservable.getStatus()).thenAnswer((Answer<TorStatusObservable.TorStatus>) invocation -> { - if (waitUntilSuccess.get()) { - return TorStatusObservable.TorStatus.ON; - } - return TorStatusObservable.TorStatus.OFF; - }); - when(TorStatusObservable.getSnowflakeStatus()).thenAnswer((Answer<TorStatusObservable.SnowflakeStatus>) 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<Boolean>) invocation -> { - waitUntilSuccess.set(true); - return true; - }); - } - } - - 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<ProviderObservable>) invocation -> observable); + 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 { @@ -633,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")); @@ -657,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; } 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<String, String> mockedStringPrefs = new HashMap<>(); HashMap<String, Integer> mockedIntPrefs = new HashMap<>(); HashMap<String, Boolean> mockedBooleanPrefs = new HashMap<>(); + HashMap<String, Long> mockedLongPrefs = new HashMap<>(); + HashMap<String, Set<String>> mockedStringSetPrefs = new HashMap<>(); @Override public Map<String, ?> getAll() { @@ -49,7 +51,7 @@ public class MockSharedPreferences implements SharedPreferences { @Nullable @Override public Set<String> getStringSet(String key, @Nullable Set<String> 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<String, String> tempStrings = new HashMap<>(mockedStringPrefs); private HashMap<String, Integer> tempIntegers = new HashMap<>(mockedIntPrefs); private HashMap<String, Boolean> tempBoolean = new HashMap<>(mockedBooleanPrefs); + private HashMap<String, Long> tempLongs = new HashMap<>(mockedLongPrefs); + private HashMap<String, Set<String>> 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<String> 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 diff --git a/app/src/test/java/se/leap/bitmaskclient/tethering/TetheringStateManagerTest.java b/app/src/test/java/se/leap/bitmaskclient/tethering/TetheringStateManagerTest.java index a2569282..a5954a97 100644 --- a/app/src/test/java/se/leap/bitmaskclient/tethering/TetheringStateManagerTest.java +++ b/app/src/test/java/se/leap/bitmaskclient/tethering/TetheringStateManagerTest.java @@ -16,279 +16,25 @@ */ package se.leap.bitmaskclient.tethering; -import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; - -import android.content.Context; -import android.content.IntentFilter; -import android.content.SharedPreferences; +import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Answers; -import org.mockito.Mock; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.net.NetworkInterface; -import java.net.SocketException; -import java.util.Arrays; -import java.util.Collections; -import java.util.Enumeration; - -import se.leap.bitmaskclient.base.utils.Cmd; -import se.leap.bitmaskclient.base.utils.PreferenceHelper; -import se.leap.bitmaskclient.testutils.MockSharedPreferences; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({WifiManagerWrapper.class, TetheringStateManager.class, Cmd.class, NetworkInterface.class, PreferenceHelper.class}) public class TetheringStateManagerTest { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - Context mockContext; - - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - IntentFilter intentFilter; - private TetheringObservable observable; @Before public void setup() throws Exception { - PowerMockito.whenNew(IntentFilter.class).withArguments(anyString()).thenReturn(intentFilter); - PowerMockito.whenNew(IntentFilter.class).withNoArguments().thenReturn(intentFilter); - mockStatic(PreferenceHelper.class); - observable = TetheringObservable.getInstance(); - - } - - @Test - public void updateUsbTetheringState_findsRndisX_returnsTrue() throws Exception { - WifiManagerWrapper mockWrapper = mock(WifiManagerWrapper.class); - when(mockWrapper.isWifiAPEnabled()).thenReturn(false); - PowerMockito.whenNew(WifiManagerWrapper.class).withAnyArguments().thenReturn(mockWrapper); - - PowerMockito.mockStatic(NetworkInterface.class); - NetworkInterface mock1 = PowerMockito.mock(NetworkInterface.class); - when(mock1.isLoopback()).thenReturn(false); - when(mock1.getName()).thenReturn("eth0"); - NetworkInterface mock2 = PowerMockito.mock(NetworkInterface.class); - when(mock2.isLoopback()).thenReturn(false); - when(mock2.getName()).thenReturn("rndis0"); - - NetworkInterface[] networkInterfaces = new NetworkInterface[2]; - networkInterfaces[0] = mock1; - networkInterfaces[1] = mock2; - - PowerMockito.when(NetworkInterface.getNetworkInterfaces()).then(new Answer<Enumeration<NetworkInterface>>() { - @Override - public Enumeration<NetworkInterface> answer(InvocationOnMock invocation) throws Throwable { - return Collections.enumeration(Arrays.asList(networkInterfaces)); - } - }); - - TetheringObservable.setUsbTethering(false, "192.168.42.0/24", "rndis0"); - TetheringStateManager.getInstance().init(mockContext); - TetheringStateManager manager = TetheringStateManager.getInstance(); - assertTrue(observable.isUsbTetheringEnabled()); - } - - @Test - public void updateUsbTetheringState_doesntFindRndisX_returnsFalse() throws Exception { - WifiManagerWrapper mockWrapper = mock(WifiManagerWrapper.class); - when(mockWrapper.isWifiAPEnabled()).thenReturn(false); - PowerMockito.whenNew(WifiManagerWrapper.class).withAnyArguments().thenReturn(mockWrapper); - - PowerMockito.mockStatic(NetworkInterface.class); - NetworkInterface mock1 = PowerMockito.mock(NetworkInterface.class); - when(mock1.isLoopback()).thenReturn(false); - when(mock1.getName()).thenReturn("eth0"); - NetworkInterface mock2 = PowerMockito.mock(NetworkInterface.class); - when(mock2.isLoopback()).thenReturn(false); - when(mock2.getName()).thenReturn("wifi0"); - - NetworkInterface[] networkInterfaces = new NetworkInterface[2]; - networkInterfaces[0] = mock1; - networkInterfaces[1] = mock2; - - PowerMockito.when(NetworkInterface.getNetworkInterfaces()).then(new Answer<Enumeration<NetworkInterface>>() { - @Override - public Enumeration<NetworkInterface> answer(InvocationOnMock invocation) throws Throwable { - return Collections.enumeration(Arrays.asList(networkInterfaces)); - } - }); - - TetheringObservable.setUsbTethering(true, "192.168.42.0/24", "rndis0"); - TetheringStateManager.getInstance().init(mockContext); - TetheringStateManager manager = TetheringStateManager.getInstance(); - assertFalse(observable.isUsbTetheringEnabled()); - } - - @Test - public void updateUsbTetheringState_ThrowsException_returnsFalse() throws Exception { - WifiManagerWrapper mockWrapper = mock(WifiManagerWrapper.class); - when(mockWrapper.isWifiAPEnabled()).thenReturn(false); - PowerMockito.whenNew(WifiManagerWrapper.class).withAnyArguments().thenReturn(mockWrapper); - - PowerMockito.mockStatic(NetworkInterface.class); - PowerMockito.when(NetworkInterface.getNetworkInterfaces()).thenThrow(new SocketException()); - - TetheringObservable.setUsbTethering(true, "192.168.42.0/24", "rndis0"); - TetheringStateManager.getInstance().init(mockContext); - TetheringStateManager manager = TetheringStateManager.getInstance(); - assertFalse(observable.isUsbTetheringEnabled()); - } - -/* //TODO enable these tests as soon as bluetooth tethering has been enabled again - @Test - public void updateBluetoothTetheringState_btDeviceFound_returnTrue() throws Exception { - WifiManagerWrapper mockWrapper = mock(WifiManagerWrapper.class); - when(mockWrapper.isWifiAPEnabled()).thenReturn(true); - PowerMockito.whenNew(WifiManagerWrapper.class).withAnyArguments().thenReturn(mockWrapper); - - mockStatic(Cmd.class); - PowerMockito.when(Cmd.runBlockingCmd(any(), any(StringBuilder.class))).then(new Answer<Integer>() { - @Override - public Integer answer(InvocationOnMock invocation) throws Throwable { - StringBuilder logStringBuilder = invocation.getArgument(1); - logStringBuilder.append("bt-pan device found"); - return 0; - } - }); - - TetheringObservable.setBluetoothTethering(false); - TetheringStateManager.getInstance().init(mockContext); - TetheringStateManager manager = TetheringStateManager.getInstance(); - assertTrue(observable.isBluetoothTetheringEnabled()); - } - - - @Test - public void updateBluetoothTetheringState_btPanDeviceNotFound_returnFalse() throws Exception { - WifiManagerWrapper mockWrapper = mock(WifiManagerWrapper.class); - when(mockWrapper.isWifiAPEnabled()).thenReturn(true); - PowerMockito.whenNew(WifiManagerWrapper.class).withAnyArguments().thenReturn(mockWrapper); - - mockStatic(Cmd.class); - PowerMockito.when(Cmd.runBlockingCmd(any(), any(StringBuilder.class))).then(new Answer<Integer>() { - @Override - public Integer answer(InvocationOnMock invocation) throws Throwable { - StringBuilder logStringBuilder = invocation.getArgument(1); - logStringBuilder.append("bt-pan device not found"); - return 1; - } - }); - - TetheringObservable.setBluetoothTethering(true); - TetheringStateManager.getInstance().init(mockContext); - TetheringStateManager manager = TetheringStateManager.getInstance(); - assertFalse(observable.isBluetoothTetheringEnabled()); - } - - @Test - public void updateBluetoothTetheringState_ThrowsException_returnsFalse() throws Exception { - WifiManagerWrapper mockWrapper = mock(WifiManagerWrapper.class); - when(mockWrapper.isWifiAPEnabled()).thenReturn(true); - PowerMockito.whenNew(WifiManagerWrapper.class).withAnyArguments().thenReturn(mockWrapper); - - mockStatic(Cmd.class); - PowerMockito.when(Cmd.runBlockingCmd(any(), any(StringBuilder.class))). - thenThrow(new SecurityException("Creation of subprocess is not allowed")); - - TetheringObservable.setBluetoothTethering(true); - TetheringStateManager.getInstance().init(mockContext); - TetheringStateManager manager = TetheringStateManager.getInstance(); - assertFalse(observable.isBluetoothTetheringEnabled()); - } - - @Test - public void updateBluetoothTetheringState_WifiManagerWrapperThrowsException_hasNoInfluenceOnResult() throws Exception { - WifiManagerWrapper mockWrapper = mock(WifiManagerWrapper.class); - when(mockWrapper.isWifiAPEnabled()).thenThrow(new NoSuchMethodException()); - PowerMockito.whenNew(WifiManagerWrapper.class).withAnyArguments().thenReturn(mockWrapper); - - mockStatic(Cmd.class); - PowerMockito.when(Cmd.runBlockingCmd(any(), any(StringBuilder.class))).then(new Answer<Integer>() { - @Override - public Integer answer(InvocationOnMock invocation) throws Throwable { - StringBuilder logStringBuilder = invocation.getArgument(1); - logStringBuilder.append("bt-pan device found"); - return 0; - } - }); - - TetheringObservable.setBluetoothTethering(false); - TetheringStateManager.getInstance().init(mockContext); - TetheringStateManager manager = TetheringStateManager.getInstance(); - assertTrue(observable.isBluetoothTetheringEnabled()); - } - */ - - @Test - public void updateWifiTetheringState_ignoreFailingWifiAPReflection_keepsOldValueTrue() throws Exception { - WifiManagerWrapper mockWrapper = mock(WifiManagerWrapper.class); - when(mockWrapper.isWifiAPEnabled()).thenThrow(new NoSuchMethodException()); - PowerMockito.whenNew(WifiManagerWrapper.class).withAnyArguments().thenReturn(mockWrapper); - - TetheringObservable.setWifiTethering(true, "192.168.43.0/24", "wlan0"); - TetheringStateManager.getInstance().init(mockContext); - TetheringStateManager manager = TetheringStateManager.getInstance(); - assertTrue(observable.isWifiTetheringEnabled()); - } - - @Test - public void updateWifiTetheringState_ignoreFailingWifiAPReflection_keepsOldValueFalse() throws Exception { - WifiManagerWrapper mockWrapper = mock(WifiManagerWrapper.class); - when(mockWrapper.isWifiAPEnabled()).thenThrow(new NoSuchMethodException()); - PowerMockito.whenNew(WifiManagerWrapper.class).withAnyArguments().thenReturn(mockWrapper); - - TetheringObservable.setWifiTethering(false, "", ""); - TetheringStateManager.getInstance().init(mockContext); - TetheringStateManager manager = TetheringStateManager.getInstance(); - assertFalse(observable.isWifiTetheringEnabled()); - } - - @Test - public void updateWifiTetheringState_WifiApReflectionWithoutException_changeValueToTrue() throws Exception { - WifiManagerWrapper mockWrapper = mock(WifiManagerWrapper.class); - when(mockWrapper.isWifiAPEnabled()).thenReturn(true); - PowerMockito.whenNew(WifiManagerWrapper.class).withAnyArguments().thenReturn(mockWrapper); - - TetheringObservable.setWifiTethering(false, "", ""); - TetheringStateManager.getInstance().init(mockContext); - TetheringStateManager manager = TetheringStateManager.getInstance(); - assertTrue(observable.isWifiTetheringEnabled()); - } - - @Test - public void updateWifiTetheringState_WifiApReflectionWithoutException_changeValueToFalse() throws Exception { - WifiManagerWrapper mockWrapper = mock(WifiManagerWrapper.class); - when(mockWrapper.isWifiAPEnabled()).thenReturn(false); - PowerMockito.whenNew(WifiManagerWrapper.class).withAnyArguments().thenReturn(mockWrapper); - - TetheringObservable.setWifiTethering(true, "", ""); - TetheringStateManager.getInstance().init(mockContext); - TetheringStateManager manager = TetheringStateManager.getInstance(); - assertFalse(observable.isWifiTetheringEnabled()); } @Test public void testGetWifiAddressRangee_keepsLastSeenAddressAndInterface() throws Exception { - WifiManagerWrapper mockWrapper = mock(WifiManagerWrapper.class); - when(mockWrapper.isWifiAPEnabled()).thenReturn(true); - PowerMockito.whenNew(WifiManagerWrapper.class).withAnyArguments().thenReturn(mockWrapper); - //WifiTethering was switched on TetheringObservable.setWifiTethering(true, "192.168.40.0/24", "wlan0"); diff --git a/app/src/test/java/se/leap/bitmaskclient/tor/TorStatusObservableTest.java b/app/src/test/java/se/leap/bitmaskclient/tor/TorStatusObservableTest.java new file mode 100644 index 00000000..10dbf6cb --- /dev/null +++ b/app/src/test/java/se/leap/bitmaskclient/tor/TorStatusObservableTest.java @@ -0,0 +1,48 @@ +package se.leap.bitmaskclient.tor; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import android.content.Context; +import android.content.pm.PackageManager; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Answers; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; + +@RunWith(MockitoJUnitRunner.class) +public class TorStatusObservableTest { + + + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + private Context mockContext; + + + + @Test + public void testPropertyChange() throws PackageManager.NameNotFoundException { + TorStatusObservable statusObservable = TorStatusObservable.getInstance(); + int i = 10; + PropertyChangeListener propertyChangeListener = new PropertyChangeListener() { + @Override + public void propertyChange(PropertyChangeEvent evt) { + assertEquals(12, TorStatusObservable.getBootstrapProgress()); + assertEquals("a logkey", TorStatusObservable.getLastLogs().lastElement()); + assertNull(evt.getOldValue()); + TorStatusObservable.getInstance().deleteObserver(this); + } + }; + + TorStatusObservable.updateState(mockContext, "STARTING", 10, "a logkey"); + TorStatusObservable.updateState(mockContext, "STARTING", 11, "a log 2"); + TorStatusObservable.getInstance().addObserver(propertyChangeListener); + TorStatusObservable.updateState(mockContext, "STARTING", 12, "a log 3"); + + } + +}
\ No newline at end of file |