diff --git a/app/build.gradle b/app/build.gradle index e699ba79..58123488 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -86,7 +86,6 @@ ext { androidTestVersion = "0.5" firebaseVersion = "11.6.2" jUnitVersion = "4.12" - powerMockVersion = "1.7.3" okHttpVersion = "3.9.0" retroFitVersion = "2.3.0" roboElectricVersion = "3.4.2" @@ -130,13 +129,6 @@ dependencies { testCompile "org.robolectric:robolectric:${roboElectricVersion}" testCompile "org.mockito:mockito-core:${mockitoCoreVersion}" - // Setup for local tests. - testCompile "org.powermock:powermock-module-junit4:${powerMockVersion}" - testCompile "org.powermock:powermock-module-junit4-rule:${powerMockVersion}" - testCompile "org.powermock:powermock-api-mockito2:${powerMockVersion}" - testCompile "org.powermock:powermock-classloading-xstream:${powerMockVersion}" - testCompile "com.squareup.okhttp3:mockwebserver:${okHttpVersion}" - // Setup for instrumented tests. androidTestCompile "com.android.support.test:runner:${androidTestVersion}" androidTestCompile "com.android.support.test:rules:${androidTestVersion}" diff --git a/app/src/main/java/com/voipgrid/vialer/t9/T9NameMatcher.java b/app/src/main/java/com/voipgrid/vialer/t9/T9NameMatcher.java index 6f2fcf83..91572ed6 100644 --- a/app/src/main/java/com/voipgrid/vialer/t9/T9NameMatcher.java +++ b/app/src/main/java/com/voipgrid/vialer/t9/T9NameMatcher.java @@ -35,11 +35,11 @@ public static boolean T9QueryMatchesName(String query, String displayName) { * @return Name with tags. */ public static String highlightMatchedPart(String t9Query, String displayName) { - ArrayList possibleQueries = T9Query.generateT9NameQueries(displayName); + String queryOfWholeName = possibleQueries.get(0); - int start = queryOfWholeName.indexOf(t9Query); + int start = adjustStartBasedOnSpaces(displayName, queryOfWholeName.indexOf(t9Query)); int end = start + t9Query.length(); // Add a empty space behind the displayname to be able to substring untill the last char @@ -47,6 +47,22 @@ public static String highlightMatchedPart(String t9Query, String displayName) { return placeBoldingTags(displayName + " ", start, end, end-start); } + /** + * Calculates the number of spaces in the display name before the start value and increases + * start based on this value. + * + * @param displayName + * @param start + * @return The value of start adjusted based on the number of spaces. + */ + private static int adjustStartBasedOnSpaces(String displayName, int start) { + String substr = displayName.substring(0, start); + + int spaceCount = substr.length() - substr.replace(" ", "").length(); + + return start + spaceCount; + } + /** * Recursively builds a string with the correct highlighting. */ diff --git a/app/src/test/java/com/voipgrid/vialer/test/AccountActivityTest.java b/app/src/test/java/com/voipgrid/vialer/test/AccountActivityTest.java deleted file mode 100644 index 8e96e02d..00000000 --- a/app/src/test/java/com/voipgrid/vialer/test/AccountActivityTest.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.voipgrid.vialer.test; - -import android.app.Activity; -import android.widget.EditText; - -import com.voipgrid.vialer.AccountActivity; -import com.voipgrid.vialer.BuildConfig; -import com.voipgrid.vialer.R; -import com.voipgrid.vialer.api.models.PhoneAccount; -import com.voipgrid.vialer.api.models.SystemUser; -import com.voipgrid.vialer.util.JsonStorage; - -import org.junit.Before; -import org.junit.Test; -import org.robolectric.Robolectric; -import org.robolectric.RuntimeEnvironment; - -import static org.junit.Assert.assertTrue; - -/** - * Test AccountActivity behaviour. - */ -public class AccountActivityTest extends RobolectricAbstractTest { - - /** - * Setup dependencies for tests. - */ - @Before - public void setUp() { - JsonStorage jsonStorage = new JsonStorage(RuntimeEnvironment.application); - SystemUser systemUser = new SystemUser(); - PhoneAccount phoneAccount = new PhoneAccount(); - - systemUser.setMobileNumber("0508009000"); - systemUser.setOutgoingCli("0508009000"); - - phoneAccount.setAccountId("123456789"); - - jsonStorage.save(systemUser); - jsonStorage.save(phoneAccount); - } - - /** - * Test if the mobile number EditText is filled. - */ - @Test - public void mobileNumberFilledTest() { - Activity activity = Robolectric.setupActivity(AccountActivity.class); - - EditText editText = (EditText) activity.findViewById(R.id.account_mobile_number_edit_text); - - String filledText = editText.getText().toString(); - - assertTrue(filledText.equals("0508009000")); - } - - /** - * Test if the outgoing cli EditText is filled. - */ - @Test - public void outgoingCliFilledTest() { - Activity activity = Robolectric.setupActivity(AccountActivity.class); - - EditText editText = (EditText) activity.findViewById(R.id.account_outgoing_number_edit_text); - - String filledText = editText.getText().toString(); - - assertTrue(filledText.equals("0508009000")); - } -} diff --git a/app/src/test/java/com/voipgrid/vialer/test/PhoneNumberUtilsTest.java b/app/src/test/java/com/voipgrid/vialer/test/PhoneNumberUtilsTest.java index 0aa7b9ef..3383ae38 100644 --- a/app/src/test/java/com/voipgrid/vialer/test/PhoneNumberUtilsTest.java +++ b/app/src/test/java/com/voipgrid/vialer/test/PhoneNumberUtilsTest.java @@ -1,13 +1,13 @@ package com.voipgrid.vialer.test; -import com.voipgrid.vialer.util.PhoneNumberUtils; - -import org.junit.Test; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import com.voipgrid.vialer.util.PhoneNumberUtils; + +import org.junit.Test; + /** * PhoneNumberUtilsTest class for testing PhoneNumberUtils functions. */ diff --git a/app/src/test/java/com/voipgrid/vialer/test/RobolectricAbstractTest.java b/app/src/test/java/com/voipgrid/vialer/test/RobolectricAbstractTest.java deleted file mode 100644 index 1948f47f..00000000 --- a/app/src/test/java/com/voipgrid/vialer/test/RobolectricAbstractTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.voipgrid.vialer.test; - -import com.voipgrid.vialer.BuildConfig; - -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; -import org.robolectric.annotation.Config; - -/** - * Abstract test class for tests that require Robolectric. - */ -@RunWith(RobolectricTestRunner.class) -@Config(constants = BuildConfig.class, sdk = 21) -public abstract class RobolectricAbstractTest { -} diff --git a/app/src/test/java/com/voipgrid/vialer/test/RobolectricPowerMockAbstractTest.java b/app/src/test/java/com/voipgrid/vialer/test/RobolectricPowerMockAbstractTest.java deleted file mode 100644 index f059349e..00000000 --- a/app/src/test/java/com/voipgrid/vialer/test/RobolectricPowerMockAbstractTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.voipgrid.vialer.test; - -import org.junit.Rule; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.modules.junit4.rule.PowerMockRule; - -/** - * Abstract test class for tests that require Robolectric and PowerMock. - */ -@PowerMockIgnore({ "org.mockito.*", "org.robolectric.*", "android.*", "retrofit2.*", - "com.squareup.*", "com.google.*", "okio.*", "okhttp3.*" }) -public abstract class RobolectricPowerMockAbstractTest extends RobolectricAbstractTest { - - @Rule - public PowerMockRule rule = new PowerMockRule(); -} diff --git a/app/src/test/java/com/voipgrid/vialer/test/logging/LogComposerTest.java b/app/src/test/java/com/voipgrid/vialer/test/logging/LogComposerTest.java index 706a1aa2..1a6eb2a1 100644 --- a/app/src/test/java/com/voipgrid/vialer/test/logging/LogComposerTest.java +++ b/app/src/test/java/com/voipgrid/vialer/test/logging/LogComposerTest.java @@ -1,5 +1,8 @@ package com.voipgrid.vialer.test.logging; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + import com.voipgrid.vialer.logging.DeviceInformation; import com.voipgrid.vialer.logging.LogComposer; @@ -9,9 +12,6 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; -import static org.junit.Assert.*; -import static org.mockito.Mockito.when; - @RunWith(MockitoJUnitRunner.class) public class LogComposerTest { diff --git a/app/src/test/java/com/voipgrid/vialer/test/logging/VialerLoggerTest.java b/app/src/test/java/com/voipgrid/vialer/test/logging/VialerLoggerTest.java index c09cc0fc..de77e75f 100644 --- a/app/src/test/java/com/voipgrid/vialer/test/logging/VialerLoggerTest.java +++ b/app/src/test/java/com/voipgrid/vialer/test/logging/VialerLoggerTest.java @@ -1,5 +1,11 @@ package com.voipgrid.vialer.test.logging; +import static org.mockito.ArgumentMatchers.anyObject; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import android.content.Context; import com.logentries.logger.AsyncLoggingWorker; @@ -12,12 +18,6 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; -import static org.mockito.ArgumentMatchers.anyObject; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - @RunWith(MockitoJUnitRunner.class) public class VialerLoggerTest { @@ -63,4 +63,4 @@ public void it_handles_the_factory_not_being_able_to_create_an_environment() { classUnderTest.initialize(new String[] {"invalidToken"}); classUnderTest.log("A log message"); } -} \ No newline at end of file +} diff --git a/app/src/test/java/com/voipgrid/vialer/test/logging/formatting/PayloadAnonymizerTest.java b/app/src/test/java/com/voipgrid/vialer/test/logging/formatting/PayloadAnonymizerTest.java index f74344a3..4cb017eb 100644 --- a/app/src/test/java/com/voipgrid/vialer/test/logging/formatting/PayloadAnonymizerTest.java +++ b/app/src/test/java/com/voipgrid/vialer/test/logging/formatting/PayloadAnonymizerTest.java @@ -1,12 +1,12 @@ package com.voipgrid.vialer.test.logging.formatting; +import static org.junit.Assert.assertFalse; + import com.voipgrid.vialer.fcm.FcmMessagingService; import com.voipgrid.vialer.logging.formatting.formatters.PayloadAnonymizer; import org.junit.Test; -import static org.junit.Assert.*; - public class PayloadAnonymizerTest { private String dummyPayloadLog = "FcmMessagingService Payload: {message_start_time=1.517230273029763E9, caller_id=, phonenumber=+41501109999, type=call, unique_key=209779d101c25d5d486304900cc8e75e, response_api=https://vialerpush.voipgrid.nl/api/call-response/}"; diff --git a/app/src/test/java/com/voipgrid/vialer/test/logging/formatting/SipLogAnonymizerTest.java b/app/src/test/java/com/voipgrid/vialer/test/logging/formatting/SipLogAnonymizerTest.java index d0ee669b..ac6d1f7b 100644 --- a/app/src/test/java/com/voipgrid/vialer/test/logging/formatting/SipLogAnonymizerTest.java +++ b/app/src/test/java/com/voipgrid/vialer/test/logging/formatting/SipLogAnonymizerTest.java @@ -1,13 +1,13 @@ package com.voipgrid.vialer.test.logging.formatting; +import static org.junit.Assert.assertFalse; + import com.voipgrid.vialer.logging.formatting.formatters.PayloadAnonymizer; import com.voipgrid.vialer.logging.formatting.formatters.SipLogAnonymizer; import com.voipgrid.vialer.sip.SipService; import org.junit.Test; -import static org.junit.Assert.*; - public class SipLogAnonymizerTest { diff --git a/app/src/test/java/com/voipgrid/vialer/test/t9/T9NameMatcherTest.java b/app/src/test/java/com/voipgrid/vialer/test/t9/T9NameMatcherTest.java index caf52962..56e704e8 100644 --- a/app/src/test/java/com/voipgrid/vialer/test/t9/T9NameMatcherTest.java +++ b/app/src/test/java/com/voipgrid/vialer/test/t9/T9NameMatcherTest.java @@ -1,12 +1,13 @@ package com.voipgrid.vialer.test.t9; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import com.voipgrid.vialer.t9.T9NameMatcher; import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - /** * Class for testing the T9NameMatcher class. */ @@ -50,44 +51,29 @@ public void T9QueryMatchesNameTest() { @Test public void highlightMatchedPartTest() { - String name = "Henk van den Berg"; - String query; - String expectedResult; - - // hen. - query = "436"; - expectedResult = "Henk van den Berg"; - assertTrue(expectedResult.equals(T9NameMatcher.highlightMatchedPart(query, name))); + t9matcherTest("436", "Henk van den Berg "); // henk. - query = "4365"; - expectedResult = "Henk van den Berg"; - assertTrue(expectedResult.equals(T9NameMatcher.highlightMatchedPart(query, name))); + t9matcherTest("4365", "Henk van den Berg "); // van. - query = "826"; - expectedResult = "Henk van den Berg"; - assertTrue(expectedResult.equals(T9NameMatcher.highlightMatchedPart(query, name))); + t9matcherTest("826", "Henk van den Berg "); // vande. - query = "82633"; - expectedResult = "Henk van den Berg"; - assertTrue(expectedResult.equals(T9NameMatcher.highlightMatchedPart(query, name))); + t9matcherTest("82633", "Henk van den Berg "); // den. - query = "336"; - expectedResult = "Henk van den Berg"; - assertTrue(expectedResult.equals(T9NameMatcher.highlightMatchedPart(query, name))); + t9matcherTest("336", "Henk van den Berg "); // denb. - query = "3362"; - expectedResult = "Henk van den Berg"; - assertTrue(expectedResult.equals(T9NameMatcher.highlightMatchedPart(query, name))); + t9matcherTest("3362", "Henk van den Berg "); // berg. - query = "2374"; - expectedResult = "Henk van den Berg"; - assertTrue(expectedResult.equals(T9NameMatcher.highlightMatchedPart(query, name))); + t9matcherTest("2374", "Henk van den Berg "); } + private void t9matcherTest(String query, String expected) { + String name = "Henk van den Berg"; + assertEquals(expected, T9NameMatcher.highlightMatchedPart(query, name)); + } } diff --git a/app/src/test/java/com/voipgrid/vialer/test/t9/T9QueryTest.java b/app/src/test/java/com/voipgrid/vialer/test/t9/T9QueryTest.java index 54bd74a4..047142d4 100644 --- a/app/src/test/java/com/voipgrid/vialer/test/t9/T9QueryTest.java +++ b/app/src/test/java/com/voipgrid/vialer/test/t9/T9QueryTest.java @@ -1,13 +1,13 @@ package com.voipgrid.vialer.test.t9; +import static org.junit.Assert.assertEquals; + import com.voipgrid.vialer.t9.T9Query; import org.junit.Test; import java.util.ArrayList; -import static org.junit.Assert.assertEquals; - public class T9QueryTest { /** diff --git a/app/src/test/java/com/voipgrid/vialer/test/util/JsonStorageTest.java b/app/src/test/java/com/voipgrid/vialer/test/util/JsonStorageTest.java deleted file mode 100644 index cd1f3689..00000000 --- a/app/src/test/java/com/voipgrid/vialer/test/util/JsonStorageTest.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.voipgrid.vialer.test.util; - -import android.content.SharedPreferences; -import android.preference.PreferenceManager; - -import com.voipgrid.vialer.api.models.SystemUser; -import com.voipgrid.vialer.test.RobolectricAbstractTest; -import com.voipgrid.vialer.util.JsonStorage; - -import org.junit.Test; -import org.robolectric.RuntimeEnvironment; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -/** - * Tests for the JsonStorage class. - */ -public class JsonStorageTest extends RobolectricAbstractTest { - - /** - * Test the JSON storage only clears JSON Classes from SharedPreferences. - */ - @Test - public void clearTest() { - JsonStorage jsonStorage = new JsonStorage(RuntimeEnvironment.application); - - // Create class used in JSON storage. - SystemUser systemUser = new SystemUser(); - systemUser.setMobileNumber("0508009000"); - systemUser.setOutgoingCli("0508009000"); - jsonStorage.save(systemUser); - - // Check if properly saved. - assertTrue(jsonStorage.has(SystemUser.class)); - - // Create setting not used in JSON storage. - SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences( - RuntimeEnvironment.application); - pref.edit().putString("setting_key", "setting_value").apply(); - - // Clear the JSON storage. - jsonStorage.clear(); - - // Check if SystemUser is gone. - assertFalse(jsonStorage.has(SystemUser.class)); - // Check if random settings still exists. - assertTrue(pref.contains("setting_key")); - } -} diff --git a/app/src/test/java/com/voipgrid/vialer/test/util/MiddlewareHelperTest.java b/app/src/test/java/com/voipgrid/vialer/test/util/MiddlewareHelperTest.java deleted file mode 100644 index c649ef98..00000000 --- a/app/src/test/java/com/voipgrid/vialer/test/util/MiddlewareHelperTest.java +++ /dev/null @@ -1,174 +0,0 @@ -package com.voipgrid.vialer.test.util; - -import android.content.Context; -import android.content.SharedPreferences; -import android.preference.PreferenceManager; - -import com.voipgrid.vialer.Preferences; -import com.voipgrid.vialer.api.models.PhoneAccount; -import com.voipgrid.vialer.api.models.SystemUser; -import com.voipgrid.vialer.test.RobolectricPowerMockAbstractTest; -import com.voipgrid.vialer.util.JsonStorage; -import com.voipgrid.vialer.middleware.MiddlewareHelper; - -import org.junit.Before; -import org.junit.Test; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.robolectric.RuntimeEnvironment; - -import okhttp3.HttpUrl; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import okhttp3.mockwebserver.RecordedRequest; - -import static com.voipgrid.vialer.middleware.MiddlewareConstants.REGISTRATION_STATUS; -import static com.voipgrid.vialer.middleware.MiddlewareConstants.STATUS_REGISTERED; -import static com.voipgrid.vialer.middleware.MiddlewareConstants.STATUS_UNREGISTERED; -import static org.junit.Assert.*; -import static org.powermock.api.mockito.PowerMockito.*; - -/** - * Tests for the MiddlewareHelper class. - */ -@PrepareForTest(MiddlewareHelper.class) -public class MiddlewareHelperTest extends RobolectricPowerMockAbstractTest { - - /** - * Setup dependencies for tests. - */ - @Before - public void setUp() { - JsonStorage jsonStorage = new JsonStorage(RuntimeEnvironment.application); - SystemUser systemUser = new SystemUser(); - PhoneAccount phoneAccount = new PhoneAccount(); - - // Systemuser with username and password. - systemUser.setFirstName("VoIP"); - systemUser.setLastName("GRID"); - systemUser.setEmail("info@example.com"); - systemUser.setPassword("password"); - - // Phone account for registration. - phoneAccount.setAccountId("123456789"); - - jsonStorage.save(systemUser); - jsonStorage.save(phoneAccount); - - // Make sure all requirements are met for SIP. - Preferences prefs = new Preferences(RuntimeEnvironment.application); - prefs.setSipPermission(true); - prefs.setSipEnabled(true); - } - - /** - * Test registering at the middleware. - * @throws Exception - */ - @Test - public void middlewareRegisterTest() throws Exception { - // Create fake web server. - MockWebServer server = new MockWebServer(); - // Make sure the server gives a 200 response the first time. - server.enqueue(new MockResponse().setResponseCode(200)); - - // Start the web server. - server.start(); - - // Get the URL to talk to the fake server. - HttpUrl fakeServerUrl = server.url(""); - - Context context = RuntimeEnvironment.application; - String fakePushToken = "APA91bHPRgkF3JUikC4ENAHEeMrd41Zxv3hVZjC9KtT8OvPVGJ-hQMRKR" + - "rZuJAEcl7B338qju59zJMjw2DELjzEvxwYv7hH5Ynpc1ODQ0aT4U4OFEeco8ohsN5PjL1iC2" + - "dNtk2BAokeMCg2ZXKqpc8FXKmhX94kIxQ"; - - // Mock the method that returns the api base URL to return the fake server URL. - spy(MiddlewareHelper.class); - stub(PowerMockito.method(MiddlewareHelper.class, "getBaseApiUrl", Context.class)) - .toReturn(fakeServerUrl.toString()); - - // Make sure the mocked method returns the right value. - assertTrue(MiddlewareHelper.getBaseApiUrl(context).equals(fakeServerUrl.toString())); - - // Register call. - MiddlewareHelper.register(context, fakePushToken); - - // Check the if the request that was made meets requirements in the middleware - // api docs. - RecordedRequest request = server.takeRequest(); - - // Check if auth header is set. - assertNotNull(request.getHeader("Authorization")); - - String body = request.getBody().readUtf8(); - - // Make sure required values are present. - assertTrue(body.contains("sip_user_id")); - assertTrue(body.contains("token")); - assertTrue(body.contains("app")); - - // Check registration status. - SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); - int status = preferences.getInt(REGISTRATION_STATUS, 10); - - assertEquals(STATUS_REGISTERED, status); - - // Shutdown the fake web server. - server.shutdown(); - } - - /** - * Test registering at the middleware. - * @throws Exception - */ - @Test - public void middlewareUnregisterTest() throws Exception { - // Create fake web server. - MockWebServer server = new MockWebServer(); - // Make sure the server gives a 200 response the first time. - server.enqueue(new MockResponse().setResponseCode(200).setBody("")); - - // Start the web server. - server.start(); - - // Get the URL to talk to the fake server. - HttpUrl fakeServerUrl = server.url(""); - - Context context = RuntimeEnvironment.application; - - // Mock the method that returns the api base URL to return the fake server URL. - spy(MiddlewareHelper.class); - stub(PowerMockito.method(MiddlewareHelper.class, "getBaseApiUrl", Context.class)) - .toReturn(fakeServerUrl.toString()); - - // Make sure the mocked method returns the right value. - assertTrue(MiddlewareHelper.getBaseApiUrl(context).equals(fakeServerUrl.toString())); - - // Unregister call. - MiddlewareHelper.unregister(context); - - // Check the if the request that was made meets requirements in the middleware - // api docs. - RecordedRequest request = server.takeRequest(); - - assertNotNull(request.getHeader("Authorization")); - - String body = request.getBody().readUtf8(); - - // Make sure required values are present. - assertTrue(body.contains("sip_user_id")); - assertTrue(body.contains("token")); - assertTrue(body.contains("app")); - - // Check registration status. - SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); - int status = preferences.getInt(REGISTRATION_STATUS, 10); - - assertTrue(status == STATUS_UNREGISTERED); - - // Shutdown the fake web server. - server.shutdown(); - } - -} diff --git a/app/src/test/java/com/voipgrid/vialer/test/util/PhoneAccountHelperTest.java b/app/src/test/java/com/voipgrid/vialer/test/util/PhoneAccountHelperTest.java deleted file mode 100644 index dfa9c068..00000000 --- a/app/src/test/java/com/voipgrid/vialer/test/util/PhoneAccountHelperTest.java +++ /dev/null @@ -1,137 +0,0 @@ -package com.voipgrid.vialer.test.util; - -import android.content.Context; - -import com.voipgrid.vialer.Preferences; -import com.voipgrid.vialer.api.ServiceGenerator; -import com.voipgrid.vialer.api.models.PhoneAccount; -import com.voipgrid.vialer.api.models.SystemUser; -import com.voipgrid.vialer.test.RobolectricPowerMockAbstractTest; -import com.voipgrid.vialer.util.JsonStorage; -import com.voipgrid.vialer.middleware.MiddlewareHelper; -import com.voipgrid.vialer.util.PhoneAccountHelper; - -import org.junit.Before; -import org.junit.Test; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.robolectric.RuntimeEnvironment; - -import okhttp3.HttpUrl; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import okhttp3.mockwebserver.RecordedRequest; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.powermock.api.mockito.PowerMockito.spy; -import static org.powermock.api.support.membermodification.MemberModifier.stub; - -/** - * PhoneAccountHelperTest tests the function provided by the PhoneAccountHelper class. - */ -@PrepareForTest({ServiceGenerator.class, MiddlewareHelper.class}) -public class PhoneAccountHelperTest extends RobolectricPowerMockAbstractTest { - - /** - * Setup dependencies for tests. - */ - @Before - public void setUp() { - JsonStorage jsonStorage = new JsonStorage(RuntimeEnvironment.application); - SystemUser systemUser = new SystemUser(); - - // Systemuser with username and password. - systemUser.setEmail("info@example.com"); - systemUser.setPassword("password"); - - jsonStorage.save(systemUser); - - // Make sure all requirements are met for SIP. - Preferences prefs = new Preferences(RuntimeEnvironment.application); - prefs.setSipPermission(true); - prefs.setSipEnabled(true); - } - - /** - * Function to return a JSON string like the api. - * @return - */ - private String createSystemuserResponse() { - return "{\"allow_app_account\": true, \"app_account\": " + - "\"/api/phoneaccount/basic/phoneaccount/24/\", \"change_password\": false, " + - "\"client\": \"/api/apprelation/client/11/\", \"description\": " + - "\"Generated systemuser\", \"email\": \"rbeer@leannonwest.info\", " + - "\"first_name\": \"Kaye\", \"groups\": [\"/api/permission/systemgroup/31/\"], " + - "\"id\": 21, \"language\": \"nl\", \"last_name\": \"Greenholt\", " + - "\"mobile_nr\": null, \"outgoing_cli\": \"+31508009000\", \"partner\": null, " + - "\"preposition\": \"\", \"resource_uri\": \"/api/permission/systemuser/21/\", " + - "\"session_expiry\": true, \"timezone\": null, \"token\": \"\"}"; - } - - /** - * Function to return a JSON string like the api. - * @return - */ - private String createPhoneAccountResponse() { - return "{\"account_id\": 129710001, " + - "\"active\": true, " + - "\"callerid_name\": \"Hilary Schroeder\", " + - "\"country\": \"/api/relation/country/nl/\", " + - "\"description\": \"Random phoneaccount 1\", " + - "\"internal_number\": 200, " + - "\"password\": \"NjhtjhGHfgghyjhg\"}"; - } - - /** - * Test the getLinkedPhoneAccount function on the PhoneAccountHelperClass. - * @throws Exception - */ - @Test - public void getLinkedPhoneAccountTest() throws Exception { - // Create fake web server. - MockWebServer server = new MockWebServer(); - - // This test will make 2 requests: - // 1: To get the systemuser. - // 2: To get the phone account linked on the systemuser. - server.enqueue(new MockResponse().setResponseCode(200).setBody(createSystemuserResponse())); - server.enqueue(new MockResponse().setResponseCode(200).setBody(createPhoneAccountResponse())); - - // Start the web server. - server.start(); - - // Get the URL to talk to the fake server. - HttpUrl fakeServerUrl = server.url(""); - - Context context = RuntimeEnvironment.application; - - // Mock methods for getting urls to to return fake api urls. - spy(ServiceGenerator.class); - stub(PowerMockito.method(ServiceGenerator.class, "getVgApiUrl", Context.class)) - .toReturn(fakeServerUrl.toString()); - - // Make sure the mocked method returns the right value. - assertTrue(ServiceGenerator.getVgApiUrl(context).equals(fakeServerUrl.toString())); - - // Do api calls to get linked phone account. - PhoneAccountHelper helper = new PhoneAccountHelper(context); - PhoneAccount phoneAccount = helper.getLinkedPhoneAccount(); - - // Get both requests. - RecordedRequest systemuserRequest = server.takeRequest(); - RecordedRequest phoneAccountRequest = server.takeRequest(); - - // Make sure they have auth headers. - assertNotNull(systemuserRequest.getHeader("Authorization")); - assertNotNull(phoneAccountRequest.getHeader("Authorization")); - - // Check if the phone account is returned as object. - assertTrue(phoneAccount.getAccountId().equals("129710001")); - assertTrue(phoneAccount.getNumber().equals("200")); - assertTrue(phoneAccount.getPassword().equals("NjhtjhGHfgghyjhg")); - - server.shutdown(); - } - -}