From 41eff5e198e79f6393d787d82d3e1e04a61d4e81 Mon Sep 17 00:00:00 2001 From: Birk Skyum <74932975+birkskyum@users.noreply.github.com> Date: Wed, 11 Jan 2023 12:19:25 +0100 Subject: [PATCH] Port Android Unit tests to Kotlin (#681) --- .../mapboxsdk/annotations/AnnotationTest.java | 94 - .../mapboxsdk/annotations/AnnotationTest.kt | 83 + .../mapboxsdk/annotations/IconTest.java | 57 - .../mapbox/mapboxsdk/annotations/IconTest.kt | 53 + .../mapboxsdk/annotations/InfoWindowTest.java | 86 - .../mapboxsdk/annotations/InfoWindowTest.kt | 80 + .../mapboxsdk/annotations/MarkerTest.java | 160 -- .../mapboxsdk/annotations/MarkerTest.kt | 159 ++ .../mapboxsdk/annotations/PolygonTest.java | 75 - .../mapboxsdk/annotations/PolygonTest.kt | 66 + .../mapboxsdk/annotations/PolylineTest.java | 75 - .../mapboxsdk/annotations/PolylineTest.kt | 66 + .../attribution/AttributionParseTest.java | 288 --- .../attribution/AttributionParseTest.kt | 383 +++ .../mapboxsdk/camera/CameraPositionTest.java | 131 - .../mapboxsdk/camera/CameraPositionTest.kt | 182 ++ .../mapboxsdk/constants/AppConstant.java | 6 - .../mapbox/mapboxsdk/constants/AppConstant.kt | 5 + .../mapboxsdk/geometry/LatLngBoundsTest.java | 815 ------- .../mapboxsdk/geometry/LatLngBoundsTest.kt | 858 +++++++ .../mapboxsdk/geometry/LatLngSpanTest.java | 65 - .../mapboxsdk/geometry/LatLngSpanTest.kt | 67 + .../mapbox/mapboxsdk/geometry/LatLngTest.java | 286 --- .../mapbox/mapboxsdk/geometry/LatLngTest.kt | 283 +++ .../geometry/ProjectedMetersTest.java | 66 - .../mapboxsdk/geometry/ProjectedMetersTest.kt | 76 + .../mapboxsdk/geometry/VisibleRegionTest.java | 95 - .../mapboxsdk/geometry/VisibleRegionTest.kt | 98 + .../mapboxsdk/location/CompassEngineTest.java | 87 - .../mapboxsdk/location/CompassEngineTest.kt | 98 + .../LocationCameraControllerTest.java | 1264 ---------- .../location/LocationCameraControllerTest.kt | 2128 +++++++++++++++++ ...ocationComponentActivationOptionsTest.java | 160 -- .../LocationComponentActivationOptionsTest.kt | 158 ++ .../LocationComponentOptionsTest.java | 82 - .../location/LocationComponentOptionsTest.kt | 98 + .../location/LocationLayerControllerTest.java | 764 ------ .../location/LocationLayerControllerTest.kt | 1504 ++++++++++++ .../mapbox/mapboxsdk/location/UtilsTest.java | 28 - .../mapbox/mapboxsdk/location/UtilsTest.kt | 28 + .../mapboxsdk/maps/AnnotationManagerTest.java | 86 - .../mapboxsdk/maps/AnnotationManagerTest.kt | 104 + .../maps/AttributionDialogManagerTest.java | 36 - .../maps/AttributionDialogManagerTest.kt | 40 + .../mapboxsdk/maps/MapChangeReceiverTest.java | 586 ----- .../mapboxsdk/maps/MapChangeReceiverTest.kt | 714 ++++++ .../mapboxsdk/maps/MapTouchListenersTest.java | 158 -- .../mapboxsdk/maps/MapTouchListenersTest.kt | 181 ++ .../mapboxsdk/maps/MapboxMapOptionsTest.java | 217 -- .../mapboxsdk/maps/MapboxMapOptionsTest.kt | 321 +++ .../mapbox/mapboxsdk/maps/UiSettingsTest.java | 472 ---- .../mapbox/mapboxsdk/maps/UiSettingsTest.kt | 726 ++++++ .../style/expressions/ExpressionTest.java | 1598 ------------- .../style/expressions/ExpressionTest.kt | 1867 +++++++++++++++ 54 files changed, 10426 insertions(+), 7837 deletions(-) delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/AnnotationTest.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/AnnotationTest.kt delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/IconTest.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/IconTest.kt delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/InfoWindowTest.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/InfoWindowTest.kt delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/MarkerTest.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/MarkerTest.kt delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/PolygonTest.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/PolygonTest.kt delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/PolylineTest.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/PolylineTest.kt delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/attribution/AttributionParseTest.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/attribution/AttributionParseTest.kt delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/camera/CameraPositionTest.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/camera/CameraPositionTest.kt delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/constants/AppConstant.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/constants/AppConstant.kt delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngBoundsTest.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngBoundsTest.kt delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngSpanTest.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngSpanTest.kt delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngTest.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngTest.kt delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/ProjectedMetersTest.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/ProjectedMetersTest.kt delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/VisibleRegionTest.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/VisibleRegionTest.kt delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/CompassEngineTest.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/CompassEngineTest.kt delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationCameraControllerTest.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationCameraControllerTest.kt delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentActivationOptionsTest.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentActivationOptionsTest.kt delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentOptionsTest.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentOptionsTest.kt delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationLayerControllerTest.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationLayerControllerTest.kt delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/UtilsTest.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/UtilsTest.kt delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/AnnotationManagerTest.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/AnnotationManagerTest.kt delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/AttributionDialogManagerTest.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/AttributionDialogManagerTest.kt delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapChangeReceiverTest.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapChangeReceiverTest.kt delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapTouchListenersTest.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapTouchListenersTest.kt delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapboxMapOptionsTest.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapboxMapOptionsTest.kt delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/UiSettingsTest.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/UiSettingsTest.kt delete mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/style/expressions/ExpressionTest.java create mode 100644 platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/style/expressions/ExpressionTest.kt diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/AnnotationTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/AnnotationTest.java deleted file mode 100644 index f0c82b376..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/AnnotationTest.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import androidx.annotation.NonNull; - -import com.mapbox.mapboxsdk.maps.MapboxMap; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class AnnotationTest { - - @InjectMocks - private MapboxMap mapboxMap = mock(MapboxMap.class); - private Annotation annotation; - @NonNull - private Annotation compare = new Annotation() { - @Override - public long getId() { - return 1; - } - }; - - @Before - public void beforeTest() { - annotation = new Annotation() { - // empty child - }; - } - - @Test - public void testSanity() { - assertNotNull("markerOptions should not be null", annotation); - } - - @Test - public void testRemove() { - annotation.setId(1); - annotation.setMapboxMap(mapboxMap); - annotation.remove(); - verify(mapboxMap, times(1)).removeAnnotation(annotation); - } - - @Test - public void testRemoveUnboundMapboxMap() { - annotation.setId(1); - annotation.remove(); - verify(mapboxMap, times(0)).removeAnnotation(annotation); - } - - @Test - public void testCompareToEqual() { - annotation.setId(1); - assertEquals("conparable equal", 0, annotation.compareTo(compare)); - } - - @Test - public void testCompareToHigher() { - annotation.setId(3); - assertEquals("conparable higher", -1, annotation.compareTo(compare)); - } - - @Test - public void testCompareTolower() { - annotation.setId(0); - assertEquals("conparable lower", 1, annotation.compareTo(compare)); - } - - @Test - public void testEquals() { - Annotation holder = null; - assertFalse(annotation.equals(holder)); - holder = annotation; - assertTrue(annotation.equals(holder)); - assertFalse(annotation.equals(new Object())); - } - - @Test - public void testHashcode() { - int id = 1; - annotation.setId(id); - assertSame("hashcode should match", annotation.hashCode(), id); - } - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/AnnotationTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/AnnotationTest.kt new file mode 100644 index 000000000..f88a8d9c3 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/AnnotationTest.kt @@ -0,0 +1,83 @@ +package com.mapbox.mapboxsdk.annotations + +import com.mapbox.mapboxsdk.maps.MapboxMap +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.mockito.InjectMocks +import org.mockito.Mockito + +class AnnotationTest { + @InjectMocks + private val mapboxMap = Mockito.mock(MapboxMap::class.java) + private var annotation: Annotation? = null + private val compare: Annotation = object : Annotation() { + override fun getId(): Long { + return 1 + } + } + + @Before + fun beforeTest() { + annotation = object : Annotation() { // empty child + } + } + + @Test + fun testSanity() { + Assert.assertNotNull("markerOptions should not be null", annotation) + } + + @Test + fun testRemove() { + annotation!!.id = 1 + annotation!!.setMapboxMap(mapboxMap) + annotation!!.remove() + Mockito.verify(mapboxMap, Mockito.times(1)).removeAnnotation( + annotation!! + ) + } + + @Test + fun testRemoveUnboundMapboxMap() { + annotation!!.id = 1 + annotation!!.remove() + Mockito.verify(mapboxMap, Mockito.times(0)).removeAnnotation( + annotation!! + ) + } + + @Test + fun testCompareToEqual() { + annotation!!.id = 1 + Assert.assertEquals("conparable equal", 0, annotation!!.compareTo(compare).toLong()) + } + + @Test + fun testCompareToHigher() { + annotation!!.id = 3 + Assert.assertEquals("conparable higher", -1, annotation!!.compareTo(compare).toLong()) + } + + @Test + fun testCompareTolower() { + annotation!!.id = 0 + Assert.assertEquals("conparable lower", 1, annotation!!.compareTo(compare).toLong()) + } + + @Test + fun testEquals() { + var holder: Annotation? = null + Assert.assertFalse(annotation == holder) + holder = annotation + Assert.assertTrue(annotation == holder) + Assert.assertFalse(annotation == Any()) + } + + @Test + fun testHashcode() { + val id = 1 + annotation!!.id = id.toLong() + Assert.assertSame("hashcode should match", annotation.hashCode(), id) + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/IconTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/IconTest.java deleted file mode 100644 index 1c259af2d..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/IconTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import android.graphics.Bitmap; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import static junit.framework.Assert.assertEquals; -import static junit.framework.Assert.assertNotSame; -import static org.mockito.Mockito.when; - -public class IconTest { - - @Mock - Bitmap bitmap; - - @Before - public void beforeTest() { - MockitoAnnotations.initMocks(this); - when(bitmap.getConfig()).thenReturn(Bitmap.Config.ARGB_8888); - } - - @Test - public void testId() { - String id = "test"; - Icon icon = IconFactory.recreate(id, Bitmap.createBitmap(0, 0, Bitmap.Config.ALPHA_8)); - assertEquals("id should match", id, icon.getId()); - } - - @Test - public void testBitmap() { - Icon icon = IconFactory.recreate("test", bitmap); - assertEquals("bitmap should match", bitmap, icon.getBitmap()); - } - - @Test - public void testEquals() { - Icon icon1 = IconFactory.recreate("test", bitmap); - Icon icon2 = IconFactory.recreate("test", bitmap); - assertEquals("icons should not match", icon1, icon2); - } - - @Test - public void testEqualsObject() { - Icon icon = IconFactory.recreate("test", Bitmap.createBitmap(0, 0, Bitmap.Config.ALPHA_8)); - assertNotSame("icon should not match", new Object(), icon); - } - - @Test - public void testHashcode() { - Icon icon = IconFactory.recreate("test", bitmap); - long expectedHashcode = 31 * bitmap.hashCode() + "test".hashCode(); - assertEquals("hashcode should match", expectedHashcode, icon.hashCode()); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/IconTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/IconTest.kt new file mode 100644 index 000000000..421c7d1d7 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/IconTest.kt @@ -0,0 +1,53 @@ +package com.mapbox.mapboxsdk.annotations + +import android.graphics.Bitmap +import junit.framework.Assert +import org.junit.Before +import org.junit.Test +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.MockitoAnnotations + +class IconTest { + @Mock + var bitmap: Bitmap? = null + + @Before + fun beforeTest() { + MockitoAnnotations.initMocks(this) + Mockito.`when`(bitmap!!.config).thenReturn(Bitmap.Config.ARGB_8888) + } + + @Test + fun testId() { + val id = "test" + val icon = IconFactory.recreate(id, Bitmap.createBitmap(0, 0, Bitmap.Config.ALPHA_8)) + Assert.assertEquals("id should match", id, icon.id) + } + + @Test + fun testBitmap() { + val icon = IconFactory.recreate("test", bitmap!!) + Assert.assertEquals("bitmap should match", bitmap, icon.bitmap) + } + + @Test + fun testEquals() { + val icon1 = IconFactory.recreate("test", bitmap!!) + val icon2 = IconFactory.recreate("test", bitmap!!) + Assert.assertEquals("icons should not match", icon1, icon2) + } + + @Test + fun testEqualsObject() { + val icon = IconFactory.recreate("test", Bitmap.createBitmap(0, 0, Bitmap.Config.ALPHA_8)) + Assert.assertNotSame("icon should not match", Any(), icon) + } + + @Test + fun testHashcode() { + val icon = IconFactory.recreate("test", bitmap!!) + val expectedHashcode = (31 * bitmap.hashCode() + "test".hashCode()).toLong() + Assert.assertEquals("hashcode should match", expectedHashcode, icon.hashCode().toLong()) + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/InfoWindowTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/InfoWindowTest.java deleted file mode 100644 index 94b629860..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/InfoWindowTest.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import android.graphics.PointF; - -import com.mapbox.mapboxsdk.geometry.LatLng; -import com.mapbox.mapboxsdk.maps.MapView; -import com.mapbox.mapboxsdk.maps.MapboxMap; -import com.mapbox.mapboxsdk.maps.Projection; - -import org.junit.Test; -import org.mockito.InjectMocks; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class InfoWindowTest { - - @InjectMocks - MapView mMapView = mock(MapView.class); - - @InjectMocks - MapboxMap mMapboxMap = mock(MapboxMap.class); - - @Test - public void testSanity() { - InfoWindow infoWindow = new InfoWindow(mMapView, mMapboxMap); - assertNotNull("infoWindow should exist", infoWindow); - } - - @Test - public void testBoundMarker() { - MarkerOptions markerOptions = new MarkerOptions(); - Marker marker = markerOptions.position(new LatLng()).getMarker(); - InfoWindow infoWindow = new InfoWindow(mMapView, mMapboxMap).setBoundMarker(marker); - assertEquals("marker should match", marker, infoWindow.getBoundMarker()); - } - - @Test - public void testClose() { - InfoWindow infoWindow = new InfoWindow(mMapView, mMapboxMap); - infoWindow.close(); - assertEquals("infowindow should not be visible", false, infoWindow.isVisible()); - } - - - @Test - public void testOpen() { - LatLng latLng = new LatLng(0, 0); - Projection projection = mock(Projection.class); - when(mMapboxMap.getProjection()).thenReturn(projection); - when(projection.toScreenLocation(latLng)).thenReturn(new PointF(0, 0)); - - InfoWindow infoWindow = new InfoWindow(mMapView, mMapboxMap); - infoWindow.open(mMapView, new MarkerOptions().position(new LatLng()).getMarker(), latLng, 0, 0); - assertEquals("infowindow should not be visible", true, infoWindow.isVisible()); - } - - @Test - public void testOpenClose() { - LatLng latLng = new LatLng(0, 0); - Projection projection = mock(Projection.class); - when(mMapboxMap.getProjection()).thenReturn(projection); - when(projection.toScreenLocation(latLng)).thenReturn(new PointF(0, 0)); - - InfoWindow infoWindow = new InfoWindow(mMapView, mMapboxMap); - infoWindow.open(mMapView, new MarkerOptions().position(new LatLng()).getMarker(), latLng, 0, 0); - infoWindow.close(); - assertEquals("infowindow should not be visible", false, infoWindow.isVisible()); - } - - - @Test - public void testUpdate() { - LatLng latLng = new LatLng(0, 0); - Projection projection = mock(Projection.class); - when(mMapboxMap.getProjection()).thenReturn(projection); - when(projection.toScreenLocation(latLng)).thenReturn(new PointF(0, 0)); - - InfoWindow infoWindow = new InfoWindow(mMapView, mMapboxMap); - infoWindow.open(mMapView, new MarkerOptions().position(latLng).getMarker(), latLng, 0, 0); - infoWindow.update(); - } - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/InfoWindowTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/InfoWindowTest.kt new file mode 100644 index 000000000..3ce882283 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/InfoWindowTest.kt @@ -0,0 +1,80 @@ +package com.mapbox.mapboxsdk.annotations + +import android.graphics.PointF +import com.mapbox.mapboxsdk.geometry.LatLng +import com.mapbox.mapboxsdk.maps.MapView +import com.mapbox.mapboxsdk.maps.MapboxMap +import com.mapbox.mapboxsdk.maps.Projection +import org.junit.Assert +import org.junit.Test +import org.mockito.InjectMocks +import org.mockito.Mockito + +class InfoWindowTest { + @InjectMocks + var mMapView = Mockito.mock(MapView::class.java) + + @InjectMocks + var mMapboxMap = Mockito.mock(MapboxMap::class.java) + + @Test + fun testSanity() { + val infoWindow = InfoWindow(mMapView, mMapboxMap) + Assert.assertNotNull("infoWindow should exist", infoWindow) + } + + @Test + fun testBoundMarker() { + val markerOptions = MarkerOptions() + val marker = markerOptions.position(LatLng()).marker + val infoWindow = InfoWindow(mMapView, mMapboxMap).setBoundMarker(marker) + Assert.assertEquals("marker should match", marker, infoWindow.boundMarker) + } + + @Test + fun testClose() { + val infoWindow = InfoWindow(mMapView, mMapboxMap) + infoWindow.close() + Assert.assertEquals("infowindow should not be visible", false, infoWindow.isVisible) + } + + @Test + fun testOpen() { + val latLng = LatLng(0.0, 0.0) + val projection = Mockito.mock( + Projection::class.java + ) + Mockito.`when`(mMapboxMap.projection).thenReturn(projection) + Mockito.`when`(projection.toScreenLocation(latLng)).thenReturn(PointF(0f, 0f)) + val infoWindow = InfoWindow(mMapView, mMapboxMap) + infoWindow.open(mMapView, MarkerOptions().position(LatLng()).marker, latLng, 0, 0) + Assert.assertEquals("infowindow should not be visible", true, infoWindow.isVisible) + } + + @Test + fun testOpenClose() { + val latLng = LatLng(0.0, 0.0) + val projection = Mockito.mock( + Projection::class.java + ) + Mockito.`when`(mMapboxMap.projection).thenReturn(projection) + Mockito.`when`(projection.toScreenLocation(latLng)).thenReturn(PointF(0f, 0f)) + val infoWindow = InfoWindow(mMapView, mMapboxMap) + infoWindow.open(mMapView, MarkerOptions().position(LatLng()).marker, latLng, 0, 0) + infoWindow.close() + Assert.assertEquals("infowindow should not be visible", false, infoWindow.isVisible) + } + + @Test + fun testUpdate() { + val latLng = LatLng(0.0, 0.0) + val projection = Mockito.mock( + Projection::class.java + ) + Mockito.`when`(mMapboxMap.projection).thenReturn(projection) + Mockito.`when`(projection.toScreenLocation(latLng)).thenReturn(PointF(0f, 0f)) + val infoWindow = InfoWindow(mMapView, mMapboxMap) + infoWindow.open(mMapView, MarkerOptions().position(latLng).marker, latLng, 0, 0) + infoWindow.update() + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/MarkerTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/MarkerTest.java deleted file mode 100644 index fa571e06b..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/MarkerTest.java +++ /dev/null @@ -1,160 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import android.graphics.Bitmap; -import android.os.Parcelable; - -import com.mapbox.mapboxsdk.exceptions.InvalidMarkerPositionException; -import com.mapbox.mapboxsdk.geometry.LatLng; -import com.mapbox.mapboxsdk.utils.MockParcel; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.mock; - -public class MarkerTest { - - @Test - public void testSanity() { - MarkerOptions markerOptions = new MarkerOptions(); - assertNotNull("markerOptions should not be null", markerOptions); - } - - @Test - public void testMarker() { - MarkerOptions markerOptions = new MarkerOptions().position(new LatLng()); - assertNotNull("marker should not be null", markerOptions.getMarker()); - } - - @Test(expected = InvalidMarkerPositionException.class) - public void testInvalidMarker() { - new MarkerOptions().getMarker(); - } - - @Test - public void testPosition() { - MarkerOptions markerOptions = new MarkerOptions().position(new LatLng(10, 12)); - Marker marker = markerOptions.getMarker(); - assertEquals(marker.getPosition(), new LatLng(10, 12)); - assertEquals(markerOptions.getPosition(), new LatLng(10, 12)); - } - - @Test - public void testTitle() { - MarkerOptions markerOptions = new MarkerOptions().title("Mapbox").position(new LatLng()); - Marker marker = markerOptions.getMarker(); - assertEquals(marker.getTitle(), "Mapbox"); - assertEquals(markerOptions.getTitle(), "Mapbox"); - } - - @Test - public void testSnippet() { - MarkerOptions markerOptions = new MarkerOptions().snippet("Mapbox").position(new LatLng()); - Marker marker = markerOptions.getMarker(); - assertEquals(marker.getSnippet(), "Mapbox"); - } - - @Test - public void testBuilder() { - Marker marker = new MarkerOptions().title("title").snippet("snippet").position(new LatLng(10, 12)).getMarker(); - assertEquals(marker.getSnippet(), "snippet"); - - assertEquals(marker.getPosition(), new LatLng(10, 12)); - } - - @Test - public void testIcon() { - Bitmap bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_4444); - Icon icon = IconFactory.recreate("test", bitmap); - MarkerOptions markerOptions = new MarkerOptions().position(new LatLng()).icon(icon); - Marker marker = markerOptions.getMarker(); - assertEquals("Icon should match", icon, marker.getIcon()); - assertEquals("Icon should match", icon, markerOptions.getIcon()); - } - - @Test - public void testHashCode() { - Marker marker = new MarkerOptions().position(new LatLng()).getMarker(); - assertEquals("hash code should match", marker.hashCode(), 0); - } - - @Test - public void testHashCodeBuilder() { - MarkerOptions markerOptions = new MarkerOptions().position(new LatLng(10, 12)); - assertEquals("hash code should match", markerOptions.hashCode(), 579999617); - } - - @Test - public void testEquals() { - Marker markerOne = new MarkerOptions().position(new LatLng(0, 0)).getMarker(); - Marker markerTwo = new MarkerOptions().position(new LatLng(0, 0)).getMarker(); - assertEquals(markerOne, markerTwo); - } - - @Test - public void testEqualityDifferentLocation() { - MarkerOptions marker = new MarkerOptions().position(new LatLng(0, 0)); - MarkerOptions other = new MarkerOptions().position(new LatLng(1, 0)); - assertNotEquals("Should not match", other, marker); - } - - - @Test - public void testEqualityDifferentSnippet() { - MarkerOptions marker = new MarkerOptions().snippet("s"); - MarkerOptions other = new MarkerOptions(); - assertNotEquals("Should not match", other, marker); - } - - @Test - public void testEqualityDifferentIcon() { - MarkerOptions marker = new MarkerOptions().icon(mock(Icon.class)); - MarkerOptions other = new MarkerOptions(); - assertNotEquals("Should not match", other, marker); - } - - @Test - public void testEqualityDifferentTitle() { - MarkerOptions marker = new MarkerOptions().title("t"); - MarkerOptions other = new MarkerOptions(); - assertNotEquals("Should not match", other, marker); - } - - @Test - public void testEqualsItself() { - MarkerOptions markerOptions = new MarkerOptions().position(new LatLng(0, 0)); - Marker marker = markerOptions.getMarker(); - assertEquals("Marker should match", marker, marker); - assertEquals("MarkerOptions should match", markerOptions, markerOptions); - } - - @Test - public void testNotEquals() { - MarkerOptions markerOptions = new MarkerOptions().position(new LatLng(0, 0)); - Marker marker = markerOptions.getMarker(); - assertNotEquals("MarkerOptions should match", markerOptions, new Object()); - assertNotEquals("Marker should match", marker, new Object()); - } - - @Test - public void testEqualityBuilder() { - MarkerOptions markerOne = new MarkerOptions().position(new LatLng(0, 0)); - MarkerOptions markerTwo = new MarkerOptions().position(new LatLng(0, 0)); - assertEquals(markerOne, markerTwo); - } - - @Test - public void testToString() { - Marker marker = new MarkerOptions().position(new LatLng(0, 0)).getMarker(); - assertEquals(marker.toString(), "Marker [position[" + "LatLng [latitude=0.0, longitude=0.0, altitude=0.0]" + "]]"); - } - - @Test - public void testParcelable() { - MarkerOptions markerOptions = new MarkerOptions().position(new LatLng()).title("t").snippet("s"); - Parcelable parcelable = MockParcel.obtain(markerOptions); - assertEquals("Parcel should match original object", parcelable, markerOptions); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/MarkerTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/MarkerTest.kt new file mode 100644 index 000000000..a607eddfe --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/MarkerTest.kt @@ -0,0 +1,159 @@ +package com.mapbox.mapboxsdk.annotations + +import android.graphics.Bitmap +import com.mapbox.mapboxsdk.exceptions.InvalidMarkerPositionException +import com.mapbox.mapboxsdk.geometry.LatLng +import com.mapbox.mapboxsdk.utils.MockParcel +import org.junit.Assert +import org.junit.Test +import org.mockito.Mockito + +class MarkerTest { + @Test + fun testSanity() { + val markerOptions = MarkerOptions() + Assert.assertNotNull("markerOptions should not be null", markerOptions) + } + + @Test + fun testMarker() { + val markerOptions = MarkerOptions().position(LatLng()) + Assert.assertNotNull("marker should not be null", markerOptions.marker) + } + + @Test(expected = InvalidMarkerPositionException::class) + fun testInvalidMarker() { + MarkerOptions().marker + } + + @Test + fun testPosition() { + val markerOptions = MarkerOptions().position(LatLng(10.0, 12.0)) + val marker = markerOptions.marker + Assert.assertEquals(marker.position, LatLng(10.0, 12.0)) + Assert.assertEquals(markerOptions.getPosition(), LatLng(10.0, 12.0)) + } + + @Test + fun testTitle() { + val markerOptions = MarkerOptions().title("Mapbox").position(LatLng()) + val marker = markerOptions.marker + Assert.assertEquals(marker.title, "Mapbox") + Assert.assertEquals(markerOptions.getTitle(), "Mapbox") + } + + @Test + fun testSnippet() { + val markerOptions = MarkerOptions().snippet("Mapbox").position(LatLng()) + val marker = markerOptions.marker + Assert.assertEquals(marker.snippet, "Mapbox") + } + + @Test + fun testBuilder() { + val marker = + MarkerOptions().title("title").snippet("snippet").position(LatLng(10.0, 12.0)).marker + Assert.assertEquals(marker.snippet, "snippet") + Assert.assertEquals(marker.position, LatLng(10.0, 12.0)) + } + + @Test + fun testIcon() { + val bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_4444) + val icon = IconFactory.recreate("test", bitmap) + val markerOptions = MarkerOptions().position(LatLng()).icon(icon) + val marker = markerOptions.marker + Assert.assertEquals("Icon should match", icon, marker.icon) + Assert.assertEquals("Icon should match", icon, markerOptions.getIcon()) + } + + @Test + fun testHashCode() { + val marker = MarkerOptions().position(LatLng()).marker + Assert.assertEquals("hash code should match", marker.hashCode().toLong(), 0) + } + + @Test + fun testHashCodeBuilder() { + val markerOptions = MarkerOptions().position(LatLng(10.0, 12.0)) + Assert.assertEquals("hash code should match", markerOptions.hashCode().toLong(), 579999617) + } + + @Test + fun testEquals() { + val markerOne = MarkerOptions().position(LatLng(0.0, 0.0)).marker + val markerTwo = MarkerOptions().position(LatLng(0.0, 0.0)).marker + Assert.assertEquals(markerOne, markerTwo) + } + + @Test + fun testEqualityDifferentLocation() { + val marker = MarkerOptions().position(LatLng(0.0, 0.0)) + val other = MarkerOptions().position(LatLng(1.0, 0.0)) + Assert.assertNotEquals("Should not match", other, marker) + } + + @Test + fun testEqualityDifferentSnippet() { + val marker = MarkerOptions().snippet("s") + val other = MarkerOptions() + Assert.assertNotEquals("Should not match", other, marker) + } + + @Test + fun testEqualityDifferentIcon() { + val marker = MarkerOptions().icon( + Mockito.mock( + Icon::class.java + ) + ) + val other = MarkerOptions() + Assert.assertNotEquals("Should not match", other, marker) + } + + @Test + fun testEqualityDifferentTitle() { + val marker = MarkerOptions().title("t") + val other = MarkerOptions() + Assert.assertNotEquals("Should not match", other, marker) + } + + @Test + fun testEqualsItself() { + val markerOptions = MarkerOptions().position(LatLng(0.0, 0.0)) + val marker = markerOptions.marker + Assert.assertEquals("Marker should match", marker, marker) + Assert.assertEquals("MarkerOptions should match", markerOptions, markerOptions) + } + + @Test + fun testNotEquals() { + val markerOptions = MarkerOptions().position(LatLng(0.0, 0.0)) + val marker = markerOptions.marker + Assert.assertNotEquals("MarkerOptions should match", markerOptions, Any()) + Assert.assertNotEquals("Marker should match", marker, Any()) + } + + @Test + fun testEqualityBuilder() { + val markerOne = MarkerOptions().position(LatLng(0.0, 0.0)) + val markerTwo = MarkerOptions().position(LatLng(0.0, 0.0)) + Assert.assertEquals(markerOne, markerTwo) + } + + @Test + fun testToString() { + val marker = MarkerOptions().position(LatLng(0.0, 0.0)).marker + Assert.assertEquals( + marker.toString(), + "Marker [position[" + "LatLng [latitude=0.0, longitude=0.0, altitude=0.0]" + "]]" + ) + } + + @Test + fun testParcelable() { + val markerOptions = MarkerOptions().position(LatLng()).title("t").snippet("s") + val parcelable = MockParcel.obtain(markerOptions) + Assert.assertEquals("Parcel should match original object", parcelable, markerOptions) + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/PolygonTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/PolygonTest.java deleted file mode 100644 index 3933c6888..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/PolygonTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import com.mapbox.mapboxsdk.geometry.LatLng; - -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -public class PolygonTest { - - @Test - public void testSanity() { - PolygonOptions polygonOptions = new PolygonOptions(); - assertNotNull("polygonOptions should not be null", polygonOptions); - } - - @Test - public void testPolygon() { - Polygon polygon = new PolygonOptions().getPolygon(); - assertNotNull("polyline should not be null", polygon); - } - - @Test - public void testAlpha() { - Polygon polygon = new PolygonOptions().alpha(0.5f).getPolygon(); - assertEquals(0.5f, polygon.getAlpha(), 0.0f); - } - - @Test - public void testStrokeColor() { - Polygon polygon = new PolygonOptions().strokeColor(1).getPolygon(); - assertEquals(1, polygon.getStrokeColor()); - } - - @Test - public void testFillColor() { - Polygon polygon = new PolygonOptions().fillColor(1).getPolygon(); - assertEquals(1, polygon.getFillColor()); - } - - @Test - public void testLatLng() { - Polygon polygon = new PolygonOptions().add(new LatLng(0, 0)).getPolygon(); - assertNotNull("points should not be null", polygon.getPoints()); - assertEquals(new LatLng(0, 0), polygon.getPoints().get(0)); - } - - @Test - public void testAddAllLatLng() { - List coordinates = new ArrayList<>(); - coordinates.add(new LatLng(0, 0)); - Polygon polygon = new PolygonOptions().addAll(coordinates).getPolygon(); - assertNotNull(polygon.getPoints()); - assertEquals(new LatLng(0, 0), polygon.getPoints().get(0)); - } - - @Test - public void testBuilder() { - PolylineOptions polylineOptions = new PolylineOptions(); - polylineOptions.width(1.0f); - polylineOptions.color(2); - polylineOptions.add(new LatLng(0, 0)); - - Polyline polyline = polylineOptions.getPolyline(); - assertEquals(1.0f, polyline.getWidth(), 0); - assertEquals(2, polyline.getColor()); - assertNotNull("Points should not be null", polyline.getPoints()); - assertEquals(new LatLng(0, 0), polyline.getPoints().get(0)); - } - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/PolygonTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/PolygonTest.kt new file mode 100644 index 000000000..13c1ac1a0 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/PolygonTest.kt @@ -0,0 +1,66 @@ +package com.mapbox.mapboxsdk.annotations + +import com.mapbox.mapboxsdk.geometry.LatLng +import org.junit.Assert +import org.junit.Test + +class PolygonTest { + @Test + fun testSanity() { + val polygonOptions = PolygonOptions() + Assert.assertNotNull("polygonOptions should not be null", polygonOptions) + } + + @Test + fun testPolygon() { + val polygon = PolygonOptions().polygon + Assert.assertNotNull("polyline should not be null", polygon) + } + + @Test + fun testAlpha() { + val polygon = PolygonOptions().alpha(0.5f).polygon + Assert.assertEquals(0.5f, polygon.alpha, 0.0f) + } + + @Test + fun testStrokeColor() { + val polygon = PolygonOptions().strokeColor(1).polygon + Assert.assertEquals(1, polygon.strokeColor.toLong()) + } + + @Test + fun testFillColor() { + val polygon = PolygonOptions().fillColor(1).polygon + Assert.assertEquals(1, polygon.fillColor.toLong()) + } + + @Test + fun testLatLng() { + val polygon = PolygonOptions().add(LatLng(0.0, 0.0)).polygon + Assert.assertNotNull("points should not be null", polygon.points) + Assert.assertEquals(LatLng(0.0, 0.0), polygon.points[0]) + } + + @Test + fun testAddAllLatLng() { + val coordinates: MutableList = ArrayList() + coordinates.add(LatLng(0.0, 0.0)) + val polygon = PolygonOptions().addAll(coordinates).polygon + Assert.assertNotNull(polygon.points) + Assert.assertEquals(LatLng(0.0, 0.0), polygon.points[0]) + } + + @Test + fun testBuilder() { + val polylineOptions = PolylineOptions() + polylineOptions.width(1.0f) + polylineOptions.color(2) + polylineOptions.add(LatLng(0.0, 0.0)) + val polyline = polylineOptions.polyline + Assert.assertEquals(1.0f, polyline.width, 0f) + Assert.assertEquals(2, polyline.color.toLong()) + Assert.assertNotNull("Points should not be null", polyline.points) + Assert.assertEquals(LatLng(0.0, 0.0), polyline.points[0]) + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/PolylineTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/PolylineTest.java deleted file mode 100644 index 54bb0e8cf..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/PolylineTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import com.mapbox.mapboxsdk.geometry.LatLng; - -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -public class PolylineTest { - - @Test - public void testSanity() { - PolylineOptions polylineOptions = new PolylineOptions(); - assertNotNull("polylineOptions should not be null", polylineOptions); - } - - @Test - public void testPolyline() { - Polyline polyline = new PolylineOptions().getPolyline(); - assertNotNull("polyline should not be null", polyline); - } - - @Test - public void testAlpha() { - Polyline polyline = new PolylineOptions().alpha(0.2f).getPolyline(); - assertEquals(0.2f, polyline.getAlpha(), 0.0f); - } - - @Test - public void testWidth() { - Polyline polyline = new PolylineOptions().width(1).getPolyline(); - assertEquals(1.0f, polyline.getWidth(), 0); - } - - @Test - public void testColor() { - Polyline polyline = new PolylineOptions().color(1).getPolyline(); - assertEquals(1, polyline.getColor()); - } - - @Test - public void testAddLatLng() { - Polyline polyline = new PolylineOptions().add(new LatLng(0, 0)).getPolyline(); - assertNotNull("Points should not be null", polyline.getPoints()); - assertEquals(new LatLng(0, 0), polyline.getPoints().get(0)); - } - - @Test - public void testAddAllLatLng() { - List coordinates = new ArrayList<>(); - coordinates.add(new LatLng(0, 0)); - Polyline polyline = new PolylineOptions().addAll(coordinates).getPolyline(); - assertNotNull(polyline.getPoints()); - assertEquals(new LatLng(0, 0), polyline.getPoints().get(0)); - } - - @Test - public void testBuilder() { - PolylineOptions polylineOptions = new PolylineOptions(); - polylineOptions.width(1.0f); - polylineOptions.color(2); - polylineOptions.add(new LatLng(0, 0)); - - Polyline polyline = polylineOptions.getPolyline(); - assertEquals(1.0f, polyline.getWidth(), 0); - assertEquals(2, polyline.getColor()); - assertNotNull("Points should not be null", polyline.getPoints()); - assertEquals(new LatLng(0, 0), polyline.getPoints().get(0)); - } - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/PolylineTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/PolylineTest.kt new file mode 100644 index 000000000..c99ba81ae --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/PolylineTest.kt @@ -0,0 +1,66 @@ +package com.mapbox.mapboxsdk.annotations + +import com.mapbox.mapboxsdk.geometry.LatLng +import org.junit.Assert +import org.junit.Test + +class PolylineTest { + @Test + fun testSanity() { + val polylineOptions = PolylineOptions() + Assert.assertNotNull("polylineOptions should not be null", polylineOptions) + } + + @Test + fun testPolyline() { + val polyline = PolylineOptions().polyline + Assert.assertNotNull("polyline should not be null", polyline) + } + + @Test + fun testAlpha() { + val polyline = PolylineOptions().alpha(0.2f).polyline + Assert.assertEquals(0.2f, polyline.alpha, 0.0f) + } + + @Test + fun testWidth() { + val polyline = PolylineOptions().width(1f).polyline + Assert.assertEquals(1.0f, polyline.width, 0f) + } + + @Test + fun testColor() { + val polyline = PolylineOptions().color(1).polyline + Assert.assertEquals(1, polyline.color.toLong()) + } + + @Test + fun testAddLatLng() { + val polyline = PolylineOptions().add(LatLng(0.0, 0.0)).polyline + Assert.assertNotNull("Points should not be null", polyline.points) + Assert.assertEquals(LatLng(0.0, 0.0), polyline.points[0]) + } + + @Test + fun testAddAllLatLng() { + val coordinates: MutableList = ArrayList() + coordinates.add(LatLng(0.0, 0.0)) + val polyline = PolylineOptions().addAll(coordinates).polyline + Assert.assertNotNull(polyline.points) + Assert.assertEquals(LatLng(0.0, 0.0), polyline.points[0]) + } + + @Test + fun testBuilder() { + val polylineOptions = PolylineOptions() + polylineOptions.width(1.0f) + polylineOptions.color(2) + polylineOptions.add(LatLng(0.0, 0.0)) + val polyline = polylineOptions.polyline + Assert.assertEquals(1.0f, polyline.width, 0f) + Assert.assertEquals(2, polyline.color.toLong()) + Assert.assertNotNull("Points should not be null", polyline.points) + Assert.assertEquals(LatLng(0.0, 0.0), polyline.points[0]) + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/attribution/AttributionParseTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/attribution/AttributionParseTest.java deleted file mode 100644 index 3ff11cfd4..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/attribution/AttributionParseTest.java +++ /dev/null @@ -1,288 +0,0 @@ -package com.mapbox.mapboxsdk.attribution; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; -import org.robolectric.RuntimeEnvironment; - -import java.util.Set; - -import static junit.framework.Assert.assertEquals; - -@RunWith(RobolectricTestRunner.class) -public class AttributionParseTest { - - private static final String STREETS_ATTRIBUTION = "© Mapbox © OpenStreetMap \n"; - private static final String SATELLITE_ATTRIBUTION = "© Mapbox © OpenStreetMap © DigitalGlobe\n"; - - @Test - public void testParseAttributionStringSatellite() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(SATELLITE_ATTRIBUTION) - .build(); - - Set attributionList = attributionParser.getAttributions(); - assertEquals("Size of list should match", 3, attributionList.size()); - - int counter = 0; - for (Attribution attribution : attributionList) { - switch (counter) { - case 0: - assertEquals("URL mapbox should match", "https://www.mapbox.com/about/maps/", attribution.getUrl()); - assertEquals("Title mapbox should match", "© Mapbox", attribution.getTitle()); - break; - case 1: - assertEquals("URL openstreetmap should match", "http://www.openstreetmap.org/about/", attribution.getUrl()); - assertEquals("Title openstreetmap should match", "© OpenStreetMap", attribution.getTitle()); - break; - case 2: - assertEquals("URL digital globe should match", "https://www.digitalglobe.com/", attribution.getUrl()); - assertEquals("Title digital globe should match", "© DigitalGlobe", attribution.getTitle()); - break; - } - counter++; - } - } - - @Test - public void testParseAttributionStringStreets() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(STREETS_ATTRIBUTION) - .build(); - - Set attributionList = attributionParser.getAttributions(); - assertEquals("Size of list should match", 2, attributionList.size()); - - int counter = 0; - for (Attribution attribution : attributionList) { - switch (counter) { - case 0: - assertEquals("URL mapbox should match", "https://www.mapbox.com/about/maps/", attribution.getUrl()); - assertEquals("Title mapbox should match", "© Mapbox", attribution.getTitle()); - break; - case 1: - assertEquals("URL openstreetmap should match", "http://www.openstreetmap.org/about/", attribution.getUrl()); - assertEquals("Title openstreetmap should match", "© OpenStreetMap", attribution.getTitle()); - break; - } - counter++; - } - } - - @Test - public void testParseAttributionWithoutMapbox() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(STREETS_ATTRIBUTION) - .withMapboxAttribution(false) - .build(); - - Set attributionList = attributionParser.getAttributions(); - assertEquals("Size of list should match", 1, attributionList.size()); - - int counter = 0; - for (Attribution attribution : attributionList) { - switch (counter) { - case 0: - assertEquals("URL openstreetmap should match", "http://www.openstreetmap.org/about/", attribution.getUrl()); - assertEquals("Title openstreetmap should match", "© OpenStreetMap", attribution.getTitle()); - break; - } - counter++; - } - } - - @Test - public void testParseAttributionArrayString() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(new String[] {STREETS_ATTRIBUTION, "", SATELLITE_ATTRIBUTION}) - .build(); - Set attributionList = attributionParser.getAttributions(); - assertEquals("Size of list should match", 3, attributionList.size()); - - int counter = 0; - for (Attribution attribution : attributionList) { - switch (counter) { - case 0: - assertEquals("URL mapbox should match", "https://www.mapbox.com/about/maps/", attribution.getUrl()); - assertEquals("Title mapbox should match", "© Mapbox", attribution.getTitle()); - break; - case 1: - assertEquals("URL openstreetmap should match", "http://www.openstreetmap.org/about/", attribution.getUrl()); - assertEquals("Title openstreetmap should match", "© OpenStreetMap", attribution.getTitle()); - break; - case 2: - assertEquals("URL digital globe should match", "https://www.digitalglobe.com/", attribution.getUrl()); - assertEquals("Title digital globe should match", "© DigitalGlobe", attribution.getTitle()); - break; - } - counter++; - } - } - - @Test - public void testHideImproveThisMapAttributionArrayString() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(SATELLITE_ATTRIBUTION) - .withImproveMap(false) - .build(); - Set attributionList = attributionParser.getAttributions(); - assertEquals("Size of list should match", 3, attributionList.size()); - - int counter = 0; - for (Attribution attribution : attributionList) { - switch (counter) { - case 0: - assertEquals("URL mapbox should match", "https://www.mapbox.com/about/maps/", attribution.getUrl()); - assertEquals("Title mapbox should match", "© Mapbox", attribution.getTitle()); - break; - case 1: - assertEquals("URL openstreetmap should match", "http://www.openstreetmap.org/about/", attribution.getUrl()); - assertEquals("Title openstreetmap should match", "© OpenStreetMap", attribution.getTitle()); - break; - case 2: - assertEquals("URL digital globe should match", "https://www.digitalglobe.com/", attribution.getUrl()); - assertEquals("Title digital globe should match", "© DigitalGlobe", attribution.getTitle()); - break; - } - counter++; - } - } - - @Test - public void testParseHideCopyrightAttributionArrayString() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(STREETS_ATTRIBUTION, "", SATELLITE_ATTRIBUTION) - .withCopyrightSign(false) - .build(); - Set attributionList = attributionParser.getAttributions(); - assertEquals("Size of list should match", 3, attributionList.size()); - - int counter = 0; - for (Attribution attribution : attributionList) { - switch (counter) { - case 0: - assertEquals("URL mapbox should match", "https://www.mapbox.com/about/maps/", attribution.getUrl()); - assertEquals("Title mapbox should match", "Mapbox", attribution.getTitle()); - break; - case 1: - assertEquals("URL openstreetmap should match", "http://www.openstreetmap.org/about/", attribution.getUrl()); - assertEquals("Title openstreetmap should match", "OpenStreetMap", attribution.getTitle()); - break; - case 2: - assertEquals("URL digital globe should match", "https://www.digitalglobe.com/", attribution.getUrl()); - assertEquals("Title digital globe should match", "DigitalGlobe", attribution.getTitle()); - break; - } - counter++; - } - } - - @Test - public void testOutputWithoutCopyRightString() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(STREETS_ATTRIBUTION) - .withCopyrightSign(false) - .withImproveMap(false) - .build(); - - assertEquals( - "Attribution string should match", - "© Mapbox / OpenStreetMap", - attributionParser.createAttributionString() - ); - } - - - @Test - public void testOutputWithCopyRightString() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(STREETS_ATTRIBUTION) - .withImproveMap(false) - .build(); - - assertEquals( - "Attribution string should match", - "© Mapbox / © OpenStreetMap", - attributionParser.createAttributionString() - ); - } - - @Test - public void testOutputWithoutCopyRightWithoutMapboxString() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(STREETS_ATTRIBUTION) - .withCopyrightSign(false) - .withImproveMap(false) - .withMapboxAttribution(false) - .build(); - - assertEquals( - "Attribution string should match", - "© OpenStreetMap", - attributionParser.createAttributionString() - ); - } - - @Test - public void testOutputWithCopyRightWithoutMapboxString() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(STREETS_ATTRIBUTION) - .withImproveMap(false) - .withMapboxAttribution(false) - .build(); - - assertEquals( - "Attribution string should match", - "© OpenStreetMap", - attributionParser.createAttributionString() - ); - } - - @Test - public void testOutputSatelliteString() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(STREETS_ATTRIBUTION, SATELLITE_ATTRIBUTION, "blabla", "") - .withImproveMap(false) - .withCopyrightSign(false) - .withMapboxAttribution(false) - .build(); - - assertEquals( - "Attribution string should match", - "© OpenStreetMap / DigitalGlobe", - attributionParser.createAttributionString() - ); - } - - @Test - public void testShortOpenStreetMapString() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(STREETS_ATTRIBUTION, SATELLITE_ATTRIBUTION, "blabla", "") - .withImproveMap(false) - .withCopyrightSign(false) - .withMapboxAttribution(false) - .build(); - - assertEquals( - "Attribution string should match", - "© OSM / DigitalGlobe", - attributionParser.createAttributionString(true) - ); - } - - @Test - public void testShortOpenStreetMapWithoutCopyrightString() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(STREETS_ATTRIBUTION, SATELLITE_ATTRIBUTION, "blabla", "") - .withImproveMap(false) - .withCopyrightSign(false) - .build(); - - assertEquals( - "Attribution string should match", - "© Mapbox / OSM / DigitalGlobe", - attributionParser.createAttributionString(true) - ); - } -} - diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/attribution/AttributionParseTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/attribution/AttributionParseTest.kt new file mode 100644 index 000000000..e9c09ca2e --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/attribution/AttributionParseTest.kt @@ -0,0 +1,383 @@ +package com.mapbox.mapboxsdk.attribution + +import junit.framework.Assert +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment + +@RunWith(RobolectricTestRunner::class) +class AttributionParseTest { + @Test + @Throws(Exception::class) + fun testParseAttributionStringSatellite() { + val attributionParser = AttributionParser.Options(RuntimeEnvironment.application) + .withAttributionData(SATELLITE_ATTRIBUTION) + .build() + val attributionList = attributionParser.attributions + Assert.assertEquals("Size of list should match", 3, attributionList.size) + var counter = 0 + for (attribution in attributionList) { + when (counter) { + 0 -> { + Assert.assertEquals( + "URL mapbox should match", + "https://www.mapbox.com/about/maps/", + attribution.url + ) + Assert.assertEquals("Title mapbox should match", "© Mapbox", attribution.title) + } + 1 -> { + Assert.assertEquals( + "URL openstreetmap should match", + "http://www.openstreetmap.org/about/", + attribution.url + ) + Assert.assertEquals( + "Title openstreetmap should match", + "© OpenStreetMap", + attribution.title + ) + } + 2 -> { + Assert.assertEquals( + "URL digital globe should match", + "https://www.digitalglobe.com/", + attribution.url + ) + Assert.assertEquals( + "Title digital globe should match", + "© DigitalGlobe", + attribution.title + ) + } + } + counter++ + } + } + + @Test + @Throws(Exception::class) + fun testParseAttributionStringStreets() { + val attributionParser = AttributionParser.Options(RuntimeEnvironment.application) + .withAttributionData(STREETS_ATTRIBUTION) + .build() + val attributionList = attributionParser.attributions + Assert.assertEquals("Size of list should match", 2, attributionList.size) + var counter = 0 + for (attribution in attributionList) { + when (counter) { + 0 -> { + Assert.assertEquals( + "URL mapbox should match", + "https://www.mapbox.com/about/maps/", + attribution.url + ) + Assert.assertEquals("Title mapbox should match", "© Mapbox", attribution.title) + } + 1 -> { + Assert.assertEquals( + "URL openstreetmap should match", + "http://www.openstreetmap.org/about/", + attribution.url + ) + Assert.assertEquals( + "Title openstreetmap should match", + "© OpenStreetMap", + attribution.title + ) + } + } + counter++ + } + } + + @Test + @Throws(Exception::class) + fun testParseAttributionWithoutMapbox() { + val attributionParser = AttributionParser.Options(RuntimeEnvironment.application) + .withAttributionData(STREETS_ATTRIBUTION) + .withMapboxAttribution(false) + .build() + val attributionList = attributionParser.attributions + Assert.assertEquals("Size of list should match", 1, attributionList.size) + var counter = 0 + for (attribution in attributionList) { + when (counter) { + 0 -> { + Assert.assertEquals( + "URL openstreetmap should match", + "http://www.openstreetmap.org/about/", + attribution.url + ) + Assert.assertEquals( + "Title openstreetmap should match", + "© OpenStreetMap", + attribution.title + ) + } + } + counter++ + } + } + + @Test + @Throws(Exception::class) + fun testParseAttributionArrayString() { + val attributionParser = AttributionParser.Options(RuntimeEnvironment.application) + .withAttributionData(*arrayOf(STREETS_ATTRIBUTION, "", SATELLITE_ATTRIBUTION)) + .build() + val attributionList = attributionParser.attributions + Assert.assertEquals("Size of list should match", 3, attributionList.size) + var counter = 0 + for (attribution in attributionList) { + when (counter) { + 0 -> { + Assert.assertEquals( + "URL mapbox should match", + "https://www.mapbox.com/about/maps/", + attribution.url + ) + Assert.assertEquals("Title mapbox should match", "© Mapbox", attribution.title) + } + 1 -> { + Assert.assertEquals( + "URL openstreetmap should match", + "http://www.openstreetmap.org/about/", + attribution.url + ) + Assert.assertEquals( + "Title openstreetmap should match", + "© OpenStreetMap", + attribution.title + ) + } + 2 -> { + Assert.assertEquals( + "URL digital globe should match", + "https://www.digitalglobe.com/", + attribution.url + ) + Assert.assertEquals( + "Title digital globe should match", + "© DigitalGlobe", + attribution.title + ) + } + } + counter++ + } + } + + @Test + @Throws(Exception::class) + fun testHideImproveThisMapAttributionArrayString() { + val attributionParser = AttributionParser.Options(RuntimeEnvironment.application) + .withAttributionData(SATELLITE_ATTRIBUTION) + .withImproveMap(false) + .build() + val attributionList = attributionParser.attributions + Assert.assertEquals("Size of list should match", 3, attributionList.size) + var counter = 0 + for (attribution in attributionList) { + when (counter) { + 0 -> { + Assert.assertEquals( + "URL mapbox should match", + "https://www.mapbox.com/about/maps/", + attribution.url + ) + Assert.assertEquals("Title mapbox should match", "© Mapbox", attribution.title) + } + 1 -> { + Assert.assertEquals( + "URL openstreetmap should match", + "http://www.openstreetmap.org/about/", + attribution.url + ) + Assert.assertEquals( + "Title openstreetmap should match", + "© OpenStreetMap", + attribution.title + ) + } + 2 -> { + Assert.assertEquals( + "URL digital globe should match", + "https://www.digitalglobe.com/", + attribution.url + ) + Assert.assertEquals( + "Title digital globe should match", + "© DigitalGlobe", + attribution.title + ) + } + } + counter++ + } + } + + @Test + @Throws(Exception::class) + fun testParseHideCopyrightAttributionArrayString() { + val attributionParser = AttributionParser.Options(RuntimeEnvironment.application) + .withAttributionData(STREETS_ATTRIBUTION, "", SATELLITE_ATTRIBUTION) + .withCopyrightSign(false) + .build() + val attributionList = attributionParser.attributions + Assert.assertEquals("Size of list should match", 3, attributionList.size) + var counter = 0 + for (attribution in attributionList) { + when (counter) { + 0 -> { + Assert.assertEquals( + "URL mapbox should match", + "https://www.mapbox.com/about/maps/", + attribution.url + ) + Assert.assertEquals("Title mapbox should match", "Mapbox", attribution.title) + } + 1 -> { + Assert.assertEquals( + "URL openstreetmap should match", + "http://www.openstreetmap.org/about/", + attribution.url + ) + Assert.assertEquals( + "Title openstreetmap should match", + "OpenStreetMap", + attribution.title + ) + } + 2 -> { + Assert.assertEquals( + "URL digital globe should match", + "https://www.digitalglobe.com/", + attribution.url + ) + Assert.assertEquals( + "Title digital globe should match", + "DigitalGlobe", + attribution.title + ) + } + } + counter++ + } + } + + @Test + @Throws(Exception::class) + fun testOutputWithoutCopyRightString() { + val attributionParser = AttributionParser.Options(RuntimeEnvironment.application) + .withAttributionData(STREETS_ATTRIBUTION) + .withCopyrightSign(false) + .withImproveMap(false) + .build() + Assert.assertEquals( + "Attribution string should match", + "© Mapbox / OpenStreetMap", + attributionParser.createAttributionString() + ) + } + + @Test + @Throws(Exception::class) + fun testOutputWithCopyRightString() { + val attributionParser = AttributionParser.Options(RuntimeEnvironment.application) + .withAttributionData(STREETS_ATTRIBUTION) + .withImproveMap(false) + .build() + Assert.assertEquals( + "Attribution string should match", + "© Mapbox / © OpenStreetMap", + attributionParser.createAttributionString() + ) + } + + @Test + @Throws(Exception::class) + fun testOutputWithoutCopyRightWithoutMapboxString() { + val attributionParser = AttributionParser.Options(RuntimeEnvironment.application) + .withAttributionData(STREETS_ATTRIBUTION) + .withCopyrightSign(false) + .withImproveMap(false) + .withMapboxAttribution(false) + .build() + Assert.assertEquals( + "Attribution string should match", + "© OpenStreetMap", + attributionParser.createAttributionString() + ) + } + + @Test + @Throws(Exception::class) + fun testOutputWithCopyRightWithoutMapboxString() { + val attributionParser = AttributionParser.Options(RuntimeEnvironment.application) + .withAttributionData(STREETS_ATTRIBUTION) + .withImproveMap(false) + .withMapboxAttribution(false) + .build() + Assert.assertEquals( + "Attribution string should match", + "© OpenStreetMap", + attributionParser.createAttributionString() + ) + } + + @Test + @Throws(Exception::class) + fun testOutputSatelliteString() { + val attributionParser = AttributionParser.Options(RuntimeEnvironment.application) + .withAttributionData(STREETS_ATTRIBUTION, SATELLITE_ATTRIBUTION, "blabla", "") + .withImproveMap(false) + .withCopyrightSign(false) + .withMapboxAttribution(false) + .build() + Assert.assertEquals( + "Attribution string should match", + "© OpenStreetMap / DigitalGlobe", + attributionParser.createAttributionString() + ) + } + + @Test + @Throws(Exception::class) + fun testShortOpenStreetMapString() { + val attributionParser = AttributionParser.Options(RuntimeEnvironment.application) + .withAttributionData(STREETS_ATTRIBUTION, SATELLITE_ATTRIBUTION, "blabla", "") + .withImproveMap(false) + .withCopyrightSign(false) + .withMapboxAttribution(false) + .build() + Assert.assertEquals( + "Attribution string should match", + "© OSM / DigitalGlobe", + attributionParser.createAttributionString(true) + ) + } + + @Test + @Throws(Exception::class) + fun testShortOpenStreetMapWithoutCopyrightString() { + val attributionParser = AttributionParser.Options(RuntimeEnvironment.application) + .withAttributionData(STREETS_ATTRIBUTION, SATELLITE_ATTRIBUTION, "blabla", "") + .withImproveMap(false) + .withCopyrightSign(false) + .build() + Assert.assertEquals( + "Attribution string should match", + "© Mapbox / OSM / DigitalGlobe", + attributionParser.createAttributionString(true) + ) + } + + companion object { + private const val STREETS_ATTRIBUTION = + "© Mapbox © OpenStreetMap \n" + private const val SATELLITE_ATTRIBUTION = + "© Mapbox © OpenStreetMap © DigitalGlobe\n" + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/camera/CameraPositionTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/camera/CameraPositionTest.java deleted file mode 100644 index 6ae801ba6..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/camera/CameraPositionTest.java +++ /dev/null @@ -1,131 +0,0 @@ -package com.mapbox.mapboxsdk.camera; - -import android.content.res.TypedArray; -import android.os.Parcel; - -import com.mapbox.mapboxsdk.R; -import com.mapbox.mapboxsdk.geometry.LatLng; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -@RunWith(RobolectricTestRunner.class) -public class CameraPositionTest { - - private static final double DELTA = 1e-15; - - @Test - public void testSanity() { - LatLng latLng = new LatLng(1, 2); - CameraPosition cameraPosition = new CameraPosition(latLng, 3, 4, 5, new double[] {0, 500, 0, 0}); - assertNotNull("cameraPosition should not be null", cameraPosition); - } - - @Test - public void testDefaultTypedArrayBuilder() { - TypedArray typedArray = null; - CameraPosition cameraPosition = new CameraPosition.Builder(typedArray).build(); - assertEquals("bearing should match", -1, cameraPosition.bearing, DELTA); - assertNull("latlng should be null", cameraPosition.target); - assertEquals("tilt should match", -1, cameraPosition.tilt, DELTA); - assertEquals("zoom should match", -1, cameraPosition.zoom, DELTA); - assertNull("padding should be null", cameraPosition.padding); - } - - @Test - public void testTypedArrayBuilder() { - float bearing = 180; - float zoom = 12; - float latitude = 10; - float longitude = 11; - float tilt = 44; - - TypedArray typedArray = mock(TypedArray.class); - when(typedArray.getFloat(R.styleable.maplibre_MapView_maplibre_cameraBearing, 0.0f)).thenReturn(bearing); - when(typedArray.getFloat(R.styleable.maplibre_MapView_maplibre_cameraTargetLat, 0.0f)).thenReturn(latitude); - when(typedArray.getFloat(R.styleable.maplibre_MapView_maplibre_cameraTargetLng, 0.0f)).thenReturn(longitude); - when(typedArray.getFloat(R.styleable.maplibre_MapView_maplibre_cameraZoom, 0.0f)).thenReturn(zoom); - when(typedArray.getFloat(R.styleable.maplibre_MapView_maplibre_cameraTilt, 0.0f)).thenReturn(tilt); - doNothing().when(typedArray).recycle(); - - CameraPosition cameraPosition = new CameraPosition.Builder(typedArray).build(); - assertEquals("bearing should match", bearing, cameraPosition.bearing, DELTA); - assertEquals("latlng should match", new LatLng(latitude, longitude), cameraPosition.target); - assertEquals("tilt should match", tilt, cameraPosition.tilt, DELTA); - assertEquals("zoom should match", zoom, cameraPosition.zoom, DELTA); - } - - @Test - public void testToString() { - LatLng latLng = new LatLng(1, 2); - CameraPosition cameraPosition = new CameraPosition(latLng, 3, 4, 5, new double[] {0, 500, 0, 0}); - assertEquals("toString should match", "Target: LatLng [latitude=1.0, longitude=2.0, altitude=0.0], Zoom:3.0, " - + "Bearing:5.0, Tilt:4.0, Padding:[0.0, 500.0, 0.0, 0.0]", cameraPosition.toString()); - } - - @Test - public void testHashcode() { - LatLng latLng = new LatLng(1, 2); - CameraPosition cameraPosition = new CameraPosition(latLng, 3, 4, 5, new double[] {0, 500, 0, 0}); - assertEquals("hashCode should match", -420915327, cameraPosition.hashCode()); - } - - @Test - public void testZoomUpdateBuilder() { - float zoomLevel = 5; - CameraPosition.Builder builder = new CameraPosition.Builder( - (CameraUpdateFactory.ZoomUpdate) CameraUpdateFactory.zoomTo(zoomLevel)); - assertEquals("zoom should match", zoomLevel, builder.build().zoom, 0); - } - - @Test - public void testEquals() { - LatLng latLng = new LatLng(1, 2); - CameraPosition cameraPosition = new CameraPosition(latLng, 3, 4, 5, new double[] {0, 500, 0, 0}); - CameraPosition cameraPositionBearing = new CameraPosition(latLng, 3, 4, 9, new double[] {0, 500, 0, 0}); - CameraPosition cameraPositionTilt = new CameraPosition(latLng, 3, 9, 5, new double[] {0, 500, 0, 0}); - CameraPosition cameraPositionZoom = new CameraPosition(latLng, 9, 4, 5, new double[] {0, 500, 0, 0}); - CameraPosition cameraPositionTarget = new CameraPosition(new LatLng(), 3, 4, 5, new double[] {0, 500, 0, 0}); - CameraPosition cameraPositionPadding = new CameraPosition(new LatLng(), 3, 4, 5, new double[] {0, 501, 0, 0}); - - assertEquals("cameraPosition should match itself", cameraPosition, cameraPosition); - assertNotEquals("cameraPosition should not match null", null, cameraPosition); - assertNotEquals("cameraPosition should not match object", new Object(), cameraPosition); - assertNotEquals("cameraPosition should not match for bearing", cameraPositionBearing, cameraPosition); - assertNotEquals("cameraPosition should not match for tilt", cameraPositionTilt, cameraPosition); - assertNotEquals("cameraPosition should not match for zoom", cameraPositionZoom, cameraPosition); - assertNotEquals("cameraPosition should not match for target", cameraPositionTarget, cameraPosition); - assertNotEquals("cameraPosition should not match for padding", cameraPositionPadding, cameraPosition); - } - - @Test - public void testParcelable() { - CameraPosition cameraPosition1 = new CameraPosition(new LatLng(1, 2), 3, 4, 5, new double[] {0, 500, 0, 0}); - Parcel parcel = Parcel.obtain(); - cameraPosition1.writeToParcel(parcel, 0); - parcel.setDataPosition(0); - - CameraPosition cameraPosition2 = CameraPosition.CREATOR.createFromParcel(parcel); - assertEquals("Parcel should match original object", cameraPosition1, cameraPosition2); - } - - @Test - public void testParcelableNulls() { - CameraPosition cameraPosition1 = new CameraPosition(null, 3, 4, 5, null); - Parcel parcel = Parcel.obtain(); - cameraPosition1.writeToParcel(parcel, 0); - parcel.setDataPosition(0); - - CameraPosition cameraPosition2 = CameraPosition.CREATOR.createFromParcel(parcel); - assertEquals("Parcel should match original object", cameraPosition1, cameraPosition2); - } -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/camera/CameraPositionTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/camera/CameraPositionTest.kt new file mode 100644 index 000000000..96b5e56dc --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/camera/CameraPositionTest.kt @@ -0,0 +1,182 @@ +package com.mapbox.mapboxsdk.camera + +import android.content.res.TypedArray +import android.os.Parcel +import com.mapbox.mapboxsdk.R +import com.mapbox.mapboxsdk.camera.CameraUpdateFactory.ZoomUpdate +import com.mapbox.mapboxsdk.camera.CameraUpdateFactory.zoomTo +import com.mapbox.mapboxsdk.geometry.LatLng +import org.junit.Assert +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Mockito +import org.robolectric.RobolectricTestRunner + +@RunWith(RobolectricTestRunner::class) +class CameraPositionTest { + @Test + fun testSanity() { + val latLng = LatLng(1.0, 2.0) + val cameraPosition = + CameraPosition(latLng, 3.0, 4.0, 5.0, doubleArrayOf(0.0, 500.0, 0.0, 0.0)) + Assert.assertNotNull("cameraPosition should not be null", cameraPosition) + } + + @Test + fun testDefaultTypedArrayBuilder() { + val typedArray: TypedArray? = null + val cameraPosition = CameraPosition.Builder(typedArray).build() + Assert.assertEquals("bearing should match", -1.0, cameraPosition.bearing, DELTA) + Assert.assertNull("latlng should be null", cameraPosition.target) + Assert.assertEquals("tilt should match", -1.0, cameraPosition.tilt, DELTA) + Assert.assertEquals("zoom should match", -1.0, cameraPosition.zoom, DELTA) + Assert.assertNull("padding should be null", cameraPosition.padding) + } + + @Test + fun testTypedArrayBuilder() { + val bearing = 180f + val zoom = 12f + val latitude = 10f + val longitude = 11f + val tilt = 44f + val typedArray = Mockito.mock(TypedArray::class.java) + Mockito.`when`( + typedArray.getFloat( + R.styleable.maplibre_MapView_maplibre_cameraBearing, + 0.0f + ) + ).thenReturn(bearing) + Mockito.`when`( + typedArray.getFloat( + R.styleable.maplibre_MapView_maplibre_cameraTargetLat, + 0.0f + ) + ).thenReturn(latitude) + Mockito.`when`( + typedArray.getFloat( + R.styleable.maplibre_MapView_maplibre_cameraTargetLng, + 0.0f + ) + ).thenReturn(longitude) + Mockito.`when`(typedArray.getFloat(R.styleable.maplibre_MapView_maplibre_cameraZoom, 0.0f)) + .thenReturn(zoom) + Mockito.`when`(typedArray.getFloat(R.styleable.maplibre_MapView_maplibre_cameraTilt, 0.0f)) + .thenReturn(tilt) + Mockito.doNothing().`when`(typedArray).recycle() + val cameraPosition = CameraPosition.Builder(typedArray).build() + Assert.assertEquals( + "bearing should match", + bearing.toDouble(), + cameraPosition.bearing, + DELTA + ) + Assert.assertEquals( + "latlng should match", + LatLng(latitude.toDouble(), longitude.toDouble()), + cameraPosition.target + ) + Assert.assertEquals("tilt should match", tilt.toDouble(), cameraPosition.tilt, DELTA) + Assert.assertEquals("zoom should match", zoom.toDouble(), cameraPosition.zoom, DELTA) + } + + @Test + fun testToString() { + val latLng = LatLng(1.0, 2.0) + val cameraPosition = + CameraPosition(latLng, 3.0, 4.0, 5.0, doubleArrayOf(0.0, 500.0, 0.0, 0.0)) + Assert.assertEquals( + "toString should match", + "Target: LatLng [latitude=1.0, longitude=2.0, altitude=0.0], Zoom:3.0, " + + "Bearing:5.0, Tilt:4.0, Padding:[0.0, 500.0, 0.0, 0.0]", + cameraPosition.toString() + ) + } + + @Test + fun testHashcode() { + val latLng = LatLng(1.0, 2.0) + val cameraPosition = + CameraPosition(latLng, 3.0, 4.0, 5.0, doubleArrayOf(0.0, 500.0, 0.0, 0.0)) + Assert.assertEquals("hashCode should match", -420915327, cameraPosition.hashCode().toLong()) + } + + @Test + fun testZoomUpdateBuilder() { + val zoomLevel = 5f + val builder = CameraPosition.Builder( + zoomTo(zoomLevel.toDouble()) as ZoomUpdate + ) + Assert.assertEquals("zoom should match", zoomLevel.toDouble(), builder.build().zoom, 0.0) + } + + @Test + fun testEquals() { + val latLng = LatLng(1.0, 2.0) + val cameraPosition = + CameraPosition(latLng, 3.0, 4.0, 5.0, doubleArrayOf(0.0, 500.0, 0.0, 0.0)) + val cameraPositionBearing = + CameraPosition(latLng, 3.0, 4.0, 9.0, doubleArrayOf(0.0, 500.0, 0.0, 0.0)) + val cameraPositionTilt = + CameraPosition(latLng, 3.0, 9.0, 5.0, doubleArrayOf(0.0, 500.0, 0.0, 0.0)) + val cameraPositionZoom = + CameraPosition(latLng, 9.0, 4.0, 5.0, doubleArrayOf(0.0, 500.0, 0.0, 0.0)) + val cameraPositionTarget = + CameraPosition(LatLng(), 3.0, 4.0, 5.0, doubleArrayOf(0.0, 500.0, 0.0, 0.0)) + val cameraPositionPadding = + CameraPosition(LatLng(), 3.0, 4.0, 5.0, doubleArrayOf(0.0, 501.0, 0.0, 0.0)) + Assert.assertEquals("cameraPosition should match itself", cameraPosition, cameraPosition) + Assert.assertNotEquals("cameraPosition should not match null", null, cameraPosition) + Assert.assertNotEquals("cameraPosition should not match object", Any(), cameraPosition) + Assert.assertNotEquals( + "cameraPosition should not match for bearing", + cameraPositionBearing, + cameraPosition + ) + Assert.assertNotEquals( + "cameraPosition should not match for tilt", + cameraPositionTilt, + cameraPosition + ) + Assert.assertNotEquals( + "cameraPosition should not match for zoom", + cameraPositionZoom, + cameraPosition + ) + Assert.assertNotEquals( + "cameraPosition should not match for target", + cameraPositionTarget, + cameraPosition + ) + Assert.assertNotEquals( + "cameraPosition should not match for padding", + cameraPositionPadding, + cameraPosition + ) + } + + @Test + fun testParcelable() { + val cameraPosition1 = + CameraPosition(LatLng(1.0, 2.0), 3.0, 4.0, 5.0, doubleArrayOf(0.0, 500.0, 0.0, 0.0)) + val parcel = Parcel.obtain() + cameraPosition1.writeToParcel(parcel, 0) + parcel.setDataPosition(0) + val cameraPosition2 = CameraPosition.CREATOR.createFromParcel(parcel) + Assert.assertEquals("Parcel should match original object", cameraPosition1, cameraPosition2) + } + + @Test + fun testParcelableNulls() { + val cameraPosition1 = CameraPosition(null, 3.0, 4.0, 5.0, null) + val parcel = Parcel.obtain() + cameraPosition1.writeToParcel(parcel, 0) + parcel.setDataPosition(0) + val cameraPosition2 = CameraPosition.CREATOR.createFromParcel(parcel) + Assert.assertEquals("Parcel should match original object", cameraPosition1, cameraPosition2) + } + + companion object { + private const val DELTA = 1e-15 + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/constants/AppConstant.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/constants/AppConstant.java deleted file mode 100644 index cb654aa55..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/constants/AppConstant.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.mapbox.mapboxsdk.constants; - -public class AppConstant { - - public static final int STYLE_VERSION = 9; -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/constants/AppConstant.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/constants/AppConstant.kt new file mode 100644 index 000000000..e7e30d773 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/constants/AppConstant.kt @@ -0,0 +1,5 @@ +package com.mapbox.mapboxsdk.constants + +object AppConstant { + const val STYLE_VERSION = 9 +} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngBoundsTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngBoundsTest.java deleted file mode 100644 index 8eee39772..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngBoundsTest.java +++ /dev/null @@ -1,815 +0,0 @@ -package com.mapbox.mapboxsdk.geometry; - -import android.os.Parcelable; - -import com.mapbox.mapboxsdk.constants.GeometryConstants; -import com.mapbox.mapboxsdk.exceptions.InvalidLatLngBoundsException; -import com.mapbox.mapboxsdk.utils.MockParcel; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -import java.util.ArrayList; -import java.util.List; - -import static junit.framework.Assert.assertNotNull; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -public class LatLngBoundsTest { - - private static final double DELTA = 1e-13; - - private LatLngBounds latLngBounds; - private static final LatLng LAT_LNG_NULL_ISLAND = new LatLng(0, 0); - private static final LatLng LAT_LNG_NOT_NULL_ISLAND = new LatLng(2, 2); - - @Before - public void beforeTest() { - latLngBounds = new LatLngBounds.Builder() - .include(LAT_LNG_NULL_ISLAND) - .include(LAT_LNG_NOT_NULL_ISLAND) - .build(); - } - - @Test - public void testSanity() { - LatLngBounds.Builder latLngBoundsBuilder = new LatLngBounds.Builder(); - latLngBoundsBuilder.include(LAT_LNG_NULL_ISLAND).include(LAT_LNG_NOT_NULL_ISLAND); - assertNotNull("latLng should not be null", latLngBoundsBuilder.build()); - } - - @Test(expected = InvalidLatLngBoundsException.class) - public void noLatLngs() { - new LatLngBounds.Builder().build(); - } - - @Test(expected = InvalidLatLngBoundsException.class) - public void oneLatLngs() { - new LatLngBounds.Builder().include(LAT_LNG_NULL_ISLAND).build(); - } - - @Test - public void latitiudeSpan() { - assertEquals("Span should be the same", 2, latLngBounds.getLatitudeSpan(), DELTA); - } - - @Test - public void longitudeSpan() { - assertEquals("Span should be the same", 2, latLngBounds.getLongitudeSpan(), DELTA); - } - - @Test - public void coordinateSpan() { - LatLngSpan latLngSpan = latLngBounds.getSpan(); - assertEquals("LatLngSpan should be the same", new LatLngSpan(2, 2), latLngSpan); - } - - @Test - public void dateLineSpanBuilder1() { - latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(10, -170)) - .include(new LatLng(-10, 170)) - .build(); - - LatLngSpan latLngSpan = latLngBounds.getSpan(); - assertEquals("LatLngSpan should be the same", new LatLngSpan(20, 340), - latLngSpan); - } - - @Test - public void dateLineSpanBuilder2() { - latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(-10, -170)) - .include(new LatLng(10, 170)) - .build(); - - LatLngSpan latLngSpan = latLngBounds.getSpan(); - assertEquals("LatLngSpan should be the same", new LatLngSpan(20, 340), - latLngSpan); - } - - @Test - public void dateLineSpanFrom1() { - latLngBounds = LatLngBounds.from(10, -170, -10, -190); - LatLngSpan latLngSpan = latLngBounds.getSpan(); - assertEquals("LatLngSpan should be the same", new LatLngSpan(20, 20), - latLngSpan); - } - - @Test - public void dateLineSpanFrom2() { - latLngBounds = LatLngBounds.from(10, 170, -10, -170); - LatLngSpan latLngSpan = latLngBounds.getSpan(); - assertEquals("LatLngSpan should be the same", new LatLngSpan(20, 340), - latLngSpan); - } - - @Test - public void zeroLongitudeSpan() { - latLngBounds = LatLngBounds.from(10, 10, -10, 10); - LatLngSpan latLngSpan = latLngBounds.getSpan(); - assertEquals("LatLngSpan should be shortest distance", new LatLngSpan(20, 0), - latLngSpan); - } - - @Test - public void nearDateLineCenter1() { - latLngBounds = LatLngBounds.from(10, -175, -10, -195); - LatLng center = latLngBounds.getCenter(); - assertEquals("Center should match", new LatLng(0, -185), center); - } - - @Test - public void nearDateLineCenter2() { - latLngBounds = LatLngBounds.from(10, 195, -10, 175); - LatLng center = latLngBounds.getCenter(); - assertEquals("Center should match", new LatLng(0, 185), center); - } - - @Test - public void nearDateLineCenter3() { - latLngBounds = LatLngBounds.from(10, -170, -10, -190); - LatLng center = latLngBounds.getCenter(); - assertEquals("Center should match", new LatLng(0, -180), center); - } - - @Test - public void nearDateLineCenter4() { - latLngBounds = LatLngBounds.from(10, 180, -10, 0); - LatLng center = latLngBounds.getCenter(); - assertEquals("Center should match", new LatLng(0, 90), center); - } - - @Test - public void nearDateLineCenter5() { - latLngBounds = LatLngBounds.from(10, 180, -10, 0); - LatLng center = latLngBounds.getCenter(); - assertEquals("Center should match", new LatLng(0, 90), center); - } - - @Test - public void centerForBoundsWithSameLongitude() { - latLngBounds = LatLngBounds.from(10, 10, -10, 10); - LatLng center = latLngBounds.getCenter(); - assertEquals("Center should match", new LatLng(0, 10), center); - } - - @Test - public void centerForBoundsWithSameLatitude() { - latLngBounds = LatLngBounds.from(10, 10, 10, -10); - LatLng center = latLngBounds.getCenter(); - assertEquals("Center should match", new LatLng(10, 0), center); - } - - @Test - public void center() { - LatLng center = latLngBounds.getCenter(); - assertEquals("Center should match", new LatLng(1, 1), center); - } - - @Test - public void notEmptySpan() { - latLngBounds = new LatLngBounds.Builder() - .include(LAT_LNG_NOT_NULL_ISLAND) - .include(LAT_LNG_NULL_ISLAND) - .build(); - assertFalse("Should not be empty", latLngBounds.isEmptySpan()); - } - - @Test - public void includeSameLatLngs() { - latLngBounds = new LatLngBounds.Builder() - .include(LAT_LNG_NOT_NULL_ISLAND) - .include(LAT_LNG_NOT_NULL_ISLAND) - .include(LAT_LNG_NULL_ISLAND) - .include(LAT_LNG_NULL_ISLAND) - .build(); - assertEquals(latLngBounds.getNorthEast(), LAT_LNG_NOT_NULL_ISLAND); - assertEquals(latLngBounds.getSouthWest(), LAT_LNG_NULL_ISLAND); - } - - @Test - public void toLatLngs() { - latLngBounds = new LatLngBounds.Builder() - .include(LAT_LNG_NOT_NULL_ISLAND) - .include(LAT_LNG_NULL_ISLAND) - .build(); - - assertArrayEquals("LatLngs should match", - new LatLng[] {LAT_LNG_NOT_NULL_ISLAND, LAT_LNG_NULL_ISLAND}, - latLngBounds.toLatLngs()); - } - - @Test - public void include() { - assertTrue("LatLng should be included", latLngBounds.contains(new LatLng(1, 1))); - } - - @Test - public void includes() { - List points = new ArrayList<>(); - points.add(LAT_LNG_NULL_ISLAND); - points.add(LAT_LNG_NOT_NULL_ISLAND); - - LatLngBounds latLngBounds1 = new LatLngBounds.Builder() - .includes(points) - .build(); - - LatLngBounds latLngBounds2 = new LatLngBounds.Builder() - .include(LAT_LNG_NULL_ISLAND) - .include(LAT_LNG_NOT_NULL_ISLAND) - .build(); - - assertEquals("LatLngBounds should match", latLngBounds1, latLngBounds2); - } - - @Test - public void includesOrderDoesNotMatter() { - LatLngBounds sameLongitudeFirst = new LatLngBounds.Builder() - .include(new LatLng(50, 10)) // southWest - .include(new LatLng(60, 10)) - .include(new LatLng(60, 20)) // northEast - .include(new LatLng(50, 20)) - .include(new LatLng(50, 10)) // southWest again - .build(); - - LatLngBounds sameLatitudeFirst = new LatLngBounds.Builder() - .include(new LatLng(50, 20)) - .include(new LatLng(50, 10)) // southWest - .include(new LatLng(60, 10)) - .include(new LatLng(60, 20)) // northEast - .include(new LatLng(50, 20)) - .build(); - - assertEquals(sameLatitudeFirst, sameLongitudeFirst); - } - - @Test - public void includesOverDateline1() { - - LatLngBounds latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(10, -170)) - .include(new LatLng(-10, -175)) - .include(new LatLng(0, -190)) - .build(); - - LatLngSpan latLngSpan = latLngBounds.getSpan(); - assertEquals("LatLngSpan should be the same", - new LatLngSpan(20, 20), latLngSpan); - } - - @Test - public void includesOverDateline2() { - - LatLngBounds latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(10, 170)) - .include(new LatLng(-10, 175)) - .include(new LatLng(0, 190)) - .build(); - - assertEquals("LatLngSpan should be the same", - new LatLngSpan(20, 20), latLngBounds.getSpan()); - } - - @Test - public void includesOverDateline3() { - - LatLngBounds latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(10, -190)) - .include(new LatLng(-10, -170)) - .include(new LatLng(0, -180)) - .include(new LatLng(5, -180)) - .build(); - - assertEquals("LatLngSpan should be the same", - new LatLngSpan(20, 20), latLngBounds.getSpan()); - } - - @Test - public void containsNot() { - assertFalse("LatLng should not be included", - latLngBounds.contains(new LatLng(3, 1))); - } - - @Test - public void containsBoundsInWorld() { - assertTrue("LatLngBounds should be contained in the world", - LatLngBounds.world().contains(latLngBounds)); - } - - @Test - public void worldSpan() { - assertEquals("LatLngBounds world span should be 180, 360", - GeometryConstants.LATITUDE_SPAN, LatLngBounds.world().getLatitudeSpan(), DELTA); - assertEquals("LatLngBounds world span should be 180, 360", - GeometryConstants.LONGITUDE_SPAN, LatLngBounds.world().getLongitudeSpan(), DELTA); - } - - @Test - public void emptySpan() { - LatLngBounds latLngBounds = LatLngBounds.from( - GeometryConstants.MIN_LATITUDE, GeometryConstants.MAX_LONGITUDE, - GeometryConstants.MIN_LATITUDE, GeometryConstants.MAX_LONGITUDE); - assertTrue("LatLngBounds empty span", latLngBounds.isEmptySpan()); - } - - @Test - public void containsBounds() { - LatLngBounds inner = new LatLngBounds.Builder() - .include(new LatLng(-5, -5)) - .include(new LatLng(5, 5)) - .build(); - LatLngBounds outer = new LatLngBounds.Builder() - .include(new LatLng(-10, -10)) - .include(new LatLng(10, 10)) - .build(); - assertTrue(outer.contains(inner)); - assertFalse(inner.contains(outer)); - } - - @Test - public void testHashCode() { - assertEquals(2147483647, latLngBounds.hashCode(), -1946419200); - } - - @Test - public void equality() { - LatLngBounds latLngBounds = new LatLngBounds.Builder() - .include(LAT_LNG_NULL_ISLAND) - .include(LAT_LNG_NOT_NULL_ISLAND) - .build(); - assertEquals("equality should match", this.latLngBounds, latLngBounds); - assertEquals("not equal to a different object type", - this.latLngBounds.equals(LAT_LNG_NOT_NULL_ISLAND), false); - } - - @Test - public void testToString() { - assertEquals(latLngBounds.toString(), "N:2.0; E:2.0; S:0.0; W:0.0"); - } - - @Test - public void intersect() { - LatLngBounds latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(1, 1)) - .include(LAT_LNG_NULL_ISLAND) - .build(); - assertEquals("intersect should match", latLngBounds, - latLngBounds.intersect(this.latLngBounds.getLatNorth(), - this.latLngBounds.getLonEast(), - this.latLngBounds.getLatSouth(), - this.latLngBounds.getLonWest())); - } - - @Test - public void intersectNot() { - LatLngBounds latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(10, 10)) - .include(new LatLng(9, 8)) - .build(); - assertNull(latLngBounds.intersect(this.latLngBounds)); - } - - @Test - public void intersectNorthCheck() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must be between -90 and 90"); - LatLngBounds intersectLatLngBounds = - LatLngBounds.from(10, 10, 0, 0) - .intersect(200, 200, 0, 0); - } - - @Test - public void intersectSouthCheck() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must be between -90 and 90"); - LatLngBounds intersectLatLngBounds = - LatLngBounds.from(0, 0, -10, -10) - .intersect(0, 0, -200, -200); - } - - @Test - public void intersectSouthLessThanNorthCheck() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latNorth cannot be less than latSouth"); - LatLngBounds intersectLatLngBounds = - LatLngBounds.from(10, 10, 0, 0) - .intersect(0, 200, 20, 0); - } - - @Test - public void intersectEastLessThanWestCheck() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("lonEast cannot be less than lonWest"); - LatLngBounds intersectLatLngBounds = - LatLngBounds.from(10, -10, 0, 0) - .intersect(0, 200, 20, 0); - } - - public void intersectEastDoesNotWrapCheck() { - - LatLngBounds latLngBounds1 = LatLngBounds.from(10, 210, 0, 0); - LatLngBounds latLngBounds2 = LatLngBounds.from(90, 200, 0, 0); - - LatLngBounds intersectLatLngBounds = LatLngBounds.from(10, 200, 0, 0); - - assertEquals(latLngBounds1.intersect(latLngBounds2), intersectLatLngBounds); - assertEquals(latLngBounds2.intersect(latLngBounds1), intersectLatLngBounds); - } - - @Test - public void intersectDoesNotWestWrapCheck() { - LatLngBounds latLngBounds1 = LatLngBounds.from(0, 0, -10, -210); - LatLngBounds latLngBounds2 = LatLngBounds.from(0, 0, -90, -200); - - LatLngBounds intersectLatLngBounds = LatLngBounds.from(0, 0, -10, -200); - - assertEquals(latLngBounds1.intersect(latLngBounds2), intersectLatLngBounds); - assertEquals(latLngBounds2.intersect(latLngBounds1), intersectLatLngBounds); - } - - @Test - public void innerUnion() { - LatLngBounds latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(1, 1)) - .include(LAT_LNG_NULL_ISLAND) - .build(); - assertEquals("union should match", latLngBounds, latLngBounds.intersect(this.latLngBounds)); - } - - @Test - public void outerUnion() { - LatLngBounds latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(10, 10)) - .include(new LatLng(9, 8)) - .build(); - assertEquals("outer union should match", - latLngBounds.union(this.latLngBounds), - new LatLngBounds.Builder() - .include(new LatLng(10, 10)) - .include(LAT_LNG_NULL_ISLAND) - .build()); - } - - @Test - public void unionOverDateLine() { - LatLngBounds latLngBounds1 = new LatLngBounds.Builder() - .include(new LatLng(10, 170)) - .include(new LatLng(0, 160)) - .build(); - - LatLngBounds latLngBounds2 = new LatLngBounds.Builder() - .include(new LatLng(0, 190)) - .include(new LatLng(-10, 200)) - .build(); - - LatLngBounds union1 = latLngBounds1.union(latLngBounds2); - LatLngBounds union2 = latLngBounds2.union(latLngBounds1); - - assertEquals(union1, - new LatLngBounds.Builder() - .include(new LatLng(10, 160)) - .include(new LatLng(-10, 200)) - .build()); - - assertEquals(union1, union2); - } - - @Test - public void unionOverDateLine2() { - LatLngBounds latLngBounds1 = new LatLngBounds.Builder() - .include(new LatLng(10, 170)) - .include(new LatLng(0, 160)) - .build(); - - LatLngBounds latLngBounds2 = new LatLngBounds.Builder() - .include(new LatLng(0, 165)) - .include(new LatLng(-10, 200)) - .build(); - - LatLngBounds union1 = latLngBounds1.union(latLngBounds2); - LatLngBounds union2 = latLngBounds2.union(latLngBounds1); - - assertEquals(union1, - new LatLngBounds.Builder() - .include(new LatLng(10, 160)) - .include(new LatLng(-10, 200)) - .build()); - - assertEquals(union1, union2); - } - - @Test - public void unionOverDateLine3() { - LatLngBounds latLngBounds1 = new LatLngBounds.Builder() - .include(new LatLng(10, 195)) - .include(new LatLng(0, 160)) - .build(); - - LatLngBounds latLngBounds2 = new LatLngBounds.Builder() - .include(new LatLng(0, 190)) - .include(new LatLng(-10, 200)) - .build(); - - LatLngBounds union1 = latLngBounds1.union(latLngBounds2); - LatLngBounds union2 = latLngBounds2.union(latLngBounds1); - - assertEquals(union1, - new LatLngBounds.Builder() - .include(new LatLng(10, 160)) - .include(new LatLng(-10, 200)) - .build()); - - assertEquals(union1, union2); - } - - @Test - public void unionOverDateLine4() { - LatLngBounds latLngBounds1 = new LatLngBounds.Builder() - .include(new LatLng(10, -160)) - .include(new LatLng(0, -200)) - .build(); - - LatLngBounds latLngBounds2 = new LatLngBounds.Builder() - .include(new LatLng(0, -170)) - .include(new LatLng(-10, -175)) - .build(); - - LatLngBounds union1 = latLngBounds1.union(latLngBounds2); - LatLngBounds union2 = latLngBounds2.union(latLngBounds1); - - assertEquals(union1, - new LatLngBounds.Builder() - .include(new LatLng(10, -200)) - .include(new LatLng(-10, -160)) - .build()); - - assertEquals(union1, union2); - } - - @Test - public void unionOverDateLine5() { - LatLngBounds latLngBounds1 = new LatLngBounds.Builder() - .include(new LatLng(10, 200)) - .include(new LatLng(0, 160)) - .build(); - - LatLngBounds latLngBounds2 = new LatLngBounds.Builder() - .include(new LatLng(0, 170)) - .include(new LatLng(-10, 175)) - .build(); - - LatLngBounds union1 = latLngBounds1.union(latLngBounds2); - LatLngBounds union2 = latLngBounds2.union(latLngBounds1); - - assertEquals(union1, - new LatLngBounds.Builder() - .include(new LatLng(10, 160)) - .include(new LatLng(-10, 200)) - .build()); - - assertEquals(union1, union2); - } - - @Test - public void unionOverDateLineReturnLongerThanWorldLonSpan() { - LatLngBounds latLngBounds1 = LatLngBounds.from(10, 200, -10, -10); - LatLngBounds latLngBounds2 = LatLngBounds.from(10, 10, -10, -200); - - LatLngBounds union1 = latLngBounds1.union(latLngBounds2); - LatLngBounds union2 = latLngBounds2.union(latLngBounds1); - - assertEquals(union1, union2); - assertEquals(union1, LatLngBounds.from(10, 200, -10, -200)); - } - - @Test - public void unionNorthCheck() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must be between -90 and 90"); - LatLngBounds unionLatLngBounds = - LatLngBounds.from(10, 10, 0, 0) - .union(200, 200, 0, 0); - } - - @Test - public void unionSouthCheck() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must be between -90 and 90"); - LatLngBounds unionLatLngBounds = - LatLngBounds.from(0, 0, -10, -10) - .union(0, 0, -200, -200); - } - - @Test - public void unionSouthLessThanNorthCheck() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latNorth cannot be less than latSouth"); - - LatLngBounds unionLatLngBounds = - LatLngBounds.from(10, 10, 0, 0) - .union(0, 200, 20, 0); - } - - - @Test - public void unionEastDoesNotWrapCheck() { - - LatLngBounds latLngBounds1 = LatLngBounds.from(10, 10, 0, 0); - LatLngBounds latLngBounds2 = LatLngBounds.from(90, 200, 0, 0); - LatLngBounds unionLatLngBounds = LatLngBounds.from(90, 200, 0, 0); - - assertEquals(latLngBounds1.union(latLngBounds2), unionLatLngBounds); - assertEquals(latLngBounds2.union(latLngBounds1), unionLatLngBounds); - } - - @Test - public void unionWestDoesNotWrapCheck() { - LatLngBounds latLngBounds1 = LatLngBounds.from(0, 0, -10, -10); - LatLngBounds latLngBounds2 = LatLngBounds.from(0, 0, -90, -200); - - LatLngBounds unionLatLngBounds = LatLngBounds.from(0, 0, -90, -200); - - assertEquals(latLngBounds1.union(latLngBounds2), unionLatLngBounds); - assertEquals(latLngBounds2.union(latLngBounds1), unionLatLngBounds); - } - - @Test - public void northWest() { - double minLat = 5; - double minLon = 6; - double maxLat = 20; - double maxLon = 21; - - LatLngBounds latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(minLat, minLon)) - .include(new LatLng(maxLat, maxLon)) - .build(); - - assertEquals("NorthWest should match", latLngBounds.getNorthWest(), new LatLng(maxLat, minLon)); - } - - @Test - public void southWest() { - double minLat = 5; - double minLon = 6; - double maxLat = 20; - double maxLon = 21; - - LatLngBounds latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(minLat, minLon)) - .include(new LatLng(maxLat, maxLon)) - .build(); - - assertEquals("SouthWest should match", latLngBounds.getSouthWest(), new LatLng(minLat, minLon)); - } - - @Test - public void northEast() { - double minLat = 5; - double minLon = 6; - double maxLat = 20; - double maxLon = 21; - - LatLngBounds latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(minLat, minLon)) - .include(new LatLng(maxLat, maxLon)) - .build(); - - assertEquals("NorthEast should match", latLngBounds.getNorthEast(), new LatLng(maxLat, maxLon)); - } - - @Test - public void southEast() { - double minLat = 5; - double minLon = 6; - double maxLat = 20; - double maxLon = 21; - - LatLngBounds latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(minLat, minLon)) - .include(new LatLng(maxLat, maxLon)) - .build(); - - assertEquals("SouthEast should match", latLngBounds.getSouthEast(), new LatLng(minLat, maxLon)); - } - - @Test - public void testParcelable() { - LatLngBounds latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(10, 10)) - .include(new LatLng(9, 8)) - .build(); - Parcelable parcel = MockParcel.obtain(latLngBounds); - assertEquals("Parcel should match original object", parcel, latLngBounds); - } - - @Test - public void fromTileID() { - LatLngBounds bounds = LatLngBounds.from(0, 0, 0); - assertEquals(GeometryConstants.MIN_WRAP_LONGITUDE, bounds.getLonWest(), DELTA); - assertEquals(GeometryConstants.MIN_MERCATOR_LATITUDE, bounds.getLatSouth(), DELTA); - assertEquals(GeometryConstants.MAX_WRAP_LONGITUDE, bounds.getLonEast(), DELTA); - assertEquals(GeometryConstants.MAX_MERCATOR_LATITUDE, bounds.getLatNorth(), DELTA); - - bounds = LatLngBounds.from(10, 288, 385); - assertEquals(-78.75, bounds.getLonWest(), DELTA); - assertEquals(40.446947059600497, bounds.getLatSouth(), DELTA); - assertEquals(-78.3984375, bounds.getLonEast(), DELTA); - assertEquals(40.713955826286039, bounds.getLatNorth(), DELTA); - - } - - @Rule - public final ExpectedException exception = ExpectedException.none(); - - @Test - public void testConstructorChecksNorthLatitudeNaN() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must not be NaN"); - LatLngBounds.from(Double.NaN, 0, -20, -20); - } - - @Test - public void testConstructorChecksEastLongitudeNaN() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("longitude must not be NaN"); - LatLngBounds.from(0, Double.NaN, -20, -20); - } - - @Test - public void testConstructorChecksNorthLatitudeGreaterThan90() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must be between -90 and 90"); - LatLngBounds.from(95, 0, -20, -20); - } - - @Test - public void testConstructorChecksNorthLatitudeLessThanThanNegative90() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must be between -90 and 90"); - LatLngBounds.from(-95, 0, -20, -20); - } - - @Test - public void testConstructorChecksEastLongitudeInfinity() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("longitude must not be infinite"); - LatLngBounds.from(0, Double.POSITIVE_INFINITY, -20, -20); - } - - @Test - public void testConstructorChecksSouthLatitudeNaN() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must not be NaN"); - LatLngBounds.from(20, 20, Double.NaN, 0); - } - - @Test - public void testConstructorChecksWesttLongitudeNaN() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("longitude must not be NaN"); - LatLngBounds.from(20, 20, 0, Double.NaN); - } - - @Test - public void testConstructorChecksSouthLatitudeGreaterThan90() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must be between -90 and 90"); - LatLngBounds.from(20, 20, 95, 0); - } - - @Test - public void testConstructorChecksSouthLatitudeLessThanThanNegative90() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must be between -90 and 90"); - LatLngBounds.from(20, 20, -95, 0); - } - - @Test - public void testConstructorChecksWestLongitudeInfinity() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("longitude must not be infinite"); - LatLngBounds.from(20, 20, 0, Double.POSITIVE_INFINITY); - } - - @Test - public void testConstructorCheckLatSouthGreaterLatNorth() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latNorth cannot be less than latSouth"); - LatLngBounds.from(0, 20, 20, 0); - } - - @Test - public void testConstructorCheckLonWestGreaterLonEast() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("lonEast cannot be less than lonWest"); - LatLngBounds.from(20, 0, 0, 20); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngBoundsTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngBoundsTest.kt new file mode 100644 index 000000000..431329cd9 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngBoundsTest.kt @@ -0,0 +1,858 @@ +package com.mapbox.mapboxsdk.geometry + +import com.mapbox.mapboxsdk.constants.GeometryConstants +import com.mapbox.mapboxsdk.exceptions.InvalidLatLngBoundsException +import com.mapbox.mapboxsdk.geometry.LatLngBounds.Companion.from +import com.mapbox.mapboxsdk.geometry.LatLngBounds.Companion.world +import com.mapbox.mapboxsdk.utils.MockParcel +import junit.framework.Assert +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.ExpectedException + +class LatLngBoundsTest { + private var latLngBounds: LatLngBounds? = null + + @Before + fun beforeTest() { + latLngBounds = LatLngBounds.Builder() + .include(LAT_LNG_NULL_ISLAND) + .include(LAT_LNG_NOT_NULL_ISLAND) + .build() + } + + @Test + fun testSanity() { + val latLngBoundsBuilder = LatLngBounds.Builder() + latLngBoundsBuilder.include(LAT_LNG_NULL_ISLAND).include(LAT_LNG_NOT_NULL_ISLAND) + Assert.assertNotNull("latLng should not be null", latLngBoundsBuilder.build()) + } + + @Test(expected = InvalidLatLngBoundsException::class) + fun noLatLngs() { + LatLngBounds.Builder().build() + } + + @Test(expected = InvalidLatLngBoundsException::class) + fun oneLatLngs() { + LatLngBounds.Builder().include(LAT_LNG_NULL_ISLAND).build() + } + + @Test + fun latitiudeSpan() { + org.junit.Assert.assertEquals( + "Span should be the same", + 2.0, + latLngBounds!!.latitudeSpan, + DELTA + ) + } + + @Test + fun longitudeSpan() { + org.junit.Assert.assertEquals( + "Span should be the same", + 2.0, + latLngBounds!!.longitudeSpan, + DELTA + ) + } + + @Test + fun coordinateSpan() { + val latLngSpan = latLngBounds!!.span + org.junit.Assert.assertEquals( + "LatLngSpan should be the same", + LatLngSpan(2.0, 2.0), + latLngSpan + ) + } + + @Test + fun dateLineSpanBuilder1() { + latLngBounds = LatLngBounds.Builder() + .include(LatLng(10.0, -170.0)) + .include(LatLng(-10.0, 170.0)) + .build() + val latLngSpan = latLngBounds!!.span + org.junit.Assert.assertEquals( + "LatLngSpan should be the same", + LatLngSpan(20.0, 340.0), + latLngSpan + ) + } + + @Test + fun dateLineSpanBuilder2() { + latLngBounds = LatLngBounds.Builder() + .include(LatLng(-10.0, -170.0)) + .include(LatLng(10.0, 170.0)) + .build() + val latLngSpan = latLngBounds!!.span + org.junit.Assert.assertEquals( + "LatLngSpan should be the same", + LatLngSpan(20.0, 340.0), + latLngSpan + ) + } + + @Test + fun dateLineSpanFrom1() { + latLngBounds = from(10.0, -170.0, -10.0, -190.0) + val latLngSpan = latLngBounds!!.span + org.junit.Assert.assertEquals( + "LatLngSpan should be the same", + LatLngSpan(20.0, 20.0), + latLngSpan + ) + } + + @Test + fun dateLineSpanFrom2() { + latLngBounds = from(10.0, 170.0, -10.0, -170.0) + val latLngSpan = latLngBounds!!.span + org.junit.Assert.assertEquals( + "LatLngSpan should be the same", + LatLngSpan(20.0, 340.0), + latLngSpan + ) + } + + @Test + fun zeroLongitudeSpan() { + latLngBounds = from(10.0, 10.0, -10.0, 10.0) + val latLngSpan = latLngBounds!!.span + org.junit.Assert.assertEquals( + "LatLngSpan should be shortest distance", + LatLngSpan(20.0, 0.0), + latLngSpan + ) + } + + @Test + fun nearDateLineCenter1() { + latLngBounds = from(10.0, -175.0, -10.0, -195.0) + val center = latLngBounds!!.center + org.junit.Assert.assertEquals("Center should match", LatLng(0.0, -185.0), center) + } + + @Test + fun nearDateLineCenter2() { + latLngBounds = from(10.0, 195.0, -10.0, 175.0) + val center = latLngBounds!!.center + org.junit.Assert.assertEquals("Center should match", LatLng(0.0, 185.0), center) + } + + @Test + fun nearDateLineCenter3() { + latLngBounds = from(10.0, -170.0, -10.0, -190.0) + val center = latLngBounds!!.center + org.junit.Assert.assertEquals("Center should match", LatLng(0.0, -180.0), center) + } + + @Test + fun nearDateLineCenter4() { + latLngBounds = from(10.0, 180.0, -10.0, 0.0) + val center = latLngBounds!!.center + org.junit.Assert.assertEquals("Center should match", LatLng(0.0, 90.0), center) + } + + @Test + fun nearDateLineCenter5() { + latLngBounds = from(10.0, 180.0, -10.0, 0.0) + val center = latLngBounds!!.center + org.junit.Assert.assertEquals("Center should match", LatLng(0.0, 90.0), center) + } + + @Test + fun centerForBoundsWithSameLongitude() { + latLngBounds = from(10.0, 10.0, -10.0, 10.0) + val center = latLngBounds!!.center + org.junit.Assert.assertEquals("Center should match", LatLng(0.0, 10.0), center) + } + + @Test + fun centerForBoundsWithSameLatitude() { + latLngBounds = from(10.0, 10.0, 10.0, -10.0) + val center = latLngBounds!!.center + org.junit.Assert.assertEquals("Center should match", LatLng(10.0, 0.0), center) + } + + @Test + fun center() { + val center = latLngBounds!!.center + org.junit.Assert.assertEquals("Center should match", LatLng(1.0, 1.0), center) + } + + @Test + fun notEmptySpan() { + latLngBounds = LatLngBounds.Builder() + .include(LAT_LNG_NOT_NULL_ISLAND) + .include(LAT_LNG_NULL_ISLAND) + .build() + org.junit.Assert.assertFalse("Should not be empty", latLngBounds!!.isEmptySpan) + } + + @Test + fun includeSameLatLngs() { + latLngBounds = LatLngBounds.Builder() + .include(LAT_LNG_NOT_NULL_ISLAND) + .include(LAT_LNG_NOT_NULL_ISLAND) + .include(LAT_LNG_NULL_ISLAND) + .include(LAT_LNG_NULL_ISLAND) + .build() + org.junit.Assert.assertEquals(latLngBounds!!.northEast, LAT_LNG_NOT_NULL_ISLAND) + org.junit.Assert.assertEquals(latLngBounds!!.southWest, LAT_LNG_NULL_ISLAND) + } + + @Test + fun toLatLngs() { + latLngBounds = LatLngBounds.Builder() + .include(LAT_LNG_NOT_NULL_ISLAND) + .include(LAT_LNG_NULL_ISLAND) + .build() + org.junit.Assert.assertArrayEquals( + "LatLngs should match", + arrayOf(LAT_LNG_NOT_NULL_ISLAND, LAT_LNG_NULL_ISLAND), + latLngBounds!!.toLatLngs() + ) + } + + @Test + fun include() { + org.junit.Assert.assertTrue( + "LatLng should be included", + latLngBounds!!.contains(LatLng(1.0, 1.0)) + ) + } + + @Test + fun includes() { + val points: MutableList = ArrayList() + points.add(LAT_LNG_NULL_ISLAND) + points.add(LAT_LNG_NOT_NULL_ISLAND) + val latLngBounds1 = LatLngBounds.Builder() + .includes(points) + .build() + val latLngBounds2 = LatLngBounds.Builder() + .include(LAT_LNG_NULL_ISLAND) + .include(LAT_LNG_NOT_NULL_ISLAND) + .build() + org.junit.Assert.assertEquals("LatLngBounds should match", latLngBounds1, latLngBounds2) + } + + @Test + fun includesOrderDoesNotMatter() { + val sameLongitudeFirst = LatLngBounds.Builder() + .include(LatLng(50.0, 10.0)) // southWest + .include(LatLng(60.0, 10.0)) + .include(LatLng(60.0, 20.0)) // northEast + .include(LatLng(50.0, 20.0)) + .include(LatLng(50.0, 10.0)) // southWest again + .build() + val sameLatitudeFirst = LatLngBounds.Builder() + .include(LatLng(50.0, 20.0)) + .include(LatLng(50.0, 10.0)) // southWest + .include(LatLng(60.0, 10.0)) + .include(LatLng(60.0, 20.0)) // northEast + .include(LatLng(50.0, 20.0)) + .build() + org.junit.Assert.assertEquals(sameLatitudeFirst, sameLongitudeFirst) + } + + @Test + fun includesOverDateline1() { + val latLngBounds = LatLngBounds.Builder() + .include(LatLng(10.0, -170.0)) + .include(LatLng(-10.0, -175.0)) + .include(LatLng(0.0, -190.0)) + .build() + val latLngSpan = latLngBounds.span + org.junit.Assert.assertEquals( + "LatLngSpan should be the same", + LatLngSpan(20.0, 20.0), + latLngSpan + ) + } + + @Test + fun includesOverDateline2() { + val latLngBounds = LatLngBounds.Builder() + .include(LatLng(10.0, 170.0)) + .include(LatLng(-10.0, 175.0)) + .include(LatLng(0.0, 190.0)) + .build() + org.junit.Assert.assertEquals( + "LatLngSpan should be the same", + LatLngSpan(20.0, 20.0), + latLngBounds.span + ) + } + + @Test + fun includesOverDateline3() { + val latLngBounds = LatLngBounds.Builder() + .include(LatLng(10.0, -190.0)) + .include(LatLng(-10.0, -170.0)) + .include(LatLng(0.0, -180.0)) + .include(LatLng(5.0, -180.0)) + .build() + org.junit.Assert.assertEquals( + "LatLngSpan should be the same", + LatLngSpan(20.0, 20.0), + latLngBounds.span + ) + } + + @Test + fun containsNot() { + org.junit.Assert.assertFalse( + "LatLng should not be included", + latLngBounds!!.contains(LatLng(3.0, 1.0)) + ) + } + + @Test + fun containsBoundsInWorld() { + org.junit.Assert.assertTrue( + "LatLngBounds should be contained in the world", + world().contains(latLngBounds!!) + ) + } + + @Test + fun worldSpan() { + org.junit.Assert.assertEquals( + "LatLngBounds world span should be 180, 360", + GeometryConstants.LATITUDE_SPAN, + world().latitudeSpan, + DELTA + ) + org.junit.Assert.assertEquals( + "LatLngBounds world span should be 180, 360", + GeometryConstants.LONGITUDE_SPAN, + world().longitudeSpan, + DELTA + ) + } + + @Test + fun emptySpan() { + val latLngBounds = from( + GeometryConstants.MIN_LATITUDE, + GeometryConstants.MAX_LONGITUDE, + GeometryConstants.MIN_LATITUDE, + GeometryConstants.MAX_LONGITUDE + ) + org.junit.Assert.assertTrue("LatLngBounds empty span", latLngBounds.isEmptySpan) + } + + @Test + fun containsBounds() { + val inner = LatLngBounds.Builder() + .include(LatLng(-5.0, -5.0)) + .include(LatLng(5.0, 5.0)) + .build() + val outer = LatLngBounds.Builder() + .include(LatLng(-10.0, -10.0)) + .include(LatLng(10.0, 10.0)) + .build() + org.junit.Assert.assertTrue(outer.contains(inner)) + org.junit.Assert.assertFalse(inner.contains(outer)) + } + + @Test + fun testHashCode() { + org.junit.Assert.assertEquals(2147483647f, latLngBounds.hashCode().toFloat(), -1946419200f) + } + + @Test + fun equality() { + val latLngBounds = LatLngBounds.Builder() + .include(LAT_LNG_NULL_ISLAND) + .include(LAT_LNG_NOT_NULL_ISLAND) + .build() + org.junit.Assert.assertEquals("equality should match", this.latLngBounds, latLngBounds) + org.junit.Assert.assertEquals( + "not equal to a different object type", + this.latLngBounds!!.equals(LAT_LNG_NOT_NULL_ISLAND), + false + ) + } + + @Test + fun testToString() { + org.junit.Assert.assertEquals(latLngBounds.toString(), "N:2.0; E:2.0; S:0.0; W:0.0") + } + + @Test + fun intersect() { + val latLngBounds = LatLngBounds.Builder() + .include(LatLng(1.0, 1.0)) + .include(LAT_LNG_NULL_ISLAND) + .build() + org.junit.Assert.assertEquals( + "intersect should match", + latLngBounds, + latLngBounds.intersect( + this.latLngBounds!!.getLatNorth(), + this.latLngBounds!!.getLonEast(), + this.latLngBounds!!.getLatSouth(), + this.latLngBounds!!.getLonWest() + ) + ) + } + + @Test + fun intersectNot() { + val latLngBounds = LatLngBounds.Builder() + .include(LatLng(10.0, 10.0)) + .include(LatLng(9.0, 8.0)) + .build() + org.junit.Assert.assertNull(latLngBounds.intersect(this.latLngBounds!!)) + } + + @Test + fun intersectNorthCheck() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("latitude must be between -90 and 90") + val intersectLatLngBounds = from(10.0, 10.0, 0.0, 0.0) + .intersect(200.0, 200.0, 0.0, 0.0) + } + + @Test + fun intersectSouthCheck() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("latitude must be between -90 and 90") + val intersectLatLngBounds = from(0.0, 0.0, -10.0, -10.0) + .intersect(0.0, 0.0, -200.0, -200.0) + } + + @Test + fun intersectSouthLessThanNorthCheck() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("latNorth cannot be less than latSouth") + val intersectLatLngBounds = from(10.0, 10.0, 0.0, 0.0) + .intersect(0.0, 200.0, 20.0, 0.0) + } + + @Test + fun intersectEastLessThanWestCheck() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("lonEast cannot be less than lonWest") + val intersectLatLngBounds = from(10.0, -10.0, 0.0, 0.0) + .intersect(0.0, 200.0, 20.0, 0.0) + } + + fun intersectEastDoesNotWrapCheck() { + val latLngBounds1 = from(10.0, 210.0, 0.0, 0.0) + val latLngBounds2 = from(90.0, 200.0, 0.0, 0.0) + val intersectLatLngBounds = from(10.0, 200.0, 0.0, 0.0) + org.junit.Assert.assertEquals(latLngBounds1.intersect(latLngBounds2), intersectLatLngBounds) + org.junit.Assert.assertEquals(latLngBounds2.intersect(latLngBounds1), intersectLatLngBounds) + } + + @Test + fun intersectDoesNotWestWrapCheck() { + val latLngBounds1 = from(0.0, 0.0, -10.0, -210.0) + val latLngBounds2 = from(0.0, 0.0, -90.0, -200.0) + val intersectLatLngBounds = from(0.0, 0.0, -10.0, -200.0) + org.junit.Assert.assertEquals(latLngBounds1.intersect(latLngBounds2), intersectLatLngBounds) + org.junit.Assert.assertEquals(latLngBounds2.intersect(latLngBounds1), intersectLatLngBounds) + } + + @Test + fun innerUnion() { + val latLngBounds = LatLngBounds.Builder() + .include(LatLng(1.0, 1.0)) + .include(LAT_LNG_NULL_ISLAND) + .build() + org.junit.Assert.assertEquals( + "union should match", + latLngBounds, + latLngBounds.intersect( + this.latLngBounds!! + ) + ) + } + + @Test + fun outerUnion() { + val latLngBounds = LatLngBounds.Builder() + .include(LatLng(10.0, 10.0)) + .include(LatLng(9.0, 8.0)) + .build() + org.junit.Assert.assertEquals( + "outer union should match", + latLngBounds.union(this.latLngBounds!!), + LatLngBounds.Builder() + .include(LatLng(10.0, 10.0)) + .include(LAT_LNG_NULL_ISLAND) + .build() + ) + } + + @Test + fun unionOverDateLine() { + val latLngBounds1 = LatLngBounds.Builder() + .include(LatLng(10.0, 170.0)) + .include(LatLng(0.0, 160.0)) + .build() + val latLngBounds2 = LatLngBounds.Builder() + .include(LatLng(0.0, 190.0)) + .include(LatLng(-10.0, 200.0)) + .build() + val union1 = latLngBounds1.union(latLngBounds2) + val union2 = latLngBounds2.union(latLngBounds1) + org.junit.Assert.assertEquals( + union1, + LatLngBounds.Builder() + .include(LatLng(10.0, 160.0)) + .include(LatLng(-10.0, 200.0)) + .build() + ) + org.junit.Assert.assertEquals(union1, union2) + } + + @Test + fun unionOverDateLine2() { + val latLngBounds1 = LatLngBounds.Builder() + .include(LatLng(10.0, 170.0)) + .include(LatLng(0.0, 160.0)) + .build() + val latLngBounds2 = LatLngBounds.Builder() + .include(LatLng(0.0, 165.0)) + .include(LatLng(-10.0, 200.0)) + .build() + val union1 = latLngBounds1.union(latLngBounds2) + val union2 = latLngBounds2.union(latLngBounds1) + org.junit.Assert.assertEquals( + union1, + LatLngBounds.Builder() + .include(LatLng(10.0, 160.0)) + .include(LatLng(-10.0, 200.0)) + .build() + ) + org.junit.Assert.assertEquals(union1, union2) + } + + @Test + fun unionOverDateLine3() { + val latLngBounds1 = LatLngBounds.Builder() + .include(LatLng(10.0, 195.0)) + .include(LatLng(0.0, 160.0)) + .build() + val latLngBounds2 = LatLngBounds.Builder() + .include(LatLng(0.0, 190.0)) + .include(LatLng(-10.0, 200.0)) + .build() + val union1 = latLngBounds1.union(latLngBounds2) + val union2 = latLngBounds2.union(latLngBounds1) + org.junit.Assert.assertEquals( + union1, + LatLngBounds.Builder() + .include(LatLng(10.0, 160.0)) + .include(LatLng(-10.0, 200.0)) + .build() + ) + org.junit.Assert.assertEquals(union1, union2) + } + + @Test + fun unionOverDateLine4() { + val latLngBounds1 = LatLngBounds.Builder() + .include(LatLng(10.0, -160.0)) + .include(LatLng(0.0, -200.0)) + .build() + val latLngBounds2 = LatLngBounds.Builder() + .include(LatLng(0.0, -170.0)) + .include(LatLng(-10.0, -175.0)) + .build() + val union1 = latLngBounds1.union(latLngBounds2) + val union2 = latLngBounds2.union(latLngBounds1) + org.junit.Assert.assertEquals( + union1, + LatLngBounds.Builder() + .include(LatLng(10.0, -200.0)) + .include(LatLng(-10.0, -160.0)) + .build() + ) + org.junit.Assert.assertEquals(union1, union2) + } + + @Test + fun unionOverDateLine5() { + val latLngBounds1 = LatLngBounds.Builder() + .include(LatLng(10.0, 200.0)) + .include(LatLng(0.0, 160.0)) + .build() + val latLngBounds2 = LatLngBounds.Builder() + .include(LatLng(0.0, 170.0)) + .include(LatLng(-10.0, 175.0)) + .build() + val union1 = latLngBounds1.union(latLngBounds2) + val union2 = latLngBounds2.union(latLngBounds1) + org.junit.Assert.assertEquals( + union1, + LatLngBounds.Builder() + .include(LatLng(10.0, 160.0)) + .include(LatLng(-10.0, 200.0)) + .build() + ) + org.junit.Assert.assertEquals(union1, union2) + } + + @Test + fun unionOverDateLineReturnLongerThanWorldLonSpan() { + val latLngBounds1 = from(10.0, 200.0, -10.0, -10.0) + val latLngBounds2 = from(10.0, 10.0, -10.0, -200.0) + val union1 = latLngBounds1.union(latLngBounds2) + val union2 = latLngBounds2.union(latLngBounds1) + org.junit.Assert.assertEquals(union1, union2) + org.junit.Assert.assertEquals(union1, from(10.0, 200.0, -10.0, -200.0)) + } + + @Test + fun unionNorthCheck() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("latitude must be between -90 and 90") + val unionLatLngBounds = from(10.0, 10.0, 0.0, 0.0) + .union(200.0, 200.0, 0.0, 0.0) + } + + @Test + fun unionSouthCheck() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("latitude must be between -90 and 90") + val unionLatLngBounds = from(0.0, 0.0, -10.0, -10.0) + .union(0.0, 0.0, -200.0, -200.0) + } + + @Test + fun unionSouthLessThanNorthCheck() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("latNorth cannot be less than latSouth") + val unionLatLngBounds = from(10.0, 10.0, 0.0, 0.0) + .union(0.0, 200.0, 20.0, 0.0) + } + + @Test + fun unionEastDoesNotWrapCheck() { + val latLngBounds1 = from(10.0, 10.0, 0.0, 0.0) + val latLngBounds2 = from(90.0, 200.0, 0.0, 0.0) + val unionLatLngBounds = from(90.0, 200.0, 0.0, 0.0) + org.junit.Assert.assertEquals(latLngBounds1.union(latLngBounds2), unionLatLngBounds) + org.junit.Assert.assertEquals(latLngBounds2.union(latLngBounds1), unionLatLngBounds) + } + + @Test + fun unionWestDoesNotWrapCheck() { + val latLngBounds1 = from(0.0, 0.0, -10.0, -10.0) + val latLngBounds2 = from(0.0, 0.0, -90.0, -200.0) + val unionLatLngBounds = from(0.0, 0.0, -90.0, -200.0) + org.junit.Assert.assertEquals(latLngBounds1.union(latLngBounds2), unionLatLngBounds) + org.junit.Assert.assertEquals(latLngBounds2.union(latLngBounds1), unionLatLngBounds) + } + + @Test + fun northWest() { + val minLat = 5.0 + val minLon = 6.0 + val maxLat = 20.0 + val maxLon = 21.0 + val latLngBounds = LatLngBounds.Builder() + .include(LatLng(minLat, minLon)) + .include(LatLng(maxLat, maxLon)) + .build() + org.junit.Assert.assertEquals( + "NorthWest should match", + latLngBounds.northWest, + LatLng(maxLat, minLon) + ) + } + + @Test + fun southWest() { + val minLat = 5.0 + val minLon = 6.0 + val maxLat = 20.0 + val maxLon = 21.0 + val latLngBounds = LatLngBounds.Builder() + .include(LatLng(minLat, minLon)) + .include(LatLng(maxLat, maxLon)) + .build() + org.junit.Assert.assertEquals( + "SouthWest should match", + latLngBounds.southWest, + LatLng(minLat, minLon) + ) + } + + @Test + fun northEast() { + val minLat = 5.0 + val minLon = 6.0 + val maxLat = 20.0 + val maxLon = 21.0 + val latLngBounds = LatLngBounds.Builder() + .include(LatLng(minLat, minLon)) + .include(LatLng(maxLat, maxLon)) + .build() + org.junit.Assert.assertEquals( + "NorthEast should match", + latLngBounds.northEast, + LatLng(maxLat, maxLon) + ) + } + + @Test + fun southEast() { + val minLat = 5.0 + val minLon = 6.0 + val maxLat = 20.0 + val maxLon = 21.0 + val latLngBounds = LatLngBounds.Builder() + .include(LatLng(minLat, minLon)) + .include(LatLng(maxLat, maxLon)) + .build() + org.junit.Assert.assertEquals( + "SouthEast should match", + latLngBounds.southEast, + LatLng(minLat, maxLon) + ) + } + + @Test + fun testParcelable() { + val latLngBounds = LatLngBounds.Builder() + .include(LatLng(10.0, 10.0)) + .include(LatLng(9.0, 8.0)) + .build() + val parcel = MockParcel.obtain(latLngBounds) + org.junit.Assert.assertEquals("Parcel should match original object", parcel, latLngBounds) + } + + @Test + fun fromTileID() { + var bounds = from(0, 0, 0) + org.junit.Assert.assertEquals( + GeometryConstants.MIN_WRAP_LONGITUDE, + bounds.getLonWest(), + DELTA + ) + org.junit.Assert.assertEquals( + GeometryConstants.MIN_MERCATOR_LATITUDE, + bounds.getLatSouth(), + DELTA + ) + org.junit.Assert.assertEquals( + GeometryConstants.MAX_WRAP_LONGITUDE, + bounds.getLonEast(), + DELTA + ) + org.junit.Assert.assertEquals( + GeometryConstants.MAX_MERCATOR_LATITUDE, + bounds.getLatNorth(), + DELTA + ) + bounds = from(10, 288, 385) + org.junit.Assert.assertEquals(-78.75, bounds.getLonWest(), DELTA) + org.junit.Assert.assertEquals(40.446947059600497, bounds.getLatSouth(), DELTA) + org.junit.Assert.assertEquals(-78.3984375, bounds.getLonEast(), DELTA) + org.junit.Assert.assertEquals(40.713955826286039, bounds.getLatNorth(), DELTA) + } + + @Rule @JvmField + val exception = ExpectedException.none() + + @Test + fun testConstructorChecksNorthLatitudeNaN() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("latitude must not be NaN") + from(Double.NaN, 0.0, -20.0, -20.0) + } + + @Test + fun testConstructorChecksEastLongitudeNaN() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("longitude must not be NaN") + from(0.0, Double.NaN, -20.0, -20.0) + } + + @Test + fun testConstructorChecksNorthLatitudeGreaterThan90() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("latitude must be between -90 and 90") + from(95.0, 0.0, -20.0, -20.0) + } + + @Test + fun testConstructorChecksNorthLatitudeLessThanThanNegative90() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("latitude must be between -90 and 90") + from(-95.0, 0.0, -20.0, -20.0) + } + + @Test + fun testConstructorChecksEastLongitudeInfinity() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("longitude must not be infinite") + from(0.0, Double.POSITIVE_INFINITY, -20.0, -20.0) + } + + @Test + fun testConstructorChecksSouthLatitudeNaN() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("latitude must not be NaN") + from(20.0, 20.0, Double.NaN, 0.0) + } + + @Test + fun testConstructorChecksWesttLongitudeNaN() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("longitude must not be NaN") + from(20.0, 20.0, 0.0, Double.NaN) + } + + @Test + fun testConstructorChecksSouthLatitudeGreaterThan90() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("latitude must be between -90 and 90") + from(20.0, 20.0, 95.0, 0.0) + } + + @Test + fun testConstructorChecksSouthLatitudeLessThanThanNegative90() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("latitude must be between -90 and 90") + from(20.0, 20.0, -95.0, 0.0) + } + + @Test + fun testConstructorChecksWestLongitudeInfinity() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("longitude must not be infinite") + from(20.0, 20.0, 0.0, Double.POSITIVE_INFINITY) + } + + @Test + fun testConstructorCheckLatSouthGreaterLatNorth() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("latNorth cannot be less than latSouth") + from(0.0, 20.0, 20.0, 0.0) + } + + @Test + fun testConstructorCheckLonWestGreaterLonEast() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("lonEast cannot be less than lonWest") + from(20.0, 0.0, 0.0, 20.0) + } + + companion object { + private const val DELTA = 1e-13 + private val LAT_LNG_NULL_ISLAND = LatLng(0.0, 0.0) + private val LAT_LNG_NOT_NULL_ISLAND = LatLng(2.0, 2.0) + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngSpanTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngSpanTest.java deleted file mode 100644 index 12297247c..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngSpanTest.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.mapbox.mapboxsdk.geometry; - -import android.os.Parcelable; - -import com.mapbox.mapboxsdk.utils.MockParcel; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -public class LatLngSpanTest { - - private static final double DELTA = 1e-15; - private static final LatLng LAT_LNG_NULL_ISLAND = new LatLng(0, 0); - - @Test - public void testSanity() { - LatLngSpan latLngSpan = new LatLngSpan(0.0, 0.0); - assertNotNull("latLngSpan should not be null", latLngSpan); - } - - @Test - public void testEquality() { - LatLngSpan latLngSpan = new LatLngSpan(0.0, 0.0); - assertEquals("latLngSpan is not equal to a LatLng", latLngSpan.equals(LAT_LNG_NULL_ISLAND), false); - } - - @Test - public void testLatitudeConstructor() { - double latitude = 1.23; - LatLngSpan latLngSpan = new LatLngSpan(latitude, 0.0); - assertEquals("latitude in constructor", latLngSpan.getLatitudeSpan(), latitude, DELTA); - } - - @Test - public void testLongitudeConstructor() { - double longitude = 1.23; - LatLngSpan latLngSpan = new LatLngSpan(0.0, longitude); - assertEquals("latitude in constructor", latLngSpan.getLongitudeSpan(), longitude, DELTA); - } - - @Test - public void testLatitudeMethod() { - double latitude = 1.23; - LatLngSpan latLngSpan = new LatLngSpan(0.0, 0.0); - latLngSpan.setLatitudeSpan(latitude); - assertEquals("latitude in constructor", latLngSpan.getLatitudeSpan(), latitude, DELTA); - } - - @Test - public void testLongitudeMethod() { - double longitude = 1.23; - LatLngSpan latLngSpan = new LatLngSpan(0.0, 0.0); - latLngSpan.setLongitudeSpan(longitude); - assertEquals("latitude in constructor", latLngSpan.getLongitudeSpan(), longitude, DELTA); - } - - @Test - public void testParcelable() { - LatLngSpan object = new LatLngSpan(1, 2); - Parcelable parcel = MockParcel.obtain(object); - assertEquals("parcel should match initial object", object, parcel); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngSpanTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngSpanTest.kt new file mode 100644 index 000000000..5c6a8fcb3 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngSpanTest.kt @@ -0,0 +1,67 @@ +package com.mapbox.mapboxsdk.geometry + +import com.mapbox.mapboxsdk.utils.MockParcel +import org.junit.Assert +import org.junit.Test + +class LatLngSpanTest { + @Test + fun testSanity() { + val latLngSpan = LatLngSpan(0.0, 0.0) + Assert.assertNotNull("latLngSpan should not be null", latLngSpan) + } + + @Test + fun testEquality() { + val latLngSpan = LatLngSpan(0.0, 0.0) + Assert.assertEquals( + "latLngSpan is not equal to a LatLng", + latLngSpan.equals( + LAT_LNG_NULL_ISLAND + ), + false + ) + } + + @Test + fun testLatitudeConstructor() { + val latitude = 1.23 + val latLngSpan = LatLngSpan(latitude, 0.0) + Assert.assertEquals("latitude in constructor", latLngSpan.latitudeSpan, latitude, DELTA) + } + + @Test + fun testLongitudeConstructor() { + val longitude = 1.23 + val latLngSpan = LatLngSpan(0.0, longitude) + Assert.assertEquals("latitude in constructor", latLngSpan.longitudeSpan, longitude, DELTA) + } + + @Test + fun testLatitudeMethod() { + val latitude = 1.23 + val latLngSpan = LatLngSpan(0.0, 0.0) + latLngSpan.latitudeSpan = latitude + Assert.assertEquals("latitude in constructor", latLngSpan.latitudeSpan, latitude, DELTA) + } + + @Test + fun testLongitudeMethod() { + val longitude = 1.23 + val latLngSpan = LatLngSpan(0.0, 0.0) + latLngSpan.longitudeSpan = longitude + Assert.assertEquals("latitude in constructor", latLngSpan.longitudeSpan, longitude, DELTA) + } + + @Test + fun testParcelable() { + val `object` = LatLngSpan(1.0, 2.0) + val parcel = MockParcel.obtain(`object`) + Assert.assertEquals("parcel should match initial object", `object`, parcel) + } + + companion object { + private const val DELTA = 1e-15 + private val LAT_LNG_NULL_ISLAND = LatLng(0.0, 0.0) + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngTest.java deleted file mode 100644 index be2af584f..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngTest.java +++ /dev/null @@ -1,286 +0,0 @@ -package com.mapbox.mapboxsdk.geometry; - -import android.location.Location; -import android.os.Parcelable; - -import com.mapbox.mapboxsdk.utils.MockParcel; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class LatLngTest { - - private static final double DELTA = 1e-15; - - @Test - public void testSanity() { - LatLng latLng = new LatLng(0.0, 0.0); - assertNotNull("latLng should not be null", latLng); - } - - @Test - public void testLatitudeEmptyConstructor() { - LatLng latLng = new LatLng(); - assertEquals("latitude default value", latLng.getLatitude(), 0, DELTA); - } - - @Test - public void testLongitudeEmptyConstructor() { - LatLng latLng = new LatLng(); - assertEquals("longitude default value", latLng.getLongitude(), 0, DELTA); - } - - @Test - public void testAltitudeEmptyConstructor() { - LatLng latLng1 = new LatLng(); - assertEquals("altitude default value", latLng1.getAltitude(), 0.0, DELTA); - } - - @Test - public void testLatitudeConstructor() { - double latitude = 1.2; - LatLng latLng = new LatLng(latitude, 3.4); - assertEquals("latitude should match", latLng.getLatitude(), latitude, DELTA); - } - - @Test - public void testLongitudeConstructor() { - double longitude = 3.4; - LatLng latLng = new LatLng(1.2, longitude); - assertEquals("longitude should match", latLng.getLongitude(), longitude, DELTA); - } - - @Test - public void testAltitudeConstructor() { - LatLng latLng1 = new LatLng(1.2, 3.4); - assertEquals("altitude default value", latLng1.getAltitude(), 0.0, DELTA); - - double altitude = 5.6; - LatLng latLng2 = new LatLng(1.2, 3.4, altitude); - assertEquals("altitude default value", latLng2.getAltitude(), altitude, DELTA); - } - - @Test - public void testLatitudeSetter() { - LatLng latLng = new LatLng(1.2, 3.4); - latLng.setLatitude(3); - assertEquals("latitude should match", 3, latLng.getLatitude(), DELTA); - } - - @Test - public void testLongitudeSetter() { - LatLng latLng = new LatLng(1.2, 3.4); - latLng.setLongitude(3); - assertEquals("longitude should match", 3, latLng.getLongitude(), DELTA); - } - - @Rule - public final ExpectedException exception = ExpectedException.none(); - - @Test - public void testConstructorChecksLatitudeNaN() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must not be NaN"); - new LatLng(Double.NaN, 0); - } - - @Test - public void testConstructorChecksLongitudeNaN() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("longitude must not be NaN"); - new LatLng(0, Double.NaN); - } - - @Test - public void testConstructorChecksLatitudeGreaterThan90() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must be between -90 and 90"); - new LatLng(95, 0); - } - - @Test - public void testConstructorChecksLatitudeLessThanThanNegative90() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must be between -90 and 90"); - new LatLng(-95, 0); - } - - @Test - public void testConstructorChecksLongitudeInfinity() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("longitude must not be infinite"); - new LatLng(0, Double.POSITIVE_INFINITY); - } - - @Test - public void testLatitudeSetterChecksNaN() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must not be NaN"); - new LatLng().setLatitude(Double.NaN); - } - - @Test - public void testLongitudeSetterChecksNaN() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("longitude must not be NaN"); - new LatLng().setLongitude(Double.NaN); - } - - @Test - public void testLatitudeSetterChecksGreaterThan90() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must be between -90 and 90"); - new LatLng().setLatitude(95); - } - - @Test - public void testLatitudeSetterChecksLessThanThanNegative90() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must be between -90 and 90"); - new LatLng().setLatitude(-95); - } - - @Test - public void testLongitudeSetterChecksInfinity() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("longitude must not be infinite"); - new LatLng().setLongitude(Double.NEGATIVE_INFINITY); - } - - @Test - public void testAltitudeSetter() { - LatLng latLng = new LatLng(1.2, 3.4); - latLng.setAltitude(3); - assertEquals("altitude should match", 3, latLng.getAltitude(), DELTA); - } - - @Test - public void testLatLngConstructor() { - LatLng latLng1 = new LatLng(1.2, 3.4); - LatLng latLng2 = new LatLng(latLng1); - assertEquals("latLng should match", latLng1, latLng2); - } - - @Test - public void testDistanceTo() { - LatLng latLng1 = new LatLng(0.0, 0.0); - LatLng latLng2 = new LatLng(1.0, 1.0); - assertEquals("distances should match", - latLng1.distanceTo(latLng2), - 157298.7453847275, DELTA); - } - - @Test - public void testDistanceToSamePoint() { - LatLng latLng1 = new LatLng(40.71199035644531, -74.0081); - LatLng latLng2 = new LatLng(40.71199035644531, -74.0081); - double distance = latLng1.distanceTo(latLng2); - assertEquals("distance should match", 0.0, distance, DELTA); - } - - // Regression test for #14216 - @Test - public void testDistanceToClosePointNotNaN() { - LatLng latLng = new LatLng(40.00599, -105.29261); - LatLng other = new LatLng(40.005990000000025, -105.29260999999997); - double distance = latLng.distanceTo(other); - assertNotEquals(distance, Double.NaN); - } - - @Test - public void testLocationProvider() { - double latitude = 1.2; - double longitude = 3.4; - double altitude = 5.6; - - // Mock the location class - Location locationMocked = mock(Location.class); - when(locationMocked.getLatitude()).thenReturn(latitude); - when(locationMocked.getLongitude()).thenReturn(longitude); - when(locationMocked.getAltitude()).thenReturn(altitude); - - // Test the constructor - LatLng latLng = new LatLng(locationMocked); - assertEquals("latitude should match", latLng.getLatitude(), latitude, DELTA); - assertEquals("longitude should match", latLng.getLongitude(), longitude, DELTA); - assertEquals("altitude should match", latLng.getAltitude(), altitude, DELTA); - } - - @Test - public void testHashCode() { - double latitude = 1.2; - double longitude = 3.4; - double altitude = 5.6; - LatLng latLng = new LatLng(latitude, longitude, altitude); - assertEquals("hash code should match", latLng.hashCode(), -151519232); - } - - @Test - public void testToString() { - double latitude = 1.2; - double longitude = 3.4; - double altitude = 5.6; - LatLng latLng = new LatLng(latitude, longitude, altitude); - assertEquals("string should match", - latLng.toString(), - "LatLng [latitude=1.2, longitude=3.4, altitude=5.6]"); - } - - @Test - public void testEqualsOther() { - double latitude = 1.2; - double longitude = 3.4; - double altitude = 5.6; - LatLng latLng1 = new LatLng(latitude, longitude, altitude); - LatLng latLng2 = new LatLng(latitude, longitude, altitude); - assertEquals("LatLng should match", latLng1, latLng2); - } - - @Test - public void testEqualsItself() { - LatLng latLng = new LatLng(1, 2, 3); - assertEquals("LatLng should match", latLng, latLng); - } - - @Test - public void testNotEquals() { - LatLng latLng = new LatLng(1, 2); - assertNotEquals("LatLng should match", latLng, new Object()); - } - - @Test - public void testParcelable() { - LatLng latLng = new LatLng(45.0, -185.0); - Parcelable parcel = MockParcel.obtain(latLng); - assertEquals("parcel should match initial object", latLng, parcel); - } - - @Test - public void testWrapped() { - LatLng originalLatLng = new LatLng(45.0, -185.0); - LatLng newLatlng = originalLatLng.wrap(); - assertNotSame(" new wrapped LatLng is created", originalLatLng, newLatlng); - assertEquals("longitude wrapped value", originalLatLng.getLongitude(), -185.0, DELTA); - assertEquals("longitude wrapped value", newLatlng.getLongitude(), 175.0, DELTA); - - newLatlng = new LatLng(45.0, 180.0).wrap(); - assertEquals("longitude wrapped max value", newLatlng.getLongitude(), 180.0, DELTA); - - newLatlng = new LatLng(45.0, -180.0).wrap(); - assertEquals("longitude wrapped min value", newLatlng.getLongitude(), -180.0, DELTA); - } - - @Test - public void testUnnecessaryWrapped() { - LatLng latLng = new LatLng(45.0, 50.0).wrap(); - assertEquals("longitude wrapped value", latLng.getLongitude(), 50.0, DELTA); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngTest.kt new file mode 100644 index 000000000..9c798e8f7 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngTest.kt @@ -0,0 +1,283 @@ +package com.mapbox.mapboxsdk.geometry + +import android.location.Location +import com.mapbox.mapboxsdk.utils.MockParcel +import org.junit.Assert +import org.junit.Rule +import org.junit.Test +import org.junit.rules.ExpectedException +import org.mockito.Mockito + +class LatLngTest { + @Test + fun testSanity() { + val latLng = LatLng(0.0, 0.0) + Assert.assertNotNull("latLng should not be null", latLng) + } + + @Test + fun testLatitudeEmptyConstructor() { + val latLng = LatLng() + Assert.assertEquals("latitude default value", latLng.latitude, 0.0, DELTA) + } + + @Test + fun testLongitudeEmptyConstructor() { + val latLng = LatLng() + Assert.assertEquals("longitude default value", latLng.longitude, 0.0, DELTA) + } + + @Test + fun testAltitudeEmptyConstructor() { + val latLng1 = LatLng() + Assert.assertEquals("altitude default value", latLng1.altitude, 0.0, DELTA) + } + + @Test + fun testLatitudeConstructor() { + val latitude = 1.2 + val latLng = LatLng(latitude, 3.4) + Assert.assertEquals("latitude should match", latLng.latitude, latitude, DELTA) + } + + @Test + fun testLongitudeConstructor() { + val longitude = 3.4 + val latLng = LatLng(1.2, longitude) + Assert.assertEquals("longitude should match", latLng.longitude, longitude, DELTA) + } + + @Test + fun testAltitudeConstructor() { + val latLng1 = LatLng(1.2, 3.4) + Assert.assertEquals("altitude default value", latLng1.altitude, 0.0, DELTA) + val altitude = 5.6 + val latLng2 = LatLng(1.2, 3.4, altitude) + Assert.assertEquals("altitude default value", latLng2.altitude, altitude, DELTA) + } + + @Test + fun testLatitudeSetter() { + val latLng = LatLng(1.2, 3.4) + latLng.setLatitude(3.0) + Assert.assertEquals("latitude should match", 3.0, latLng.latitude, DELTA) + } + + @Test + fun testLongitudeSetter() { + val latLng = LatLng(1.2, 3.4) + latLng.setLongitude(3.0) + Assert.assertEquals("longitude should match", 3.0, latLng.longitude, DELTA) + } + + @Rule @JvmField + val exception = ExpectedException.none() + + @Test + fun testConstructorChecksLatitudeNaN() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("latitude must not be NaN") + LatLng(Double.NaN, 0.0) + } + + @Test + fun testConstructorChecksLongitudeNaN() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("longitude must not be NaN") + LatLng(0.0, Double.NaN) + } + + @Test + fun testConstructorChecksLatitudeGreaterThan90() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("latitude must be between -90 and 90") + LatLng(95.0, 0.0) + } + + @Test + fun testConstructorChecksLatitudeLessThanThanNegative90() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("latitude must be between -90 and 90") + LatLng(-95.0, 0.0) + } + + @Test + fun testConstructorChecksLongitudeInfinity() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("longitude must not be infinite") + LatLng(0.0, Double.POSITIVE_INFINITY) + } + + @Test + fun testLatitudeSetterChecksNaN() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("latitude must not be NaN") + LatLng().setLatitude(Double.NaN) + } + + @Test + fun testLongitudeSetterChecksNaN() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("longitude must not be NaN") + LatLng().setLongitude(Double.NaN) + } + + @Test + fun testLatitudeSetterChecksGreaterThan90() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("latitude must be between -90 and 90") + LatLng().setLatitude(95.0) + } + + @Test + fun testLatitudeSetterChecksLessThanThanNegative90() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("latitude must be between -90 and 90") + LatLng().setLatitude(-95.0) + } + + @Test + fun testLongitudeSetterChecksInfinity() { + exception.expect(IllegalArgumentException::class.java) + exception.expectMessage("longitude must not be infinite") + LatLng().setLongitude(Double.NEGATIVE_INFINITY) + } + + @Test + fun testAltitudeSetter() { + val latLng = LatLng(1.2, 3.4) + latLng.altitude = 3.0 + Assert.assertEquals("altitude should match", 3.0, latLng.altitude, DELTA) + } + + @Test + fun testLatLngConstructor() { + val latLng1 = LatLng(1.2, 3.4) + val latLng2 = LatLng(latLng1) + Assert.assertEquals("latLng should match", latLng1, latLng2) + } + + @Test + fun testDistanceTo() { + val latLng1 = LatLng(0.0, 0.0) + val latLng2 = LatLng(1.0, 1.0) + Assert.assertEquals( + "distances should match", + latLng1.distanceTo(latLng2), + 157298.7453847275, + DELTA + ) + } + + @Test + fun testDistanceToSamePoint() { + val latLng1 = LatLng(40.71199035644531, -74.0081) + val latLng2 = LatLng(40.71199035644531, -74.0081) + val distance = latLng1.distanceTo(latLng2) + Assert.assertEquals("distance should match", 0.0, distance, DELTA) + } + + // Regression test for #14216 + @Test + fun testDistanceToClosePointNotNaN() { + val latLng = LatLng(40.00599, -105.29261) + val other = LatLng(40.005990000000025, -105.29260999999997) + val distance = latLng.distanceTo(other) + Assert.assertNotEquals(distance, Double.NaN) + } + + @Test + fun testLocationProvider() { + val latitude = 1.2 + val longitude = 3.4 + val altitude = 5.6 + + // Mock the location class + val locationMocked = Mockito.mock( + Location::class.java + ) + Mockito.`when`(locationMocked.latitude).thenReturn(latitude) + Mockito.`when`(locationMocked.longitude).thenReturn(longitude) + Mockito.`when`(locationMocked.altitude).thenReturn(altitude) + + // Test the constructor + val latLng = LatLng(locationMocked) + Assert.assertEquals("latitude should match", latLng.latitude, latitude, DELTA) + Assert.assertEquals("longitude should match", latLng.longitude, longitude, DELTA) + Assert.assertEquals("altitude should match", latLng.altitude, altitude, DELTA) + } + + @Test + fun testHashCode() { + val latitude = 1.2 + val longitude = 3.4 + val altitude = 5.6 + val latLng = LatLng(latitude, longitude, altitude) + Assert.assertEquals("hash code should match", latLng.hashCode().toLong(), -151519232) + } + + @Test + fun testToString() { + val latitude = 1.2 + val longitude = 3.4 + val altitude = 5.6 + val latLng = LatLng(latitude, longitude, altitude) + Assert.assertEquals( + "string should match", + latLng.toString(), + "LatLng [latitude=1.2, longitude=3.4, altitude=5.6]" + ) + } + + @Test + fun testEqualsOther() { + val latitude = 1.2 + val longitude = 3.4 + val altitude = 5.6 + val latLng1 = LatLng(latitude, longitude, altitude) + val latLng2 = LatLng(latitude, longitude, altitude) + Assert.assertEquals("LatLng should match", latLng1, latLng2) + } + + @Test + fun testEqualsItself() { + val latLng = LatLng(1.0, 2.0, 3.0) + Assert.assertEquals("LatLng should match", latLng, latLng) + } + + @Test + fun testNotEquals() { + val latLng = LatLng(1.0, 2.0) + Assert.assertNotEquals("LatLng should match", latLng, Any()) + } + + @Test + fun testParcelable() { + val latLng = LatLng(45.0, -185.0) + val parcel = MockParcel.obtain(latLng) + Assert.assertEquals("parcel should match initial object", latLng, parcel) + } + + @Test + fun testWrapped() { + val originalLatLng = LatLng(45.0, -185.0) + var newLatlng = originalLatLng.wrap() + Assert.assertNotSame(" new wrapped LatLng is created", originalLatLng, newLatlng) + Assert.assertEquals("longitude wrapped value", originalLatLng.longitude, -185.0, DELTA) + Assert.assertEquals("longitude wrapped value", newLatlng.longitude, 175.0, DELTA) + newLatlng = LatLng(45.0, 180.0).wrap() + Assert.assertEquals("longitude wrapped max value", newLatlng.longitude, 180.0, DELTA) + newLatlng = LatLng(45.0, -180.0).wrap() + Assert.assertEquals("longitude wrapped min value", newLatlng.longitude, -180.0, DELTA) + } + + @Test + fun testUnnecessaryWrapped() { + val latLng = LatLng(45.0, 50.0).wrap() + Assert.assertEquals("longitude wrapped value", latLng.longitude, 50.0, DELTA) + } + + companion object { + private const val DELTA = 1e-15 + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/ProjectedMetersTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/ProjectedMetersTest.java deleted file mode 100644 index 00fd125a1..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/ProjectedMetersTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.mapbox.mapboxsdk.geometry; - -import android.os.Parcelable; - -import com.mapbox.mapboxsdk.utils.MockParcel; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -public class ProjectedMetersTest { - - private static final LatLng LAT_LNG_NULL_ISLAND = new LatLng(0, 0); - - @Test - public void testSanity() { - ProjectedMeters projectedMeters = new ProjectedMeters(0.0, 0.0); - assertNotNull("projectedMeters should not be null", projectedMeters); - } - - @Test - public void testEquality() { - ProjectedMeters projectedMeters = new ProjectedMeters(0.0, 0.0); - assertEquals("projectedMeters is not equal to a LatLng", projectedMeters.equals(LAT_LNG_NULL_ISLAND), false); - assertEquals("projectedMeters is equal to itself", projectedMeters.equals(projectedMeters), true); - } - - @Test - public void testNorthing() { - ProjectedMeters projectedMeters = new ProjectedMeters(1.0, 0.0); - assertEquals("northing should be 1", 1, projectedMeters.getNorthing(), 0); - } - - @Test - public void testEasting() { - ProjectedMeters projectedMeters = new ProjectedMeters(0.0, 1.0); - assertEquals("easting should be 1", 1, projectedMeters.getEasting(), 0); - } - - @Test - public void testConstructor() { - ProjectedMeters projectedMeters1 = new ProjectedMeters(1, 2); - ProjectedMeters projectedMeters2 = new ProjectedMeters(projectedMeters1); - assertEquals("projectedmeters should match", projectedMeters1, projectedMeters2); - } - - @Test - public void testHashcode() { - ProjectedMeters meters = new ProjectedMeters(1, 2); - assertEquals("hashcode should match", -1048576, meters.hashCode()); - } - - @Test - public void testToString() { - ProjectedMeters meters = new ProjectedMeters(1, 1); - assertEquals("toString should match", "ProjectedMeters [northing=1.0, easting=1.0]", meters.toString()); - } - - @Test - public void testParcelable() { - ProjectedMeters meters = new ProjectedMeters(1, 1); - Parcelable parcel = MockParcel.obtain(meters); - assertEquals("parcel should match initial object", meters, parcel); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/ProjectedMetersTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/ProjectedMetersTest.kt new file mode 100644 index 000000000..d23349a9f --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/ProjectedMetersTest.kt @@ -0,0 +1,76 @@ +package com.mapbox.mapboxsdk.geometry + +import com.mapbox.mapboxsdk.utils.MockParcel +import org.junit.Assert +import org.junit.Test + +class ProjectedMetersTest { + @Test + fun testSanity() { + val projectedMeters = ProjectedMeters(0.0, 0.0) + Assert.assertNotNull("projectedMeters should not be null", projectedMeters) + } + + @Test + fun testEquality() { + val projectedMeters = ProjectedMeters(0.0, 0.0) + Assert.assertEquals( + "projectedMeters is not equal to a LatLng", + projectedMeters.equals( + LAT_LNG_NULL_ISLAND + ), + false + ) + Assert.assertEquals( + "projectedMeters is equal to itself", + projectedMeters.equals(projectedMeters), + true + ) + } + + @Test + fun testNorthing() { + val projectedMeters = ProjectedMeters(1.0, 0.0) + Assert.assertEquals("northing should be 1", 1.0, projectedMeters.northing, 0.0) + } + + @Test + fun testEasting() { + val projectedMeters = ProjectedMeters(0.0, 1.0) + Assert.assertEquals("easting should be 1", 1.0, projectedMeters.easting, 0.0) + } + + @Test + fun testConstructor() { + val projectedMeters1 = ProjectedMeters(1.0, 2.0) + val projectedMeters2 = ProjectedMeters(projectedMeters1) + Assert.assertEquals("projectedmeters should match", projectedMeters1, projectedMeters2) + } + + @Test + fun testHashcode() { + val meters = ProjectedMeters(1.0, 2.0) + Assert.assertEquals("hashcode should match", -1048576, meters.hashCode().toLong()) + } + + @Test + fun testToString() { + val meters = ProjectedMeters(1.0, 1.0) + Assert.assertEquals( + "toString should match", + "ProjectedMeters [northing=1.0, easting=1.0]", + meters.toString() + ) + } + + @Test + fun testParcelable() { + val meters = ProjectedMeters(1.0, 1.0) + val parcel = MockParcel.obtain(meters) + Assert.assertEquals("parcel should match initial object", meters, parcel) + } + + companion object { + private val LAT_LNG_NULL_ISLAND = LatLng(0.0, 0.0) + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/VisibleRegionTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/VisibleRegionTest.java deleted file mode 100644 index 12b779de5..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/VisibleRegionTest.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.mapbox.mapboxsdk.geometry; - -import android.os.Parcelable; - -import com.mapbox.mapboxsdk.utils.MockParcel; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -public class VisibleRegionTest { - - private static final LatLng FAR_LEFT = new LatLng(52, -12); - private static final LatLng NEAR_LEFT = new LatLng(34, -12); - private static final LatLng FAR_RIGHT = new LatLng(52, 26); - private static final LatLng NEAR_RIGHT = new LatLng(34, 26); - private static final LatLngBounds BOUNDS = - new LatLngBounds.Builder().include(FAR_LEFT).include(FAR_RIGHT).include(NEAR_LEFT).include(NEAR_RIGHT).build(); - - @Test - public void testSanity() { - VisibleRegion region = new VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS); - assertNotNull("region should not be null", region); - } - - @Test - public void testEquality() { - VisibleRegion region = new VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS); - assertEquals("visibleRegion is not equal to a LatLng", region.equals(FAR_LEFT), false); - assertEquals("visibleRegion is equal to itself", region.equals(region), true); - } - - @Test - public void testFarLeftConstructor() { - VisibleRegion region = new VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS); - assertEquals("LatLng should match", region.farLeft, FAR_LEFT); - } - - @Test - public void testNearLeftConstructor() { - VisibleRegion region = new VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS); - assertEquals("LatLng should match", region.nearLeft, NEAR_LEFT); - } - - @Test - public void testFarRightConstructor() { - VisibleRegion region = new VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS); - assertEquals("LatLng should match", region.farRight, FAR_RIGHT); - } - - @Test - public void testNearRightConstructor() { - VisibleRegion region = new VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS); - assertEquals("LatLng should match", region.nearRight, NEAR_RIGHT); - } - - @Test - public void testLatLngBoundsConstructor() { - VisibleRegion region = new VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS); - assertEquals("LatLngBounds should match", region.latLngBounds, BOUNDS); - } - - @Test - public void testEquals() { - VisibleRegion regionLeft = new VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS); - VisibleRegion regionRight = new VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS); - assertEquals("VisibleRegions should match", regionLeft, regionRight); - } - - @Test - public void testHashcode() { - VisibleRegion region = new VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS); - assertEquals("hashcode should match", -923534102, region.hashCode()); - } - - @Test - public void testToString() { - VisibleRegion region = new VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS); - assertEquals("string should match", - "[farLeft [LatLng [latitude=52.0, longitude=-12.0, altitude=0.0]], " - + "farRight [LatLng [latitude=52.0, longitude=26.0, altitude=0.0]], " - + "nearLeft [LatLng [latitude=34.0, longitude=-12.0, altitude=0.0]], " - + "nearRight [LatLng [latitude=34.0, longitude=26.0, altitude=0.0]], " - + "latLngBounds [N:52.0; E:26.0; S:34.0; W:-12.0]]", - region.toString()); - } - - @Test - public void testParcelable() { - VisibleRegion region = new VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS); - Parcelable parcel = MockParcel.obtain(region); - assertEquals("parcel should match initial object", region, parcel); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/VisibleRegionTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/VisibleRegionTest.kt new file mode 100644 index 000000000..c9d8ae7f0 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/VisibleRegionTest.kt @@ -0,0 +1,98 @@ +package com.mapbox.mapboxsdk.geometry + +import com.mapbox.mapboxsdk.utils.MockParcel +import org.junit.Assert +import org.junit.Test + +class VisibleRegionTest { + @Test + fun testSanity() { + val region = VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS) + Assert.assertNotNull("region should not be null", region) + } + + @Test + fun testEquality() { + val region = VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS) + Assert.assertEquals( + "visibleRegion is not equal to a LatLng", + region.equals(FAR_LEFT), + false + ) + Assert.assertEquals("visibleRegion is equal to itself", region.equals(region), true) + } + + @Test + fun testFarLeftConstructor() { + val region = VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS) + Assert.assertEquals("LatLng should match", region.farLeft, FAR_LEFT) + } + + @Test + fun testNearLeftConstructor() { + val region = VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS) + Assert.assertEquals("LatLng should match", region.nearLeft, NEAR_LEFT) + } + + @Test + fun testFarRightConstructor() { + val region = VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS) + Assert.assertEquals("LatLng should match", region.farRight, FAR_RIGHT) + } + + @Test + fun testNearRightConstructor() { + val region = VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS) + Assert.assertEquals("LatLng should match", region.nearRight, NEAR_RIGHT) + } + + @Test + fun testLatLngBoundsConstructor() { + val region = VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS) + Assert.assertEquals("LatLngBounds should match", region.latLngBounds, BOUNDS) + } + + @Test + fun testEquals() { + val regionLeft = VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS) + val regionRight = VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS) + Assert.assertEquals("VisibleRegions should match", regionLeft, regionRight) + } + + @Test + fun testHashcode() { + val region = VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS) + Assert.assertEquals("hashcode should match", -923534102, region.hashCode().toLong()) + } + + @Test + fun testToString() { + val region = VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS) + Assert.assertEquals( + "string should match", + "[farLeft [LatLng [latitude=52.0, longitude=-12.0, altitude=0.0]], " + + "farRight [LatLng [latitude=52.0, longitude=26.0, altitude=0.0]], " + + "nearLeft [LatLng [latitude=34.0, longitude=-12.0, altitude=0.0]], " + + "nearRight [LatLng [latitude=34.0, longitude=26.0, altitude=0.0]], " + + "latLngBounds [N:52.0; E:26.0; S:34.0; W:-12.0]]", + region.toString() + ) + } + + @Test + fun testParcelable() { + val region = VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS) + val parcel = MockParcel.obtain(region) + Assert.assertEquals("parcel should match initial object", region, parcel) + } + + companion object { + private val FAR_LEFT = LatLng(52.0, -12.0) + private val NEAR_LEFT = LatLng(34.0, -12.0) + private val FAR_RIGHT = LatLng(52.0, 26.0) + private val NEAR_RIGHT = LatLng(34.0, 26.0) + private val BOUNDS = LatLngBounds.Builder().include(FAR_LEFT).include(FAR_RIGHT).include( + NEAR_LEFT + ).include(NEAR_RIGHT).build() + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/CompassEngineTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/CompassEngineTest.java deleted file mode 100644 index 0ff562a43..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/CompassEngineTest.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.hardware.Sensor; -import android.hardware.SensorEventListener; -import android.hardware.SensorManager; -import android.view.WindowManager; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import static com.mapbox.mapboxsdk.location.LocationComponentCompassEngine.SENSOR_DELAY_MICROS; -import static junit.framework.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -@RunWith(MockitoJUnitRunner.class) -public class CompassEngineTest { - - private LocationComponentCompassEngine compassEngine; - - @Mock - private WindowManager windowManager; - - @Mock - private SensorManager sensorManager; - - @Mock - private Sensor compassSensor; - - @Mock - private CompassListener compassListener; - - @Before - public void setUp() throws Exception { - when(sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR)).thenReturn(compassSensor); - compassEngine = new LocationComponentCompassEngine(windowManager, sensorManager); - } - - @Test - public void lastKnownCompassBearingAccuracyDefault() { - assertEquals("Last accuracy should match", compassEngine.getLastAccuracySensorStatus(), 0); - } - - @Test - public void lastKnownCompassAccuracyStatusValue() { - Sensor sensor = mock(Sensor.class); - compassEngine.onAccuracyChanged(sensor, 2); - assertEquals("Last accuracy should match", compassEngine.getLastAccuracySensorStatus(), 2); - } - - @Test - public void whenGyroscopeIsNull_fallbackToGravity() { - SensorManager sensorManager = mock(SensorManager.class); - new LocationComponentCompassEngine(windowManager, sensorManager); - - verify(sensorManager, times(1)).getDefaultSensor(Sensor.TYPE_ACCELEROMETER); - } - - @Test - public void whenGyroscopeIsNull_fallbackToMagneticField() { - SensorManager sensorManager = mock(SensorManager.class); - new LocationComponentCompassEngine(windowManager, sensorManager); - - verify(sensorManager, times(1)).getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); - } - - @Test - public void listener_registerOnAdd() { - compassEngine.addCompassListener(compassListener); - verify(sensorManager) - .registerListener(any(SensorEventListener.class), eq(compassSensor), eq(SENSOR_DELAY_MICROS)); - } - - @Test - public void listener_unregisterOnRemove() { - compassEngine.addCompassListener(compassListener); - compassEngine.removeCompassListener(compassListener); - verify(sensorManager).unregisterListener(any(SensorEventListener.class), eq(compassSensor)); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/CompassEngineTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/CompassEngineTest.kt new file mode 100644 index 000000000..52a3fed0f --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/CompassEngineTest.kt @@ -0,0 +1,98 @@ +package com.mapbox.mapboxsdk.location + +import android.hardware.Sensor +import android.hardware.SensorEventListener +import android.hardware.SensorManager +import android.view.WindowManager +import junit.framework.Assert +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentMatchers +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +@RunWith(MockitoJUnitRunner::class) +class CompassEngineTest { + private var compassEngine: LocationComponentCompassEngine? = null + + @Mock + private val windowManager: WindowManager? = null + + @Mock + private val sensorManager: SensorManager? = null + + @Mock + private val compassSensor: Sensor? = null + + @Mock + private val compassListener: CompassListener? = null + + @Before + @Throws(Exception::class) + fun setUp() { + Mockito.`when`(sensorManager!!.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR)) + .thenReturn(compassSensor) + compassEngine = LocationComponentCompassEngine(windowManager!!, sensorManager) + } + + @Test + fun lastKnownCompassBearingAccuracyDefault() { + Assert.assertEquals( + "Last accuracy should match", + compassEngine!!.lastAccuracySensorStatus, + 0 + ) + } + + @Test + fun lastKnownCompassAccuracyStatusValue() { + val sensor = Mockito.mock( + Sensor::class.java + ) + compassEngine!!.onAccuracyChanged(sensor, 2) + Assert.assertEquals( + "Last accuracy should match", + compassEngine!!.lastAccuracySensorStatus, + 2 + ) + } + + @Test + fun whenGyroscopeIsNull_fallbackToGravity() { + val sensorManager = Mockito.mock(SensorManager::class.java) + LocationComponentCompassEngine(windowManager!!, sensorManager) + Mockito.verify(sensorManager, Mockito.times(1)).getDefaultSensor(Sensor.TYPE_ACCELEROMETER) + } + + @Test + fun whenGyroscopeIsNull_fallbackToMagneticField() { + val sensorManager = Mockito.mock(SensorManager::class.java) + LocationComponentCompassEngine(windowManager!!, sensorManager) + Mockito.verify(sensorManager, Mockito.times(1)).getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) + } + + @Test + fun listener_registerOnAdd() { + compassEngine!!.addCompassListener(compassListener!!) + Mockito.verify(sensorManager) + ?.registerListener( + ArgumentMatchers.any(SensorEventListener::class.java), + ArgumentMatchers.eq(compassSensor), + ArgumentMatchers.eq(LocationComponentCompassEngine.SENSOR_DELAY_MICROS) + ) + } + + @Test + fun listener_unregisterOnRemove() { + compassEngine!!.addCompassListener(compassListener!!) + compassEngine!!.removeCompassListener(compassListener) + Mockito.verify(sensorManager)?.unregisterListener( + ArgumentMatchers.any( + SensorEventListener::class.java + ), + ArgumentMatchers.eq(compassSensor) + ) + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationCameraControllerTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationCameraControllerTest.java deleted file mode 100644 index c2ec764fd..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationCameraControllerTest.java +++ /dev/null @@ -1,1264 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.graphics.PointF; -import android.graphics.RectF; -import android.location.Location; - -import com.mapbox.android.gestures.AndroidGesturesManager; -import com.mapbox.android.gestures.MoveGestureDetector; -import com.mapbox.mapboxsdk.camera.CameraPosition; -import com.mapbox.mapboxsdk.camera.CameraUpdate; -import com.mapbox.mapboxsdk.camera.CameraUpdateFactory; -import com.mapbox.mapboxsdk.geometry.LatLng; -import com.mapbox.mapboxsdk.maps.MapboxMap; -import com.mapbox.mapboxsdk.maps.Projection; -import com.mapbox.mapboxsdk.maps.Transform; -import com.mapbox.mapboxsdk.maps.UiSettings; - -import junit.framework.Assert; - -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.util.Set; - -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.TRANSITION_ANIMATION_DURATION_MS; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_CAMERA_COMPASS_BEARING; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_CAMERA_GPS_BEARING; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_CAMERA_LATLNG; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_TILT; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_ZOOM; -import static com.mapbox.mapboxsdk.location.modes.CameraMode.NONE; -import static com.mapbox.mapboxsdk.location.modes.CameraMode.NONE_COMPASS; -import static com.mapbox.mapboxsdk.location.modes.CameraMode.NONE_GPS; -import static com.mapbox.mapboxsdk.location.modes.CameraMode.TRACKING; -import static com.mapbox.mapboxsdk.location.modes.CameraMode.TRACKING_COMPASS; -import static com.mapbox.mapboxsdk.location.modes.CameraMode.TRACKING_GPS; -import static com.mapbox.mapboxsdk.location.modes.CameraMode.TRACKING_GPS_NORTH; -import static junit.framework.Assert.assertNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.atMost; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class LocationCameraControllerTest { - - @Test - public void setCameraMode_mapTransitionsAreCancelled() { - MapboxMap mapboxMap = mock(MapboxMap.class); - LocationCameraController camera = buildCamera(mapboxMap); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setEnabled(true); - camera.setCameraMode(TRACKING_GPS); - - verify(mapboxMap).cancelTransitions(); - } - - @Test - public void setCameraMode_gestureThresholdIsAdjusted() { - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - LocationCameraController camera = buildCamera(moveGestureDetector); - LocationComponentOptions options = mock(LocationComponentOptions.class); - float moveThreshold = 5f; - when(options.trackingInitialMoveThreshold()).thenReturn(moveThreshold); - when(options.trackingGesturesManagement()).thenReturn(true); - camera.initializeOptions(options); - - camera.setCameraMode(TRACKING_GPS); - - verify(moveGestureDetector).setMoveThreshold(moveThreshold); - verify(moveGestureDetector, times(0)).setMoveThresholdRect(any(RectF.class)); - } - - @Test - public void setCameraMode_gestureThresholdNotAdjustedWhenDisabled() { - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - LocationCameraController camera = buildCamera(moveGestureDetector); - LocationComponentOptions options = mock(LocationComponentOptions.class); - float moveThreshold = 5f; - when(options.trackingInitialMoveThreshold()).thenReturn(moveThreshold); - when(options.trackingGesturesManagement()).thenReturn(false); - camera.initializeOptions(options); - - camera.setCameraMode(TRACKING_GPS); - - verify(moveGestureDetector, times(0)).setMoveThreshold(moveThreshold); - verify(moveGestureDetector, times(0)).setMoveThreshold(0f); - verify(moveGestureDetector, times(0)).setMoveThresholdRect(any(RectF.class)); - } - - @Test - public void setCameraMode_gestureThresholdIsResetWhenNotTracking() { - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - LocationCameraController camera = buildCamera(moveGestureDetector); - LocationComponentOptions options = mock(LocationComponentOptions.class); - when(options.trackingGesturesManagement()).thenReturn(true); - camera.initializeOptions(options); - - camera.setCameraMode(NONE); - - verify(moveGestureDetector, times(2)).setMoveThreshold(0f); // one for initialization - verify(moveGestureDetector, times(2)).setMoveThresholdRect(null); // one for initialization - } - - @Test - public void setCameraMode_notTrackingAdjustsFocalPoint() { - MapboxMap mapboxMap = mock(MapboxMap.class); - when(mapboxMap.getUiSettings()).thenReturn(mock(UiSettings.class)); - LocationCameraController camera = buildCamera(mapboxMap); - camera.initializeOptions(mock(LocationComponentOptions.class)); - - camera.setCameraMode(TRACKING_GPS); - camera.setCameraMode(NONE); - - verify(mapboxMap.getUiSettings()).setFocalPoint(null); - } - - @Test - public void setCameraMode_trackingChangeListenerCameraDismissedIsCalled() { - OnCameraTrackingChangedListener internalTrackingChangedListener = mock(OnCameraTrackingChangedListener.class); - LocationCameraController camera = buildCamera(internalTrackingChangedListener); - camera.initializeOptions(mock(LocationComponentOptions.class)); - - camera.setCameraMode(TRACKING_GPS); - camera.setCameraMode(NONE); - - verify(internalTrackingChangedListener).onCameraTrackingDismissed(); - } - - @Test - public void setCameraMode_internalCameraTrackingChangeListenerIsCalled() { - OnCameraTrackingChangedListener internalTrackingChangedListener = mock(OnCameraTrackingChangedListener.class); - LocationCameraController camera = buildCamera(internalTrackingChangedListener); - camera.initializeOptions(mock(LocationComponentOptions.class)); - int cameraMode = NONE; - - camera.setCameraMode(cameraMode); - - verify(internalTrackingChangedListener).onCameraTrackingChanged(cameraMode); - } - - @Test - public void setCameraMode_doNotNotifyAboutDuplicates_NONE() { - OnCameraTrackingChangedListener internalTrackingChangedListener = mock(OnCameraTrackingChangedListener.class); - LocationCameraController camera = buildCamera(internalTrackingChangedListener); - camera.initializeOptions(mock(LocationComponentOptions.class)); - int cameraMode = NONE; - - camera.setCameraMode(cameraMode); - camera.setCameraMode(cameraMode); - - verify(internalTrackingChangedListener, times(1)).onCameraTrackingChanged(cameraMode); - } - - @Test - public void setCameraMode_doNotNotifyAboutDuplicates_TRACKING_GPS() { - OnCameraTrackingChangedListener internalTrackingChangedListener = mock(OnCameraTrackingChangedListener.class); - LocationCameraController camera = buildCamera(internalTrackingChangedListener); - camera.initializeOptions(mock(LocationComponentOptions.class)); - int cameraMode = TRACKING_GPS; - - camera.setCameraMode(cameraMode); - camera.setCameraMode(cameraMode); - - verify(internalTrackingChangedListener, times(1)).onCameraTrackingChanged(cameraMode); - } - - @Test - public void setCameraMode_cancelTransitionsWhenSet() { - MapboxMap mapboxMap = mock(MapboxMap.class); - when(mapboxMap.getUiSettings()).thenReturn(mock(UiSettings.class)); - when(mapboxMap.getProjection()).thenReturn(mock(Projection.class)); - LocationCameraController camera = buildCamera(mapboxMap); - camera.initializeOptions(mock(LocationComponentOptions.class)); - - camera.setCameraMode(NONE_COMPASS); - verify(mapboxMap, times(1)).cancelTransitions(); - - camera.setCameraMode(NONE_GPS); - verify(mapboxMap, times(2)).cancelTransitions(); - - camera.setCameraMode(TRACKING); - verify(mapboxMap, times(3)).cancelTransitions(); - - camera.setCameraMode(TRACKING_COMPASS); - verify(mapboxMap, times(4)).cancelTransitions(); - - camera.setCameraMode(TRACKING_GPS); - verify(mapboxMap, times(5)).cancelTransitions(); - - camera.setCameraMode(TRACKING_GPS_NORTH); - verify(mapboxMap, times(6)).cancelTransitions(); - } - - @Test - public void setCameraMode_dontCancelTransitionsWhenNoneSet() { - MapboxMap mapboxMap = mock(MapboxMap.class); - when(mapboxMap.getUiSettings()).thenReturn(mock(UiSettings.class)); - when(mapboxMap.getProjection()).thenReturn(mock(Projection.class)); - LocationCameraController camera = buildCamera(mapboxMap); - camera.initializeOptions(mock(LocationComponentOptions.class)); - - camera.setCameraMode(NONE); - verify(mapboxMap, never()).cancelTransitions(); - } - - @Test - public void onNewLatLngValue_cameraModeTrackingUpdatesLatLng() { - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(TRACKING); - LatLng latLng = mock(LatLng.class); - - getAnimationListener(ANIMATOR_CAMERA_LATLNG, camera.getAnimationListeners()).onNewAnimationValue(latLng); - - verify(transform).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNewLatLngValue_cameraModeTrackingGpsNorthUpdatesLatLng() { - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(TRACKING_GPS_NORTH); - LatLng latLng = mock(LatLng.class); - - getAnimationListener(ANIMATOR_CAMERA_LATLNG, camera.getAnimationListeners()).onNewAnimationValue(latLng); - - verify(transform).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNewLatLngValue_cameraModeTrackingGpsUpdatesLatLng() { - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(TRACKING_GPS); - LatLng latLng = mock(LatLng.class); - - getAnimationListener(ANIMATOR_CAMERA_LATLNG, camera.getAnimationListeners()).onNewAnimationValue(latLng); - - verify(transform).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNewLatLngValue_cameraModeTrackingCompassUpdatesLatLng() { - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(TRACKING_COMPASS); - LatLng latLng = mock(LatLng.class); - - getAnimationListener(ANIMATOR_CAMERA_LATLNG, camera.getAnimationListeners()).onNewAnimationValue(latLng); - - verify(transform).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNewLatLngValue_cameraModeNoneIgnored() { - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(NONE); - - assertNull(getAnimationListener(ANIMATOR_CAMERA_LATLNG, camera.getAnimationListeners())); - verify(transform, times(0)).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNewLatLngValue_focalPointIsAdjusted() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - - final MapboxMap.OnCameraMoveListener[] listener = {null}; - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) { - listener[0] = (MapboxMap.OnCameraMoveListener) invocation.getArguments()[0]; - return null; - } - }).when(mapboxMap).addOnCameraMoveListener(any(MapboxMap.OnCameraMoveListener.class)); - - Projection projection = mock(Projection.class); - PointF pointF = mock(PointF.class); - when(projection.toScreenLocation(any(LatLng.class))).thenReturn(pointF); - when(mapboxMap.getProjection()).thenReturn(projection); - LocationCameraController camera = buildCamera(mapboxMap, transform); - LocationComponentOptions options = mock(LocationComponentOptions.class); - when(options.trackingGesturesManagement()).thenReturn(true); - camera.initializeOptions(options); - camera.setCameraMode(TRACKING); - LatLng latLng = mock(LatLng.class); - - getAnimationListener(ANIMATOR_CAMERA_LATLNG, camera.getAnimationListeners()).onNewAnimationValue(latLng); - verify(transform).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - - UiSettings uiSettings = mock(UiSettings.class); - when(mapboxMap.getUiSettings()).thenReturn(uiSettings); - listener[0].onCameraMove(); - verify(uiSettings).setFocalPoint(pointF); - } - - @Test - public void onNewGpsBearingValue_cameraModeTrackingGpsUpdatesBearing() { - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(TRACKING_GPS); - float gpsBearing = 5f; - - getAnimationListener(ANIMATOR_CAMERA_GPS_BEARING, camera.getAnimationListeners()).onNewAnimationValue(gpsBearing); - - verify(transform).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNewGpsBearingValue_cameraModeNoneGpsUpdatesBearing() { - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(NONE_GPS); - float gpsBearing = 5f; - - getAnimationListener(ANIMATOR_CAMERA_GPS_BEARING, camera.getAnimationListeners()).onNewAnimationValue(gpsBearing); - - verify(transform).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNewGpsBearingValue_cameraModeTrackingNorthUpdatesBearing() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(mapboxMap, transform); - CameraPosition cameraPosition = new CameraPosition.Builder().bearing(7d).build(); - when(mapboxMap.getCameraPosition()).thenReturn(cameraPosition); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(TRACKING_GPS_NORTH); - float gpsBearing = 5f; - - getAnimationListener(ANIMATOR_CAMERA_GPS_BEARING, camera.getAnimationListeners()).onNewAnimationValue(gpsBearing); - - verify(transform).moveCamera(eq(mapboxMap), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNewGpsBearingValue_cameraModeTrackingNorthBearingZeroIgnored() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(mapboxMap, transform); - CameraPosition cameraPosition = new CameraPosition.Builder().bearing(0d).build(); - when(mapboxMap.getCameraPosition()).thenReturn(cameraPosition); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(TRACKING_GPS_NORTH); - float gpsBearing = 5f; - - getAnimationListener(ANIMATOR_CAMERA_GPS_BEARING, camera.getAnimationListeners()).onNewAnimationValue(gpsBearing); - - verify(transform, times(0)).moveCamera(eq(mapboxMap), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNewGpsBearingValue_cameraModeNoneIgnored() { - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(NONE); - - assertNull(getAnimationListener(ANIMATOR_CAMERA_GPS_BEARING, camera.getAnimationListeners())); - verify(transform, times(0)).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNewCompassBearingValue_cameraModeTrackingCompassUpdatesBearing() { - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(TRACKING_COMPASS); - float compassBearing = 5f; - - getAnimationListener(ANIMATOR_CAMERA_COMPASS_BEARING, camera.getAnimationListeners()) - .onNewAnimationValue(compassBearing); - - verify(transform).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNewCompassBearingValue_cameraModeNoneCompassUpdatesBearing() { - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(NONE_COMPASS); - float compassBearing = 5f; - - getAnimationListener(ANIMATOR_CAMERA_COMPASS_BEARING, camera.getAnimationListeners()) - .onNewAnimationValue(compassBearing); - - verify(transform).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNewCompassBearingValue_cameraModeNoneIgnored() { - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(NONE); - - assertNull(getAnimationListener(ANIMATOR_CAMERA_COMPASS_BEARING, camera.getAnimationListeners())); - verify(transform, times(0)).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNewZoomValue_cameraIsUpdated() { - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(TRACKING); - float zoom = 5f; - - getAnimationListener(ANIMATOR_ZOOM, camera.getAnimationListeners()).onNewAnimationValue(zoom); - - verify(transform).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNeTiltValue_cameraIsUpdated() { - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(TRACKING); - float tilt = 5f; - - getAnimationListener(ANIMATOR_TILT, camera.getAnimationListeners()).onNewAnimationValue(tilt); - - verify(transform).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void gesturesManagement_enabled() { - MapboxMap mapboxMap = mock(MapboxMap.class); - AndroidGesturesManager initialGesturesManager = mock(AndroidGesturesManager.class); - AndroidGesturesManager internalGesturesManager = mock(AndroidGesturesManager.class); - when(mapboxMap.getGesturesManager()).thenReturn(initialGesturesManager); - LocationCameraController camera = buildCamera(mapboxMap, initialGesturesManager, internalGesturesManager); - LocationComponentOptions options = mock(LocationComponentOptions.class); - when(options.trackingGesturesManagement()).thenReturn(true); - camera.initializeOptions(options); - - verify(mapboxMap).setGesturesManager(internalGesturesManager, true, true); - } - - @Test - public void gesturesManagement_disabled() { - MapboxMap mapboxMap = mock(MapboxMap.class); - AndroidGesturesManager initialGesturesManager = mock(AndroidGesturesManager.class); - AndroidGesturesManager internalGesturesManager = mock(AndroidGesturesManager.class); - when(mapboxMap.getGesturesManager()).thenReturn(internalGesturesManager); - LocationCameraController camera = buildCamera(mapboxMap, initialGesturesManager, internalGesturesManager); - LocationComponentOptions options = mock(LocationComponentOptions.class); - when(options.trackingGesturesManagement()).thenReturn(false); - camera.initializeOptions(options); - - verify(mapboxMap).setGesturesManager(initialGesturesManager, true, true); - } - - @Test - public void gesturesManagement_optionNotChangedInitial() { - MapboxMap mapboxMap = mock(MapboxMap.class); - AndroidGesturesManager initialGesturesManager = mock(AndroidGesturesManager.class); - AndroidGesturesManager internalGesturesManager = mock(AndroidGesturesManager.class); - when(mapboxMap.getGesturesManager()).thenReturn(initialGesturesManager); - LocationCameraController camera = buildCamera(mapboxMap, initialGesturesManager, internalGesturesManager); - LocationComponentOptions options = mock(LocationComponentOptions.class); - when(options.trackingGesturesManagement()).thenReturn(false); - camera.initializeOptions(options); - - verify(mapboxMap, times(0)).setGesturesManager(initialGesturesManager, true, true); - } - - @Test - public void gesturesManagement_optionNotChangedInternal() { - MapboxMap mapboxMap = mock(MapboxMap.class); - AndroidGesturesManager initialGesturesManager = mock(AndroidGesturesManager.class); - AndroidGesturesManager internalGesturesManager = mock(AndroidGesturesManager.class); - when(mapboxMap.getGesturesManager()).thenReturn(internalGesturesManager); - LocationCameraController camera = buildCamera(mapboxMap, initialGesturesManager, internalGesturesManager); - LocationComponentOptions options = mock(LocationComponentOptions.class); - when(options.trackingGesturesManagement()).thenReturn(true); - camera.initializeOptions(options); - - verify(mapboxMap, times(0)).setGesturesManager(internalGesturesManager, true, true); - } - - @Test - public void gesturesManagement_moveGesture_notTracking() { - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - when(moveGestureDetector.getPointersCount()).thenReturn(1); - LocationCameraController camera = buildCamera(moveGestureDetector); - LocationComponentOptions options = mock(LocationComponentOptions.class); - when(options.trackingGesturesManagement()).thenReturn(true); - float initial = 100; - float multiFinger = 200; - RectF multiFingerArea = mock(RectF.class); - when(options.trackingInitialMoveThreshold()).thenReturn(initial); - when(options.trackingMultiFingerMoveThreshold()).thenReturn(multiFinger); - when(options.trackingMultiFingerProtectedMoveArea()).thenReturn(multiFingerArea); - camera.initializeOptions(options); - - camera.onMoveListener.onMoveBegin(moveGestureDetector); - - verify(moveGestureDetector, times(2)).setMoveThreshold(0); - verify(moveGestureDetector, times(2)).setMoveThresholdRect(null); - } - - @Test - public void gesturesManagement_moveGesture_singlePointer_tracking() { - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - when(moveGestureDetector.getPointersCount()).thenReturn(1); - LocationCameraController camera = buildCamera(moveGestureDetector); - LocationComponentOptions options = mock(LocationComponentOptions.class); - when(options.trackingGesturesManagement()).thenReturn(true); - float initial = 100; - when(options.trackingInitialMoveThreshold()).thenReturn(initial); - camera.initializeOptions(options); - - camera.setCameraMode(TRACKING); - when(moveGestureDetector.getMoveThreshold()).thenReturn(initial); - camera.onMoveListener.onMoveBegin(moveGestureDetector); - - verify(moveGestureDetector, atMost(1)).setMoveThreshold(initial); - verify(moveGestureDetector, times(0)).setMoveThresholdRect(any(RectF.class)); - } - - @Test - public void gesturesManagement_moveGesture_singlePointer_tracking_duplicateCall() { - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - when(moveGestureDetector.getPointersCount()).thenReturn(1); - LocationCameraController camera = buildCamera(moveGestureDetector); - LocationComponentOptions options = mock(LocationComponentOptions.class); - when(options.trackingGesturesManagement()).thenReturn(true); - float initial = 100; - when(options.trackingInitialMoveThreshold()).thenReturn(initial); - camera.initializeOptions(options); - - camera.setCameraMode(TRACKING); - when(moveGestureDetector.getMoveThreshold()).thenReturn(initial); - camera.onMoveListener.onMoveBegin(moveGestureDetector); - - verify(moveGestureDetector, atMost(1)).setMoveThreshold(initial); - verify(moveGestureDetector, times(0)).setMoveThresholdRect(any(RectF.class)); - } - - @Test - public void gesturesManagement_moveGesture_singlePointer_tracking_thresholdMet() { - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - when(moveGestureDetector.getPointersCount()).thenReturn(1); - LocationCameraController camera = buildCamera(moveGestureDetector); - LocationComponentOptions options = mock(LocationComponentOptions.class); - when(options.trackingGesturesManagement()).thenReturn(true); - float initial = 100; - when(options.trackingInitialMoveThreshold()).thenReturn(initial); - camera.initializeOptions(options); - - // verify the number of detector interruptions - camera.setCameraMode(TRACKING); - camera.onMoveListener.onMoveBegin(moveGestureDetector); - when(moveGestureDetector.getMoveThreshold()).thenReturn(initial); - camera.onMoveListener.onMove(moveGestureDetector); - verify(moveGestureDetector, times(1)).interrupt(); - camera.onMoveListener.onMoveEnd(moveGestureDetector); - camera.onMoveListener.onMoveBegin(moveGestureDetector); - camera.onMoveListener.onMove(moveGestureDetector); - verify(moveGestureDetector, times(2)).interrupt(); - camera.onMoveListener.onMoveEnd(moveGestureDetector); - camera.onMoveListener.onMoveBegin(moveGestureDetector); - camera.onMoveListener.onMove(moveGestureDetector); - camera.onMoveListener.onMoveEnd(moveGestureDetector); - - verify(moveGestureDetector, times(2)).interrupt(); - - // verify that threshold are reset - ArgumentCaptor moveThresholdCaptor = ArgumentCaptor.forClass(Float.class); - verify(moveGestureDetector, atLeastOnce()).setMoveThreshold(moveThresholdCaptor.capture()); - org.junit.Assert.assertEquals(Float.valueOf(0), moveThresholdCaptor.getValue()); - } - - @Test - public void gesturesManagement_moveGesture_multiPointer_tracking() { - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - when(moveGestureDetector.getPointersCount()).thenReturn(2); - LocationCameraController camera = buildCamera(moveGestureDetector); - LocationComponentOptions options = mock(LocationComponentOptions.class); - when(options.trackingGesturesManagement()).thenReturn(true); - float initial = 100; - float multiFinger = 200; - RectF multiFingerArea = mock(RectF.class); - when(options.trackingInitialMoveThreshold()).thenReturn(initial); - when(options.trackingMultiFingerMoveThreshold()).thenReturn(multiFinger); - when(options.trackingMultiFingerProtectedMoveArea()).thenReturn(multiFingerArea); - camera.initializeOptions(options); - - camera.setCameraMode(TRACKING); - camera.onMoveListener.onMoveBegin(moveGestureDetector); - - verify(moveGestureDetector, atMost(1)).setMoveThreshold(multiFinger); - verify(moveGestureDetector, atMost(1)).setMoveThresholdRect(multiFingerArea); - } - - @Test - public void gesturesManagement_moveGesture_multiPointer_tracking_duplicateCall() { - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - when(moveGestureDetector.getPointersCount()).thenReturn(2); - LocationCameraController camera = buildCamera(moveGestureDetector); - LocationComponentOptions options = mock(LocationComponentOptions.class); - when(options.trackingGesturesManagement()).thenReturn(true); - float initial = 100; - float multiFinger = 200; - RectF multiFingerArea = mock(RectF.class); - when(options.trackingInitialMoveThreshold()).thenReturn(initial); - when(options.trackingMultiFingerMoveThreshold()).thenReturn(multiFinger); - when(options.trackingMultiFingerProtectedMoveArea()).thenReturn(multiFingerArea); - camera.initializeOptions(options); - - camera.setCameraMode(TRACKING); - camera.onMoveListener.onMoveBegin(moveGestureDetector); - when(moveGestureDetector.getMoveThreshold()).thenReturn(multiFinger); - when(moveGestureDetector.getMoveThresholdRect()).thenReturn(multiFingerArea); - camera.onMoveListener.onMoveBegin(moveGestureDetector); - - verify(moveGestureDetector, atMost(1)).setMoveThreshold(multiFinger); - verify(moveGestureDetector, atMost(1)).setMoveThresholdRect(multiFingerArea); - } - - @Test - public void gesturesManagement_moveGesture_multiPointer_tracking_thresholdMet() { - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - when(moveGestureDetector.getPointersCount()).thenReturn(2); - LocationCameraController camera = buildCamera(moveGestureDetector); - LocationComponentOptions options = mock(LocationComponentOptions.class); - when(options.trackingGesturesManagement()).thenReturn(true); - float initial = 100; - float multiFinger = 200; - RectF multiFingerArea = mock(RectF.class); - when(options.trackingInitialMoveThreshold()).thenReturn(initial); - when(options.trackingMultiFingerMoveThreshold()).thenReturn(multiFinger); - when(options.trackingMultiFingerProtectedMoveArea()).thenReturn(multiFingerArea); - camera.initializeOptions(options); - - // verify the number of detector interruptions - camera.setCameraMode(TRACKING); - camera.onMoveListener.onMoveBegin(moveGestureDetector); - when(moveGestureDetector.getMoveThreshold()).thenReturn(initial); - when(moveGestureDetector.getMoveThreshold()).thenReturn(multiFinger); - when(moveGestureDetector.getMoveThresholdRect()).thenReturn(multiFingerArea); - camera.onMoveListener.onMove(moveGestureDetector); - verify(moveGestureDetector, times(1)).interrupt(); - camera.onMoveListener.onMoveEnd(moveGestureDetector); - camera.onMoveListener.onMoveBegin(moveGestureDetector); - camera.onMoveListener.onMove(moveGestureDetector); - verify(moveGestureDetector, times(2)).interrupt(); - camera.onMoveListener.onMoveEnd(moveGestureDetector); - camera.onMoveListener.onMoveBegin(moveGestureDetector); - camera.onMoveListener.onMove(moveGestureDetector); - camera.onMoveListener.onMoveEnd(moveGestureDetector); - - verify(moveGestureDetector, times(2)).interrupt(); - - // verify that threshold are reset - ArgumentCaptor moveThresholdCaptor = ArgumentCaptor.forClass(Float.class); - verify(moveGestureDetector, atLeastOnce()).setMoveThreshold(moveThresholdCaptor.capture()); - org.junit.Assert.assertEquals(Float.valueOf(0), moveThresholdCaptor.getValue()); - - ArgumentCaptor areaCaptor = ArgumentCaptor.forClass(RectF.class); - verify(moveGestureDetector, atLeastOnce()).setMoveThresholdRect(areaCaptor.capture()); - org.junit.Assert.assertNull(areaCaptor.getValue()); - } - - @Test - public void onMove_notCancellingTransitionWhileNone() { - MapboxMap mapboxMap = mock(MapboxMap.class); - when(mapboxMap.getUiSettings()).thenReturn(mock(UiSettings.class)); - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - LocationCameraController camera = buildCamera(mapboxMap); - camera.initializeOptions(mock(LocationComponentOptions.class)); - - camera.setCameraMode(NONE); - camera.onMoveListener.onMove(moveGestureDetector); - verify(mapboxMap, times(0)).cancelTransitions(); - verify(moveGestureDetector, times(0)).interrupt(); - - // testing subsequent calls - camera.onMoveListener.onMove(moveGestureDetector); - verify(mapboxMap, times(0)).cancelTransitions(); - verify(moveGestureDetector, times(0)).interrupt(); - } - - @Test - public void onMove_cancellingTransitionWhileGps() { - MapboxMap mapboxMap = mock(MapboxMap.class); - when(mapboxMap.getUiSettings()).thenReturn(mock(UiSettings.class)); - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - LocationCameraController camera = buildCamera(mapboxMap); - camera.initializeOptions(mock(LocationComponentOptions.class)); - - camera.setCameraMode(TRACKING); - camera.onMoveListener.onMove(moveGestureDetector); - verify(mapboxMap, times(1)).cancelTransitions(); - verify(moveGestureDetector, times(1)).interrupt(); - - // testing subsequent calls - camera.onMoveListener.onMove(moveGestureDetector); - verify(mapboxMap, times(1)).cancelTransitions(); - verify(moveGestureDetector, times(1)).interrupt(); - } - - @Test - public void onMove_cancellingTransitionWhileBearing() { - MapboxMap mapboxMap = mock(MapboxMap.class); - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - LocationCameraController camera = buildCamera(mapboxMap); - camera.initializeOptions(mock(LocationComponentOptions.class)); - - camera.setCameraMode(NONE_COMPASS); - camera.onMoveListener.onMove(moveGestureDetector); - verify(mapboxMap, times(1)).cancelTransitions(); - verify(moveGestureDetector, times(1)).interrupt(); - - // testing subsequent calls - camera.onMoveListener.onMove(moveGestureDetector); - verify(mapboxMap, times(1)).cancelTransitions(); - verify(moveGestureDetector, times(1)).interrupt(); - } - - @Test - public void transition_locationIsNull() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(mapboxMap, transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - OnLocationCameraTransitionListener listener = mock(OnLocationCameraTransitionListener.class); - - camera.setCameraMode(TRACKING, null, TRANSITION_ANIMATION_DURATION_MS, null, null, null, listener); - Assert.assertEquals(TRACKING, camera.getCameraMode()); - verify(listener).onLocationCameraTransitionFinished(TRACKING); - verify(transform, times(0)) - .animateCamera(eq(mapboxMap), any(CameraUpdate.class), any(Integer.class), - any(MapboxMap.CancelableCallback.class)); - } - - @Test - public void transition_notTracking() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(mapboxMap, transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - OnLocationCameraTransitionListener listener = mock(OnLocationCameraTransitionListener.class); - Location location = mock(Location.class); - - camera.setCameraMode(NONE, location, TRANSITION_ANIMATION_DURATION_MS, null, null, null, listener); - verify(listener, times(1)).onLocationCameraTransitionFinished(NONE); - verify(transform, times(0)) - .animateCamera(eq(mapboxMap), any(CameraUpdate.class), any(Integer.class), - any(MapboxMap.CancelableCallback.class)); - } - - @Test - public void transition_trackingChanged() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - when(mapboxMap.getCameraPosition()).thenReturn(CameraPosition.DEFAULT); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1000)); - LocationCameraController camera = buildCamera(mapboxMap, transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - final OnLocationCameraTransitionListener listener = mock(OnLocationCameraTransitionListener.class); - Location location = mock(Location.class); - - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - listener.onLocationCameraTransitionFinished(TRACKING); - return null; - } - }).when(transform).animateCamera(eq(mapboxMap), any(CameraUpdate.class), any(Integer.class), - any(MapboxMap.CancelableCallback.class)); - - camera.setCameraMode(TRACKING, location, TRANSITION_ANIMATION_DURATION_MS, null, null, null, listener); - verify(listener).onLocationCameraTransitionFinished(TRACKING); - verify(transform) - .animateCamera(eq(mapboxMap), any(CameraUpdate.class), any(Integer.class), - any(MapboxMap.CancelableCallback.class)); - } - - @Test - public void transition_trackingNotChanged() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - when(mapboxMap.getCameraPosition()).thenReturn(CameraPosition.DEFAULT); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1000)); - LocationCameraController camera = buildCamera(mapboxMap, transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - final OnLocationCameraTransitionListener listener = mock(OnLocationCameraTransitionListener.class); - Location location = mock(Location.class); - - camera.setCameraMode(TRACKING, location, TRANSITION_ANIMATION_DURATION_MS, null, null, null, listener); - - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - listener.onLocationCameraTransitionFinished(TRACKING_GPS_NORTH); - return null; - } - }).when(transform).animateCamera(eq(mapboxMap), any(CameraUpdate.class), any(Integer.class), - any(MapboxMap.CancelableCallback.class)); - - camera.setCameraMode(TRACKING_GPS_NORTH, location, TRANSITION_ANIMATION_DURATION_MS, null, null, null, listener); - verify(listener, times(1)).onLocationCameraTransitionFinished(TRACKING_GPS_NORTH); - verify(transform, times(1)) - .animateCamera(eq(mapboxMap), any(CameraUpdate.class), any(Integer.class), - any(MapboxMap.CancelableCallback.class)); - } - - @Test - public void transition_duplicateMode() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - when(mapboxMap.getCameraPosition()).thenReturn(CameraPosition.DEFAULT); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1000)); - LocationCameraController camera = buildCamera(mapboxMap, transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - final OnLocationCameraTransitionListener listener = mock(OnLocationCameraTransitionListener.class); - Location location = mock(Location.class); - - camera.setCameraMode(TRACKING, location, TRANSITION_ANIMATION_DURATION_MS, null, null, null, listener); - - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - listener.onLocationCameraTransitionFinished(TRACKING); - return null; - } - }).when(transform).animateCamera(eq(mapboxMap), any(CameraUpdate.class), any(Integer.class), - any(MapboxMap.CancelableCallback.class)); - camera.setCameraMode(TRACKING, location, TRANSITION_ANIMATION_DURATION_MS, null, null, null, listener); - verify(listener, times(1)).onLocationCameraTransitionFinished(TRACKING); - verify(transform, times(1)) - .animateCamera(eq(mapboxMap), any(CameraUpdate.class), any(Integer.class), - any(MapboxMap.CancelableCallback.class)); - } - - @Test - public void transition_canceled() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - when(mapboxMap.getCameraPosition()).thenReturn(CameraPosition.DEFAULT); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1000)); - LocationCameraController camera = buildCamera(mapboxMap, transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - final OnLocationCameraTransitionListener listener = mock(OnLocationCameraTransitionListener.class); - Location location = mock(Location.class); - - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - listener.onLocationCameraTransitionCanceled(TRACKING); - return null; - } - }).when(transform).animateCamera(eq(mapboxMap), any(CameraUpdate.class), any(Integer.class), - any(MapboxMap.CancelableCallback.class)); - - camera.setCameraMode(TRACKING, location, TRANSITION_ANIMATION_DURATION_MS, null, null, null, listener); - verify(listener).onLocationCameraTransitionCanceled(TRACKING); - verify(transform) - .animateCamera(eq(mapboxMap), any(CameraUpdate.class), any(Integer.class), - any(MapboxMap.CancelableCallback.class)); - } - - @Test - public void transition_mapboxCallbackFinished() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - when(mapboxMap.getCameraPosition()).thenReturn(CameraPosition.DEFAULT); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1000)); - LocationCameraController camera = buildCamera(mapboxMap, transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - final OnLocationCameraTransitionListener listener = mock(OnLocationCameraTransitionListener.class); - Location location = mock(Location.class); - when(location.getLatitude()).thenReturn(1.0); - when(location.getLongitude()).thenReturn(1.0); - when(location.getBearing()).thenReturn(30f); - when(location.getAltitude()).thenReturn(0.0); - - ArgumentCaptor callbackCaptor - = ArgumentCaptor.forClass(MapboxMap.CancelableCallback.class); - - camera.setCameraMode(TRACKING, location, TRANSITION_ANIMATION_DURATION_MS, null, null, null, listener); - - CameraPosition.Builder builder = new CameraPosition.Builder().target(new LatLng(location)); - verify(transform).animateCamera( - eq(mapboxMap), - eq(CameraUpdateFactory.newCameraPosition(builder.build())), - eq((int) TRANSITION_ANIMATION_DURATION_MS), - callbackCaptor.capture()); - - Assert.assertTrue(camera.isTransitioning()); - - callbackCaptor.getValue().onFinish(); - - Assert.assertFalse(camera.isTransitioning()); - - verify(listener).onLocationCameraTransitionFinished(TRACKING); - } - - @Test - public void transition_mapboxCallbackFinishedImmediately() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - when(mapboxMap.getCameraPosition()).thenReturn(CameraPosition.DEFAULT); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1)); - LocationCameraController camera = buildCamera(mapboxMap, transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - final OnLocationCameraTransitionListener listener = mock(OnLocationCameraTransitionListener.class); - Location location = mock(Location.class); - when(location.getLatitude()).thenReturn(1.0); - when(location.getLongitude()).thenReturn(1.0); - when(location.getBearing()).thenReturn(30f); - when(location.getAltitude()).thenReturn(0.0); - - ArgumentCaptor callbackCaptor - = ArgumentCaptor.forClass(MapboxMap.CancelableCallback.class); - - camera.setCameraMode(TRACKING, location, TRANSITION_ANIMATION_DURATION_MS, null, null, null, listener); - - CameraPosition.Builder builder = new CameraPosition.Builder().target(new LatLng(location)); - verify(transform).moveCamera( - eq(mapboxMap), - eq(CameraUpdateFactory.newCameraPosition(builder.build())), - callbackCaptor.capture()); - - Assert.assertTrue(camera.isTransitioning()); - - callbackCaptor.getValue().onFinish(); - - Assert.assertFalse(camera.isTransitioning()); - - verify(listener).onLocationCameraTransitionFinished(TRACKING); - } - - @Test - public void transition_mapboxCallbackCanceled() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - when(mapboxMap.getCameraPosition()).thenReturn(CameraPosition.DEFAULT); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1000)); - LocationCameraController camera = buildCamera(mapboxMap, transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - final OnLocationCameraTransitionListener listener = mock(OnLocationCameraTransitionListener.class); - Location location = mock(Location.class); - when(location.getLatitude()).thenReturn(1.0); - when(location.getLongitude()).thenReturn(1.0); - when(location.getBearing()).thenReturn(30f); - when(location.getAltitude()).thenReturn(0.0); - - ArgumentCaptor callbackCaptor - = ArgumentCaptor.forClass(MapboxMap.CancelableCallback.class); - - camera.setCameraMode(TRACKING, location, TRANSITION_ANIMATION_DURATION_MS, null, null, null, listener); - - CameraPosition.Builder builder = new CameraPosition.Builder().target(new LatLng(location)); - verify(transform).animateCamera( - eq(mapboxMap), - eq(CameraUpdateFactory.newCameraPosition(builder.build())), - eq((int) TRANSITION_ANIMATION_DURATION_MS), - callbackCaptor.capture()); - - Assert.assertTrue(camera.isTransitioning()); - - callbackCaptor.getValue().onCancel(); - - Assert.assertFalse(camera.isTransitioning()); - - verify(listener).onLocationCameraTransitionCanceled(TRACKING); - } - - @Test - public void transition_mapboxAnimateBearing() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - when(mapboxMap.getCameraPosition()).thenReturn(CameraPosition.DEFAULT); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1000)); - LocationCameraController camera = buildCamera(mapboxMap, transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - final OnLocationCameraTransitionListener listener = mock(OnLocationCameraTransitionListener.class); - Location location = mock(Location.class); - when(location.getLatitude()).thenReturn(1.0); - when(location.getLongitude()).thenReturn(1.0); - when(location.getBearing()).thenReturn(30f); - when(location.getAltitude()).thenReturn(0.0); - - camera.setCameraMode(TRACKING_GPS, location, TRANSITION_ANIMATION_DURATION_MS, null, null, null, listener); - - CameraPosition.Builder builder = new CameraPosition.Builder().target(new LatLng(location)).bearing(30); - verify(transform).animateCamera( - eq(mapboxMap), - eq(CameraUpdateFactory.newCameraPosition(builder.build())), - eq((int) TRANSITION_ANIMATION_DURATION_MS), - any(MapboxMap.CancelableCallback.class)); - } - - @Test - public void transition_mapboxAnimateNorth() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - when(mapboxMap.getCameraPosition()).thenReturn(CameraPosition.DEFAULT); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1000)); - LocationCameraController camera = buildCamera(mapboxMap, transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - final OnLocationCameraTransitionListener listener = mock(OnLocationCameraTransitionListener.class); - Location location = mock(Location.class); - when(location.getLatitude()).thenReturn(1.0); - when(location.getLongitude()).thenReturn(1.0); - when(location.getBearing()).thenReturn(30f); - when(location.getAltitude()).thenReturn(0.0); - - camera.setCameraMode(TRACKING_GPS_NORTH, location, TRANSITION_ANIMATION_DURATION_MS, null, null, null, listener); - - CameraPosition.Builder builder = new CameraPosition.Builder().target(new LatLng(location)).bearing(0); - verify(transform).animateCamera( - eq(mapboxMap), - eq(CameraUpdateFactory.newCameraPosition(builder.build())), - eq((int) TRANSITION_ANIMATION_DURATION_MS), - any(MapboxMap.CancelableCallback.class)); - } - - @Test - public void transition_animatorValuesDuringTransition() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - when(mapboxMap.getCameraPosition()).thenReturn(CameraPosition.DEFAULT); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1000)); - LocationCameraController camera = buildCamera(mapboxMap, transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - final OnLocationCameraTransitionListener listener = mock(OnLocationCameraTransitionListener.class); - Location location = mock(Location.class); - - ArgumentCaptor callbackCaptor - = ArgumentCaptor.forClass(MapboxMap.CancelableCallback.class); - - camera.setCameraMode(TRACKING_GPS, location, TRANSITION_ANIMATION_DURATION_MS, null, null, null, listener); - - verify(transform).animateCamera( - eq(mapboxMap), - any(CameraUpdate.class), - eq((int) TRANSITION_ANIMATION_DURATION_MS), - callbackCaptor.capture()); - - LatLng latLng = new LatLng(10, 10); - getAnimationListener(ANIMATOR_CAMERA_LATLNG, camera.getAnimationListeners()).onNewAnimationValue(latLng); - getAnimationListener(ANIMATOR_CAMERA_GPS_BEARING, camera.getAnimationListeners()).onNewAnimationValue(10f); - getAnimationListener(ANIMATOR_TILT, camera.getAnimationListeners()).onNewAnimationValue(10f); - getAnimationListener(ANIMATOR_ZOOM, camera.getAnimationListeners()).onNewAnimationValue(10f); - - verify(transform, times(0)).moveCamera(eq(mapboxMap), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - - callbackCaptor.getValue().onFinish(); - - getAnimationListener(ANIMATOR_CAMERA_LATLNG, camera.getAnimationListeners()).onNewAnimationValue(latLng); - getAnimationListener(ANIMATOR_CAMERA_GPS_BEARING, camera.getAnimationListeners()).onNewAnimationValue(10f); - getAnimationListener(ANIMATOR_TILT, camera.getAnimationListeners()).onNewAnimationValue(10f); - getAnimationListener(ANIMATOR_ZOOM, camera.getAnimationListeners()).onNewAnimationValue(10f); - - verify(transform, times(4)).moveCamera(eq(mapboxMap), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void transition_customAnimation() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - when(mapboxMap.getCameraPosition()).thenReturn(CameraPosition.DEFAULT); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1000)); - LocationCameraController camera = buildCamera(mapboxMap, transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - Location location = mock(Location.class); - CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition( - new CameraPosition.Builder() - .target(new LatLng(location)) - .zoom(14.0) - .bearing(13.0) - .tilt(45.0) - .build() - ); - - camera.setCameraMode(TRACKING, location, 1200, 14.0, 13.0, 45.0, null); - verify(transform) - .animateCamera(eq(mapboxMap), eq(cameraUpdate), eq(1200), any(MapboxMap.CancelableCallback.class)); - } - - @Test - public void transition_customAnimationDisabled() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - when(mapboxMap.getCameraPosition()).thenReturn(CameraPosition.DEFAULT); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1000)); - LocationCameraController camera = buildCamera(mapboxMap, transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - Location location = mock(Location.class); - CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition( - new CameraPosition.Builder() - .target(new LatLng(location)) - .zoom(14.0) - .bearing(13.0) - .tilt(45.0) - .build() - ); - - camera.setEnabled(false); - camera.setCameraMode(TRACKING, location, 1200, 14.0, 13.0, 45.0, null); - verify(transform, times(0)) - .animateCamera(eq(mapboxMap), eq(cameraUpdate), eq(1200), any(MapboxMap.CancelableCallback.class)); - } - - private LocationCameraController buildCamera(OnCameraTrackingChangedListener onCameraTrackingChangedListener) { - MapboxMap mapboxMap = mock(MapboxMap.class); - when(mapboxMap.getUiSettings()).thenReturn(mock(UiSettings.class)); - Transform transform = mock(Transform.class); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1000)); - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - OnCameraMoveInvalidateListener onCameraMoveInvalidateListener = mock(OnCameraMoveInvalidateListener.class); - AndroidGesturesManager initialGesturesManager = mock(AndroidGesturesManager.class); - AndroidGesturesManager internalGesturesManager = mock(AndroidGesturesManager.class); - return new LocationCameraController(mapboxMap, transform, moveGestureDetector, - onCameraTrackingChangedListener, onCameraMoveInvalidateListener, initialGesturesManager, internalGesturesManager); - } - - private LocationCameraController buildCamera(MoveGestureDetector moveGestureDetector) { - MapboxMap mapboxMap = mock(MapboxMap.class); - when(mapboxMap.getUiSettings()).thenReturn(mock(UiSettings.class)); - Transform transform = mock(Transform.class); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1000)); - OnCameraTrackingChangedListener onCameraTrackingChangedListener = mock(OnCameraTrackingChangedListener.class); - OnCameraMoveInvalidateListener onCameraMoveInvalidateListener = mock(OnCameraMoveInvalidateListener.class); - AndroidGesturesManager initialGesturesManager = mock(AndroidGesturesManager.class); - AndroidGesturesManager internalGesturesManager = mock(AndroidGesturesManager.class); - return new LocationCameraController(mapboxMap, transform, moveGestureDetector, - onCameraTrackingChangedListener, onCameraMoveInvalidateListener, initialGesturesManager, internalGesturesManager); - } - - private LocationCameraController buildCamera(MapboxMap mapboxMap) { - Transform transform = mock(Transform.class); - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - OnCameraTrackingChangedListener onCameraTrackingChangedListener = mock(OnCameraTrackingChangedListener.class); - OnCameraMoveInvalidateListener onCameraMoveInvalidateListener = mock(OnCameraMoveInvalidateListener.class); - AndroidGesturesManager initialGesturesManager = mock(AndroidGesturesManager.class); - AndroidGesturesManager internalGesturesManager = mock(AndroidGesturesManager.class); - return new LocationCameraController(mapboxMap, transform, moveGestureDetector, - onCameraTrackingChangedListener, onCameraMoveInvalidateListener, initialGesturesManager, internalGesturesManager); - } - - private LocationCameraController buildCamera(Transform transform) { - MapboxMap mapboxMap = mock(MapboxMap.class); - when(mapboxMap.getUiSettings()).thenReturn(mock(UiSettings.class)); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1000)); - when(mapboxMap.getUiSettings()).thenReturn(mock(UiSettings.class)); - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - OnCameraTrackingChangedListener onCameraTrackingChangedListener = mock(OnCameraTrackingChangedListener.class); - OnCameraMoveInvalidateListener onCameraMoveInvalidateListener = mock(OnCameraMoveInvalidateListener.class); - AndroidGesturesManager initialGesturesManager = mock(AndroidGesturesManager.class); - AndroidGesturesManager internalGesturesManager = mock(AndroidGesturesManager.class); - return new LocationCameraController(mapboxMap, transform, moveGestureDetector, - onCameraTrackingChangedListener, onCameraMoveInvalidateListener, initialGesturesManager, internalGesturesManager); - } - - private LocationCameraController buildCamera(MapboxMap mapboxMap, Transform transform) { - when(mapboxMap.getUiSettings()).thenReturn(mock(UiSettings.class)); - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - OnCameraTrackingChangedListener onCameraTrackingChangedListener = mock(OnCameraTrackingChangedListener.class); - OnCameraMoveInvalidateListener onCameraMoveInvalidateListener = mock(OnCameraMoveInvalidateListener.class); - AndroidGesturesManager initialGesturesManager = mock(AndroidGesturesManager.class); - AndroidGesturesManager internalGesturesManager = mock(AndroidGesturesManager.class); - LocationCameraController locationCameraController = new LocationCameraController( - mapboxMap, transform, moveGestureDetector, onCameraTrackingChangedListener, - onCameraMoveInvalidateListener, initialGesturesManager, internalGesturesManager); - locationCameraController.setEnabled(true); - return locationCameraController; - } - - private LocationCameraController buildCamera(MapboxMap mapboxMap, AndroidGesturesManager initialGesturesManager, - AndroidGesturesManager internalGesturesManager) { - Transform transform = mock(Transform.class); - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - OnCameraTrackingChangedListener onCameraTrackingChangedListener = mock(OnCameraTrackingChangedListener.class); - OnCameraMoveInvalidateListener onCameraMoveInvalidateListener = mock(OnCameraMoveInvalidateListener.class); - return new LocationCameraController(mapboxMap, transform, moveGestureDetector, - onCameraTrackingChangedListener, onCameraMoveInvalidateListener, initialGesturesManager, internalGesturesManager); - } - - private MapboxAnimator.AnimationsValueChangeListener getAnimationListener( - @MapboxAnimator.Type int animatorType, - Set holders) { - for (AnimatorListenerHolder holder : holders) { - @MapboxAnimator.Type int type = holder.getAnimatorType(); - if (type == animatorType) { - return holder.getListener(); - } - } - - return null; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationCameraControllerTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationCameraControllerTest.kt new file mode 100644 index 000000000..40666344e --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationCameraControllerTest.kt @@ -0,0 +1,2128 @@ +package com.mapbox.mapboxsdk.location + +import android.graphics.PointF +import android.graphics.RectF +import android.location.Location +import com.mapbox.android.gestures.AndroidGesturesManager +import com.mapbox.android.gestures.MoveGestureDetector +import com.mapbox.mapboxsdk.camera.CameraPosition +import com.mapbox.mapboxsdk.camera.CameraUpdate +import com.mapbox.mapboxsdk.camera.CameraUpdateFactory.newCameraPosition +import com.mapbox.mapboxsdk.geometry.LatLng +import com.mapbox.mapboxsdk.location.MapboxAnimator.AnimationsValueChangeListener +import com.mapbox.mapboxsdk.location.modes.CameraMode +import com.mapbox.mapboxsdk.maps.MapboxMap +import com.mapbox.mapboxsdk.maps.MapboxMap.CancelableCallback +import com.mapbox.mapboxsdk.maps.MapboxMap.OnCameraMoveListener +import com.mapbox.mapboxsdk.maps.Projection +import com.mapbox.mapboxsdk.maps.Transform +import com.mapbox.mapboxsdk.maps.UiSettings +import junit.framework.Assert +import org.junit.Test +import org.mockito.ArgumentCaptor +import org.mockito.ArgumentMatchers +import org.mockito.Mockito + +class LocationCameraControllerTest { + @Test + fun setCameraMode_mapTransitionsAreCancelled() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + val camera = buildCamera(mapboxMap) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + camera.setEnabled(true) + camera.cameraMode = CameraMode.TRACKING_GPS + Mockito.verify(mapboxMap).cancelTransitions() + } + + @Test + fun setCameraMode_gestureThresholdIsAdjusted() { + val moveGestureDetector = Mockito.mock( + MoveGestureDetector::class.java + ) + val camera = buildCamera(moveGestureDetector) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + val moveThreshold = 5f + Mockito.`when`(options.trackingInitialMoveThreshold()).thenReturn(moveThreshold) + Mockito.`when`(options.trackingGesturesManagement()).thenReturn(true) + camera.initializeOptions(options) + camera.cameraMode = CameraMode.TRACKING_GPS + Mockito.verify(moveGestureDetector).moveThreshold = moveThreshold + Mockito.verify(moveGestureDetector, Mockito.times(0)).moveThresholdRect = + ArgumentMatchers.any( + RectF::class.java + ) + } + + @Test + fun setCameraMode_gestureThresholdNotAdjustedWhenDisabled() { + val moveGestureDetector = Mockito.mock( + MoveGestureDetector::class.java + ) + val camera = buildCamera(moveGestureDetector) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + val moveThreshold = 5f + Mockito.`when`(options.trackingInitialMoveThreshold()).thenReturn(moveThreshold) + Mockito.`when`(options.trackingGesturesManagement()).thenReturn(false) + camera.initializeOptions(options) + camera.cameraMode = CameraMode.TRACKING_GPS + Mockito.verify(moveGestureDetector, Mockito.times(0)).moveThreshold = moveThreshold + Mockito.verify(moveGestureDetector, Mockito.times(0)).moveThreshold = 0f + Mockito.verify(moveGestureDetector, Mockito.times(0)).moveThresholdRect = + ArgumentMatchers.any( + RectF::class.java + ) + } + + @Test + fun setCameraMode_gestureThresholdIsResetWhenNotTracking() { + val moveGestureDetector = Mockito.mock( + MoveGestureDetector::class.java + ) + val camera = buildCamera(moveGestureDetector) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + Mockito.`when`(options.trackingGesturesManagement()).thenReturn(true) + camera.initializeOptions(options) + camera.cameraMode = CameraMode.NONE + Mockito.verify(moveGestureDetector, Mockito.times(2)).moveThreshold = + 0f // one for initialization + Mockito.verify(moveGestureDetector, Mockito.times(2)).moveThresholdRect = + null // one for initialization + } + + @Test + fun setCameraMode_notTrackingAdjustsFocalPoint() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + Mockito.`when`(mapboxMap.uiSettings).thenReturn( + Mockito.mock( + UiSettings::class.java + ) + ) + val camera = buildCamera(mapboxMap) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + camera.cameraMode = CameraMode.TRACKING_GPS + camera.cameraMode = CameraMode.NONE + Mockito.verify(mapboxMap.uiSettings).focalPoint = null + } + + @Test + fun setCameraMode_trackingChangeListenerCameraDismissedIsCalled() { + val internalTrackingChangedListener = Mockito.mock( + OnCameraTrackingChangedListener::class.java + ) + val camera = buildCamera(internalTrackingChangedListener) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + camera.cameraMode = CameraMode.TRACKING_GPS + camera.cameraMode = CameraMode.NONE + Mockito.verify(internalTrackingChangedListener).onCameraTrackingDismissed() + } + + @Test + fun setCameraMode_internalCameraTrackingChangeListenerIsCalled() { + val internalTrackingChangedListener = Mockito.mock( + OnCameraTrackingChangedListener::class.java + ) + val camera = buildCamera(internalTrackingChangedListener) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + val cameraMode = CameraMode.NONE + camera.cameraMode = cameraMode + Mockito.verify(internalTrackingChangedListener).onCameraTrackingChanged(cameraMode) + } + + @Test + fun setCameraMode_doNotNotifyAboutDuplicates_NONE() { + val internalTrackingChangedListener = Mockito.mock( + OnCameraTrackingChangedListener::class.java + ) + val camera = buildCamera(internalTrackingChangedListener) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + val cameraMode = CameraMode.NONE + camera.cameraMode = cameraMode + camera.cameraMode = cameraMode + Mockito.verify(internalTrackingChangedListener, Mockito.times(1)) + .onCameraTrackingChanged(cameraMode) + } + + @Test + fun setCameraMode_doNotNotifyAboutDuplicates_TRACKING_GPS() { + val internalTrackingChangedListener = Mockito.mock( + OnCameraTrackingChangedListener::class.java + ) + val camera = buildCamera(internalTrackingChangedListener) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + val cameraMode = CameraMode.TRACKING_GPS + camera.cameraMode = cameraMode + camera.cameraMode = cameraMode + Mockito.verify(internalTrackingChangedListener, Mockito.times(1)) + .onCameraTrackingChanged(cameraMode) + } + + @Test + fun setCameraMode_cancelTransitionsWhenSet() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + Mockito.`when`(mapboxMap.uiSettings).thenReturn( + Mockito.mock( + UiSettings::class.java + ) + ) + Mockito.`when`(mapboxMap.projection).thenReturn( + Mockito.mock( + Projection::class.java + ) + ) + val camera = buildCamera(mapboxMap) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + camera.cameraMode = CameraMode.NONE_COMPASS + Mockito.verify(mapboxMap, Mockito.times(1)).cancelTransitions() + camera.cameraMode = CameraMode.NONE_GPS + Mockito.verify(mapboxMap, Mockito.times(2)).cancelTransitions() + camera.cameraMode = CameraMode.TRACKING + Mockito.verify(mapboxMap, Mockito.times(3)).cancelTransitions() + camera.cameraMode = CameraMode.TRACKING_COMPASS + Mockito.verify(mapboxMap, Mockito.times(4)).cancelTransitions() + camera.cameraMode = CameraMode.TRACKING_GPS + Mockito.verify(mapboxMap, Mockito.times(5)).cancelTransitions() + camera.cameraMode = CameraMode.TRACKING_GPS_NORTH + Mockito.verify(mapboxMap, Mockito.times(6)).cancelTransitions() + } + + @Test + fun setCameraMode_dontCancelTransitionsWhenNoneSet() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + Mockito.`when`(mapboxMap.uiSettings).thenReturn( + Mockito.mock( + UiSettings::class.java + ) + ) + Mockito.`when`(mapboxMap.projection).thenReturn( + Mockito.mock( + Projection::class.java + ) + ) + val camera = buildCamera(mapboxMap) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + camera.cameraMode = CameraMode.NONE + Mockito.verify(mapboxMap, Mockito.never()).cancelTransitions() + } + + @Test + fun onNewLatLngValue_cameraModeTrackingUpdatesLatLng() { + val transform = Mockito.mock( + Transform::class.java + ) + val camera = buildCamera(transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + camera.cameraMode = CameraMode.TRACKING + val latLng = Mockito.mock(LatLng::class.java) + getAnimationListener( + MapboxAnimator.ANIMATOR_CAMERA_LATLNG, + camera.animationListeners + )!!.onNewAnimationValue(latLng) + Mockito.verify(transform).moveCamera( + ArgumentMatchers.any( + MapboxMap::class.java + ), + ArgumentMatchers.any(CameraUpdate::class.java), + ArgumentMatchers.nullable(CancelableCallback::class.java) + ) + } + + @Test + fun onNewLatLngValue_cameraModeTrackingGpsNorthUpdatesLatLng() { + val transform = Mockito.mock( + Transform::class.java + ) + val camera = buildCamera(transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + camera.cameraMode = CameraMode.TRACKING_GPS_NORTH + val latLng = Mockito.mock(LatLng::class.java) + getAnimationListener( + MapboxAnimator.ANIMATOR_CAMERA_LATLNG, + camera.animationListeners + )!!.onNewAnimationValue(latLng) + Mockito.verify(transform).moveCamera( + ArgumentMatchers.any( + MapboxMap::class.java + ), + ArgumentMatchers.any(CameraUpdate::class.java), + ArgumentMatchers.nullable(CancelableCallback::class.java) + ) + } + + @Test + fun onNewLatLngValue_cameraModeTrackingGpsUpdatesLatLng() { + val transform = Mockito.mock( + Transform::class.java + ) + val camera = buildCamera(transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + camera.cameraMode = CameraMode.TRACKING_GPS + val latLng = Mockito.mock(LatLng::class.java) + getAnimationListener( + MapboxAnimator.ANIMATOR_CAMERA_LATLNG, + camera.animationListeners + )!!.onNewAnimationValue(latLng) + Mockito.verify(transform).moveCamera( + ArgumentMatchers.any( + MapboxMap::class.java + ), + ArgumentMatchers.any(CameraUpdate::class.java), + ArgumentMatchers.nullable(CancelableCallback::class.java) + ) + } + + @Test + fun onNewLatLngValue_cameraModeTrackingCompassUpdatesLatLng() { + val transform = Mockito.mock( + Transform::class.java + ) + val camera = buildCamera(transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + camera.cameraMode = CameraMode.TRACKING_COMPASS + val latLng = Mockito.mock(LatLng::class.java) + getAnimationListener( + MapboxAnimator.ANIMATOR_CAMERA_LATLNG, + camera.animationListeners + )!!.onNewAnimationValue(latLng) + Mockito.verify(transform).moveCamera( + ArgumentMatchers.any( + MapboxMap::class.java + ), + ArgumentMatchers.any(CameraUpdate::class.java), + ArgumentMatchers.nullable(CancelableCallback::class.java) + ) + } + + @Test + fun onNewLatLngValue_cameraModeNoneIgnored() { + val transform = Mockito.mock( + Transform::class.java + ) + val camera = buildCamera(transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + camera.cameraMode = CameraMode.NONE + Assert.assertNull( + getAnimationListener( + MapboxAnimator.ANIMATOR_CAMERA_LATLNG, + camera.animationListeners + ) + ) + Mockito.verify(transform, Mockito.times(0)).moveCamera( + ArgumentMatchers.any( + MapboxMap::class.java + ), + ArgumentMatchers.any(CameraUpdate::class.java), + ArgumentMatchers.nullable(CancelableCallback::class.java) + ) + } + + @Test + fun onNewLatLngValue_focalPointIsAdjusted() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + val transform = Mockito.mock( + Transform::class.java + ) + val listener = arrayOf(null) + Mockito.doAnswer { invocation -> + listener[0] = invocation.arguments[0] as OnCameraMoveListener + null + }.`when`(mapboxMap).addOnCameraMoveListener( + ArgumentMatchers.any( + OnCameraMoveListener::class.java + ) + ) + val projection = Mockito.mock( + Projection::class.java + ) + val pointF = Mockito.mock(PointF::class.java) + Mockito.`when`( + projection.toScreenLocation( + ArgumentMatchers.any( + LatLng::class.java + ) + ) + ).thenReturn(pointF) + Mockito.`when`(mapboxMap.projection).thenReturn(projection) + val camera = buildCamera(mapboxMap, transform) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + Mockito.`when`(options.trackingGesturesManagement()).thenReturn(true) + camera.initializeOptions(options) + camera.cameraMode = CameraMode.TRACKING + val latLng = Mockito.mock(LatLng::class.java) + getAnimationListener( + MapboxAnimator.ANIMATOR_CAMERA_LATLNG, + camera.animationListeners + )!!.onNewAnimationValue(latLng) + Mockito.verify(transform).moveCamera( + ArgumentMatchers.any( + MapboxMap::class.java + ), + ArgumentMatchers.any(CameraUpdate::class.java), + ArgumentMatchers.nullable(CancelableCallback::class.java) + ) + val uiSettings = Mockito.mock(UiSettings::class.java) + Mockito.`when`(mapboxMap.uiSettings).thenReturn(uiSettings) + listener[0]!!.onCameraMove() + Mockito.verify(uiSettings).focalPoint = pointF + } + + @Test + fun onNewGpsBearingValue_cameraModeTrackingGpsUpdatesBearing() { + val transform = Mockito.mock( + Transform::class.java + ) + val camera = buildCamera(transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + camera.cameraMode = CameraMode.TRACKING_GPS + val gpsBearing = 5f + getAnimationListener( + MapboxAnimator.ANIMATOR_CAMERA_GPS_BEARING, + camera.animationListeners + )!!.onNewAnimationValue(gpsBearing) + Mockito.verify(transform).moveCamera( + ArgumentMatchers.any( + MapboxMap::class.java + ), + ArgumentMatchers.any(CameraUpdate::class.java), + ArgumentMatchers.nullable(CancelableCallback::class.java) + ) + } + + @Test + fun onNewGpsBearingValue_cameraModeNoneGpsUpdatesBearing() { + val transform = Mockito.mock( + Transform::class.java + ) + val camera = buildCamera(transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + camera.cameraMode = CameraMode.NONE_GPS + val gpsBearing = 5f + getAnimationListener( + MapboxAnimator.ANIMATOR_CAMERA_GPS_BEARING, + camera.animationListeners + )!!.onNewAnimationValue(gpsBearing) + Mockito.verify(transform).moveCamera( + ArgumentMatchers.any( + MapboxMap::class.java + ), + ArgumentMatchers.any(CameraUpdate::class.java), + ArgumentMatchers.nullable(CancelableCallback::class.java) + ) + } + + @Test + fun onNewGpsBearingValue_cameraModeTrackingNorthUpdatesBearing() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + val transform = Mockito.mock( + Transform::class.java + ) + val camera = buildCamera(mapboxMap, transform) + val cameraPosition = CameraPosition.Builder().bearing(7.0).build() + Mockito.`when`(mapboxMap.cameraPosition).thenReturn(cameraPosition) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + camera.cameraMode = CameraMode.TRACKING_GPS_NORTH + val gpsBearing = 5f + getAnimationListener( + MapboxAnimator.ANIMATOR_CAMERA_GPS_BEARING, + camera.animationListeners + )!!.onNewAnimationValue(gpsBearing) + Mockito.verify(transform).moveCamera( + ArgumentMatchers.eq(mapboxMap), + ArgumentMatchers.any( + CameraUpdate::class.java + ), + ArgumentMatchers.nullable(CancelableCallback::class.java) + ) + } + + @Test + fun onNewGpsBearingValue_cameraModeTrackingNorthBearingZeroIgnored() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + val transform = Mockito.mock( + Transform::class.java + ) + val camera = buildCamera(mapboxMap, transform) + val cameraPosition = CameraPosition.Builder().bearing(0.0).build() + Mockito.`when`(mapboxMap.cameraPosition).thenReturn(cameraPosition) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + camera.cameraMode = CameraMode.TRACKING_GPS_NORTH + val gpsBearing = 5f + getAnimationListener( + MapboxAnimator.ANIMATOR_CAMERA_GPS_BEARING, + camera.animationListeners + )!!.onNewAnimationValue(gpsBearing) + Mockito.verify(transform, Mockito.times(0)).moveCamera( + ArgumentMatchers.eq(mapboxMap), + ArgumentMatchers.any( + CameraUpdate::class.java + ), + ArgumentMatchers.nullable(CancelableCallback::class.java) + ) + } + + @Test + fun onNewGpsBearingValue_cameraModeNoneIgnored() { + val transform = Mockito.mock( + Transform::class.java + ) + val camera = buildCamera(transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + camera.cameraMode = CameraMode.NONE + Assert.assertNull( + getAnimationListener( + MapboxAnimator.ANIMATOR_CAMERA_GPS_BEARING, + camera.animationListeners + ) + ) + Mockito.verify(transform, Mockito.times(0)).moveCamera( + ArgumentMatchers.any( + MapboxMap::class.java + ), + ArgumentMatchers.any(CameraUpdate::class.java), + ArgumentMatchers.nullable(CancelableCallback::class.java) + ) + } + + @Test + fun onNewCompassBearingValue_cameraModeTrackingCompassUpdatesBearing() { + val transform = Mockito.mock( + Transform::class.java + ) + val camera = buildCamera(transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + camera.cameraMode = CameraMode.TRACKING_COMPASS + val compassBearing = 5f + getAnimationListener( + MapboxAnimator.ANIMATOR_CAMERA_COMPASS_BEARING, + camera.animationListeners + ) + ?.onNewAnimationValue(compassBearing) + Mockito.verify(transform).moveCamera( + ArgumentMatchers.any( + MapboxMap::class.java + ), + ArgumentMatchers.any(CameraUpdate::class.java), + ArgumentMatchers.nullable(CancelableCallback::class.java) + ) + } + + @Test + fun onNewCompassBearingValue_cameraModeNoneCompassUpdatesBearing() { + val transform = Mockito.mock( + Transform::class.java + ) + val camera = buildCamera(transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + camera.cameraMode = CameraMode.NONE_COMPASS + val compassBearing = 5f + getAnimationListener( + MapboxAnimator.ANIMATOR_CAMERA_COMPASS_BEARING, + camera.animationListeners + ) + ?.onNewAnimationValue(compassBearing) + Mockito.verify(transform).moveCamera( + ArgumentMatchers.any( + MapboxMap::class.java + ), + ArgumentMatchers.any(CameraUpdate::class.java), + ArgumentMatchers.nullable(CancelableCallback::class.java) + ) + } + + @Test + fun onNewCompassBearingValue_cameraModeNoneIgnored() { + val transform = Mockito.mock( + Transform::class.java + ) + val camera = buildCamera(transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + camera.cameraMode = CameraMode.NONE + Assert.assertNull( + getAnimationListener( + MapboxAnimator.ANIMATOR_CAMERA_COMPASS_BEARING, + camera.animationListeners + ) + ) + Mockito.verify(transform, Mockito.times(0)).moveCamera( + ArgumentMatchers.any( + MapboxMap::class.java + ), + ArgumentMatchers.any(CameraUpdate::class.java), + ArgumentMatchers.nullable(CancelableCallback::class.java) + ) + } + + @Test + fun onNewZoomValue_cameraIsUpdated() { + val transform = Mockito.mock( + Transform::class.java + ) + val camera = buildCamera(transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + camera.cameraMode = CameraMode.TRACKING + val zoom = 5f + getAnimationListener( + MapboxAnimator.ANIMATOR_ZOOM, + camera.animationListeners + )!!.onNewAnimationValue(zoom) + Mockito.verify(transform).moveCamera( + ArgumentMatchers.any( + MapboxMap::class.java + ), + ArgumentMatchers.any(CameraUpdate::class.java), + ArgumentMatchers.nullable(CancelableCallback::class.java) + ) + } + + @Test + fun onNeTiltValue_cameraIsUpdated() { + val transform = Mockito.mock( + Transform::class.java + ) + val camera = buildCamera(transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + camera.cameraMode = CameraMode.TRACKING + val tilt = 5f + getAnimationListener( + MapboxAnimator.ANIMATOR_TILT, + camera.animationListeners + )!!.onNewAnimationValue(tilt) + Mockito.verify(transform).moveCamera( + ArgumentMatchers.any( + MapboxMap::class.java + ), + ArgumentMatchers.any(CameraUpdate::class.java), + ArgumentMatchers.nullable(CancelableCallback::class.java) + ) + } + + @Test + fun gesturesManagement_enabled() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + val initialGesturesManager = Mockito.mock( + AndroidGesturesManager::class.java + ) + val internalGesturesManager = Mockito.mock( + AndroidGesturesManager::class.java + ) + Mockito.`when`(mapboxMap.gesturesManager).thenReturn(initialGesturesManager) + val camera = buildCamera(mapboxMap, initialGesturesManager, internalGesturesManager) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + Mockito.`when`(options.trackingGesturesManagement()).thenReturn(true) + camera.initializeOptions(options) + Mockito.verify(mapboxMap).setGesturesManager(internalGesturesManager, true, true) + } + + @Test + fun gesturesManagement_disabled() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + val initialGesturesManager = Mockito.mock( + AndroidGesturesManager::class.java + ) + val internalGesturesManager = Mockito.mock( + AndroidGesturesManager::class.java + ) + Mockito.`when`(mapboxMap.gesturesManager).thenReturn(internalGesturesManager) + val camera = buildCamera(mapboxMap, initialGesturesManager, internalGesturesManager) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + Mockito.`when`(options.trackingGesturesManagement()).thenReturn(false) + camera.initializeOptions(options) + Mockito.verify(mapboxMap).setGesturesManager(initialGesturesManager, true, true) + } + + @Test + fun gesturesManagement_optionNotChangedInitial() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + val initialGesturesManager = Mockito.mock( + AndroidGesturesManager::class.java + ) + val internalGesturesManager = Mockito.mock( + AndroidGesturesManager::class.java + ) + Mockito.`when`(mapboxMap.gesturesManager).thenReturn(initialGesturesManager) + val camera = buildCamera(mapboxMap, initialGesturesManager, internalGesturesManager) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + Mockito.`when`(options.trackingGesturesManagement()).thenReturn(false) + camera.initializeOptions(options) + Mockito.verify(mapboxMap, Mockito.times(0)) + .setGesturesManager(initialGesturesManager, true, true) + } + + @Test + fun gesturesManagement_optionNotChangedInternal() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + val initialGesturesManager = Mockito.mock( + AndroidGesturesManager::class.java + ) + val internalGesturesManager = Mockito.mock( + AndroidGesturesManager::class.java + ) + Mockito.`when`(mapboxMap.gesturesManager).thenReturn(internalGesturesManager) + val camera = buildCamera(mapboxMap, initialGesturesManager, internalGesturesManager) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + Mockito.`when`(options.trackingGesturesManagement()).thenReturn(true) + camera.initializeOptions(options) + Mockito.verify(mapboxMap, Mockito.times(0)) + .setGesturesManager(internalGesturesManager, true, true) + } + + @Test + fun gesturesManagement_moveGesture_notTracking() { + val moveGestureDetector = Mockito.mock( + MoveGestureDetector::class.java + ) + Mockito.`when`(moveGestureDetector.pointersCount).thenReturn(1) + val camera = buildCamera(moveGestureDetector) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + Mockito.`when`(options.trackingGesturesManagement()).thenReturn(true) + val initial = 100f + val multiFinger = 200f + val multiFingerArea = Mockito.mock(RectF::class.java) + Mockito.`when`(options.trackingInitialMoveThreshold()).thenReturn(initial) + Mockito.`when`(options.trackingMultiFingerMoveThreshold()).thenReturn(multiFinger) + Mockito.`when`(options.trackingMultiFingerProtectedMoveArea()).thenReturn(multiFingerArea) + camera.initializeOptions(options) + camera.onMoveListener.onMoveBegin(moveGestureDetector) + Mockito.verify(moveGestureDetector, Mockito.times(2)).moveThreshold = 0f + Mockito.verify(moveGestureDetector, Mockito.times(2)).moveThresholdRect = null + } + + @Test + fun gesturesManagement_moveGesture_singlePointer_tracking() { + val moveGestureDetector = Mockito.mock( + MoveGestureDetector::class.java + ) + Mockito.`when`(moveGestureDetector.pointersCount).thenReturn(1) + val camera = buildCamera(moveGestureDetector) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + Mockito.`when`(options.trackingGesturesManagement()).thenReturn(true) + val initial = 100f + Mockito.`when`(options.trackingInitialMoveThreshold()).thenReturn(initial) + camera.initializeOptions(options) + camera.cameraMode = CameraMode.TRACKING + Mockito.`when`(moveGestureDetector.moveThreshold).thenReturn(initial) + camera.onMoveListener.onMoveBegin(moveGestureDetector) + Mockito.verify(moveGestureDetector, Mockito.atMost(1)).moveThreshold = initial + Mockito.verify(moveGestureDetector, Mockito.times(0)).moveThresholdRect = + ArgumentMatchers.any( + RectF::class.java + ) + } + + @Test + fun gesturesManagement_moveGesture_singlePointer_tracking_duplicateCall() { + val moveGestureDetector = Mockito.mock( + MoveGestureDetector::class.java + ) + Mockito.`when`(moveGestureDetector.pointersCount).thenReturn(1) + val camera = buildCamera(moveGestureDetector) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + Mockito.`when`(options.trackingGesturesManagement()).thenReturn(true) + val initial = 100f + Mockito.`when`(options.trackingInitialMoveThreshold()).thenReturn(initial) + camera.initializeOptions(options) + camera.cameraMode = CameraMode.TRACKING + Mockito.`when`(moveGestureDetector.moveThreshold).thenReturn(initial) + camera.onMoveListener.onMoveBegin(moveGestureDetector) + Mockito.verify(moveGestureDetector, Mockito.atMost(1)).moveThreshold = initial + Mockito.verify(moveGestureDetector, Mockito.times(0)).moveThresholdRect = + ArgumentMatchers.any( + RectF::class.java + ) + } + + @Test + fun gesturesManagement_moveGesture_singlePointer_tracking_thresholdMet() { + val moveGestureDetector = Mockito.mock( + MoveGestureDetector::class.java + ) + Mockito.`when`(moveGestureDetector.pointersCount).thenReturn(1) + val camera = buildCamera(moveGestureDetector) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + Mockito.`when`(options.trackingGesturesManagement()).thenReturn(true) + val initial = 100f + Mockito.`when`(options.trackingInitialMoveThreshold()).thenReturn(initial) + camera.initializeOptions(options) + + // verify the number of detector interruptions + camera.cameraMode = CameraMode.TRACKING + camera.onMoveListener.onMoveBegin(moveGestureDetector) + Mockito.`when`(moveGestureDetector.moveThreshold).thenReturn(initial) + camera.onMoveListener.onMove(moveGestureDetector) + Mockito.verify(moveGestureDetector, Mockito.times(1)).interrupt() + camera.onMoveListener.onMoveEnd(moveGestureDetector) + camera.onMoveListener.onMoveBegin(moveGestureDetector) + camera.onMoveListener.onMove(moveGestureDetector) + Mockito.verify(moveGestureDetector, Mockito.times(2)).interrupt() + camera.onMoveListener.onMoveEnd(moveGestureDetector) + camera.onMoveListener.onMoveBegin(moveGestureDetector) + camera.onMoveListener.onMove(moveGestureDetector) + camera.onMoveListener.onMoveEnd(moveGestureDetector) + Mockito.verify(moveGestureDetector, Mockito.times(2)).interrupt() + + // verify that threshold are reset + val moveThresholdCaptor = ArgumentCaptor.forClass( + Float::class.java + ) + Mockito.verify(moveGestureDetector, Mockito.atLeastOnce()).moveThreshold = + moveThresholdCaptor.capture() + org.junit.Assert.assertEquals(java.lang.Float.valueOf(0f), moveThresholdCaptor.value) + } + + @Test + fun gesturesManagement_moveGesture_multiPointer_tracking() { + val moveGestureDetector = Mockito.mock( + MoveGestureDetector::class.java + ) + Mockito.`when`(moveGestureDetector.pointersCount).thenReturn(2) + val camera = buildCamera(moveGestureDetector) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + Mockito.`when`(options.trackingGesturesManagement()).thenReturn(true) + val initial = 100f + val multiFinger = 200f + val multiFingerArea = Mockito.mock(RectF::class.java) + Mockito.`when`(options.trackingInitialMoveThreshold()).thenReturn(initial) + Mockito.`when`(options.trackingMultiFingerMoveThreshold()).thenReturn(multiFinger) + Mockito.`when`(options.trackingMultiFingerProtectedMoveArea()).thenReturn(multiFingerArea) + camera.initializeOptions(options) + camera.cameraMode = CameraMode.TRACKING + camera.onMoveListener.onMoveBegin(moveGestureDetector) + Mockito.verify(moveGestureDetector, Mockito.atMost(1)).moveThreshold = multiFinger + Mockito.verify(moveGestureDetector, Mockito.atMost(1)).moveThresholdRect = multiFingerArea + } + + @Test + fun gesturesManagement_moveGesture_multiPointer_tracking_duplicateCall() { + val moveGestureDetector = Mockito.mock( + MoveGestureDetector::class.java + ) + Mockito.`when`(moveGestureDetector.pointersCount).thenReturn(2) + val camera = buildCamera(moveGestureDetector) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + Mockito.`when`(options.trackingGesturesManagement()).thenReturn(true) + val initial = 100f + val multiFinger = 200f + val multiFingerArea = Mockito.mock(RectF::class.java) + Mockito.`when`(options.trackingInitialMoveThreshold()).thenReturn(initial) + Mockito.`when`(options.trackingMultiFingerMoveThreshold()).thenReturn(multiFinger) + Mockito.`when`(options.trackingMultiFingerProtectedMoveArea()).thenReturn(multiFingerArea) + camera.initializeOptions(options) + camera.cameraMode = CameraMode.TRACKING + camera.onMoveListener.onMoveBegin(moveGestureDetector) + Mockito.`when`(moveGestureDetector.moveThreshold).thenReturn(multiFinger) + Mockito.`when`(moveGestureDetector.moveThresholdRect).thenReturn(multiFingerArea) + camera.onMoveListener.onMoveBegin(moveGestureDetector) + Mockito.verify(moveGestureDetector, Mockito.atMost(1)).moveThreshold = multiFinger + Mockito.verify(moveGestureDetector, Mockito.atMost(1)).moveThresholdRect = multiFingerArea + } + + @Test + fun gesturesManagement_moveGesture_multiPointer_tracking_thresholdMet() { + val moveGestureDetector = Mockito.mock( + MoveGestureDetector::class.java + ) + Mockito.`when`(moveGestureDetector.pointersCount).thenReturn(2) + val camera = buildCamera(moveGestureDetector) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + Mockito.`when`(options.trackingGesturesManagement()).thenReturn(true) + val initial = 100f + val multiFinger = 200f + val multiFingerArea = Mockito.mock(RectF::class.java) + Mockito.`when`(options.trackingInitialMoveThreshold()).thenReturn(initial) + Mockito.`when`(options.trackingMultiFingerMoveThreshold()).thenReturn(multiFinger) + Mockito.`when`(options.trackingMultiFingerProtectedMoveArea()).thenReturn(multiFingerArea) + camera.initializeOptions(options) + + // verify the number of detector interruptions + camera.cameraMode = CameraMode.TRACKING + camera.onMoveListener.onMoveBegin(moveGestureDetector) + Mockito.`when`(moveGestureDetector.moveThreshold).thenReturn(initial) + Mockito.`when`(moveGestureDetector.moveThreshold).thenReturn(multiFinger) + Mockito.`when`(moveGestureDetector.moveThresholdRect).thenReturn(multiFingerArea) + camera.onMoveListener.onMove(moveGestureDetector) + Mockito.verify(moveGestureDetector, Mockito.times(1)).interrupt() + camera.onMoveListener.onMoveEnd(moveGestureDetector) + camera.onMoveListener.onMoveBegin(moveGestureDetector) + camera.onMoveListener.onMove(moveGestureDetector) + Mockito.verify(moveGestureDetector, Mockito.times(2)).interrupt() + camera.onMoveListener.onMoveEnd(moveGestureDetector) + camera.onMoveListener.onMoveBegin(moveGestureDetector) + camera.onMoveListener.onMove(moveGestureDetector) + camera.onMoveListener.onMoveEnd(moveGestureDetector) + Mockito.verify(moveGestureDetector, Mockito.times(2)).interrupt() + + // verify that threshold are reset + val moveThresholdCaptor = ArgumentCaptor.forClass( + Float::class.java + ) + Mockito.verify(moveGestureDetector, Mockito.atLeastOnce()).moveThreshold = + moveThresholdCaptor.capture() + org.junit.Assert.assertEquals(java.lang.Float.valueOf(0f), moveThresholdCaptor.value) + val areaCaptor = ArgumentCaptor.forClass( + RectF::class.java + ) + Mockito.verify(moveGestureDetector, Mockito.atLeastOnce()).moveThresholdRect = + areaCaptor.capture() + org.junit.Assert.assertNull(areaCaptor.value) + } + + @Test + fun onMove_notCancellingTransitionWhileNone() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + Mockito.`when`(mapboxMap.uiSettings).thenReturn( + Mockito.mock( + UiSettings::class.java + ) + ) + val moveGestureDetector = Mockito.mock( + MoveGestureDetector::class.java + ) + val camera = buildCamera(mapboxMap) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + camera.cameraMode = CameraMode.NONE + camera.onMoveListener.onMove(moveGestureDetector) + Mockito.verify(mapboxMap, Mockito.times(0)).cancelTransitions() + Mockito.verify(moveGestureDetector, Mockito.times(0)).interrupt() + + // testing subsequent calls + camera.onMoveListener.onMove(moveGestureDetector) + Mockito.verify(mapboxMap, Mockito.times(0)).cancelTransitions() + Mockito.verify(moveGestureDetector, Mockito.times(0)).interrupt() + } + + @Test + fun onMove_cancellingTransitionWhileGps() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + Mockito.`when`(mapboxMap.uiSettings).thenReturn( + Mockito.mock( + UiSettings::class.java + ) + ) + val moveGestureDetector = Mockito.mock( + MoveGestureDetector::class.java + ) + val camera = buildCamera(mapboxMap) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + camera.cameraMode = CameraMode.TRACKING + camera.onMoveListener.onMove(moveGestureDetector) + Mockito.verify(mapboxMap, Mockito.times(1)).cancelTransitions() + Mockito.verify(moveGestureDetector, Mockito.times(1)).interrupt() + + // testing subsequent calls + camera.onMoveListener.onMove(moveGestureDetector) + Mockito.verify(mapboxMap, Mockito.times(1)).cancelTransitions() + Mockito.verify(moveGestureDetector, Mockito.times(1)).interrupt() + } + + @Test + fun onMove_cancellingTransitionWhileBearing() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + val moveGestureDetector = Mockito.mock( + MoveGestureDetector::class.java + ) + val camera = buildCamera(mapboxMap) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + camera.cameraMode = CameraMode.NONE_COMPASS + camera.onMoveListener.onMove(moveGestureDetector) + Mockito.verify(mapboxMap, Mockito.times(1)).cancelTransitions() + Mockito.verify(moveGestureDetector, Mockito.times(1)).interrupt() + + // testing subsequent calls + camera.onMoveListener.onMove(moveGestureDetector) + Mockito.verify(mapboxMap, Mockito.times(1)).cancelTransitions() + Mockito.verify(moveGestureDetector, Mockito.times(1)).interrupt() + } + + @Test + fun transition_locationIsNull() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + val transform = Mockito.mock( + Transform::class.java + ) + val camera = buildCamera(mapboxMap, transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + val listener = Mockito.mock( + OnLocationCameraTransitionListener::class.java + ) + camera.setCameraMode( + CameraMode.TRACKING, + null, + LocationComponentConstants.TRANSITION_ANIMATION_DURATION_MS, + null, + null, + null, + listener + ) + Assert.assertEquals(CameraMode.TRACKING, camera.cameraMode) + Mockito.verify(listener).onLocationCameraTransitionFinished(CameraMode.TRACKING) + Mockito.verify(transform, Mockito.times(0)) + .animateCamera( + ArgumentMatchers.eq(mapboxMap), + ArgumentMatchers.any( + CameraUpdate::class.java + ), + ArgumentMatchers.any(Int::class.java), + ArgumentMatchers.any(CancelableCallback::class.java) + ) + } + + @Test + fun transition_notTracking() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + val transform = Mockito.mock( + Transform::class.java + ) + val camera = buildCamera(mapboxMap, transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + val listener = Mockito.mock( + OnLocationCameraTransitionListener::class.java + ) + val location = Mockito.mock( + Location::class.java + ) + camera.setCameraMode( + CameraMode.NONE, + location, + LocationComponentConstants.TRANSITION_ANIMATION_DURATION_MS, + null, + null, + null, + listener + ) + Mockito.verify(listener, Mockito.times(1)) + .onLocationCameraTransitionFinished(CameraMode.NONE) + Mockito.verify(transform, Mockito.times(0)) + .animateCamera( + ArgumentMatchers.eq(mapboxMap), + ArgumentMatchers.any( + CameraUpdate::class.java + ), + ArgumentMatchers.any(Int::class.java), + ArgumentMatchers.any(CancelableCallback::class.java) + ) + } + + @Test + fun transition_trackingChanged() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + val transform = Mockito.mock( + Transform::class.java + ) + Mockito.`when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) + val projection = Mockito.mock( + Projection::class.java + ) + Mockito.`when`(mapboxMap.projection).thenReturn(projection) + Mockito.`when`( + projection.getMetersPerPixelAtLatitude( + ArgumentMatchers.any( + Double::class.java + ) + ) + ).thenReturn(java.lang.Double.valueOf(1000.0)) + val camera = buildCamera(mapboxMap, transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + val listener = Mockito.mock( + OnLocationCameraTransitionListener::class.java + ) + val location = Mockito.mock( + Location::class.java + ) + Mockito.doAnswer { + listener.onLocationCameraTransitionFinished(CameraMode.TRACKING) + null + }.`when`(transform).animateCamera( + ArgumentMatchers.eq(mapboxMap), + ArgumentMatchers.any( + CameraUpdate::class.java + ), + ArgumentMatchers.any(Int::class.java), + ArgumentMatchers.any(CancelableCallback::class.java) + ) + camera.setCameraMode( + CameraMode.TRACKING, + location, + LocationComponentConstants.TRANSITION_ANIMATION_DURATION_MS, + null, + null, + null, + listener + ) + Mockito.verify(listener).onLocationCameraTransitionFinished(CameraMode.TRACKING) + Mockito.verify(transform) + .animateCamera( + ArgumentMatchers.eq(mapboxMap), + ArgumentMatchers.any( + CameraUpdate::class.java + ), + ArgumentMatchers.any(Int::class.java), + ArgumentMatchers.any(CancelableCallback::class.java) + ) + } + + @Test + fun transition_trackingNotChanged() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + val transform = Mockito.mock( + Transform::class.java + ) + Mockito.`when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) + val projection = Mockito.mock( + Projection::class.java + ) + Mockito.`when`(mapboxMap.projection).thenReturn(projection) + Mockito.`when`( + projection.getMetersPerPixelAtLatitude( + ArgumentMatchers.any( + Double::class.java + ) + ) + ).thenReturn(java.lang.Double.valueOf(1000.0)) + val camera = buildCamera(mapboxMap, transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + val listener = Mockito.mock( + OnLocationCameraTransitionListener::class.java + ) + val location = Mockito.mock( + Location::class.java + ) + camera.setCameraMode( + CameraMode.TRACKING, + location, + LocationComponentConstants.TRANSITION_ANIMATION_DURATION_MS, + null, + null, + null, + listener + ) + Mockito.doAnswer { + listener.onLocationCameraTransitionFinished(CameraMode.TRACKING_GPS_NORTH) + null + }.`when`(transform).animateCamera( + ArgumentMatchers.eq(mapboxMap), + ArgumentMatchers.any( + CameraUpdate::class.java + ), + ArgumentMatchers.any(Int::class.java), + ArgumentMatchers.any(CancelableCallback::class.java) + ) + camera.setCameraMode( + CameraMode.TRACKING_GPS_NORTH, + location, + LocationComponentConstants.TRANSITION_ANIMATION_DURATION_MS, + null, + null, + null, + listener + ) + Mockito.verify(listener, Mockito.times(1)) + .onLocationCameraTransitionFinished(CameraMode.TRACKING_GPS_NORTH) + Mockito.verify(transform, Mockito.times(1)) + .animateCamera( + ArgumentMatchers.eq(mapboxMap), + ArgumentMatchers.any( + CameraUpdate::class.java + ), + ArgumentMatchers.any(Int::class.java), + ArgumentMatchers.any(CancelableCallback::class.java) + ) + } + + @Test + fun transition_duplicateMode() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + val transform = Mockito.mock( + Transform::class.java + ) + Mockito.`when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) + val projection = Mockito.mock( + Projection::class.java + ) + Mockito.`when`(mapboxMap.projection).thenReturn(projection) + Mockito.`when`( + projection.getMetersPerPixelAtLatitude( + ArgumentMatchers.any( + Double::class.java + ) + ) + ).thenReturn(java.lang.Double.valueOf(1000.0)) + val camera = buildCamera(mapboxMap, transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + val listener = Mockito.mock( + OnLocationCameraTransitionListener::class.java + ) + val location = Mockito.mock( + Location::class.java + ) + camera.setCameraMode( + CameraMode.TRACKING, + location, + LocationComponentConstants.TRANSITION_ANIMATION_DURATION_MS, + null, + null, + null, + listener + ) + Mockito.doAnswer { + listener.onLocationCameraTransitionFinished(CameraMode.TRACKING) + null + }.`when`(transform).animateCamera( + ArgumentMatchers.eq(mapboxMap), + ArgumentMatchers.any( + CameraUpdate::class.java + ), + ArgumentMatchers.any(Int::class.java), + ArgumentMatchers.any(CancelableCallback::class.java) + ) + camera.setCameraMode( + CameraMode.TRACKING, + location, + LocationComponentConstants.TRANSITION_ANIMATION_DURATION_MS, + null, + null, + null, + listener + ) + Mockito.verify(listener, Mockito.times(1)) + .onLocationCameraTransitionFinished(CameraMode.TRACKING) + Mockito.verify(transform, Mockito.times(1)) + .animateCamera( + ArgumentMatchers.eq(mapboxMap), + ArgumentMatchers.any( + CameraUpdate::class.java + ), + ArgumentMatchers.any(Int::class.java), + ArgumentMatchers.any(CancelableCallback::class.java) + ) + } + + @Test + fun transition_canceled() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + val transform = Mockito.mock( + Transform::class.java + ) + Mockito.`when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) + val projection = Mockito.mock( + Projection::class.java + ) + Mockito.`when`(mapboxMap.projection).thenReturn(projection) + Mockito.`when`( + projection.getMetersPerPixelAtLatitude( + ArgumentMatchers.any( + Double::class.java + ) + ) + ).thenReturn(java.lang.Double.valueOf(1000.0)) + val camera = buildCamera(mapboxMap, transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + val listener = Mockito.mock( + OnLocationCameraTransitionListener::class.java + ) + val location = Mockito.mock( + Location::class.java + ) + Mockito.doAnswer { + listener.onLocationCameraTransitionCanceled(CameraMode.TRACKING) + null + }.`when`(transform).animateCamera( + ArgumentMatchers.eq(mapboxMap), + ArgumentMatchers.any( + CameraUpdate::class.java + ), + ArgumentMatchers.any(Int::class.java), + ArgumentMatchers.any(CancelableCallback::class.java) + ) + camera.setCameraMode( + CameraMode.TRACKING, + location, + LocationComponentConstants.TRANSITION_ANIMATION_DURATION_MS, + null, + null, + null, + listener + ) + Mockito.verify(listener).onLocationCameraTransitionCanceled(CameraMode.TRACKING) + Mockito.verify(transform) + .animateCamera( + ArgumentMatchers.eq(mapboxMap), + ArgumentMatchers.any( + CameraUpdate::class.java + ), + ArgumentMatchers.any(Int::class.java), + ArgumentMatchers.any(CancelableCallback::class.java) + ) + } + + @Test + fun transition_mapboxCallbackFinished() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + val transform = Mockito.mock( + Transform::class.java + ) + Mockito.`when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) + val projection = Mockito.mock( + Projection::class.java + ) + Mockito.`when`(mapboxMap.projection).thenReturn(projection) + Mockito.`when`( + projection.getMetersPerPixelAtLatitude( + ArgumentMatchers.any( + Double::class.java + ) + ) + ).thenReturn(java.lang.Double.valueOf(1000.0)) + val camera = buildCamera(mapboxMap, transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + val listener = Mockito.mock( + OnLocationCameraTransitionListener::class.java + ) + val location = Mockito.mock( + Location::class.java + ) + Mockito.`when`(location.latitude).thenReturn(1.0) + Mockito.`when`(location.longitude).thenReturn(1.0) + Mockito.`when`(location.bearing).thenReturn(30f) + Mockito.`when`(location.altitude).thenReturn(0.0) + val callbackCaptor = ArgumentCaptor.forClass( + CancelableCallback::class.java + ) + camera.setCameraMode( + CameraMode.TRACKING, + location, + LocationComponentConstants.TRANSITION_ANIMATION_DURATION_MS, + null, + null, + null, + listener + ) + val builder = CameraPosition.Builder().target(LatLng(location)) + Mockito.verify(transform).animateCamera( + ArgumentMatchers.eq(mapboxMap), + ArgumentMatchers.eq(newCameraPosition(builder.build())), + ArgumentMatchers.eq(LocationComponentConstants.TRANSITION_ANIMATION_DURATION_MS.toInt()), + callbackCaptor.capture() + ) + Assert.assertTrue(camera.isTransitioning) + callbackCaptor.value.onFinish() + Assert.assertFalse(camera.isTransitioning) + Mockito.verify(listener).onLocationCameraTransitionFinished(CameraMode.TRACKING) + } + + @Test + fun transition_mapboxCallbackFinishedImmediately() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + val transform = Mockito.mock( + Transform::class.java + ) + Mockito.`when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) + val projection = Mockito.mock( + Projection::class.java + ) + Mockito.`when`(mapboxMap.projection).thenReturn(projection) + Mockito.`when`( + projection.getMetersPerPixelAtLatitude( + ArgumentMatchers.any( + Double::class.java + ) + ) + ).thenReturn(java.lang.Double.valueOf(1.0)) + val camera = buildCamera(mapboxMap, transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + val listener = Mockito.mock( + OnLocationCameraTransitionListener::class.java + ) + val location = Mockito.mock( + Location::class.java + ) + Mockito.`when`(location.latitude).thenReturn(1.0) + Mockito.`when`(location.longitude).thenReturn(1.0) + Mockito.`when`(location.bearing).thenReturn(30f) + Mockito.`when`(location.altitude).thenReturn(0.0) + val callbackCaptor = ArgumentCaptor.forClass( + CancelableCallback::class.java + ) + camera.setCameraMode( + CameraMode.TRACKING, + location, + LocationComponentConstants.TRANSITION_ANIMATION_DURATION_MS, + null, + null, + null, + listener + ) + val builder = CameraPosition.Builder().target(LatLng(location)) + Mockito.verify(transform).moveCamera( + ArgumentMatchers.eq(mapboxMap), + ArgumentMatchers.eq(newCameraPosition(builder.build())), + callbackCaptor.capture() + ) + Assert.assertTrue(camera.isTransitioning) + callbackCaptor.value.onFinish() + Assert.assertFalse(camera.isTransitioning) + Mockito.verify(listener).onLocationCameraTransitionFinished(CameraMode.TRACKING) + } + + @Test + fun transition_mapboxCallbackCanceled() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + val transform = Mockito.mock( + Transform::class.java + ) + Mockito.`when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) + val projection = Mockito.mock( + Projection::class.java + ) + Mockito.`when`(mapboxMap.projection).thenReturn(projection) + Mockito.`when`( + projection.getMetersPerPixelAtLatitude( + ArgumentMatchers.any( + Double::class.java + ) + ) + ).thenReturn(java.lang.Double.valueOf(1000.0)) + val camera = buildCamera(mapboxMap, transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + val listener = Mockito.mock( + OnLocationCameraTransitionListener::class.java + ) + val location = Mockito.mock( + Location::class.java + ) + Mockito.`when`(location.latitude).thenReturn(1.0) + Mockito.`when`(location.longitude).thenReturn(1.0) + Mockito.`when`(location.bearing).thenReturn(30f) + Mockito.`when`(location.altitude).thenReturn(0.0) + val callbackCaptor = ArgumentCaptor.forClass( + CancelableCallback::class.java + ) + camera.setCameraMode( + CameraMode.TRACKING, + location, + LocationComponentConstants.TRANSITION_ANIMATION_DURATION_MS, + null, + null, + null, + listener + ) + val builder = CameraPosition.Builder().target(LatLng(location)) + Mockito.verify(transform).animateCamera( + ArgumentMatchers.eq(mapboxMap), + ArgumentMatchers.eq(newCameraPosition(builder.build())), + ArgumentMatchers.eq(LocationComponentConstants.TRANSITION_ANIMATION_DURATION_MS.toInt()), + callbackCaptor.capture() + ) + Assert.assertTrue(camera.isTransitioning) + callbackCaptor.value.onCancel() + Assert.assertFalse(camera.isTransitioning) + Mockito.verify(listener).onLocationCameraTransitionCanceled(CameraMode.TRACKING) + } + + @Test + fun transition_mapboxAnimateBearing() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + val transform = Mockito.mock( + Transform::class.java + ) + Mockito.`when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) + val projection = Mockito.mock( + Projection::class.java + ) + Mockito.`when`(mapboxMap.projection).thenReturn(projection) + Mockito.`when`( + projection.getMetersPerPixelAtLatitude( + ArgumentMatchers.any( + Double::class.java + ) + ) + ).thenReturn(java.lang.Double.valueOf(1000.0)) + val camera = buildCamera(mapboxMap, transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + val listener = Mockito.mock( + OnLocationCameraTransitionListener::class.java + ) + val location = Mockito.mock( + Location::class.java + ) + Mockito.`when`(location.latitude).thenReturn(1.0) + Mockito.`when`(location.longitude).thenReturn(1.0) + Mockito.`when`(location.bearing).thenReturn(30f) + Mockito.`when`(location.altitude).thenReturn(0.0) + camera.setCameraMode( + CameraMode.TRACKING_GPS, + location, + LocationComponentConstants.TRANSITION_ANIMATION_DURATION_MS, + null, + null, + null, + listener + ) + val builder = CameraPosition.Builder().target(LatLng(location)).bearing(30.0) + Mockito.verify(transform).animateCamera( + ArgumentMatchers.eq(mapboxMap), + ArgumentMatchers.eq(newCameraPosition(builder.build())), + ArgumentMatchers.eq(LocationComponentConstants.TRANSITION_ANIMATION_DURATION_MS.toInt()), + ArgumentMatchers.any(CancelableCallback::class.java) + ) + } + + @Test + fun transition_mapboxAnimateNorth() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + val transform = Mockito.mock( + Transform::class.java + ) + Mockito.`when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) + val projection = Mockito.mock( + Projection::class.java + ) + Mockito.`when`(mapboxMap.projection).thenReturn(projection) + Mockito.`when`( + projection.getMetersPerPixelAtLatitude( + ArgumentMatchers.any( + Double::class.java + ) + ) + ).thenReturn(java.lang.Double.valueOf(1000.0)) + val camera = buildCamera(mapboxMap, transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + val listener = Mockito.mock( + OnLocationCameraTransitionListener::class.java + ) + val location = Mockito.mock( + Location::class.java + ) + Mockito.`when`(location.latitude).thenReturn(1.0) + Mockito.`when`(location.longitude).thenReturn(1.0) + Mockito.`when`(location.bearing).thenReturn(30f) + Mockito.`when`(location.altitude).thenReturn(0.0) + camera.setCameraMode( + CameraMode.TRACKING_GPS_NORTH, + location, + LocationComponentConstants.TRANSITION_ANIMATION_DURATION_MS, + null, + null, + null, + listener + ) + val builder = CameraPosition.Builder().target(LatLng(location)).bearing(0.0) + Mockito.verify(transform).animateCamera( + ArgumentMatchers.eq(mapboxMap), + ArgumentMatchers.eq(newCameraPosition(builder.build())), + ArgumentMatchers.eq(LocationComponentConstants.TRANSITION_ANIMATION_DURATION_MS.toInt()), + ArgumentMatchers.any(CancelableCallback::class.java) + ) + } + + @Test + fun transition_animatorValuesDuringTransition() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + val transform = Mockito.mock( + Transform::class.java + ) + Mockito.`when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) + val projection = Mockito.mock( + Projection::class.java + ) + Mockito.`when`(mapboxMap.projection).thenReturn(projection) + Mockito.`when`( + projection.getMetersPerPixelAtLatitude( + ArgumentMatchers.any( + Double::class.java + ) + ) + ).thenReturn(java.lang.Double.valueOf(1000.0)) + val camera = buildCamera(mapboxMap, transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + val listener = Mockito.mock( + OnLocationCameraTransitionListener::class.java + ) + val location = Mockito.mock( + Location::class.java + ) + val callbackCaptor = ArgumentCaptor.forClass( + CancelableCallback::class.java + ) + camera.setCameraMode( + CameraMode.TRACKING_GPS, + location, + LocationComponentConstants.TRANSITION_ANIMATION_DURATION_MS, + null, + null, + null, + listener + ) + Mockito.verify(transform).animateCamera( + ArgumentMatchers.eq(mapboxMap), + ArgumentMatchers.any(CameraUpdate::class.java), + ArgumentMatchers.eq(LocationComponentConstants.TRANSITION_ANIMATION_DURATION_MS.toInt()), + callbackCaptor.capture() + ) + val latLng = LatLng(10.0, 10.0) + getAnimationListener( + MapboxAnimator.ANIMATOR_CAMERA_LATLNG, + camera.animationListeners + )!!.onNewAnimationValue(latLng) + getAnimationListener( + MapboxAnimator.ANIMATOR_CAMERA_GPS_BEARING, + camera.animationListeners + )!!.onNewAnimationValue(10f) + getAnimationListener( + MapboxAnimator.ANIMATOR_TILT, + camera.animationListeners + )!!.onNewAnimationValue(10f) + getAnimationListener( + MapboxAnimator.ANIMATOR_ZOOM, + camera.animationListeners + )!!.onNewAnimationValue(10f) + Mockito.verify(transform, Mockito.times(0)).moveCamera( + ArgumentMatchers.eq(mapboxMap), + ArgumentMatchers.any( + CameraUpdate::class.java + ), + ArgumentMatchers.nullable(CancelableCallback::class.java) + ) + callbackCaptor.value.onFinish() + getAnimationListener( + MapboxAnimator.ANIMATOR_CAMERA_LATLNG, + camera.animationListeners + )!!.onNewAnimationValue(latLng) + getAnimationListener( + MapboxAnimator.ANIMATOR_CAMERA_GPS_BEARING, + camera.animationListeners + )!!.onNewAnimationValue(10f) + getAnimationListener( + MapboxAnimator.ANIMATOR_TILT, + camera.animationListeners + )!!.onNewAnimationValue(10f) + getAnimationListener( + MapboxAnimator.ANIMATOR_ZOOM, + camera.animationListeners + )!!.onNewAnimationValue(10f) + Mockito.verify(transform, Mockito.times(4)).moveCamera( + ArgumentMatchers.eq(mapboxMap), + ArgumentMatchers.any( + CameraUpdate::class.java + ), + ArgumentMatchers.nullable(CancelableCallback::class.java) + ) + } + + @Test + fun transition_customAnimation() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + val transform = Mockito.mock( + Transform::class.java + ) + Mockito.`when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) + val projection = Mockito.mock( + Projection::class.java + ) + Mockito.`when`(mapboxMap.projection).thenReturn(projection) + Mockito.`when`( + projection.getMetersPerPixelAtLatitude( + ArgumentMatchers.any( + Double::class.java + ) + ) + ).thenReturn(java.lang.Double.valueOf(1000.0)) + val camera = buildCamera(mapboxMap, transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + val location = Mockito.mock( + Location::class.java + ) + val cameraUpdate = newCameraPosition( + CameraPosition.Builder() + .target(LatLng(location)) + .zoom(14.0) + .bearing(13.0) + .tilt(45.0) + .build() + ) + camera.setCameraMode(CameraMode.TRACKING, location, 1200, 14.0, 13.0, 45.0, null) + Mockito.verify(transform) + .animateCamera( + ArgumentMatchers.eq(mapboxMap), + ArgumentMatchers.eq(cameraUpdate), + ArgumentMatchers.eq(1200), + ArgumentMatchers.any( + CancelableCallback::class.java + ) + ) + } + + @Test + fun transition_customAnimationDisabled() { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + val transform = Mockito.mock( + Transform::class.java + ) + Mockito.`when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) + val projection = Mockito.mock( + Projection::class.java + ) + Mockito.`when`(mapboxMap.projection).thenReturn(projection) + Mockito.`when`( + projection.getMetersPerPixelAtLatitude( + ArgumentMatchers.any( + Double::class.java + ) + ) + ).thenReturn(java.lang.Double.valueOf(1000.0)) + val camera = buildCamera(mapboxMap, transform) + camera.initializeOptions( + Mockito.mock( + LocationComponentOptions::class.java + ) + ) + val location = Mockito.mock( + Location::class.java + ) + val cameraUpdate = newCameraPosition( + CameraPosition.Builder() + .target(LatLng(location)) + .zoom(14.0) + .bearing(13.0) + .tilt(45.0) + .build() + ) + camera.setEnabled(false) + camera.setCameraMode(CameraMode.TRACKING, location, 1200, 14.0, 13.0, 45.0, null) + Mockito.verify(transform, Mockito.times(0)) + .animateCamera( + ArgumentMatchers.eq(mapboxMap), + ArgumentMatchers.eq(cameraUpdate), + ArgumentMatchers.eq(1200), + ArgumentMatchers.any( + CancelableCallback::class.java + ) + ) + } + + private fun buildCamera(onCameraTrackingChangedListener: OnCameraTrackingChangedListener): LocationCameraController { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + Mockito.`when`(mapboxMap.uiSettings).thenReturn( + Mockito.mock( + UiSettings::class.java + ) + ) + val transform = Mockito.mock( + Transform::class.java + ) + val projection = Mockito.mock( + Projection::class.java + ) + Mockito.`when`(mapboxMap.projection).thenReturn(projection) + Mockito.`when`( + projection.getMetersPerPixelAtLatitude( + ArgumentMatchers.any( + Double::class.java + ) + ) + ).thenReturn(java.lang.Double.valueOf(1000.0)) + val moveGestureDetector = Mockito.mock( + MoveGestureDetector::class.java + ) + val onCameraMoveInvalidateListener = Mockito.mock( + OnCameraMoveInvalidateListener::class.java + ) + val initialGesturesManager = Mockito.mock( + AndroidGesturesManager::class.java + ) + val internalGesturesManager = Mockito.mock( + AndroidGesturesManager::class.java + ) + return LocationCameraController( + mapboxMap, + transform, + moveGestureDetector, + onCameraTrackingChangedListener, + onCameraMoveInvalidateListener, + initialGesturesManager, + internalGesturesManager + ) + } + + private fun buildCamera(moveGestureDetector: MoveGestureDetector): LocationCameraController { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + Mockito.`when`(mapboxMap.uiSettings).thenReturn( + Mockito.mock( + UiSettings::class.java + ) + ) + val transform = Mockito.mock( + Transform::class.java + ) + val projection = Mockito.mock( + Projection::class.java + ) + Mockito.`when`(mapboxMap.projection).thenReturn(projection) + Mockito.`when`( + projection.getMetersPerPixelAtLatitude( + ArgumentMatchers.any( + Double::class.java + ) + ) + ).thenReturn(java.lang.Double.valueOf(1000.0)) + val onCameraTrackingChangedListener = Mockito.mock( + OnCameraTrackingChangedListener::class.java + ) + val onCameraMoveInvalidateListener = Mockito.mock( + OnCameraMoveInvalidateListener::class.java + ) + val initialGesturesManager = Mockito.mock( + AndroidGesturesManager::class.java + ) + val internalGesturesManager = Mockito.mock( + AndroidGesturesManager::class.java + ) + return LocationCameraController( + mapboxMap, + transform, + moveGestureDetector, + onCameraTrackingChangedListener, + onCameraMoveInvalidateListener, + initialGesturesManager, + internalGesturesManager + ) + } + + private fun buildCamera(mapboxMap: MapboxMap): LocationCameraController { + val transform = Mockito.mock( + Transform::class.java + ) + val moveGestureDetector = Mockito.mock( + MoveGestureDetector::class.java + ) + val onCameraTrackingChangedListener = Mockito.mock( + OnCameraTrackingChangedListener::class.java + ) + val onCameraMoveInvalidateListener = Mockito.mock( + OnCameraMoveInvalidateListener::class.java + ) + val initialGesturesManager = Mockito.mock( + AndroidGesturesManager::class.java + ) + val internalGesturesManager = Mockito.mock( + AndroidGesturesManager::class.java + ) + return LocationCameraController( + mapboxMap, + transform, + moveGestureDetector, + onCameraTrackingChangedListener, + onCameraMoveInvalidateListener, + initialGesturesManager, + internalGesturesManager + ) + } + + private fun buildCamera(transform: Transform): LocationCameraController { + val mapboxMap = Mockito.mock(MapboxMap::class.java) + Mockito.`when`(mapboxMap.uiSettings).thenReturn( + Mockito.mock( + UiSettings::class.java + ) + ) + val projection = Mockito.mock( + Projection::class.java + ) + Mockito.`when`(mapboxMap.projection).thenReturn(projection) + Mockito.`when`( + projection.getMetersPerPixelAtLatitude( + ArgumentMatchers.any( + Double::class.java + ) + ) + ).thenReturn(java.lang.Double.valueOf(1000.0)) + Mockito.`when`(mapboxMap.uiSettings).thenReturn( + Mockito.mock( + UiSettings::class.java + ) + ) + val moveGestureDetector = Mockito.mock( + MoveGestureDetector::class.java + ) + val onCameraTrackingChangedListener = Mockito.mock( + OnCameraTrackingChangedListener::class.java + ) + val onCameraMoveInvalidateListener = Mockito.mock( + OnCameraMoveInvalidateListener::class.java + ) + val initialGesturesManager = Mockito.mock( + AndroidGesturesManager::class.java + ) + val internalGesturesManager = Mockito.mock( + AndroidGesturesManager::class.java + ) + return LocationCameraController( + mapboxMap, + transform, + moveGestureDetector, + onCameraTrackingChangedListener, + onCameraMoveInvalidateListener, + initialGesturesManager, + internalGesturesManager + ) + } + + private fun buildCamera(mapboxMap: MapboxMap, transform: Transform): LocationCameraController { + Mockito.`when`(mapboxMap.uiSettings).thenReturn( + Mockito.mock( + UiSettings::class.java + ) + ) + val moveGestureDetector = Mockito.mock( + MoveGestureDetector::class.java + ) + val onCameraTrackingChangedListener = Mockito.mock( + OnCameraTrackingChangedListener::class.java + ) + val onCameraMoveInvalidateListener = Mockito.mock( + OnCameraMoveInvalidateListener::class.java + ) + val initialGesturesManager = Mockito.mock( + AndroidGesturesManager::class.java + ) + val internalGesturesManager = Mockito.mock( + AndroidGesturesManager::class.java + ) + val locationCameraController = LocationCameraController( + mapboxMap, + transform, + moveGestureDetector, + onCameraTrackingChangedListener, + onCameraMoveInvalidateListener, + initialGesturesManager, + internalGesturesManager + ) + locationCameraController.setEnabled(true) + return locationCameraController + } + + private fun buildCamera( + mapboxMap: MapboxMap, + initialGesturesManager: AndroidGesturesManager, + internalGesturesManager: AndroidGesturesManager + ): LocationCameraController { + val transform = Mockito.mock( + Transform::class.java + ) + val moveGestureDetector = Mockito.mock( + MoveGestureDetector::class.java + ) + val onCameraTrackingChangedListener = Mockito.mock( + OnCameraTrackingChangedListener::class.java + ) + val onCameraMoveInvalidateListener = Mockito.mock( + OnCameraMoveInvalidateListener::class.java + ) + return LocationCameraController( + mapboxMap, + transform, + moveGestureDetector, + onCameraTrackingChangedListener, + onCameraMoveInvalidateListener, + initialGesturesManager, + internalGesturesManager + ) + } + + private fun getAnimationListener( + @MapboxAnimator.Type animatorType: Int, + holders: Set + ): AnimationsValueChangeListener? { + for (holder in holders) { + @MapboxAnimator.Type val type = holder.animatorType + if (type == animatorType) { + return holder.listener + } + } + return null + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentActivationOptionsTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentActivationOptionsTest.java deleted file mode 100644 index 73a88f33f..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentActivationOptionsTest.java +++ /dev/null @@ -1,160 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.content.Context; -import android.content.res.Resources; -import android.content.res.TypedArray; -import android.graphics.Color; -import android.view.animation.LinearInterpolator; - -import androidx.annotation.NonNull; - -import com.mapbox.mapboxsdk.R; -import com.mapbox.mapboxsdk.maps.Style; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoJUnitRunner; -import org.mockito.junit.MockitoRule; - -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.when; - -@RunWith(MockitoJUnitRunner.class) -public class LocationComponentActivationOptionsTest { - - @Mock - private Context context; - @Mock - private TypedArray array; - @Mock - private Resources resources; - @Mock - private Style style; - - @Rule - public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @NonNull - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Before - public void setUp() throws Exception { - when(context.obtainStyledAttributes(R.style.maplibre_LocationComponent, R.styleable.maplibre_LocationComponent)) - .thenReturn(array); - when(array.getResourceId(R.styleable.maplibre_LocationComponent_maplibre_foregroundDrawable, -1)) - .thenReturn(R.drawable.maplibre_user_icon); - when(context.getResources()).thenReturn(resources); - } - - @Test - public void sanity() throws Exception { - when(style.isFullyLoaded()).thenReturn(true); - - LocationComponentOptions locationComponentOptions = LocationComponentOptions.builder(context) - .accuracyAlpha(0.5f) - .build(); - assertNotNull(locationComponentOptions); - - LocationComponentActivationOptions locationComponentActivationOptions = - LocationComponentActivationOptions.builder(context, style) - .locationComponentOptions(locationComponentOptions) - .useDefaultLocationEngine(true) - .build(); - assertNotNull(locationComponentActivationOptions); - } - - @Test - public void sanityWithDefaultPulsingCircle() throws Exception { - when(style.isFullyLoaded()).thenReturn(true); - - LocationComponentOptions locationComponentOptions = LocationComponentOptions.builder(context) - .accuracyAlpha(0.5f) - .pulseEnabled(true) - .build(); - assertNotNull(locationComponentOptions); - - LocationComponentActivationOptions locationComponentActivationOptions = - LocationComponentActivationOptions.builder(context, style) - .locationComponentOptions(locationComponentOptions) - .useDefaultLocationEngine(true) - .build(); - assertNotNull(locationComponentActivationOptions); - } - - @Test - public void sanityWithCustomizedPulsingCircle() throws Exception { - when(style.isFullyLoaded()).thenReturn(true); - - LocationComponentOptions locationComponentOptions = LocationComponentOptions.builder(context) - .accuracyAlpha(0.5f) - .pulseEnabled(true) - .pulseColor(Color.RED) - .pulseInterpolator(new LinearInterpolator()) - .build(); - assertNotNull(locationComponentOptions); - - LocationComponentActivationOptions locationComponentActivationOptions = - LocationComponentActivationOptions.builder(context, style) - .locationComponentOptions(locationComponentOptions) - .useDefaultLocationEngine(true) - .build(); - assertNotNull(locationComponentActivationOptions); - } - - @Test - public void includingBothStyleResAndComponentOptions_causesExceptionToBeThrown() throws Exception { - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("You've provided both a style resource and a LocationComponentOptions" - + " object to the LocationComponentActivationOptions builder. You can't use both and " - + "you must choose one of the two to style the LocationComponent."); - - LocationComponentOptions locationComponentOptions = LocationComponentOptions.builder(context) - .accuracyAlpha(0.5f) - .build(); - - LocationComponentActivationOptions.builder(context, style) - .locationComponentOptions(locationComponentOptions) - .styleRes(R.style.maplibre_LocationComponent) - .build(); - } - - @Test - public void nullContext_causesExceptionToBeThrown() throws Exception { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Context in LocationComponentActivationOptions is null."); - - LocationComponentActivationOptions.builder(null, style) - .build(); - } - - @Test - public void nullStyle_causesExceptionToBeThrown() throws Exception { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Style in LocationComponentActivationOptions is null. Make sure the Style object isn't null." - + " Wait for the map to fully load before passing the Style object to LocationComponentActivationOptions."); - - LocationComponentActivationOptions.builder(context, null) - .build(); - } - - @Test - public void locationComponent_exceptionThrownWithDefaultLocationEngineButNotFullyLoadedStyle() throws Exception { - - when(style.isFullyLoaded()).thenReturn(false); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Style in LocationComponentActivationOptions isn't fully loaded. Wait for the " - + "map to fully load before passing the Style object to " - + "LocationComponentActivationOptions."); - - LocationComponentActivationOptions.builder(context, style) - .build(); - } -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentActivationOptionsTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentActivationOptionsTest.kt new file mode 100644 index 000000000..0878da3cb --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentActivationOptionsTest.kt @@ -0,0 +1,158 @@ +package com.mapbox.mapboxsdk.location + +import android.content.Context +import android.content.res.Resources +import android.content.res.TypedArray +import android.graphics.Color +import android.view.animation.LinearInterpolator +import com.mapbox.mapboxsdk.R +import com.mapbox.mapboxsdk.maps.Style +import org.junit.Assert +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.ExpectedException +import org.junit.runner.RunWith +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnit +import org.mockito.junit.MockitoJUnitRunner + +@RunWith(MockitoJUnitRunner::class) +class LocationComponentActivationOptionsTest { + @Mock + private val context: Context? = null + + @Mock + private val array: TypedArray? = null + + @Mock + private val resources: Resources? = null + + @Mock + private val style: Style? = null + + @Rule @JvmField + var mockitoRule = MockitoJUnit.rule() + + @Rule @JvmField + var thrown = ExpectedException.none() + + @Before + @Throws(Exception::class) + fun setUp() { + Mockito.`when`( + context!!.obtainStyledAttributes( + R.style.maplibre_LocationComponent, + R.styleable.maplibre_LocationComponent + ) + ) + .thenReturn(array) + Mockito.`when`( + array!!.getResourceId( + R.styleable.maplibre_LocationComponent_maplibre_foregroundDrawable, + -1 + ) + ) + .thenReturn(R.drawable.maplibre_user_icon) + Mockito.`when`(context.resources).thenReturn(resources) + } + + @Test + @Throws(Exception::class) + fun sanity() { + Mockito.`when`(style!!.isFullyLoaded).thenReturn(true) + val locationComponentOptions = LocationComponentOptions.builder( + context!! + ) + .accuracyAlpha(0.5f) + .build() + Assert.assertNotNull(locationComponentOptions) + val locationComponentActivationOptions = LocationComponentActivationOptions.builder( + context, + style + ) + .locationComponentOptions(locationComponentOptions) + .useDefaultLocationEngine(true) + .build() + Assert.assertNotNull(locationComponentActivationOptions) + } + + @Test + @Throws(Exception::class) + fun sanityWithDefaultPulsingCircle() { + Mockito.`when`(style!!.isFullyLoaded).thenReturn(true) + val locationComponentOptions = LocationComponentOptions.builder( + context!! + ) + .accuracyAlpha(0.5f) + .pulseEnabled(true) + .build() + Assert.assertNotNull(locationComponentOptions) + val locationComponentActivationOptions = LocationComponentActivationOptions.builder( + context, + style + ) + .locationComponentOptions(locationComponentOptions) + .useDefaultLocationEngine(true) + .build() + Assert.assertNotNull(locationComponentActivationOptions) + } + + @Test + @Throws(Exception::class) + fun sanityWithCustomizedPulsingCircle() { + Mockito.`when`(style!!.isFullyLoaded).thenReturn(true) + val locationComponentOptions = LocationComponentOptions.builder( + context!! + ) + .accuracyAlpha(0.5f) + .pulseEnabled(true) + .pulseColor(Color.RED) + .pulseInterpolator(LinearInterpolator()) + .build() + Assert.assertNotNull(locationComponentOptions) + val locationComponentActivationOptions = LocationComponentActivationOptions.builder( + context, + style + ) + .locationComponentOptions(locationComponentOptions) + .useDefaultLocationEngine(true) + .build() + Assert.assertNotNull(locationComponentActivationOptions) + } + + @Test + @Throws(Exception::class) + fun includingBothStyleResAndComponentOptions_causesExceptionToBeThrown() { + thrown.expect(IllegalArgumentException::class.java) + thrown.expectMessage( + "You've provided both a style resource and a LocationComponentOptions" + + " object to the LocationComponentActivationOptions builder. You can't use both and " + + "you must choose one of the two to style the LocationComponent." + ) + val locationComponentOptions = LocationComponentOptions.builder( + context!! + ) + .accuracyAlpha(0.5f) + .build() + LocationComponentActivationOptions.builder(context, style!!) + .locationComponentOptions(locationComponentOptions) + .styleRes(R.style.maplibre_LocationComponent) + .build() + } + + @Test + @Throws(Exception::class) + fun locationComponent_exceptionThrownWithDefaultLocationEngineButNotFullyLoadedStyle() { + Mockito.`when`(style!!.isFullyLoaded).thenReturn(false) + thrown.expect(IllegalArgumentException::class.java) + thrown.expectMessage( + "Style in LocationComponentActivationOptions isn't fully loaded. Wait for the " + + "map to fully load before passing the Style object to " + + "LocationComponentActivationOptions." + ) + LocationComponentActivationOptions.builder(context!!, style) + .build() + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentOptionsTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentOptionsTest.java deleted file mode 100644 index d89287fa3..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentOptionsTest.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.content.Context; -import android.content.res.Resources; -import android.content.res.TypedArray; - -import androidx.annotation.NonNull; - -import com.mapbox.mapboxsdk.R; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.when; - -@RunWith(MockitoJUnitRunner.class) -public class LocationComponentOptionsTest { - - @Mock - private Context context; - @Mock - private TypedArray array; - @Mock - private Resources resources; - - @NonNull - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Before - public void setUp() throws Exception { - when(context.obtainStyledAttributes(R.style.maplibre_LocationComponent, R.styleable.maplibre_LocationComponent)) - .thenReturn(array); - when(array.getResourceId(R.styleable.maplibre_LocationComponent_maplibre_foregroundDrawable, -1)) - .thenReturn(R.drawable.maplibre_user_icon); - when(context.getResources()).thenReturn(resources); - } - - @Test - public void sanity() throws Exception { - LocationComponentOptions locationComponentOptions = LocationComponentOptions.builder(context) - .accuracyAlpha(0.5f) - .build(); - assertNotNull(locationComponentOptions); - } - - @Test - public void passingOutOfRangeAccuracyAlpha_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Accuracy alpha value must be between 0.0 and " - + "1.0."); - LocationComponentOptions.builder(context) - .accuracyAlpha(2f) - .build(); - } - - @Test - public void negativeElevation_causesExceptionToBeThrown() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Invalid shadow size -500.0. Must be >= 0"); - LocationComponentOptions.builder(context) - .elevation(-500) - .build(); - } - - @Test - public void passingBothLayerPositionOptions_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("You cannot set both layerAbove and layerBelow options." - + " Choose one or the other."); - LocationComponentOptions.builder(context) - .layerAbove("above") - .layerBelow("below") - .build(); - } -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentOptionsTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentOptionsTest.kt new file mode 100644 index 000000000..6c388a448 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentOptionsTest.kt @@ -0,0 +1,98 @@ +package com.mapbox.mapboxsdk.location + +import android.content.Context +import android.content.res.Resources +import android.content.res.TypedArray +import com.mapbox.mapboxsdk.R +import org.junit.Assert +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.ExpectedException +import org.junit.runner.RunWith +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +@RunWith(MockitoJUnitRunner::class) +class LocationComponentOptionsTest { + @Mock + private val context: Context? = null + + @Mock + private val array: TypedArray? = null + + @Mock + private val resources: Resources? = null + + @Rule @JvmField + var thrown = ExpectedException.none() + + @Before + @Throws(Exception::class) + fun setUp() { + Mockito.`when`( + context!!.obtainStyledAttributes( + R.style.maplibre_LocationComponent, + R.styleable.maplibre_LocationComponent + ) + ) + .thenReturn(array) + Mockito.`when`( + array!!.getResourceId( + R.styleable.maplibre_LocationComponent_maplibre_foregroundDrawable, + -1 + ) + ) + .thenReturn(R.drawable.maplibre_user_icon) + Mockito.`when`(context.resources).thenReturn(resources) + } + + @Test + @Throws(Exception::class) + fun sanity() { + val locationComponentOptions = LocationComponentOptions.builder( + context!! + ) + .accuracyAlpha(0.5f) + .build() + Assert.assertNotNull(locationComponentOptions) + } + + @Test + @Throws(Exception::class) + fun passingOutOfRangeAccuracyAlpha_throwsException() { + thrown.expect(IllegalArgumentException::class.java) + thrown.expectMessage( + "Accuracy alpha value must be between 0.0 and " + + "1.0." + ) + LocationComponentOptions.builder(context!!) + .accuracyAlpha(2f) + .build() + } + + @Test + @Throws(Exception::class) + fun negativeElevation_causesExceptionToBeThrown() { + thrown.expect(IllegalArgumentException::class.java) + thrown.expectMessage("Invalid shadow size -500.0. Must be >= 0") + LocationComponentOptions.builder(context!!) + .elevation(-500f) + .build() + } + + @Test + @Throws(Exception::class) + fun passingBothLayerPositionOptions_throwsException() { + thrown.expect(IllegalArgumentException::class.java) + thrown.expectMessage( + "You cannot set both layerAbove and layerBelow options." + + " Choose one or the other." + ) + LocationComponentOptions.builder(context!!) + .layerAbove("above") + .layerBelow("below") + .build() + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationLayerControllerTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationLayerControllerTest.java deleted file mode 100644 index 1d5ebb124..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationLayerControllerTest.java +++ /dev/null @@ -1,764 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.graphics.Bitmap; - -import androidx.annotation.NonNull; - -import com.google.gson.JsonElement; -import com.mapbox.geojson.Feature; -import com.mapbox.mapboxsdk.geometry.LatLng; -import com.mapbox.mapboxsdk.location.modes.RenderMode; -import com.mapbox.mapboxsdk.maps.MapboxMap; -import com.mapbox.mapboxsdk.maps.Style; -import com.mapbox.mapboxsdk.style.layers.Layer; -import com.mapbox.mapboxsdk.style.sources.GeoJsonSource; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.util.HashSet; -import java.util.Set; - -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.ACCURACY_LAYER; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.BACKGROUND_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.BACKGROUND_LAYER; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.BACKGROUND_STALE_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.BEARING_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.BEARING_LAYER; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.FOREGROUND_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.FOREGROUND_LAYER; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.FOREGROUND_STALE_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.LOCATION_SOURCE; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_ACCURACY_RADIUS; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_COMPASS_BEARING; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_FOREGROUND_ICON_OFFSET; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_GPS_BEARING; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_SHADOW_ICON_OFFSET; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PULSING_CIRCLE_LAYER; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.SHADOW_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.SHADOW_LAYER; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_LAYER_ACCURACY; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_LAYER_COMPASS_BEARING; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_LAYER_GPS_BEARING; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_LAYER_LATLNG; -import static junit.framework.Assert.assertEquals; -import static junit.framework.Assert.assertNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class LocationLayerControllerTest { - - private MapboxMap mapboxMap = mock(MapboxMap.class); - private Style style = mock(Style.class); - private LocationLayerRenderer indicatorRenderer = mock(LocationLayerRenderer.class); - - @Before - public void before() { - when(mapboxMap.getStyle()).thenReturn(style); - } - - @Test - public void onInitialization_locationSourceIsAdded() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener, false); - - verify(style).addSource(locationSource); - } - - @Test - public void onInitialization_shadowLayerIsAdded() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - Layer shadowLayer = mock(Layer.class); - when(sourceProvider.generateLayer(SHADOW_LAYER)).thenReturn(shadowLayer); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener, false); - - verify(style).addLayerBelow(shadowLayer, BACKGROUND_LAYER); - } - - @Test - public void onInitialization_backgroundLayerIsAdded() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - Layer backgroundLayer = mock(Layer.class); - when(sourceProvider.generateLayer(BACKGROUND_LAYER)).thenReturn(backgroundLayer); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener, false); - - verify(style).addLayerBelow(backgroundLayer, FOREGROUND_LAYER); - } - - @Test - public void onInitialization_foregroundLayerIsAdded() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - Layer foregroundLayer = mock(Layer.class); - when(sourceProvider.generateLayer(FOREGROUND_LAYER)).thenReturn(foregroundLayer); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener, false); - - verify(style).addLayerBelow(foregroundLayer, BEARING_LAYER); - } - - @Test - public void onInitialization_bearingLayerIsAdded() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - Layer bearingLayer = mock(Layer.class); - when(sourceProvider.generateLayer(BEARING_LAYER)).thenReturn(bearingLayer); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - String layerBelow = "layer-below"; - when(options.layerBelow()).thenReturn(layerBelow); - - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener, false); - - verify(style).addLayerBelow(bearingLayer, layerBelow); - } - - @Test - public void onInitialization_accuracyLayerIsAdded() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - Layer accuracyLayer = mock(Layer.class); - when(sourceProvider.generateAccuracyLayer()).thenReturn(accuracyLayer); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener, false); - - verify(style).addLayerBelow(accuracyLayer, BACKGROUND_LAYER); - } - - @Test - public void onInitialization_pulsingCircleLayerIsAdded() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - Layer pulsingCircleLayer = mock(Layer.class); - when(sourceProvider.generatePulsingCircleLayer()).thenReturn(pulsingCircleLayer); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener, false); - - verify(style).addLayerBelow(pulsingCircleLayer, ACCURACY_LAYER); - } - - @Test - public void onInitialization_numberOfCachedLayerIdsIsConstant() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - Set layerSet = new HashSet<>(); - when(sourceProvider.getEmptyLayerSet()).thenReturn(layerSet); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - - LocationLayerController controller = - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener, false); - - controller.initializeComponents(mapboxMap.getStyle(), options); - - assertEquals(6, layerSet.size()); - } - - @Test - public void applyStyle_styleShadowWithValidElevation() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(mock(GeoJsonSource.class)); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - Bitmap bitmap = mock(Bitmap.class); - when(bitmapProvider.generateShadowBitmap(any(LocationComponentOptions.class))).thenReturn(bitmap); - LocationComponentOptions options = mock(LocationComponentOptions.class); - when(options.elevation()).thenReturn(2f); - - // Style is applied on initialization - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener, false); - - verify(style).addImage(SHADOW_ICON, bitmap); - } - - @Test - public void applyStyle_ignoreStyleShadowWithInvalidElevation() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(mock(GeoJsonSource.class)); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - Bitmap bitmap = mock(Bitmap.class); - when(bitmapProvider.generateShadowBitmap(any(LocationComponentOptions.class))).thenReturn(bitmap); - LocationComponentOptions options = mock(LocationComponentOptions.class); - when(options.elevation()).thenReturn(0f); - - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener, false); - - verify(style, times(0)).addImage(SHADOW_ICON, bitmap); - } - - @Test - public void applyStyle_styleForegroundFromOptions() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(mock(GeoJsonSource.class)); - LocationComponentOptions options = mock(LocationComponentOptions.class); - int drawableResId = 123; - int tintColor = 456; - when(options.foregroundDrawable()).thenReturn(drawableResId); - when(options.foregroundTintColor()).thenReturn(tintColor); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - Bitmap bitmap = mock(Bitmap.class); - when(bitmapProvider.generateBitmap(drawableResId, tintColor)).thenReturn(bitmap); - - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener, false); - - verify(style).addImage(FOREGROUND_ICON, bitmap); - } - - @Test - public void applyStyle_styleForegroundStaleFromOptions() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(mock(GeoJsonSource.class)); - LocationComponentOptions options = mock(LocationComponentOptions.class); - int drawableResId = 123; - int tintColor = 456; - when(options.foregroundDrawableStale()).thenReturn(drawableResId); - when(options.foregroundStaleTintColor()).thenReturn(tintColor); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - Bitmap bitmap = mock(Bitmap.class); - when(bitmapProvider.generateBitmap(drawableResId, tintColor)).thenReturn(bitmap); - - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener, false); - - verify(style).addImage(FOREGROUND_STALE_ICON, bitmap); - } - - @Test - public void applyStyle_styleBackgroundFromOptions() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(mock(GeoJsonSource.class)); - LocationComponentOptions options = mock(LocationComponentOptions.class); - int drawableResId = 123; - int tintColor = 456; - when(options.backgroundDrawable()).thenReturn(drawableResId); - when(options.backgroundTintColor()).thenReturn(tintColor); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - Bitmap bitmap = mock(Bitmap.class); - when(bitmapProvider.generateBitmap(drawableResId, tintColor)).thenReturn(bitmap); - - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener, false); - - verify(style).addImage(BACKGROUND_ICON, bitmap); - } - - @Test - public void applyStyle_styleBackgroundStaleFromOptions() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(mock(GeoJsonSource.class)); - LocationComponentOptions options = mock(LocationComponentOptions.class); - int drawableResId = 123; - int tintColor = 456; - when(options.backgroundDrawableStale()).thenReturn(drawableResId); - when(options.backgroundStaleTintColor()).thenReturn(tintColor); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - Bitmap bitmap = mock(Bitmap.class); - when(bitmapProvider.generateBitmap(drawableResId, tintColor)).thenReturn(bitmap); - - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener, false); - - verify(style).addImage(BACKGROUND_STALE_ICON, bitmap); - } - - @Test - public void applyStyle_styleBearingFromOptions() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(mock(GeoJsonSource.class)); - LocationComponentOptions options = mock(LocationComponentOptions.class); - int drawableResId = 123; - int tintColor = 456; - when(options.bearingDrawable()).thenReturn(drawableResId); - when(options.bearingTintColor()).thenReturn(tintColor); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - Bitmap bitmap = mock(Bitmap.class); - when(bitmapProvider.generateBitmap(drawableResId, tintColor)).thenReturn(bitmap); - - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener, false); - - verify(style).addImage(BEARING_ICON, bitmap); - } - - @Test - public void applyStyle_specializedLayer_ignoreBitmapNames() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - LocationComponentOptions options = mock(LocationComponentOptions.class); - when(options.foregroundName()).thenReturn("new_name"); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener, true); - - verify(indicatorRenderer).updateIconIds(eq(FOREGROUND_ICON), anyString(), anyString(), anyString(), anyString()); - } - - @Test - public void applyStyle_layerBelowChanged() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(mock(GeoJsonSource.class)); - - LocationComponentOptions options = mock(LocationComponentOptions.class); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - Bitmap bitmap = mock(Bitmap.class); - when(bitmapProvider.generateShadowBitmap(any(LocationComponentOptions.class))).thenReturn(bitmap); - - LocationLayerController layerController = - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener, false); - - Layer bearingLayer2 = mock(Layer.class); - when(sourceProvider.generateLayer(BEARING_LAYER)).thenReturn(bearingLayer2); - Layer foregroundLayer2 = mock(Layer.class); - when(sourceProvider.generateLayer(FOREGROUND_LAYER)).thenReturn(foregroundLayer2); - Layer backgroundLayer2 = mock(Layer.class); - when(sourceProvider.generateLayer(BACKGROUND_LAYER)).thenReturn(backgroundLayer2); - Layer shadowLayer2 = mock(Layer.class); - when(sourceProvider.generateLayer(SHADOW_LAYER)).thenReturn(shadowLayer2); - Layer accuracyLayer2 = mock(Layer.class); - when(sourceProvider.generateAccuracyLayer()).thenReturn(accuracyLayer2); - String layerBelow = "layer-below"; - when(options.layerBelow()).thenReturn(layerBelow); - - layerController.applyStyle(options); - - verify(style).removeLayer(BEARING_LAYER); - verify(style).removeLayer(FOREGROUND_LAYER); - verify(style).removeLayer(BACKGROUND_LAYER); - verify(style).removeLayer(SHADOW_LAYER); - verify(style).removeLayer(ACCURACY_LAYER); - - verify(style).addLayerBelow(bearingLayer2, layerBelow); - verify(style).addLayerBelow(foregroundLayer2, BEARING_LAYER); - verify(style).addLayerBelow(backgroundLayer2, FOREGROUND_LAYER); - verify(style).addLayerBelow(shadowLayer2, BACKGROUND_LAYER); - verify(style).addLayerBelow(accuracyLayer2, BACKGROUND_LAYER); - } - - @Test - public void applyStyle_layerBelowNotChanged() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(mock(GeoJsonSource.class)); - LocationComponentOptions options = mock(LocationComponentOptions.class); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - Bitmap bitmap = mock(Bitmap.class); - when(bitmapProvider.generateShadowBitmap(any(LocationComponentOptions.class))).thenReturn(bitmap); - - String layerBelow = "layer-below"; - when(options.layerBelow()).thenReturn(layerBelow); - - LocationLayerController layerController = - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener, false); - - options = mock(LocationComponentOptions.class); - layerBelow = "layer-below"; - when(options.layerBelow()).thenReturn(layerBelow); - layerController.applyStyle(options); - - verify(style, times(0)).removeLayer(any(String.class)); - verify(style, times(6)).addLayerBelow(any(Layer.class), any(String.class)); - } - - @Test - public void applyStyle_layerBelowNotChangedNull() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(mock(GeoJsonSource.class)); - LocationComponentOptions options = mock(LocationComponentOptions.class); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - Bitmap bitmap = mock(Bitmap.class); - when(bitmapProvider.generateShadowBitmap(any(LocationComponentOptions.class))).thenReturn(bitmap); - - LocationLayerController layerController = - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener, false); - - options = mock(LocationComponentOptions.class); - layerController.applyStyle(options); - - verify(style, times(0)).removeLayer(any(String.class)); - verify(style, times(1)).addLayer(any(Layer.class)); - verify(style, times(5)).addLayerBelow(any(Layer.class), Mockito.any()); - } - - @Test - public void updateForegroundOffset_foregroundIconPropertyIsUpdated() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - Feature locationFeature = mock(Feature.class); - LocationLayerController layer = new LocationLayerController( - mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(locationFeature, options), - bitmapProvider, options, internalRenderModeChangedListener, false); - - layer.cameraTiltUpdated(2d); - - verify(locationFeature).addProperty(eq(PROPERTY_FOREGROUND_ICON_OFFSET), any(JsonElement.class)); - } - - @Test - public void updateForegroundOffset_shadowPropertyIsUpdated() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - Feature locationFeature = mock(Feature.class); - LocationLayerController layer = new LocationLayerController( - mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(locationFeature, options), - bitmapProvider, options, internalRenderModeChangedListener, false); - layer.cameraTiltUpdated(2d); - - verify(locationFeature).addProperty(eq(PROPERTY_SHADOW_ICON_OFFSET), any(JsonElement.class)); - } - - @Test - public void onNewLatLngValue_locationFeatureIsUpdated() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(style.getSourceAs(LOCATION_SOURCE)).thenReturn(locationSource); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - Feature locationFeature = mock(Feature.class); - LocationLayerController layer = new LocationLayerController( - mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(locationFeature, options), - bitmapProvider, options, internalRenderModeChangedListener, false); - - getAnimationListener(ANIMATOR_LAYER_LATLNG, layer.getAnimationListeners()).onNewAnimationValue(new LatLng()); - - // wanted twice (once for initialization) - verify(locationSource, times(2)).setGeoJson(locationFeature); - } - - @Test - public void onNewGpsBearingValue_locationFeatureIsUpdated() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(style.getSourceAs(LOCATION_SOURCE)).thenReturn(locationSource); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - Feature locationFeature = mock(Feature.class); - LocationLayerController layer = new LocationLayerController( - mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(locationFeature, options), - bitmapProvider, options, internalRenderModeChangedListener, false); - layer.setRenderMode(RenderMode.GPS); - float gpsBearing = 2f; - - getAnimationListener(ANIMATOR_LAYER_GPS_BEARING, layer.getAnimationListeners()).onNewAnimationValue(gpsBearing); - - verify(locationFeature).addNumberProperty(PROPERTY_GPS_BEARING, gpsBearing); - } - - @Test - public void onNewGpsBearingValue_updateIgnoredWithInvalidRenderMode() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(style.getSourceAs(LOCATION_SOURCE)).thenReturn(locationSource); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - Feature locationFeature = mock(Feature.class); - LocationLayerController layer = new LocationLayerController( - mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(locationFeature, options), - bitmapProvider, options, internalRenderModeChangedListener, false); - layer.setRenderMode(RenderMode.COMPASS); - float gpsBearing = 2f; - - assertNull(getAnimationListener(ANIMATOR_LAYER_GPS_BEARING, layer.getAnimationListeners())); - verify(locationFeature, times(0)).addNumberProperty(PROPERTY_GPS_BEARING, gpsBearing); - } - - @Test - public void onNewCompassBearingValue_locationFeatureIsUpdated() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(style.getSourceAs(LOCATION_SOURCE)).thenReturn(locationSource); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - Feature locationFeature = mock(Feature.class); - LocationLayerController layer = new LocationLayerController( - mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(locationFeature, options), - bitmapProvider, options, internalRenderModeChangedListener, false); - layer.setRenderMode(RenderMode.COMPASS); - float compassBearing = 2f; - - getAnimationListener(ANIMATOR_LAYER_COMPASS_BEARING, layer.getAnimationListeners()) - .onNewAnimationValue(compassBearing); - - verify(locationFeature).addNumberProperty(PROPERTY_COMPASS_BEARING, compassBearing); - } - - @Test - public void onNewCompassBearingValue_updateIgnoredWithInvalidRenderMode() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(style.getSourceAs(LOCATION_SOURCE)).thenReturn(locationSource); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - Feature locationFeature = mock(Feature.class); - LocationLayerController layer = new LocationLayerController( - mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(locationFeature, options), - bitmapProvider, options, internalRenderModeChangedListener, false); - layer.setRenderMode(RenderMode.GPS); - float compassBearing = 2f; - - assertNull(getAnimationListener(ANIMATOR_LAYER_COMPASS_BEARING, layer.getAnimationListeners())); - verify(locationFeature, times(0)).addNumberProperty(PROPERTY_COMPASS_BEARING, compassBearing); - } - - @Test - public void onNewAccuracyRadiusValue_locationFeatureIsUpdated() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(style.getSourceAs(LOCATION_SOURCE)).thenReturn(locationSource); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - Feature locationFeature = mock(Feature.class); - LocationLayerController layer = new LocationLayerController( - mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(locationFeature, options), - bitmapProvider, options, internalRenderModeChangedListener, false); - layer.setRenderMode(RenderMode.NORMAL); - float accuracyRadiusValue = 2f; - - getAnimationListener(ANIMATOR_LAYER_ACCURACY, layer.getAnimationListeners()) - .onNewAnimationValue(accuracyRadiusValue); - - verify(locationFeature).addNumberProperty(PROPERTY_ACCURACY_RADIUS, accuracyRadiusValue); - } - - @Test - public void onNewAccuracyRadiusValue_updateIgnoredWithInvalidRenderMode() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(style.getSourceAs(LOCATION_SOURCE)).thenReturn(locationSource); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - Feature locationFeature = mock(Feature.class); - LocationLayerController layer = new LocationLayerController( - mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(locationFeature, options), - bitmapProvider, options, internalRenderModeChangedListener, false); - layer.setRenderMode(RenderMode.GPS); - float accuracyRadiusValue = 2f; - - assertNull(getAnimationListener(ANIMATOR_LAYER_ACCURACY, layer.getAnimationListeners())); - verify(locationFeature, times(0)) - .addNumberProperty(PROPERTY_ACCURACY_RADIUS, accuracyRadiusValue); - } - - @Test - public void renderModeChanged_doNotNotifyAboutDuplicates_NORMAL() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - - LocationLayerController controller = - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener, false); - - controller.setRenderMode(RenderMode.NORMAL); - controller.setRenderMode(RenderMode.NORMAL); - - verify(internalRenderModeChangedListener, times(1)).onRenderModeChanged(RenderMode.NORMAL); - } - - @Test - public void renderModeChanged_doNotNotifyAboutDuplicates_GPS() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - - LocationLayerController controller = - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener, false); - - controller.setRenderMode(RenderMode.GPS); - controller.setRenderMode(RenderMode.GPS); - - verify(internalRenderModeChangedListener, times(1)).onRenderModeChanged(RenderMode.GPS); - } - - @Test - public void layerHidden_renderModeChanged_layerShown_foregroundIconUpdated() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(mock(GeoJsonSource.class)); - LocationComponentOptions options = mock(LocationComponentOptions.class); - int drawableResId = 123; - int tintColor = 456; - when(options.foregroundDrawable()).thenReturn(drawableResId); - when(options.foregroundTintColor()).thenReturn(tintColor); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - Bitmap bitmap = mock(Bitmap.class); - when(bitmapProvider.generateBitmap(drawableResId, tintColor)).thenReturn(bitmap); - - LocationLayerController controller = - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener, false); - - verify(style).addImage(FOREGROUND_ICON, bitmap); - - int drawableGpsResId = 789; - when(options.gpsDrawable()).thenReturn(drawableGpsResId); - - Bitmap bitmapGps = mock(Bitmap.class); - when(bitmapProvider.generateBitmap(drawableGpsResId, tintColor)).thenReturn(bitmapGps); - - controller.hide(); - - controller.setRenderMode(RenderMode.GPS); - - controller.show(); - - verify(style).addImage(FOREGROUND_ICON, bitmapGps); - } - - private LayerFeatureProvider buildFeatureProvider(@NonNull LocationComponentOptions options) { - LayerFeatureProvider provider = mock(LayerFeatureProvider.class); - when(provider.generateLocationFeature(null, options.enableStaleState())).thenReturn(mock(Feature.class)); - return provider; - } - - private LayerFeatureProvider buildFeatureProvider(Feature feature, @NonNull LocationComponentOptions options) { - LayerFeatureProvider provider = mock(LayerFeatureProvider.class); - when(provider.generateLocationFeature(null, options.enableStaleState())).thenReturn(feature); - return provider; - } - - private LayerSourceProvider buildLayerProvider() { - final LayerSourceProvider layerSourceProvider = mock(LayerSourceProvider.class); - when(layerSourceProvider.getIndicatorLocationLayerRenderer()).thenReturn(indicatorRenderer); - when(layerSourceProvider.getSymbolLocationLayerRenderer(any(LayerFeatureProvider.class), anyBoolean())).thenAnswer( - new Answer() { - @Override - public LocationLayerRenderer answer(InvocationOnMock invocation) { - LayerFeatureProvider featureProvider = invocation.getArgument(0); - boolean isStale = invocation.getArgument(1); - return new SymbolLocationLayerRenderer(layerSourceProvider, featureProvider, isStale); - } - } - ); - - Layer shadowLayer = mock(Layer.class); - when(shadowLayer.getId()).thenReturn(SHADOW_LAYER); - when(layerSourceProvider.generateLayer(SHADOW_LAYER)).thenReturn(shadowLayer); - - Layer backgroundLayer = mock(Layer.class); - when(backgroundLayer.getId()).thenReturn(BACKGROUND_LAYER); - when(layerSourceProvider.generateLayer(BACKGROUND_LAYER)).thenReturn(backgroundLayer); - - Layer foregroundLayer = mock(Layer.class); - when(foregroundLayer.getId()).thenReturn(FOREGROUND_LAYER); - when(layerSourceProvider.generateLayer(FOREGROUND_LAYER)).thenReturn(foregroundLayer); - - Layer bearingLayer = mock(Layer.class); - when(bearingLayer.getId()).thenReturn(BEARING_LAYER); - when(layerSourceProvider.generateLayer(BEARING_LAYER)).thenReturn(bearingLayer); - - Layer accuracyLayer = mock(Layer.class); - when(accuracyLayer.getId()).thenReturn(ACCURACY_LAYER); - when(layerSourceProvider.generateAccuracyLayer()).thenReturn(accuracyLayer); - Layer pulsingCircleLayer = mock(Layer.class); - when(pulsingCircleLayer.getId()).thenReturn(PULSING_CIRCLE_LAYER); - when(layerSourceProvider.generatePulsingCircleLayer()).thenReturn(pulsingCircleLayer); - return layerSourceProvider; - } - - private MapboxAnimator.AnimationsValueChangeListener getAnimationListener( - @MapboxAnimator.Type int animatorType, - Set holders) { - for (AnimatorListenerHolder holder : holders) { - @MapboxAnimator.Type int type = holder.getAnimatorType(); - if (type == animatorType) { - return holder.getListener(); - } - } - return null; - } -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationLayerControllerTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationLayerControllerTest.kt new file mode 100644 index 000000000..92302acb6 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationLayerControllerTest.kt @@ -0,0 +1,1504 @@ +package com.mapbox.mapboxsdk.location + +import android.graphics.Bitmap +import com.google.gson.JsonElement +import com.mapbox.geojson.Feature +import com.mapbox.mapboxsdk.geometry.LatLng +import com.mapbox.mapboxsdk.location.MapboxAnimator.AnimationsValueChangeListener +import com.mapbox.mapboxsdk.location.modes.RenderMode +import com.mapbox.mapboxsdk.maps.MapboxMap +import com.mapbox.mapboxsdk.maps.Style +import com.mapbox.mapboxsdk.style.layers.Layer +import com.mapbox.mapboxsdk.style.sources.GeoJsonSource +import junit.framework.Assert +import org.junit.Before +import org.junit.Test +import org.mockito.ArgumentMatchers +import org.mockito.Mockito + +class LocationLayerControllerTest { + private val mapboxMap = Mockito.mock(MapboxMap::class.java) + private val style = Mockito.mock( + Style::class.java + ) + private val indicatorRenderer = Mockito.mock( + LocationLayerRenderer::class.java + ) + + @Before + fun before() { + Mockito.`when`(mapboxMap.style).thenReturn(style) + } + + @Test + fun onInitialization_locationSourceIsAdded() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val sourceProvider = buildLayerProvider() + val locationSource = Mockito.mock(GeoJsonSource::class.java) + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn(locationSource) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + Mockito.verify(style).addSource(locationSource) + } + + @Test + fun onInitialization_shadowLayerIsAdded() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val sourceProvider = buildLayerProvider() + val shadowLayer = Mockito.mock( + Layer::class.java + ) + Mockito.`when`(sourceProvider.generateLayer(LocationComponentConstants.SHADOW_LAYER)) + .thenReturn(shadowLayer) + val locationSource = Mockito.mock(GeoJsonSource::class.java) + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn(locationSource) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + Mockito.verify(style) + .addLayerBelow(shadowLayer, LocationComponentConstants.BACKGROUND_LAYER) + } + + @Test + fun onInitialization_backgroundLayerIsAdded() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val sourceProvider = buildLayerProvider() + val backgroundLayer = Mockito.mock( + Layer::class.java + ) + Mockito.`when`(sourceProvider.generateLayer(LocationComponentConstants.BACKGROUND_LAYER)) + .thenReturn(backgroundLayer) + val locationSource = Mockito.mock(GeoJsonSource::class.java) + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn(locationSource) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + Mockito.verify(style) + .addLayerBelow(backgroundLayer, LocationComponentConstants.FOREGROUND_LAYER) + } + + @Test + fun onInitialization_foregroundLayerIsAdded() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val sourceProvider = buildLayerProvider() + val foregroundLayer = Mockito.mock( + Layer::class.java + ) + Mockito.`when`(sourceProvider.generateLayer(LocationComponentConstants.FOREGROUND_LAYER)) + .thenReturn(foregroundLayer) + val locationSource = Mockito.mock(GeoJsonSource::class.java) + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn(locationSource) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + Mockito.verify(style) + .addLayerBelow(foregroundLayer, LocationComponentConstants.BEARING_LAYER) + } + + @Test + fun onInitialization_bearingLayerIsAdded() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val sourceProvider = buildLayerProvider() + val bearingLayer = Mockito.mock( + Layer::class.java + ) + Mockito.`when`(sourceProvider.generateLayer(LocationComponentConstants.BEARING_LAYER)) + .thenReturn(bearingLayer) + val locationSource = Mockito.mock(GeoJsonSource::class.java) + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn(locationSource) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + val layerBelow = "layer-below" + Mockito.`when`(options.layerBelow()).thenReturn(layerBelow) + LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + Mockito.verify(style).addLayerBelow(bearingLayer, layerBelow) + } + + @Test + fun onInitialization_accuracyLayerIsAdded() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val sourceProvider = buildLayerProvider() + val accuracyLayer = Mockito.mock( + Layer::class.java + ) + Mockito.`when`(sourceProvider.generateAccuracyLayer()).thenReturn(accuracyLayer) + val locationSource = Mockito.mock(GeoJsonSource::class.java) + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn(locationSource) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + Mockito.verify(style) + .addLayerBelow(accuracyLayer, LocationComponentConstants.BACKGROUND_LAYER) + } + + @Test + fun onInitialization_pulsingCircleLayerIsAdded() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val sourceProvider = buildLayerProvider() + val pulsingCircleLayer = Mockito.mock( + Layer::class.java + ) + Mockito.`when`(sourceProvider.generatePulsingCircleLayer()).thenReturn(pulsingCircleLayer) + val locationSource = Mockito.mock(GeoJsonSource::class.java) + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn(locationSource) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + Mockito.verify(style) + .addLayerBelow(pulsingCircleLayer, LocationComponentConstants.ACCURACY_LAYER) + } + + @Test + fun onInitialization_numberOfCachedLayerIdsIsConstant() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val sourceProvider = buildLayerProvider() + val locationSource = Mockito.mock(GeoJsonSource::class.java) + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn(locationSource) + val layerSet: Set = HashSet() + Mockito.`when`(sourceProvider.emptyLayerSet).thenReturn(layerSet) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + val controller = LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + controller.initializeComponents(mapboxMap.style, options) + Assert.assertEquals(6, layerSet.size) + } + + @Test + fun applyStyle_styleShadowWithValidElevation() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val sourceProvider = buildLayerProvider() + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn( + Mockito.mock( + GeoJsonSource::class.java + ) + ) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val bitmap = Mockito.mock(Bitmap::class.java) + Mockito.`when`( + bitmapProvider.generateShadowBitmap( + ArgumentMatchers.any( + LocationComponentOptions::class.java + ) + ) + ).thenReturn(bitmap) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + Mockito.`when`(options.elevation()).thenReturn(2f) + + // Style is applied on initialization + LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + Mockito.verify(style).addImage(LocationComponentConstants.SHADOW_ICON, bitmap) + } + + @Test + fun applyStyle_ignoreStyleShadowWithInvalidElevation() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val sourceProvider = buildLayerProvider() + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn( + Mockito.mock( + GeoJsonSource::class.java + ) + ) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val bitmap = Mockito.mock(Bitmap::class.java) + Mockito.`when`( + bitmapProvider.generateShadowBitmap( + ArgumentMatchers.any( + LocationComponentOptions::class.java + ) + ) + ).thenReturn(bitmap) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + Mockito.`when`(options.elevation()).thenReturn(0f) + LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + Mockito.verify(style, Mockito.times(0)) + .addImage(LocationComponentConstants.SHADOW_ICON, bitmap) + } + + @Test + fun applyStyle_styleForegroundFromOptions() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val sourceProvider = buildLayerProvider() + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn( + Mockito.mock( + GeoJsonSource::class.java + ) + ) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + val drawableResId = 123 + val tintColor = 456 + Mockito.`when`(options.foregroundDrawable()).thenReturn(drawableResId) + Mockito.`when`(options.foregroundTintColor()).thenReturn(tintColor) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val bitmap = Mockito.mock(Bitmap::class.java) + Mockito.`when`(bitmapProvider.generateBitmap(drawableResId, tintColor)).thenReturn(bitmap) + LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + Mockito.verify(style).addImage(LocationComponentConstants.FOREGROUND_ICON, bitmap) + } + + @Test + fun applyStyle_styleForegroundStaleFromOptions() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val sourceProvider = buildLayerProvider() + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn( + Mockito.mock( + GeoJsonSource::class.java + ) + ) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + val drawableResId = 123 + val tintColor = 456 + Mockito.`when`(options.foregroundDrawableStale()).thenReturn(drawableResId) + Mockito.`when`(options.foregroundStaleTintColor()).thenReturn(tintColor) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val bitmap = Mockito.mock(Bitmap::class.java) + Mockito.`when`(bitmapProvider.generateBitmap(drawableResId, tintColor)).thenReturn(bitmap) + LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + Mockito.verify(style).addImage(LocationComponentConstants.FOREGROUND_STALE_ICON, bitmap) + } + + @Test + fun applyStyle_styleBackgroundFromOptions() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val sourceProvider = buildLayerProvider() + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn( + Mockito.mock( + GeoJsonSource::class.java + ) + ) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + val drawableResId = 123 + val tintColor = 456 + Mockito.`when`(options.backgroundDrawable()).thenReturn(drawableResId) + Mockito.`when`(options.backgroundTintColor()).thenReturn(tintColor) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val bitmap = Mockito.mock(Bitmap::class.java) + Mockito.`when`(bitmapProvider.generateBitmap(drawableResId, tintColor)).thenReturn(bitmap) + LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + Mockito.verify(style).addImage(LocationComponentConstants.BACKGROUND_ICON, bitmap) + } + + @Test + fun applyStyle_styleBackgroundStaleFromOptions() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val sourceProvider = buildLayerProvider() + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn( + Mockito.mock( + GeoJsonSource::class.java + ) + ) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + val drawableResId = 123 + val tintColor = 456 + Mockito.`when`(options.backgroundDrawableStale()).thenReturn(drawableResId) + Mockito.`when`(options.backgroundStaleTintColor()).thenReturn(tintColor) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val bitmap = Mockito.mock(Bitmap::class.java) + Mockito.`when`(bitmapProvider.generateBitmap(drawableResId, tintColor)).thenReturn(bitmap) + LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + Mockito.verify(style).addImage(LocationComponentConstants.BACKGROUND_STALE_ICON, bitmap) + } + + @Test + fun applyStyle_styleBearingFromOptions() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val sourceProvider = buildLayerProvider() + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn( + Mockito.mock( + GeoJsonSource::class.java + ) + ) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + val drawableResId = 123 + val tintColor = 456 + Mockito.`when`(options.bearingDrawable()).thenReturn(drawableResId) + Mockito.`when`(options.bearingTintColor()).thenReturn(tintColor) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val bitmap = Mockito.mock(Bitmap::class.java) + Mockito.`when`(bitmapProvider.generateBitmap(drawableResId, tintColor)).thenReturn(bitmap) + LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + Mockito.verify(style).addImage(LocationComponentConstants.BEARING_ICON, bitmap) + } + + @Test + fun applyStyle_specializedLayer_ignoreBitmapNames() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val sourceProvider = buildLayerProvider() + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + Mockito.`when`(options.foregroundName()).thenReturn("new_name") + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(options), + bitmapProvider, + options, + internalRenderModeChangedListener, + true + ) + Mockito.verify(indicatorRenderer).updateIconIds( + ArgumentMatchers.eq(LocationComponentConstants.FOREGROUND_ICON), + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString() + ) + } + + @Test + fun applyStyle_layerBelowChanged() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val sourceProvider = buildLayerProvider() + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn( + Mockito.mock( + GeoJsonSource::class.java + ) + ) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val bitmap = Mockito.mock(Bitmap::class.java) + Mockito.`when`( + bitmapProvider.generateShadowBitmap( + ArgumentMatchers.any( + LocationComponentOptions::class.java + ) + ) + ).thenReturn(bitmap) + val layerController = LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + val bearingLayer2 = Mockito.mock( + Layer::class.java + ) + Mockito.`when`(sourceProvider.generateLayer(LocationComponentConstants.BEARING_LAYER)) + .thenReturn(bearingLayer2) + val foregroundLayer2 = Mockito.mock( + Layer::class.java + ) + Mockito.`when`(sourceProvider.generateLayer(LocationComponentConstants.FOREGROUND_LAYER)) + .thenReturn(foregroundLayer2) + val backgroundLayer2 = Mockito.mock( + Layer::class.java + ) + Mockito.`when`(sourceProvider.generateLayer(LocationComponentConstants.BACKGROUND_LAYER)) + .thenReturn(backgroundLayer2) + val shadowLayer2 = Mockito.mock( + Layer::class.java + ) + Mockito.`when`(sourceProvider.generateLayer(LocationComponentConstants.SHADOW_LAYER)) + .thenReturn(shadowLayer2) + val accuracyLayer2 = Mockito.mock( + Layer::class.java + ) + Mockito.`when`(sourceProvider.generateAccuracyLayer()).thenReturn(accuracyLayer2) + val layerBelow = "layer-below" + Mockito.`when`(options.layerBelow()).thenReturn(layerBelow) + layerController.applyStyle(options) + Mockito.verify(style).removeLayer(LocationComponentConstants.BEARING_LAYER) + Mockito.verify(style).removeLayer(LocationComponentConstants.FOREGROUND_LAYER) + Mockito.verify(style).removeLayer(LocationComponentConstants.BACKGROUND_LAYER) + Mockito.verify(style).removeLayer(LocationComponentConstants.SHADOW_LAYER) + Mockito.verify(style).removeLayer(LocationComponentConstants.ACCURACY_LAYER) + Mockito.verify(style).addLayerBelow(bearingLayer2, layerBelow) + Mockito.verify(style) + .addLayerBelow(foregroundLayer2, LocationComponentConstants.BEARING_LAYER) + Mockito.verify(style) + .addLayerBelow(backgroundLayer2, LocationComponentConstants.FOREGROUND_LAYER) + Mockito.verify(style) + .addLayerBelow(shadowLayer2, LocationComponentConstants.BACKGROUND_LAYER) + Mockito.verify(style) + .addLayerBelow(accuracyLayer2, LocationComponentConstants.BACKGROUND_LAYER) + } + + @Test + fun applyStyle_layerBelowNotChanged() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val sourceProvider = buildLayerProvider() + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn( + Mockito.mock( + GeoJsonSource::class.java + ) + ) + var options = Mockito.mock( + LocationComponentOptions::class.java + ) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val bitmap = Mockito.mock(Bitmap::class.java) + Mockito.`when`( + bitmapProvider.generateShadowBitmap( + ArgumentMatchers.any( + LocationComponentOptions::class.java + ) + ) + ).thenReturn(bitmap) + var layerBelow = "layer-below" + Mockito.`when`(options.layerBelow()).thenReturn(layerBelow) + val layerController = LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + options = Mockito.mock(LocationComponentOptions::class.java) + layerBelow = "layer-below" + Mockito.`when`(options.layerBelow()).thenReturn(layerBelow) + layerController.applyStyle(options) + Mockito.verify(style, Mockito.times(0)).removeLayer( + ArgumentMatchers.any( + String::class.java + ) + ) + Mockito.verify(style, Mockito.times(6)).addLayerBelow( + ArgumentMatchers.any( + Layer::class.java + ), + ArgumentMatchers.any( + String::class.java + ) + ) + } + + @Test + fun applyStyle_layerBelowNotChangedNull() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val sourceProvider = buildLayerProvider() + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn( + Mockito.mock( + GeoJsonSource::class.java + ) + ) + var options = Mockito.mock( + LocationComponentOptions::class.java + ) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val bitmap = Mockito.mock(Bitmap::class.java) + Mockito.`when`( + bitmapProvider.generateShadowBitmap( + ArgumentMatchers.any( + LocationComponentOptions::class.java + ) + ) + ).thenReturn(bitmap) + val layerController = LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + options = Mockito.mock(LocationComponentOptions::class.java) + layerController.applyStyle(options) + Mockito.verify(style, Mockito.times(0)).removeLayer( + ArgumentMatchers.any( + String::class.java + ) + ) + Mockito.verify(style, Mockito.times(1)).addLayer( + ArgumentMatchers.any( + Layer::class.java + ) + ) + Mockito.verify(style, Mockito.times(5)).addLayerBelow( + ArgumentMatchers.any( + Layer::class.java + ), + Mockito.any() + ) + } + + @Test + fun updateForegroundOffset_foregroundIconPropertyIsUpdated() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val sourceProvider = buildLayerProvider() + val locationSource = Mockito.mock(GeoJsonSource::class.java) + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn(locationSource) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + val locationFeature = Mockito.mock( + Feature::class.java + ) + val layer = LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(locationFeature, options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + layer.cameraTiltUpdated(2.0) + Mockito.verify(locationFeature).addProperty( + ArgumentMatchers.eq(LocationComponentConstants.PROPERTY_FOREGROUND_ICON_OFFSET), + ArgumentMatchers.any( + JsonElement::class.java + ) + ) + } + + @Test + fun updateForegroundOffset_shadowPropertyIsUpdated() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val sourceProvider = buildLayerProvider() + val locationSource = Mockito.mock(GeoJsonSource::class.java) + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn(locationSource) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + val locationFeature = Mockito.mock( + Feature::class.java + ) + val layer = LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(locationFeature, options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + layer.cameraTiltUpdated(2.0) + Mockito.verify(locationFeature).addProperty( + ArgumentMatchers.eq(LocationComponentConstants.PROPERTY_SHADOW_ICON_OFFSET), + ArgumentMatchers.any( + JsonElement::class.java + ) + ) + } + + @Test + fun onNewLatLngValue_locationFeatureIsUpdated() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val locationSource = Mockito.mock(GeoJsonSource::class.java) + Mockito.`when`(style.getSourceAs(LocationComponentConstants.LOCATION_SOURCE)) + .thenReturn(locationSource) + val sourceProvider = buildLayerProvider() + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn(locationSource) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + val locationFeature = Mockito.mock( + Feature::class.java + ) + val layer = LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(locationFeature, options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + getAnimationListener( + MapboxAnimator.ANIMATOR_LAYER_LATLNG, + layer.animationListeners + )!!.onNewAnimationValue(LatLng()) + + // wanted twice (once for initialization) + Mockito.verify(locationSource, Mockito.times(2)).setGeoJson(locationFeature) + } + + @Test + fun onNewGpsBearingValue_locationFeatureIsUpdated() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val locationSource = Mockito.mock(GeoJsonSource::class.java) + Mockito.`when`(style.getSourceAs(LocationComponentConstants.LOCATION_SOURCE)) + .thenReturn(locationSource) + val sourceProvider = buildLayerProvider() + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn(locationSource) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + val locationFeature = Mockito.mock( + Feature::class.java + ) + val layer = LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(locationFeature, options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + layer.renderMode = RenderMode.GPS + val gpsBearing = 2f + getAnimationListener( + MapboxAnimator.ANIMATOR_LAYER_GPS_BEARING, + layer.animationListeners + )!!.onNewAnimationValue(gpsBearing) + Mockito.verify(locationFeature) + .addNumberProperty(LocationComponentConstants.PROPERTY_GPS_BEARING, gpsBearing) + } + + @Test + fun onNewGpsBearingValue_updateIgnoredWithInvalidRenderMode() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val locationSource = Mockito.mock(GeoJsonSource::class.java) + Mockito.`when`(style.getSourceAs(LocationComponentConstants.LOCATION_SOURCE)) + .thenReturn(locationSource) + val sourceProvider = buildLayerProvider() + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn(locationSource) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + val locationFeature = Mockito.mock( + Feature::class.java + ) + val layer = LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(locationFeature, options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + layer.renderMode = RenderMode.COMPASS + val gpsBearing = 2f + Assert.assertNull( + getAnimationListener( + MapboxAnimator.ANIMATOR_LAYER_GPS_BEARING, + layer.animationListeners + ) + ) + Mockito.verify(locationFeature, Mockito.times(0)) + .addNumberProperty(LocationComponentConstants.PROPERTY_GPS_BEARING, gpsBearing) + } + + @Test + fun onNewCompassBearingValue_locationFeatureIsUpdated() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val locationSource = Mockito.mock(GeoJsonSource::class.java) + Mockito.`when`(style.getSourceAs(LocationComponentConstants.LOCATION_SOURCE)) + .thenReturn(locationSource) + val sourceProvider = buildLayerProvider() + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn(locationSource) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + val locationFeature = Mockito.mock( + Feature::class.java + ) + val layer = LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(locationFeature, options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + layer.renderMode = RenderMode.COMPASS + val compassBearing = 2f + getAnimationListener( + MapboxAnimator.ANIMATOR_LAYER_COMPASS_BEARING, + layer.animationListeners + ) + ?.onNewAnimationValue(compassBearing) + Mockito.verify(locationFeature) + .addNumberProperty(LocationComponentConstants.PROPERTY_COMPASS_BEARING, compassBearing) + } + + @Test + fun onNewCompassBearingValue_updateIgnoredWithInvalidRenderMode() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val locationSource = Mockito.mock(GeoJsonSource::class.java) + Mockito.`when`(style.getSourceAs(LocationComponentConstants.LOCATION_SOURCE)) + .thenReturn(locationSource) + val sourceProvider = buildLayerProvider() + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn(locationSource) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + val locationFeature = Mockito.mock( + Feature::class.java + ) + val layer = LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(locationFeature, options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + layer.renderMode = RenderMode.GPS + val compassBearing = 2f + Assert.assertNull( + getAnimationListener( + MapboxAnimator.ANIMATOR_LAYER_COMPASS_BEARING, + layer.animationListeners + ) + ) + Mockito.verify(locationFeature, Mockito.times(0)) + .addNumberProperty(LocationComponentConstants.PROPERTY_COMPASS_BEARING, compassBearing) + } + + @Test + fun onNewAccuracyRadiusValue_locationFeatureIsUpdated() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val locationSource = Mockito.mock(GeoJsonSource::class.java) + Mockito.`when`(style.getSourceAs(LocationComponentConstants.LOCATION_SOURCE)) + .thenReturn(locationSource) + val sourceProvider = buildLayerProvider() + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn(locationSource) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + val locationFeature = Mockito.mock( + Feature::class.java + ) + val layer = LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(locationFeature, options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + layer.renderMode = RenderMode.NORMAL + val accuracyRadiusValue = 2f + getAnimationListener(MapboxAnimator.ANIMATOR_LAYER_ACCURACY, layer.animationListeners) + ?.onNewAnimationValue(accuracyRadiusValue) + Mockito.verify(locationFeature).addNumberProperty( + LocationComponentConstants.PROPERTY_ACCURACY_RADIUS, + accuracyRadiusValue + ) + } + + @Test + fun onNewAccuracyRadiusValue_updateIgnoredWithInvalidRenderMode() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val locationSource = Mockito.mock(GeoJsonSource::class.java) + Mockito.`when`(style.getSourceAs(LocationComponentConstants.LOCATION_SOURCE)) + .thenReturn(locationSource) + val sourceProvider = buildLayerProvider() + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn(locationSource) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + val locationFeature = Mockito.mock( + Feature::class.java + ) + val layer = LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(locationFeature, options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + layer.renderMode = RenderMode.GPS + val accuracyRadiusValue = 2f + Assert.assertNull( + getAnimationListener( + MapboxAnimator.ANIMATOR_LAYER_ACCURACY, + layer.animationListeners + ) + ) + Mockito.verify(locationFeature, Mockito.times(0)) + .addNumberProperty( + LocationComponentConstants.PROPERTY_ACCURACY_RADIUS, + accuracyRadiusValue + ) + } + + @Test + fun renderModeChanged_doNotNotifyAboutDuplicates_NORMAL() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val sourceProvider = buildLayerProvider() + val locationSource = Mockito.mock(GeoJsonSource::class.java) + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn(locationSource) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + val controller = LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + controller.renderMode = RenderMode.NORMAL + controller.renderMode = RenderMode.NORMAL + Mockito.verify(internalRenderModeChangedListener, Mockito.times(1)).onRenderModeChanged( + RenderMode.NORMAL + ) + } + + @Test + fun renderModeChanged_doNotNotifyAboutDuplicates_GPS() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val sourceProvider = buildLayerProvider() + val locationSource = Mockito.mock(GeoJsonSource::class.java) + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn(locationSource) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + val controller = LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + controller.renderMode = RenderMode.GPS + controller.renderMode = RenderMode.GPS + Mockito.verify(internalRenderModeChangedListener, Mockito.times(1)).onRenderModeChanged( + RenderMode.GPS + ) + } + + @Test + fun layerHidden_renderModeChanged_layerShown_foregroundIconUpdated() { + val internalRenderModeChangedListener = Mockito.mock( + OnRenderModeChangedListener::class.java + ) + val sourceProvider = buildLayerProvider() + Mockito.`when`( + sourceProvider.generateSource( + ArgumentMatchers.any( + Feature::class.java + ) + ) + ).thenReturn( + Mockito.mock( + GeoJsonSource::class.java + ) + ) + val options = Mockito.mock( + LocationComponentOptions::class.java + ) + val drawableResId = 123 + val tintColor = 456 + Mockito.`when`(options.foregroundDrawable()).thenReturn(drawableResId) + Mockito.`when`(options.foregroundTintColor()).thenReturn(tintColor) + val bitmapProvider = Mockito.mock( + LayerBitmapProvider::class.java + ) + val bitmap = Mockito.mock(Bitmap::class.java) + Mockito.`when`(bitmapProvider.generateBitmap(drawableResId, tintColor)).thenReturn(bitmap) + val controller = LocationLayerController( + mapboxMap, + mapboxMap.style, + sourceProvider, + buildFeatureProvider(options), + bitmapProvider, + options, + internalRenderModeChangedListener, + false + ) + Mockito.verify(style).addImage(LocationComponentConstants.FOREGROUND_ICON, bitmap) + val drawableGpsResId = 789 + Mockito.`when`(options.gpsDrawable()).thenReturn(drawableGpsResId) + val bitmapGps = Mockito.mock(Bitmap::class.java) + Mockito.`when`(bitmapProvider.generateBitmap(drawableGpsResId, tintColor)) + .thenReturn(bitmapGps) + controller.hide() + controller.renderMode = RenderMode.GPS + controller.show() + Mockito.verify(style).addImage(LocationComponentConstants.FOREGROUND_ICON, bitmapGps) + } + + private fun buildFeatureProvider(options: LocationComponentOptions): LayerFeatureProvider { + val provider = Mockito.mock( + LayerFeatureProvider::class.java + ) + Mockito.`when`(provider.generateLocationFeature(null, options.enableStaleState())) + .thenReturn( + Mockito.mock( + Feature::class.java + ) + ) + return provider + } + + private fun buildFeatureProvider( + feature: Feature, + options: LocationComponentOptions + ): LayerFeatureProvider { + val provider = Mockito.mock( + LayerFeatureProvider::class.java + ) + Mockito.`when`(provider.generateLocationFeature(null, options.enableStaleState())) + .thenReturn(feature) + return provider + } + + private fun buildLayerProvider(): LayerSourceProvider { + val layerSourceProvider = Mockito.mock( + LayerSourceProvider::class.java + ) + Mockito.`when`(layerSourceProvider.indicatorLocationLayerRenderer) + .thenReturn(indicatorRenderer) + Mockito.`when`( + layerSourceProvider.getSymbolLocationLayerRenderer( + ArgumentMatchers.any( + LayerFeatureProvider::class.java + ), + ArgumentMatchers.anyBoolean() + ) + ).thenAnswer { invocation -> + val featureProvider = invocation.getArgument(0) + val isStale = invocation.getArgument(1) + SymbolLocationLayerRenderer(layerSourceProvider, featureProvider, isStale) + } + val shadowLayer = Mockito.mock( + Layer::class.java + ) + Mockito.`when`(shadowLayer.id).thenReturn(LocationComponentConstants.SHADOW_LAYER) + Mockito.`when`(layerSourceProvider.generateLayer(LocationComponentConstants.SHADOW_LAYER)) + .thenReturn(shadowLayer) + val backgroundLayer = Mockito.mock( + Layer::class.java + ) + Mockito.`when`(backgroundLayer.id).thenReturn(LocationComponentConstants.BACKGROUND_LAYER) + Mockito.`when`(layerSourceProvider.generateLayer(LocationComponentConstants.BACKGROUND_LAYER)) + .thenReturn(backgroundLayer) + val foregroundLayer = Mockito.mock( + Layer::class.java + ) + Mockito.`when`(foregroundLayer.id).thenReturn(LocationComponentConstants.FOREGROUND_LAYER) + Mockito.`when`(layerSourceProvider.generateLayer(LocationComponentConstants.FOREGROUND_LAYER)) + .thenReturn(foregroundLayer) + val bearingLayer = Mockito.mock( + Layer::class.java + ) + Mockito.`when`(bearingLayer.id).thenReturn(LocationComponentConstants.BEARING_LAYER) + Mockito.`when`(layerSourceProvider.generateLayer(LocationComponentConstants.BEARING_LAYER)) + .thenReturn(bearingLayer) + val accuracyLayer = Mockito.mock( + Layer::class.java + ) + Mockito.`when`(accuracyLayer.id).thenReturn(LocationComponentConstants.ACCURACY_LAYER) + Mockito.`when`(layerSourceProvider.generateAccuracyLayer()).thenReturn(accuracyLayer) + val pulsingCircleLayer = Mockito.mock( + Layer::class.java + ) + Mockito.`when`(pulsingCircleLayer.id) + .thenReturn(LocationComponentConstants.PULSING_CIRCLE_LAYER) + Mockito.`when`(layerSourceProvider.generatePulsingCircleLayer()) + .thenReturn(pulsingCircleLayer) + return layerSourceProvider + } + + private fun getAnimationListener( + @MapboxAnimator.Type animatorType: Int, + holders: Set + ): AnimationsValueChangeListener? { + for (holder in holders) { + @MapboxAnimator.Type val type = holder.animatorType + if (type == animatorType) { + return holder.listener + } + } + return null + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/UtilsTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/UtilsTest.java deleted file mode 100644 index bf5ee40f4..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/UtilsTest.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import org.junit.Test; - -import static junit.framework.Assert.assertEquals; - -public final class UtilsTest { - - @Test - public void shortestRotation_doesReturnValueDistanceQuickestToZero() throws Exception { - float value = Utils.shortestRotation(0, 181); - assertEquals(360f, value); - value = Utils.shortestRotation(0, 179); - assertEquals(0f, value); - value = Utils.shortestRotation(0, 180); - assertEquals(0f, value); - } - - @Test - public void shortestRotation_doesReturnValueDistanceQuickestToFifty() throws Exception { - float value = Utils.shortestRotation(50, 231); - assertEquals(410f, value); - value = Utils.shortestRotation(50, 229); - assertEquals(50f, value); - value = Utils.shortestRotation(50, 180); - assertEquals(50f, value); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/UtilsTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/UtilsTest.kt new file mode 100644 index 000000000..71fea6eb4 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/UtilsTest.kt @@ -0,0 +1,28 @@ +package com.mapbox.mapboxsdk.location + +import junit.framework.Assert +import org.junit.Test + +class UtilsTest { + @Test + @Throws(Exception::class) + fun shortestRotation_doesReturnValueDistanceQuickestToZero() { + var value = Utils.shortestRotation(0f, 181f) + Assert.assertEquals(360f, value) + value = Utils.shortestRotation(0f, 179f) + Assert.assertEquals(0f, value) + value = Utils.shortestRotation(0f, 180f) + Assert.assertEquals(0f, value) + } + + @Test + @Throws(Exception::class) + fun shortestRotation_doesReturnValueDistanceQuickestToFifty() { + var value = Utils.shortestRotation(50f, 231f) + Assert.assertEquals(410f, value) + value = Utils.shortestRotation(50f, 229f) + Assert.assertEquals(50f, value) + value = Utils.shortestRotation(50f, 180f) + Assert.assertEquals(50f, value) + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/AnnotationManagerTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/AnnotationManagerTest.java deleted file mode 100644 index 21855fe4f..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/AnnotationManagerTest.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import androidx.collection.LongSparseArray; - -import com.mapbox.mapboxsdk.annotations.Annotation; -import com.mapbox.mapboxsdk.annotations.BaseMarkerOptions; -import com.mapbox.mapboxsdk.annotations.Marker; -import com.mapbox.mapboxsdk.annotations.MarkerOptions; -import com.mapbox.mapboxsdk.geometry.LatLng; - -import org.junit.Test; -import org.mockito.ArgumentMatchers; - -import java.util.ArrayList; -import java.util.List; - -import static junit.framework.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class AnnotationManagerTest { - - @Test - public void checksAddAMarker() throws Exception { - NativeMap aNativeMapView = mock(NativeMapView.class); - MapView aMapView = mock(MapView.class); - LongSparseArray annotationsArray = new LongSparseArray<>(); - IconManager aIconManager = mock(IconManager.class); - Annotations annotations = new AnnotationContainer(aNativeMapView, annotationsArray); - Markers markers = new MarkerContainer(aNativeMapView, annotationsArray, aIconManager); - Polygons polygons = new PolygonContainer(aNativeMapView, annotationsArray); - Polylines polylines = new PolylineContainer(aNativeMapView, annotationsArray); - ShapeAnnotations shapeAnnotations = new ShapeAnnotationContainer(aNativeMapView, annotationsArray); - AnnotationManager annotationManager = new AnnotationManager(aMapView, annotationsArray, - aIconManager, annotations, markers, polygons, polylines, shapeAnnotations); - Marker aMarker = mock(Marker.class); - long aId = 5L; - when(aNativeMapView.addMarker(aMarker)).thenReturn(aId); - BaseMarkerOptions aMarkerOptions = mock(BaseMarkerOptions.class); - MapboxMap aMapboxMap = mock(MapboxMap.class); - when(aMarkerOptions.getMarker()).thenReturn(aMarker); - - annotationManager.addMarker(aMarkerOptions, aMapboxMap); - - assertEquals(aMarker, annotationManager.getAnnotations().get(0)); - assertEquals(aMarker, annotationManager.getAnnotation(aId)); - } - - @Test - public void checksAddMarkers() throws Exception { - NativeMapView aNativeMapView = mock(NativeMapView.class); - MapView aMapView = mock(MapView.class); - LongSparseArray annotationsArray = new LongSparseArray<>(); - IconManager aIconManager = mock(IconManager.class); - Annotations annotations = new AnnotationContainer(aNativeMapView, annotationsArray); - Markers markers = new MarkerContainer(aNativeMapView, annotationsArray, aIconManager); - Polygons polygons = new PolygonContainer(aNativeMapView, annotationsArray); - Polylines polylines = new PolylineContainer(aNativeMapView, annotationsArray); - ShapeAnnotations shapeAnnotations = new ShapeAnnotationContainer(aNativeMapView, annotationsArray); - AnnotationManager annotationManager = new AnnotationManager(aMapView, annotationsArray, - aIconManager, annotations, markers, polygons, polylines, shapeAnnotations); - - long firstId = 1L; - long secondId = 2L; - List markerList = new ArrayList<>(); - MarkerOptions firstMarkerOption = new MarkerOptions().position(new LatLng()).title("first"); - MarkerOptions secondMarkerOption = new MarkerOptions().position(new LatLng()).title("second"); - - markerList.add(firstMarkerOption); - markerList.add(secondMarkerOption); - MapboxMap aMapboxMap = mock(MapboxMap.class); - when(aNativeMapView.addMarker(any(Marker.class))).thenReturn(firstId, secondId); - - when(aNativeMapView.addMarkers(ArgumentMatchers.anyList())) - .thenReturn(new long[] {firstId, secondId}); - - annotationManager.addMarkers(markerList, aMapboxMap); - - assertEquals(2, annotationManager.getAnnotations().size()); - assertEquals("first", ((Marker) annotationManager.getAnnotations().get(0)).getTitle()); - assertEquals("second", ((Marker) annotationManager.getAnnotations().get(1)).getTitle()); - assertEquals("first", ((Marker) annotationManager.getAnnotation(firstId)).getTitle()); - assertEquals("second", ((Marker) annotationManager.getAnnotation(secondId)).getTitle()); - } -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/AnnotationManagerTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/AnnotationManagerTest.kt new file mode 100644 index 000000000..21c6ea29e --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/AnnotationManagerTest.kt @@ -0,0 +1,104 @@ +package com.mapbox.mapboxsdk.maps + +import androidx.collection.LongSparseArray +import com.mapbox.mapboxsdk.annotations.Annotation +import com.mapbox.mapboxsdk.annotations.BaseMarkerOptions +import com.mapbox.mapboxsdk.annotations.Marker +import com.mapbox.mapboxsdk.annotations.MarkerOptions +import com.mapbox.mapboxsdk.geometry.LatLng +import junit.framework.Assert +import org.junit.Test +import org.mockito.ArgumentMatchers +import org.mockito.Mockito + +class AnnotationManagerTest { + @Test + @Throws(Exception::class) + fun checksAddAMarker() { + val aNativeMapView: NativeMap = Mockito.mock(NativeMapView::class.java) + val aMapView = Mockito.mock(MapView::class.java) + val annotationsArray = LongSparseArray() + val aIconManager = Mockito.mock( + IconManager::class.java + ) + val annotations: Annotations = AnnotationContainer(aNativeMapView, annotationsArray) + val markers: Markers = MarkerContainer(aNativeMapView, annotationsArray, aIconManager) + val polygons: Polygons = PolygonContainer(aNativeMapView, annotationsArray) + val polylines: Polylines = PolylineContainer(aNativeMapView, annotationsArray) + val shapeAnnotations: ShapeAnnotations = + ShapeAnnotationContainer(aNativeMapView, annotationsArray) + val annotationManager = AnnotationManager( + aMapView, + annotationsArray, + aIconManager, + annotations, + markers, + polygons, + polylines, + shapeAnnotations + ) + val aMarker = Mockito.mock( + Marker::class.java + ) + val aId = 5L + Mockito.`when`(aNativeMapView.addMarker(aMarker)).thenReturn(aId) + val aMarkerOptions = Mockito.mock( + BaseMarkerOptions::class.java + ) + val aMapboxMap = Mockito.mock(MapboxMap::class.java) + Mockito.`when`(aMarkerOptions.marker).thenReturn(aMarker) + annotationManager.addMarker(aMarkerOptions, aMapboxMap) + Assert.assertEquals(aMarker, annotationManager.annotations[0]) + Assert.assertEquals(aMarker, annotationManager.getAnnotation(aId)) + } + + @Test + @Throws(Exception::class) + fun checksAddMarkers() { + val aNativeMapView = Mockito.mock(NativeMapView::class.java) + val aMapView = Mockito.mock(MapView::class.java) + val annotationsArray = LongSparseArray() + val aIconManager = Mockito.mock( + IconManager::class.java + ) + val annotations: Annotations = AnnotationContainer(aNativeMapView, annotationsArray) + val markers: Markers = MarkerContainer(aNativeMapView, annotationsArray, aIconManager) + val polygons: Polygons = PolygonContainer(aNativeMapView, annotationsArray) + val polylines: Polylines = PolylineContainer(aNativeMapView, annotationsArray) + val shapeAnnotations: ShapeAnnotations = + ShapeAnnotationContainer(aNativeMapView, annotationsArray) + val annotationManager = AnnotationManager( + aMapView, + annotationsArray, + aIconManager, + annotations, + markers, + polygons, + polylines, + shapeAnnotations + ) + val firstId = 1L + val secondId = 2L + val markerList: MutableList> = ArrayList() + val firstMarkerOption = MarkerOptions().position(LatLng()).title("first") + val secondMarkerOption = MarkerOptions().position(LatLng()).title("second") + markerList.add(firstMarkerOption) + markerList.add(secondMarkerOption) + val aMapboxMap = Mockito.mock(MapboxMap::class.java) + Mockito.`when`( + aNativeMapView.addMarker( + ArgumentMatchers.any( + Marker::class.java + ) + ) + ).thenReturn(firstId, secondId) + Mockito.`when`(aNativeMapView.addMarkers(ArgumentMatchers.anyList())) + .thenReturn(longArrayOf(firstId, secondId)) + annotationManager.addMarkers(markerList, aMapboxMap) + Assert.assertEquals(2, annotationManager.annotations.size) + Assert.assertEquals("first", (annotationManager.annotations[0] as Marker).title) + Assert.assertEquals("second", (annotationManager.annotations[1] as Marker).title) + Assert.assertEquals("first", (annotationManager.getAnnotation(firstId) as Marker).title) + Assert.assertEquals("second", (annotationManager.getAnnotation(secondId) as Marker).title) + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/AttributionDialogManagerTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/AttributionDialogManagerTest.java deleted file mode 100644 index 24b66c3ad..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/AttributionDialogManagerTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.content.Context; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.robolectric.RobolectricTestRunner; - -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.mock; - -@RunWith(RobolectricTestRunner.class) -public class AttributionDialogManagerTest { - @InjectMocks - Context context = mock(Context.class); - - @InjectMocks - MapboxMap mapboxMap = mock(MapboxMap.class); - - @InjectMocks - Style style = mock(Style.class); - - private AttributionDialogManager attributionDialogManager; - - @Before - public void beforeTest() { - attributionDialogManager = new AttributionDialogManager(context, mapboxMap); - } - - @Test - public void testSanity() { - assertNotNull("AttributionDialogManager should not be null", attributionDialogManager); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/AttributionDialogManagerTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/AttributionDialogManagerTest.kt new file mode 100644 index 000000000..4b5a846c0 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/AttributionDialogManagerTest.kt @@ -0,0 +1,40 @@ +package com.mapbox.mapboxsdk.maps + +import android.content.Context +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.InjectMocks +import org.mockito.Mockito +import org.robolectric.RobolectricTestRunner + +@RunWith(RobolectricTestRunner::class) +class AttributionDialogManagerTest { + @InjectMocks + var context = Mockito.mock( + Context::class.java + ) + + @InjectMocks + var mapboxMap = Mockito.mock(MapboxMap::class.java) + + @InjectMocks + var style = Mockito.mock( + Style::class.java + ) + private var attributionDialogManager: AttributionDialogManager? = null + + @Before + fun beforeTest() { + attributionDialogManager = AttributionDialogManager(context, mapboxMap) + } + + @Test + fun testSanity() { + Assert.assertNotNull( + "AttributionDialogManager should not be null", + attributionDialogManager + ) + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapChangeReceiverTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapChangeReceiverTest.java deleted file mode 100644 index 025f06752..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapChangeReceiverTest.java +++ /dev/null @@ -1,586 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import com.google.common.util.concurrent.ExecutionError; -import com.mapbox.mapboxsdk.log.Logger; -import com.mapbox.mapboxsdk.log.LoggerDefinition; - -import junit.framework.Assert; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.verify; - -/** - * Tests integration of MapChangeDispatcher and see if events are correctly forwarded. - */ -public class MapChangeReceiverTest { - - private static final String TEST_STRING = "mapChangeRandom"; - - private MapChangeReceiver mapChangeEventManager; - - @Mock - private MapView.OnCameraWillChangeListener onCameraWillChangeListener; - - @Mock - private MapView.OnCameraDidChangeListener onCameraDidChangeListener; - - @Mock - private MapView.OnCameraIsChangingListener onCameraIsChangingListener; - - @Mock - private MapView.OnWillStartLoadingMapListener onWillStartLoadingMapListener; - - @Mock - private MapView.OnDidFinishLoadingMapListener onDidFinishLoadingMapListener; - - @Mock - private MapView.OnDidFailLoadingMapListener onDidFailLoadingMapListener; - - @Mock - private MapView.OnWillStartRenderingFrameListener onWillStartRenderingFrameListener; - - @Mock - private MapView.OnDidFinishRenderingFrameListener onDidFinishRenderingFrameListener; - - @Mock - private MapView.OnWillStartRenderingMapListener onWillStartRenderingMapListener; - - @Mock - private MapView.OnDidFinishRenderingMapListener onDidFinishRenderingMapListener; - - @Mock - private MapView.OnDidBecomeIdleListener onDidBecomeIdleListener; - - @Mock - private MapView.OnDidFinishLoadingStyleListener onDidFinishLoadingStyleListener; - - @Mock - private MapView.OnSourceChangedListener onSourceChangedListener; - - @Mock - private LoggerDefinition loggerDefinition; - - @Before - public void beforeTest() { - MockitoAnnotations.initMocks(this); - mapChangeEventManager = new MapChangeReceiver(); - } - - @Test - public void testOnCameraRegionWillChangeListener() { - mapChangeEventManager.addOnCameraWillChangeListener(onCameraWillChangeListener); - mapChangeEventManager.onCameraWillChange(false); - verify(onCameraWillChangeListener).onCameraWillChange(false); - - mapChangeEventManager.removeOnCameraWillChangeListener(onCameraWillChangeListener); - mapChangeEventManager.onCameraWillChange(false); - verify(onCameraWillChangeListener).onCameraWillChange(false); - - mapChangeEventManager.addOnCameraWillChangeListener(onCameraWillChangeListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onCameraWillChangeListener).onCameraWillChange(false); - try { - mapChangeEventManager.onCameraWillChange(false); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onCameraWillChangeListener).onCameraWillChange(false); - try { - mapChangeEventManager.onCameraWillChange(false); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnCameraRegionWillChangeAnimatedListener() { - mapChangeEventManager.addOnCameraWillChangeListener(onCameraWillChangeListener); - mapChangeEventManager.onCameraWillChange(true); - verify(onCameraWillChangeListener).onCameraWillChange(true); - mapChangeEventManager.removeOnCameraWillChangeListener(onCameraWillChangeListener); - mapChangeEventManager.onCameraWillChange(true); - verify(onCameraWillChangeListener).onCameraWillChange(true); - - mapChangeEventManager.addOnCameraWillChangeListener(onCameraWillChangeListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onCameraWillChangeListener).onCameraWillChange(true); - try { - mapChangeEventManager.onCameraWillChange(true); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onCameraWillChangeListener).onCameraWillChange(true); - try { - mapChangeEventManager.onCameraWillChange(true); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnCameraIsChangingListener() { - mapChangeEventManager.addOnCameraIsChangingListener(onCameraIsChangingListener); - mapChangeEventManager.onCameraIsChanging(); - verify(onCameraIsChangingListener).onCameraIsChanging(); - mapChangeEventManager.removeOnCameraIsChangingListener(onCameraIsChangingListener); - mapChangeEventManager.onCameraIsChanging(); - verify(onCameraIsChangingListener).onCameraIsChanging(); - - mapChangeEventManager.addOnCameraIsChangingListener(onCameraIsChangingListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onCameraIsChangingListener).onCameraIsChanging(); - try { - mapChangeEventManager.onCameraIsChanging(); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onCameraIsChangingListener).onCameraIsChanging(); - try { - mapChangeEventManager.onCameraIsChanging(); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnCameraRegionDidChangeListener() { - mapChangeEventManager.addOnCameraDidChangeListener(onCameraDidChangeListener); - mapChangeEventManager.onCameraDidChange(false); - verify(onCameraDidChangeListener).onCameraDidChange(false); - mapChangeEventManager.removeOnCameraDidChangeListener(onCameraDidChangeListener); - mapChangeEventManager.onCameraDidChange(false); - verify(onCameraDidChangeListener).onCameraDidChange(false); - - mapChangeEventManager.addOnCameraDidChangeListener(onCameraDidChangeListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onCameraDidChangeListener).onCameraDidChange(false); - try { - mapChangeEventManager.onCameraDidChange(false); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onCameraDidChangeListener).onCameraDidChange(false); - try { - mapChangeEventManager.onCameraDidChange(false); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnCameraRegionDidChangeAnimatedListener() { - mapChangeEventManager.addOnCameraDidChangeListener(onCameraDidChangeListener); - mapChangeEventManager.onCameraDidChange(true); - verify(onCameraDidChangeListener).onCameraDidChange(true); - mapChangeEventManager.removeOnCameraDidChangeListener(onCameraDidChangeListener); - mapChangeEventManager.onCameraDidChange(true); - verify(onCameraDidChangeListener).onCameraDidChange(true); - - mapChangeEventManager.addOnCameraDidChangeListener(onCameraDidChangeListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onCameraDidChangeListener).onCameraDidChange(true); - try { - mapChangeEventManager.onCameraDidChange(true); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onCameraDidChangeListener).onCameraDidChange(true); - try { - mapChangeEventManager.onCameraDidChange(true); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnWillStartLoadingMapListener() { - mapChangeEventManager.addOnWillStartLoadingMapListener(onWillStartLoadingMapListener); - mapChangeEventManager.onWillStartLoadingMap(); - verify(onWillStartLoadingMapListener).onWillStartLoadingMap(); - mapChangeEventManager.removeOnWillStartLoadingMapListener(onWillStartLoadingMapListener); - mapChangeEventManager.onWillStartLoadingMap(); - verify(onWillStartLoadingMapListener).onWillStartLoadingMap(); - - mapChangeEventManager.addOnWillStartLoadingMapListener(onWillStartLoadingMapListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onWillStartLoadingMapListener).onWillStartLoadingMap(); - try { - mapChangeEventManager.onWillStartLoadingMap(); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onWillStartLoadingMapListener).onWillStartLoadingMap(); - try { - mapChangeEventManager.onWillStartLoadingMap(); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnDidFinishLoadingMapListener() { - mapChangeEventManager.addOnDidFinishLoadingMapListener(onDidFinishLoadingMapListener); - mapChangeEventManager.onDidFinishLoadingMap(); - verify(onDidFinishLoadingMapListener).onDidFinishLoadingMap(); - mapChangeEventManager.removeOnDidFinishLoadingMapListener(onDidFinishLoadingMapListener); - mapChangeEventManager.onDidFinishLoadingMap(); - verify(onDidFinishLoadingMapListener).onDidFinishLoadingMap(); - - mapChangeEventManager.addOnDidFinishLoadingMapListener(onDidFinishLoadingMapListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onDidFinishLoadingMapListener).onDidFinishLoadingMap(); - try { - mapChangeEventManager.onDidFinishLoadingMap(); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onDidFinishLoadingMapListener).onDidFinishLoadingMap(); - try { - mapChangeEventManager.onDidFinishLoadingMap(); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnDidFailLoadingMapListener() { - mapChangeEventManager.addOnDidFailLoadingMapListener(onDidFailLoadingMapListener); - mapChangeEventManager.onDidFailLoadingMap(TEST_STRING); - verify(onDidFailLoadingMapListener).onDidFailLoadingMap(TEST_STRING); - mapChangeEventManager.removeOnDidFailLoadingMapListener(onDidFailLoadingMapListener); - mapChangeEventManager.onDidFailLoadingMap(TEST_STRING); - verify(onDidFailLoadingMapListener).onDidFailLoadingMap(TEST_STRING); - - mapChangeEventManager.addOnDidFailLoadingMapListener(onDidFailLoadingMapListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onDidFailLoadingMapListener).onDidFailLoadingMap(TEST_STRING); - try { - mapChangeEventManager.onDidFailLoadingMap(TEST_STRING); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onDidFailLoadingMapListener).onDidFailLoadingMap(TEST_STRING); - try { - mapChangeEventManager.onDidFailLoadingMap(TEST_STRING); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnWillStartRenderingFrameListener() { - mapChangeEventManager.addOnWillStartRenderingFrameListener(onWillStartRenderingFrameListener); - mapChangeEventManager.onWillStartRenderingFrame(); - verify(onWillStartRenderingFrameListener).onWillStartRenderingFrame(); - mapChangeEventManager.removeOnWillStartRenderingFrameListener(onWillStartRenderingFrameListener); - mapChangeEventManager.onWillStartRenderingFrame(); - verify(onWillStartRenderingFrameListener).onWillStartRenderingFrame(); - - mapChangeEventManager.addOnWillStartRenderingFrameListener(onWillStartRenderingFrameListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onWillStartRenderingFrameListener).onWillStartRenderingFrame(); - try { - mapChangeEventManager.onWillStartRenderingFrame(); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onWillStartRenderingFrameListener).onWillStartRenderingFrame(); - try { - mapChangeEventManager.onWillStartRenderingFrame(); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnDidFinishRenderingFrameListener() { - mapChangeEventManager.addOnDidFinishRenderingFrameListener(onDidFinishRenderingFrameListener); - mapChangeEventManager.onDidFinishRenderingFrame(true); - verify(onDidFinishRenderingFrameListener).onDidFinishRenderingFrame(true); - mapChangeEventManager.removeOnDidFinishRenderingFrameListener(onDidFinishRenderingFrameListener); - mapChangeEventManager.onDidFinishRenderingFrame(true); - verify(onDidFinishRenderingFrameListener).onDidFinishRenderingFrame(true); - - mapChangeEventManager.addOnDidFinishRenderingFrameListener(onDidFinishRenderingFrameListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onDidFinishRenderingFrameListener).onDidFinishRenderingFrame(true); - try { - mapChangeEventManager.onDidFinishRenderingFrame(true); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onDidFinishRenderingFrameListener).onDidFinishRenderingFrame(true); - try { - mapChangeEventManager.onDidFinishRenderingFrame(true); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnDidFinishRenderingFrameFullyRenderedListener() { - mapChangeEventManager.addOnDidFinishRenderingFrameListener(onDidFinishRenderingFrameListener); - mapChangeEventManager.onDidFinishRenderingFrame(false); - verify(onDidFinishRenderingFrameListener).onDidFinishRenderingFrame(false); - mapChangeEventManager.removeOnDidFinishRenderingFrameListener(onDidFinishRenderingFrameListener); - mapChangeEventManager.onDidFinishRenderingFrame(false); - verify(onDidFinishRenderingFrameListener).onDidFinishRenderingFrame(false); - - mapChangeEventManager.addOnDidFinishRenderingFrameListener(onDidFinishRenderingFrameListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onDidFinishRenderingFrameListener).onDidFinishRenderingFrame(false); - try { - mapChangeEventManager.onDidFinishRenderingFrame(false); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onDidFinishRenderingFrameListener).onDidFinishRenderingFrame(false); - try { - mapChangeEventManager.onDidFinishRenderingFrame(false); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnWillStartRenderingMapListener() { - mapChangeEventManager.addOnWillStartRenderingMapListener(onWillStartRenderingMapListener); - mapChangeEventManager.onWillStartRenderingMap(); - verify(onWillStartRenderingMapListener).onWillStartRenderingMap(); - mapChangeEventManager.removeOnWillStartRenderingMapListener(onWillStartRenderingMapListener); - mapChangeEventManager.onWillStartRenderingMap(); - verify(onWillStartRenderingMapListener).onWillStartRenderingMap(); - - mapChangeEventManager.addOnWillStartRenderingMapListener(onWillStartRenderingMapListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onWillStartRenderingMapListener).onWillStartRenderingMap(); - try { - mapChangeEventManager.onWillStartRenderingMap(); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onWillStartRenderingMapListener).onWillStartRenderingMap(); - try { - mapChangeEventManager.onWillStartRenderingMap(); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnDidFinishRenderingMapListener() { - mapChangeEventManager.addOnDidFinishRenderingMapListener(onDidFinishRenderingMapListener); - mapChangeEventManager.onDidFinishRenderingMap(true); - verify(onDidFinishRenderingMapListener).onDidFinishRenderingMap(true); - mapChangeEventManager.removeOnDidFinishRenderingMapListener(onDidFinishRenderingMapListener); - mapChangeEventManager.onDidFinishRenderingMap(true); - verify(onDidFinishRenderingMapListener).onDidFinishRenderingMap(true); - - mapChangeEventManager.addOnDidFinishRenderingMapListener(onDidFinishRenderingMapListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onDidFinishRenderingMapListener).onDidFinishRenderingMap(true); - try { - mapChangeEventManager.onDidFinishRenderingMap(true); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onDidFinishRenderingMapListener).onDidFinishRenderingMap(true); - try { - mapChangeEventManager.onDidFinishRenderingMap(true); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnDidFinishRenderingMapFullyRenderedListener() { - mapChangeEventManager.addOnDidFinishRenderingMapListener(onDidFinishRenderingMapListener); - mapChangeEventManager.onDidFinishRenderingMap(false); - verify(onDidFinishRenderingMapListener).onDidFinishRenderingMap(false); - mapChangeEventManager.removeOnDidFinishRenderingMapListener(onDidFinishRenderingMapListener); - mapChangeEventManager.onDidFinishRenderingMap(false); - verify(onDidFinishRenderingMapListener).onDidFinishRenderingMap(false); - - mapChangeEventManager.addOnDidFinishRenderingMapListener(onDidFinishRenderingMapListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onDidFinishRenderingMapListener).onDidFinishRenderingMap(false); - try { - mapChangeEventManager.onDidFinishRenderingMap(false); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onDidFinishRenderingMapListener).onDidFinishRenderingMap(false); - try { - mapChangeEventManager.onDidFinishRenderingMap(false); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnDidBecomeIdleListener() { - mapChangeEventManager.addOnDidBecomeIdleListener(onDidBecomeIdleListener); - mapChangeEventManager.onDidBecomeIdle(); - verify(onDidBecomeIdleListener).onDidBecomeIdle(); - mapChangeEventManager.removeOnDidBecomeIdleListener(onDidBecomeIdleListener); - mapChangeEventManager.onDidBecomeIdle(); - verify(onDidBecomeIdleListener).onDidBecomeIdle(); - - mapChangeEventManager.addOnDidBecomeIdleListener(onDidBecomeIdleListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onDidBecomeIdleListener).onDidBecomeIdle(); - try { - mapChangeEventManager.onDidBecomeIdle(); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onDidBecomeIdleListener).onDidBecomeIdle(); - try { - mapChangeEventManager.onDidBecomeIdle(); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnDidFinishLoadingStyleListener() { - mapChangeEventManager.addOnDidFinishLoadingStyleListener(onDidFinishLoadingStyleListener); - mapChangeEventManager.onDidFinishLoadingStyle(); - verify(onDidFinishLoadingStyleListener).onDidFinishLoadingStyle(); - mapChangeEventManager.removeOnDidFinishLoadingStyleListener(onDidFinishLoadingStyleListener); - mapChangeEventManager.onDidFinishLoadingStyle(); - verify(onDidFinishLoadingStyleListener).onDidFinishLoadingStyle(); - - mapChangeEventManager.addOnDidFinishLoadingStyleListener(onDidFinishLoadingStyleListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onDidFinishLoadingStyleListener).onDidFinishLoadingStyle(); - try { - mapChangeEventManager.onDidFinishLoadingStyle(); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onDidFinishLoadingStyleListener).onDidFinishLoadingStyle(); - try { - mapChangeEventManager.onDidFinishLoadingStyle(); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnSourceChangedListener() { - mapChangeEventManager.addOnSourceChangedListener(onSourceChangedListener); - mapChangeEventManager.onSourceChanged(TEST_STRING); - verify(onSourceChangedListener).onSourceChangedListener(TEST_STRING); - mapChangeEventManager.removeOnSourceChangedListener(onSourceChangedListener); - mapChangeEventManager.onSourceChanged(TEST_STRING); - verify(onSourceChangedListener).onSourceChangedListener(TEST_STRING); - - mapChangeEventManager.addOnSourceChangedListener(onSourceChangedListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onSourceChangedListener).onSourceChangedListener(TEST_STRING); - try { - mapChangeEventManager.onSourceChanged(TEST_STRING); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onSourceChangedListener).onSourceChangedListener(TEST_STRING); - try { - mapChangeEventManager.onSourceChanged(TEST_STRING); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapChangeReceiverTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapChangeReceiverTest.kt new file mode 100644 index 000000000..ffcf09013 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapChangeReceiverTest.kt @@ -0,0 +1,714 @@ +package com.mapbox.mapboxsdk.maps + +import com.google.common.util.concurrent.ExecutionError +import com.mapbox.mapboxsdk.log.Logger +import com.mapbox.mapboxsdk.log.LoggerDefinition +import com.mapbox.mapboxsdk.maps.MapView.* +import junit.framework.Assert +import org.junit.Before +import org.junit.Test +import org.mockito.ArgumentMatchers +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.MockitoAnnotations + +/** + * Tests integration of MapChangeDispatcher and see if events are correctly forwarded. + */ +class MapChangeReceiverTest { + private var mapChangeEventManager: MapChangeReceiver? = null + + @Mock + private val onCameraWillChangeListener: OnCameraWillChangeListener? = null + + @Mock + private val onCameraDidChangeListener: OnCameraDidChangeListener? = null + + @Mock + private val onCameraIsChangingListener: OnCameraIsChangingListener? = null + + @Mock + private val onWillStartLoadingMapListener: OnWillStartLoadingMapListener? = null + + @Mock + private val onDidFinishLoadingMapListener: OnDidFinishLoadingMapListener? = null + + @Mock + private val onDidFailLoadingMapListener: OnDidFailLoadingMapListener? = null + + @Mock + private val onWillStartRenderingFrameListener: OnWillStartRenderingFrameListener? = null + + @Mock + private val onDidFinishRenderingFrameListener: OnDidFinishRenderingFrameListener? = null + + @Mock + private val onWillStartRenderingMapListener: OnWillStartRenderingMapListener? = null + + @Mock + private val onDidFinishRenderingMapListener: OnDidFinishRenderingMapListener? = null + + @Mock + private val onDidBecomeIdleListener: OnDidBecomeIdleListener? = null + + @Mock + private val onDidFinishLoadingStyleListener: OnDidFinishLoadingStyleListener? = null + + @Mock + private val onSourceChangedListener: OnSourceChangedListener? = null + + @Mock + private val loggerDefinition: LoggerDefinition? = null + + @Before + fun beforeTest() { + MockitoAnnotations.initMocks(this) + mapChangeEventManager = MapChangeReceiver() + } + + @Test + fun testOnCameraRegionWillChangeListener() { + mapChangeEventManager!!.addOnCameraWillChangeListener(onCameraWillChangeListener) + mapChangeEventManager!!?.onCameraWillChange(false) + Mockito.verify(onCameraWillChangeListener)?.onCameraWillChange(false) + mapChangeEventManager!!.removeOnCameraWillChangeListener(onCameraWillChangeListener) + mapChangeEventManager!!?.onCameraWillChange(false) + Mockito.verify(onCameraWillChangeListener)?.onCameraWillChange(false) + mapChangeEventManager!!.addOnCameraWillChangeListener(onCameraWillChangeListener) + Logger.setLoggerDefinition(loggerDefinition) + val exc: Exception = RuntimeException() + Mockito.doThrow(exc).`when`(onCameraWillChangeListener)?.onCameraWillChange(false) + try { + mapChangeEventManager!!?.onCameraWillChange(false) + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: RuntimeException) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(exc) + ) + } + val err: Error = ExecutionError("", Error()) + Mockito.doThrow(err).`when`(onCameraWillChangeListener)?.onCameraWillChange(false) + try { + mapChangeEventManager!!?.onCameraWillChange(false) + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: ExecutionError) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(err) + ) + } + } + + @Test + fun testOnCameraRegionWillChangeAnimatedListener() { + mapChangeEventManager!!.addOnCameraWillChangeListener(onCameraWillChangeListener) + mapChangeEventManager!!?.onCameraWillChange(true) + Mockito.verify(onCameraWillChangeListener)?.onCameraWillChange(true) + mapChangeEventManager!!.removeOnCameraWillChangeListener(onCameraWillChangeListener) + mapChangeEventManager!!?.onCameraWillChange(true) + Mockito.verify(onCameraWillChangeListener)?.onCameraWillChange(true) + mapChangeEventManager!!.addOnCameraWillChangeListener(onCameraWillChangeListener) + Logger.setLoggerDefinition(loggerDefinition) + val exc: Exception = RuntimeException() + Mockito.doThrow(exc).`when`(onCameraWillChangeListener)?.onCameraWillChange(true) + try { + mapChangeEventManager!!?.onCameraWillChange(true) + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: RuntimeException) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(exc) + ) + } + val err: Error = ExecutionError("", Error()) + Mockito.doThrow(err).`when`(onCameraWillChangeListener)?.onCameraWillChange(true) + try { + mapChangeEventManager!!?.onCameraWillChange(true) + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: ExecutionError) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(err) + ) + } + } + + @Test + fun testOnCameraIsChangingListener() { + mapChangeEventManager!!.addOnCameraIsChangingListener(onCameraIsChangingListener) + mapChangeEventManager!!?.onCameraIsChanging() + Mockito.verify(onCameraIsChangingListener)?.onCameraIsChanging() + mapChangeEventManager!!.removeOnCameraIsChangingListener(onCameraIsChangingListener) + mapChangeEventManager!!?.onCameraIsChanging() + Mockito.verify(onCameraIsChangingListener)?.onCameraIsChanging() + mapChangeEventManager!!.addOnCameraIsChangingListener(onCameraIsChangingListener) + Logger.setLoggerDefinition(loggerDefinition) + val exc: Exception = RuntimeException() + Mockito.doThrow(exc).`when`(onCameraIsChangingListener)?.onCameraIsChanging() + try { + mapChangeEventManager!!?.onCameraIsChanging() + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: RuntimeException) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(exc) + ) + } + val err: Error = ExecutionError("", Error()) + Mockito.doThrow(err).`when`(onCameraIsChangingListener)?.onCameraIsChanging() + try { + mapChangeEventManager!!?.onCameraIsChanging() + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: ExecutionError) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(err) + ) + } + } + + @Test + fun testOnCameraRegionDidChangeListener() { + mapChangeEventManager!!.addOnCameraDidChangeListener(onCameraDidChangeListener) + mapChangeEventManager!!?.onCameraDidChange(false) + Mockito.verify(onCameraDidChangeListener)?.onCameraDidChange(false) + mapChangeEventManager!!.removeOnCameraDidChangeListener(onCameraDidChangeListener) + mapChangeEventManager!!?.onCameraDidChange(false) + Mockito.verify(onCameraDidChangeListener)?.onCameraDidChange(false) + mapChangeEventManager!!.addOnCameraDidChangeListener(onCameraDidChangeListener) + Logger.setLoggerDefinition(loggerDefinition) + val exc: Exception = RuntimeException() + Mockito.doThrow(exc).`when`(onCameraDidChangeListener)?.onCameraDidChange(false) + try { + mapChangeEventManager!!?.onCameraDidChange(false) + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: RuntimeException) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(exc) + ) + } + val err: Error = ExecutionError("", Error()) + Mockito.doThrow(err).`when`(onCameraDidChangeListener)?.onCameraDidChange(false) + try { + mapChangeEventManager!!?.onCameraDidChange(false) + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: ExecutionError) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(err) + ) + } + } + + @Test + fun testOnCameraRegionDidChangeAnimatedListener() { + mapChangeEventManager!!.addOnCameraDidChangeListener(onCameraDidChangeListener) + mapChangeEventManager!!?.onCameraDidChange(true) + Mockito.verify(onCameraDidChangeListener)?.onCameraDidChange(true) + mapChangeEventManager!!.removeOnCameraDidChangeListener(onCameraDidChangeListener) + mapChangeEventManager!!?.onCameraDidChange(true) + Mockito.verify(onCameraDidChangeListener)?.onCameraDidChange(true) + mapChangeEventManager!!.addOnCameraDidChangeListener(onCameraDidChangeListener) + Logger.setLoggerDefinition(loggerDefinition) + val exc: Exception = RuntimeException() + Mockito.doThrow(exc).`when`(onCameraDidChangeListener)?.onCameraDidChange(true) + try { + mapChangeEventManager!!?.onCameraDidChange(true) + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: RuntimeException) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(exc) + ) + } + val err: Error = ExecutionError("", Error()) + Mockito.doThrow(err).`when`(onCameraDidChangeListener)?.onCameraDidChange(true) + try { + mapChangeEventManager!!?.onCameraDidChange(true) + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: ExecutionError) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(err) + ) + } + } + + @Test + fun testOnWillStartLoadingMapListener() { + mapChangeEventManager!!.addOnWillStartLoadingMapListener(onWillStartLoadingMapListener) + mapChangeEventManager!!?.onWillStartLoadingMap() + Mockito.verify(onWillStartLoadingMapListener)?.onWillStartLoadingMap() + mapChangeEventManager!!.removeOnWillStartLoadingMapListener(onWillStartLoadingMapListener) + mapChangeEventManager!!?.onWillStartLoadingMap() + Mockito.verify(onWillStartLoadingMapListener)?.onWillStartLoadingMap() + mapChangeEventManager!!.addOnWillStartLoadingMapListener(onWillStartLoadingMapListener) + Logger.setLoggerDefinition(loggerDefinition) + val exc: Exception = RuntimeException() + Mockito.doThrow(exc).`when`(onWillStartLoadingMapListener)?.onWillStartLoadingMap() + try { + mapChangeEventManager!!?.onWillStartLoadingMap() + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: RuntimeException) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(exc) + ) + } + val err: Error = ExecutionError("", Error()) + Mockito.doThrow(err).`when`(onWillStartLoadingMapListener)?.onWillStartLoadingMap() + try { + mapChangeEventManager!!?.onWillStartLoadingMap() + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: ExecutionError) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(err) + ) + } + } + + @Test + fun testOnDidFinishLoadingMapListener() { + mapChangeEventManager!!.addOnDidFinishLoadingMapListener(onDidFinishLoadingMapListener) + mapChangeEventManager!!?.onDidFinishLoadingMap() + Mockito.verify(onDidFinishLoadingMapListener)?.onDidFinishLoadingMap() + mapChangeEventManager!!.removeOnDidFinishLoadingMapListener(onDidFinishLoadingMapListener) + mapChangeEventManager!!?.onDidFinishLoadingMap() + Mockito.verify(onDidFinishLoadingMapListener)?.onDidFinishLoadingMap() + mapChangeEventManager!!.addOnDidFinishLoadingMapListener(onDidFinishLoadingMapListener) + Logger.setLoggerDefinition(loggerDefinition) + val exc: Exception = RuntimeException() + Mockito.doThrow(exc).`when`(onDidFinishLoadingMapListener)?.onDidFinishLoadingMap() + try { + mapChangeEventManager!!?.onDidFinishLoadingMap() + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: RuntimeException) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(exc) + ) + } + val err: Error = ExecutionError("", Error()) + Mockito.doThrow(err).`when`(onDidFinishLoadingMapListener)?.onDidFinishLoadingMap() + try { + mapChangeEventManager!!?.onDidFinishLoadingMap() + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: ExecutionError) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(err) + ) + } + } + + @Test + fun testOnDidFailLoadingMapListener() { + mapChangeEventManager!!.addOnDidFailLoadingMapListener(onDidFailLoadingMapListener) + mapChangeEventManager!!?.onDidFailLoadingMap(TEST_STRING) + Mockito.verify(onDidFailLoadingMapListener)?.onDidFailLoadingMap(TEST_STRING) + mapChangeEventManager!!.removeOnDidFailLoadingMapListener(onDidFailLoadingMapListener) + mapChangeEventManager!!?.onDidFailLoadingMap(TEST_STRING) + Mockito.verify(onDidFailLoadingMapListener)?.onDidFailLoadingMap(TEST_STRING) + mapChangeEventManager!!.addOnDidFailLoadingMapListener(onDidFailLoadingMapListener) + Logger.setLoggerDefinition(loggerDefinition) + val exc: Exception = RuntimeException() + Mockito.doThrow(exc).`when`(onDidFailLoadingMapListener)?.onDidFailLoadingMap(TEST_STRING) + try { + mapChangeEventManager!!?.onDidFailLoadingMap(TEST_STRING) + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: RuntimeException) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(exc) + ) + } + val err: Error = ExecutionError("", Error()) + Mockito.doThrow(err).`when`(onDidFailLoadingMapListener)?.onDidFailLoadingMap(TEST_STRING) + try { + mapChangeEventManager!!?.onDidFailLoadingMap(TEST_STRING) + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: ExecutionError) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(err) + ) + } + } + + @Test + fun testOnWillStartRenderingFrameListener() { + mapChangeEventManager!!.addOnWillStartRenderingFrameListener( + onWillStartRenderingFrameListener + ) + mapChangeEventManager!!?.onWillStartRenderingFrame() + Mockito.verify(onWillStartRenderingFrameListener)?.onWillStartRenderingFrame() + mapChangeEventManager!!.removeOnWillStartRenderingFrameListener( + onWillStartRenderingFrameListener + ) + mapChangeEventManager!!?.onWillStartRenderingFrame() + Mockito.verify(onWillStartRenderingFrameListener)?.onWillStartRenderingFrame() + mapChangeEventManager!!.addOnWillStartRenderingFrameListener( + onWillStartRenderingFrameListener + ) + Logger.setLoggerDefinition(loggerDefinition) + val exc: Exception = RuntimeException() + Mockito.doThrow(exc).`when`(onWillStartRenderingFrameListener)?.onWillStartRenderingFrame() + try { + mapChangeEventManager!!?.onWillStartRenderingFrame() + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: RuntimeException) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(exc) + ) + } + val err: Error = ExecutionError("", Error()) + Mockito.doThrow(err).`when`(onWillStartRenderingFrameListener)?.onWillStartRenderingFrame() + try { + mapChangeEventManager!!?.onWillStartRenderingFrame() + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: ExecutionError) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(err) + ) + } + } + + @Test + fun testOnDidFinishRenderingFrameListener() { + mapChangeEventManager!!.addOnDidFinishRenderingFrameListener( + onDidFinishRenderingFrameListener + ) + mapChangeEventManager!!?.onDidFinishRenderingFrame(true) + Mockito.verify(onDidFinishRenderingFrameListener)?.onDidFinishRenderingFrame(true) + mapChangeEventManager!!.removeOnDidFinishRenderingFrameListener( + onDidFinishRenderingFrameListener + ) + mapChangeEventManager!!?.onDidFinishRenderingFrame(true) + Mockito.verify(onDidFinishRenderingFrameListener)?.onDidFinishRenderingFrame(true) + mapChangeEventManager!!.addOnDidFinishRenderingFrameListener( + onDidFinishRenderingFrameListener + ) + Logger.setLoggerDefinition(loggerDefinition) + val exc: Exception = RuntimeException() + Mockito.doThrow(exc).`when`(onDidFinishRenderingFrameListener) + ?.onDidFinishRenderingFrame(true) + try { + mapChangeEventManager!!?.onDidFinishRenderingFrame(true) + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: RuntimeException) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(exc) + ) + } + val err: Error = ExecutionError("", Error()) + Mockito.doThrow(err).`when`(onDidFinishRenderingFrameListener) + ?.onDidFinishRenderingFrame(true) + try { + mapChangeEventManager!!?.onDidFinishRenderingFrame(true) + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: ExecutionError) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(err) + ) + } + } + + @Test + fun testOnDidFinishRenderingFrameFullyRenderedListener() { + mapChangeEventManager!!.addOnDidFinishRenderingFrameListener( + onDidFinishRenderingFrameListener + ) + mapChangeEventManager!!?.onDidFinishRenderingFrame(false) + Mockito.verify(onDidFinishRenderingFrameListener)?.onDidFinishRenderingFrame(false) + mapChangeEventManager!!.removeOnDidFinishRenderingFrameListener( + onDidFinishRenderingFrameListener + ) + mapChangeEventManager!!?.onDidFinishRenderingFrame(false) + Mockito.verify(onDidFinishRenderingFrameListener)?.onDidFinishRenderingFrame(false) + mapChangeEventManager!!.addOnDidFinishRenderingFrameListener( + onDidFinishRenderingFrameListener + ) + Logger.setLoggerDefinition(loggerDefinition) + val exc: Exception = RuntimeException() + Mockito.doThrow(exc).`when`(onDidFinishRenderingFrameListener) + ?.onDidFinishRenderingFrame(false) + try { + mapChangeEventManager!!?.onDidFinishRenderingFrame(false) + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: RuntimeException) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(exc) + ) + } + val err: Error = ExecutionError("", Error()) + Mockito.doThrow(err).`when`(onDidFinishRenderingFrameListener) + ?.onDidFinishRenderingFrame(false) + try { + mapChangeEventManager!!?.onDidFinishRenderingFrame(false) + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: ExecutionError) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(err) + ) + } + } + + @Test + fun testOnWillStartRenderingMapListener() { + mapChangeEventManager!!.addOnWillStartRenderingMapListener(onWillStartRenderingMapListener) + mapChangeEventManager!!?.onWillStartRenderingMap() + Mockito.verify(onWillStartRenderingMapListener)?.onWillStartRenderingMap() + mapChangeEventManager!!.removeOnWillStartRenderingMapListener( + onWillStartRenderingMapListener + ) + mapChangeEventManager!!?.onWillStartRenderingMap() + Mockito.verify(onWillStartRenderingMapListener)?.onWillStartRenderingMap() + mapChangeEventManager!!.addOnWillStartRenderingMapListener(onWillStartRenderingMapListener) + Logger.setLoggerDefinition(loggerDefinition) + val exc: Exception = RuntimeException() + Mockito.doThrow(exc).`when`(onWillStartRenderingMapListener)?.onWillStartRenderingMap() + try { + mapChangeEventManager!!?.onWillStartRenderingMap() + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: RuntimeException) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(exc) + ) + } + val err: Error = ExecutionError("", Error()) + Mockito.doThrow(err).`when`(onWillStartRenderingMapListener)?.onWillStartRenderingMap() + try { + mapChangeEventManager!!?.onWillStartRenderingMap() + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: ExecutionError) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(err) + ) + } + } + + @Test + fun testOnDidFinishRenderingMapListener() { + mapChangeEventManager!!.addOnDidFinishRenderingMapListener(onDidFinishRenderingMapListener) + mapChangeEventManager!!?.onDidFinishRenderingMap(true) + Mockito.verify(onDidFinishRenderingMapListener)?.onDidFinishRenderingMap(true) + mapChangeEventManager!!.removeOnDidFinishRenderingMapListener( + onDidFinishRenderingMapListener + ) + mapChangeEventManager!!?.onDidFinishRenderingMap(true) + Mockito.verify(onDidFinishRenderingMapListener)?.onDidFinishRenderingMap(true) + mapChangeEventManager!!.addOnDidFinishRenderingMapListener(onDidFinishRenderingMapListener) + Logger.setLoggerDefinition(loggerDefinition) + val exc: Exception = RuntimeException() + Mockito.doThrow(exc).`when`(onDidFinishRenderingMapListener)?.onDidFinishRenderingMap(true) + try { + mapChangeEventManager!!?.onDidFinishRenderingMap(true) + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: RuntimeException) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(exc) + ) + } + val err: Error = ExecutionError("", Error()) + Mockito.doThrow(err).`when`(onDidFinishRenderingMapListener)?.onDidFinishRenderingMap(true) + try { + mapChangeEventManager!!?.onDidFinishRenderingMap(true) + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: ExecutionError) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(err) + ) + } + } + + @Test + fun testOnDidFinishRenderingMapFullyRenderedListener() { + mapChangeEventManager!!.addOnDidFinishRenderingMapListener(onDidFinishRenderingMapListener) + mapChangeEventManager!!?.onDidFinishRenderingMap(false) + Mockito.verify(onDidFinishRenderingMapListener)?.onDidFinishRenderingMap(false) + mapChangeEventManager!!.removeOnDidFinishRenderingMapListener( + onDidFinishRenderingMapListener + ) + mapChangeEventManager!!?.onDidFinishRenderingMap(false) + Mockito.verify(onDidFinishRenderingMapListener)?.onDidFinishRenderingMap(false) + mapChangeEventManager!!.addOnDidFinishRenderingMapListener(onDidFinishRenderingMapListener) + Logger.setLoggerDefinition(loggerDefinition) + val exc: Exception = RuntimeException() + Mockito.doThrow(exc).`when`(onDidFinishRenderingMapListener)?.onDidFinishRenderingMap(false) + try { + mapChangeEventManager!!?.onDidFinishRenderingMap(false) + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: RuntimeException) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(exc) + ) + } + val err: Error = ExecutionError("", Error()) + Mockito.doThrow(err).`when`(onDidFinishRenderingMapListener)?.onDidFinishRenderingMap(false) + try { + mapChangeEventManager!!?.onDidFinishRenderingMap(false) + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: ExecutionError) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(err) + ) + } + } + + @Test + fun testOnDidBecomeIdleListener() { + mapChangeEventManager!!.addOnDidBecomeIdleListener(onDidBecomeIdleListener) + mapChangeEventManager!!?.onDidBecomeIdle() + Mockito.verify(onDidBecomeIdleListener)?.onDidBecomeIdle() + mapChangeEventManager!!.removeOnDidBecomeIdleListener(onDidBecomeIdleListener) + mapChangeEventManager!!?.onDidBecomeIdle() + Mockito.verify(onDidBecomeIdleListener)?.onDidBecomeIdle() + mapChangeEventManager!!.addOnDidBecomeIdleListener(onDidBecomeIdleListener) + Logger.setLoggerDefinition(loggerDefinition) + val exc: Exception = RuntimeException() + Mockito.doThrow(exc).`when`(onDidBecomeIdleListener)?.onDidBecomeIdle() + try { + mapChangeEventManager!!?.onDidBecomeIdle() + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: RuntimeException) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(exc) + ) + } + val err: Error = ExecutionError("", Error()) + Mockito.doThrow(err).`when`(onDidBecomeIdleListener)?.onDidBecomeIdle() + try { + mapChangeEventManager!!?.onDidBecomeIdle() + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: ExecutionError) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(err) + ) + } + } + + @Test + fun testOnDidFinishLoadingStyleListener() { + mapChangeEventManager!!.addOnDidFinishLoadingStyleListener(onDidFinishLoadingStyleListener) + mapChangeEventManager!!?.onDidFinishLoadingStyle() + Mockito.verify(onDidFinishLoadingStyleListener)?.onDidFinishLoadingStyle() + mapChangeEventManager!!.removeOnDidFinishLoadingStyleListener( + onDidFinishLoadingStyleListener + ) + mapChangeEventManager!!?.onDidFinishLoadingStyle() + Mockito.verify(onDidFinishLoadingStyleListener)?.onDidFinishLoadingStyle() + mapChangeEventManager!!.addOnDidFinishLoadingStyleListener(onDidFinishLoadingStyleListener) + Logger.setLoggerDefinition(loggerDefinition) + val exc: Exception = RuntimeException() + Mockito.doThrow(exc).`when`(onDidFinishLoadingStyleListener)?.onDidFinishLoadingStyle() + try { + mapChangeEventManager!!?.onDidFinishLoadingStyle() + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: RuntimeException) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(exc) + ) + } + val err: Error = ExecutionError("", Error()) + Mockito.doThrow(err).`when`(onDidFinishLoadingStyleListener)?.onDidFinishLoadingStyle() + try { + mapChangeEventManager!!?.onDidFinishLoadingStyle() + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: ExecutionError) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(err) + ) + } + } + + @Test + fun testOnSourceChangedListener() { + mapChangeEventManager!!.addOnSourceChangedListener(onSourceChangedListener) + mapChangeEventManager!!?.onSourceChanged(TEST_STRING) + Mockito.verify(onSourceChangedListener)?.onSourceChangedListener(TEST_STRING) + mapChangeEventManager!!.removeOnSourceChangedListener(onSourceChangedListener) + mapChangeEventManager!!?.onSourceChanged(TEST_STRING) + Mockito.verify(onSourceChangedListener)?.onSourceChangedListener(TEST_STRING) + mapChangeEventManager!!.addOnSourceChangedListener(onSourceChangedListener) + Logger.setLoggerDefinition(loggerDefinition) + val exc: Exception = RuntimeException() + Mockito.doThrow(exc).`when`(onSourceChangedListener)?.onSourceChangedListener(TEST_STRING) + try { + mapChangeEventManager!!?.onSourceChanged(TEST_STRING) + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: RuntimeException) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(exc) + ) + } + val err: Error = ExecutionError("", Error()) + Mockito.doThrow(err).`when`(onSourceChangedListener)?.onSourceChangedListener(TEST_STRING) + try { + mapChangeEventManager!!?.onSourceChanged(TEST_STRING) + Assert.fail("The exception should've been re-thrown.") + } catch (throwable: ExecutionError) { + Mockito.verify(loggerDefinition)?.e( + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(err) + ) + } + } + + companion object { + private const val TEST_STRING = "mapChangeRandom" + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapTouchListenersTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapTouchListenersTest.java deleted file mode 100644 index 08977b3ec..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapTouchListenersTest.java +++ /dev/null @@ -1,158 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.graphics.PointF; - -import androidx.annotation.Nullable; - -import com.mapbox.android.gestures.MoveGestureDetector; -import com.mapbox.android.gestures.RotateGestureDetector; -import com.mapbox.android.gestures.ShoveGestureDetector; -import com.mapbox.android.gestures.StandardScaleGestureDetector; -import com.mapbox.mapboxsdk.geometry.LatLng; - -import org.junit.Before; -import org.junit.Test; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class MapTouchListenersTest { - - @Nullable - private MapGestureDetector mapGestureDetector; - private LatLng latLng; - private PointF pointF; - - @Before - public void setUp() throws Exception { - latLng = new LatLng(); - pointF = new PointF(); - - Projection projection = mock(Projection.class); - when(projection.fromScreenLocation(pointF)).thenReturn(latLng); - mapGestureDetector = new MapGestureDetector(null, - null, projection, null, null, null); - } - - @Test - public void onMapClickListenerTest() throws Exception { - MapboxMap.OnMapClickListener listener = mock(MapboxMap.OnMapClickListener.class); - mapGestureDetector.addOnMapClickListener(listener); - mapGestureDetector.notifyOnMapClickListeners(pointF); - verify(listener, times(1)).onMapClick(latLng); - - mapGestureDetector.removeOnMapClickListener(listener); - mapGestureDetector.notifyOnMapClickListeners(pointF); - verify(listener, times(1)).onMapClick(latLng); - } - - @Test - public void onMapLongClickListenerTest() throws Exception { - MapboxMap.OnMapLongClickListener listener = mock(MapboxMap.OnMapLongClickListener.class); - mapGestureDetector.addOnMapLongClickListener(listener); - mapGestureDetector.notifyOnMapLongClickListeners(pointF); - verify(listener, times(1)).onMapLongClick(latLng); - - mapGestureDetector.removeOnMapLongClickListener(listener); - mapGestureDetector.notifyOnMapLongClickListeners(pointF); - verify(listener, times(1)).onMapLongClick(latLng); - } - - @Test - public void onFlingListenerTest() throws Exception { - MapboxMap.OnFlingListener listener = mock(MapboxMap.OnFlingListener.class); - mapGestureDetector.addOnFlingListener(listener); - mapGestureDetector.notifyOnFlingListeners(); - verify(listener, times(1)).onFling(); - - mapGestureDetector.removeOnFlingListener(listener); - mapGestureDetector.notifyOnFlingListeners(); - verify(listener, times(1)).onFling(); - } - - @Test - public void onMoveListenerTest() throws Exception { - MapboxMap.OnMoveListener listener = mock(MapboxMap.OnMoveListener.class); - MoveGestureDetector detector = mock(MoveGestureDetector.class); - mapGestureDetector.addOnMoveListener(listener); - mapGestureDetector.notifyOnMoveBeginListeners(detector); - mapGestureDetector.notifyOnMoveListeners(detector); - mapGestureDetector.notifyOnMoveEndListeners(detector); - verify(listener, times(1)).onMoveBegin(detector); - verify(listener, times(1)).onMove(detector); - verify(listener, times(1)).onMoveEnd(detector); - - mapGestureDetector.removeOnMoveListener(listener); - mapGestureDetector.notifyOnMoveBeginListeners(detector); - mapGestureDetector.notifyOnMoveListeners(detector); - mapGestureDetector.notifyOnMoveEndListeners(detector); - verify(listener, times(1)).onMoveBegin(detector); - verify(listener, times(1)).onMove(detector); - verify(listener, times(1)).onMoveEnd(detector); - } - - @Test - public void onRotateListenerTest() throws Exception { - MapboxMap.OnRotateListener listener = mock(MapboxMap.OnRotateListener.class); - RotateGestureDetector detector = mock(RotateGestureDetector.class); - mapGestureDetector.addOnRotateListener(listener); - mapGestureDetector.notifyOnRotateBeginListeners(detector); - mapGestureDetector.notifyOnRotateListeners(detector); - mapGestureDetector.notifyOnRotateEndListeners(detector); - verify(listener, times(1)).onRotateBegin(detector); - verify(listener, times(1)).onRotate(detector); - verify(listener, times(1)).onRotateEnd(detector); - - mapGestureDetector.removeOnRotateListener(listener); - mapGestureDetector.notifyOnRotateBeginListeners(detector); - mapGestureDetector.notifyOnRotateListeners(detector); - mapGestureDetector.notifyOnRotateEndListeners(detector); - verify(listener, times(1)).onRotateBegin(detector); - verify(listener, times(1)).onRotate(detector); - verify(listener, times(1)).onRotateEnd(detector); - } - - @Test - public void onScaleListenerTest() throws Exception { - MapboxMap.OnScaleListener listener = mock(MapboxMap.OnScaleListener.class); - StandardScaleGestureDetector detector = mock(StandardScaleGestureDetector.class); - mapGestureDetector.addOnScaleListener(listener); - mapGestureDetector.notifyOnScaleBeginListeners(detector); - mapGestureDetector.notifyOnScaleListeners(detector); - mapGestureDetector.notifyOnScaleEndListeners(detector); - verify(listener, times(1)).onScaleBegin(detector); - verify(listener, times(1)).onScale(detector); - verify(listener, times(1)).onScaleEnd(detector); - - mapGestureDetector.removeOnScaleListener(listener); - mapGestureDetector.notifyOnScaleBeginListeners(detector); - mapGestureDetector.notifyOnScaleListeners(detector); - mapGestureDetector.notifyOnScaleEndListeners(detector); - verify(listener, times(1)).onScaleBegin(detector); - verify(listener, times(1)).onScale(detector); - verify(listener, times(1)).onScaleEnd(detector); - } - - @Test - public void onShoveListenerTest() throws Exception { - MapboxMap.OnShoveListener listener = mock(MapboxMap.OnShoveListener.class); - ShoveGestureDetector detector = mock(ShoveGestureDetector.class); - mapGestureDetector.addShoveListener(listener); - mapGestureDetector.notifyOnShoveBeginListeners(detector); - mapGestureDetector.notifyOnShoveListeners(detector); - mapGestureDetector.notifyOnShoveEndListeners(detector); - verify(listener, times(1)).onShoveBegin(detector); - verify(listener, times(1)).onShove(detector); - verify(listener, times(1)).onShoveEnd(detector); - - mapGestureDetector.removeShoveListener(listener); - mapGestureDetector.notifyOnShoveBeginListeners(detector); - mapGestureDetector.notifyOnShoveListeners(detector); - mapGestureDetector.notifyOnShoveEndListeners(detector); - verify(listener, times(1)).onShoveBegin(detector); - verify(listener, times(1)).onShove(detector); - verify(listener, times(1)).onShoveEnd(detector); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapTouchListenersTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapTouchListenersTest.kt new file mode 100644 index 000000000..7a95b8611 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapTouchListenersTest.kt @@ -0,0 +1,181 @@ +package com.mapbox.mapboxsdk.maps + +import android.graphics.PointF +import com.mapbox.android.gestures.MoveGestureDetector +import com.mapbox.android.gestures.RotateGestureDetector +import com.mapbox.android.gestures.ShoveGestureDetector +import com.mapbox.android.gestures.StandardScaleGestureDetector +import com.mapbox.mapboxsdk.geometry.LatLng +import com.mapbox.mapboxsdk.maps.MapboxMap.* +import org.junit.Before +import org.junit.Test +import org.mockito.Mockito + +class MapTouchListenersTest { + private var mapGestureDetector: MapGestureDetector? = null + private var latLng: LatLng? = null + private var pointF: PointF? = null + + @Before + @Throws(Exception::class) + fun setUp() { + latLng = LatLng() + pointF = PointF() + val projection = Mockito.mock( + Projection::class.java + ) + Mockito.`when`(projection.fromScreenLocation(pointF!!)).thenReturn(latLng) + mapGestureDetector = MapGestureDetector( + null, + null, + projection, + null, + null, + null + ) + } + + @Test + @Throws(Exception::class) + fun onMapClickListenerTest() { + val listener = Mockito.mock( + OnMapClickListener::class.java + ) + mapGestureDetector!!.addOnMapClickListener(listener) + mapGestureDetector!!.notifyOnMapClickListeners(pointF!!) + Mockito.verify(listener, Mockito.times(1)).onMapClick( + latLng!! + ) + mapGestureDetector!!.removeOnMapClickListener(listener) + mapGestureDetector!!.notifyOnMapClickListeners(pointF!!) + Mockito.verify(listener, Mockito.times(1)).onMapClick( + latLng!! + ) + } + + @Test + @Throws(Exception::class) + fun onMapLongClickListenerTest() { + val listener = Mockito.mock( + OnMapLongClickListener::class.java + ) + mapGestureDetector!!.addOnMapLongClickListener(listener) + mapGestureDetector!!.notifyOnMapLongClickListeners(pointF!!) + Mockito.verify(listener, Mockito.times(1)).onMapLongClick( + latLng!! + ) + mapGestureDetector!!.removeOnMapLongClickListener(listener) + mapGestureDetector!!.notifyOnMapLongClickListeners(pointF!!) + Mockito.verify(listener, Mockito.times(1)).onMapLongClick( + latLng!! + ) + } + + @Test + @Throws(Exception::class) + fun onFlingListenerTest() { + val listener = Mockito.mock( + MapboxMap.OnFlingListener::class.java + ) + mapGestureDetector!!.addOnFlingListener(listener) + mapGestureDetector!!.notifyOnFlingListeners() + Mockito.verify(listener, Mockito.times(1)).onFling() + mapGestureDetector!!.removeOnFlingListener(listener) + mapGestureDetector!!.notifyOnFlingListeners() + Mockito.verify(listener, Mockito.times(1)).onFling() + } + + @Test + @Throws(Exception::class) + fun onMoveListenerTest() { + val listener = Mockito.mock(OnMoveListener::class.java) + val detector = Mockito.mock( + MoveGestureDetector::class.java + ) + mapGestureDetector!!.addOnMoveListener(listener) + mapGestureDetector!!.notifyOnMoveBeginListeners(detector) + mapGestureDetector!!.notifyOnMoveListeners(detector) + mapGestureDetector!!.notifyOnMoveEndListeners(detector) + Mockito.verify(listener, Mockito.times(1)).onMoveBegin(detector) + Mockito.verify(listener, Mockito.times(1)).onMove(detector) + Mockito.verify(listener, Mockito.times(1)).onMoveEnd(detector) + mapGestureDetector!!.removeOnMoveListener(listener) + mapGestureDetector!!.notifyOnMoveBeginListeners(detector) + mapGestureDetector!!.notifyOnMoveListeners(detector) + mapGestureDetector!!.notifyOnMoveEndListeners(detector) + Mockito.verify(listener, Mockito.times(1)).onMoveBegin(detector) + Mockito.verify(listener, Mockito.times(1)).onMove(detector) + Mockito.verify(listener, Mockito.times(1)).onMoveEnd(detector) + } + + @Test + @Throws(Exception::class) + fun onRotateListenerTest() { + val listener = Mockito.mock( + MapboxMap.OnRotateListener::class.java + ) + val detector = Mockito.mock( + RotateGestureDetector::class.java + ) + mapGestureDetector!!.addOnRotateListener(listener) + mapGestureDetector!!.notifyOnRotateBeginListeners(detector) + mapGestureDetector!!.notifyOnRotateListeners(detector) + mapGestureDetector!!.notifyOnRotateEndListeners(detector) + Mockito.verify(listener, Mockito.times(1)).onRotateBegin(detector) + Mockito.verify(listener, Mockito.times(1)).onRotate(detector) + Mockito.verify(listener, Mockito.times(1)).onRotateEnd(detector) + mapGestureDetector!!.removeOnRotateListener(listener) + mapGestureDetector!!.notifyOnRotateBeginListeners(detector) + mapGestureDetector!!.notifyOnRotateListeners(detector) + mapGestureDetector!!.notifyOnRotateEndListeners(detector) + Mockito.verify(listener, Mockito.times(1)).onRotateBegin(detector) + Mockito.verify(listener, Mockito.times(1)).onRotate(detector) + Mockito.verify(listener, Mockito.times(1)).onRotateEnd(detector) + } + + @Test + @Throws(Exception::class) + fun onScaleListenerTest() { + val listener = Mockito.mock(OnScaleListener::class.java) + val detector = Mockito.mock( + StandardScaleGestureDetector::class.java + ) + mapGestureDetector!!.addOnScaleListener(listener) + mapGestureDetector!!.notifyOnScaleBeginListeners(detector) + mapGestureDetector!!.notifyOnScaleListeners(detector) + mapGestureDetector!!.notifyOnScaleEndListeners(detector) + Mockito.verify(listener, Mockito.times(1)).onScaleBegin(detector) + Mockito.verify(listener, Mockito.times(1)).onScale(detector) + Mockito.verify(listener, Mockito.times(1)).onScaleEnd(detector) + mapGestureDetector!!.removeOnScaleListener(listener) + mapGestureDetector!!.notifyOnScaleBeginListeners(detector) + mapGestureDetector!!.notifyOnScaleListeners(detector) + mapGestureDetector!!.notifyOnScaleEndListeners(detector) + Mockito.verify(listener, Mockito.times(1)).onScaleBegin(detector) + Mockito.verify(listener, Mockito.times(1)).onScale(detector) + Mockito.verify(listener, Mockito.times(1)).onScaleEnd(detector) + } + + @Test + @Throws(Exception::class) + fun onShoveListenerTest() { + val listener = Mockito.mock(OnShoveListener::class.java) + val detector = Mockito.mock( + ShoveGestureDetector::class.java + ) + mapGestureDetector!!.addShoveListener(listener) + mapGestureDetector!!.notifyOnShoveBeginListeners(detector) + mapGestureDetector!!.notifyOnShoveListeners(detector) + mapGestureDetector!!.notifyOnShoveEndListeners(detector) + Mockito.verify(listener, Mockito.times(1)).onShoveBegin(detector) + Mockito.verify(listener, Mockito.times(1)).onShove(detector) + Mockito.verify(listener, Mockito.times(1)).onShoveEnd(detector) + mapGestureDetector!!.removeShoveListener(listener) + mapGestureDetector!!.notifyOnShoveBeginListeners(detector) + mapGestureDetector!!.notifyOnShoveListeners(detector) + mapGestureDetector!!.notifyOnShoveEndListeners(detector) + Mockito.verify(listener, Mockito.times(1)).onShoveBegin(detector) + Mockito.verify(listener, Mockito.times(1)).onShove(detector) + Mockito.verify(listener, Mockito.times(1)).onShoveEnd(detector) + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapboxMapOptionsTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapboxMapOptionsTest.java deleted file mode 100644 index ae98ee256..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapboxMapOptionsTest.java +++ /dev/null @@ -1,217 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.graphics.Color; -import android.view.Gravity; - -import com.mapbox.mapboxsdk.camera.CameraPosition; -import com.mapbox.mapboxsdk.constants.MapboxConstants; -import com.mapbox.mapboxsdk.geometry.LatLng; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; -import org.robolectric.RuntimeEnvironment; - -import java.util.Arrays; - -import static junit.framework.Assert.assertEquals; -import static junit.framework.Assert.assertFalse; -import static junit.framework.Assert.assertNull; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -@RunWith(RobolectricTestRunner.class) -public class MapboxMapOptionsTest { - - private static final double DELTA = 1e-15; - - @Test - public void testSanity() { - assertNotNull("should not be null", new MapboxMapOptions()); - } - - @Test - public void testDebugEnabled() { - assertFalse(new MapboxMapOptions().getDebugActive()); - assertTrue(new MapboxMapOptions().debugActive(true).getDebugActive()); - assertFalse(new MapboxMapOptions().debugActive(false).getDebugActive()); - } - - @Test - public void testCompassEnabled() { - assertTrue(new MapboxMapOptions().compassEnabled(true).getCompassEnabled()); - assertFalse(new MapboxMapOptions().compassEnabled(false).getCompassEnabled()); - } - - @Test - public void testCompassGravity() { - assertEquals(Gravity.TOP | Gravity.END, new MapboxMapOptions().getCompassGravity()); - assertEquals(Gravity.BOTTOM, new MapboxMapOptions().compassGravity(Gravity.BOTTOM).getCompassGravity()); - assertNotEquals(Gravity.START, new MapboxMapOptions().compassGravity(Gravity.BOTTOM).getCompassGravity()); - } - - @Test - public void testCompassMargins() { - assertTrue(Arrays.equals(new int[] {0, 1, 2, 3}, new MapboxMapOptions().compassMargins( - new int[] {0, 1, 2, 3}).getCompassMargins())); - assertFalse(Arrays.equals(new int[] {0, 1, 2, 3}, new MapboxMapOptions().compassMargins( - new int[] {0, 0, 0, 0}).getCompassMargins())); - } - - @Test - public void testLogoEnabled() { - assertTrue(new MapboxMapOptions().logoEnabled(true).getLogoEnabled()); - assertFalse(new MapboxMapOptions().logoEnabled(false).getLogoEnabled()); - } - - @Test - public void testLogoGravity() { - assertEquals(Gravity.BOTTOM | Gravity.START, new MapboxMapOptions().getLogoGravity()); - assertEquals(Gravity.BOTTOM, new MapboxMapOptions().logoGravity(Gravity.BOTTOM).getLogoGravity()); - assertNotEquals(Gravity.START, new MapboxMapOptions().logoGravity(Gravity.BOTTOM).getLogoGravity()); - } - - @Test - public void testLogoMargins() { - assertTrue(Arrays.equals(new int[] {0, 1, 2, 3}, new MapboxMapOptions().logoMargins( - new int[] {0, 1, 2, 3}).getLogoMargins())); - assertFalse(Arrays.equals(new int[] {0, 1, 2, 3}, new MapboxMapOptions().logoMargins( - new int[] {0, 0, 0, 0}).getLogoMargins())); - } - - @Test - public void testAttributionTintColor() { - assertEquals(-1, new MapboxMapOptions().getAttributionTintColor()); - assertEquals(Color.RED, new MapboxMapOptions().attributionTintColor(Color.RED).getAttributionTintColor()); - } - - @Test - public void testAttributionEnabled() { - assertTrue(new MapboxMapOptions().attributionEnabled(true).getAttributionEnabled()); - assertFalse(new MapboxMapOptions().attributionEnabled(false).getAttributionEnabled()); - } - - @Test - public void testAttributionGravity() { - assertEquals(Gravity.BOTTOM | Gravity.START, new MapboxMapOptions().getAttributionGravity()); - assertEquals(Gravity.BOTTOM, new MapboxMapOptions().attributionGravity(Gravity.BOTTOM).getAttributionGravity()); - assertNotEquals(Gravity.START, new MapboxMapOptions().attributionGravity(Gravity.BOTTOM).getAttributionGravity()); - } - - @Test - public void testAttributionMargins() { - assertTrue(Arrays.equals(new int[] {0, 1, 2, 3}, new MapboxMapOptions().attributionMargins( - new int[] {0, 1, 2, 3}).getAttributionMargins())); - assertFalse(Arrays.equals(new int[] {0, 1, 2, 3}, new MapboxMapOptions().attributionMargins( - new int[] {0, 0, 0, 0}).getAttributionMargins())); - } - - @Test - public void testMinZoom() { - assertEquals(MapboxConstants.MINIMUM_ZOOM, new MapboxMapOptions().getMinZoomPreference(), DELTA); - assertEquals(5.0f, new MapboxMapOptions().minZoomPreference(5.0f).getMinZoomPreference(), DELTA); - assertNotEquals(2.0f, new MapboxMapOptions().minZoomPreference(5.0f).getMinZoomPreference(), DELTA); - } - - @Test - public void testMaxZoom() { - assertEquals(MapboxConstants.MAXIMUM_ZOOM, new MapboxMapOptions().getMaxZoomPreference(), DELTA); - assertEquals(5.0f, new MapboxMapOptions().maxZoomPreference(5.0f).getMaxZoomPreference(), DELTA); - assertNotEquals(2.0f, new MapboxMapOptions().maxZoomPreference(5.0f).getMaxZoomPreference(), DELTA); - } - - @Test - public void testMinPitch() { - assertEquals(MapboxConstants.MINIMUM_PITCH, new MapboxMapOptions().getMinPitchPreference(), DELTA); - assertEquals(5.0f, new MapboxMapOptions().minPitchPreference(5.0f).getMinPitchPreference(), DELTA); - assertNotEquals(2.0f, new MapboxMapOptions().minPitchPreference(5.0f).getMinPitchPreference(), DELTA); - } - - @Test - public void testMaxPitch() { - assertEquals(MapboxConstants.MAXIMUM_PITCH, new MapboxMapOptions().getMaxPitchPreference(), DELTA); - assertEquals(5.0f, new MapboxMapOptions().maxPitchPreference(5.0f).getMaxPitchPreference(), DELTA); - assertNotEquals(2.0f, new MapboxMapOptions().maxPitchPreference(5.0f).getMaxPitchPreference(), DELTA); - } - - @Test - public void testTiltGesturesEnabled() { - assertTrue(new MapboxMapOptions().getTiltGesturesEnabled()); - assertTrue(new MapboxMapOptions().tiltGesturesEnabled(true).getTiltGesturesEnabled()); - assertFalse(new MapboxMapOptions().tiltGesturesEnabled(false).getTiltGesturesEnabled()); - } - - @Test - public void testScrollGesturesEnabled() { - assertTrue(new MapboxMapOptions().getScrollGesturesEnabled()); - assertTrue(new MapboxMapOptions().scrollGesturesEnabled(true).getScrollGesturesEnabled()); - assertFalse(new MapboxMapOptions().scrollGesturesEnabled(false).getScrollGesturesEnabled()); - } - - @Test - public void testHorizontalScrollGesturesEnabled() { - assertTrue(new MapboxMapOptions().getHorizontalScrollGesturesEnabled()); - assertTrue(new MapboxMapOptions().horizontalScrollGesturesEnabled(true).getHorizontalScrollGesturesEnabled()); - assertFalse(new MapboxMapOptions().horizontalScrollGesturesEnabled(false).getHorizontalScrollGesturesEnabled()); - } - - @Test - public void testZoomGesturesEnabled() { - assertTrue(new MapboxMapOptions().getZoomGesturesEnabled()); - assertTrue(new MapboxMapOptions().zoomGesturesEnabled(true).getZoomGesturesEnabled()); - assertFalse(new MapboxMapOptions().zoomGesturesEnabled(false).getZoomGesturesEnabled()); - } - - @Test - public void testRotateGesturesEnabled() { - assertTrue(new MapboxMapOptions().getRotateGesturesEnabled()); - assertTrue(new MapboxMapOptions().rotateGesturesEnabled(true).getRotateGesturesEnabled()); - assertFalse(new MapboxMapOptions().rotateGesturesEnabled(false).getRotateGesturesEnabled()); - } - - @Test - public void testCamera() { - CameraPosition position = new CameraPosition.Builder().build(); - assertEquals(new CameraPosition.Builder(position).build(), new MapboxMapOptions().camera(position).getCamera()); - assertNotEquals(new CameraPosition.Builder().target(new LatLng(1, 1)), new MapboxMapOptions().camera(position)); - assertNull(new MapboxMapOptions().getCamera()); - } - - @Test - public void testPrefetchesTiles() { - // Default value - assertTrue(new MapboxMapOptions().getPrefetchesTiles()); - - // Check mutations - assertTrue(new MapboxMapOptions().setPrefetchesTiles(true).getPrefetchesTiles()); - assertFalse(new MapboxMapOptions().setPrefetchesTiles(false).getPrefetchesTiles()); - } - - @Test - public void testPrefetchZoomDelta() { - // Default value - assertEquals(4, new MapboxMapOptions().getPrefetchZoomDelta()); - - // Check mutations - assertEquals(5, new MapboxMapOptions().setPrefetchZoomDelta(5).getPrefetchZoomDelta()); - } - - - @Test - public void testCrossSourceCollisions() { - // Default value - assertTrue(new MapboxMapOptions().getCrossSourceCollisions()); - - // check mutations - assertTrue(new MapboxMapOptions().crossSourceCollisions(true).getCrossSourceCollisions()); - assertFalse(new MapboxMapOptions().crossSourceCollisions(false).getCrossSourceCollisions()); - } - - @Test - public void testLocalIdeographFontFamily_enabledByDefault() { - MapboxMapOptions options = MapboxMapOptions.createFromAttributes(RuntimeEnvironment.application, null); - assertEquals(MapboxConstants.DEFAULT_FONT, options.getLocalIdeographFontFamily()); - } -} - diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapboxMapOptionsTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapboxMapOptionsTest.kt new file mode 100644 index 000000000..825acd070 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapboxMapOptionsTest.kt @@ -0,0 +1,321 @@ +package com.mapbox.mapboxsdk.maps + +import android.graphics.Color +import android.view.Gravity +import com.mapbox.mapboxsdk.camera.CameraPosition +import com.mapbox.mapboxsdk.constants.MapboxConstants +import com.mapbox.mapboxsdk.geometry.LatLng +import org.junit.Assert +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import java.util.* + +@RunWith(RobolectricTestRunner::class) +class MapboxMapOptionsTest { + @Test + fun testSanity() { + Assert.assertNotNull("should not be null", MapboxMapOptions()) + } + + @Test + fun testDebugEnabled() { + junit.framework.Assert.assertFalse(MapboxMapOptions().debugActive) + Assert.assertTrue(MapboxMapOptions().debugActive(true).debugActive) + junit.framework.Assert.assertFalse(MapboxMapOptions().debugActive(false).debugActive) + } + + @Test + fun testCompassEnabled() { + Assert.assertTrue(MapboxMapOptions().compassEnabled(true).compassEnabled) + junit.framework.Assert.assertFalse(MapboxMapOptions().compassEnabled(false).compassEnabled) + } + + @Test + fun testCompassGravity() { + junit.framework.Assert.assertEquals( + Gravity.TOP or Gravity.END, + MapboxMapOptions().compassGravity + ) + junit.framework.Assert.assertEquals( + Gravity.BOTTOM, + MapboxMapOptions().compassGravity(Gravity.BOTTOM).compassGravity + ) + Assert.assertNotEquals( + Gravity.START.toLong(), + MapboxMapOptions().compassGravity(Gravity.BOTTOM).compassGravity.toLong() + ) + } + + @Test + fun testCompassMargins() { + Assert.assertTrue( + Arrays.equals( + intArrayOf(0, 1, 2, 3), + MapboxMapOptions().compassMargins(intArrayOf(0, 1, 2, 3)).compassMargins + ) + ) + junit.framework.Assert.assertFalse( + Arrays.equals( + intArrayOf(0, 1, 2, 3), + MapboxMapOptions().compassMargins(intArrayOf(0, 0, 0, 0)).compassMargins + ) + ) + } + + @Test + fun testLogoEnabled() { + Assert.assertTrue(MapboxMapOptions().logoEnabled(true).logoEnabled) + junit.framework.Assert.assertFalse(MapboxMapOptions().logoEnabled(false).logoEnabled) + } + + @Test + fun testLogoGravity() { + junit.framework.Assert.assertEquals( + Gravity.BOTTOM or Gravity.START, + MapboxMapOptions().logoGravity + ) + junit.framework.Assert.assertEquals( + Gravity.BOTTOM, + MapboxMapOptions().logoGravity(Gravity.BOTTOM).logoGravity + ) + Assert.assertNotEquals( + Gravity.START.toLong(), + MapboxMapOptions().logoGravity(Gravity.BOTTOM).logoGravity.toLong() + ) + } + + @Test + fun testLogoMargins() { + Assert.assertTrue( + Arrays.equals( + intArrayOf(0, 1, 2, 3), + MapboxMapOptions().logoMargins(intArrayOf(0, 1, 2, 3)).logoMargins + ) + ) + junit.framework.Assert.assertFalse( + Arrays.equals( + intArrayOf(0, 1, 2, 3), + MapboxMapOptions().logoMargins(intArrayOf(0, 0, 0, 0)).logoMargins + ) + ) + } + + @Test + fun testAttributionTintColor() { + junit.framework.Assert.assertEquals(-1, MapboxMapOptions().attributionTintColor) + junit.framework.Assert.assertEquals( + Color.RED, + MapboxMapOptions().attributionTintColor(Color.RED).attributionTintColor + ) + } + + @Test + fun testAttributionEnabled() { + Assert.assertTrue(MapboxMapOptions().attributionEnabled(true).attributionEnabled) + junit.framework.Assert.assertFalse(MapboxMapOptions().attributionEnabled(false).attributionEnabled) + } + + @Test + fun testAttributionGravity() { + junit.framework.Assert.assertEquals( + Gravity.BOTTOM or Gravity.START, + MapboxMapOptions().attributionGravity + ) + junit.framework.Assert.assertEquals( + Gravity.BOTTOM, + MapboxMapOptions().attributionGravity(Gravity.BOTTOM).attributionGravity + ) + Assert.assertNotEquals( + Gravity.START.toLong(), + MapboxMapOptions().attributionGravity(Gravity.BOTTOM).attributionGravity.toLong() + ) + } + + @Test + fun testAttributionMargins() { + Assert.assertTrue( + Arrays.equals( + intArrayOf(0, 1, 2, 3), + MapboxMapOptions().attributionMargins(intArrayOf(0, 1, 2, 3)).attributionMargins + ) + ) + junit.framework.Assert.assertFalse( + Arrays.equals( + intArrayOf(0, 1, 2, 3), + MapboxMapOptions().attributionMargins(intArrayOf(0, 0, 0, 0)).attributionMargins + ) + ) + } + + @Test + fun testMinZoom() { + junit.framework.Assert.assertEquals( + MapboxConstants.MINIMUM_ZOOM.toDouble(), + MapboxMapOptions().minZoomPreference, + DELTA + ) + junit.framework.Assert.assertEquals( + 5.0, + MapboxMapOptions().minZoomPreference(5.0).minZoomPreference, + DELTA + ) + Assert.assertNotEquals( + 2.0, + MapboxMapOptions().minZoomPreference(5.0).minZoomPreference, + DELTA + ) + } + + @Test + fun testMaxZoom() { + junit.framework.Assert.assertEquals( + MapboxConstants.MAXIMUM_ZOOM.toDouble(), + MapboxMapOptions().maxZoomPreference, + DELTA + ) + junit.framework.Assert.assertEquals( + 5.0, + MapboxMapOptions().maxZoomPreference(5.0).maxZoomPreference, + DELTA + ) + Assert.assertNotEquals( + 2.0, + MapboxMapOptions().maxZoomPreference(5.0).maxZoomPreference, + DELTA + ) + } + + @Test + fun testMinPitch() { + junit.framework.Assert.assertEquals( + MapboxConstants.MINIMUM_PITCH.toDouble(), + MapboxMapOptions().minPitchPreference, + DELTA + ) + junit.framework.Assert.assertEquals( + 5.0, + MapboxMapOptions().minPitchPreference(5.0).minPitchPreference, + DELTA + ) + Assert.assertNotEquals( + 2.0, + MapboxMapOptions().minPitchPreference(5.0).minPitchPreference, + DELTA + ) + } + + @Test + fun testMaxPitch() { + junit.framework.Assert.assertEquals( + MapboxConstants.MAXIMUM_PITCH.toDouble(), + MapboxMapOptions().maxPitchPreference, + DELTA + ) + junit.framework.Assert.assertEquals( + 5.0, + MapboxMapOptions().maxPitchPreference(5.0).maxPitchPreference, + DELTA + ) + Assert.assertNotEquals( + 2.0, + MapboxMapOptions().maxPitchPreference(5.0).maxPitchPreference, + DELTA + ) + } + + @Test + fun testTiltGesturesEnabled() { + Assert.assertTrue(MapboxMapOptions().tiltGesturesEnabled) + Assert.assertTrue(MapboxMapOptions().tiltGesturesEnabled(true).tiltGesturesEnabled) + junit.framework.Assert.assertFalse(MapboxMapOptions().tiltGesturesEnabled(false).tiltGesturesEnabled) + } + + @Test + fun testScrollGesturesEnabled() { + Assert.assertTrue(MapboxMapOptions().scrollGesturesEnabled) + Assert.assertTrue(MapboxMapOptions().scrollGesturesEnabled(true).scrollGesturesEnabled) + junit.framework.Assert.assertFalse(MapboxMapOptions().scrollGesturesEnabled(false).scrollGesturesEnabled) + } + + @Test + fun testHorizontalScrollGesturesEnabled() { + Assert.assertTrue(MapboxMapOptions().horizontalScrollGesturesEnabled) + Assert.assertTrue(MapboxMapOptions().horizontalScrollGesturesEnabled(true).horizontalScrollGesturesEnabled) + junit.framework.Assert.assertFalse(MapboxMapOptions().horizontalScrollGesturesEnabled(false).horizontalScrollGesturesEnabled) + } + + @Test + fun testZoomGesturesEnabled() { + Assert.assertTrue(MapboxMapOptions().zoomGesturesEnabled) + Assert.assertTrue(MapboxMapOptions().zoomGesturesEnabled(true).zoomGesturesEnabled) + junit.framework.Assert.assertFalse(MapboxMapOptions().zoomGesturesEnabled(false).zoomGesturesEnabled) + } + + @Test + fun testRotateGesturesEnabled() { + Assert.assertTrue(MapboxMapOptions().rotateGesturesEnabled) + Assert.assertTrue(MapboxMapOptions().rotateGesturesEnabled(true).rotateGesturesEnabled) + junit.framework.Assert.assertFalse(MapboxMapOptions().rotateGesturesEnabled(false).rotateGesturesEnabled) + } + + @Test + fun testCamera() { + val position = CameraPosition.Builder().build() + junit.framework.Assert.assertEquals( + CameraPosition.Builder(position).build(), + MapboxMapOptions().camera(position).camera + ) + Assert.assertNotEquals( + CameraPosition.Builder().target(LatLng(1.0, 1.0)), + MapboxMapOptions().camera(position) + ) + junit.framework.Assert.assertNull(MapboxMapOptions().camera) + } + + @Test + fun testPrefetchesTiles() { + // Default value + Assert.assertTrue(MapboxMapOptions().prefetchesTiles) + + // Check mutations + Assert.assertTrue(MapboxMapOptions().setPrefetchesTiles(true).prefetchesTiles) + junit.framework.Assert.assertFalse(MapboxMapOptions().setPrefetchesTiles(false).prefetchesTiles) + } + + @Test + fun testPrefetchZoomDelta() { + // Default value + junit.framework.Assert.assertEquals(4, MapboxMapOptions().prefetchZoomDelta) + + // Check mutations + junit.framework.Assert.assertEquals( + 5, + MapboxMapOptions().setPrefetchZoomDelta(5).prefetchZoomDelta + ) + } + + @Test + fun testCrossSourceCollisions() { + // Default value + Assert.assertTrue(MapboxMapOptions().crossSourceCollisions) + + // check mutations + Assert.assertTrue(MapboxMapOptions().crossSourceCollisions(true).crossSourceCollisions) + junit.framework.Assert.assertFalse(MapboxMapOptions().crossSourceCollisions(false).crossSourceCollisions) + } + + @Test + fun testLocalIdeographFontFamily_enabledByDefault() { + val options = MapboxMapOptions.createFromAttributes(RuntimeEnvironment.application, null) + junit.framework.Assert.assertEquals( + MapboxConstants.DEFAULT_FONT, + options.localIdeographFontFamily + ) + } + + companion object { + private const val DELTA = 1e-15 + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/UiSettingsTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/UiSettingsTest.java deleted file mode 100644 index 81d97a1b9..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/UiSettingsTest.java +++ /dev/null @@ -1,472 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.content.Context; -import android.content.res.Resources; -import android.view.Gravity; -import android.view.View; -import android.widget.FrameLayout; -import android.widget.ImageView; - -import com.mapbox.mapboxsdk.camera.CameraPosition; -import com.mapbox.mapboxsdk.maps.widgets.CompassView; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class UiSettingsTest { - @InjectMocks - MapView mapview = mock(MapView.class); - - @InjectMocks - Context context = mock(Context.class); - - @InjectMocks - Resources resources = mock(Resources.class); - - @InjectMocks - Projection projection = mock(Projection.class); - - @InjectMocks - FocalPointChangeListener focalPointChangeListener = mock(FocalPointChangeListener.class); - - @InjectMocks - CompassView compassView = mock(CompassView.class); - - @InjectMocks - ImageView attributionView = mock(ImageView.class); - - @InjectMocks - ImageView logoView = mock(ImageView.class); - - @InjectMocks - FrameLayout.LayoutParams layoutParams = mock(FrameLayout.LayoutParams.class); - - private UiSettings uiSettings; - private MapboxMapOptions mapboxMapOptions; - - @Before - public void beforeTest() { - uiSettings = new UiSettings(projection, focalPointChangeListener, 1, mapview); - uiSettings.compassView = this.compassView; - uiSettings.attributionsView = this.attributionView; - uiSettings.logoView = this.logoView; - when(compassView.getContext()).thenReturn(context); - when(attributionView.getContext()).thenReturn(context); - when(logoView.getContext()).thenReturn(context); - when(context.getResources()).thenReturn(resources); - } - - @Test - public void testSanity() { - assertNotNull("uiSettings should not be null", uiSettings); - } - - @Test - public void testGetCompassEnabled() { - when(compassView.isEnabled()).thenReturn(true); - assertEquals("Compass should be enabled", true, uiSettings.isCompassEnabled()); - } - - @Test - public void testSetCompassEnabled() { - uiSettings.isCompassInitialized = true; - uiSettings.setCompassEnabled(true); - verify(compassView).setEnabled(true); - } - - @Test - public void testCompassDisabled() { - uiSettings.setCompassEnabled(false); - assertEquals("Compass should be disabled", false, uiSettings.isCompassEnabled()); - } - - @Test - public void testCompassGravity() { - when(compassView.getLayoutParams()).thenReturn(layoutParams); - layoutParams.gravity = Gravity.START; - uiSettings.setCompassGravity(Gravity.START); - assertEquals("Compass gravity should be same", Gravity.START, uiSettings.getCompassGravity()); - } - - @Test - public void testCompassMargins() { - when(projection.getContentPadding()).thenReturn(new int[]{0, 0, 0, 0}); - when(compassView.getLayoutParams()).thenReturn(layoutParams); - layoutParams.leftMargin = 1; - layoutParams.topMargin = 2; - layoutParams.rightMargin = 3; - layoutParams.bottomMargin = 4; - uiSettings.setCompassMargins(1, 2, 3, 4); - assertTrue("Compass margin left should be same", uiSettings.getCompassMarginLeft() == 1); - assertTrue("Compass margin top should be same", uiSettings.getCompassMarginTop() == 2); - assertTrue("Compass margin right should be same", uiSettings.getCompassMarginRight() == 3); - assertTrue("Compass margin bottom should be same", uiSettings.getCompassMarginBottom() == 4); - } - - @Test - public void testCompassFadeWhenFacingNorth() { - when(compassView.isFadeCompassViewFacingNorth()).thenReturn(true); - assertTrue("Compass should fade when facing north by default.", uiSettings.isCompassFadeWhenFacingNorth()); - uiSettings.setCompassFadeFacingNorth(false); - when(compassView.isFadeCompassViewFacingNorth()).thenReturn(false); - assertFalse("Compass fading should be disabled", uiSettings.isCompassFadeWhenFacingNorth()); - } - - @Test - public void testLogoEnabled() { - uiSettings.isLogoInitialized = true; - uiSettings.setLogoEnabled(true); - assertEquals("Logo should be enabled", true, uiSettings.isLogoEnabled()); - } - - @Test - public void testLogoDisabled() { - when(logoView.getVisibility()).thenReturn(View.GONE); - uiSettings.setLogoEnabled(false); - assertEquals("Logo should be disabled", false, uiSettings.isLogoEnabled()); - } - - @Test - public void testLogoGravity() { - layoutParams.gravity = Gravity.END; - when(logoView.getLayoutParams()).thenReturn(layoutParams); - uiSettings.setLogoGravity(Gravity.END); - assertEquals("Logo gravity should be same", Gravity.END, uiSettings.getLogoGravity()); - } - - @Test - public void testLogoMargins() { - when(projection.getContentPadding()).thenReturn(new int[]{0, 0, 0, 0}); - when(logoView.getLayoutParams()).thenReturn(layoutParams); - layoutParams.leftMargin = 1; - layoutParams.topMargin = 2; - layoutParams.rightMargin = 3; - layoutParams.bottomMargin = 4; - uiSettings.setLogoMargins(1, 2, 3, 4); - assertTrue("Compass margin left should be same", uiSettings.getLogoMarginLeft() == 1); - assertTrue("Compass margin top should be same", uiSettings.getLogoMarginTop() == 2); - assertTrue("Compass margin right should be same", uiSettings.getLogoMarginRight() == 3); - assertTrue("Compass margin bottom should be same", uiSettings.getLogoMarginBottom() == 4); - } - - @Test - public void testAttributionEnabled() { - uiSettings.isAttributionInitialized = true; - when(attributionView.getVisibility()).thenReturn(View.VISIBLE); - uiSettings.setAttributionEnabled(true); - assertEquals("Attribution should be enabled", true, uiSettings.isAttributionEnabled()); - } - - @Test - public void testAttributionDisabled() { - when(attributionView.getVisibility()).thenReturn(View.GONE); - uiSettings.setAttributionEnabled(false); - assertEquals("Attribution should be disabled", false, uiSettings.isAttributionEnabled()); - } - - @Test - public void testAttributionGravity() { - when(attributionView.getLayoutParams()).thenReturn(layoutParams); - layoutParams.gravity = Gravity.END; - uiSettings.setAttributionGravity(Gravity.END); - assertEquals("Attribution gravity should be same", Gravity.END, uiSettings.getAttributionGravity()); - } - - @Test - public void testAttributionMargins() { - when(attributionView.getLayoutParams()).thenReturn(layoutParams); - when(projection.getContentPadding()).thenReturn(new int[]{0, 0, 0, 0}); - layoutParams.leftMargin = 1; - layoutParams.topMargin = 2; - layoutParams.rightMargin = 3; - layoutParams.bottomMargin = 4; - uiSettings.setAttributionMargins(1, 2, 3, 4); - assertTrue("Attribution margin left should be same", uiSettings.getAttributionMarginLeft() == 1); - assertTrue("Attribution margin top should be same", uiSettings.getAttributionMarginTop() == 2); - assertTrue("Attribution margin right should be same", uiSettings.getAttributionMarginRight() == 3); - assertTrue("Attribution margin bottom should be same", uiSettings.getAttributionMarginBottom() == 4); - } - - @Test - public void testRotateGesturesEnabled() { - uiSettings.setRotateGesturesEnabled(true); - assertEquals("Rotate gesture should be enabled", true, uiSettings.isRotateGesturesEnabled()); - } - - @Test - public void testRotateGesturesDisabled() { - uiSettings.setRotateGesturesEnabled(false); - assertEquals("Rotate gesture should be disabled", false, uiSettings.isRotateGesturesEnabled()); - } - - @Test - public void testRotateGestureChangeAllowed() { - uiSettings.setRotateGesturesEnabled(false); - assertEquals("Rotate gesture should be false", false, uiSettings.isRotateGesturesEnabled()); - uiSettings.setRotateGesturesEnabled(true); - assertEquals("Rotate gesture should be true", true, uiSettings.isRotateGesturesEnabled()); - } - - @Test - public void testTiltGesturesEnabled() { - uiSettings.setTiltGesturesEnabled(true); - assertEquals("Tilt gesture should be enabled", true, uiSettings.isTiltGesturesEnabled()); - } - - @Test - public void testTiltGesturesDisabled() { - uiSettings.setTiltGesturesEnabled(false); - assertEquals("Tilt gesture should be disabled", false, uiSettings.isTiltGesturesEnabled()); - } - - @Test - public void testTiltGestureChangeAllowed() { - uiSettings.setTiltGesturesEnabled(false); - assertEquals("Tilt gesture should be false", false, uiSettings.isTiltGesturesEnabled()); - uiSettings.setTiltGesturesEnabled(true); - assertEquals("Tilt gesture should be true", true, uiSettings.isTiltGesturesEnabled()); - } - - @Test - public void testZoomGesturesEnabled() { - uiSettings.setZoomGesturesEnabled(true); - assertEquals("Zoom gesture should be enabled", true, uiSettings.isZoomGesturesEnabled()); - } - - @Test - public void testZoomGesturesDisabled() { - uiSettings.setZoomGesturesEnabled(false); - assertEquals("Zoom gesture should be disabled", false, uiSettings.isZoomGesturesEnabled()); - } - - @Test - public void testZoomGestureChangeAllowed() { - uiSettings.setZoomGesturesEnabled(false); - assertEquals("Zoom gesture should be false", false, uiSettings.isZoomGesturesEnabled()); - uiSettings.setZoomGesturesEnabled(true); - assertEquals("Zoom gesture should be true", true, uiSettings.isZoomGesturesEnabled()); - } - - @Test - public void testDoubleTapGesturesEnabled() { - uiSettings.setDoubleTapGesturesEnabled(true); - assertEquals("DoubleTap gesture should be enabled", true, uiSettings.isDoubleTapGesturesEnabled()); - } - - @Test - public void testDoubleTapGesturesDisabled() { - uiSettings.setDoubleTapGesturesEnabled(false); - assertEquals("DoubleTap gesture should be disabled", false, uiSettings.isDoubleTapGesturesEnabled()); - } - - @Test - public void testDoubleTapGestureChangeAllowed() { - uiSettings.setDoubleTapGesturesEnabled(false); - assertEquals("DoubleTap gesture should be false", false, uiSettings.isDoubleTapGesturesEnabled()); - uiSettings.setDoubleTapGesturesEnabled(true); - assertEquals("DoubleTap gesture should be true", true, uiSettings.isDoubleTapGesturesEnabled()); - } - - @Test - public void testQuickZoomGesturesEnabled() { - uiSettings.setQuickZoomGesturesEnabled(true); - assertEquals("QuickZoom gesture should be enabled", true, uiSettings.isQuickZoomGesturesEnabled()); - } - - @Test - public void testQuickZoomGesturesDisabled() { - uiSettings.setQuickZoomGesturesEnabled(false); - assertEquals("QuickZoom gesture should be disabled", false, uiSettings.isQuickZoomGesturesEnabled()); - } - - @Test - public void testQuickZoomGestureChangeAllowed() { - uiSettings.setQuickZoomGesturesEnabled(false); - assertEquals("QuickZoom gesture should be false", false, uiSettings.isQuickZoomGesturesEnabled()); - uiSettings.setQuickZoomGesturesEnabled(true); - assertEquals("QuickZoom gesture should be true", true, uiSettings.isQuickZoomGesturesEnabled()); - } - - @Test - public void testScrollGesturesEnabled() { - uiSettings.setScrollGesturesEnabled(true); - assertEquals("Scroll gesture should be enabled", true, uiSettings.isScrollGesturesEnabled()); - } - - @Test - public void testScrollGesturesDisabled() { - uiSettings.setScrollGesturesEnabled(false); - assertEquals("Scroll gesture should be disabled", false, uiSettings.isScrollGesturesEnabled()); - } - - - @Test - public void testHorizontalScrollGesturesEnabled() { - uiSettings.setHorizontalScrollGesturesEnabled(true); - assertEquals("Scroll gesture should be enabled", true, uiSettings.isHorizontalScrollGesturesEnabled()); - } - - @Test - public void testHorizontalScrollGesturesDisabled() { - uiSettings.setHorizontalScrollGesturesEnabled(false); - assertEquals("Scroll gesture should be disabled", false, uiSettings.isHorizontalScrollGesturesEnabled()); - } - - @Test - public void testScrollGestureChangeAllowed() { - uiSettings.setScrollGesturesEnabled(false); - assertEquals("Scroll gesture should be false", false, uiSettings.isScrollGesturesEnabled()); - uiSettings.setScrollGesturesEnabled(true); - assertEquals("Scroll gesture should be true", true, uiSettings.isScrollGesturesEnabled()); - } - - @Test - public void testScaleVelocityAnimationEnabled() { - uiSettings.setScaleVelocityAnimationEnabled(true); - assertEquals("Scale velocity animation should be enabled", true, uiSettings.isScaleVelocityAnimationEnabled()); - } - - @Test - public void testScaleVelocityAnimationDisabled() { - uiSettings.setScaleVelocityAnimationEnabled(false); - assertEquals("Scale velocity animation should be disabled", false, uiSettings.isScaleVelocityAnimationEnabled()); - } - - @Test - public void testRotateVelocityAnimationEnabled() { - uiSettings.setRotateVelocityAnimationEnabled(true); - assertEquals("Rotate velocity animation should be enabled", true, uiSettings.isRotateVelocityAnimationEnabled()); - } - - @Test - public void testRotateVelocityAnimationDisabled() { - uiSettings.setRotateVelocityAnimationEnabled(false); - assertEquals("Rotate velocity animation should be disabled", false, uiSettings.isRotateVelocityAnimationEnabled()); - } - - @Test - public void testFlingVelocityAnimationEnabled() { - uiSettings.setFlingVelocityAnimationEnabled(true); - assertEquals("Fling velocity animation should be enabled", true, uiSettings.isFlingVelocityAnimationEnabled()); - } - - @Test - public void testFlingVelocityAnimationDisabled() { - uiSettings.setFlingVelocityAnimationEnabled(false); - assertEquals("Fling velocity animation should be disabled", false, uiSettings.isFlingVelocityAnimationEnabled()); - } - - @Test - public void testAllVelocityAnimationsEnabled() { - uiSettings.setAllVelocityAnimationsEnabled(true); - assertEquals("Scale velocity animation should be enabled", true, uiSettings.isScaleVelocityAnimationEnabled()); - assertEquals("Rotate velocity animation should be enabled", true, uiSettings.isRotateVelocityAnimationEnabled()); - assertEquals("Fling velocity animation should be enabled", true, uiSettings.isFlingVelocityAnimationEnabled()); - } - - @Test - public void testAllVelocityAnimationsDisabled() { - uiSettings.setAllVelocityAnimationsEnabled(false); - assertEquals("Scale velocity animation should be disabled", false, uiSettings.isScaleVelocityAnimationEnabled()); - assertEquals("Rotate velocity animation should be disabled", false, uiSettings.isRotateVelocityAnimationEnabled()); - assertEquals("Fling velocity animation should be disabled", false, uiSettings.isFlingVelocityAnimationEnabled()); - } - - @Test - public void testDisableRotateWhenScalingEnabled() { - uiSettings.setDisableRotateWhenScaling(true); - assertEquals("Rotate disabling should be enabled", true, - uiSettings.isDisableRotateWhenScaling()); - } - - @Test - public void testDisableRotateWhenScalingDisabled() { - uiSettings.setDisableRotateWhenScaling(false); - assertEquals("Rotate disabling should be disabled", false, - uiSettings.isDisableRotateWhenScaling()); - } - - @Test - public void testIncreaseScaleThresholdWhenRotatingEnabled() { - uiSettings.setIncreaseScaleThresholdWhenRotating(true); - assertEquals("Scale threshold increase should be enabled", true, uiSettings.isIncreaseScaleThresholdWhenRotating()); - } - - @Test - public void testIncreaseScaleThresholdWhenRotatingDisabled() { - uiSettings.setIncreaseScaleThresholdWhenRotating(false); - assertEquals("Scale threshold increase should be disabled", false, - uiSettings.isIncreaseScaleThresholdWhenRotating()); - } - - @Test - public void testAllGesturesEnabled() { - uiSettings.setAllGesturesEnabled(true); - assertEquals("Rotate gesture should be enabled", true, uiSettings.isRotateGesturesEnabled()); - assertEquals("Tilt gesture should be enabled", true, uiSettings.isTiltGesturesEnabled()); - assertEquals("Zoom gesture should be enabled", true, uiSettings.isZoomGesturesEnabled()); - assertEquals("Scroll gesture should be enabled", true, uiSettings.isScrollGesturesEnabled()); - } - - @Test - public void testAllGesturesDisabled() { - uiSettings.setAllGesturesEnabled(false); - assertEquals("Rotate gesture should be enabled", false, uiSettings.isRotateGesturesEnabled()); - assertEquals("Tilt gesture should be disabled", false, uiSettings.isTiltGesturesEnabled()); - assertEquals("Zoom gesture should be disabled", false, uiSettings.isZoomGesturesEnabled()); - assertEquals("Scroll gesture should be disabled", false, uiSettings.isScrollGesturesEnabled()); - } - - @Test - public void testAreAllGesturesEnabled() { - uiSettings.setAllGesturesEnabled(true); - assertEquals("All gestures check should return true", true, - uiSettings.areAllGesturesEnabled()); - } - - @Test - public void testAreAllGesturesEnabledWithOneGestureDisabled() { - uiSettings.setAllGesturesEnabled(true); - uiSettings.setScrollGesturesEnabled(false); - assertEquals("All gestures check should return false", false, - uiSettings.areAllGesturesEnabled()); - } - - @Test - public void testZoomRateDefaultValue() { - assertEquals("Default zoom rate should be 1.0f", 1.0f, - uiSettings.getZoomRate(), 0); - } - - @Test - public void testZoomRate() { - uiSettings.setZoomRate(0.83f); - assertEquals("Zoom rate should be 0.83f", 0.83f, - uiSettings.getZoomRate(), 0); - } - - @Test - public void testUpdateWhenCompassViewNotHidden() { - CameraPosition cameraPosition = new CameraPosition.Builder(CameraPosition.DEFAULT).bearing(24.0f).build(); - when(compassView.isHidden()).thenReturn(false); - uiSettings.update(cameraPosition); - verify(compassView).update(-24.0f); - } - - @Test - public void testUpdateWhenCompassViewHidden() { - CameraPosition cameraPosition = new CameraPosition.Builder(CameraPosition.DEFAULT).bearing(24.0f).build(); - when(compassView.isHidden()).thenReturn(true); - uiSettings.update(cameraPosition); - verify(compassView).update(-24.0f); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/UiSettingsTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/UiSettingsTest.kt new file mode 100644 index 000000000..cdcebbb3a --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/UiSettingsTest.kt @@ -0,0 +1,726 @@ +package com.mapbox.mapboxsdk.maps + +import android.content.Context +import android.content.res.Resources +import android.view.Gravity +import android.view.View +import android.widget.FrameLayout +import android.widget.ImageView +import com.mapbox.mapboxsdk.camera.CameraPosition +import com.mapbox.mapboxsdk.maps.widgets.CompassView +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.mockito.InjectMocks +import org.mockito.Mockito + +class UiSettingsTest { + @InjectMocks + var mapview = Mockito.mock(MapView::class.java) + + @InjectMocks + var context = Mockito.mock( + Context::class.java + ) + + @InjectMocks + var resources = Mockito.mock( + Resources::class.java + ) + + @InjectMocks + var projection = Mockito.mock( + Projection::class.java + ) + + @InjectMocks + var focalPointChangeListener = Mockito.mock( + FocalPointChangeListener::class.java + ) + + @InjectMocks + var compassView = Mockito.mock(CompassView::class.java) + + @InjectMocks + var attributionView = Mockito.mock( + ImageView::class.java + ) + + @InjectMocks + var logoView = Mockito.mock( + ImageView::class.java + ) + + @InjectMocks + var layoutParams = Mockito.mock( + FrameLayout.LayoutParams::class.java + ) + private var uiSettings: UiSettings? = null + private val mapboxMapOptions: MapboxMapOptions? = null + + @Before + fun beforeTest() { + uiSettings = UiSettings(projection, focalPointChangeListener, 1f, mapview) + uiSettings!!.compassView = compassView + uiSettings!!.attributionsView = attributionView + uiSettings!!.logoView = logoView + Mockito.`when`(compassView.context).thenReturn(context) + Mockito.`when`(attributionView.context).thenReturn(context) + Mockito.`when`(logoView.context).thenReturn(context) + Mockito.`when`(context.resources).thenReturn(resources) + } + + @Test + fun testSanity() { + Assert.assertNotNull("uiSettings should not be null", uiSettings) + } + + @Test + fun testGetCompassEnabled() { + Mockito.`when`(compassView.isEnabled).thenReturn(true) + Assert.assertEquals("Compass should be enabled", true, uiSettings!!.isCompassEnabled) + } + + @Test + fun testSetCompassEnabled() { + uiSettings!!.isCompassInitialized = true + uiSettings!!.isCompassEnabled = true + Mockito.verify(compassView).isEnabled = true + } + + @Test + fun testCompassDisabled() { + uiSettings!!.isCompassEnabled = false + Assert.assertEquals("Compass should be disabled", false, uiSettings!!.isCompassEnabled) + } + + @Test + fun testCompassGravity() { + Mockito.`when`(compassView.layoutParams).thenReturn(layoutParams) + layoutParams.gravity = Gravity.START + uiSettings!!.compassGravity = Gravity.START + Assert.assertEquals( + "Compass gravity should be same", + Gravity.START.toLong(), + uiSettings!!.compassGravity.toLong() + ) + } + + @Test + fun testCompassMargins() { + Mockito.`when`(projection.contentPadding).thenReturn(intArrayOf(0, 0, 0, 0)) + Mockito.`when`(compassView.layoutParams).thenReturn(layoutParams) + layoutParams.leftMargin = 1 + layoutParams.topMargin = 2 + layoutParams.rightMargin = 3 + layoutParams.bottomMargin = 4 + uiSettings!!.setCompassMargins(1, 2, 3, 4) + Assert.assertTrue("Compass margin left should be same", uiSettings!!.compassMarginLeft == 1) + Assert.assertTrue("Compass margin top should be same", uiSettings!!.compassMarginTop == 2) + Assert.assertTrue( + "Compass margin right should be same", + uiSettings!!.compassMarginRight == 3 + ) + Assert.assertTrue( + "Compass margin bottom should be same", + uiSettings!!.compassMarginBottom == 4 + ) + } + + @Test + fun testCompassFadeWhenFacingNorth() { + Mockito.`when`(compassView.isFadeCompassViewFacingNorth).thenReturn(true) + Assert.assertTrue( + "Compass should fade when facing north by default.", + uiSettings!!.isCompassFadeWhenFacingNorth + ) + uiSettings!!.setCompassFadeFacingNorth(false) + Mockito.`when`(compassView.isFadeCompassViewFacingNorth).thenReturn(false) + Assert.assertFalse( + "Compass fading should be disabled", + uiSettings!!.isCompassFadeWhenFacingNorth + ) + } + + @Test + fun testLogoEnabled() { + uiSettings!!.isLogoInitialized = true + uiSettings!!.isLogoEnabled = true + Assert.assertEquals("Logo should be enabled", true, uiSettings!!.isLogoEnabled) + } + + @Test + fun testLogoDisabled() { + Mockito.`when`(logoView.visibility).thenReturn(View.GONE) + uiSettings!!.isLogoEnabled = false + Assert.assertEquals("Logo should be disabled", false, uiSettings!!.isLogoEnabled) + } + + @Test + fun testLogoGravity() { + layoutParams.gravity = Gravity.END + Mockito.`when`(logoView.layoutParams).thenReturn(layoutParams) + uiSettings!!.logoGravity = Gravity.END + Assert.assertEquals( + "Logo gravity should be same", + Gravity.END.toLong(), + uiSettings!!.logoGravity.toLong() + ) + } + + @Test + fun testLogoMargins() { + Mockito.`when`(projection.contentPadding).thenReturn(intArrayOf(0, 0, 0, 0)) + Mockito.`when`(logoView.layoutParams).thenReturn(layoutParams) + layoutParams.leftMargin = 1 + layoutParams.topMargin = 2 + layoutParams.rightMargin = 3 + layoutParams.bottomMargin = 4 + uiSettings!!.setLogoMargins(1, 2, 3, 4) + Assert.assertTrue("Compass margin left should be same", uiSettings!!.logoMarginLeft == 1) + Assert.assertTrue("Compass margin top should be same", uiSettings!!.logoMarginTop == 2) + Assert.assertTrue("Compass margin right should be same", uiSettings!!.logoMarginRight == 3) + Assert.assertTrue( + "Compass margin bottom should be same", + uiSettings!!.logoMarginBottom == 4 + ) + } + + @Test + fun testAttributionEnabled() { + uiSettings!!.isAttributionInitialized = true + Mockito.`when`(attributionView.visibility).thenReturn(View.VISIBLE) + uiSettings!!.isAttributionEnabled = true + Assert.assertEquals( + "Attribution should be enabled", + true, + uiSettings!!.isAttributionEnabled + ) + } + + @Test + fun testAttributionDisabled() { + Mockito.`when`(attributionView.visibility).thenReturn(View.GONE) + uiSettings!!.isAttributionEnabled = false + Assert.assertEquals( + "Attribution should be disabled", + false, + uiSettings!!.isAttributionEnabled + ) + } + + @Test + fun testAttributionGravity() { + Mockito.`when`(attributionView.layoutParams).thenReturn(layoutParams) + layoutParams.gravity = Gravity.END + uiSettings!!.attributionGravity = Gravity.END + Assert.assertEquals( + "Attribution gravity should be same", + Gravity.END.toLong(), + uiSettings!!.attributionGravity.toLong() + ) + } + + @Test + fun testAttributionMargins() { + Mockito.`when`(attributionView.layoutParams).thenReturn(layoutParams) + Mockito.`when`(projection.contentPadding).thenReturn(intArrayOf(0, 0, 0, 0)) + layoutParams.leftMargin = 1 + layoutParams.topMargin = 2 + layoutParams.rightMargin = 3 + layoutParams.bottomMargin = 4 + uiSettings!!.setAttributionMargins(1, 2, 3, 4) + Assert.assertTrue( + "Attribution margin left should be same", + uiSettings!!.attributionMarginLeft == 1 + ) + Assert.assertTrue( + "Attribution margin top should be same", + uiSettings!!.attributionMarginTop == 2 + ) + Assert.assertTrue( + "Attribution margin right should be same", + uiSettings!!.attributionMarginRight == 3 + ) + Assert.assertTrue( + "Attribution margin bottom should be same", + uiSettings!!.attributionMarginBottom == 4 + ) + } + + @Test + fun testRotateGesturesEnabled() { + uiSettings!!.isRotateGesturesEnabled = true + Assert.assertEquals( + "Rotate gesture should be enabled", + true, + uiSettings!!.isRotateGesturesEnabled + ) + } + + @Test + fun testRotateGesturesDisabled() { + uiSettings!!.isRotateGesturesEnabled = false + Assert.assertEquals( + "Rotate gesture should be disabled", + false, + uiSettings!!.isRotateGesturesEnabled + ) + } + + @Test + fun testRotateGestureChangeAllowed() { + uiSettings!!.isRotateGesturesEnabled = false + Assert.assertEquals( + "Rotate gesture should be false", + false, + uiSettings!!.isRotateGesturesEnabled + ) + uiSettings!!.isRotateGesturesEnabled = true + Assert.assertEquals( + "Rotate gesture should be true", + true, + uiSettings!!.isRotateGesturesEnabled + ) + } + + @Test + fun testTiltGesturesEnabled() { + uiSettings!!.isTiltGesturesEnabled = true + Assert.assertEquals( + "Tilt gesture should be enabled", + true, + uiSettings!!.isTiltGesturesEnabled + ) + } + + @Test + fun testTiltGesturesDisabled() { + uiSettings!!.isTiltGesturesEnabled = false + Assert.assertEquals( + "Tilt gesture should be disabled", + false, + uiSettings!!.isTiltGesturesEnabled + ) + } + + @Test + fun testTiltGestureChangeAllowed() { + uiSettings!!.isTiltGesturesEnabled = false + Assert.assertEquals( + "Tilt gesture should be false", + false, + uiSettings!!.isTiltGesturesEnabled + ) + uiSettings!!.isTiltGesturesEnabled = true + Assert.assertEquals("Tilt gesture should be true", true, uiSettings!!.isTiltGesturesEnabled) + } + + @Test + fun testZoomGesturesEnabled() { + uiSettings!!.isZoomGesturesEnabled = true + Assert.assertEquals( + "Zoom gesture should be enabled", + true, + uiSettings!!.isZoomGesturesEnabled + ) + } + + @Test + fun testZoomGesturesDisabled() { + uiSettings!!.isZoomGesturesEnabled = false + Assert.assertEquals( + "Zoom gesture should be disabled", + false, + uiSettings!!.isZoomGesturesEnabled + ) + } + + @Test + fun testZoomGestureChangeAllowed() { + uiSettings!!.isZoomGesturesEnabled = false + Assert.assertEquals( + "Zoom gesture should be false", + false, + uiSettings!!.isZoomGesturesEnabled + ) + uiSettings!!.isZoomGesturesEnabled = true + Assert.assertEquals("Zoom gesture should be true", true, uiSettings!!.isZoomGesturesEnabled) + } + + @Test + fun testDoubleTapGesturesEnabled() { + uiSettings!!.isDoubleTapGesturesEnabled = true + Assert.assertEquals( + "DoubleTap gesture should be enabled", + true, + uiSettings!!.isDoubleTapGesturesEnabled + ) + } + + @Test + fun testDoubleTapGesturesDisabled() { + uiSettings!!.isDoubleTapGesturesEnabled = false + Assert.assertEquals( + "DoubleTap gesture should be disabled", + false, + uiSettings!!.isDoubleTapGesturesEnabled + ) + } + + @Test + fun testDoubleTapGestureChangeAllowed() { + uiSettings!!.isDoubleTapGesturesEnabled = false + Assert.assertEquals( + "DoubleTap gesture should be false", + false, + uiSettings!!.isDoubleTapGesturesEnabled + ) + uiSettings!!.isDoubleTapGesturesEnabled = true + Assert.assertEquals( + "DoubleTap gesture should be true", + true, + uiSettings!!.isDoubleTapGesturesEnabled + ) + } + + @Test + fun testQuickZoomGesturesEnabled() { + uiSettings!!.isQuickZoomGesturesEnabled = true + Assert.assertEquals( + "QuickZoom gesture should be enabled", + true, + uiSettings!!.isQuickZoomGesturesEnabled + ) + } + + @Test + fun testQuickZoomGesturesDisabled() { + uiSettings!!.isQuickZoomGesturesEnabled = false + Assert.assertEquals( + "QuickZoom gesture should be disabled", + false, + uiSettings!!.isQuickZoomGesturesEnabled + ) + } + + @Test + fun testQuickZoomGestureChangeAllowed() { + uiSettings!!.isQuickZoomGesturesEnabled = false + Assert.assertEquals( + "QuickZoom gesture should be false", + false, + uiSettings!!.isQuickZoomGesturesEnabled + ) + uiSettings!!.isQuickZoomGesturesEnabled = true + Assert.assertEquals( + "QuickZoom gesture should be true", + true, + uiSettings!!.isQuickZoomGesturesEnabled + ) + } + + @Test + fun testScrollGesturesEnabled() { + uiSettings!!.isScrollGesturesEnabled = true + Assert.assertEquals( + "Scroll gesture should be enabled", + true, + uiSettings!!.isScrollGesturesEnabled + ) + } + + @Test + fun testScrollGesturesDisabled() { + uiSettings!!.isScrollGesturesEnabled = false + Assert.assertEquals( + "Scroll gesture should be disabled", + false, + uiSettings!!.isScrollGesturesEnabled + ) + } + + @Test + fun testHorizontalScrollGesturesEnabled() { + uiSettings!!.isHorizontalScrollGesturesEnabled = true + Assert.assertEquals( + "Scroll gesture should be enabled", + true, + uiSettings!!.isHorizontalScrollGesturesEnabled + ) + } + + @Test + fun testHorizontalScrollGesturesDisabled() { + uiSettings!!.isHorizontalScrollGesturesEnabled = false + Assert.assertEquals( + "Scroll gesture should be disabled", + false, + uiSettings!!.isHorizontalScrollGesturesEnabled + ) + } + + @Test + fun testScrollGestureChangeAllowed() { + uiSettings!!.isScrollGesturesEnabled = false + Assert.assertEquals( + "Scroll gesture should be false", + false, + uiSettings!!.isScrollGesturesEnabled + ) + uiSettings!!.isScrollGesturesEnabled = true + Assert.assertEquals( + "Scroll gesture should be true", + true, + uiSettings!!.isScrollGesturesEnabled + ) + } + + @Test + fun testScaleVelocityAnimationEnabled() { + uiSettings!!.isScaleVelocityAnimationEnabled = true + Assert.assertEquals( + "Scale velocity animation should be enabled", + true, + uiSettings!!.isScaleVelocityAnimationEnabled + ) + } + + @Test + fun testScaleVelocityAnimationDisabled() { + uiSettings!!.isScaleVelocityAnimationEnabled = false + Assert.assertEquals( + "Scale velocity animation should be disabled", + false, + uiSettings!!.isScaleVelocityAnimationEnabled + ) + } + + @Test + fun testRotateVelocityAnimationEnabled() { + uiSettings!!.isRotateVelocityAnimationEnabled = true + Assert.assertEquals( + "Rotate velocity animation should be enabled", + true, + uiSettings!!.isRotateVelocityAnimationEnabled + ) + } + + @Test + fun testRotateVelocityAnimationDisabled() { + uiSettings!!.isRotateVelocityAnimationEnabled = false + Assert.assertEquals( + "Rotate velocity animation should be disabled", + false, + uiSettings!!.isRotateVelocityAnimationEnabled + ) + } + + @Test + fun testFlingVelocityAnimationEnabled() { + uiSettings!!.isFlingVelocityAnimationEnabled = true + Assert.assertEquals( + "Fling velocity animation should be enabled", + true, + uiSettings!!.isFlingVelocityAnimationEnabled + ) + } + + @Test + fun testFlingVelocityAnimationDisabled() { + uiSettings!!.isFlingVelocityAnimationEnabled = false + Assert.assertEquals( + "Fling velocity animation should be disabled", + false, + uiSettings!!.isFlingVelocityAnimationEnabled + ) + } + + @Test + fun testAllVelocityAnimationsEnabled() { + uiSettings!!.setAllVelocityAnimationsEnabled(true) + Assert.assertEquals( + "Scale velocity animation should be enabled", + true, + uiSettings!!.isScaleVelocityAnimationEnabled + ) + Assert.assertEquals( + "Rotate velocity animation should be enabled", + true, + uiSettings!!.isRotateVelocityAnimationEnabled + ) + Assert.assertEquals( + "Fling velocity animation should be enabled", + true, + uiSettings!!.isFlingVelocityAnimationEnabled + ) + } + + @Test + fun testAllVelocityAnimationsDisabled() { + uiSettings!!.setAllVelocityAnimationsEnabled(false) + Assert.assertEquals( + "Scale velocity animation should be disabled", + false, + uiSettings!!.isScaleVelocityAnimationEnabled + ) + Assert.assertEquals( + "Rotate velocity animation should be disabled", + false, + uiSettings!!.isRotateVelocityAnimationEnabled + ) + Assert.assertEquals( + "Fling velocity animation should be disabled", + false, + uiSettings!!.isFlingVelocityAnimationEnabled + ) + } + + @Test + fun testDisableRotateWhenScalingEnabled() { + uiSettings!!.isDisableRotateWhenScaling = true + Assert.assertEquals( + "Rotate disabling should be enabled", + true, + uiSettings!!.isDisableRotateWhenScaling + ) + } + + @Test + fun testDisableRotateWhenScalingDisabled() { + uiSettings!!.isDisableRotateWhenScaling = false + Assert.assertEquals( + "Rotate disabling should be disabled", + false, + uiSettings!!.isDisableRotateWhenScaling + ) + } + + @Test + fun testIncreaseScaleThresholdWhenRotatingEnabled() { + uiSettings!!.isIncreaseScaleThresholdWhenRotating = true + Assert.assertEquals( + "Scale threshold increase should be enabled", + true, + uiSettings!!.isIncreaseScaleThresholdWhenRotating + ) + } + + @Test + fun testIncreaseScaleThresholdWhenRotatingDisabled() { + uiSettings!!.isIncreaseScaleThresholdWhenRotating = false + Assert.assertEquals( + "Scale threshold increase should be disabled", + false, + uiSettings!!.isIncreaseScaleThresholdWhenRotating + ) + } + + @Test + fun testAllGesturesEnabled() { + uiSettings!!.setAllGesturesEnabled(true) + Assert.assertEquals( + "Rotate gesture should be enabled", + true, + uiSettings!!.isRotateGesturesEnabled + ) + Assert.assertEquals( + "Tilt gesture should be enabled", + true, + uiSettings!!.isTiltGesturesEnabled + ) + Assert.assertEquals( + "Zoom gesture should be enabled", + true, + uiSettings!!.isZoomGesturesEnabled + ) + Assert.assertEquals( + "Scroll gesture should be enabled", + true, + uiSettings!!.isScrollGesturesEnabled + ) + } + + @Test + fun testAllGesturesDisabled() { + uiSettings!!.setAllGesturesEnabled(false) + Assert.assertEquals( + "Rotate gesture should be enabled", + false, + uiSettings!!.isRotateGesturesEnabled + ) + Assert.assertEquals( + "Tilt gesture should be disabled", + false, + uiSettings!!.isTiltGesturesEnabled + ) + Assert.assertEquals( + "Zoom gesture should be disabled", + false, + uiSettings!!.isZoomGesturesEnabled + ) + Assert.assertEquals( + "Scroll gesture should be disabled", + false, + uiSettings!!.isScrollGesturesEnabled + ) + } + + @Test + fun testAreAllGesturesEnabled() { + uiSettings!!.setAllGesturesEnabled(true) + Assert.assertEquals( + "All gestures check should return true", + true, + uiSettings!!.areAllGesturesEnabled() + ) + } + + @Test + fun testAreAllGesturesEnabledWithOneGestureDisabled() { + uiSettings!!.setAllGesturesEnabled(true) + uiSettings!!.isScrollGesturesEnabled = false + Assert.assertEquals( + "All gestures check should return false", + false, + uiSettings!!.areAllGesturesEnabled() + ) + } + + @Test + fun testZoomRateDefaultValue() { + Assert.assertEquals( + "Default zoom rate should be 1.0f", + 1.0f, + uiSettings!!.zoomRate, + 0f + ) + } + + @Test + fun testZoomRate() { + uiSettings!!.zoomRate = 0.83f + Assert.assertEquals( + "Zoom rate should be 0.83f", + 0.83f, + uiSettings!!.zoomRate, + 0f + ) + } + + @Test + fun testUpdateWhenCompassViewNotHidden() { + val cameraPosition = CameraPosition.Builder(CameraPosition.DEFAULT).bearing(24.0).build() + Mockito.`when`(compassView.isHidden).thenReturn(false) + uiSettings!!.update(cameraPosition) + Mockito.verify(compassView).update(-24.0) + } + + @Test + fun testUpdateWhenCompassViewHidden() { + val cameraPosition = CameraPosition.Builder(CameraPosition.DEFAULT).bearing(24.0).build() + Mockito.`when`(compassView.isHidden).thenReturn(true) + uiSettings!!.update(cameraPosition) + Mockito.verify(compassView).update(-24.0) + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/style/expressions/ExpressionTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/style/expressions/ExpressionTest.java deleted file mode 100644 index 729b58def..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/style/expressions/ExpressionTest.java +++ /dev/null @@ -1,1598 +0,0 @@ -package com.mapbox.mapboxsdk.style.expressions; - -import android.graphics.Color; - -import com.mapbox.geojson.Point; -import com.mapbox.geojson.Polygon; -import com.mapbox.mapboxsdk.style.layers.PropertyValue; -import com.mapbox.mapboxsdk.utils.ColorUtils; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import static com.mapbox.mapboxsdk.style.expressions.Expression.FormatOption.formatFontScale; -import static com.mapbox.mapboxsdk.style.expressions.Expression.FormatOption.formatTextColor; -import static com.mapbox.mapboxsdk.style.expressions.Expression.FormatOption.formatTextFont; -import static com.mapbox.mapboxsdk.style.expressions.Expression.abs; -import static com.mapbox.mapboxsdk.style.expressions.Expression.acos; -import static com.mapbox.mapboxsdk.style.expressions.Expression.all; -import static com.mapbox.mapboxsdk.style.expressions.Expression.any; -import static com.mapbox.mapboxsdk.style.expressions.Expression.array; -import static com.mapbox.mapboxsdk.style.expressions.Expression.asin; -import static com.mapbox.mapboxsdk.style.expressions.Expression.at; -import static com.mapbox.mapboxsdk.style.expressions.Expression.atan; -import static com.mapbox.mapboxsdk.style.expressions.Expression.bool; -import static com.mapbox.mapboxsdk.style.expressions.Expression.ceil; -import static com.mapbox.mapboxsdk.style.expressions.Expression.coalesce; -import static com.mapbox.mapboxsdk.style.expressions.Expression.collator; -import static com.mapbox.mapboxsdk.style.expressions.Expression.color; -import static com.mapbox.mapboxsdk.style.expressions.Expression.concat; -import static com.mapbox.mapboxsdk.style.expressions.Expression.cos; -import static com.mapbox.mapboxsdk.style.expressions.Expression.cubicBezier; -import static com.mapbox.mapboxsdk.style.expressions.Expression.distance; -import static com.mapbox.mapboxsdk.style.expressions.Expression.division; -import static com.mapbox.mapboxsdk.style.expressions.Expression.downcase; -import static com.mapbox.mapboxsdk.style.expressions.Expression.e; -import static com.mapbox.mapboxsdk.style.expressions.Expression.eq; -import static com.mapbox.mapboxsdk.style.expressions.Expression.exponential; -import static com.mapbox.mapboxsdk.style.expressions.Expression.floor; -import static com.mapbox.mapboxsdk.style.expressions.Expression.format; -import static com.mapbox.mapboxsdk.style.expressions.Expression.formatEntry; -import static com.mapbox.mapboxsdk.style.expressions.Expression.geometryType; -import static com.mapbox.mapboxsdk.style.expressions.Expression.get; -import static com.mapbox.mapboxsdk.style.expressions.Expression.gt; -import static com.mapbox.mapboxsdk.style.expressions.Expression.gte; -import static com.mapbox.mapboxsdk.style.expressions.Expression.has; -import static com.mapbox.mapboxsdk.style.expressions.Expression.heatmapDensity; -import static com.mapbox.mapboxsdk.style.expressions.Expression.id; -import static com.mapbox.mapboxsdk.style.expressions.Expression.in; -import static com.mapbox.mapboxsdk.style.expressions.Expression.interpolate; -import static com.mapbox.mapboxsdk.style.expressions.Expression.isSupportedScript; -import static com.mapbox.mapboxsdk.style.expressions.Expression.length; -import static com.mapbox.mapboxsdk.style.expressions.Expression.let; -import static com.mapbox.mapboxsdk.style.expressions.Expression.linear; -import static com.mapbox.mapboxsdk.style.expressions.Expression.literal; -import static com.mapbox.mapboxsdk.style.expressions.Expression.ln; -import static com.mapbox.mapboxsdk.style.expressions.Expression.ln2; -import static com.mapbox.mapboxsdk.style.expressions.Expression.log10; -import static com.mapbox.mapboxsdk.style.expressions.Expression.log2; -import static com.mapbox.mapboxsdk.style.expressions.Expression.lt; -import static com.mapbox.mapboxsdk.style.expressions.Expression.lte; -import static com.mapbox.mapboxsdk.style.expressions.Expression.match; -import static com.mapbox.mapboxsdk.style.expressions.Expression.max; -import static com.mapbox.mapboxsdk.style.expressions.Expression.min; -import static com.mapbox.mapboxsdk.style.expressions.Expression.mod; -import static com.mapbox.mapboxsdk.style.expressions.Expression.neq; -import static com.mapbox.mapboxsdk.style.expressions.Expression.not; -import static com.mapbox.mapboxsdk.style.expressions.Expression.number; -import static com.mapbox.mapboxsdk.style.expressions.Expression.object; -import static com.mapbox.mapboxsdk.style.expressions.Expression.pi; -import static com.mapbox.mapboxsdk.style.expressions.Expression.pow; -import static com.mapbox.mapboxsdk.style.expressions.Expression.product; -import static com.mapbox.mapboxsdk.style.expressions.Expression.properties; -import static com.mapbox.mapboxsdk.style.expressions.Expression.raw; -import static com.mapbox.mapboxsdk.style.expressions.Expression.resolvedLocale; -import static com.mapbox.mapboxsdk.style.expressions.Expression.rgb; -import static com.mapbox.mapboxsdk.style.expressions.Expression.rgba; -import static com.mapbox.mapboxsdk.style.expressions.Expression.round; -import static com.mapbox.mapboxsdk.style.expressions.Expression.sin; -import static com.mapbox.mapboxsdk.style.expressions.Expression.sqrt; -import static com.mapbox.mapboxsdk.style.expressions.Expression.step; -import static com.mapbox.mapboxsdk.style.expressions.Expression.stop; -import static com.mapbox.mapboxsdk.style.expressions.Expression.string; -import static com.mapbox.mapboxsdk.style.expressions.Expression.subtract; -import static com.mapbox.mapboxsdk.style.expressions.Expression.sum; -import static com.mapbox.mapboxsdk.style.expressions.Expression.switchCase; -import static com.mapbox.mapboxsdk.style.expressions.Expression.tan; -import static com.mapbox.mapboxsdk.style.expressions.Expression.toBool; -import static com.mapbox.mapboxsdk.style.expressions.Expression.toColor; -import static com.mapbox.mapboxsdk.style.expressions.Expression.toNumber; -import static com.mapbox.mapboxsdk.style.expressions.Expression.toRgba; -import static com.mapbox.mapboxsdk.style.expressions.Expression.typeOf; -import static com.mapbox.mapboxsdk.style.expressions.Expression.upcase; -import static com.mapbox.mapboxsdk.style.expressions.Expression.var; -import static com.mapbox.mapboxsdk.style.expressions.Expression.within; -import static com.mapbox.mapboxsdk.style.expressions.Expression.zoom; -import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineOpacity; -import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineWidth; -import static junit.framework.Assert.assertTrue; -import static org.junit.Assert.assertEquals; - -/** - * Expression unit tests that validate the expression output with the expected Object[]array representation. - */ -@RunWith(RobolectricTestRunner.class) -public class ExpressionTest { - - @Test - public void testPropertyValueIsExpression() { - PropertyValue property = lineWidth(Expression.get("width")); - assertTrue(property.isExpression()); - } - - @Test - public void testPropertyValueEqualsExpression() { - PropertyValue property = lineWidth(Expression.get("width")); - assertEquals(Expression.get("width"), property.getExpression()); - } - - @Test - public void testRgb() throws Exception { - Object[] expected = new Object[] {"rgb", 0f, 0f, 0f}; - Object[] actual = rgb(literal(0), literal(0), literal(0)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testRgbLiteral() throws Exception { - Object[] expected = new Object[] {"rgb", 0f, 0f, 0f}; - Object[] actual = rgb(0, 0, 0).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testRgba() throws Exception { - Object[] expected = new Object[] {"rgba", 0f, 0f, 0f, 1f}; - Object[] actual = rgba(literal(0), literal(0), literal(0), literal(1)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testRgbaLiteral() throws Exception { - Object[] expected = new Object[] {"rgba", 0f, 0f, 0f, 1f}; - Object[] actual = rgba(0, 0, 0, 1).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testToRgba() throws Exception { - Object[] expected = new Object[] {"to-rgba", new Object[] {"to-color", "rgba(255, 0, 0, 1)"}}; - Object[] actual = toRgba(toColor(literal(ColorUtils.colorToRgbaString(Color.RED)))).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testEq() throws Exception { - Object[] expected = new Object[] {"==", 1f, 1f}; - Object[] actual = eq(literal(1), literal(1)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testEqLiteral() throws Exception { - Object[] expected = new Object[] {"==", 1f, 1f}; - Object[] actual = eq(literal(1), 1).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testEqExpression() throws Exception { - Object[] expected = new Object[] {"==", new Object[] {"get", "hello"}, 1f}; - Object[] actual = eq(get("hello"), 1).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testNeq() throws Exception { - Object[] expected = new Object[] {"!=", 0f, 1f}; - Object[] actual = neq(literal(0), literal(1)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testNeqLiteral() throws Exception { - Object[] expected = new Object[] {"!=", 0f, 1f}; - Object[] actual = neq(literal(0), 1).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testNeqExpression() throws Exception { - Object[] expected = new Object[] {"!=", new Object[] {"get", "hello"}, 1f}; - Object[] actual = neq(get("hello"), 1).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testGt() throws Exception { - Object[] expected = new Object[] {">", 0f, 1f}; - Object[] actual = gt(literal(0), literal(1)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testGtLiteral() throws Exception { - Object[] expected = new Object[] {">", 0f, 1f}; - Object[] actual = gt(literal(0), 1).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testGtExpression() throws Exception { - Object[] expected = new Object[] {">", new Object[] {"get", "hello"}, 1f}; - Object[] actual = gt(get("hello"), 1).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testLt() throws Exception { - Object[] expected = new Object[] {"<", 1f, 0f}; - Object[] actual = lt(literal(1), literal(0)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testLtLiteral() throws Exception { - Object[] expected = new Object[] {"<", 1f, 0f}; - Object[] actual = lt(literal(1), 0).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testLtExpression() throws Exception { - Object[] expected = new Object[] {"<", new Object[] {"get", "hello"}, 1f}; - Object[] actual = lt(get("hello"), 1).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testGte() throws Exception { - Object[] expected = new Object[] {">=", 1f, 1f}; - Object[] actual = gte(literal(1), literal(1)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testGteLiteral() throws Exception { - Object[] expected = new Object[] {">=", 1f, 1f}; - Object[] actual = gte(literal(1), 1).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testGteExpression() throws Exception { - Object[] expected = new Object[] {">=", new Object[] {"get", "hello"}, 1f}; - Object[] actual = gte(get("hello"), 1).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testLte() throws Exception { - Object[] expected = new Object[] {"<=", 1f, 1f}; - Object[] actual = lte(literal(1), literal(1)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testLteExpression() throws Exception { - Object[] expected = new Object[] {"<=", new Object[] {"get", "hello"}, 1f}; - Object[] actual = lte(get("hello"), 1).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testLteLiteral() throws Exception { - Object[] expected = new Object[] {"<=", 1f, 1f}; - Object[] actual = lte(literal(1), 1).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testAll() throws Exception { - Object[] expected = new Object[] {"all", true, true, true}; - Object[] actual = all(literal(true), literal(true), literal(true)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testAny() throws Exception { - Object[] expected = new Object[] {"any", true, false, false}; - Object[] actual = any(literal(true), literal(false), literal(false)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testNot() throws Exception { - Object[] expected = new Object[] {"!", false}; - Object[] actual = not(literal(false)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testNotLiteral() throws Exception { - Object[] expected = new Object[] {"!", false}; - Object[] actual = not(false).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testSwitchCase() throws Exception { - Object[] expectedCaseOneGet = new Object[] {"get", "key1"}; - Object[] expectedCaseOne = new Object[] {"==", expectedCaseOneGet, "value1"}; - Object[] expectedCaseTwoGet = new Object[] {"get", "key2"}; - Object[] expectedCaseTwo = new Object[] {"!=", expectedCaseTwoGet, "value2"}; - Object[] expected = new Object[] {"case", expectedCaseOne, expectedCaseTwo}; - - Object[] actual = switchCase( - eq(get(literal("key1")), literal("value1")), - neq(get(literal("key2")), literal("value2")) - ).toArray(); - - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testSwitchCaseLiteral() throws Exception { - Object[] expectedCaseOneGet = new Object[] {"get", "key1"}; - Object[] expectedCaseOne = new Object[] {"==", expectedCaseOneGet, "value1"}; - Object[] expectedCaseTwoGet = new Object[] {"get", "key2"}; - Object[] expectedCaseTwo = new Object[] {"!=", expectedCaseTwoGet, "value2"}; - Object[] expected = new Object[] {"case", expectedCaseOne, expectedCaseTwo}; - - Object[] actual = switchCase( - eq(get("key1"), literal("value1")), - neq(get("key2"), literal("value2")) - ).toArray(); - - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testMatch() throws Exception { - String input = "input"; - String[] labels = new String[] {"a", "b", "c"}; - String[] outputs = new String[] {"1", "2", "3"}; - String defaultOutput = "0"; - - Object[] expected = new Object[] {"match", input, - labels[0], outputs[0], - labels[1], outputs[1], - labels[2], outputs[2], - defaultOutput}; - - Object[] actual = match(literal(input), - literal(labels[0]), literal(outputs[0]), - literal(labels[1]), literal(outputs[1]), - literal(labels[2]), literal(outputs[2]), - literal(defaultOutput) - ).toArray(); - - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testMatchWithStops() throws Exception { - String input = "input"; - String[] labels = new String[] {"a", "b", "c"}; - String[] outputs = new String[] {"1", "2", "3"}; - String defaultOutput = "0"; - - Object[] expected = new Object[] {"match", input, - labels[0], outputs[0], - labels[1], outputs[1], - labels[2], outputs[2], - defaultOutput}; - - Object[] actual = match(literal(input), literal(defaultOutput), - stop(labels[0], outputs[0]), - stop(labels[1], outputs[1]), - stop(labels[2], outputs[2])) - .toArray(); - - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testCoalesce() throws Exception { - Object[] expectedGetOne = new Object[] {"get", "invalidKey"}; - Object[] expectedGetTwo = new Object[] {"get", "validKey"}; - Object[] expected = new Object[] {"coalesce", expectedGetOne, expectedGetTwo}; - - Object[] actual = coalesce( - get(literal("invalidKey")), - get(literal("validKey")) - ).toArray(); - - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testCoalesceLiteral() throws Exception { - Object[] expectedGetOne = new Object[] {"get", "invalidKey"}; - Object[] expectedGetTwo = new Object[] {"get", "validKey"}; - Object[] expected = new Object[] {"coalesce", expectedGetOne, expectedGetTwo}; - - Object[] actual = coalesce( - get("invalidKey"), - get("validKey") - ).toArray(); - - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testProperties() throws Exception { - Object[] expected = new Object[] {"properties"}; - Object[] actual = properties().toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testGeometryType() throws Exception { - Object[] expected = new Object[] {"geometry-type"}; - Object[] actual = geometryType().toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testId() throws Exception { - Object[] expected = new Object[] {"id"}; - Object[] actual = id().toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testHeatmapDensity() throws Exception { - Object[] expected = new Object[] {"heatmap-density"}; - Object[] actual = heatmapDensity().toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testAt() throws Exception { - Object[] expected = new Object[] {"at", 3f, new Object[] {"literal", new Object[] {"one", "two"}}}; - Object[] actual = at(literal(3), literal(new Object[] {"one", "two"})).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testInString() throws Exception { - Object[] expected = new Object[] {"in", "one", "onetwo"}; - Object[] actual = in(literal("one"), literal("onetwo")).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testWithIn() throws Exception { - List> lngLats = Collections.singletonList( - Arrays.asList( - Point.fromLngLat(0, 0), - Point.fromLngLat(0, 5), - Point.fromLngLat(5, 5), - Point.fromLngLat(5, 0), - Point.fromLngLat(0, 0) - ) - ); - - Polygon polygon = Polygon.fromLngLats(lngLats); - HashMap map = new HashMap<>(); - map.put("type", "Polygon"); - map.put("json", polygon.toJson()); - Object[] expected = new Object[] {"within", map}; - Object[] actual = within(polygon).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testInNumber() throws Exception { - Object[] expected = new Object[] {"in", 1f, new Object[] {"literal", new Object[] {1f, 2f}}}; - Object[] actual = in(literal(1f), literal(new Object[] {1f, 2f})).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - - @Test - public void testDistance() throws Exception { - Point point = Point.fromLngLat(1, 2); - HashMap map = new HashMap<>(); - map.put("json", point.toJson()); - Object[] expected = new Object[] {"distance", map}; - Object[] actual = distance(point).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - - @Test - public void testInArray() throws Exception { - Object[] expected = new Object[] {"in", "one", new Object[] {"literal", new Object[] {"one", "two"}}}; - Object[] actual = in(literal("one"), literal(new Object[] {"one", "two"})).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testAtLiteral() throws Exception { - Object[] expected = new Object[] {"at", 3f, new Object[] {"literal", new Object[] {"one", "two"}}}; - Object[] actual = at(3, literal(new Object[] {"one", "two"})).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testAtExpression() throws Exception { - Object[] expected = new Object[] {"at", 3f, new Object[] {"properties"}}; - Object[] actual = at(literal(3), properties()).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testGet() throws Exception { - Object[] expected = new Object[] {"get", "key"}; - Object[] actual = get(literal("key")).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testGetLiteral() throws Exception { - Object[] expected = new Object[] {"get", "key"}; - Object[] actual = get("key").toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testGetObject() throws Exception { - Object[] expected = new Object[] {"get", "key", new Object[] {"properties"}}; - Object[] actual = get(literal("key"), properties()).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testGetObjectLiteral() throws Exception { - Object[] expected = new Object[] {"get", "key", new Object[] {"properties"}}; - Object[] actual = get("key", properties()).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testHas() throws Exception { - Object[] expected = new Object[] {"has", "key"}; - Object[] actual = has(literal("key")).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testHasLiteral() throws Exception { - Object[] expected = new Object[] {"has", "key"}; - Object[] actual = has("key").toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testHasObject() throws Exception { - Object[] expected = new Object[] {"has", "key", new Object[] {"properties"}}; - Object[] actual = has(literal("key"), properties()).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testHasObjectLiteral() throws Exception { - Object[] expected = new Object[] {"has", "key", new Object[] {"properties"}}; - Object[] actual = has("key", properties()).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testHasExpression() throws Exception { - Object[] expected = new Object[] {"has", new Object[] {"get", "key"}, new Object[] {"properties"}}; - Object[] actual = has(get(literal("key")), properties()).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testHasExpressionLiteral() throws Exception { - Object[] expected = new Object[] {"has", new Object[] {"get", "key"}, new Object[] {"properties"}}; - Object[] actual = has(get("key"), properties()).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testLength() throws Exception { - Object[] expected = new Object[] {"length", "key"}; - Object[] actual = length(literal("key")).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testLengthLiteral() throws Exception { - Object[] expected = new Object[] {"length", "key"}; - Object[] actual = length("key").toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testLengthExpression() throws Exception { - Object[] expected = new Object[] {"length", new Object[] {"get", "key"}}; - Object[] actual = length(get(literal("key"))).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testLn2() throws Exception { - Object[] expected = new Object[] {"ln2"}; - Object[] actual = ln2().toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testPi() throws Exception { - Object[] expected = new Object[] {"pi"}; - Object[] actual = pi().toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testE() throws Exception { - Object[] expected = new Object[] {"e"}; - Object[] actual = e().toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testSum() throws Exception { - Object[] expected = new Object[] {"+", 1f, 2f}; - Object[] actual = sum(literal(1), literal(2)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testSumLiteral() throws Exception { - Object[] expected = new Object[] {"+", 1f, 2f}; - Object[] actual = sum(1, 2).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testProduct() throws Exception { - Object[] expected = new Object[] {"*", 1f, 2f}; - Object[] actual = product(literal(1), literal(2)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testProductLiteral() throws Exception { - Object[] expected = new Object[] {"*", 1f, 2f}; - Object[] actual = product(1, 2).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testSubtract() throws Exception { - Object[] expected = new Object[] {"-", 2f, 1f}; - Object[] actual = subtract(literal(2), literal(1)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testSubtractLiteral() throws Exception { - Object[] expected = new Object[] {"-", 2f, 1f}; - Object[] actual = subtract(2, 1).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testDivision() throws Exception { - Object[] expected = new Object[] {"/", 2f, 1f}; - Object[] actual = division(literal(2), literal(1)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testDivisionLiteral() throws Exception { - Object[] expected = new Object[] {"/", 2f, 1f}; - Object[] actual = division(2, 1).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testDivisionWithNestedGet() throws Exception { - Object nestedGet = new Object[] {"get", "key"}; - Object[] expected = new Object[] {"/", 2f, nestedGet}; - Object[] actual = division(literal(2), get(literal("key"))).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testMod() throws Exception { - Object[] expected = new Object[] {"%", 1f, 3f}; - Object[] actual = mod(literal(1), literal(3)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testModLiteral() throws Exception { - Object[] expected = new Object[] {"%", 1f, 3f}; - Object[] actual = mod(1, 3).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testPow() throws Exception { - Object[] expected = new Object[] {"^", 2f, 3f}; - Object[] actual = pow(literal(2), literal(3)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testPowLiteral() throws Exception { - Object[] expected = new Object[] {"^", 2f, 3f}; - Object[] actual = pow(2, 3).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testSqrt() throws Exception { - Object[] expected = new Object[] {"sqrt", 4f}; - Object[] actual = sqrt(literal(4)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testSqrtLiteral() throws Exception { - Object[] expected = new Object[] {"sqrt", 4f}; - Object[] actual = sqrt(4).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testLog10() throws Exception { - Object[] expected = new Object[] {"log10", 10f}; - Object[] actual = log10(literal(10f)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testLog10Literal() throws Exception { - Object[] expected = new Object[] {"log10", 10f}; - Object[] actual = log10(10).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testLn() throws Exception { - Object[] expected = new Object[] {"ln", 2f}; - Object[] actual = ln(literal(2)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testLnLiteral() throws Exception { - Object[] expected = new Object[] {"ln", 2f}; - Object[] actual = ln(2).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testLog2() throws Exception { - Object[] expected = new Object[] {"log2", 16f}; - Object[] actual = log2(literal(16)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testLog2Literal() throws Exception { - Object[] expected = new Object[] {"log2", 16f}; - Object[] actual = log2(16).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testSin() throws Exception { - Object[] expected = new Object[] {"sin", 45f}; - Object[] actual = sin(literal(45)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testSinLiteral() throws Exception { - Object[] expected = new Object[] {"sin", 45f}; - Object[] actual = sin(45).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testCos() throws Exception { - Object[] expected = new Object[] {"cos", 45f}; - Object[] actual = cos(literal(45)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testCosLiteral() throws Exception { - Object[] expected = new Object[] {"cos", 45f}; - Object[] actual = cos(45).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testTan() throws Exception { - Object[] expected = new Object[] {"tan", 45f}; - Object[] actual = tan(literal(45)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testTanLiteral() throws Exception { - Object[] expected = new Object[] {"tan", 45f}; - Object[] actual = tan(45).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testAsin() throws Exception { - Object[] expected = new Object[] {"asin", 45f}; - Object[] actual = asin(literal(45)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testAsinLiteral() throws Exception { - Object[] expected = new Object[] {"asin", 45f}; - Object[] actual = asin(45).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testAcos() throws Exception { - Object[] expected = new Object[] {"acos", 45f}; - Object[] actual = acos(literal(45)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testAcosLiteral() throws Exception { - Object[] expected = new Object[] {"acos", 45f}; - Object[] actual = acos(45).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testAtan() throws Exception { - Object[] expected = new Object[] {"atan", 45f}; - Object[] actual = atan(literal(45)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testAtanLiteral() throws Exception { - Object[] expected = new Object[] {"atan", 45f}; - Object[] actual = atan(45).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testMin() throws Exception { - Object[] expected = new Object[] {"min", 0f, 1f, 2f, 3f}; - Object[] actual = min(literal(0), literal(1), literal(2), literal(3)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testMinLiteral() throws Exception { - Object[] expected = new Object[] {"min", 0f, 1f, 2f, 3f}; - Object[] actual = min(0, 1, 2, 3).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testMax() throws Exception { - Object[] expected = new Object[] {"max", 0f, 1f, 2f, 3f}; - Object[] actual = max(literal(0), literal(1), literal(2), literal(3)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testMaxLiteral() throws Exception { - Object[] expected = new Object[] {"max", 0f, 1f, 2f, 3f}; - Object[] actual = max(0, 1, 2, 3).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testUpcase() throws Exception { - Object[] expected = new Object[] {"upcase", "string"}; - Object[] actual = upcase(literal("string")).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testUpcaseLiteral() throws Exception { - Object[] expected = new Object[] {"upcase", "string"}; - Object[] actual = upcase("string").toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testDowncase() throws Exception { - Object[] expected = new Object[] {"downcase", "string"}; - Object[] actual = downcase(literal("string")).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testDowncaseLiteral() throws Exception { - Object[] expected = new Object[] {"downcase", "string"}; - Object[] actual = downcase("string").toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testConcat() throws Exception { - Object[] expected = new Object[] {"concat", "foo", "bar"}; - Object[] actual = concat(literal("foo"), literal("bar")).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testConcatLiteral() throws Exception { - Object[] expected = new Object[] {"concat", "foo", "bar"}; - Object[] actual = concat("foo", "bar").toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testArray() throws Exception { - Object[] get = new Object[] {"get", "keyToArray"}; - Object[] expected = new Object[] {"array", get}; - Object[] actual = array(get(literal("keyToArray"))).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testArrayLiteral() throws Exception { - Object[] get = new Object[] {"get", "keyToArray"}; - Object[] expected = new Object[] {"array", get}; - Object[] actual = array(get("keyToArray")).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testTypeOf() throws Exception { - Object[] expected = new Object[] {"typeof", "value"}; - Object[] actual = typeOf(literal("value")).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testString() throws Exception { - Object[] expected = new Object[] {"string", "value"}; - Object[] actual = string(literal("value")).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testNumber() throws Exception { - Object[] expected = new Object[] {"number", 1f}; - Object[] actual = number(literal(1)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testBool() throws Exception { - Object[] expected = new Object[] {"boolean", true}; - Object[] actual = bool(literal(true)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testObject() throws Exception { - Object object = new Object(); - Object[] expected = new Object[] {"object", object}; - Object[] actual = object(literal(object)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testToString() throws Exception { - Object[] expected = new Object[] {"to-string", 3f}; - Object[] actual = Expression.toString(literal(3)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testToNumber() throws Exception { - Object[] expected = new Object[] {"to-number", "3"}; - Object[] actual = toNumber(literal("3")).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testToBool() throws Exception { - Object[] expected = new Object[] {"to-boolean", "true"}; - Object[] actual = toBool(literal("true")).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testToColor() throws Exception { - Object[] expected = new Object[] {"to-color", "value"}; - Object[] actual = toColor(literal("value")).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testLet() throws Exception { - Object[] expected = new Object[] {"let", "letName", "value"}; - Object[] actual = let(literal("letName"), literal("value")).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testVar() throws Exception { - Object[] expected = new Object[] {"var", "letName"}; - Object[] actual = var(literal("letName")).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testVarLiteral() throws Exception { - Object[] expected = new Object[] {"var", "letName"}; - Object[] actual = var("letName").toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testVarExpression() throws Exception { - Object[] expected = new Object[] {"var", new Object[] {"get", "letName"}}; - Object[] actual = var(get(literal("letName"))).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testVarExpressionLiteral() throws Exception { - Object[] expected = new Object[] {"var", new Object[] {"get", "letName"}}; - Object[] actual = var(get("letName")).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testZoom() throws Exception { - Object[] expected = new Object[] {"zoom"}; - Object[] actual = zoom().toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testStepBasic() throws Exception { - Object[] expected = new Object[] {"step", 12f, 11f, 0f, 111f, 1f, 1111f}; - Object[] actual = step(literal(12), literal(11), literal(0), literal(111), literal(1), literal(1111)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testStepBasicLiteral() throws Exception { - Object[] expected = new Object[] {"step", new Object[] {"get", "line-width"}, 11f, 0f, 111f, 1f, 1111f}; - Object[] actual = step(get("line-width"), literal(11), stop(0, 111), stop(1, 1111)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testStepExpression() throws Exception { - Object[] input = new Object[] {"get", "key"}; - Object[] number = new Object[] {"to-number", input}; - Object[] expected = new Object[] {"step", number, 11f, 0f, 111f, 1f, 1111f}; - Object[] actual = step(toNumber(get(literal("key"))), - literal(11), literal(0), literal(111), literal(1), literal(1111)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testStepExpressionLiteral() throws Exception { - Object[] input = new Object[] {"get", "key"}; - Object[] number = new Object[] {"to-number", input}; - Object[] expected = new Object[] {"step", number, 11f, 0f, 111f, 1f, 1111f}; - Object[] actual = step(toNumber(get("key")), literal(11), stop(0, 111), stop(1, 1111)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testLinear() throws Exception { - Object[] expected = new Object[] {"interpolate", new Object[] {"linear"}, 12f, 0f, 1f, 1f, 2f, 2f, 3f}; - Object[] actual = interpolate( - linear(), literal(12), - literal(0), literal(1), - literal(1), literal(2), - literal(2), literal(3)) - .toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testLinearStops() throws Exception { - Object[] expected = new Object[] {"interpolate", new Object[] {"linear"}, 12f, 0f, 1f, 1f, 2f, 2f, 3f}; - Object[] actual = interpolate(linear(), literal(12), stop(0, 1), stop(1, 2), stop(2, 3)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testExponential() throws Exception { - Object[] exponential = new Object[] {"exponential", 12f}; - Object[] get = new Object[] {"get", "x"}; - Object[] expected = new Object[] {"interpolate", exponential, get, 0f, 100f, 200f}; - Object[] actual = interpolate(exponential(literal(12)), - get(literal("x")), literal(0), literal(100), literal(200)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testExponentialLiteral() throws Exception { - Object[] exponential = new Object[] {"exponential", 12f}; - Object[] get = new Object[] {"get", "x"}; - Object[] expected = new Object[] {"interpolate", exponential, get, 0f, 100f, 100f, 200f}; - Object[] actual = interpolate(exponential(12), get("x"), stop(0, 100), stop(100, 200)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testExponentialExpressionLiteral() throws Exception { - Object[] getX = new Object[] {"get", "x"}; - Object[] exponential = new Object[] {"exponential", getX}; - Object[] getY = new Object[] {"get", "y"}; - Object[] expected = new Object[] {"interpolate", exponential, getY, 0f, 100f, 100f, 200f}; - Object[] actual = interpolate(exponential(get("x")), get("y"), stop(0, 100), stop(100, 200)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testCubicBezier() throws Exception { - Object[] cubicBezier = new Object[] {"cubic-bezier", 1f, 1f, 1f, 1f}; - Object[] get = new Object[] {"get", "x"}; - Object[] expected = new Object[] {"interpolate", cubicBezier, get, 0f, 100f, 100f, 200f}; - Object[] actual = interpolate(cubicBezier(literal(1), literal(1), literal(1), literal(1)), - get(literal("x")), literal(0), literal(100), literal(100), literal(200)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testCubicBezierLiteral() throws Exception { - Object[] cubicBezier = new Object[] {"cubic-bezier", 1f, 1f, 1f, 1f}; - Object[] get = new Object[] {"get", "x"}; - Object[] expected = new Object[] {"interpolate", cubicBezier, get, 0f, 100f, 100f, 200f}; - Object[] actual = interpolate(cubicBezier(1, 1, 1, 1), get("x"), stop(0, 100), stop(100, 200)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testCubicBezierExpression() throws Exception { - Object[] getX = new Object[] {"get", "x"}; - Object[] getY = new Object[] {"get", "y"}; - Object[] getZ = new Object[] {"get", "z"}; - Object[] cubicBezier = new Object[] {"cubic-bezier", getZ, 1f, getY, 1f}; - Object[] expected = new Object[] {"interpolate", cubicBezier, getX, 0f, 100f, 200f}; - Object[] actual = interpolate(cubicBezier(get(literal("z")), literal(1), - get(literal("y")), literal(1)), get(literal("x")), literal(0), literal(100), literal(200)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testCubicBezierExpressionLiteral() throws Exception { - Object[] getX = new Object[] {"get", "x"}; - Object[] getY = new Object[] {"get", "y"}; - Object[] getZ = new Object[] {"get", "z"}; - Object[] cubicBezier = new Object[] {"cubic-bezier", getZ, 1f, getY, 1f}; - Object[] expected = new Object[] {"interpolate", cubicBezier, getX, 0f, 100f, 100f, 200f}; - Object[] actual = interpolate(cubicBezier(get("z"), literal(1), get("y"), - literal(1)), get("x"), stop(0, 100), stop(100, 200)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testExpressionConcatToString() throws Exception { - String expected = "[\"concat\", \"foo\", \"bar\"]"; - String actual = concat(literal("foo"), literal("bar")).toString(); - assertEquals("toString should match", expected, actual); - } - - @Test - public void testExpressionMinToString() throws Exception { - String expected = "[\"min\", 0.0, 1.0, 2.0, 3.0]"; - String actual = min(0, 1, 2, 3).toString(); - assertEquals("toString should match", expected, actual); - } - - @Test - public void testExpressionExponentialToString() throws Exception { - String expected = "[\"interpolate\", [\"cubic-bezier\", 1.0, 1.0, 1.0, 1.0]," - + " [\"get\", \"x\"], 0.0, 100.0, 100.0, 200.0]"; - String actual = interpolate(cubicBezier(literal(1), literal(1), literal(1), literal(1)), - get(literal("x")), literal(0), literal(100), literal(100), literal(200)).toString(); - assertEquals("toString should match", expected, actual); - } - - @Test - public void testLiteralArray() throws Exception { - Object[] array = new Object[] {1, "text"}; - Object[] expected = new Object[] {"literal", array}; - Object[] actual = literal(array).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testLiteralArrayString() throws Exception { - Object[] array = new Object[] {1, "text"}; - String expected = "[\"literal\", [1, \"text\"]]"; - String actual = literal(array).toString(); - assertEquals("literal array should match", expected, actual); - } - - @Test - public void testLiteralPrimitiveArrayConversion() throws Exception { - float[] array = new float[] {0.2f, 0.5f}; - Object[] expected = new Object[] {"literal", new Object[] {0.2f, 0.5f}}; - Object[] actual = literal(array).toArray(); - assertEquals("primitive array should be converted", expected, actual); - } - - @Test - public void testColorConversion() { - Expression greenColor = color(0xFF00FF00); - Object[] expected = new Object[] {"rgba", 0f, 255f, 0f, 1f}; - assertTrue("expression should match", Arrays.deepEquals(expected, greenColor.toArray())); - } - - @Test(expected = IllegalArgumentException.class) - public void testThrowIllegalArgumentExceptionForPropertyValueLiteral() { - Expression expression = interpolate(exponential(1f), zoom(), - stop(17f, lineOpacity(1f)), - stop(16.5f, lineOpacity(0.5f)), - stop(16f, lineOpacity(0f)) - ); - expression.toArray(); - } - - @Test - public void testRound() { - Object[] expected = new Object[] {"round", 2.2f}; - Object[] actual = round(2.2f).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testRoundLiteral() { - Object[] expected = new Object[] {"round", 2.2f}; - Object[] actual = round(literal(2.2f)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testAbs() { - Object[] expected = new Object[] {"abs", -2.2f}; - Object[] actual = abs(-2.2f).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testAbsLiteral() { - Object[] expected = new Object[] {"abs", -2.2f}; - Object[] actual = abs(literal(-2.2f)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testCeil() { - Object[] expected = new Object[] {"ceil", 2.2f}; - Object[] actual = ceil(2.2f).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testCeilLiteral() { - Object[] expected = new Object[] {"ceil", 2.2f}; - Object[] actual = ceil(literal(2.2f)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testFloor() { - Object[] expected = new Object[] {"floor", 2.2f}; - Object[] actual = floor(2.2f).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testFloorLiteral() { - Object[] expected = new Object[] {"floor", 2.2f}; - Object[] actual = floor(literal(2.2f)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testRawEmpty() { - String raw = "[\"get\", ]"; - Expression expected = get(""); - assertEquals("expressions should match", raw(raw), expected); - - raw = "[\"get\", key]"; - expected = get("key"); - assertEquals("expressions should match", raw(raw), expected); - } - - @Test - public void testRawAndroidColors() { - Expression expected = interpolate(linear(), zoom(), - stop(12, step(get("stroke-width"), - color(Color.BLACK), - stop(1f, color(Color.RED)), - stop(2f, color(Color.WHITE)), - stop(3f, color(Color.BLUE)) - )), - stop(15, step(get("stroke-width"), - color(Color.BLACK), - stop(1f, color(Color.YELLOW)), - stop(2f, color(Color.LTGRAY)), - stop(3f, color(Color.CYAN)) - )), - stop(18, step(get("stroke-width"), - color(Color.BLACK), - stop(1f, color(Color.WHITE)), - stop(2f, color(Color.GRAY)), - stop(3f, color(Color.GREEN)) - )) - ); - assertEquals("expressions should match", expected, raw(expected.toString())); - } - - @Test - public void testRawRgbaColor() { - Expression expected = interpolate( - exponential(2f), zoom(), - literal(5f), literal("rgba(0, 0, 0, 1)"), - literal(10.5f), literal("rgb(255, 0, 0)"), - literal(15), color(Color.GREEN), - literal(20), literal(ColorUtils.colorToRgbaString(Color.BLUE))); - assertEquals("expressions should match", expected, raw(expected.toString())); - } - - @Test - public void testRawMatchStrings() { - Expression expected = match(get("property"), literal(""), - stop("layer1", "image1"), - stop("layer2", "image2")); - assertEquals("expressions should match", expected, raw(expected.toString())); - } - - @Test - public void testRawMatchNumbers() { - Expression expected = match(get("property"), literal(""), - stop("layer1", 2), - stop("layer2", 2.7)); - assertEquals("expressions should match", expected, raw(expected.toString())); - } - - @Test - public void testAlphaValueInColorConversion() { - // regression test for #12198 - Expression colorExpression = color(Color.parseColor("#41FF0000")); // 25.4% alpha red - Object[] result = colorExpression.toArray(); - assertEquals("alpha value should match", 0.254f, (Float) result[4], 0.001f); - } - - @Test - public void testAlphaValueInStringConversion() { - String color = ColorUtils.colorToRgbaString(Color.parseColor("#41FF0000")).split(" ")[3]; - String alpha = color.substring(0, color.length() - 1); - assertEquals("alpha value should match", 0.254f, Float.valueOf(alpha), 0.001f); - } - - @Test - public void testCollator() { - Object[] expected = new Object[] {"collator", - new HashMap() { - { - put("case-sensitive", true); - put("diacritic-sensitive", true); - put("locale", "it-IT"); - } - } - }; - Object[] actual = collator(true, true, Locale.ITALY).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testStringCollator() { - String expected = "[\"collator\", {\"diacritic-sensitive\": true, \"case-sensitive\": true, \"locale\": " - + "\"it\"}]"; - String actual = collator(true, true, Locale.ITALIAN).toString(); - assertEquals("expression should match", expected, actual); - } - - @Test - public void testResolvedLocale() { - Object[] expected = new Object[] {"resolved-locale", - new Object[] {"collator", - new HashMap() { - { - put("case-sensitive", false); - put("diacritic-sensitive", false); - put("locale", "it"); - } - } - } - }; - Object[] actual = resolvedLocale(collator(false, false, Locale.ITALIAN)).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testRawCollator() { - Object[] expected = new Object[] {"collator", - new HashMap() { - { - put("case-sensitive", true); - put("diacritic-sensitive", true); - put("locale", "it-IT"); - } - } - }; - Object[] actual = raw("[\"collator\", {\"diacritic-sensitive\": true, \"case-sensitive\": true, \"locale\": " - + "\"it-IT\"}]").toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testRawCollatorDoubleConversion() { - Expression expected = collator(false, false, Locale.ITALIAN); - Object[] actual = raw(expected.toString()).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected.toArray(), actual)); - } - - @Test - public void testStringNestedCollator() { - String expected = "[\"collator\", {\"diacritic-sensitive\": [\"==\", 2.0, 1.0], \"case-sensitive\": false," - + " \"locale\": \"it\"}]"; - String actual = collator(literal(false), eq(literal(2), literal(1)), literal("it")).toString(); - assertEquals("expression should match", expected, actual); - } - - @Test - public void testStringReverseConversion() { - String expected = "[\"to-string\", [\"get\", \"name_en\"]]"; - String actual = Expression.toString(get("name_en")).toString(); - assertEquals("Reverse string conversion should match", expected, actual); - } - - @Test - public void testIsSupportedScriptLiteral() { - Object[] expected = new Object[] {"is-supported-script", "ಗೌರವಾರ್ಥವಾಗಿ"}; - Object[] actual = isSupportedScript("ಗೌರವಾರ್ಥವಾಗಿ").toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testIsSupportedScriptExpressions() { - Object[] expected = new Object[] {"is-supported-script", new Object[] {"get", "property_name"}}; - Object[] actual = isSupportedScript(get("property_name")).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testFormatSingleArgument() { - Object[] expected = new Object[] {"format", "test", - new TestableExpressionHashMap() { - { - put("font-scale", 1.5f); - put("text-font", new Object[] {"literal", new String[] {"awesome"}}); - put("text-color", new Object[] {"rgb", 255f, 0f, 0f}); - } - } - }; - Object[] actual = format( - formatEntry( - literal("test"), - formatFontScale(literal(1.5)), - formatTextFont(literal(new String[] {"awesome"})), - formatTextColor(rgb(255, 0, 0)) - ) - ).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - @Test - public void testFormatMultipleArgument() { - Object[] expected = new Object[] { - "format", - "test", - new TestableExpressionHashMap() { - { - put("text-font", new Object[] {"literal", new String[] {"awesome"}}); - } - }, - "test2", - new TestableExpressionHashMap() { - { - put("font-scale", 1.5f); - } - }, - "test3", - new TestableExpressionHashMap() { - { - } - }, - "test4", - new TestableExpressionHashMap() { - { - put("text-color", new Object[] {"rgb", 255f, 0f, 0f}); - } - }, - "test5", - new TestableExpressionHashMap() { - { - put("font-scale", 1.5f); - put("text-font", new Object[] {"literal", new String[] {"awesome"}}); - put("text-color", new Object[] {"rgb", 255f, 0f, 0f}); - } - } - }; - Object[] actual = format( - formatEntry(literal("test"), formatTextFont(new String[] {"awesome"})), - formatEntry("test2", formatFontScale(1.5)), - formatEntry(literal("test3")), - formatEntry(literal("test4"), formatTextColor(rgb(255, 0, 0))), - formatEntry( - literal("test5"), - formatFontScale(literal(1.5)), - formatTextFont(new String[] {"awesome"}), - formatTextColor(rgb(255, 0, 0)) - ) - ).toArray(); - assertTrue("expression should match", Arrays.deepEquals(expected, actual)); - } - - /** - * This class overrides {@link java.util.AbstractMap#equals(Object)} - * in order to correctly compare nodes values if they are arrays, - * which is the case for {@link Expression#format(Expression.FormatEntry...)}'s "text-format" argument. - */ - private class TestableExpressionHashMap extends HashMap { - - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } - - if (!(o instanceof Map)) { - return false; - } - Map m = (Map) o; - if (m.size() != size()) { - return false; - } - - try { - for (Entry e : entrySet()) { - String key = e.getKey(); - Object value = e.getValue(); - if (value == null) { - if (!(m.get(key) == null && m.containsKey(key))) { - return false; - } - } else { - if (value instanceof Object[]) { - // Use Arrays.deepEquals() if values are Object arrays. - if (!Arrays.deepEquals((Object[]) value, (Object[]) m.get(key))) { - return false; - } - } else { - if (!value.equals(m.get(key))) { - return false; - } - } - } - } - } catch (ClassCastException unused) { - return false; - } catch (NullPointerException unused) { - return false; - } - - return true; - } - } -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/style/expressions/ExpressionTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/style/expressions/ExpressionTest.kt new file mode 100644 index 000000000..b0535b11f --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/style/expressions/ExpressionTest.kt @@ -0,0 +1,1867 @@ +package com.mapbox.mapboxsdk.style.expressions + +import android.graphics.Color +import com.mapbox.geojson.Point +import com.mapbox.geojson.Polygon +import com.mapbox.mapboxsdk.style.expressions.Expression.FormatOption +import com.mapbox.mapboxsdk.style.layers.PropertyFactory +import com.mapbox.mapboxsdk.style.layers.PropertyValue +import com.mapbox.mapboxsdk.utils.ColorUtils +import junit.framework.Assert +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import java.util.* + +/** + * Expression unit tests that validate the expression output with the expected Object[]array representation. + */ +@RunWith(RobolectricTestRunner::class) +class ExpressionTest { + @Test + fun testPropertyValueIsExpression() { + val property: PropertyValue<*> = PropertyFactory.lineWidth(Expression.get("width")) + Assert.assertTrue(property.isExpression) + } + + @Test + fun testPropertyValueEqualsExpression() { + val property: PropertyValue<*> = PropertyFactory.lineWidth(Expression.get("width")) + org.junit.Assert.assertEquals(Expression.get("width"), property.expression) + } + + @Test + @Throws(Exception::class) + fun testRgb() { + val expected = arrayOf("rgb", 0f, 0f, 0f) + val actual = + Expression.rgb(Expression.literal(0), Expression.literal(0), Expression.literal(0)) + .toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testRgbLiteral() { + val expected = arrayOf("rgb", 0f, 0f, 0f) + val actual = Expression.rgb(0, 0, 0).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testRgba() { + val expected = arrayOf("rgba", 0f, 0f, 0f, 1f) + val actual = Expression.rgba( + Expression.literal(0), + Expression.literal(0), + Expression.literal(0), + Expression.literal(1) + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testRgbaLiteral() { + val expected = arrayOf("rgba", 0f, 0f, 0f, 1f) + val actual = Expression.rgba(0, 0, 0, 1).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testToRgba() { + val expected = arrayOf("to-rgba", arrayOf("to-color", "rgba(255, 0, 0, 1)")) + val actual = Expression.toRgba( + Expression.toColor( + Expression.literal( + ColorUtils.colorToRgbaString( + Color.RED + ) + ) + ) + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testEq() { + val expected = arrayOf("==", 1f, 1f) + val actual = Expression.eq(Expression.literal(1), Expression.literal(1)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testEqLiteral() { + val expected = arrayOf("==", 1f, 1f) + val actual = Expression.eq(Expression.literal(1), 1).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testEqExpression() { + val expected = arrayOf("==", arrayOf("get", "hello"), 1f) + val actual = Expression.eq(Expression.get("hello"), 1).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testNeq() { + val expected = arrayOf("!=", 0f, 1f) + val actual = Expression.neq(Expression.literal(0), Expression.literal(1)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testNeqLiteral() { + val expected = arrayOf("!=", 0f, 1f) + val actual = Expression.neq(Expression.literal(0), 1).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testNeqExpression() { + val expected = arrayOf("!=", arrayOf("get", "hello"), 1f) + val actual = Expression.neq(Expression.get("hello"), 1).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testGt() { + val expected = arrayOf(">", 0f, 1f) + val actual = Expression.gt(Expression.literal(0), Expression.literal(1)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testGtLiteral() { + val expected = arrayOf(">", 0f, 1f) + val actual = Expression.gt(Expression.literal(0), 1).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testGtExpression() { + val expected = arrayOf(">", arrayOf("get", "hello"), 1f) + val actual = Expression.gt(Expression.get("hello"), 1).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testLt() { + val expected = arrayOf("<", 1f, 0f) + val actual = Expression.lt(Expression.literal(1), Expression.literal(0)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testLtLiteral() { + val expected = arrayOf("<", 1f, 0f) + val actual = Expression.lt(Expression.literal(1), 0).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testLtExpression() { + val expected = arrayOf("<", arrayOf("get", "hello"), 1f) + val actual = Expression.lt(Expression.get("hello"), 1).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testGte() { + val expected = arrayOf(">=", 1f, 1f) + val actual = Expression.gte(Expression.literal(1), Expression.literal(1)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testGteLiteral() { + val expected = arrayOf(">=", 1f, 1f) + val actual = Expression.gte(Expression.literal(1), 1).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testGteExpression() { + val expected = arrayOf(">=", arrayOf("get", "hello"), 1f) + val actual = Expression.gte(Expression.get("hello"), 1).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testLte() { + val expected = arrayOf("<=", 1f, 1f) + val actual = Expression.lte(Expression.literal(1), Expression.literal(1)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testLteExpression() { + val expected = arrayOf("<=", arrayOf("get", "hello"), 1f) + val actual = Expression.lte(Expression.get("hello"), 1).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testLteLiteral() { + val expected = arrayOf("<=", 1f, 1f) + val actual = Expression.lte(Expression.literal(1), 1).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testAll() { + val expected = arrayOf("all", true, true, true) + val actual = Expression.all( + Expression.literal(true), + Expression.literal(true), + Expression.literal(true) + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testAny() { + val expected = arrayOf("any", true, false, false) + val actual = Expression.any( + Expression.literal(true), + Expression.literal(false), + Expression.literal(false) + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testNot() { + val expected = arrayOf("!", false) + val actual = Expression.not(Expression.literal(false)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testNotLiteral() { + val expected = arrayOf("!", false) + val actual = Expression.not(false).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testSwitchCase() { + val expectedCaseOneGet = arrayOf("get", "key1") + val expectedCaseOne = arrayOf("==", expectedCaseOneGet, "value1") + val expectedCaseTwoGet = arrayOf("get", "key2") + val expectedCaseTwo = arrayOf("!=", expectedCaseTwoGet, "value2") + val expected = arrayOf("case", expectedCaseOne, expectedCaseTwo) + val actual = Expression.switchCase( + Expression.eq(Expression.get(Expression.literal("key1")), Expression.literal("value1")), + Expression.neq(Expression.get(Expression.literal("key2")), Expression.literal("value2")) + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testSwitchCaseLiteral() { + val expectedCaseOneGet = arrayOf("get", "key1") + val expectedCaseOne = arrayOf("==", expectedCaseOneGet, "value1") + val expectedCaseTwoGet = arrayOf("get", "key2") + val expectedCaseTwo = arrayOf("!=", expectedCaseTwoGet, "value2") + val expected = arrayOf("case", expectedCaseOne, expectedCaseTwo) + val actual = Expression.switchCase( + Expression.eq(Expression.get("key1"), Expression.literal("value1")), + Expression.neq(Expression.get("key2"), Expression.literal("value2")) + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testMatch() { + val input = "input" + val labels = arrayOf("a", "b", "c") + val outputs = arrayOf("1", "2", "3") + val defaultOutput = "0" + val expected = arrayOf( + "match", input, + labels[0], outputs[0], + labels[1], outputs[1], + labels[2], outputs[2], + defaultOutput + ) + val actual = Expression.match( + Expression.literal(input), + Expression.literal(labels[0]), + Expression.literal( + outputs[0] + ), + Expression.literal(labels[1]), + Expression.literal( + outputs[1] + ), + Expression.literal(labels[2]), + Expression.literal( + outputs[2] + ), + Expression.literal(defaultOutput) + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testMatchWithStops() { + val input = "input" + val labels = arrayOf("a", "b", "c") + val outputs = arrayOf("1", "2", "3") + val defaultOutput = "0" + val expected = arrayOf( + "match", input, + labels[0], outputs[0], + labels[1], outputs[1], + labels[2], outputs[2], + defaultOutput + ) + val actual = Expression.match( + Expression.literal(input), + Expression.literal(defaultOutput), + Expression.stop(labels[0], outputs[0]), + Expression.stop(labels[1], outputs[1]), + Expression.stop(labels[2], outputs[2]) + ) + .toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testCoalesce() { + val expectedGetOne = arrayOf("get", "invalidKey") + val expectedGetTwo = arrayOf("get", "validKey") + val expected = arrayOf("coalesce", expectedGetOne, expectedGetTwo) + val actual = Expression.coalesce( + Expression.get(Expression.literal("invalidKey")), + Expression.get(Expression.literal("validKey")) + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testCoalesceLiteral() { + val expectedGetOne = arrayOf("get", "invalidKey") + val expectedGetTwo = arrayOf("get", "validKey") + val expected = arrayOf("coalesce", expectedGetOne, expectedGetTwo) + val actual = Expression.coalesce( + Expression.get("invalidKey"), + Expression.get("validKey") + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testProperties() { + val expected = arrayOf("properties") + val actual = Expression.properties().toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testGeometryType() { + val expected = arrayOf("geometry-type") + val actual = Expression.geometryType().toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testId() { + val expected = arrayOf("id") + val actual = Expression.id().toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testHeatmapDensity() { + val expected = arrayOf("heatmap-density") + val actual = Expression.heatmapDensity().toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testAt() { + val expected = arrayOf("at", 3f, arrayOf("literal", arrayOf("one", "two"))) + val actual = + Expression.at(Expression.literal(3), Expression.literal(arrayOf("one", "two"))) + .toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testInString() { + val expected = arrayOf("in", "one", "onetwo") + val actual = + Expression.`in`(Expression.literal("one"), Expression.literal("onetwo")).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testWithIn() { + val lngLats = listOf( + Arrays.asList( + Point.fromLngLat(0.0, 0.0), + Point.fromLngLat(0.0, 5.0), + Point.fromLngLat(5.0, 5.0), + Point.fromLngLat(5.0, 0.0), + Point.fromLngLat(0.0, 0.0) + ) + ) + val polygon = Polygon.fromLngLats(lngLats) + val map = HashMap() + map["type"] = "Polygon" + map["json"] = polygon.toJson() + val expected = arrayOf("within", map) + val actual = Expression.within(polygon).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testInNumber() { + val expected = arrayOf("in", 1f, arrayOf("literal", arrayOf(1f, 2f))) + val actual = + Expression.`in`(Expression.literal(1f), Expression.literal(arrayOf(1f, 2f))) + .toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testDistance() { + val point = Point.fromLngLat(1.0, 2.0) + val map = HashMap() + map["json"] = point.toJson() + val expected = arrayOf("distance", map) + val actual = Expression.distance(point).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testInArray() { + val expected = + arrayOf("in", "one", arrayOf("literal", arrayOf("one", "two"))) + val actual = Expression.`in`( + Expression.literal("one"), + Expression.literal(arrayOf("one", "two")) + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testAtLiteral() { + val expected = arrayOf("at", 3f, arrayOf("literal", arrayOf("one", "two"))) + val actual = Expression.at(3, Expression.literal(arrayOf("one", "two"))).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testAtExpression() { + val expected = arrayOf("at", 3f, arrayOf("properties")) + val actual = Expression.at(Expression.literal(3), Expression.properties()).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testGet() { + val expected = arrayOf("get", "key") + val actual = Expression.get(Expression.literal("key")).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testGetLiteral() { + val expected = arrayOf("get", "key") + val actual = Expression.get("key").toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testGetObject() { + val expected = arrayOf("get", "key", arrayOf("properties")) + val actual = Expression.get(Expression.literal("key"), Expression.properties()).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testGetObjectLiteral() { + val expected = arrayOf("get", "key", arrayOf("properties")) + val actual = Expression.get("key", Expression.properties()).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testHas() { + val expected = arrayOf("has", "key") + val actual = Expression.has(Expression.literal("key")).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testHasLiteral() { + val expected = arrayOf("has", "key") + val actual = Expression.has("key").toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testHasObject() { + val expected = arrayOf("has", "key", arrayOf("properties")) + val actual = Expression.has(Expression.literal("key"), Expression.properties()).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testHasObjectLiteral() { + val expected = arrayOf("has", "key", arrayOf("properties")) + val actual = Expression.has("key", Expression.properties()).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testHasExpression() { + val expected = arrayOf("has", arrayOf("get", "key"), arrayOf("properties")) + val actual = + Expression.has(Expression.get(Expression.literal("key")), Expression.properties()) + .toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testHasExpressionLiteral() { + val expected = arrayOf("has", arrayOf("get", "key"), arrayOf("properties")) + val actual = Expression.has(Expression.get("key"), Expression.properties()).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testLength() { + val expected = arrayOf("length", "key") + val actual = Expression.length(Expression.literal("key")).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testLengthLiteral() { + val expected = arrayOf("length", "key") + val actual = Expression.length("key").toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testLengthExpression() { + val expected = arrayOf("length", arrayOf("get", "key")) + val actual = Expression.length(Expression.get(Expression.literal("key"))).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testLn2() { + val expected = arrayOf("ln2") + val actual = Expression.ln2().toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testPi() { + val expected = arrayOf("pi") + val actual = Expression.pi().toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testE() { + val expected = arrayOf("e") + val actual = Expression.e().toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testSum() { + val expected = arrayOf("+", 1f, 2f) + val actual = Expression.sum(Expression.literal(1), Expression.literal(2)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testSumLiteral() { + val expected = arrayOf("+", 1f, 2f) + val actual = Expression.sum(1, 2).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testProduct() { + val expected = arrayOf("*", 1f, 2f) + val actual = Expression.product(Expression.literal(1), Expression.literal(2)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testProductLiteral() { + val expected = arrayOf("*", 1f, 2f) + val actual = Expression.product(1, 2).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testSubtract() { + val expected = arrayOf("-", 2f, 1f) + val actual = Expression.subtract(Expression.literal(2), Expression.literal(1)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testSubtractLiteral() { + val expected = arrayOf("-", 2f, 1f) + val actual = Expression.subtract(2, 1).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testDivision() { + val expected = arrayOf("/", 2f, 1f) + val actual = Expression.division(Expression.literal(2), Expression.literal(1)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testDivisionLiteral() { + val expected = arrayOf("/", 2f, 1f) + val actual = Expression.division(2, 1).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testDivisionWithNestedGet() { + val nestedGet: Any = arrayOf("get", "key") + val expected = arrayOf("/", 2f, nestedGet) + val actual = + Expression.division(Expression.literal(2), Expression.get(Expression.literal("key"))) + .toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testMod() { + val expected = arrayOf("%", 1f, 3f) + val actual = Expression.mod(Expression.literal(1), Expression.literal(3)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testModLiteral() { + val expected = arrayOf("%", 1f, 3f) + val actual = Expression.mod(1, 3).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testPow() { + val expected = arrayOf("^", 2f, 3f) + val actual = Expression.pow(Expression.literal(2), Expression.literal(3)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testPowLiteral() { + val expected = arrayOf("^", 2f, 3f) + val actual = Expression.pow(2, 3).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testSqrt() { + val expected = arrayOf("sqrt", 4f) + val actual = Expression.sqrt(Expression.literal(4)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testSqrtLiteral() { + val expected = arrayOf("sqrt", 4f) + val actual = Expression.sqrt(4).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testLog10() { + val expected = arrayOf("log10", 10f) + val actual = Expression.log10(Expression.literal(10f)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testLog10Literal() { + val expected = arrayOf("log10", 10f) + val actual = Expression.log10(10).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testLn() { + val expected = arrayOf("ln", 2f) + val actual = Expression.ln(Expression.literal(2)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testLnLiteral() { + val expected = arrayOf("ln", 2f) + val actual = Expression.ln(2).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testLog2() { + val expected = arrayOf("log2", 16f) + val actual = Expression.log2(Expression.literal(16)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testLog2Literal() { + val expected = arrayOf("log2", 16f) + val actual = Expression.log2(16).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testSin() { + val expected = arrayOf("sin", 45f) + val actual = Expression.sin(Expression.literal(45)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testSinLiteral() { + val expected = arrayOf("sin", 45f) + val actual = Expression.sin(45).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testCos() { + val expected = arrayOf("cos", 45f) + val actual = Expression.cos(Expression.literal(45)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testCosLiteral() { + val expected = arrayOf("cos", 45f) + val actual = Expression.cos(45).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testTan() { + val expected = arrayOf("tan", 45f) + val actual = Expression.tan(Expression.literal(45)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testTanLiteral() { + val expected = arrayOf("tan", 45f) + val actual = Expression.tan(45).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testAsin() { + val expected = arrayOf("asin", 45f) + val actual = Expression.asin(Expression.literal(45)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testAsinLiteral() { + val expected = arrayOf("asin", 45f) + val actual = Expression.asin(45).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testAcos() { + val expected = arrayOf("acos", 45f) + val actual = Expression.acos(Expression.literal(45)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testAcosLiteral() { + val expected = arrayOf("acos", 45f) + val actual = Expression.acos(45).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testAtan() { + val expected = arrayOf("atan", 45f) + val actual = Expression.atan(Expression.literal(45)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testAtanLiteral() { + val expected = arrayOf("atan", 45f) + val actual = Expression.atan(45).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testMin() { + val expected = arrayOf("min", 0f, 1f, 2f, 3f) + val actual = Expression.min( + Expression.literal(0), + Expression.literal(1), + Expression.literal(2), + Expression.literal(3) + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testMinLiteral() { + val expected = arrayOf("min", 0f, 1f, 2f, 3f) + val actual = Expression.min(0, 1, 2, 3).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testMax() { + val expected = arrayOf("max", 0f, 1f, 2f, 3f) + val actual = Expression.max( + Expression.literal(0), + Expression.literal(1), + Expression.literal(2), + Expression.literal(3) + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testMaxLiteral() { + val expected = arrayOf("max", 0f, 1f, 2f, 3f) + val actual = Expression.max(0, 1, 2, 3).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testUpcase() { + val expected = arrayOf("upcase", "string") + val actual = Expression.upcase(Expression.literal("string")).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testUpcaseLiteral() { + val expected = arrayOf("upcase", "string") + val actual = Expression.upcase("string").toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testDowncase() { + val expected = arrayOf("downcase", "string") + val actual = Expression.downcase(Expression.literal("string")).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testDowncaseLiteral() { + val expected = arrayOf("downcase", "string") + val actual = Expression.downcase("string").toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testConcat() { + val expected = arrayOf("concat", "foo", "bar") + val actual = + Expression.concat(Expression.literal("foo"), Expression.literal("bar")).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testConcatLiteral() { + val expected = arrayOf("concat", "foo", "bar") + val actual = Expression.concat("foo", "bar").toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testArray() { + val get = arrayOf("get", "keyToArray") + val expected = arrayOf("array", get) + val actual = Expression.array(Expression.get(Expression.literal("keyToArray"))).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testArrayLiteral() { + val get = arrayOf("get", "keyToArray") + val expected = arrayOf("array", get) + val actual = Expression.array(Expression.get("keyToArray")).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testTypeOf() { + val expected = arrayOf("typeof", "value") + val actual = Expression.typeOf(Expression.literal("value")).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testString() { + val expected = arrayOf("string", "value") + val actual = Expression.string(Expression.literal("value")).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testNumber() { + val expected = arrayOf("number", 1f) + val actual = Expression.number(Expression.literal(1)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testBool() { + val expected = arrayOf("boolean", true) + val actual = Expression.bool(Expression.literal(true)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testObject() { + val `object` = Any() + val expected = arrayOf("object", `object`) + val actual = Expression.`object`(Expression.literal(`object`)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testToString() { + val expected = arrayOf("to-string", 3f) + val actual = Expression.toString(Expression.literal(3)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testToNumber() { + val expected = arrayOf("to-number", "3") + val actual = Expression.toNumber(Expression.literal("3")).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testToBool() { + val expected = arrayOf("to-boolean", "true") + val actual = Expression.toBool(Expression.literal("true")).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testToColor() { + val expected = arrayOf("to-color", "value") + val actual = Expression.toColor(Expression.literal("value")).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testLet() { + val expected = arrayOf("let", "letName", "value") + val actual = + Expression.let(Expression.literal("letName"), Expression.literal("value")).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testVar() { + val expected = arrayOf("var", "letName") + val actual = Expression.`var`(Expression.literal("letName")).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testVarLiteral() { + val expected = arrayOf("var", "letName") + val actual = Expression.`var`("letName").toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testVarExpression() { + val expected = arrayOf("var", arrayOf("get", "letName")) + val actual = Expression.`var`(Expression.get(Expression.literal("letName"))).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testVarExpressionLiteral() { + val expected = arrayOf("var", arrayOf("get", "letName")) + val actual = Expression.`var`(Expression.get("letName")).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testZoom() { + val expected = arrayOf("zoom") + val actual = Expression.zoom().toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testStepBasic() { + val expected = arrayOf("step", 12f, 11f, 0f, 111f, 1f, 1111f) + val actual = Expression.step( + Expression.literal(12), + Expression.literal(11), + Expression.literal(0), + Expression.literal(111), + Expression.literal(1), + Expression.literal(1111) + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testStepBasicLiteral() { + val expected = + arrayOf("step", arrayOf("get", "line-width"), 11f, 0f, 111f, 1f, 1111f) + val actual = Expression.step( + Expression.get("line-width"), + Expression.literal(11), + Expression.stop(0, 111), + Expression.stop(1, 1111) + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testStepExpression() { + val input = arrayOf("get", "key") + val number = arrayOf("to-number", input) + val expected = arrayOf("step", number, 11f, 0f, 111f, 1f, 1111f) + val actual = Expression.step( + Expression.toNumber(Expression.get(Expression.literal("key"))), + Expression.literal(11), + Expression.literal(0), + Expression.literal(111), + Expression.literal(1), + Expression.literal(1111) + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testStepExpressionLiteral() { + val input = arrayOf("get", "key") + val number = arrayOf("to-number", input) + val expected = arrayOf("step", number, 11f, 0f, 111f, 1f, 1111f) + val actual = Expression.step( + Expression.toNumber(Expression.get("key")), + Expression.literal(11), + Expression.stop(0, 111), + Expression.stop(1, 1111) + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testLinear() { + val expected = + arrayOf("interpolate", arrayOf("linear"), 12f, 0f, 1f, 1f, 2f, 2f, 3f) + val actual = Expression.interpolate( + Expression.linear(), + Expression.literal(12), + Expression.literal(0), + Expression.literal(1), + Expression.literal(1), + Expression.literal(2), + Expression.literal(2), + Expression.literal(3) + ) + .toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testLinearStops() { + val expected = + arrayOf("interpolate", arrayOf("linear"), 12f, 0f, 1f, 1f, 2f, 2f, 3f) + val actual = Expression.interpolate( + Expression.linear(), + Expression.literal(12), + Expression.stop(0, 1), + Expression.stop(1, 2), + Expression.stop(2, 3) + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testExponential() { + val exponential = arrayOf("exponential", 12f) + val get = arrayOf("get", "x") + val expected = arrayOf("interpolate", exponential, get, 0f, 100f, 200f) + val actual = Expression.interpolate( + Expression.exponential(Expression.literal(12)), + Expression.get(Expression.literal("x")), + Expression.literal(0), + Expression.literal(100), + Expression.literal(200) + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testExponentialLiteral() { + val exponential = arrayOf("exponential", 12f) + val get = arrayOf("get", "x") + val expected = arrayOf("interpolate", exponential, get, 0f, 100f, 100f, 200f) + val actual = Expression.interpolate( + Expression.exponential(12), + Expression.get("x"), + Expression.stop(0, 100), + Expression.stop(100, 200) + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testExponentialExpressionLiteral() { + val getX = arrayOf("get", "x") + val exponential = arrayOf("exponential", getX) + val getY = arrayOf("get", "y") + val expected = arrayOf("interpolate", exponential, getY, 0f, 100f, 100f, 200f) + val actual = Expression.interpolate( + Expression.exponential(Expression.get("x")), + Expression.get("y"), + Expression.stop(0, 100), + Expression.stop(100, 200) + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testCubicBezier() { + val cubicBezier = arrayOf("cubic-bezier", 1f, 1f, 1f, 1f) + val get = arrayOf("get", "x") + val expected = arrayOf("interpolate", cubicBezier, get, 0f, 100f, 100f, 200f) + val actual = Expression.interpolate( + Expression.cubicBezier( + Expression.literal(1), + Expression.literal(1), + Expression.literal(1), + Expression.literal(1) + ), + Expression.get(Expression.literal("x")), + Expression.literal(0), + Expression.literal(100), + Expression.literal(100), + Expression.literal(200) + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testCubicBezierLiteral() { + val cubicBezier = arrayOf("cubic-bezier", 1f, 1f, 1f, 1f) + val get = arrayOf("get", "x") + val expected = arrayOf("interpolate", cubicBezier, get, 0f, 100f, 100f, 200f) + val actual = Expression.interpolate( + Expression.cubicBezier(1, 1, 1, 1), + Expression.get("x"), + Expression.stop(0, 100), + Expression.stop(100, 200) + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testCubicBezierExpression() { + val getX = arrayOf("get", "x") + val getY = arrayOf("get", "y") + val getZ = arrayOf("get", "z") + val cubicBezier = arrayOf("cubic-bezier", getZ, 1f, getY, 1f) + val expected = arrayOf("interpolate", cubicBezier, getX, 0f, 100f, 200f) + val actual = Expression.interpolate( + Expression.cubicBezier( + Expression.get(Expression.literal("z")), + Expression.literal(1), + Expression.get(Expression.literal("y")), + Expression.literal(1) + ), + Expression.get(Expression.literal("x")), + Expression.literal(0), + Expression.literal(100), + Expression.literal(200) + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testCubicBezierExpressionLiteral() { + val getX = arrayOf("get", "x") + val getY = arrayOf("get", "y") + val getZ = arrayOf("get", "z") + val cubicBezier = arrayOf("cubic-bezier", getZ, 1f, getY, 1f) + val expected = arrayOf("interpolate", cubicBezier, getX, 0f, 100f, 100f, 200f) + val actual = Expression.interpolate( + Expression.cubicBezier( + Expression.get("z"), + Expression.literal(1), + Expression.get("y"), + Expression.literal(1) + ), + Expression.get("x"), + Expression.stop(0, 100), + Expression.stop(100, 200) + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testExpressionConcatToString() { + val expected = "[\"concat\", \"foo\", \"bar\"]" + val actual = + Expression.concat(Expression.literal("foo"), Expression.literal("bar")).toString() + org.junit.Assert.assertEquals("toString should match", expected, actual) + } + + @Test + @Throws(Exception::class) + fun testExpressionMinToString() { + val expected = "[\"min\", 0.0, 1.0, 2.0, 3.0]" + val actual = Expression.min(0, 1, 2, 3).toString() + org.junit.Assert.assertEquals("toString should match", expected, actual) + } + + @Test + @Throws(Exception::class) + fun testExpressionExponentialToString() { + val expected = ( + "[\"interpolate\", [\"cubic-bezier\", 1.0, 1.0, 1.0, 1.0]," + + " [\"get\", \"x\"], 0.0, 100.0, 100.0, 200.0]" + ) + val actual = Expression.interpolate( + Expression.cubicBezier( + Expression.literal(1), + Expression.literal(1), + Expression.literal(1), + Expression.literal(1) + ), + Expression.get(Expression.literal("x")), + Expression.literal(0), + Expression.literal(100), + Expression.literal(100), + Expression.literal(200) + ).toString() + org.junit.Assert.assertEquals("toString should match", expected, actual) + } + + @Test + @Throws(Exception::class) + fun testLiteralArray() { + val array = arrayOf(1, "text") + val expected = arrayOf("literal", array) + val actual = Expression.literal(array).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + @Throws(Exception::class) + fun testLiteralArrayString() { + val array = arrayOf(1, "text") + val expected = "[\"literal\", [1, \"text\"]]" + val actual = Expression.literal(array).toString() + org.junit.Assert.assertEquals("literal array should match", expected, actual) + } + + @Test + @Throws(Exception::class) + fun testLiteralPrimitiveArrayConversion() { + val array = floatArrayOf(0.2f, 0.5f) + val expected = arrayOf("literal", arrayOf(0.2f, 0.5f)) + val actual = Expression.literal(array).toArray() + org.junit.Assert.assertEquals("primitive array should be converted", expected, actual) + } + + @Test + fun testColorConversion() { + val greenColor = Expression.color(-0xff0100) + val expected = arrayOf("rgba", 0f, 255f, 0f, 1f) + Assert.assertTrue( + "expression should match", + Arrays.deepEquals(expected, greenColor.toArray()) + ) + } + + @Test(expected = IllegalArgumentException::class) + fun testThrowIllegalArgumentExceptionForPropertyValueLiteral() { + val expression = Expression.interpolate( + Expression.exponential(1f), + Expression.zoom(), + Expression.stop(17f, PropertyFactory.lineOpacity(1f)), + Expression.stop(16.5f, PropertyFactory.lineOpacity(0.5f)), + Expression.stop(16f, PropertyFactory.lineOpacity(0f)) + ) + expression.toArray() + } + + @Test + fun testRound() { + val expected = arrayOf("round", 2.2f) + val actual = Expression.round(2.2f).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + fun testRoundLiteral() { + val expected = arrayOf("round", 2.2f) + val actual = Expression.round(Expression.literal(2.2f)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + fun testAbs() { + val expected = arrayOf("abs", -2.2f) + val actual = Expression.abs(-2.2f).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + fun testAbsLiteral() { + val expected = arrayOf("abs", -2.2f) + val actual = Expression.abs(Expression.literal(-2.2f)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + fun testCeil() { + val expected = arrayOf("ceil", 2.2f) + val actual = Expression.ceil(2.2f).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + fun testCeilLiteral() { + val expected = arrayOf("ceil", 2.2f) + val actual = Expression.ceil(Expression.literal(2.2f)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + fun testFloor() { + val expected = arrayOf("floor", 2.2f) + val actual = Expression.floor(2.2f).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + fun testFloorLiteral() { + val expected = arrayOf("floor", 2.2f) + val actual = Expression.floor(Expression.literal(2.2f)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + fun testRawEmpty() { + var raw = "[\"get\", ]" + var expected = Expression.get("") + org.junit.Assert.assertEquals( + "expressions should match", + Expression.raw( + raw + ), + expected + ) + raw = "[\"get\", key]" + expected = Expression.get("key") + org.junit.Assert.assertEquals("expressions should match", Expression.raw(raw), expected) + } + + @Test + fun testRawAndroidColors() { + val expected = Expression.interpolate( + Expression.linear(), + Expression.zoom(), + Expression.stop( + 12, + Expression.step( + Expression.get("stroke-width"), + Expression.color(Color.BLACK), + Expression.stop(1f, Expression.color(Color.RED)), + Expression.stop(2f, Expression.color(Color.WHITE)), + Expression.stop(3f, Expression.color(Color.BLUE)) + ) + ), + Expression.stop( + 15, + Expression.step( + Expression.get("stroke-width"), + Expression.color(Color.BLACK), + Expression.stop(1f, Expression.color(Color.YELLOW)), + Expression.stop(2f, Expression.color(Color.LTGRAY)), + Expression.stop(3f, Expression.color(Color.CYAN)) + ) + ), + Expression.stop( + 18, + Expression.step( + Expression.get("stroke-width"), + Expression.color(Color.BLACK), + Expression.stop(1f, Expression.color(Color.WHITE)), + Expression.stop(2f, Expression.color(Color.GRAY)), + Expression.stop(3f, Expression.color(Color.GREEN)) + ) + ) + ) + org.junit.Assert.assertEquals( + "expressions should match", + expected, + Expression.raw(expected.toString()) + ) + } + + @Test + fun testRawRgbaColor() { + val expected = Expression.interpolate( + Expression.exponential(2f), Expression.zoom(), + Expression.literal(5f), Expression.literal("rgba(0, 0, 0, 1)"), + Expression.literal(10.5f), Expression.literal("rgb(255, 0, 0)"), + Expression.literal(15), Expression.color(Color.GREEN), + Expression.literal(20), Expression.literal(ColorUtils.colorToRgbaString(Color.BLUE)) + ) + org.junit.Assert.assertEquals( + "expressions should match", + expected, + Expression.raw(expected.toString()) + ) + } + + @Test + fun testRawMatchStrings() { + val expected = Expression.match( + Expression.get("property"), + Expression.literal(""), + Expression.stop("layer1", "image1"), + Expression.stop("layer2", "image2") + ) + org.junit.Assert.assertEquals( + "expressions should match", + expected, + Expression.raw(expected.toString()) + ) + } + + @Test + fun testRawMatchNumbers() { + val expected = Expression.match( + Expression.get("property"), + Expression.literal(""), + Expression.stop("layer1", 2), + Expression.stop("layer2", 2.7) + ) + org.junit.Assert.assertEquals( + "expressions should match", + expected, + Expression.raw(expected.toString()) + ) + } + + @Test + fun testAlphaValueInColorConversion() { + // regression test for #12198 + val colorExpression = Expression.color(Color.parseColor("#41FF0000")) // 25.4% alpha red + val result = colorExpression.toArray() + org.junit.Assert.assertEquals( + "alpha value should match", + 0.254f, + (result[4] as Float), + 0.001f + ) + } + + @Test + fun testAlphaValueInStringConversion() { + val color = ColorUtils.colorToRgbaString(Color.parseColor("#41FF0000")) + .split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[3] + val alpha = color.substring(0, color.length - 1) + org.junit.Assert.assertEquals( + "alpha value should match", + 0.254f, + java.lang.Float.valueOf(alpha), + 0.001f + ) + } + + @Test + fun testCollator() { + val expected = arrayOf( + "collator", + object : HashMap() { + init { + put("case-sensitive", true) + put("diacritic-sensitive", true) + put("locale", "it-IT") + } + } + ) + val actual = Expression.collator(true, true, Locale.ITALY).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + fun testStringCollator() { + val expected = + ( + "[\"collator\", {\"diacritic-sensitive\": true, \"case-sensitive\": true, \"locale\": " + + "\"it\"}]" + ) + val actual = Expression.collator(true, true, Locale.ITALIAN).toString() + org.junit.Assert.assertEquals("expression should match", expected, actual) + } + + @Test + fun testResolvedLocale() { + val expected = arrayOf( + "resolved-locale", + arrayOf( + "collator", + object : HashMap() { + init { + put("case-sensitive", false) + put("diacritic-sensitive", false) + put("locale", "it") + } + } + ) + ) + val actual = + Expression.resolvedLocale(Expression.collator(false, false, Locale.ITALIAN)).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + fun testRawCollator() { + val expected = arrayOf( + "collator", + object : HashMap() { + init { + put("case-sensitive", true) + put("diacritic-sensitive", true) + put("locale", "it-IT") + } + } + ) + val actual = Expression.raw( + "[\"collator\", {\"diacritic-sensitive\": true, \"case-sensitive\": true, \"locale\": " + + "\"it-IT\"}]" + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + fun testRawCollatorDoubleConversion() { + val expected = Expression.collator(false, false, Locale.ITALIAN) + val actual = Expression.raw(expected.toString()).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected.toArray(), actual)) + } + + @Test + fun testStringNestedCollator() { + val expected = + ( + "[\"collator\", {\"diacritic-sensitive\": [\"==\", 2.0, 1.0], \"case-sensitive\": false," + + " \"locale\": \"it\"}]" + ) + val actual = Expression.collator( + Expression.literal(false), + Expression.eq(Expression.literal(2), Expression.literal(1)), + Expression.literal("it") + ).toString() + org.junit.Assert.assertEquals("expression should match", expected, actual) + } + + @Test + fun testStringReverseConversion() { + val expected = "[\"to-string\", [\"get\", \"name_en\"]]" + val actual = Expression.toString(Expression.get("name_en")).toString() + org.junit.Assert.assertEquals("Reverse string conversion should match", expected, actual) + } + + @Test + fun testIsSupportedScriptLiteral() { + val expected = arrayOf("is-supported-script", "ಗೌರವಾರ್ಥವಾಗಿ") + val actual = Expression.isSupportedScript("ಗೌರವಾರ್ಥವಾಗಿ").toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + fun testIsSupportedScriptExpressions() { + val expected = arrayOf("is-supported-script", arrayOf("get", "property_name")) + val actual = Expression.isSupportedScript(Expression.get("property_name")).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + fun testFormatSingleArgument() { + val expected = arrayOf( + "format", + "test", + object : TestableExpressionHashMap() { + init { + put("font-scale", 1.5f) + put("text-font", arrayOf("literal", arrayOf("awesome"))) + put("text-color", arrayOf("rgb", 255f, 0f, 0f)) + } + } + ) + val actual = Expression.format( + Expression.formatEntry( + Expression.literal("test"), + FormatOption.formatFontScale(Expression.literal(1.5)), + FormatOption.formatTextFont(Expression.literal(arrayOf("awesome"))), + FormatOption.formatTextColor(Expression.rgb(255, 0, 0)) + ) + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + @Test + fun testFormatMultipleArgument() { + val expected = arrayOf( + "format", + "test", + object : TestableExpressionHashMap() { + init { + put("text-font", arrayOf("literal", arrayOf("awesome"))) + } + }, + "test2", + object : TestableExpressionHashMap() { + init { + put("font-scale", 1.5f) + } + }, + "test3", + object : TestableExpressionHashMap() { + }, + "test4", + object : TestableExpressionHashMap() { + init { + put("text-color", arrayOf("rgb", 255f, 0f, 0f)) + } + }, + "test5", + object : TestableExpressionHashMap() { + init { + put("font-scale", 1.5f) + put("text-font", arrayOf("literal", arrayOf("awesome"))) + put("text-color", arrayOf("rgb", 255f, 0f, 0f)) + } + } + ) + val actual = Expression.format( + Expression.formatEntry( + Expression.literal("test"), + FormatOption.formatTextFont(arrayOf("awesome")) + ), + Expression.formatEntry("test2", FormatOption.formatFontScale(1.5)), + Expression.formatEntry(Expression.literal("test3")), + Expression.formatEntry( + Expression.literal("test4"), + FormatOption.formatTextColor(Expression.rgb(255, 0, 0)) + ), + Expression.formatEntry( + Expression.literal("test5"), + FormatOption.formatFontScale(Expression.literal(1.5)), + FormatOption.formatTextFont(arrayOf("awesome")), + FormatOption.formatTextColor(Expression.rgb(255, 0, 0)) + ) + ).toArray() + Assert.assertTrue("expression should match", Arrays.deepEquals(expected, actual)) + } + + /** + * This class overrides [java.util.AbstractMap.equals] + * in order to correctly compare nodes values if they are arrays, + * which is the case for [Expression.format]'s "text-format" argument. + */ + private open inner class TestableExpressionHashMap : HashMap() { + override fun equals(o: Any?): Boolean { + if (o === this) { + return true + } + if (o !is Map<*, *>) { + return false + } + val m = o + if (m.size != size) { + return false + } + try { + for ((key, value) in entries) { + if (value == null) { + if (!(m[key] == null && m.containsKey(key))) { + return false + } + } else { + if (value is Array<*>) { + // Use Arrays.deepEquals() if values are Object arrays. + if (!Arrays.deepEquals(value as Array?, m[key] as Array?)) { + return false + } + } else { + if (value != m[key]) { + return false + } + } + } + } + } catch (unused: ClassCastException) { + return false + } catch (unused: NullPointerException) { + return false + } + return true + } + } +}