Skip to content

Commit

Permalink
[telemetry] Fix crash when using obtainCellularNetworkType
Browse files Browse the repository at this point in the history
`TelemetryUtils.obtainCellularNetworkType` is annotated with @nonnull
annotation meaning that this function should never return a null.
However before this change there was a way to return a null when
returned underlying network type is not covered in the `NETWORKS` map.
  • Loading branch information
mr1sunshine committed Dec 16, 2021
1 parent 92b695d commit 442bd99
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,16 +1,33 @@
package com.mapbox.android.telemetry;

import android.content.Context;
import android.telephony.TelephonyManager;

import androidx.test.platform.app.InstrumentationRegistry;

import org.junit.Assert;
import org.junit.Test;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.ArgumentMatchers.any;

public class TestCellularNetworkType {
@Test
public void testCellularNetworkType() {
Context context = InstrumentationRegistry.getInstrumentation().getContext();
String cellularNetworkType = TelemetryUtils.obtainCellularNetworkType(context);
Assert.assertFalse(cellularNetworkType.isEmpty());
}

@Test
public void testUnknownNetworkType() {
Context mockedContext = mock(Context.class);
TelephonyManager mockedTelephonyManager = mock(TelephonyManager.class);
when(mockedContext.getSystemService(any(String.class))).thenReturn(mockedTelephonyManager);
when(mockedTelephonyManager.getDataNetworkType()).thenReturn(TelephonyManager.NETWORK_TYPE_UNKNOWN);
Assert.assertEquals(TelemetryUtils.obtainCellularNetworkType(mockedContext), "Unknown");
when(mockedTelephonyManager.getDataNetworkType()).thenReturn(Integer.MAX_VALUE);
Assert.assertEquals(TelemetryUtils.obtainCellularNetworkType(mockedContext), "Unknown");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,11 @@ public static String obtainCellularNetworkType(Context context) {
} else {
output = telephonyManager.getNetworkType();
}
return NETWORKS.get(output);
String foundTelemetryType = NETWORKS.get(output);
if (foundTelemetryType == null) {
return UNKNOWN;
}
return foundTelemetryType;
}

public static String obtainCurrentDate() {
Expand Down

0 comments on commit 442bd99

Please sign in to comment.