Rename Gradle targets Android (#2226)

This commit is contained in:
Bart Louwers
2024-04-02 23:15:50 +02:00
committed by GitHub
parent 37170ed61c
commit 9f8ae7a98b
1081 changed files with 132 additions and 370 deletions

View File

@@ -0,0 +1,32 @@
package org.maplibre.android
import android.content.Context
import org.maplibre.android.MapLibre
import org.maplibre.android.util.TileServerOptions
object MapLibreInjector {
private const val FIELD_INSTANCE = "INSTANCE"
@JvmStatic
fun inject(context: Context, apiKey: String,
options: TileServerOptions) {
val maplibre = MapLibre(context, apiKey, options)
try {
val instance = MapLibre::class.java.getDeclaredField(FIELD_INSTANCE)
instance.isAccessible = true
instance[maplibre] = maplibre
} catch (exception: Exception) {
throw AssertionError()
}
}
@JvmStatic
fun clear() {
try {
val field = MapLibre::class.java.getDeclaredField(FIELD_INSTANCE)
field.isAccessible = true
field[field] = null
} catch (exception: Exception) {
throw AssertionError()
}
}
}

View File

@@ -0,0 +1,88 @@
package org.maplibre.android
import android.content.Context
import android.content.res.Resources
import android.content.res.TypedArray
import android.util.AttributeSet
import android.util.DisplayMetrics
import org.junit.After
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExpectedException
import org.maplibre.android.MapLibreInjector.clear
import org.maplibre.android.MapLibreInjector.inject
import org.maplibre.android.exceptions.MapLibreConfigurationException
import org.maplibre.android.maps.MapView
import org.maplibre.android.utils.ConfigUtils.Companion.getMockedOptions
import org.mockito.ArgumentMatchers
import org.mockito.Mockito
class MapLibreTest {
private var context: Context? = null
private var appContext: Context? = null
@Rule
@JvmField // J2K: https://stackoverflow.com/a/33449455
var expectedException = ExpectedException.none()
@Before
fun before() {
context = Mockito.mock(Context::class.java)
appContext = Mockito.mock(Context::class.java)
// J2K: https://www.baeldung.com/kotlin/smart-cast-to-type-is-impossible#2-using-the-safe-call-operator--and-a-scope-function
Mockito.`when`(context?.getApplicationContext()).thenReturn(appContext)
}
@Test
fun testGetApiKey() {
val apiKey = "pk.0000000001"
inject(context!!, apiKey, getMockedOptions())
Assert.assertSame(apiKey, MapLibre.getApiKey())
}
@Test
fun testApplicationContext() {
inject(context!!, "pk.0000000001", getMockedOptions())
Assert.assertNotNull(MapLibre.getApplicationContext())
Assert.assertNotEquals(context, appContext)
Assert.assertEquals(appContext, appContext)
}
@Test
fun testPlainTokenValid() {
Assert.assertTrue(MapLibre.isApiKeyValid("apiKey"))
}
@Test
fun testEmptyToken() {
Assert.assertFalse(MapLibre.isApiKeyValid(""))
}
@Test
fun testNullToken() {
Assert.assertFalse(MapLibre.isApiKeyValid(null))
}
@Test
fun testNoInstance() {
val displayMetrics = Mockito.mock(DisplayMetrics::class.java)
val resources = Mockito.mock(Resources::class.java)
Mockito.`when`(resources.displayMetrics).thenReturn(displayMetrics)
Mockito.`when`(context!!.resources).thenReturn(resources)
val typedArray = Mockito.mock(TypedArray::class.java)
Mockito.`when`(context!!.obtainStyledAttributes(ArgumentMatchers.nullable(AttributeSet::class.java), ArgumentMatchers.any(IntArray::class.java), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt()))
.thenReturn(typedArray)
expectedException.expect(MapLibreConfigurationException::class.java)
expectedException.expectMessage("""
Using MapView requires calling MapLibre.getInstance(Context context, String apiKey, WellKnownTileServer wellKnownTileServer) before inflating or creating the view.
""".trimIndent())
MapView(context!!)
}
@After
fun after() {
clear()
}
}

View File

@@ -0,0 +1,83 @@
package org.maplibre.android.annotations
import org.maplibre.android.maps.MapLibreMap
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 maplibreMap = Mockito.mock(MapLibreMap::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(maplibreMap)
annotation!!.remove()
Mockito.verify(maplibreMap, Mockito.times(1)).removeAnnotation(
annotation!!
)
}
@Test
fun testRemoveUnboundMapboxMap() {
annotation!!.id = 1
annotation!!.remove()
Mockito.verify(maplibreMap, 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)
}
}

View File

@@ -0,0 +1,53 @@
package org.maplibre.android.annotations
import android.graphics.Bitmap
import org.junit.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())
}
}

View File

@@ -0,0 +1,80 @@
package org.maplibre.android.annotations
import android.graphics.PointF
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.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 mMapLibreMap = Mockito.mock(MapLibreMap::class.java)
@Test
fun testSanity() {
val infoWindow = InfoWindow(mMapView, mMapLibreMap)
Assert.assertNotNull("infoWindow should exist", infoWindow)
}
@Test
fun testBoundMarker() {
val markerOptions = MarkerOptions()
val marker = markerOptions.position(LatLng()).marker
val infoWindow = InfoWindow(mMapView, mMapLibreMap).setBoundMarker(marker)
Assert.assertEquals("marker should match", marker, infoWindow.boundMarker)
}
@Test
fun testClose() {
val infoWindow = InfoWindow(mMapView, mMapLibreMap)
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`(mMapLibreMap.projection).thenReturn(projection)
Mockito.`when`(projection.toScreenLocation(latLng)).thenReturn(PointF(0f, 0f))
val infoWindow = InfoWindow(mMapView, mMapLibreMap)
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`(mMapLibreMap.projection).thenReturn(projection)
Mockito.`when`(projection.toScreenLocation(latLng)).thenReturn(PointF(0f, 0f))
val infoWindow = InfoWindow(mMapView, mMapLibreMap)
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`(mMapLibreMap.projection).thenReturn(projection)
Mockito.`when`(projection.toScreenLocation(latLng)).thenReturn(PointF(0f, 0f))
val infoWindow = InfoWindow(mMapView, mMapLibreMap)
infoWindow.open(mMapView, MarkerOptions().position(latLng).marker, latLng, 0, 0)
infoWindow.update()
}
}

View File

@@ -0,0 +1,159 @@
package org.maplibre.android.annotations
import android.graphics.Bitmap
import org.maplibre.android.exceptions.InvalidMarkerPositionException
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.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("MapLibre").position(LatLng())
val marker = markerOptions.marker
Assert.assertEquals(marker.title, "MapLibre")
Assert.assertEquals(markerOptions.getTitle(), "MapLibre")
}
@Test
fun testSnippet() {
val markerOptions = MarkerOptions().snippet("MapLibre").position(LatLng())
val marker = markerOptions.marker
Assert.assertEquals(marker.snippet, "MapLibre")
}
@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)
}
}

View File

@@ -0,0 +1,66 @@
package org.maplibre.android.annotations
import org.maplibre.android.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<LatLng> = 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])
}
}

View File

@@ -0,0 +1,66 @@
package org.maplibre.android.annotations
import org.maplibre.android.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<LatLng> = 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])
}
}

View File

@@ -0,0 +1,371 @@
package org.maplibre.android.attribution
import org.junit.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)
for ((counter, attribution) in attributionList.withIndex()) {
when (counter) {
0 -> {
Assert.assertEquals(
"URL mapbox should match",
"https://www.mapbox.com/about/maps/",
attribution.url
)
Assert.assertEquals("Title mapbox should match", "© MapLibre", 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
)
}
}
}
}
@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)
for ((counter, attribution) in attributionList.withIndex()) {
when (counter) {
0 -> {
Assert.assertEquals(
"URL mapbox should match",
"https://www.mapbox.com/about/maps/",
attribution.url
)
Assert.assertEquals("Title mapbox should match", "© MapLibre", 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
)
}
}
}
}
@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)
for ((counter, attribution) in attributionList.withIndex()) {
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
)
}
}
}
}
@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)
for ((counter, attribution) in attributionList.withIndex()) {
when (counter) {
0 -> {
Assert.assertEquals(
"URL mapbox should match",
"https://www.mapbox.com/about/maps/",
attribution.url
)
Assert.assertEquals("Title mapbox should match", "© MapLibre", 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
)
}
}
}
}
@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)
for ((counter, attribution) in attributionList.withIndex()) {
when (counter) {
0 -> {
Assert.assertEquals(
"URL mapbox should match",
"https://www.mapbox.com/about/maps/",
attribution.url
)
Assert.assertEquals("Title mapbox should match", "© MapLibre", 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
)
}
}
}
}
@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)
for ((counter, attribution) in attributionList.withIndex()) {
when (counter) {
0 -> {
Assert.assertEquals(
"URL mapbox should match",
"https://www.mapbox.com/about/maps/",
attribution.url
)
Assert.assertEquals("Title mapbox should match", "MapLibre", 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
)
}
}
}
}
@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",
"© MapLibre / 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",
"© MapLibre / © 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",
"© MapLibre / OSM / DigitalGlobe",
attributionParser.createAttributionString(true)
)
}
companion object {
private const val STREETS_ATTRIBUTION =
"<a href=\"https://www.mapbox.com/about/maps/\" target=\"_blank\">&copy; MapLibre</a> <a href=\"http://www.openstreetmap.org/about/\" target=\"_blank\">&copy; OpenStreetMap</a> \n"
private const val SATELLITE_ATTRIBUTION =
"<a href=\"https://www.mapbox.com/about/maps/\" target=\"_blank\">&copy; MapLibre</a> <a href=\"http://www.openstreetmap.org/about/\" target=\"_blank\">&copy; OpenStreetMap</a> <a href=\"https://www.digitalglobe.com/\" target=\"_blank\">&copy; DigitalGlobe</a>\n"
}
}

View File

@@ -0,0 +1,182 @@
package org.maplibre.android.camera
import android.content.res.TypedArray
import android.os.Parcel
import org.maplibre.android.R
import org.maplibre.android.camera.CameraUpdateFactory.ZoomUpdate
import org.maplibre.android.camera.CameraUpdateFactory.zoomTo
import org.maplibre.android.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
}
}

View File

@@ -0,0 +1,5 @@
package org.maplibre.android.constants
object AppConstant {
const val STYLE_VERSION = 9
}

View File

@@ -0,0 +1,858 @@
package org.maplibre.android.geometry
import org.maplibre.android.constants.GeometryConstants
import org.maplibre.android.exceptions.InvalidLatLngBoundsException
import org.maplibre.android.geometry.LatLngBounds.Companion.from
import org.maplibre.android.geometry.LatLngBounds.Companion.world
import org.maplibre.android.utils.MockParcel
import org.junit.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() {
Assert.assertEquals(
"Span should be the same",
2.0,
latLngBounds!!.latitudeSpan,
DELTA
)
}
@Test
fun longitudeSpan() {
Assert.assertEquals(
"Span should be the same",
2.0,
latLngBounds!!.longitudeSpan,
DELTA
)
}
@Test
fun coordinateSpan() {
val latLngSpan = latLngBounds!!.span
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
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
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
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
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
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
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
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
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
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
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
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
Assert.assertEquals("Center should match", LatLng(10.0, 0.0), center)
}
@Test
fun center() {
val center = latLngBounds!!.center
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()
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()
Assert.assertEquals(latLngBounds!!.northEast, LAT_LNG_NOT_NULL_ISLAND)
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()
Assert.assertArrayEquals(
"LatLngs should match",
arrayOf(LAT_LNG_NOT_NULL_ISLAND, LAT_LNG_NULL_ISLAND),
latLngBounds!!.toLatLngs()
)
}
@Test
fun include() {
Assert.assertTrue(
"LatLng should be included",
latLngBounds!!.contains(LatLng(1.0, 1.0))
)
}
@Test
fun includes() {
val points: MutableList<LatLng> = 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()
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()
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
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()
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()
Assert.assertEquals(
"LatLngSpan should be the same",
LatLngSpan(20.0, 20.0),
latLngBounds.span
)
}
@Test
fun containsNot() {
Assert.assertFalse(
"LatLng should not be included",
latLngBounds!!.contains(LatLng(3.0, 1.0))
)
}
@Test
fun containsBoundsInWorld() {
Assert.assertTrue(
"LatLngBounds should be contained in the world",
world().contains(latLngBounds!!)
)
}
@Test
fun worldSpan() {
Assert.assertEquals(
"LatLngBounds world span should be 180, 360",
GeometryConstants.LATITUDE_SPAN,
world().latitudeSpan,
DELTA
)
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
)
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()
Assert.assertTrue(outer.contains(inner))
Assert.assertFalse(inner.contains(outer))
}
@Test
fun testHashCode() {
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()
Assert.assertEquals("equality should match", this.latLngBounds, latLngBounds)
Assert.assertEquals(
"not equal to a different object type",
this.latLngBounds!!.equals(LAT_LNG_NOT_NULL_ISLAND),
false
)
}
@Test
fun testToString() {
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()
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()
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)
Assert.assertEquals(latLngBounds1.intersect(latLngBounds2), intersectLatLngBounds)
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)
Assert.assertEquals(latLngBounds1.intersect(latLngBounds2), intersectLatLngBounds)
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()
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()
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)
Assert.assertEquals(
union1,
LatLngBounds.Builder()
.include(LatLng(10.0, 160.0))
.include(LatLng(-10.0, 200.0))
.build()
)
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)
Assert.assertEquals(
union1,
LatLngBounds.Builder()
.include(LatLng(10.0, 160.0))
.include(LatLng(-10.0, 200.0))
.build()
)
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)
Assert.assertEquals(
union1,
LatLngBounds.Builder()
.include(LatLng(10.0, 160.0))
.include(LatLng(-10.0, 200.0))
.build()
)
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)
Assert.assertEquals(
union1,
LatLngBounds.Builder()
.include(LatLng(10.0, -200.0))
.include(LatLng(-10.0, -160.0))
.build()
)
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)
Assert.assertEquals(
union1,
LatLngBounds.Builder()
.include(LatLng(10.0, 160.0))
.include(LatLng(-10.0, 200.0))
.build()
)
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)
Assert.assertEquals(union1, union2)
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)
Assert.assertEquals(latLngBounds1.union(latLngBounds2), unionLatLngBounds)
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)
Assert.assertEquals(latLngBounds1.union(latLngBounds2), unionLatLngBounds)
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()
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()
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()
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()
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)
Assert.assertEquals("Parcel should match original object", parcel, latLngBounds)
}
@Test
fun fromTileID() {
var bounds = from(0, 0, 0)
Assert.assertEquals(
GeometryConstants.MIN_WRAP_LONGITUDE,
bounds.getLonWest(),
DELTA
)
Assert.assertEquals(
GeometryConstants.MIN_MERCATOR_LATITUDE,
bounds.getLatSouth(),
DELTA
)
Assert.assertEquals(
GeometryConstants.MAX_WRAP_LONGITUDE,
bounds.getLonEast(),
DELTA
)
Assert.assertEquals(
GeometryConstants.MAX_MERCATOR_LATITUDE,
bounds.getLatNorth(),
DELTA
)
bounds = from(10, 288, 385)
Assert.assertEquals(-78.75, bounds.getLonWest(), DELTA)
Assert.assertEquals(40.446947059600497, bounds.getLatSouth(), DELTA)
Assert.assertEquals(-78.3984375, bounds.getLonEast(), DELTA)
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)
}
}

View File

@@ -0,0 +1,67 @@
package org.maplibre.android.geometry
import org.maplibre.android.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)
}
}

View File

@@ -0,0 +1,283 @@
package org.maplibre.android.geometry
import android.location.Location
import org.maplibre.android.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.latitude = 3.0
Assert.assertEquals("latitude should match", 3.0, latLng.latitude, DELTA)
}
@Test
fun testLongitudeSetter() {
val latLng = LatLng(1.2, 3.4)
latLng.longitude = 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().latitude = Double.NaN
}
@Test
fun testLongitudeSetterChecksNaN() {
exception.expect(IllegalArgumentException::class.java)
exception.expectMessage("longitude must not be NaN")
LatLng().longitude = Double.NaN
}
@Test
fun testLatitudeSetterChecksGreaterThan90() {
exception.expect(IllegalArgumentException::class.java)
exception.expectMessage("latitude must be between -90 and 90")
LatLng().latitude = 95.0
}
@Test
fun testLatitudeSetterChecksLessThanThanNegative90() {
exception.expect(IllegalArgumentException::class.java)
exception.expectMessage("latitude must be between -90 and 90")
LatLng().latitude = -95.0
}
@Test
fun testLongitudeSetterChecksInfinity() {
exception.expect(IllegalArgumentException::class.java)
exception.expectMessage("longitude must not be infinite")
LatLng().longitude = 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
}
}

View File

@@ -0,0 +1,76 @@
package org.maplibre.android.geometry
import org.maplibre.android.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)
}
}

View File

@@ -0,0 +1,98 @@
package org.maplibre.android.geometry
import org.maplibre.android.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()
}
}

View File

@@ -0,0 +1,98 @@
package org.maplibre.android.location
import android.hardware.Sensor
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.view.WindowManager
import org.junit.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)
)
}
}

View File

@@ -0,0 +1,327 @@
package org.maplibre.android.location
import android.graphics.Bitmap
import android.graphics.Color
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.location.LocationComponentConstants.*
import org.maplibre.android.location.modes.RenderMode
import org.maplibre.android.maps.Style
import org.maplibre.android.style.expressions.Expression
import org.maplibre.android.style.layers.Layer
import org.maplibre.android.style.layers.Property
import org.maplibre.android.utils.BitmapUtils
import org.maplibre.android.utils.ColorUtils
import io.mockk.*
import org.junit.Assert
import org.junit.Before
import org.junit.Test
class IndicatorLocationLayerRendererTest {
private val style: Style = mockk(relaxUnitFun = true)
private val layerSourceProvider: LayerSourceProvider = mockk(relaxUnitFun = true)
private val layer: Layer = mockk(relaxUnitFun = true)
private lateinit var locationLayerRenderer: IndicatorLocationLayerRenderer
@Before
fun setup() {
every { style.removeLayer(any<Layer>()) } returns true
locationLayerRenderer = IndicatorLocationLayerRenderer(layerSourceProvider)
every { layerSourceProvider.generateLocationComponentLayer() } returns layer
locationLayerRenderer.initializeComponents(style)
}
@Test
fun sanity() {
Assert.assertNotNull(locationLayerRenderer)
}
@Test
fun initializeComponents_withLocation() {
val newLayer: Layer = mockk(relaxUnitFun = true)
every { layerSourceProvider.generateLocationComponentLayer() } returns newLayer
val latLng = LatLng(10.0, 20.0)
val bearing = 11f
val accuracy = 65f
locationLayerRenderer.setLatLng(latLng)
locationLayerRenderer.setGpsBearing(bearing)
locationLayerRenderer.setAccuracyRadius(accuracy)
locationLayerRenderer.initializeComponents(mockk())
verify { newLayer.setProperties(LocationPropertyFactory.location(latLng.toLocationArray())) }
verify { newLayer.setProperties(LocationPropertyFactory.bearing(bearing.toDouble())) }
verify { newLayer.setProperties(LocationPropertyFactory.accuracyRadius(accuracy)) }
}
@Test
fun addLayers() {
val positionManager: LocationComponentPositionManager = mockk(relaxUnitFun = true)
locationLayerRenderer.addLayers(positionManager)
verify { positionManager.addLayerToMap(layer) }
}
@Test
fun removeLayers() {
locationLayerRenderer.removeLayers()
verify { style.removeLayer(layer) }
}
@Test
fun hide() {
locationLayerRenderer.hide()
verify { layer.setProperties(LocationPropertyFactory.visibility(Property.NONE)) }
}
@Test
fun show() {
locationLayerRenderer.show(RenderMode.NORMAL, false)
verify { layer.setProperties(LocationPropertyFactory.visibility(Property.VISIBLE)) }
}
@Test
fun show_normal_notStale() {
locationLayerRenderer.show(RenderMode.NORMAL, false)
verify {
layer.setProperties(
LocationPropertyFactory.topImage(FOREGROUND_ICON),
LocationPropertyFactory.bearingImage(BACKGROUND_ICON),
LocationPropertyFactory.shadowImage(SHADOW_ICON)
)
}
}
@Test
fun show_compass_notStale() {
locationLayerRenderer.show(RenderMode.COMPASS, false)
verify {
layer.setProperties(
LocationPropertyFactory.topImage(FOREGROUND_ICON),
LocationPropertyFactory.bearingImage(BEARING_ICON),
LocationPropertyFactory.shadowImage(SHADOW_ICON)
)
}
}
@Test
fun show_gps_notStale() {
locationLayerRenderer.show(RenderMode.GPS, false)
verify {
layer.setProperties(
LocationPropertyFactory.topImage(""),
LocationPropertyFactory.bearingImage(FOREGROUND_ICON),
LocationPropertyFactory.shadowImage(BACKGROUND_ICON)
)
}
verify { layer.setProperties(LocationPropertyFactory.accuracyRadius(0f)) }
}
@Test
fun show_normal_stale() {
locationLayerRenderer.show(RenderMode.NORMAL, true)
verify {
layer.setProperties(
LocationPropertyFactory.topImage(FOREGROUND_STALE_ICON),
LocationPropertyFactory.bearingImage(BACKGROUND_STALE_ICON),
LocationPropertyFactory.shadowImage(SHADOW_ICON)
)
}
}
@Test
fun show_compass_stale() {
locationLayerRenderer.show(RenderMode.COMPASS, true)
verify {
layer.setProperties(
LocationPropertyFactory.topImage(FOREGROUND_STALE_ICON),
LocationPropertyFactory.bearingImage(BEARING_STALE_ICON),
LocationPropertyFactory.shadowImage(SHADOW_ICON)
)
}
}
@Test
fun show_gps_stale() {
locationLayerRenderer.show(RenderMode.GPS, true)
verify {
layer.setProperties(
LocationPropertyFactory.topImage(""),
LocationPropertyFactory.bearingImage(FOREGROUND_STALE_ICON),
LocationPropertyFactory.shadowImage(BACKGROUND_STALE_ICON)
)
}
verify { layer.setProperties(LocationPropertyFactory.accuracyRadius(0f)) }
}
@Test
fun styleAccuracy() {
val colorArray = ColorUtils.colorToRgbaArray(Color.RED)
val exp = Expression.rgba(colorArray[0], colorArray[1], colorArray[2], 0.7f)
locationLayerRenderer.styleAccuracy(0.7f, Color.RED)
verify {
layer.setProperties(
LocationPropertyFactory.accuracyRadiusColor(exp),
LocationPropertyFactory.accuracyRadiusBorderColor(exp)
)
}
}
@Test
fun setLatLng() {
val latLng = LatLng(10.0, 20.0)
locationLayerRenderer.setLatLng(latLng)
verify { layer.setProperties(LocationPropertyFactory.location(latLng.toLocationArray())) }
}
@Test
fun setGpsBearing() {
val bearing = 30.0
locationLayerRenderer.setGpsBearing(bearing.toFloat())
verify { layer.setProperties(LocationPropertyFactory.bearing(bearing)) }
}
@Test
fun setCompassBearing() {
val bearing = 30.0
locationLayerRenderer.setCompassBearing(bearing.toFloat())
verify { layer.setProperties(LocationPropertyFactory.bearing(bearing)) }
}
@Test
fun setAccuracyRadius() {
val radius = 40f
locationLayerRenderer.setAccuracyRadius(radius)
verify { layer.setProperties(LocationPropertyFactory.accuracyRadius(radius)) }
}
@Test
fun styleScaling() {
val exp = Expression.literal("")
locationLayerRenderer.styleScaling(exp)
verify {
layer.setProperties(
LocationPropertyFactory.shadowImageSize(exp),
LocationPropertyFactory.bearingImageSize(exp),
LocationPropertyFactory.topImageSize(exp)
)
}
}
@Test
fun setLocationStale() {
locationLayerRenderer.setLocationStale(true, RenderMode.NORMAL)
verify {
layer.setProperties(
LocationPropertyFactory.topImage(FOREGROUND_STALE_ICON),
LocationPropertyFactory.bearingImage(BACKGROUND_STALE_ICON),
LocationPropertyFactory.shadowImage(SHADOW_ICON)
)
}
}
@Test
fun addBitmaps_shadow() {
addBitmaps(withShadow = true, renderMode = RenderMode.NORMAL)
verify { style.addImage(SHADOW_ICON, shadowBitmap) }
}
@Test
fun addBitmaps_noShadow() {
addBitmaps(withShadow = false, renderMode = RenderMode.NORMAL)
verify { style.removeImage(SHADOW_ICON) }
}
@Test
fun addBitmaps_normal() {
addBitmaps(withShadow = true, renderMode = RenderMode.NORMAL)
verify { style.addImage(FOREGROUND_ICON, foregroundBitmap) }
verify { style.addImage(FOREGROUND_STALE_ICON, foregroundStaleBitmap) }
verify { style.addImage(BACKGROUND_ICON, backgroundBitmap) }
verify { style.addImage(BACKGROUND_STALE_ICON, backgroundStaleBitmap) }
verify { style.addImage(BEARING_ICON, bearingBitmap) }
}
@Test
fun addBitmaps_compass() {
every { bearingBitmap.width } returns 40
every { bearingBitmap.height } returns 40
every { bearingBitmap.config } returns mockk()
every { backgroundBitmap.width } returns 20
every { backgroundBitmap.height } returns 10
val mergedBitmap = mockk<Bitmap>()
mockkStatic(BitmapUtils::class)
every { BitmapUtils.mergeBitmap(bearingBitmap, backgroundBitmap, 10f, 15f) } returns mergedBitmap
every { bearingBitmap.width } returns 40
every { bearingBitmap.height } returns 40
every { bearingBitmap.config } returns mockk()
every { backgroundStaleBitmap.width } returns 30
every { backgroundStaleBitmap.height } returns 10
val mergedStaleBitmap = mockk<Bitmap>()
every { BitmapUtils.mergeBitmap(bearingBitmap, backgroundStaleBitmap, 5f, 15f) } returns mergedStaleBitmap
addBitmaps(withShadow = true, renderMode = RenderMode.COMPASS)
verify { style.addImage(BEARING_ICON, mergedBitmap) }
verify { style.addImage(BEARING_STALE_ICON, mergedStaleBitmap) }
unmockkStatic(BitmapUtils::class)
}
@Test
fun addBitmaps_gps() {
addBitmaps(withShadow = true, renderMode = RenderMode.GPS)
verify { style.addImage(FOREGROUND_ICON, foregroundBitmap) }
verify { style.addImage(FOREGROUND_STALE_ICON, foregroundStaleBitmap) }
verify { style.addImage(BACKGROUND_ICON, backgroundBitmap) }
verify { style.addImage(BACKGROUND_STALE_ICON, backgroundStaleBitmap) }
verify { style.addImage(BEARING_ICON, bearingBitmap) }
}
private val shadowBitmap = mockk<Bitmap>()
private val backgroundBitmap = mockk<Bitmap>()
private val backgroundStaleBitmap = mockk<Bitmap>()
private val bearingBitmap = mockk<Bitmap>()
private val foregroundBitmap = mockk<Bitmap>()
private val foregroundStaleBitmap = mockk<Bitmap>()
private fun addBitmaps(withShadow: Boolean, @RenderMode.Mode renderMode: Int) {
locationLayerRenderer.addBitmaps(
renderMode,
if (withShadow) shadowBitmap else null,
backgroundBitmap,
backgroundStaleBitmap,
bearingBitmap,
foregroundBitmap,
foregroundStaleBitmap
)
}
private fun LatLng.toLocationArray() = arrayOf(latitude, longitude, 0.0)
}

View File

@@ -0,0 +1,808 @@
package org.maplibre.android.location
import android.animation.Animator
import android.animation.ValueAnimator
import android.location.Location
import android.util.SparseArray
import android.view.animation.LinearInterpolator
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.location.LocationComponentConstants.DEFAULT_TRACKING_TILT_ANIM_DURATION
import org.maplibre.android.location.LocationComponentConstants.DEFAULT_TRACKING_ZOOM_ANIM_DURATION
import org.maplibre.android.location.MapLibreAnimator.*
import org.maplibre.android.location.modes.RenderMode
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.Projection
import io.mockk.*
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.maplibre.android.location.LocationComponentConstants.DEFAULT_TRACKING_PADDING_ANIM_DURATION
import org.mockito.Mockito
import org.robolectric.RobolectricTestRunner
import org.maplibre.testUtils.Assert as MapLibreAssert
@RunWith(RobolectricTestRunner::class)
class LocationAnimatorCoordinatorTest {
private lateinit var locationAnimatorCoordinator: LocationAnimatorCoordinator
private val cameraPosition: CameraPosition = CameraPosition.DEFAULT
private val animatorProvider: MapLibreAnimatorProvider = mockk()
private val animatorSetProvider: MapLibreAnimatorSetProvider = mockk()
private val projection: Projection = mockk()
@Before
fun setUp() {
locationAnimatorCoordinator = LocationAnimatorCoordinator(
projection,
animatorSetProvider,
animatorProvider
)
configureAnimatorProvider()
every { projection.getMetersPerPixelAtLatitude(any()) } answers { 1.0 }
val startedAnimatorsSlot = slot<List<Animator>>()
every { animatorSetProvider.startAnimation(capture(startedAnimatorsSlot), any(), any()) } answers {
startedAnimatorsSlot.captured.forEach {
it.start()
}
}
locationAnimatorCoordinator.updateAnimatorListenerHolders(
getListenerHoldersSet(
ANIMATOR_LAYER_LATLNG,
ANIMATOR_CAMERA_LATLNG,
ANIMATOR_LAYER_GPS_BEARING,
ANIMATOR_LAYER_COMPASS_BEARING,
ANIMATOR_CAMERA_GPS_BEARING,
ANIMATOR_CAMERA_COMPASS_BEARING,
ANIMATOR_LAYER_ACCURACY,
ANIMATOR_ZOOM,
ANIMATOR_TILT,
ANIMATOR_PADDING
)
)
}
private fun configureAnimatorProvider() {
// workaround https://github.com/mockk/mockk/issues/229#issuecomment-457816131
registerInstanceFactory { AnimationsValueChangeListener<Float> {} }
registerInstanceFactory { AnimationsValueChangeListener<LatLng> {} }
val floatsSlot = slot<Array<Float>>()
val listenerSlot = slot<AnimationsValueChangeListener<*>>()
val maxFpsSlot = slot<Int>()
every {
animatorProvider.floatAnimator(capture(floatsSlot), capture(listenerSlot), capture(maxFpsSlot))
} answers {
MapLibreFloatAnimator(
floatsSlot.captured,
listenerSlot.captured,
maxFpsSlot.captured
)
}
val latLngsSlot = slot<Array<LatLng>>()
every {
animatorProvider.latLngAnimator(capture(latLngsSlot), capture(listenerSlot), capture(maxFpsSlot))
} answers {
MapLibreLatLngAnimator(
latLngsSlot.captured,
listenerSlot.captured,
maxFpsSlot.captured
)
}
val callback = slot<MapLibreMap.CancelableCallback>()
every {
animatorProvider.cameraAnimator(capture(floatsSlot), capture(listenerSlot), capture(callback))
} answers {
MapLibreCameraAnimatorAdapter(
floatsSlot.captured,
listenerSlot.captured,
callback.captured
)
}
every {
animatorProvider.cameraAnimator(capture(floatsSlot), capture(listenerSlot), null)
} answers {
MapLibreCameraAnimatorAdapter(
floatsSlot.captured,
listenerSlot.captured,
null
)
}
val doubleArraySlot = slot<Array<DoubleArray>>()
val doubleArrayListenerSlot = slot<AnimationsValueChangeListener<DoubleArray>>()
every {
animatorProvider.paddingAnimator(capture(doubleArraySlot), capture(doubleArrayListenerSlot), capture(callback))
} answers {
MapLibrePaddingAnimator(doubleArraySlot.captured, doubleArrayListenerSlot.captured, callback.captured)
}
every {
animatorProvider.paddingAnimator(capture(doubleArraySlot), capture(doubleArrayListenerSlot), null)
} answers {
MapLibrePaddingAnimator(doubleArraySlot.captured, doubleArrayListenerSlot.captured, null)
}
}
@Test
fun feedNewLocation_animatorsAreCreated() {
locationAnimatorCoordinator.feedNewLocation(Location(""), cameraPosition, false)
assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_LATLNG] != null)
assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_GPS_BEARING] != null)
assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_LATLNG] != null)
assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_GPS_BEARING] != null)
}
@Test
fun feedNewLocation_animatorValue() {
val location = Location("")
location.latitude = 51.0
location.longitude = 17.0
location.bearing = 35f
locationAnimatorCoordinator.feedNewLocation(location, cameraPosition, false)
val cameraLatLngTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_LATLNG]?.target as LatLng
MapLibreAssert.assertEquals(location.latitude, cameraLatLngTarget.latitude)
MapLibreAssert.assertEquals(location.longitude, cameraLatLngTarget.longitude)
val layerLatLngTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_LATLNG]?.target as LatLng
MapLibreAssert.assertEquals(location.latitude, layerLatLngTarget.latitude)
MapLibreAssert.assertEquals(location.longitude, layerLatLngTarget.longitude)
val cameraBearingTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_GPS_BEARING]?.target as Float
MapLibreAssert.assertEquals(location.bearing, cameraBearingTarget)
val layerBearingTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_GPS_BEARING]?.target as Float
MapLibreAssert.assertEquals(location.bearing, layerBearingTarget)
}
@Test
fun feedNewLocation_animatorValue_multiplePoints() {
val previousLocation = Location("")
previousLocation.latitude = 0.0
previousLocation.longitude = 0.0
previousLocation.bearing = 0f
val locationInter = Location("")
locationInter.latitude = 51.1
locationInter.longitude = 17.1
locationInter.bearing = 35f
val location = Location("")
location.latitude = 51.2
location.longitude = 17.2
location.bearing = 36f
locationAnimatorCoordinator.feedNewLocation(arrayOf(locationInter, location), cameraPosition, false, false)
val cameraLatLngTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_LATLNG]?.target as LatLng
MapLibreAssert.assertEquals(location.latitude, cameraLatLngTarget.latitude)
MapLibreAssert.assertEquals(location.longitude, cameraLatLngTarget.longitude)
val layerLatLngTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_LATLNG]?.target as LatLng
MapLibreAssert.assertEquals(location.latitude, layerLatLngTarget.latitude)
MapLibreAssert.assertEquals(location.longitude, layerLatLngTarget.longitude)
val cameraBearingTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_GPS_BEARING]?.target as Float
MapLibreAssert.assertEquals(location.bearing, cameraBearingTarget)
val layerBearingTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_GPS_BEARING]?.target as Float
MapLibreAssert.assertEquals(location.bearing, layerBearingTarget)
verify {
animatorProvider.latLngAnimator(
arrayOf(
LatLng(previousLocation.latitude, previousLocation.longitude),
LatLng(locationInter.latitude, locationInter.longitude),
LatLng(location.latitude, location.longitude)
),
any(),
any()
)
}
verify {
animatorProvider.floatAnimator(
arrayOf(previousLocation.bearing, locationInter.bearing, location.bearing),
any(),
any()
)
}
}
@Test
fun feedNewLocation_animatorValue_bearing() {
val previous = Location("")
previous.latitude = 51.1
previous.longitude = 17.1
previous.bearing = 355f
val current = Location("")
current.latitude = 51.2
current.longitude = 17.2
current.bearing = 0f
locationAnimatorCoordinator.feedNewLocation(arrayOf(previous, current), cameraPosition, false, false)
verify {
animatorProvider.floatAnimator(
arrayOf(0f, -5f, 0f),
any(),
any()
)
}
locationAnimatorCoordinator.feedNewLocation(arrayOf(previous, current), cameraPosition, true, false)
verify {
animatorProvider.floatAnimator(
arrayOf(0f, 0f),
any(),
any()
)
}
}
@Test
fun feedNewLocation_animatorValue_multiplePoints_animationDuration() {
every { projection.getMetersPerPixelAtLatitude(any()) } answers { 10000.0 } // disable snap
val locationInter = Location("")
locationInter.latitude = 51.1
locationInter.longitude = 17.1
locationInter.bearing = 35f
val location = Location("")
location.latitude = 51.2
location.longitude = 17.2
location.bearing = 36f
locationAnimatorCoordinator.feedNewLocation(arrayOf(locationInter, location), cameraPosition, false, false)
verify {
animatorSetProvider.startAnimation(
eq(
listOf(
locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_LATLNG],
locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_GPS_BEARING],
locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_LATLNG],
locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_GPS_BEARING]
)
),
any<LinearInterpolator>(),
0
)
}
}
@Test
fun feedNewLocation_animatorValue_multiplePoints_animationDuration_lookAhead() {
every { projection.getMetersPerPixelAtLatitude(any()) } answers { 10000.0 } // disable snap
val locationInter = Location("")
locationInter.latitude = 51.1
locationInter.longitude = 17.1
locationInter.bearing = 35f
val location = Location("")
location.latitude = 51.2
location.longitude = 17.2
location.bearing = 36f
location.time = System.currentTimeMillis() + 2000
locationAnimatorCoordinator.feedNewLocation(arrayOf(locationInter, location), cameraPosition, false, true)
verify {
animatorSetProvider.startAnimation(
eq(
listOf(
locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_LATLNG],
locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_GPS_BEARING],
locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_LATLNG],
locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_GPS_BEARING]
)
),
any<LinearInterpolator>(),
more(1500L)
)
}
}
@Test
fun feedNewLocation_animatorValue_correctRotation_1() {
val location = Location("")
location.latitude = 51.0
location.longitude = 17.0
location.bearing = 0f
val animator = mockk<MapLibreFloatAnimator>(relaxed = true)
every { animator.animatedValue } returns 270f
locationAnimatorCoordinator.animatorArray.put(ANIMATOR_LAYER_GPS_BEARING, animator)
locationAnimatorCoordinator.feedNewLocation(location, cameraPosition, false)
val layerBearingTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_GPS_BEARING]?.target as Float
MapLibreAssert.assertEquals(360f, layerBearingTarget)
}
@Test
fun feedNewLocation_animatorValue_correctRotation_2() {
val location = Location("")
location.latitude = 51.0
location.longitude = 17.0
location.bearing = 90f
val animator = mockk<MapLibreFloatAnimator>(relaxed = true)
every { animator.animatedValue } returns 280f
locationAnimatorCoordinator.animatorArray.put(ANIMATOR_LAYER_GPS_BEARING, animator)
locationAnimatorCoordinator.feedNewLocation(location, cameraPosition, false)
val layerBearingTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_GPS_BEARING]?.target as Float
MapLibreAssert.assertEquals(450f, layerBearingTarget)
}
@Test
fun feedNewLocation_animatorValue_correctRotation_3() {
val location = Location("")
location.latitude = 51.0
location.longitude = 17.0
location.bearing = 300f
val animator = mockk<MapLibreFloatAnimator>(relaxed = true)
every { animator.animatedValue } returns 450f
locationAnimatorCoordinator.animatorArray.put(ANIMATOR_LAYER_GPS_BEARING, animator)
locationAnimatorCoordinator.feedNewLocation(location, cameraPosition, false)
val layerBearingTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_GPS_BEARING]?.target as Float
MapLibreAssert.assertEquals(-60f, layerBearingTarget)
}
@Test
fun feedNewLocation_animatorValue_correctRotation_4() {
val location = Location("")
location.latitude = 51.0
location.longitude = 17.0
location.bearing = 350f
val animator = mockk<MapLibreFloatAnimator>(relaxed = true)
every { animator.animatedValue } returns 10f
locationAnimatorCoordinator.animatorArray.put(ANIMATOR_LAYER_GPS_BEARING, animator)
locationAnimatorCoordinator.feedNewLocation(location, cameraPosition, false)
val layerBearingTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_GPS_BEARING]?.target as Float
MapLibreAssert.assertEquals(-10f, layerBearingTarget)
}
@Test
fun feedNewLocation_animatorValue_correctRotation_5() {
val location = Location("")
location.latitude = 51.0
location.longitude = 17.0
location.bearing = 90f
val animator = mockk<MapLibreFloatAnimator>(relaxed = true)
every { animator.animatedValue } returns -280f
locationAnimatorCoordinator.animatorArray.put(ANIMATOR_LAYER_GPS_BEARING, animator)
locationAnimatorCoordinator.feedNewLocation(location, cameraPosition, false)
val layerBearingTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_GPS_BEARING]?.target as Float
MapLibreAssert.assertEquals(90f, layerBearingTarget)
}
@Test
fun feedNewLocation_animatorValue_correctRotation_6() {
val location = Location("")
location.latitude = 51.0
location.longitude = 17.0
location.bearing = 270f
val animator = mockk<MapLibreFloatAnimator>(relaxed = true)
every { animator.animatedValue } returns -350f
locationAnimatorCoordinator.animatorArray.put(ANIMATOR_LAYER_GPS_BEARING, animator)
locationAnimatorCoordinator.feedNewLocation(location, cameraPosition, false)
val layerBearingTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_GPS_BEARING]?.target as Float
MapLibreAssert.assertEquals(-90f, layerBearingTarget)
}
@Test
fun feedNewLocation_isNorth_animatorsAreCreated() {
val location = Location("")
location.latitude = 51.0
location.longitude = 17.0
location.bearing = 35f
locationAnimatorCoordinator.feedNewLocation(location, cameraPosition, false)
assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_LATLNG] != null)
assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_GPS_BEARING] != null)
assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_LATLNG] != null)
assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_GPS_BEARING] != null)
}
@Test
fun feedNewLocation_isNorth_animatorValue() {
val location = Location("")
location.latitude = 51.0
location.longitude = 17.0
location.bearing = 35f
locationAnimatorCoordinator.feedNewLocation(location, cameraPosition, true)
val cameraLatLngTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_LATLNG]?.target as LatLng
MapLibreAssert.assertEquals(cameraLatLngTarget.latitude, cameraLatLngTarget.latitude)
val layerLatLngTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_LATLNG]?.target as LatLng
MapLibreAssert.assertEquals(layerLatLngTarget.latitude, layerLatLngTarget.latitude)
val cameraBearingTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_GPS_BEARING]?.target as Float
MapLibreAssert.assertEquals(0f, cameraBearingTarget)
val layerBearingTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_GPS_BEARING]?.target as Float
MapLibreAssert.assertEquals(location.bearing, layerBearingTarget)
}
@Test
fun feedNewCompassBearing_animatorsAreCreated() {
locationAnimatorCoordinator.feedNewCompassBearing(77f, cameraPosition)
assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_COMPASS_BEARING] != null)
assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_COMPASS_BEARING] != null)
}
@Test
fun feedNewCompassBearing_animatorValue() {
val bearing = 77f
locationAnimatorCoordinator.feedNewCompassBearing(bearing, cameraPosition)
val cameraBearingTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_COMPASS_BEARING]?.target as Float
MapLibreAssert.assertEquals(bearing, cameraBearingTarget)
val layerBearingTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_COMPASS_BEARING]?.target as Float
MapLibreAssert.assertEquals(bearing, layerBearingTarget)
}
@Test
fun feedNewAccuracyRadius_animatorsCreated() {
locationAnimatorCoordinator.feedNewAccuracyRadius(150f, false)
assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_ACCURACY] != null)
}
@Test
fun feedNewAccuracyRadius_animatorValue() {
val accuracy = 150f
locationAnimatorCoordinator.feedNewAccuracyRadius(accuracy, false)
val layerAccuracy = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_ACCURACY]?.target as Float
MapLibreAssert.assertEquals(layerAccuracy, accuracy)
}
@Test
fun feedNewAccuracyRadius_noAnimation_animatorsCreated() {
locationAnimatorCoordinator.feedNewAccuracyRadius(150f, true)
assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_ACCURACY] != null)
}
@Test
fun feedNewAccuracyRadius_noAnimation_animatorValue() {
val accuracy = 150f
locationAnimatorCoordinator.feedNewAccuracyRadius(accuracy, true)
val layerAccuracy = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_ACCURACY]?.target as Float
MapLibreAssert.assertEquals(layerAccuracy, accuracy)
}
@Test
fun feedNewZoomLevel_animatorsCreated() {
locationAnimatorCoordinator.feedNewZoomLevel(
15.0,
cameraPosition,
DEFAULT_TRACKING_ZOOM_ANIM_DURATION,
null
)
assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_ZOOM] != null)
}
@Test
fun feedNewZoomLevel_animatorValue() {
val zoom = 15.0f
locationAnimatorCoordinator.feedNewZoomLevel(
zoom.toDouble(),
cameraPosition,
DEFAULT_TRACKING_ZOOM_ANIM_DURATION,
null
)
val animator = locationAnimatorCoordinator.animatorArray[ANIMATOR_ZOOM]
MapLibreAssert.assertEquals(zoom, animator.target as Float)
verify { animatorSetProvider.startAnimation(eq(listOf(animator)), any<LinearInterpolator>(), DEFAULT_TRACKING_ZOOM_ANIM_DURATION) }
}
@Test
fun feedNewPadding_animatorsCreated() {
locationAnimatorCoordinator.feedNewPadding(
doubleArrayOf(100.0, 200.0, 300.0, 400.0),
cameraPosition,
DEFAULT_TRACKING_PADDING_ANIM_DURATION,
null
)
assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_PADDING] != null)
}
@Test
fun feedNewPadding_animatorValue() {
val padding = doubleArrayOf(100.0, 200.0, 300.0, 400.0)
locationAnimatorCoordinator.feedNewPadding(
padding,
cameraPosition,
DEFAULT_TRACKING_PADDING_ANIM_DURATION,
null
)
val animator = locationAnimatorCoordinator.animatorArray[ANIMATOR_PADDING]
assertTrue(padding.contentEquals(animator.target as DoubleArray))
verify { animatorSetProvider.startAnimation(eq(listOf(animator)), any<LinearInterpolator>(), DEFAULT_TRACKING_PADDING_ANIM_DURATION) }
}
@Test
fun feedNewTiltLevel_animatorsCreated() {
locationAnimatorCoordinator.feedNewTilt(
30.0,
cameraPosition,
DEFAULT_TRACKING_TILT_ANIM_DURATION,
null
)
assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_TILT] != null)
}
@Test
fun feedNewTiltLevel_animatorValue() {
val tilt = 30.0f
locationAnimatorCoordinator.feedNewTilt(
tilt.toDouble(),
cameraPosition,
DEFAULT_TRACKING_TILT_ANIM_DURATION,
null
)
val animator = locationAnimatorCoordinator.animatorArray[ANIMATOR_TILT]
MapLibreAssert.assertEquals(tilt, animator.target as Float)
verify { animatorSetProvider.startAnimation(eq(listOf(animator)), any<LinearInterpolator>(), DEFAULT_TRACKING_TILT_ANIM_DURATION) }
}
@Test
fun cancelAllAnimators() {
locationAnimatorCoordinator.feedNewLocation(Location(""), cameraPosition, true)
assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_LATLNG].isStarted)
locationAnimatorCoordinator.cancelAllAnimations()
assertFalse(locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_LATLNG].isStarted)
}
@Test
fun cancelZoomAnimators() {
locationAnimatorCoordinator.feedNewZoomLevel(
15.0,
cameraPosition,
DEFAULT_TRACKING_ZOOM_ANIM_DURATION,
null
)
assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_ZOOM].isStarted)
locationAnimatorCoordinator.cancelZoomAnimation()
assertFalse(locationAnimatorCoordinator.animatorArray[ANIMATOR_ZOOM].isStarted)
}
@Test
fun cancelPaddingAnimators() {
locationAnimatorCoordinator.feedNewPadding(
doubleArrayOf(100.0, 200.0, 300.0, 400.0),
cameraPosition,
DEFAULT_TRACKING_PADDING_ANIM_DURATION,
null
)
assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_PADDING].isStarted)
locationAnimatorCoordinator.cancelPaddingAnimation()
assertFalse(locationAnimatorCoordinator.animatorArray[ANIMATOR_PADDING].isStarted)
}
@Test
fun cancelTiltAnimation() {
locationAnimatorCoordinator.feedNewTilt(
30.0,
cameraPosition,
DEFAULT_TRACKING_TILT_ANIM_DURATION,
null
)
assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_TILT].isStarted)
locationAnimatorCoordinator.cancelTiltAnimation()
assertFalse(locationAnimatorCoordinator.animatorArray[ANIMATOR_TILT].isStarted)
}
@Test
fun resetAllCameraAnimations_empty() {
locationAnimatorCoordinator.resetAllCameraAnimations(cameraPosition, false)
assertTrue(locationAnimatorCoordinator.animatorArray.size() == 0)
}
@Test
fun resetAllLayerAnimations_empty() {
locationAnimatorCoordinator.resetAllLayerAnimations()
assertTrue(locationAnimatorCoordinator.animatorArray.size() == 0)
}
@Test
fun addNewListener() {
val listener = Mockito.mock(AnimationsValueChangeListener::class.java)
val holder = AnimatorListenerHolder(RenderMode.NORMAL, listener)
val set = HashSet<AnimatorListenerHolder>().also {
it.add(holder)
}
locationAnimatorCoordinator.updateAnimatorListenerHolders(set)
assertTrue(locationAnimatorCoordinator.listeners.contains(listener))
}
@Test
fun updateListeners() {
val listener = Mockito.mock(AnimationsValueChangeListener::class.java)
val holder = AnimatorListenerHolder(ANIMATOR_LAYER_LATLNG, listener)
val set = HashSet<AnimatorListenerHolder>().also {
it.add(holder)
}
locationAnimatorCoordinator.updateAnimatorListenerHolders(set)
val listener2 = Mockito.mock(AnimationsValueChangeListener::class.java)
val holder2 = AnimatorListenerHolder(ANIMATOR_LAYER_LATLNG, listener2)
val listener3 = Mockito.mock(AnimationsValueChangeListener::class.java)
val holder3 = AnimatorListenerHolder(ANIMATOR_LAYER_ACCURACY, listener3)
val set2 = HashSet<AnimatorListenerHolder>().also {
it.add(holder2)
it.add(holder3)
}
locationAnimatorCoordinator.updateAnimatorListenerHolders(set2)
assertTrue(locationAnimatorCoordinator.listeners.size() == 2)
assertTrue(locationAnimatorCoordinator.listeners.contains(listener2))
assertTrue(locationAnimatorCoordinator.listeners.contains(listener3))
}
@Test
fun updateListeners_listenerRemoved_animtorInvalid() {
// setup accuracy animator
val listener: AnimationsValueChangeListener<Float> = mockk(relaxUnitFun = true)
val holder = AnimatorListenerHolder(ANIMATOR_LAYER_ACCURACY, listener)
val set = HashSet<AnimatorListenerHolder>().also {
it.add(holder)
}
locationAnimatorCoordinator.updateAnimatorListenerHolders(set)
locationAnimatorCoordinator.feedNewAccuracyRadius(500f, true)
// reset animator listeners which should make the previously created animator invalid
val listener2: AnimationsValueChangeListener<*> = mockk()
val holder2 = AnimatorListenerHolder(ANIMATOR_LAYER_LATLNG, listener2)
val listener3: AnimationsValueChangeListener<*> = mockk()
val holder3 = AnimatorListenerHolder(ANIMATOR_CAMERA_GPS_BEARING, listener3)
val set2 = HashSet<AnimatorListenerHolder>().also {
it.add(holder2)
it.add(holder3)
}
locationAnimatorCoordinator.updateAnimatorListenerHolders(set2)
// try pushing an update to verify it was ignored
val valueAnimator: ValueAnimator = mockk()
every { valueAnimator.animatedValue } returns 10f
val animator = locationAnimatorCoordinator.animatorArray.get(ANIMATOR_LAYER_ACCURACY)
animator.onAnimationUpdate(valueAnimator)
verify(exactly = 0) { listener.onNewAnimationValue(10f) }
}
@Test
fun feedNewCompassBearing_withAnimation() {
locationAnimatorCoordinator.setCompassAnimationEnabled(true)
locationAnimatorCoordinator.feedNewCompassBearing(77f, cameraPosition)
val animators = mutableListOf<Animator>(
locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_COMPASS_BEARING],
locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_COMPASS_BEARING]
)
verify(exactly = 1) { animatorSetProvider.startAnimation(eq(animators), ofType(LinearInterpolator::class), eq(LocationComponentConstants.COMPASS_UPDATE_RATE_MS)) }
}
@Test
fun feedNewCompassBearing_withoutAnimation() {
locationAnimatorCoordinator.setCompassAnimationEnabled(false)
locationAnimatorCoordinator.feedNewCompassBearing(77f, cameraPosition)
val animators = mutableListOf<Animator>(
locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_COMPASS_BEARING],
locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_COMPASS_BEARING]
)
verify(exactly = 1) { animatorSetProvider.startAnimation(eq(animators), ofType(LinearInterpolator::class), eq(0)) }
}
@Test
fun feedNewAccuracy_withAnimation() {
locationAnimatorCoordinator.setAccuracyAnimationEnabled(true)
locationAnimatorCoordinator.feedNewAccuracyRadius(150f, false)
val animators = mutableListOf<Animator>(
locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_ACCURACY]
)
verify(exactly = 1) { animatorSetProvider.startAnimation(eq(animators), ofType(LinearInterpolator::class), eq(LocationComponentConstants.ACCURACY_RADIUS_ANIMATION_DURATION)) }
}
@Test
fun feedNewAccuracy_withoutAnimation() {
locationAnimatorCoordinator.setAccuracyAnimationEnabled(false)
locationAnimatorCoordinator.feedNewAccuracyRadius(150f, false)
val animators = mutableListOf<Animator>(
locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_ACCURACY]
)
verify(exactly = 1) { animatorSetProvider.startAnimation(eq(animators), ofType(LinearInterpolator::class), eq(0)) }
}
@Test
fun maxFps_setter() {
locationAnimatorCoordinator.setMaxAnimationFps(5)
assertEquals(5, locationAnimatorCoordinator.maxAnimationFps)
}
@Test
fun maxFps_moreThanZeroRequired() {
locationAnimatorCoordinator.setMaxAnimationFps(0)
assertEquals(Int.MAX_VALUE, locationAnimatorCoordinator.maxAnimationFps)
locationAnimatorCoordinator.setMaxAnimationFps(-1)
assertEquals(Int.MAX_VALUE, locationAnimatorCoordinator.maxAnimationFps)
}
@Test
fun maxFps_givenToAnimator() {
locationAnimatorCoordinator.setMaxAnimationFps(5)
locationAnimatorCoordinator.feedNewLocation(Location(""), cameraPosition, false)
verify { animatorProvider.latLngAnimator(any(), any(), 5) }
verify { animatorProvider.floatAnimator(any(), any(), 5) }
}
@Test
fun remove_gps_animator() {
val animator = mockk<MapLibreFloatAnimator>(relaxed = true)
locationAnimatorCoordinator.animatorArray.put(ANIMATOR_LAYER_GPS_BEARING, animator)
locationAnimatorCoordinator.cancelAndRemoveGpsBearingAnimation()
assertTrue(locationAnimatorCoordinator.animatorArray.get(ANIMATOR_LAYER_GPS_BEARING) == null)
}
private fun getListenerHoldersSet(vararg animatorTypes: Int): Set<AnimatorListenerHolder> {
return HashSet<AnimatorListenerHolder>().also {
for (type in animatorTypes) {
it.add(AnimatorListenerHolder(type, mockk(relaxUnitFun = true)))
}
}
}
}
private fun <E> SparseArray<E>.contains(listener: AnimationsValueChangeListener<*>?): Boolean {
for (i in 0 until this.size()) {
val element = this.get(this.keyAt(i))
if (element == listener) {
return true
}
}
return false
}

View File

@@ -0,0 +1,158 @@
package org.maplibre.android.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 org.maplibre.android.R
import org.maplibre.android.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()
}
}

View File

@@ -0,0 +1,98 @@
package org.maplibre.android.location
import android.content.Context
import android.content.res.Resources
import android.content.res.TypedArray
import org.maplibre.android.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()
}
}

View File

@@ -0,0 +1,130 @@
package org.maplibre.android.location
import org.maplibre.android.maps.Style
import org.maplibre.android.style.layers.Layer
import io.mockk.mockk
import io.mockk.verify
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.junit.MockitoJUnitRunner
@RunWith(MockitoJUnitRunner::class)
class LocationComponentPositionManagerTest {
private lateinit var style: Style
private lateinit var layer: Layer
@Before
fun setup() {
style = mockk(relaxed = true)
layer = mockk(relaxed = true)
}
@Test
fun update_noChange_null() {
val positionManager = LocationComponentPositionManager(style, null, null)
val requiresUpdate = positionManager.update(null, null)
assertFalse(requiresUpdate)
}
@Test
fun update_noChange_above() {
val positionManager = LocationComponentPositionManager(style, "above", null)
val requiresUpdate = positionManager.update("above", null)
assertFalse(requiresUpdate)
}
@Test
fun update_noChange_below() {
val positionManager = LocationComponentPositionManager(style, null, "below")
val requiresUpdate = positionManager.update(null, "below")
assertFalse(requiresUpdate)
}
@Test
fun update_fromNull_above() {
val positionManager = LocationComponentPositionManager(style, null, null)
val requiresUpdate = positionManager.update("above", null)
assertTrue(requiresUpdate)
}
@Test
fun update_fromNull_below() {
val positionManager = LocationComponentPositionManager(style, null, null)
val requiresUpdate = positionManager.update(null, "below")
assertTrue(requiresUpdate)
}
@Test
fun update_toNull_above() {
val positionManager = LocationComponentPositionManager(style, "above", null)
val requiresUpdate = positionManager.update(null, null)
assertTrue(requiresUpdate)
}
@Test
fun update_toNull_below() {
val positionManager = LocationComponentPositionManager(style, null, "below")
val requiresUpdate = positionManager.update(null, null)
assertTrue(requiresUpdate)
}
@Test
fun update_fromValue_above() {
val positionManager = LocationComponentPositionManager(style, "above1", null)
val requiresUpdate = positionManager.update("above2", null)
assertTrue(requiresUpdate)
}
@Test
fun update_fromValue_below() {
val positionManager = LocationComponentPositionManager(style, null, "below1")
val requiresUpdate = positionManager.update(null, "below2")
assertTrue(requiresUpdate)
}
@Test
fun addLayer_noModifier() {
val positionManager = LocationComponentPositionManager(style, null, null)
positionManager.addLayerToMap(layer)
verify { style.addLayer(layer) }
}
@Test
fun addLayer_above() {
val positionManager = LocationComponentPositionManager(style, "above", null)
positionManager.addLayerToMap(layer)
verify { style.addLayerAbove(layer, "above") }
}
@Test
fun addLayer_below() {
val positionManager = LocationComponentPositionManager(style, null, "below")
positionManager.addLayerToMap(layer)
verify { style.addLayerBelow(layer, "below") }
}
@Test
fun addLayer_afterUpdate_above() {
val positionManager = LocationComponentPositionManager(style, null, null)
positionManager.update("above", null)
positionManager.addLayerToMap(layer)
verify { style.addLayerAbove(layer, "above") }
}
@Test
fun addLayer_afterUpdate_below() {
val positionManager = LocationComponentPositionManager(style, null, null)
positionManager.update(null, "below")
positionManager.addLayerToMap(layer)
verify { style.addLayerBelow(layer, "below") }
}
}

View File

@@ -0,0 +1,642 @@
package org.maplibre.android.location
import android.content.Context
import android.location.Location
import android.os.Looper
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.location.LocationComponentConstants.TRANSITION_ANIMATION_DURATION_MS
import org.maplibre.android.location.engine.LocationEngine
import org.maplibre.android.location.engine.LocationEngineRequest
import org.maplibre.android.location.modes.CameraMode
import org.maplibre.android.location.modes.RenderMode
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.Projection
import org.maplibre.android.maps.Style
import org.maplibre.android.maps.Transform
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentCaptor
import org.mockito.Mock
import org.mockito.Mockito.*
import org.mockito.MockitoAnnotations
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class LocationComponentTest {
private lateinit var locationComponent: LocationComponent
@Mock
private lateinit var locationComponentOptions: LocationComponentOptions
@Mock
private lateinit var maplibreMap: MapLibreMap
@Mock
private lateinit var transform: Transform
@Mock
private lateinit var context: Context
@Mock
private lateinit var locationEngine: LocationEngine
@Mock
private lateinit var locationEngineRequest: LocationEngineRequest
@Mock
private lateinit var currentListener: LocationComponent.CurrentLocationEngineCallback
@Mock
private lateinit var lastListener: LocationComponent.LastLocationEngineCallback
@Mock
private lateinit var compassEngine: CompassEngine
@Mock
private lateinit var locationLayerController: LocationLayerController
@Mock
private lateinit var locationCameraController: LocationCameraController
@Mock
private lateinit var locationAnimatorCoordinator: LocationAnimatorCoordinator
@Mock
private lateinit var staleStateManager: StaleStateManager
@Mock
private lateinit var style: Style
private lateinit var developerAnimationListeners: List<MapLibreMap.OnDeveloperAnimationListener>
private val defaultOptions: LocationComponentActivationOptions
get() = LocationComponentActivationOptions.builder(context, style).locationEngine(locationEngine).locationEngineRequest(locationEngineRequest).locationComponentOptions(locationComponentOptions).build()
@Before
fun before() {
MockitoAnnotations.initMocks(this)
developerAnimationListeners = mutableListOf()
locationComponent = LocationComponent(maplibreMap, transform, developerAnimationListeners, currentListener, lastListener, locationLayerController, locationCameraController, locationAnimatorCoordinator, staleStateManager, compassEngine, false)
doReturn(style).`when`(maplibreMap).style
`when`(style.isFullyLoaded).thenReturn(true)
}
@Test
fun activateWithDefaultLocationEngineRequestAndOptionsTestDefaultLocationEngine() {
val options = LocationComponentActivationOptions.builder(context, style).locationEngine(locationEngine).locationEngineRequest(locationEngineRequest).locationComponentOptions(locationComponentOptions).build()
locationComponent.activateLocationComponent(options)
Assert.assertEquals(locationEngineRequest, locationComponent.locationEngineRequest)
Assert.assertNotNull(locationComponent.locationEngine)
}
@Test
fun activateWithDefaultLocationEngineRequestAndOptionsTestCustomLocationEngine() {
val options = LocationComponentActivationOptions.builder(context, style).useDefaultLocationEngine(false).locationEngineRequest(locationEngineRequest).locationComponentOptions(locationComponentOptions).build()
locationComponent.activateLocationComponent(options)
Assert.assertEquals(locationEngineRequest, locationComponent.locationEngineRequest)
Assert.assertNull(locationComponent.locationEngine)
}
@Test
fun locationUpdatesWhenEnabledDisableTest() {
locationComponent.activateLocationComponent(defaultOptions)
verify(locationEngine, times(0)).removeLocationUpdates(currentListener)
verify(locationEngine, times(0)).requestLocationUpdates(eq(locationEngineRequest), eq(currentListener), any(Looper::class.java))
locationComponent.onStart()
verify(locationEngine, times(0)).removeLocationUpdates(currentListener)
verify(locationEngine, times(0)).requestLocationUpdates(eq(locationEngineRequest), eq(currentListener), any(Looper::class.java))
locationComponent.isLocationComponentEnabled = true
verify(locationEngine).requestLocationUpdates(eq(locationEngineRequest), eq(currentListener), any(Looper::class.java))
locationComponent.isLocationComponentEnabled = false
verify(locationEngine).requestLocationUpdates(eq(locationEngineRequest), eq(currentListener), any(Looper::class.java))
verify(locationEngine).removeLocationUpdates(currentListener)
}
@Test
fun locationUpdatesWhenStartedStoppedTest() {
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.onStart()
locationComponent.isLocationComponentEnabled = true
locationComponent.onStop()
verify(locationEngine).removeLocationUpdates(currentListener)
locationComponent.onStart()
verify(locationEngine, times(2)).requestLocationUpdates(eq(locationEngineRequest), eq(currentListener), any(Looper::class.java))
}
@Test
fun locationUpdatesWhenNewRequestTest() {
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.onStart()
locationComponent.isLocationComponentEnabled = true
val newRequest = mock(LocationEngineRequest::class.java)
locationComponent.locationEngineRequest = newRequest
verify(locationEngine).removeLocationUpdates(currentListener)
verify(locationEngine).requestLocationUpdates(eq(newRequest), eq(currentListener), any(Looper::class.java))
}
@Test
fun lastLocationUpdateOnStartTest() {
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.onStart()
locationComponent.isLocationComponentEnabled = true
verify(locationEngine).getLastLocation(lastListener)
}
@Test
fun transitionCallbackFinishedTest() {
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.onStart()
locationComponent.isLocationComponentEnabled = true
`when`(maplibreMap.cameraPosition).thenReturn(CameraPosition.DEFAULT)
val listener = mock(OnLocationCameraTransitionListener::class.java)
val callback = ArgumentCaptor.forClass(OnLocationCameraTransitionListener::class.java)
locationComponent.setCameraMode(CameraMode.TRACKING, listener)
verify(locationCameraController).setCameraMode(eq(CameraMode.TRACKING), any(), eq(TRANSITION_ANIMATION_DURATION_MS), isNull(), isNull(), isNull(), callback.capture())
callback.value.onLocationCameraTransitionFinished(CameraMode.TRACKING)
verify(listener).onLocationCameraTransitionFinished(CameraMode.TRACKING)
verify(locationAnimatorCoordinator).resetAllCameraAnimations(CameraPosition.DEFAULT, false)
}
@Test
fun transitionCallbackCanceledTest() {
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.onStart()
locationComponent.isLocationComponentEnabled = true
`when`(maplibreMap.cameraPosition).thenReturn(CameraPosition.DEFAULT)
val listener = mock(OnLocationCameraTransitionListener::class.java)
val callback = ArgumentCaptor.forClass(OnLocationCameraTransitionListener::class.java)
locationComponent.setCameraMode(CameraMode.TRACKING, listener)
verify(locationCameraController).setCameraMode(eq(CameraMode.TRACKING), any(), eq(TRANSITION_ANIMATION_DURATION_MS), isNull(), isNull(), isNull(), callback.capture())
callback.value.onLocationCameraTransitionCanceled(CameraMode.TRACKING)
verify(listener).onLocationCameraTransitionCanceled(CameraMode.TRACKING)
verify(locationAnimatorCoordinator).resetAllCameraAnimations(CameraPosition.DEFAULT, false)
}
@Test
fun transitionCustomFinishedTest() {
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.onStart()
locationComponent.isLocationComponentEnabled = true
`when`(maplibreMap.cameraPosition).thenReturn(CameraPosition.DEFAULT)
val listener = mock(OnLocationCameraTransitionListener::class.java)
val callback = ArgumentCaptor.forClass(OnLocationCameraTransitionListener::class.java)
locationComponent.setCameraMode(CameraMode.TRACKING, 1200, 14.0, 13.0, 45.0, listener)
verify(locationCameraController).setCameraMode(eq(CameraMode.TRACKING), any(), eq(1200L), eq(14.0), eq(13.0), eq(45.0), callback.capture())
callback.value.onLocationCameraTransitionFinished(CameraMode.TRACKING)
verify(listener).onLocationCameraTransitionFinished(CameraMode.TRACKING)
verify(locationAnimatorCoordinator).resetAllCameraAnimations(CameraPosition.DEFAULT, false)
}
@Test
fun compass_listenWhenConsumedByNoneCamera() {
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.onStart()
locationComponent.isLocationComponentEnabled = true
`when`(maplibreMap.cameraPosition).thenReturn(CameraPosition.DEFAULT)
`when`(locationCameraController.isConsumingCompass).thenReturn(true)
locationComponent.cameraMode = CameraMode.NONE_COMPASS
verify(compassEngine).addCompassListener(any(CompassListener::class.java))
}
@Test
fun compass_listenWhenConsumedByTrackingCamera() {
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.onStart()
locationComponent.isLocationComponentEnabled = true
`when`(maplibreMap.cameraPosition).thenReturn(CameraPosition.DEFAULT)
`when`(locationCameraController.isConsumingCompass).thenReturn(true)
locationComponent.cameraMode = CameraMode.TRACKING_COMPASS
verify(compassEngine).addCompassListener(any(CompassListener::class.java))
}
@Test
fun compass_listenWhenConsumedByLayer() {
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.onStart()
locationComponent.isLocationComponentEnabled = true
`when`(maplibreMap.cameraPosition).thenReturn(CameraPosition.DEFAULT)
`when`(locationLayerController.isConsumingCompass).thenReturn(true)
locationComponent.renderMode = RenderMode.COMPASS
verify(compassEngine).addCompassListener(any(CompassListener::class.java))
}
@Test
fun compass_notListenWhenNotConsumed() {
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.onStart()
locationComponent.isLocationComponentEnabled = true
`when`(maplibreMap.cameraPosition).thenReturn(CameraPosition.DEFAULT)
`when`(locationLayerController.isConsumingCompass).thenReturn(false)
`when`(locationCameraController.isConsumingCompass).thenReturn(false)
locationComponent.renderMode = RenderMode.GPS
locationComponent.renderMode = RenderMode.NORMAL
locationComponent.cameraMode = CameraMode.TRACKING
locationComponent.cameraMode = CameraMode.NONE
locationComponent.cameraMode = CameraMode.NONE_GPS
locationComponent.cameraMode = CameraMode.TRACKING_GPS
locationComponent.cameraMode = CameraMode.TRACKING_GPS_NORTH
verify(compassEngine, never()).addCompassListener(any(CompassListener::class.java))
}
@Test
fun compass_removeListenerOnChange() {
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.onStart()
locationComponent.isLocationComponentEnabled = true
`when`(maplibreMap.cameraPosition).thenReturn(CameraPosition.DEFAULT)
`when`(locationLayerController.isConsumingCompass).thenReturn(true)
locationComponent.renderMode = RenderMode.COMPASS
`when`(locationLayerController.isConsumingCompass).thenReturn(false)
locationComponent.renderMode = RenderMode.NORMAL
verify(compassEngine).removeCompassListener(any(CompassListener::class.java))
}
@Test
fun compass_removeListenerOnStop() {
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.onStart()
locationComponent.isLocationComponentEnabled = true
`when`(maplibreMap.cameraPosition).thenReturn(CameraPosition.DEFAULT)
`when`(locationLayerController.isConsumingCompass).thenReturn(true)
locationComponent.renderMode = RenderMode.COMPASS
locationComponent.onStop()
verify(compassEngine).removeCompassListener(any(CompassListener::class.java))
}
@Test
fun compass_reAddListenerOnStart() {
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.onStart()
locationComponent.isLocationComponentEnabled = true
`when`(maplibreMap.cameraPosition).thenReturn(CameraPosition.DEFAULT)
`when`(locationLayerController.isConsumingCompass).thenReturn(true)
locationComponent.renderMode = RenderMode.COMPASS
locationComponent.onStop()
locationComponent.onStart()
verify(compassEngine, times(2)).addCompassListener(any(CompassListener::class.java))
}
@Test
fun compass_removeListenerOnStyleStartLoad() {
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.onStart()
locationComponent.isLocationComponentEnabled = true
`when`(maplibreMap.cameraPosition).thenReturn(CameraPosition.DEFAULT)
`when`(locationLayerController.isConsumingCompass).thenReturn(true)
locationComponent.renderMode = RenderMode.COMPASS
locationComponent.onStartLoadingMap()
verify(compassEngine).removeCompassListener(any(CompassListener::class.java))
}
@Test
fun compass_reAddListenerOnStyleLoadFinished() {
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.onStart()
locationComponent.isLocationComponentEnabled = true
`when`(maplibreMap.cameraPosition).thenReturn(CameraPosition.DEFAULT)
`when`(locationLayerController.isConsumingCompass).thenReturn(true)
locationComponent.renderMode = RenderMode.COMPASS
locationComponent.onStartLoadingMap()
locationComponent.onFinishLoadingStyle()
verify(compassEngine, times(2)).addCompassListener(any(CompassListener::class.java))
}
@Test
fun compass_reAddListenerOnlyWhenEnabled() {
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.onStart()
locationComponent.isLocationComponentEnabled = true
`when`(maplibreMap.cameraPosition).thenReturn(CameraPosition.DEFAULT)
`when`(locationLayerController.isConsumingCompass).thenReturn(true)
locationComponent.renderMode = RenderMode.COMPASS
locationComponent.isLocationComponentEnabled = false
locationComponent.onStartLoadingMap()
locationComponent.onFinishLoadingStyle()
verify(compassEngine).addCompassListener(any(CompassListener::class.java))
}
@Test
fun compass_notAdListenerWhenDisabled() {
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.onStart()
`when`(maplibreMap.cameraPosition).thenReturn(CameraPosition.DEFAULT)
`when`(locationLayerController.isConsumingCompass).thenReturn(true)
locationComponent.renderMode = RenderMode.COMPASS
verify(compassEngine, never()).addCompassListener(any(CompassListener::class.java))
}
@Test
fun compass_notAdListenerWhenStopped() {
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.isLocationComponentEnabled = true
`when`(maplibreMap.cameraPosition).thenReturn(CameraPosition.DEFAULT)
`when`(locationLayerController.isConsumingCompass).thenReturn(true)
locationComponent.renderMode = RenderMode.COMPASS
verify(compassEngine, never()).addCompassListener(any(CompassListener::class.java))
}
@Test
fun compass_notAddListenerWhenLayerNotReady() {
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.onStart()
locationComponent.isLocationComponentEnabled = true
`when`(maplibreMap.cameraPosition).thenReturn(CameraPosition.DEFAULT)
`when`(locationLayerController.isConsumingCompass).thenReturn(true)
locationComponent.renderMode = RenderMode.COMPASS
verify(compassEngine, times(1)).addCompassListener(any(CompassListener::class.java))
locationComponent.onStartLoadingMap()
// Layer should be disabled at this point
locationComponent.setCameraMode(CameraMode.TRACKING_COMPASS)
verify(compassEngine, times(1)).addCompassListener(any(CompassListener::class.java))
}
@Test
fun developerAnimationCalled() {
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.isLocationComponentEnabled = true
for (listener in developerAnimationListeners) {
listener.onDeveloperAnimationStarted()
}
verify(locationCameraController).setCameraMode(eq(CameraMode.NONE), isNull<Location>(), eq(TRANSITION_ANIMATION_DURATION_MS), isNull<Double>(), isNull<Double>(), isNull<Double>(), any())
}
@Test
fun internal_cameraTrackingChangedListener_onCameraTrackingDismissed() {
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.isLocationComponentEnabled = true
val cameraChangeListener: OnCameraTrackingChangedListener = mock(OnCameraTrackingChangedListener::class.java)
locationComponent.addOnCameraTrackingChangedListener(cameraChangeListener)
locationComponent.cameraTrackingChangedListener.onCameraTrackingDismissed()
verify(cameraChangeListener).onCameraTrackingDismissed()
}
@Test
fun internal_cameraTrackingChangedListener_onCameraTrackingChanged() {
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.isLocationComponentEnabled = true
val cameraValueListener: AnimatorListenerHolder = mock(AnimatorListenerHolder::class.java)
val layerValueListener: AnimatorListenerHolder = mock(AnimatorListenerHolder::class.java)
`when`(locationCameraController.animationListeners).thenReturn(setOf(cameraValueListener))
`when`(locationLayerController.animationListeners).thenReturn(setOf(layerValueListener))
val cameraChangeListener: OnCameraTrackingChangedListener = mock(OnCameraTrackingChangedListener::class.java)
locationComponent.addOnCameraTrackingChangedListener(cameraChangeListener)
locationComponent.cameraTrackingChangedListener.onCameraTrackingChanged(CameraMode.TRACKING_GPS)
verify(locationAnimatorCoordinator).cancelZoomAnimation()
verify(locationAnimatorCoordinator).cancelTiltAnimation()
verify(locationAnimatorCoordinator).updateAnimatorListenerHolders(eq(setOf(cameraValueListener, layerValueListener)))
verify(locationAnimatorCoordinator).resetAllCameraAnimations(any(), anyBoolean())
verify(locationAnimatorCoordinator).resetAllLayerAnimations()
verify(cameraChangeListener).onCameraTrackingChanged(CameraMode.TRACKING_GPS)
}
@Test
fun internal_renderModeChangedListener_onRenderModeChanged() {
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.isLocationComponentEnabled = true
val cameraListener: AnimatorListenerHolder = mock(AnimatorListenerHolder::class.java)
val layerListener: AnimatorListenerHolder = mock(AnimatorListenerHolder::class.java)
`when`(locationCameraController.animationListeners).thenReturn(setOf(cameraListener))
`when`(locationLayerController.animationListeners).thenReturn(setOf(layerListener))
val renderChangeListener: OnRenderModeChangedListener = mock(OnRenderModeChangedListener::class.java)
locationComponent.addOnRenderModeChangedListener(renderChangeListener)
locationComponent.renderModeChangedListener.onRenderModeChanged(RenderMode.NORMAL)
verify(locationAnimatorCoordinator).updateAnimatorListenerHolders(eq(setOf(cameraListener, layerListener)))
verify(locationAnimatorCoordinator).resetAllCameraAnimations(any(), anyBoolean())
verify(locationAnimatorCoordinator).resetAllLayerAnimations()
verify(renderChangeListener).onRenderModeChanged(RenderMode.NORMAL)
}
@Test
fun change_to_gps_mode_symbolLayerBearingValue() {
val location = Location("test")
location.bearing = 50f
val projection: Projection = mock(Projection::class.java)
`when`(projection.getMetersPerPixelAtLatitude(location.latitude)).thenReturn(10.0)
`when`(maplibreMap.projection).thenReturn(projection)
`when`(maplibreMap.cameraPosition).thenReturn(CameraPosition.DEFAULT)
locationComponent.activateLocationComponent(
LocationComponentActivationOptions.builder(context, style)
.locationComponentOptions(locationComponentOptions)
.useDefaultLocationEngine(false)
.build()
)
locationComponent.isLocationComponentEnabled = true
locationComponent.onStart()
locationComponent.renderMode = RenderMode.NORMAL
locationComponent.forceLocationUpdate(location)
verify(locationLayerController, times(0)).setGpsBearing(50f)
locationComponent.renderMode = RenderMode.GPS
verify(locationLayerController, times(1)).setGpsBearing(50f)
verify(locationAnimatorCoordinator).cancelAndRemoveGpsBearingAnimation()
}
@Test
fun tiltWhileTracking_notReady() {
`when`(maplibreMap.cameraPosition).thenReturn(CameraPosition.DEFAULT)
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.isLocationComponentEnabled = true
val callback = mock(MapLibreMap.CancelableCallback::class.java)
locationComponent.tiltWhileTracking(30.0, 500L, callback)
verify(callback).onCancel()
verify(locationAnimatorCoordinator, times(0)).feedNewTilt(anyDouble(), any(), anyLong(), any())
}
@Test
fun tiltWhileTracking_notTracking() {
`when`(maplibreMap.cameraPosition).thenReturn(CameraPosition.DEFAULT)
`when`(locationCameraController.cameraMode).thenReturn(CameraMode.NONE)
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.isLocationComponentEnabled = true
locationComponent.onStart()
val callback = mock(MapLibreMap.CancelableCallback::class.java)
locationComponent.tiltWhileTracking(30.0, 500L, callback)
verify(callback).onCancel()
verify(locationAnimatorCoordinator, times(0)).feedNewTilt(anyDouble(), any(), anyLong(), any())
}
@Test
fun tiltWhileTracking_transitioning() {
`when`(maplibreMap.cameraPosition).thenReturn(CameraPosition.DEFAULT)
`when`(locationCameraController.cameraMode).thenReturn(CameraMode.TRACKING)
`when`(locationCameraController.isTransitioning).thenReturn(true)
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.isLocationComponentEnabled = true
locationComponent.onStart()
val callback = mock(MapLibreMap.CancelableCallback::class.java)
locationComponent.tiltWhileTracking(30.0, 500L, callback)
verify(callback).onCancel()
verify(locationAnimatorCoordinator, times(0)).feedNewTilt(anyDouble(), any(), anyLong(), any())
}
@Test
fun tiltWhileTracking_sucessful() {
`when`(maplibreMap.cameraPosition).thenReturn(CameraPosition.DEFAULT)
`when`(locationCameraController.cameraMode).thenReturn(CameraMode.TRACKING)
`when`(locationCameraController.isTransitioning).thenReturn(false)
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.isLocationComponentEnabled = true
locationComponent.onStart()
val callback = mock(MapLibreMap.CancelableCallback::class.java)
locationComponent.tiltWhileTracking(30.0, 500L, callback)
verify(callback, times(0)).onCancel()
verify(locationAnimatorCoordinator).feedNewTilt(30.0, CameraPosition.DEFAULT, 500L, callback)
}
@Test
fun zoomWhileTracking_notReady() {
`when`(maplibreMap.cameraPosition).thenReturn(CameraPosition.DEFAULT)
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.isLocationComponentEnabled = true
val callback = mock(MapLibreMap.CancelableCallback::class.java)
locationComponent.zoomWhileTracking(14.0, 500L, callback)
verify(callback).onCancel()
verify(locationAnimatorCoordinator, times(0)).feedNewZoomLevel(anyDouble(), any(), anyLong(), any())
}
@Test
fun zoomWhileTracking_notTracking() {
`when`(maplibreMap.cameraPosition).thenReturn(CameraPosition.DEFAULT)
`when`(locationCameraController.cameraMode).thenReturn(CameraMode.NONE)
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.isLocationComponentEnabled = true
locationComponent.onStart()
val callback = mock(MapLibreMap.CancelableCallback::class.java)
locationComponent.zoomWhileTracking(14.0, 500L, callback)
verify(callback).onCancel()
verify(locationAnimatorCoordinator, times(0)).feedNewZoomLevel(anyDouble(), any(), anyLong(), any())
}
@Test
fun zoomWhileTracking_transitioning() {
`when`(maplibreMap.cameraPosition).thenReturn(CameraPosition.DEFAULT)
`when`(locationCameraController.cameraMode).thenReturn(CameraMode.TRACKING)
`when`(locationCameraController.isTransitioning).thenReturn(true)
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.isLocationComponentEnabled = true
locationComponent.onStart()
val callback = mock(MapLibreMap.CancelableCallback::class.java)
locationComponent.zoomWhileTracking(14.0, 500L, callback)
verify(callback).onCancel()
verify(locationAnimatorCoordinator, times(0)).feedNewZoomLevel(anyDouble(), any(), anyLong(), any())
}
@Test
fun zoomWhileTracking_successful() {
`when`(maplibreMap.cameraPosition).thenReturn(CameraPosition.DEFAULT)
`when`(locationCameraController.cameraMode).thenReturn(CameraMode.TRACKING)
`when`(locationCameraController.isTransitioning).thenReturn(false)
locationComponent.activateLocationComponent(defaultOptions)
locationComponent.isLocationComponentEnabled = true
locationComponent.onStart()
val callback = mock(MapLibreMap.CancelableCallback::class.java)
locationComponent.zoomWhileTracking(14.0, 500L, callback)
verify(callback, times(0)).onCancel()
verify(locationAnimatorCoordinator).feedNewZoomLevel(14.0, CameraPosition.DEFAULT, 500L, callback)
}
@Test
fun newLocation_accuracy_symbolLayerRadiusValue() {
val location = Location("test")
location.accuracy = 50f
val projection: Projection = mock(Projection::class.java)
`when`(projection.getMetersPerPixelAtLatitude(location.latitude)).thenReturn(10.0)
`when`(maplibreMap.projection).thenReturn(projection)
locationComponent.activateLocationComponent(
LocationComponentActivationOptions.builder(context, style)
.locationComponentOptions(locationComponentOptions)
.useDefaultLocationEngine(false)
.build()
)
locationComponent.isLocationComponentEnabled = true
locationComponent.onStart()
locationComponent.forceLocationUpdate(location)
val radius = (location.accuracy * (1 / 10.0)).toFloat()
verify(locationAnimatorCoordinator).feedNewAccuracyRadius(radius, false)
}
@Test
fun newLocation_accuracy_indicatorLayerRadiusValue() {
val location = Location("test")
location.accuracy = 50f
locationComponent = LocationComponent(maplibreMap, transform, developerAnimationListeners, currentListener, lastListener, locationLayerController, locationCameraController, locationAnimatorCoordinator, staleStateManager, compassEngine, true)
locationComponent.activateLocationComponent(
LocationComponentActivationOptions.builder(context, style)
.locationComponentOptions(locationComponentOptions)
.useSpecializedLocationLayer(true)
.useDefaultLocationEngine(false)
.build()
)
locationComponent.isLocationComponentEnabled = true
locationComponent.onStart()
locationComponent.forceLocationUpdate(location)
verify(locationAnimatorCoordinator).feedNewAccuracyRadius(location.accuracy, false)
}
}

View File

@@ -0,0 +1,53 @@
package org.maplibre.android.location
import android.animation.ValueAnimator
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class MapLibreAnimatorTest {
@Test
fun fps_unlimited() {
val valueAnimator = mockk<ValueAnimator>()
every { valueAnimator.animatedValue } answers { 5f }
val listener = mockk<MapLibreAnimator.AnimationsValueChangeListener<Float>>()
every { listener.onNewAnimationValue(any()) } answers {}
val mapboxAnimator = MapLibreFloatAnimator(
floatArrayOf(
0f,
10f
).toTypedArray(), listener, Int.MAX_VALUE
)
for (i in 0 until 5)
mapboxAnimator.onAnimationUpdate(valueAnimator)
verify(exactly = 5) { listener.onNewAnimationValue(5f) }
}
@Test
fun fps_limited() {
val valueAnimator = mockk<ValueAnimator>()
every { valueAnimator.animatedValue } answers { 5f }
val listener = mockk<MapLibreAnimator.AnimationsValueChangeListener<Float>>()
every { listener.onNewAnimationValue(any()) } answers {}
val mapboxAnimator = MapLibreFloatAnimator(
floatArrayOf(
0f,
10f
).toTypedArray(), listener, 5
)
for (i in 0 until 5) {
mapboxAnimator.onAnimationUpdate(valueAnimator)
Thread.sleep(150)
}
verify(exactly = 3) { listener.onNewAnimationValue(5f) }
}
}

View File

@@ -0,0 +1,28 @@
package org.maplibre.android.location
import org.junit.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)
}
}

View File

@@ -0,0 +1,170 @@
package org.maplibre.android.location.engine
import android.app.PendingIntent
import android.content.Context
import android.location.Criteria
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Looper
import junit.framework.TestCase
import org.assertj.core.api.Assertions.*
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentCaptor
import org.mockito.ArgumentMatchers
import org.mockito.Mock
import org.mockito.Mockito.*
import org.mockito.junit.MockitoJUnitRunner
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
@RunWith(MockitoJUnitRunner::class)
class AndroidLocationEngineImplTest {
@Mock
private val locationManagerMock: LocationManager? = null
private var engine: LocationEngine? = null
private var androidLocationEngineImpl: AndroidLocationEngineImpl? = null
@Before
fun setUp() {
val context = mock(Context::class.java)
`when`(context.getSystemService(Context.LOCATION_SERVICE)).thenReturn(locationManagerMock)
androidLocationEngineImpl = AndroidLocationEngineImpl(context)
engine = LocationEngineProxy(androidLocationEngineImpl)
}
//@get:Throws(InterruptedException::class)
@Test
fun getLastLocation() {
val latch = CountDownLatch(1)
val resultRef = AtomicReference<LocationEngineResult>()
val callback = getCallback(resultRef, latch)
val location = getMockLocation(LATITUDE, LONGITUDE)
val expectedResult = getMockEngineResult(location)
`when`(locationManagerMock!!.getLastKnownLocation(anyString())).thenReturn(location)
engine!!.getLastLocation(callback)
TestCase.assertTrue(latch.await(5, TimeUnit.SECONDS))
val result = resultRef.get()
assertThat(result.lastLocation).isEqualTo(expectedResult.lastLocation)
}
@Test
fun createListener() {
val callback: LocationEngineCallback<LocationEngineResult> = mock(LocationEngineCallback::class.java) as LocationEngineCallback<LocationEngineResult>
val locationListener = androidLocationEngineImpl!!.createListener(callback)
val mockLocation = getMockLocation(LATITUDE, LONGITUDE)
locationListener.onLocationChanged(mockLocation)
val argument = ArgumentCaptor.forClass(LocationEngineResult::class.java)
verify(callback).onSuccess(argument.capture())
val result = argument.value
assertThat(result.lastLocation).isSameAs(mockLocation)
}
@Test
fun requestLocationUpdatesWithNoPower() {
val request = LocationEngineRequest.Builder(10)
.setPriority(LocationEngineRequest.PRIORITY_NO_POWER).build()
val callback: LocationEngineCallback<LocationEngineResult> = mock(LocationEngineCallback::class.java) as LocationEngineCallback<LocationEngineResult>
val looper = mock(Looper::class.java)
val criteria = mock(Criteria::class.java)
engine!!.requestLocationUpdates(request, callback, looper)
verify(locationManagerMock, never())?.getBestProvider(criteria, true)
}
@Test
fun requestLocationUpdatesBestProviderNull() {
val request = LocationEngineRequest.Builder(10)
.setPriority(LocationEngineRequest.PRIORITY_HIGH_ACCURACY).build()
val callback: LocationEngineCallback<LocationEngineResult> = mock(LocationEngineCallback::class.java) as LocationEngineCallback<LocationEngineResult>
val looper = mock(Looper::class.java)
`when`(locationManagerMock!!.getBestProvider(any(Criteria::class.java), anyBoolean())).thenReturn(null)
engine!!.requestLocationUpdates(request, callback, looper)
assertThat(androidLocationEngineImpl!!.currentProvider).isEqualTo("passive")
}
@Test
fun requestLocationUpdatesWithPendingIntent() {
val request = LocationEngineRequest.Builder(10)
.setPriority(LocationEngineRequest.PRIORITY_HIGH_ACCURACY).build()
val pendingIntent = mock(PendingIntent::class.java)
`when`(locationManagerMock!!.getBestProvider(any(Criteria::class.java), anyBoolean())).thenReturn(null)
engine!!.requestLocationUpdates(request, pendingIntent)
assertThat(androidLocationEngineImpl!!.currentProvider).isEqualTo("passive")
}
@Test
fun removeLocationUpdatesForInvalidListener() {
val callback: LocationEngineCallback<LocationEngineResult> = mock(LocationEngineCallback::class.java) as LocationEngineCallback<LocationEngineResult>
engine!!.removeLocationUpdates(callback)
verify(locationManagerMock, never())?.removeUpdates(ArgumentMatchers.any(LocationListener::class.java))
}
@Test
fun removeLocationUpdatesForPendingIntent() {
val pendingIntent = mock(PendingIntent::class.java)
engine!!.removeLocationUpdates(pendingIntent)
verify(locationManagerMock, times(1))?.removeUpdates(ArgumentMatchers.any(PendingIntent::class.java))
}
@Test
fun removeLocationUpdatesForValidListener() {
val callback: LocationEngineCallback<LocationEngineResult> = mock(LocationEngineCallback::class.java) as LocationEngineCallback<LocationEngineResult>
val request = LocationEngineRequest.Builder(10)
.setPriority(LocationEngineRequest.PRIORITY_HIGH_ACCURACY).build()
engine!!.requestLocationUpdates(request, callback, mock(Looper::class.java))
engine!!.removeLocationUpdates(callback)
verify(locationManagerMock, times(1))?.removeUpdates(ArgumentMatchers.any(LocationListener::class.java))
}
// J2K: removed "get". TODO: validate necessity of this test
@Test(expected = NullPointerException::class)
fun lastLocationNullCallback() {
engine!!.getLastLocation(null!!)
}
// J2K: add "!!". TODO: validate necessity of this test
@Test(expected = NullPointerException::class)
fun requestLocationUpdatesNullCallback() {
engine!!.requestLocationUpdates(null!!, null!!, null!!)
}
@After
fun tearDown() {
reset(locationManagerMock)
engine = null
}
companion object {
private const val LATITUDE = 37.7749
private const val LONGITUDE = 122.4194
private fun getCallback(
resultRef: AtomicReference<LocationEngineResult>,
latch: CountDownLatch): LocationEngineCallback<LocationEngineResult> {
// J2K: remove "?" from LocationEngineResult?
return object : LocationEngineCallback<LocationEngineResult> {
override fun onSuccess(result: LocationEngineResult) {
resultRef.set(result)
latch.countDown()
}
override fun onFailure(exception: Exception) {
exception.printStackTrace()
}
}
}
private fun getMockEngineResult(location: Location): LocationEngineResult {
return LocationEngineResult.create(location)
}
private fun getMockLocation(lat: Double, lon: Double): Location {
val location = mock(Location::class.java)
location.latitude = lat
location.longitude = lon
return location
}
}
}

View File

@@ -0,0 +1,88 @@
package org.maplibre.android.location.engine
import android.location.LocationListener
import org.assertj.core.api.Assertions.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.maplibre.android.location.engine.AndroidLocationEngineImpl.AndroidLocationEngineCallbackTransport
import org.mockito.Mock
import org.mockito.Mockito.*
import org.mockito.junit.MockitoJUnitRunner
@RunWith(MockitoJUnitRunner::class)
class LocationEngineProxyTest {
@Mock
private val callback: LocationEngineCallback<LocationEngineResult>? = null
@Mock
private val engineImpl: LocationEngineImpl<LocationListener>? = null
private var locationEngineProxy: LocationEngineProxy<LocationListener>? = null
@Before
fun setUp() {
locationEngineProxy = LocationEngineProxy(engineImpl)
}
@Test
fun testAddListener() {
val transport = AndroidLocationEngineCallbackTransport(callback)
`when`(engineImpl!!.createListener(callback)).thenReturn(transport)
val locationListener = locationEngineProxy!!.getListener(callback!!)
assertThat(locationListener).isSameAs(transport)
assertThat(locationEngineProxy!!.listenersCount).isEqualTo(1)
}
@Test
fun testAddListenerTwice() {
val transport = AndroidLocationEngineCallbackTransport(callback)
`when`(engineImpl!!.createListener(callback)).thenReturn(transport)
locationEngineProxy!!.getListener(callback!!)
locationEngineProxy!!.getListener(callback)
assertThat(locationEngineProxy!!.listenersCount).isEqualTo(1)
}
@Test
fun testAddTwoListeners() {
val transport = AndroidLocationEngineCallbackTransport(callback)
`when`(engineImpl!!.createListener(callback)).thenReturn(transport)
locationEngineProxy!!.getListener(callback!!)
// J2K: using IDE suggestion "as LocationEngineCallback<LocationEngineResult>"
val anotherCallback: LocationEngineCallback<LocationEngineResult> = mock(LocationEngineCallback::class.java) as LocationEngineCallback<LocationEngineResult>
val anotherTransport = AndroidLocationEngineCallbackTransport(anotherCallback)
`when`(engineImpl.createListener(anotherCallback)).thenReturn(anotherTransport)
locationEngineProxy!!.getListener(anotherCallback)
assertThat(locationEngineProxy!!.listenersCount).isEqualTo(2)
}
@Test
fun testRemoveListener() {
val transport = AndroidLocationEngineCallbackTransport(callback)
`when`(engineImpl!!.createListener(callback)).thenReturn(transport)
locationEngineProxy!!.getListener(callback!!)
locationEngineProxy!!.removeListener(callback)
assertThat(locationEngineProxy!!.listenersCount).isEqualTo(0)
}
@Test
fun testCheckRemovedListener() {
val transport = AndroidLocationEngineCallbackTransport(callback)
`when`(engineImpl!!.createListener(callback)).thenReturn(transport)
locationEngineProxy!!.getListener(callback!!)
// J2K: using IDE suggestion "as LocationEngineCallback<LocationEngineResult>"
val anotherCallback: LocationEngineCallback<LocationEngineResult> = mock(LocationEngineCallback::class.java) as LocationEngineCallback<LocationEngineResult>
val anotherTransport = AndroidLocationEngineCallbackTransport(anotherCallback)
`when`(engineImpl.createListener(anotherCallback)).thenReturn(anotherTransport)
locationEngineProxy!!.getListener(anotherCallback)
assertThat(locationEngineProxy!!.removeListener(callback)).isSameAs(transport)
assertThat(locationEngineProxy!!.removeListener(anotherCallback)).isSameAs(anotherTransport)
}
@Test
fun testRemoveListenerTwice() {
val transport = AndroidLocationEngineCallbackTransport(callback)
`when`(engineImpl!!.createListener(callback)).thenReturn(transport)
locationEngineProxy!!.getListener(callback!!)
assertThat(locationEngineProxy!!.removeListener(callback)).isSameAs(transport)
assertThat(locationEngineProxy!!.removeListener(callback)).isNull()
}
}

View File

@@ -0,0 +1,64 @@
package org.maplibre.android.location.engine
import org.assertj.core.api.Assertions.*
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.junit.MockitoJUnitRunner
@RunWith(MockitoJUnitRunner::class)
class LocationEngineRequestTest {
@Test
fun checkDefaultValues() {
val request = LocationEngineRequest.Builder(1000L).build()
assertThat(request.interval).isEqualTo(1000L)
assertThat(request.displacement).isEqualTo(0.0f)
assertThat(request.maxWaitTime).isEqualTo(0L)
assertThat(request.fastestInterval).isEqualTo(0L)
}
@Test
fun checkBuilder() {
val request = LocationEngineRequest.Builder(2000L)
.setDisplacement(100.0f)
.setMaxWaitTime(5000L)
.setFastestInterval(500L)
.build()
assertThat(request.interval).isEqualTo(2000L)
assertThat(request.displacement).isEqualTo(100.0f)
assertThat(request.maxWaitTime).isEqualTo(5000L)
assertThat(request.fastestInterval).isEqualTo(500L)
}
@Test
fun checkRequestEqual() {
val request = LocationEngineRequest.Builder(2000L).build()
val otherRequest = LocationEngineRequest.Builder(2000L).build()
assertThat(request).isEqualTo(otherRequest)
assertThat(request.hashCode()).isEqualTo(otherRequest.hashCode())
}
@Test
fun checkRequestsNotEqual() {
val request = LocationEngineRequest.Builder(2000L).build()
val otherRequest = LocationEngineRequest.Builder(2000L)
.setFastestInterval(500L)
.build()
assertThat(request).isNotEqualTo(otherRequest)
}
@Test
fun checkRequestsEqualHashCode() {
val request = LocationEngineRequest.Builder(2000L).build()
val otherRequest = LocationEngineRequest.Builder(2000L).build()
assertThat(request.hashCode()).isEqualTo(otherRequest.hashCode())
}
@Test
fun checkRequestsNonEqualHashCode() {
val request = LocationEngineRequest.Builder(2000L).build()
val otherRequest = LocationEngineRequest.Builder(2000L)
.setFastestInterval(500L)
.build()
assertThat(request.hashCode()).isNotEqualTo(otherRequest.hashCode())
}
}

View File

@@ -0,0 +1,127 @@
package org.maplibre.android.location.engine
import android.content.Intent
import android.location.Location
import android.location.LocationManager
import android.os.Bundle
import org.assertj.core.api.Assertions.*
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.*
import org.mockito.junit.MockitoJUnitRunner
import java.util.Collections
@RunWith(MockitoJUnitRunner::class)
class LocationEngineResultTest {
@Test
fun checkNullIntent() {
val result = LocationEngineResult.extractResult(null)
assertThat(result).isNull()
}
@Test
fun passInvalidIntent() {
val intent = mock(Intent::class.java)
val result = LocationEngineResult.extractResult(intent)
assertThat(result).isNull()
}
@Test
fun passValidIntent() {
val location = mock(Location::class.java)
val result = LocationEngineResult.extractResult(getValidIntent(location))
assertThat(result).isNotNull()
assertThat(result!!.lastLocation).isSameAs(location)
}
@Test
fun passNullLocation() {
val location: Location? = null
val result = LocationEngineResult.create(location)
assertForNullInput(result)
}
@Test
fun passNullLocationList() {
val locations: List<Location>? = null
val result = LocationEngineResult.create(locations)
assertForNullInput(result)
}
@Test
fun passValidLocation() {
val location = validLocation
val result = LocationEngineResult.create(location)
assertForValidInput(result)
}
@Test
fun passValidLocationList() {
val locations = listOf(validLocation)
val result = LocationEngineResult.create(locations)
assertForValidInput(result)
}
@Test
fun passMutableLocationListWithNulls() {
val locations = locationsWithNulls
val result = LocationEngineResult.create(locations)
assertForValidInput(result)
}
@Test
fun passImmutableLocationListWithNulls() {
val locations = Collections.unmodifiableList(locationsWithNulls)
val result = LocationEngineResult.create(locations)
assertForValidInput(result)
}
@Test
fun passImmutableListWithNullLocation() {
val locations = listOf<Location?>(null)
val result = LocationEngineResult.create(locations)
assertThat(result != null)
assertThat(result.locations.size == 0)
}
companion object {
private const val TEST_LAT_LNG = 1.0
// J2K: IDE suggestion to use ArrayList<Location?>
private val locationsWithNulls: ArrayList<Location?>
private get() = object : ArrayList<Location?>() {
init {
add(null)
add(validLocation)
add(null)
}
}
private val validLocation: Location
private get() {
val location = mock(Location::class.java)
`when`(location.latitude).thenReturn(TEST_LAT_LNG)
`when`(location.longitude).thenReturn(TEST_LAT_LNG)
return location
}
private fun assertForNullInput(result: LocationEngineResult) {
assertThat(result).isNotNull()
assertThat(result.locations).isEmpty()
}
private fun assertForValidInput(result: LocationEngineResult) {
assertThat(result.locations).isNotNull()
assertThat(result.locations.size).isEqualTo(1)
assertThat(result.locations[0].latitude).isEqualTo(TEST_LAT_LNG)
assertThat(result.locations[0].longitude).isEqualTo(TEST_LAT_LNG)
}
private fun getValidIntent(location: Location): Intent {
val intent = mock(Intent::class.java)
`when`(intent.hasExtra(LocationManager.KEY_LOCATION_CHANGED)).thenReturn(true)
val bundle = mock(Bundle::class.java)
`when`<Any?>(bundle.getParcelable(LocationManager.KEY_LOCATION_CHANGED)).thenReturn(location)
`when`(intent.extras).thenReturn(bundle)
return intent
}
}
}

View File

@@ -0,0 +1,127 @@
package org.maplibre.android.location.engine
import android.location.Location
import android.location.LocationListener
import android.os.Looper
import org.assertj.core.api.Assertions.*
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.maplibre.android.location.engine.AndroidLocationEngineImpl.AndroidLocationEngineCallbackTransport
import org.mockito.Mock
import org.mockito.Mockito.*
import org.mockito.junit.MockitoJUnitRunner
import org.mockito.stubbing.Stubber
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
@RunWith(MockitoJUnitRunner::class)
class LocationEngineTest {
@Mock
private val locationEngineImpl: LocationEngineImpl<LocationListener>? = null
private var engine: LocationEngine? = null
@Before
fun setUp() {
engine = LocationEngineProxy(locationEngineImpl)
}
//@get:Throws(InterruptedException::class)
@Test
fun getLastLocation ()
{
val latch = CountDownLatch(1)
val resultRef = AtomicReference<LocationEngineResult>()
val callback = getCallback(resultRef, latch)
val location = getMockLocation(LATITUDE, LONGITUDE)
val expectedResult = getMockEngineResult(location)
setupDoAnswer(expectedResult).`when`(locationEngineImpl)?.getLastLocation(callback)
engine!!.getLastLocation(callback)
assertTrue(latch.await(5, TimeUnit.SECONDS))
val result = resultRef.get()
assertThat(result).isSameAs(expectedResult)
assertThat(result.lastLocation).isEqualTo(expectedResult.lastLocation)
}
// J2K: // TODO: this becomes unreachable, validate necessity of test
@Test(expected = NullPointerException::class)
fun getLastLocationNullCallback () {
engine!!.getLastLocation(null!!)
}
@Test
@Throws(InterruptedException::class)
fun requestLocationUpdates() {
val latch = CountDownLatch(1)
val resultRef = AtomicReference<LocationEngineResult>()
val callback = getCallback(resultRef, latch)
val location = getMockLocation(LATITUDE, LONGITUDE)
val expectedResult = getMockEngineResult(location)
val looper = mock(Looper::class.java)
val transport = AndroidLocationEngineCallbackTransport(callback)
`when`(locationEngineImpl!!.createListener(callback)).thenReturn(transport)
engine!!.requestLocationUpdates(getRequest(INTERVAL), callback, looper)
transport.onLocationChanged(location)
assertTrue(latch.await(5, TimeUnit.SECONDS))
val result = resultRef.get()
assertThat(result.lastLocation).isEqualTo(expectedResult.lastLocation)
}
// J2K: // TODO: this becomes unreachable, validate necessity of test
@Test(expected = NullPointerException::class)
fun requestLocationUpdatesNullCallback() {
engine!!.requestLocationUpdates(null!!, null!!, null!!)
}
@After
fun tearDown() {
reset(locationEngineImpl)
engine = null
}
companion object {
private const val LATITUDE = 37.7749
private const val LONGITUDE = 122.4194
private const val INTERVAL = 1000L
private fun setupDoAnswer(expectedResult: LocationEngineResult): Stubber {
return doAnswer { invocation ->
val callback = invocation.getArgument<LocationEngineCallback<LocationEngineResult>>(0)
callback.onSuccess(expectedResult)
null
}
}
private fun getRequest(interval: Long): LocationEngineRequest {
return LocationEngineRequest.Builder(interval).build()
}
private fun getCallback(
resultRef: AtomicReference<LocationEngineResult>,
latch: CountDownLatch): LocationEngineCallback<LocationEngineResult> {
// J2K: remove ?
return object : LocationEngineCallback<LocationEngineResult> {
override fun onSuccess(result: LocationEngineResult) {
resultRef.set(result)
latch.countDown()
}
override fun onFailure(exception: Exception) {
exception.printStackTrace()
}
}
}
private fun getMockEngineResult(location: Location): LocationEngineResult {
return LocationEngineResult.create(location)
}
private fun getMockLocation(lat: Double, lon: Double): Location {
val location = mock(Location::class.java)
location.latitude = lat
location.longitude = lon
return location
}
}
}

View File

@@ -0,0 +1,118 @@
package org.maplibre.android.location.engine
import android.content.Context
import android.location.Criteria
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.location.LocationProvider
import android.os.Looper
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers
import org.mockito.Mockito.*
import org.mockito.junit.MockitoJUnitRunner
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
@RunWith(MockitoJUnitRunner::class)
class MapLibreFusedLocationEngineImplAdditionalTest2 {
private val engines = ArrayList<LocationEngineProxy<*>>()
private var mockLocationManager: LocationManager? = null
private var location = Location(PROVIDER)
@Before
fun setUp() {
location = mock(Location::class.java)
`when`(location.latitude).thenReturn(1.0)
`when`(location.longitude).thenReturn(2.0)
val mockContext = mock(Context::class.java)
mockLocationManager = mock(LocationManager::class.java)
`when`(mockContext.getSystemService(anyString())).thenReturn(mockLocationManager)
val providers: MutableList<String> = ArrayList()
providers.add(PROVIDER)
// J2K: add ?
`when`(mockLocationManager?.getAllProviders()).thenReturn(providers)
`when`(mockLocationManager?.getBestProvider(any(Criteria::class.java), anyBoolean()))
.thenReturn(LocationManager.GPS_PROVIDER)
doAnswer { invocation ->
val listener = invocation.arguments[3] as LocationListener
listener.onProviderEnabled(PROVIDER)
listener.onStatusChanged(PROVIDER, LocationProvider.AVAILABLE, null)
listener.onLocationChanged(location)
listener.onProviderDisabled(PROVIDER)
null
}.`when`(mockLocationManager)
// J2K: add ?
?.requestLocationUpdates(ArgumentMatchers.anyString(), ArgumentMatchers.anyLong(), ArgumentMatchers.anyFloat(), ArgumentMatchers.any(LocationListener::class.java), ArgumentMatchers.any(Looper::class.java))
engines.add(LocationEngineProxy(MapLibreFusedLocationEngineImpl(mockContext)))
engines.add(LocationEngineProxy(AndroidLocationEngineImpl(mockContext)))
}
@Test
@Throws(InterruptedException::class)
fun checkGetLastLocation() {
val latch = CountDownLatch(engines.size)
for (engineProxy in engines) {
// J2K: remove ? from LocationEngineResult
engineProxy.getLastLocation(object : LocationEngineCallback<LocationEngineResult> {
override fun onSuccess(result: LocationEngineResult) {}
override fun onFailure(exception: Exception) {
assertEquals("Last location unavailable", exception.localizedMessage)
latch.countDown()
}
})
}
assertTrue(latch.await(1, TimeUnit.SECONDS))
`when`(mockLocationManager!!.getLastKnownLocation(anyString())).thenReturn(location)
val latch1 = CountDownLatch(engines.size)
for (engineProxy in engines) {
// J2K: remove ? from LocationEngineResult
engineProxy.getLastLocation(object : LocationEngineCallback<LocationEngineResult> {
override fun onSuccess(result: LocationEngineResult) {
val list = result.locations
assertEquals(1, list.size.toLong())
assertEquals(1.0, list[0].latitude, 0.0)
assertEquals(2.0, list[0].longitude, 0.0)
latch1.countDown()
}
override fun onFailure(exception: Exception) {}
})
}
assertTrue(latch1.await(1, TimeUnit.SECONDS))
}
@Test
@Throws(InterruptedException::class)
fun checkRequestAndRemoveLocationUpdates() {
val latch = CountDownLatch(engines.size)
// J2K: remove ? from LocationEngineResult
val engineCallback: LocationEngineCallback<LocationEngineResult> = object : LocationEngineCallback<LocationEngineResult> {
override fun onSuccess(result: LocationEngineResult) {
val list = result.locations
assertEquals(1, list.size.toLong())
assertEquals(1.0, list[0].latitude, 0.0)
assertEquals(2.0, list[0].longitude, 0.0)
latch.countDown()
}
override fun onFailure(exception: Exception) {}
}
for (engineProxy in engines) {
engineProxy.requestLocationUpdates(getRequest(INTERVAL, LocationEngineRequest.PRIORITY_HIGH_ACCURACY),
engineCallback, mock(Looper::class.java))
assertTrue(latch.await(1, TimeUnit.SECONDS))
assertNotNull(engineProxy.removeListener(engineCallback))
}
}
companion object {
private const val INTERVAL = 1000L
private const val PROVIDER = "test_provider"
private fun getRequest(interval: Long, priority: Int): LocationEngineRequest {
return LocationEngineRequest.Builder(interval).setPriority(priority).build()
}
}
}

View File

@@ -0,0 +1,166 @@
package org.maplibre.android.location.engine
import android.app.PendingIntent
import android.content.Context
import android.location.Criteria
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Looper
import junit.framework.TestCase.*
import org.assertj.core.api.Assertions.*
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentCaptor
import org.mockito.ArgumentMatchers.*
import org.mockito.Mock
import org.mockito.Mockito.*
import org.mockito.junit.MockitoJUnitRunner
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
@RunWith(MockitoJUnitRunner::class)
class MapLibreFusedLocationEngineImplTest {
@Mock
private val locationManagerMock: LocationManager? = null
private var engine: LocationEngine? = null
private var maplibreFusedLocationEngineImpl: MapLibreFusedLocationEngineImpl? = null
@Before
fun setUp() {
val context = mock(Context::class.java)
`when`(context.getSystemService(Context.LOCATION_SERVICE)).thenReturn(locationManagerMock)
maplibreFusedLocationEngineImpl = MapLibreFusedLocationEngineImpl(context)
engine = LocationEngineProxy(maplibreFusedLocationEngineImpl)
}
// J2K: rewrite test to not use "@get"
@Test
fun getLastLocation() {
val latch = CountDownLatch(1)
val resultRef = AtomicReference<LocationEngineResult>()
val callback = getCallback(resultRef, latch)
val location = getMockLocation(LATITUDE, LONGITUDE)
val expectedResult = getMockEngineResult(location)
`when`(locationManagerMock!!.allProviders).thenReturn(mutableListOf("gps", "network"))
`when`(locationManagerMock.getLastKnownLocation(anyString())).thenReturn(location)
engine!!.getLastLocation(callback)
assertTrue(latch.await(5, TimeUnit.SECONDS))
val result = resultRef.get()
assertThat(result.lastLocation).isEqualTo(expectedResult.lastLocation)
}
@Test
fun createListener() {
// J2K: IDE suggestion "as LocationEngineCallback<LocationEngineResult>"
val callback: LocationEngineCallback<LocationEngineResult> = mock(LocationEngineCallback::class.java) as LocationEngineCallback<LocationEngineResult>
val locationListener = maplibreFusedLocationEngineImpl!!.createListener(callback)
val mockLocation = getMockLocation(LATITUDE, LONGITUDE)
locationListener.onLocationChanged(mockLocation)
val argument = ArgumentCaptor.forClass(LocationEngineResult::class.java)
verify(callback).onSuccess(argument.capture())
val result = argument.value
assertThat(result.lastLocation).isSameAs(mockLocation)
}
@Test
fun requestLocationUpdatesOutdoors() {
val request = LocationEngineRequest.Builder(10)
.setPriority(LocationEngineRequest.PRIORITY_HIGH_ACCURACY).build()
// J2K: IDE suggestion "as LocationEngineCallback<LocationEngineResult>"
val callback: LocationEngineCallback<LocationEngineResult> = mock(LocationEngineCallback::class.java) as LocationEngineCallback<LocationEngineResult>
val looper = mock(Looper::class.java)
`when`(locationManagerMock!!.getBestProvider(any(Criteria::class.java), anyBoolean())).thenReturn("gps")
engine!!.requestLocationUpdates(request, callback, looper)
verify(locationManagerMock, times(2)).requestLocationUpdates(anyString(),
anyLong(), anyFloat(), any(LocationListener::class.java), any(Looper::class.java))
}
@Test
fun requestLocationUpdatesIndoors() {
val request = LocationEngineRequest.Builder(10)
.setPriority(LocationEngineRequest.PRIORITY_HIGH_ACCURACY).build()
// J2K: IDE suggestion "as LocationEngineCallback<LocationEngineResult>"
val callback: LocationEngineCallback<LocationEngineResult> = mock(LocationEngineCallback::class.java) as LocationEngineCallback<LocationEngineResult>
val looper = mock(Looper::class.java)
`when`(locationManagerMock!!.getBestProvider(any(Criteria::class.java), anyBoolean())).thenReturn("network")
engine!!.requestLocationUpdates(request, callback, looper)
verify(locationManagerMock, times(1)).requestLocationUpdates(anyString(),
anyLong(), anyFloat(), any(LocationListener::class.java), any(Looper::class.java))
}
@Test
fun requestLocationUpdatesOutdoorsWithPendingIntent() {
val request = LocationEngineRequest.Builder(10)
.setPriority(LocationEngineRequest.PRIORITY_HIGH_ACCURACY).build()
val pendingIntent = mock(PendingIntent::class.java)
`when`(locationManagerMock!!.getBestProvider(any(Criteria::class.java), anyBoolean())).thenReturn("gps")
engine!!.requestLocationUpdates(request, pendingIntent)
verify(locationManagerMock, times(2)).requestLocationUpdates(anyString(),
anyLong(), anyFloat(), any(PendingIntent::class.java))
}
@Test
fun requestLocationUpdatesIndoorsWithPendingIntent() {
val request = LocationEngineRequest.Builder(10)
.setPriority(LocationEngineRequest.PRIORITY_HIGH_ACCURACY).build()
val pendingIntent = mock(PendingIntent::class.java)
`when`(locationManagerMock!!.getBestProvider(any(Criteria::class.java), anyBoolean())).thenReturn("network")
engine!!.requestLocationUpdates(request, pendingIntent)
verify(locationManagerMock, times(1)).requestLocationUpdates(anyString(),
anyLong(), anyFloat(), any(PendingIntent::class.java))
}
// J2k: // TODO: see https://github.com/maplibre/maplibre-native/issues/1949
/*
// J2K: rewrite test to not use "@get", rename to "getLastLocationNull"
@Test(expected = NullPointerException::class)
fun getLastLocationNull() {
engine!!.getLastLocation(null!!)
}
// J2K: changed "null" to "null!!"
@Test(expected = NullPointerException::class)
fun requestLocationUpdatesNullCallback() {
engine!!.requestLocationUpdates(null!!, null!!, null!!)
}
*/
@After
fun tearDown() {
reset(locationManagerMock)
engine = null
}
companion object {
private const val LATITUDE = 37.7749
private const val LONGITUDE = 122.4194
private fun getCallback(
resultRef: AtomicReference<LocationEngineResult>,
latch: CountDownLatch): LocationEngineCallback<LocationEngineResult> {
// J2K: remove '?' from LocationEngineResult?
return object : LocationEngineCallback<LocationEngineResult> {
override fun onSuccess(result: LocationEngineResult) {
resultRef.set(result)
latch.countDown()
}
override fun onFailure(exception: Exception) {
exception.printStackTrace()
}
}
}
private fun getMockEngineResult(location: Location): LocationEngineResult {
return LocationEngineResult.create(location)
}
private fun getMockLocation(lat: Double, lon: Double): Location {
val location = mock(Location::class.java)
location.latitude = lat
location.longitude = lon
return location
}
}
}

View File

@@ -0,0 +1,93 @@
package org.maplibre.android.log
import io.mockk.mockk
import io.mockk.verify
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class LoggerTest {
private val logger: LoggerDefinition = mockk(relaxed = true)
@Before
fun setUp() {
Logger.setLoggerDefinition(logger)
}
@Test
fun verbosityLogLevel() {
Logger.setVerbosity(Logger.VERBOSE)
Logger.v(TAG, MESSAGE)
verify { logger.v(TAG, MESSAGE) }
}
@Test
fun verbosityLogLevelIgnore() {
Logger.setVerbosity(Logger.DEBUG)
Logger.v(TAG, MESSAGE)
verify(exactly = 0) { logger.v(TAG, MESSAGE) }
}
@Test
fun debugLogLevel() {
Logger.setVerbosity(Logger.VERBOSE)
Logger.d(TAG, MESSAGE)
verify { logger.d(TAG, MESSAGE) }
}
@Test
fun debugLogLevelIgnore() {
Logger.setVerbosity(Logger.WARN)
Logger.d(TAG, MESSAGE)
verify(exactly = 0) { logger.d(TAG, MESSAGE) }
}
@Test
fun warnLogLevel() {
Logger.setVerbosity(Logger.WARN)
Logger.w(TAG, MESSAGE)
verify { logger.w(TAG, MESSAGE) }
}
@Test
fun warnLogLevelIgnore() {
Logger.setVerbosity(Logger.ERROR)
Logger.w(TAG, MESSAGE)
verify(exactly = 0) { logger.w(TAG, MESSAGE) }
}
@Test
fun errorLogLevel() {
Logger.setVerbosity(Logger.ERROR)
Logger.e(TAG, MESSAGE)
verify { logger.e(TAG, MESSAGE) }
}
@Test
fun errorLogLevelIgnore() {
Logger.setVerbosity(Logger.NONE)
Logger.e(TAG, MESSAGE)
verify(exactly = 0) { logger.e(TAG, MESSAGE) }
}
@Test
fun noneLogLevelIgnore() {
Logger.setVerbosity(Logger.NONE)
Logger.v(TAG, MESSAGE)
Logger.d(TAG, MESSAGE)
Logger.w(TAG, MESSAGE)
Logger.e(TAG, MESSAGE)
verify(exactly = 0) { logger.v(TAG, MESSAGE) }
verify(exactly = 0) { logger.d(TAG, MESSAGE) }
verify(exactly = 0) { logger.w(TAG, MESSAGE) }
verify(exactly = 0) { logger.e(TAG, MESSAGE) }
}
companion object {
const val TAG: String = "TAG"
const val MESSAGE: String = "message"
}
}

View File

@@ -0,0 +1,104 @@
package org.maplibre.android.maps
import androidx.collection.LongSparseArray
import org.maplibre.android.annotations.Annotation
import org.maplibre.android.annotations.BaseMarkerOptions
import org.maplibre.android.annotations.Marker
import org.maplibre.android.annotations.MarkerOptions
import org.maplibre.android.geometry.LatLng
import org.junit.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<Annotation>()
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 aMapLibreMap = Mockito.mock(MapLibreMap::class.java)
Mockito.`when`(aMarkerOptions.marker).thenReturn(aMarker)
annotationManager.addMarker(aMarkerOptions, aMapLibreMap)
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<Annotation>()
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<BaseMarkerOptions<*, *>> = ArrayList()
val firstMarkerOption = MarkerOptions().position(LatLng()).title("first")
val secondMarkerOption = MarkerOptions().position(LatLng()).title("second")
markerList.add(firstMarkerOption)
markerList.add(secondMarkerOption)
val aMapLibreMap = Mockito.mock(MapLibreMap::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, aMapLibreMap)
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)
}
}

View File

@@ -0,0 +1,40 @@
package org.maplibre.android.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 maplibreMap = Mockito.mock(MapLibreMap::class.java)
@InjectMocks
var style = Mockito.mock(
Style::class.java
)
private var attributionDialogManager: AttributionDialogManager? = null
@Before
fun beforeTest() {
attributionDialogManager = AttributionDialogManager(context, maplibreMap)
}
@Test
fun testSanity() {
Assert.assertNotNull(
"AttributionDialogManager should not be null",
attributionDialogManager
)
}
}

View File

@@ -0,0 +1,714 @@
package org.maplibre.android.maps
import com.google.common.util.concurrent.ExecutionError
import org.maplibre.android.log.Logger
import org.maplibre.android.log.LoggerDefinition
import org.maplibre.android.maps.MapView.*
import org.junit.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, .0, .0)
Mockito.verify(onDidFinishRenderingFrameListener)?.onDidFinishRenderingFrame(true, .0, .0)
mapChangeEventManager!!.removeOnDidFinishRenderingFrameListener(
onDidFinishRenderingFrameListener
)
mapChangeEventManager!!?.onDidFinishRenderingFrame(true, .0, .0)
Mockito.verify(onDidFinishRenderingFrameListener)?.onDidFinishRenderingFrame(true,.0, .0)
mapChangeEventManager!!.addOnDidFinishRenderingFrameListener(
onDidFinishRenderingFrameListener
)
Logger.setLoggerDefinition(loggerDefinition)
val exc: Exception = RuntimeException()
Mockito.doThrow(exc).`when`(onDidFinishRenderingFrameListener)
?.onDidFinishRenderingFrame(true, .0, .0)
try {
mapChangeEventManager!!?.onDidFinishRenderingFrame(true, .0, .0)
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, .0, .0)
try {
mapChangeEventManager!!?.onDidFinishRenderingFrame(true, .0, .0)
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, .0, .0)
Mockito.verify(onDidFinishRenderingFrameListener)?.onDidFinishRenderingFrame(false, .0, .0)
mapChangeEventManager!!.removeOnDidFinishRenderingFrameListener(
onDidFinishRenderingFrameListener
)
mapChangeEventManager!!?.onDidFinishRenderingFrame(false, .0, .0)
Mockito.verify(onDidFinishRenderingFrameListener)?.onDidFinishRenderingFrame(false, .0, .0)
mapChangeEventManager!!.addOnDidFinishRenderingFrameListener(
onDidFinishRenderingFrameListener
)
Logger.setLoggerDefinition(loggerDefinition)
val exc: Exception = RuntimeException()
Mockito.doThrow(exc).`when`(onDidFinishRenderingFrameListener)
?.onDidFinishRenderingFrame(false, .0, .0)
try {
mapChangeEventManager!!?.onDidFinishRenderingFrame(false, .0, .0)
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, .0, .0)
try {
mapChangeEventManager!!?.onDidFinishRenderingFrame(false, .0, .0)
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"
}
}

View File

@@ -0,0 +1,101 @@
package org.maplibre.android.maps
import android.content.Context
import android.content.res.Resources
import android.content.res.TypedArray
import org.maplibre.android.R
import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.RelaxedMockK
import io.mockk.verify
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class MapLibreMapOptionsAttrsTest {
@RelaxedMockK
private lateinit var options: MapLibreMapOptions
@RelaxedMockK
private lateinit var typedArray: TypedArray
@RelaxedMockK
private lateinit var context: Context
@RelaxedMockK
private lateinit var resources: Resources
@Before
fun setUp() {
MockKAnnotations.init(this)
every {
context.resources
}.returns(resources)
}
@Test
fun enabledLocalIdeographFontFamily() {
mockEnableLocalIdeograph(enabled = true)
val options = MapLibreMapOptions.createFromAttributes(options, context, typedArray)
verify(exactly = 1) {
options.localIdeographFontFamily(any())
}
}
@Test
fun localIdeographFontFamily() {
mockEnableLocalIdeograph(enabled = true)
val font = "foo"
mockLocalIdeographString(font)
val options = MapLibreMapOptions.createFromAttributes(options, context, typedArray)
verify(exactly = 1) {
options.localIdeographFontFamily(font)
}
}
@Test
fun localIdeographFontFamilies() {
mockEnableLocalIdeograph(enabled = true)
val fonts = arrayOf("foo", "bar")
mockLocalIdeographStringArray(fonts)
val options = MapLibreMapOptions.createFromAttributes(options, context, typedArray)
verify(exactly = 1) {
options.localIdeographFontFamily(*fonts)
}
}
private fun mockEnableLocalIdeograph(enabled: Boolean) {
every {
typedArray.getBoolean(R.styleable.maplibre_MapView_maplibre_localIdeographEnabled, true)
}.returns(enabled)
}
private fun mockLocalIdeographString(font: String) {
every {
typedArray.getString(R.styleable.maplibre_MapView_maplibre_localIdeographFontFamily)
}.returns(font)
}
private fun mockLocalIdeographStringArray(fonts: Array<String>) {
val resId = 9000
every {
typedArray.getResourceId(R.styleable.maplibre_MapView_maplibre_localIdeographFontFamilies, 0)
}.returns(resId)
every {
resources.getStringArray(resId)
}.returns(fonts)
}
}

View File

@@ -0,0 +1,329 @@
package org.maplibre.android.maps
import android.graphics.Color
import android.view.Gravity
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.constants.MapLibreConstants
import org.maplibre.android.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 MapLibreMapOptionsTest {
@Test
fun testSanity() {
Assert.assertNotNull("should not be null",
MapLibreMapOptions()
)
}
@Test
fun testDebugEnabled() {
Assert.assertFalse(MapLibreMapOptions().debugActive)
Assert.assertTrue(MapLibreMapOptions().debugActive(true).debugActive)
Assert.assertFalse(MapLibreMapOptions().debugActive(false).debugActive)
}
@Test
fun testCompassEnabled() {
Assert.assertTrue(MapLibreMapOptions().compassEnabled(true).compassEnabled)
Assert.assertFalse(MapLibreMapOptions().compassEnabled(false).compassEnabled)
}
@Test
fun testCompassGravity() {
Assert.assertEquals(
Gravity.TOP or Gravity.END,
MapLibreMapOptions().compassGravity
)
Assert.assertEquals(
Gravity.BOTTOM,
MapLibreMapOptions().compassGravity(Gravity.BOTTOM).compassGravity
)
Assert.assertNotEquals(
Gravity.START.toLong(),
MapLibreMapOptions().compassGravity(Gravity.BOTTOM).compassGravity.toLong()
)
}
@Test
fun testCompassMargins() {
Assert.assertTrue(
Arrays.equals(
intArrayOf(0, 1, 2, 3),
MapLibreMapOptions()
.compassMargins(intArrayOf(0, 1, 2, 3)).compassMargins
)
)
Assert.assertFalse(
Arrays.equals(
intArrayOf(0, 1, 2, 3),
MapLibreMapOptions()
.compassMargins(intArrayOf(0, 0, 0, 0)).compassMargins
)
)
}
@Test
fun testLogoEnabled() {
Assert.assertTrue(MapLibreMapOptions().logoEnabled(true).logoEnabled)
Assert.assertFalse(MapLibreMapOptions().logoEnabled(false).logoEnabled)
}
@Test
fun testLogoGravity() {
Assert.assertEquals(
Gravity.BOTTOM or Gravity.START,
MapLibreMapOptions().logoGravity
)
Assert.assertEquals(
Gravity.BOTTOM,
MapLibreMapOptions().logoGravity(Gravity.BOTTOM).logoGravity
)
Assert.assertNotEquals(
Gravity.START.toLong(),
MapLibreMapOptions().logoGravity(Gravity.BOTTOM).logoGravity.toLong()
)
}
@Test
fun testLogoMargins() {
Assert.assertTrue(
Arrays.equals(
intArrayOf(0, 1, 2, 3),
MapLibreMapOptions()
.logoMargins(intArrayOf(0, 1, 2, 3)).logoMargins
)
)
Assert.assertFalse(
Arrays.equals(
intArrayOf(0, 1, 2, 3),
MapLibreMapOptions()
.logoMargins(intArrayOf(0, 0, 0, 0)).logoMargins
)
)
}
@Test
fun testAttributionTintColor() {
Assert.assertEquals(-1, MapLibreMapOptions().attributionTintColor)
Assert.assertEquals(
Color.RED,
MapLibreMapOptions().attributionTintColor(Color.RED).attributionTintColor
)
}
@Test
fun testAttributionEnabled() {
Assert.assertTrue(MapLibreMapOptions().attributionEnabled(true).attributionEnabled)
Assert.assertFalse(MapLibreMapOptions().attributionEnabled(false).attributionEnabled)
}
@Test
fun testAttributionGravity() {
Assert.assertEquals(
Gravity.BOTTOM or Gravity.START,
MapLibreMapOptions().attributionGravity
)
Assert.assertEquals(
Gravity.BOTTOM,
MapLibreMapOptions().attributionGravity(Gravity.BOTTOM).attributionGravity
)
Assert.assertNotEquals(
Gravity.START.toLong(),
MapLibreMapOptions().attributionGravity(Gravity.BOTTOM).attributionGravity.toLong()
)
}
@Test
fun testAttributionMargins() {
Assert.assertTrue(
Arrays.equals(
intArrayOf(0, 1, 2, 3),
MapLibreMapOptions()
.attributionMargins(intArrayOf(0, 1, 2, 3)).attributionMargins
)
)
Assert.assertFalse(
Arrays.equals(
intArrayOf(0, 1, 2, 3),
MapLibreMapOptions()
.attributionMargins(intArrayOf(0, 0, 0, 0)).attributionMargins
)
)
}
@Test
fun testMinZoom() {
Assert.assertEquals(
MapLibreConstants.MINIMUM_ZOOM.toDouble(),
MapLibreMapOptions().minZoomPreference,
DELTA
)
Assert.assertEquals(
5.0,
MapLibreMapOptions().minZoomPreference(5.0).minZoomPreference,
DELTA
)
Assert.assertNotEquals(
2.0,
MapLibreMapOptions().minZoomPreference(5.0).minZoomPreference,
DELTA
)
}
@Test
fun testMaxZoom() {
Assert.assertEquals(
MapLibreConstants.MAXIMUM_ZOOM.toDouble(),
MapLibreMapOptions().maxZoomPreference,
DELTA
)
Assert.assertEquals(
5.0,
MapLibreMapOptions().maxZoomPreference(5.0).maxZoomPreference,
DELTA
)
Assert.assertNotEquals(
2.0,
MapLibreMapOptions().maxZoomPreference(5.0).maxZoomPreference,
DELTA
)
}
@Test
fun testMinPitch() {
Assert.assertEquals(
MapLibreConstants.MINIMUM_PITCH.toDouble(),
MapLibreMapOptions().minPitchPreference,
DELTA
)
Assert.assertEquals(
5.0,
MapLibreMapOptions().minPitchPreference(5.0).minPitchPreference,
DELTA
)
Assert.assertNotEquals(
2.0,
MapLibreMapOptions().minPitchPreference(5.0).minPitchPreference,
DELTA
)
}
@Test
fun testMaxPitch() {
Assert.assertEquals(
MapLibreConstants.MAXIMUM_PITCH.toDouble(),
MapLibreMapOptions().maxPitchPreference,
DELTA
)
Assert.assertEquals(
5.0,
MapLibreMapOptions().maxPitchPreference(5.0).maxPitchPreference,
DELTA
)
Assert.assertNotEquals(
2.0,
MapLibreMapOptions().maxPitchPreference(5.0).maxPitchPreference,
DELTA
)
}
@Test
fun testTiltGesturesEnabled() {
Assert.assertTrue(MapLibreMapOptions().tiltGesturesEnabled)
Assert.assertTrue(MapLibreMapOptions().tiltGesturesEnabled(true).tiltGesturesEnabled)
Assert.assertFalse(MapLibreMapOptions().tiltGesturesEnabled(false).tiltGesturesEnabled)
}
@Test
fun testScrollGesturesEnabled() {
Assert.assertTrue(MapLibreMapOptions().scrollGesturesEnabled)
Assert.assertTrue(MapLibreMapOptions().scrollGesturesEnabled(true).scrollGesturesEnabled)
Assert.assertFalse(MapLibreMapOptions().scrollGesturesEnabled(false).scrollGesturesEnabled)
}
@Test
fun testHorizontalScrollGesturesEnabled() {
Assert.assertTrue(MapLibreMapOptions().horizontalScrollGesturesEnabled)
Assert.assertTrue(MapLibreMapOptions().horizontalScrollGesturesEnabled(true).horizontalScrollGesturesEnabled)
Assert.assertFalse(MapLibreMapOptions().horizontalScrollGesturesEnabled(false).horizontalScrollGesturesEnabled)
}
@Test
fun testZoomGesturesEnabled() {
Assert.assertTrue(MapLibreMapOptions().zoomGesturesEnabled)
Assert.assertTrue(MapLibreMapOptions().zoomGesturesEnabled(true).zoomGesturesEnabled)
Assert.assertFalse(MapLibreMapOptions().zoomGesturesEnabled(false).zoomGesturesEnabled)
}
@Test
fun testRotateGesturesEnabled() {
Assert.assertTrue(MapLibreMapOptions().rotateGesturesEnabled)
Assert.assertTrue(MapLibreMapOptions().rotateGesturesEnabled(true).rotateGesturesEnabled)
Assert.assertFalse(MapLibreMapOptions().rotateGesturesEnabled(false).rotateGesturesEnabled)
}
@Test
fun testCamera() {
val position = CameraPosition.Builder().build()
Assert.assertEquals(
CameraPosition.Builder(position).build(),
MapLibreMapOptions().camera(position).camera
)
Assert.assertNotEquals(
CameraPosition.Builder().target(LatLng(1.0, 1.0)),
MapLibreMapOptions().camera(position)
)
Assert.assertNull(MapLibreMapOptions().camera)
}
@Test
fun testPrefetchesTiles() {
// Default value
Assert.assertTrue(MapLibreMapOptions().prefetchesTiles)
// Check mutations
Assert.assertTrue(MapLibreMapOptions().setPrefetchesTiles(true).prefetchesTiles)
Assert.assertFalse(MapLibreMapOptions().setPrefetchesTiles(false).prefetchesTiles)
}
@Test
fun testPrefetchZoomDelta() {
// Default value
Assert.assertEquals(4, MapLibreMapOptions().prefetchZoomDelta)
// Check mutations
Assert.assertEquals(
5,
MapLibreMapOptions().setPrefetchZoomDelta(5).prefetchZoomDelta
)
}
@Test
fun testCrossSourceCollisions() {
// Default value
Assert.assertTrue(MapLibreMapOptions().crossSourceCollisions)
// check mutations
Assert.assertTrue(MapLibreMapOptions().crossSourceCollisions(true).crossSourceCollisions)
Assert.assertFalse(MapLibreMapOptions().crossSourceCollisions(false).crossSourceCollisions)
}
@Test
fun testLocalIdeographFontFamily_enabledByDefault() {
val options = MapLibreMapOptions.createFromAttributes(RuntimeEnvironment.application, null)
Assert.assertEquals(
MapLibreConstants.DEFAULT_FONT,
options.localIdeographFontFamily
)
}
companion object {
private const val DELTA = 1e-15
}
}

View File

@@ -0,0 +1,247 @@
package org.maplibre.android.maps
import android.content.Context
import org.maplibre.android.MapLibreInjector
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.camera.CameraUpdateFactory
import org.maplibre.android.constants.MapLibreConstants
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.geometry.LatLngBounds
import org.maplibre.android.style.layers.TransitionOptions
import org.maplibre.android.utils.ConfigUtils
import io.mockk.*
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.MockitoAnnotations
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class MapLibreMapTest {
private lateinit var maplibreMap: MapLibreMap
private lateinit var nativeMapView: NativeMap
private lateinit var transform: Transform
private lateinit var cameraChangeDispatcher: CameraChangeDispatcher
private lateinit var developerAnimationListener: MapLibreMap.OnDeveloperAnimationListener
@Mock
private lateinit var context: Context
@Mock
private lateinit var appContext: Context
@Before
fun setup() {
MockitoAnnotations.initMocks(this)
MapLibreInjector.inject(context, "abcdef", ConfigUtils.getMockedOptions())
cameraChangeDispatcher = spyk()
developerAnimationListener = mockk(relaxed = true)
nativeMapView = mockk(relaxed = true)
transform = mockk(relaxed = true)
maplibreMap = MapLibreMap(
nativeMapView,
transform,
mockk(relaxed = true),
null,
null,
cameraChangeDispatcher,
listOf(developerAnimationListener)
)
every { nativeMapView.isDestroyed } returns false
every { nativeMapView.nativePtr } returns 5
maplibreMap.injectLocationComponent(spyk())
maplibreMap.setStyle(Style.getPredefinedStyle("Streets"))
maplibreMap.onFinishLoadingStyle()
}
@Test
fun testTransitionOptions() {
val expected = TransitionOptions(100, 200)
maplibreMap.style?.transition = expected
verify { nativeMapView.transitionOptions = expected }
}
@Test
fun testMoveCamera() {
val callback = mockk<MapLibreMap.CancelableCallback>()
val target = LatLng(1.0, 2.0)
val expected = CameraPosition.Builder().target(target).build()
val update = CameraUpdateFactory.newCameraPosition(expected)
maplibreMap.moveCamera(update, callback)
verify { transform.moveCamera(maplibreMap, update, callback) }
verify { developerAnimationListener.onDeveloperAnimationStarted() }
}
@Test
fun testEaseCamera() {
val callback = mockk<MapLibreMap.CancelableCallback>()
val target = LatLng(1.0, 2.0)
val expected = CameraPosition.Builder().target(target).build()
val update = CameraUpdateFactory.newCameraPosition(expected)
maplibreMap.easeCamera(update, callback)
verify { transform.easeCamera(maplibreMap, update, MapLibreConstants.ANIMATION_DURATION, true, callback) }
verify { developerAnimationListener.onDeveloperAnimationStarted() }
}
@Test
fun testAnimateCamera() {
val callback = mockk<MapLibreMap.CancelableCallback>()
val target = LatLng(1.0, 2.0)
val expected = CameraPosition.Builder().target(target).build()
val update = CameraUpdateFactory.newCameraPosition(expected)
maplibreMap.animateCamera(update, callback)
verify { transform.animateCamera(maplibreMap, update, MapLibreConstants.ANIMATION_DURATION, callback) }
verify { developerAnimationListener.onDeveloperAnimationStarted() }
}
@Test
fun testScrollBy() {
maplibreMap.scrollBy(100f, 200f)
verify { nativeMapView.moveBy(100.0, 200.0, 0) }
verify { developerAnimationListener.onDeveloperAnimationStarted() }
}
@Test
fun testResetNorth() {
maplibreMap.resetNorth()
verify { transform.resetNorth() }
verify { developerAnimationListener.onDeveloperAnimationStarted() }
}
@Test
fun testFocalBearing() {
maplibreMap.setFocalBearing(35.0, 100f, 200f, 1000)
verify { transform.setBearing(35.0, 100f, 200f, 1000) }
verify { developerAnimationListener.onDeveloperAnimationStarted() }
}
@Test
fun testMinZoom() {
maplibreMap.setMinZoomPreference(10.0)
verify { transform.minZoom = 10.0 }
}
@Test
fun testMaxZoom() {
maplibreMap.setMaxZoomPreference(10.0)
verify { transform.maxZoom = 10.0 }
}
@Test
fun testMinPitch() {
maplibreMap.setMinPitchPreference(10.0)
verify { transform.minPitch = 10.0 }
}
@Test
fun testMaxPitch() {
maplibreMap.setMaxPitchPreference(10.0)
verify { transform.maxPitch = 10.0 }
}
@Test
fun testFpsListener() {
val fpsChangedListener = mockk<MapLibreMap.OnFpsChangedListener>()
maplibreMap.onFpsChangedListener = fpsChangedListener
assertEquals("Listener should match", fpsChangedListener, maplibreMap.onFpsChangedListener)
}
@Test
fun testTilePrefetch() {
maplibreMap.prefetchesTiles = true
verify { nativeMapView.prefetchTiles = true }
}
@Test
fun testGetPrefetchZoomDelta() {
every { nativeMapView.prefetchZoomDelta } answers { 3 }
assertEquals(3, maplibreMap.prefetchZoomDelta)
}
@Test
fun testSetPrefetchZoomDelta() {
maplibreMap.prefetchZoomDelta = 2
verify { nativeMapView.prefetchZoomDelta = 2 }
}
@Test
fun testCameraForLatLngBounds() {
val bounds = LatLngBounds.Builder().include(LatLng()).include(LatLng(1.0, 1.0)).build()
maplibreMap.setLatLngBoundsForCameraTarget(bounds)
verify { nativeMapView.setLatLngBounds(bounds) }
}
@Test(expected = IllegalArgumentException::class)
fun testAnimateCameraChecksDurationPositive() {
maplibreMap.animateCamera(CameraUpdateFactory.newLatLng(LatLng(30.0, 30.0)), 0, null)
}
@Test(expected = IllegalArgumentException::class)
fun testEaseCameraChecksDurationPositive() {
maplibreMap.easeCamera(CameraUpdateFactory.newLatLng(LatLng(30.0, 30.0)), 0, null)
}
@Test
fun testGetNativeMapPtr() {
assertEquals(5, maplibreMap.nativeMapPtr)
}
@Test
fun testNativeMapIsNotCalledOnStateSave() {
clearMocks(nativeMapView)
maplibreMap.onSaveInstanceState(mockk(relaxed = true))
verify { nativeMapView wasNot Called }
}
@Test
fun testCameraChangeDispatcherCleared() {
maplibreMap.onDestroy()
verify { cameraChangeDispatcher.onDestroy() }
}
@Test
fun testStyleClearedOnDestroy() {
val style = mockk<Style>(relaxed = true)
val builder = mockk<Style.Builder>(relaxed = true)
every { builder.build(nativeMapView) } returns style
maplibreMap.setStyle(builder)
maplibreMap.onDestroy()
verify(exactly = 1) { style.clear() }
}
@Test
fun testStyleCallbackNotCalledWhenPreviousFailed() {
val style = mockk<Style>(relaxed = true)
val builder = mockk<Style.Builder>(relaxed = true)
every { builder.build(nativeMapView) } returns style
val onStyleLoadedListener = mockk<Style.OnStyleLoaded>(relaxed = true)
maplibreMap.setStyle(builder, onStyleLoadedListener)
maplibreMap.onFailLoadingStyle()
maplibreMap.setStyle(builder, onStyleLoadedListener)
maplibreMap.onFinishLoadingStyle()
verify(exactly = 1) { onStyleLoadedListener.onStyleLoaded(style) }
}
@Test
fun testStyleCallbackNotCalledWhenPreviousNotFinished() {
// regression test for #14337
val style = mockk<Style>(relaxed = true)
val builder = mockk<Style.Builder>(relaxed = true)
every { builder.build(nativeMapView) } returns style
val onStyleLoadedListener = mockk<Style.OnStyleLoaded>(relaxed = true)
maplibreMap.setStyle(builder, onStyleLoadedListener)
maplibreMap.setStyle(builder, onStyleLoadedListener)
maplibreMap.onFinishLoadingStyle()
verify(exactly = 1) { onStyleLoadedListener.onStyleLoaded(style) }
}
}

View File

@@ -0,0 +1,181 @@
package org.maplibre.android.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 org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.MapLibreMap.*
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(
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(
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)
}
}

View File

@@ -0,0 +1,249 @@
package org.maplibre.android.maps
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.graphics.drawable.ShapeDrawable
import android.util.Pair
import org.maplibre.android.style.layers.SymbolLayer
import org.maplibre.android.style.layers.TransitionOptions
import org.maplibre.android.style.sources.GeoJsonSource
import org.maplibre.android.utils.BitmapUtils
import io.mockk.mockk
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class StyleBuilderTest {
@Test
fun testFromUrl() {
val expected = "https://demotiles.maplibre.org/style.json"
val builder = Style.Builder()
builder.fromUrl(expected)
assertEquals(expected, builder.uri)
}
@Test
fun testFromJson() {
val expected = "{}"
val builder = Style.Builder()
builder.fromJson(expected)
assertEquals(expected, builder.json)
}
@Test
fun testWithLayer() {
val layer = mockk<SymbolLayer>()
val builder = Style.Builder()
builder.withLayer(layer)
assertEquals(layer, builder.layers[0].layer)
}
@Test
fun testWithLayers() {
val layer1 = mockk<SymbolLayer>()
val layer2 = mockk<SymbolLayer>()
val builder = Style.Builder()
builder.withLayers(layer1, layer2)
assertEquals(layer1, builder.layers[0].layer)
assertEquals(layer2, builder.layers[1].layer)
}
@Test
fun testWithLayerAt() {
val expectedIndex = 5
val layer = mockk<SymbolLayer>()
val builder = Style.Builder()
builder.withLayerAt(layer, expectedIndex)
assertEquals(layer, builder.layers[0].layer)
assertEquals(expectedIndex, (builder.layers[0] as Style.Builder.LayerAtWrapper).index)
}
@Test
fun testWithLayerAbove() {
val expectedAbove = "above"
val layer = mockk<SymbolLayer>()
val builder = Style.Builder()
builder.withLayerAbove(layer, expectedAbove)
assertEquals(layer, builder.layers[0].layer)
assertEquals(expectedAbove, (builder.layers[0] as Style.Builder.LayerAboveWrapper).aboveLayer)
}
@Test
fun testWithLayerBelow() {
val expectedBelow = "above"
val layer = mockk<SymbolLayer>()
val builder = Style.Builder()
builder.withLayerBelow(layer, expectedBelow)
assertEquals(layer, builder.layers[0].layer)
assertEquals(expectedBelow, (builder.layers[0] as Style.Builder.LayerBelowWrapper).belowLayer)
}
@Test
fun testWithSource() {
val source = mockk<GeoJsonSource>()
val builder = Style.Builder()
builder.withSource(source)
assertEquals(source, builder.sources[0])
}
@Test
fun testWithSources() {
val source1 = mockk<GeoJsonSource>()
val source2 = mockk<GeoJsonSource>()
val builder = Style.Builder()
builder.withSources(source1, source2)
assertEquals(source1, builder.sources[0])
assertEquals(source2, builder.sources[1])
}
@Test
fun testWithImage() {
val bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8)
val builder = Style.Builder()
builder.withImage("id", bitmap)
assertEquals(bitmap, builder.images[0].bitmap)
assertEquals("id", builder.images[0].id)
assertEquals(false, builder.images[0].sdf)
}
@Test
fun testWithImages() {
val bitmap1 = Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8)
val bitmap2 = Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8)
val builder = Style.Builder()
builder.withBitmapImages(Pair("id1", bitmap1), Pair("id2", bitmap2))
assertEquals(bitmap1, builder.images[0].bitmap)
assertEquals("id1", builder.images[0].id)
assertEquals(false, builder.images[0].sdf)
assertEquals(bitmap2, builder.images[1].bitmap)
assertEquals("id2", builder.images[1].id)
assertEquals(false, builder.images[1].sdf)
}
@Test
fun testWithImageSdf() {
val bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8)
val builder = Style.Builder()
builder.withImage("id", bitmap, true)
assertEquals(bitmap, builder.images[0].bitmap)
assertEquals("id", builder.images[0].id)
assertEquals(true, builder.images[0].sdf)
}
@Test
fun testWithImageSdfs() {
val bitmap1 = Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8)
val bitmap2 = Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8)
val builder = Style.Builder()
builder.withBitmapImages(true, Pair("id1", bitmap1), Pair("id2", bitmap2))
assertEquals(bitmap1, builder.images[0].bitmap)
assertEquals("id1", builder.images[0].id)
assertEquals(true, builder.images[0].sdf)
assertEquals(bitmap2, builder.images[1].bitmap)
assertEquals("id2", builder.images[1].id)
assertEquals(true, builder.images[1].sdf)
}
@Test
fun testWithImageDrawable() {
val drawable = ShapeDrawable()
drawable.intrinsicWidth = 1
drawable.intrinsicHeight = 1
val builder = Style.Builder()
builder.withImage("id", drawable)
assertTrue(
BitmapUtils.equals(
BitmapUtils.getBitmapFromDrawable(drawable)!!,
builder.images[0].bitmap
)
)
assertEquals("id", builder.images[0].id)
assertEquals(false, builder.images[0].sdf)
}
@Test
fun testWithImageDrawableSdf() {
val drawable = ShapeDrawable()
drawable.intrinsicWidth = 1
drawable.intrinsicHeight = 1
val builder = Style.Builder()
builder.withImage("id", drawable, true)
assertTrue(
BitmapUtils.equals(
BitmapUtils.getBitmapFromDrawable(drawable)!!,
builder.images[0].bitmap
)
)
assertEquals("id", builder.images[0].id)
assertEquals(true, builder.images[0].sdf)
}
@Test
fun testWithImageDrawables() {
val drawable1 = ShapeDrawable()
drawable1.intrinsicWidth = 1
drawable1.intrinsicHeight = 1
val drawable2 = ShapeDrawable()
drawable2.intrinsicWidth = 1
drawable2.intrinsicHeight = 1
val builder = Style.Builder()
builder.withDrawableImages(Pair<String, Drawable>("id1", drawable1), Pair<String, Drawable>("id2", drawable2))
assertTrue(
BitmapUtils.equals(
BitmapUtils.getBitmapFromDrawable(drawable1)!!,
builder.images[0].bitmap
)
)
assertEquals("id1", builder.images[0].id)
assertEquals(false, builder.images[0].sdf)
assertTrue(
BitmapUtils.equals(
BitmapUtils.getBitmapFromDrawable(drawable2)!!,
builder.images[1].bitmap
)
)
assertEquals("id2", builder.images[1].id)
assertEquals(false, builder.images[1].sdf)
}
@Test
fun testWithImageSdfDrawables() {
val drawable1 = ShapeDrawable()
drawable1.intrinsicWidth = 1
drawable1.intrinsicHeight = 1
val drawable2 = ShapeDrawable()
drawable2.intrinsicWidth = 1
drawable2.intrinsicHeight = 1
val builder = Style.Builder()
builder.withDrawableImages(true, Pair<String, Drawable>("id1", drawable1), Pair<String, Drawable>("id2", drawable2))
assertTrue(
BitmapUtils.equals(
BitmapUtils.getBitmapFromDrawable(drawable1)!!,
builder.images[0].bitmap
)
)
assertEquals("id1", builder.images[0].id)
assertEquals(true, builder.images[0].sdf)
assertTrue(
BitmapUtils.equals(
BitmapUtils.getBitmapFromDrawable(drawable2)!!,
builder.images[1].bitmap
)
)
assertEquals("id2", builder.images[1].id)
assertEquals(true, builder.images[1].sdf)
}
@Test
fun testWithTransitionOptions() {
val transitionOptions = TransitionOptions(100, 200)
val builder = Style.Builder()
builder.withTransition(transitionOptions)
assertEquals(100, builder.transitionOptions.duration)
assertEquals(200, builder.transitionOptions.delay)
}
}

View File

@@ -0,0 +1,481 @@
package org.maplibre.android.maps
import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.ShapeDrawable
import org.maplibre.android.MapLibreInjector
import org.maplibre.android.constants.MapLibreConstants
import org.maplibre.android.style.layers.CannotAddLayerException
import org.maplibre.android.style.layers.SymbolLayer
import org.maplibre.android.style.layers.TransitionOptions
import org.maplibre.android.style.sources.CannotAddSourceException
import org.maplibre.android.style.sources.GeoJsonSource
import org.maplibre.android.utils.ConfigUtils
import io.mockk.every
import io.mockk.mockk
import io.mockk.spyk
import io.mockk.verify
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.MockitoAnnotations
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class StyleTest {
private lateinit var maplibreMap: MapLibreMap
private lateinit var nativeMapView: NativeMap
@Mock
private lateinit var context: Context
@Mock
private lateinit var appContext: Context
@Before
fun setup() {
MockitoAnnotations.initMocks(this)
MapLibreInjector.inject(context, "abcdef", ConfigUtils.getMockedOptions())
nativeMapView = mockk(relaxed = true)
maplibreMap = MapLibreMap(
nativeMapView,
null,
null,
null,
null,
null,
null
)
every { nativeMapView.isDestroyed } returns false
maplibreMap.injectLocationComponent(spyk())
}
@Test
fun testFromUrl() {
val builder = Style.Builder().fromUrl(Style.getPredefinedStyle("Streets"))
maplibreMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleUri = Style.getPredefinedStyle("Streets") }
}
@Test
fun testFromJson() {
val builder = Style.Builder().fromJson("{}")
maplibreMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleJson = "{}" }
}
@Test
fun testEmptyBuilder() {
val builder = Style.Builder()
maplibreMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleJson = Style.EMPTY_JSON }
}
@Test
fun testWithLayer() {
val layer = mockk<SymbolLayer>()
every { layer.id } returns "1"
val builder = Style.Builder().withLayer(layer)
maplibreMap.setStyle(builder)
maplibreMap.onFinishLoadingStyle()
verify(exactly = 1) {
nativeMapView.addLayerBelow(
layer,
MapLibreConstants.LAYER_ID_ANNOTATIONS
)
}
}
@Test
fun testWithLayerAbove() {
val layer = mockk<SymbolLayer>()
every { layer.id } returns "1"
val builder = Style.Builder().withLayerAbove(layer, "id")
maplibreMap.setStyle(builder)
maplibreMap.onFinishLoadingStyle()
verify(exactly = 1) { nativeMapView.addLayerAbove(layer, "id") }
}
@Test
fun testWithLayerBelow() {
val layer = mockk<SymbolLayer>()
every { layer.id } returns "1"
val builder = Style.Builder().withLayerBelow(layer, "id")
maplibreMap.setStyle(builder)
maplibreMap.onFinishLoadingStyle()
verify(exactly = 1) { nativeMapView.addLayerBelow(layer, "id") }
}
@Test
fun testWithLayerAt() {
val layer = mockk<SymbolLayer>()
every { layer.id } returns "1"
val builder = Style.Builder().withLayerAt(layer, 1)
maplibreMap.setStyle(builder)
maplibreMap.onFinishLoadingStyle()
verify(exactly = 1) { nativeMapView.addLayerAt(layer, 1) }
}
@Test
fun testWithSource() {
val source = mockk<GeoJsonSource>()
every { source.id } returns "1"
val builder = Style.Builder().withSource(source)
maplibreMap.setStyle(builder)
maplibreMap.onFinishLoadingStyle()
verify(exactly = 1) { nativeMapView.addSource(source) }
}
@Test
fun testWithTransitionOptions() {
val transitionOptions = TransitionOptions(100, 200)
val builder = Style.Builder().withTransition(transitionOptions)
maplibreMap.setStyle(builder)
maplibreMap.onFinishLoadingStyle()
verify(exactly = 1) { nativeMapView.transitionOptions = transitionOptions }
}
@Test
fun testWithFromLoadingSource() {
val source = mockk<GeoJsonSource>()
every { source.id } returns "1"
val builder =
Style.Builder().fromUrl(Style.getPredefinedStyle("Streets")).withSource(source)
maplibreMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleUri = Style.getPredefinedStyle("Streets") }
maplibreMap.notifyStyleLoaded()
verify(exactly = 1) { nativeMapView.addSource(source) }
}
@Test
fun testWithFromLoadingLayer() {
val layer = mockk<SymbolLayer>()
every { layer.id } returns "1"
val builder = Style.Builder().fromUrl(Style.getPredefinedStyle("Streets")).withLayer(layer)
maplibreMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleUri = Style.getPredefinedStyle("Streets") }
maplibreMap.notifyStyleLoaded()
verify(exactly = 1) {
nativeMapView.addLayerBelow(
layer,
MapLibreConstants.LAYER_ID_ANNOTATIONS
)
}
}
@Test
fun testWithFromLoadingLayerAt() {
val layer = mockk<SymbolLayer>()
every { layer.id } returns "1"
val builder =
Style.Builder().fromUrl(Style.getPredefinedStyle("Streets")).withLayerAt(layer, 1)
maplibreMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleUri = Style.getPredefinedStyle("Streets") }
maplibreMap.notifyStyleLoaded()
verify(exactly = 1) { nativeMapView.addLayerAt(layer, 1) }
}
@Test
fun testWithFromLoadingLayerBelow() {
val layer = mockk<SymbolLayer>()
every { layer.id } returns "1"
val builder = Style.Builder().fromUrl(Style.getPredefinedStyle("Streets"))
.withLayerBelow(layer, "below")
maplibreMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleUri = Style.getPredefinedStyle("Streets") }
maplibreMap.notifyStyleLoaded()
verify(exactly = 1) { nativeMapView.addLayerBelow(layer, "below") }
}
@Test
fun testWithFromLoadingLayerAbove() {
val layer = mockk<SymbolLayer>()
every { layer.id } returns "1"
val builder = Style.Builder().fromUrl(Style.getPredefinedStyle("Streets"))
.withLayerBelow(layer, "below")
maplibreMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleUri = Style.getPredefinedStyle("Streets") }
maplibreMap.notifyStyleLoaded()
verify(exactly = 1) { nativeMapView.addLayerBelow(layer, "below") }
}
@Test
fun testWithFromLoadingTransitionOptions() {
val transitionOptions = TransitionOptions(100, 200)
val builder = Style.Builder().fromUrl(Style.getPredefinedStyle("Streets"))
.withTransition(transitionOptions)
maplibreMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleUri = Style.getPredefinedStyle("Streets") }
maplibreMap.notifyStyleLoaded()
verify(exactly = 1) { nativeMapView.transitionOptions = transitionOptions }
}
@Test
fun testFromCallback() {
val callback = mockk<Style.OnStyleLoaded>()
every { callback.onStyleLoaded(any()) } answers {}
val builder = Style.Builder().fromUrl(Style.getPredefinedStyle("Streets"))
maplibreMap.setStyle(builder, callback)
verify(exactly = 1) { nativeMapView.styleUri = Style.getPredefinedStyle("Streets") }
maplibreMap.notifyStyleLoaded()
verify(exactly = 1) { callback.onStyleLoaded(any()) }
}
@Test
fun testWithCallback() {
val callback = mockk<Style.OnStyleLoaded>()
every { callback.onStyleLoaded(any()) } answers {}
val source = mockk<GeoJsonSource>()
every { source.id } returns "1"
val builder = Style.Builder().withSource(source)
maplibreMap.setStyle(builder, callback)
maplibreMap.onFinishLoadingStyle()
verify(exactly = 1) { nativeMapView.addSource(source) }
verify(exactly = 1) { callback.onStyleLoaded(any()) }
}
@Test
fun testGetAsyncWith() {
val callback = mockk<Style.OnStyleLoaded>()
every { callback.onStyleLoaded(any()) } answers {}
maplibreMap.getStyle(callback)
val source = mockk<GeoJsonSource>()
every { source.id } returns "1"
val builder = Style.Builder().withSource(source)
maplibreMap.setStyle(builder)
maplibreMap.onFinishLoadingStyle()
verify(exactly = 1) { nativeMapView.addSource(source) }
verify(exactly = 1) { callback.onStyleLoaded(any()) }
}
@Test
fun testGetAsyncFrom() {
val callback = mockk<Style.OnStyleLoaded>()
every { callback.onStyleLoaded(any()) } answers {}
maplibreMap.getStyle(callback)
val source = mockk<GeoJsonSource>()
every { source.id } returns "1"
val builder = Style.Builder().fromJson("{}")
maplibreMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleJson = "{}" }
maplibreMap.notifyStyleLoaded()
verify(exactly = 1) { callback.onStyleLoaded(any()) }
}
@Test
fun testGetAsyncWithFrom() {
val callback = mockk<Style.OnStyleLoaded>()
every { callback.onStyleLoaded(any()) } answers {}
maplibreMap.getStyle(callback)
val source = mockk<GeoJsonSource>()
every { source.id } returns "1"
val builder =
Style.Builder().fromUrl(Style.getPredefinedStyle("Streets")).withSource(source)
maplibreMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleUri = Style.getPredefinedStyle("Streets") }
maplibreMap.notifyStyleLoaded()
verify(exactly = 1) { nativeMapView.addSource(source) }
verify(exactly = 1) { callback.onStyleLoaded(any()) }
}
@Test
fun testGetNullStyle() {
Assert.assertNull(maplibreMap.style)
}
@Test
fun testGetNullWhileLoading() {
val transitionOptions = TransitionOptions(100, 200)
val builder = Style.Builder().fromUrl(Style.getPredefinedStyle("Streets"))
.withTransition(transitionOptions)
maplibreMap.setStyle(builder)
Assert.assertNull(maplibreMap.style)
maplibreMap.notifyStyleLoaded()
Assert.assertNotNull(maplibreMap.style)
}
@Test
fun testNotReinvokeSameListener() {
val callback = mockk<Style.OnStyleLoaded>()
every { callback.onStyleLoaded(any()) } answers {}
maplibreMap.getStyle(callback)
val source = mockk<GeoJsonSource>()
every { source.id } returns "1"
val builder = Style.Builder().fromJson("{}")
maplibreMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleJson = "{}" }
maplibreMap.notifyStyleLoaded()
maplibreMap.setStyle(Style.getPredefinedStyle("Streets"))
verify(exactly = 1) { callback.onStyleLoaded(any()) }
}
@Test(expected = IllegalStateException::class)
fun testIllegalStateExceptionWithStyleReload() {
val builder = Style.Builder().fromUrl(Style.getPredefinedStyle("Streets"))
maplibreMap.setStyle(builder)
maplibreMap.notifyStyleLoaded()
val style = maplibreMap.style
maplibreMap.setStyle(Style.Builder().fromUrl(Style.getPredefinedStyle("Bright")))
style!!.addLayer(mockk<SymbolLayer>())
}
@Test
fun testAddImage() {
val bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888)
val builder =
Style.Builder().fromUrl(Style.getPredefinedStyle("Satellite Hybrid")).withImage("id", bitmap)
maplibreMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleUri = Style.getPredefinedStyle("Satellite Hybrid") }
verify(exactly = 0) { nativeMapView.addImages(any()) }
maplibreMap.notifyStyleLoaded()
verify(exactly = 1) { nativeMapView.addImages(any()) }
}
@Test
fun testAddDrawable() {
val drawable = ShapeDrawable()
drawable.intrinsicHeight = 10
drawable.intrinsicWidth = 10
val builder =
Style.Builder().fromUrl(Style.getPredefinedStyle("Satellite Hybrid")).withImage("id", drawable)
maplibreMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleUri = Style.getPredefinedStyle("Satellite Hybrid") }
verify(exactly = 0) { nativeMapView.addImages(any()) }
maplibreMap.notifyStyleLoaded()
verify(exactly = 1) { nativeMapView.addImages(any()) }
}
@Test
fun testSourceSkippedIfAdditionFails() {
val source1 = mockk<GeoJsonSource>(relaxed = true)
every { source1.id } returns "source1"
val source2 = mockk<GeoJsonSource>(relaxed = true)
every { source2.id } returns "source1" // same ID
val builder = Style.Builder().withSource(source1)
maplibreMap.setStyle(builder)
maplibreMap.notifyStyleLoaded()
every { nativeMapView.addSource(any()) } throws CannotAddSourceException("Duplicate ID")
try {
maplibreMap.style!!.addSource(source2)
} catch (ex: Exception) {
Assert.assertEquals(
"Source that failed to be added shouldn't be cached",
source1,
maplibreMap.style!!.getSource("source1")
)
}
}
@Test
fun testLayerSkippedIfAdditionFails() {
val layer1 = mockk<SymbolLayer>(relaxed = true)
every { layer1.id } returns "layer1"
val layer2 = mockk<SymbolLayer>(relaxed = true)
every { layer2.id } returns "layer1" // same ID
val builder = Style.Builder().withLayer(layer1)
maplibreMap.setStyle(builder)
maplibreMap.notifyStyleLoaded()
every { nativeMapView.addLayer(any()) } throws CannotAddLayerException("Duplicate ID")
try {
maplibreMap.style!!.addLayer(layer2)
} catch (ex: Exception) {
Assert.assertEquals(
"Layer that failed to be added shouldn't be cached",
layer1,
maplibreMap.style!!.getLayer("layer1")
)
}
}
@Test
fun testLayerSkippedIfAdditionBelowFails() {
val layer1 = mockk<SymbolLayer>(relaxed = true)
every { layer1.id } returns "layer1"
val layer2 = mockk<SymbolLayer>(relaxed = true)
every { layer2.id } returns "layer1" // same ID
val builder = Style.Builder().withLayer(layer1)
maplibreMap.setStyle(builder)
maplibreMap.notifyStyleLoaded()
every {
nativeMapView.addLayerBelow(
any(),
""
)
} throws CannotAddLayerException("Duplicate ID")
try {
maplibreMap.style!!.addLayerBelow(layer2, "")
} catch (ex: Exception) {
Assert.assertEquals(
"Layer that failed to be added shouldn't be cached",
layer1,
maplibreMap.style!!.getLayer("layer1")
)
}
}
@Test
fun testLayerSkippedIfAdditionAboveFails() {
val layer1 = mockk<SymbolLayer>(relaxed = true)
every { layer1.id } returns "layer1"
val layer2 = mockk<SymbolLayer>(relaxed = true)
every { layer2.id } returns "layer1" // same ID
val builder = Style.Builder().withLayer(layer1)
maplibreMap.setStyle(builder)
maplibreMap.notifyStyleLoaded()
every {
nativeMapView.addLayerAbove(
any(),
""
)
} throws CannotAddLayerException("Duplicate ID")
try {
maplibreMap.style!!.addLayerAbove(layer2, "")
} catch (ex: Exception) {
Assert.assertEquals(
"Layer that failed to be added shouldn't be cached",
layer1,
maplibreMap.style!!.getLayer("layer1")
)
}
}
@Test
fun testLayerSkippedIfAdditionAtFails() {
val layer1 = mockk<SymbolLayer>(relaxed = true)
every { layer1.id } returns "layer1"
val layer2 = mockk<SymbolLayer>(relaxed = true)
every { layer2.id } returns "layer1" // same ID
val builder = Style.Builder().withLayer(layer1)
maplibreMap.setStyle(builder)
maplibreMap.notifyStyleLoaded()
every { nativeMapView.addLayerAt(any(), 5) } throws CannotAddLayerException("Duplicate ID")
try {
maplibreMap.style!!.addLayerAt(layer2, 5)
} catch (ex: Exception) {
Assert.assertEquals(
"Layer that failed to be added shouldn't be cached",
layer1,
maplibreMap.style!!.getLayer("layer1")
)
}
}
}

View File

@@ -0,0 +1,210 @@
package org.maplibre.android.maps
import android.os.Looper.getMainLooper
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.camera.CameraUpdateFactory
import org.maplibre.android.geometry.LatLng
import io.mockk.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
import org.robolectric.shadows.ShadowLooper
@RunWith(RobolectricTestRunner::class)
class TransformTest {
private lateinit var mapView: MapView
private lateinit var nativeMapView: NativeMap
private lateinit var transform: Transform
private lateinit var cameraChangeDispatcher: CameraChangeDispatcher
private lateinit var mainLooper: ShadowLooper
@Before
fun setup() {
cameraChangeDispatcher = spyk()
mapView = mockk()
nativeMapView = mockk()
mainLooper = shadowOf(getMainLooper())
transform = Transform(mapView, nativeMapView, cameraChangeDispatcher)
every { nativeMapView.isDestroyed } returns false
every { nativeMapView.cameraPosition } returns CameraPosition.DEFAULT
every { nativeMapView.cancelTransitions() } answers {}
every { nativeMapView.jumpTo(any(), any(), any(), any(), any()) } answers {}
every { nativeMapView.easeTo(any(), any(), any(), any(), any(), any(), any()) } answers {}
every { nativeMapView.flyTo(any(), any(), any(), any(), any(), any()) } answers {}
every { nativeMapView.minZoom = any() } answers {}
every { nativeMapView.maxZoom = any() } answers {}
every { nativeMapView.minPitch = any() } answers {}
every { nativeMapView.maxPitch = any() } answers {}
}
@Test
fun testMoveCamera() {
val maplibreMap = mockk<MapLibreMap>()
every { maplibreMap.cameraPosition } answers { CameraPosition.DEFAULT }
val callback = mockk<MapLibreMap.CancelableCallback>()
every { callback.onFinish() } answers {}
val target = LatLng(1.0, 2.0)
val expected = CameraPosition.Builder().target(target).build()
val update = CameraUpdateFactory.newCameraPosition(expected)
transform.cameraPosition
every { nativeMapView.cameraPosition } returns expected
transform.moveCamera(maplibreMap, update, callback)
mainLooper.idle()
verify { cameraChangeDispatcher.onCameraMove() }
verify { nativeMapView.jumpTo(target, -1.0, -1.0, -1.0, null) }
verify { callback.onFinish() }
}
@Test
fun testMoveCameraToSamePosition() {
val maplibreMap = mockk<MapLibreMap>()
every { maplibreMap.cameraPosition } answers { CameraPosition.DEFAULT }
val callback = mockk<MapLibreMap.CancelableCallback>()
every { callback.onFinish() } answers {}
val expected = CameraPosition.DEFAULT
val update = CameraUpdateFactory.newCameraPosition(expected)
transform.moveCamera(maplibreMap, update, null) // Initialize camera position
transform.moveCamera(maplibreMap, update, callback)
verify(exactly = 1, verifyBlock = { nativeMapView.jumpTo(any(), any(), any(), any(), any()) })
verify { callback.onFinish() }
}
@Test
fun testEaseCamera() {
val maplibreMap = mockk<MapLibreMap>()
every { maplibreMap.cameraPosition } answers { CameraPosition.DEFAULT }
every { mapView.addOnCameraDidChangeListener(any()) } answers { transform.onCameraDidChange(true) }
every { mapView.removeOnCameraDidChangeListener(any()) } answers {}
val callback = mockk<MapLibreMap.CancelableCallback>()
every { callback.onFinish() } answers {}
val target = LatLng(1.0, 2.0)
val expected = CameraPosition.Builder().target(target).build()
val update = CameraUpdateFactory.newCameraPosition(expected)
transform.easeCamera(maplibreMap, update, 100, false, callback)
mainLooper.idle()
verify { nativeMapView.easeTo(target, -1.0, -1.0, -1.0, null, 100, false) }
verify { callback.onFinish() }
}
@Test
fun testEaseCameraToSamePosition() {
val maplibreMap = mockk<MapLibreMap>()
every { maplibreMap.cameraPosition } answers { CameraPosition.DEFAULT }
val callback = mockk<MapLibreMap.CancelableCallback>()
every { callback.onFinish() } answers {}
val expected = CameraPosition.DEFAULT
val update = CameraUpdateFactory.newCameraPosition(expected)
transform.moveCamera(maplibreMap, update, null)
transform.easeCamera(maplibreMap, update, 100, false, callback)
verify(exactly = 0, verifyBlock = { nativeMapView.easeTo(any(), any(), any(), any(), any(), any(), any()) })
verify { callback.onFinish() }
}
@Test
fun testAnimateCamera() {
val maplibreMap = mockk<MapLibreMap>()
every { maplibreMap.cameraPosition } answers { CameraPosition.DEFAULT }
every { mapView.addOnCameraDidChangeListener(any()) } answers { transform.onCameraDidChange(true) }
every { mapView.removeOnCameraDidChangeListener(any()) } answers {}
val callback = mockk<MapLibreMap.CancelableCallback>()
every { callback.onFinish() } answers {}
val target = LatLng(1.0, 2.0)
val expected = CameraPosition.Builder().target(target).build()
val update = CameraUpdateFactory.newCameraPosition(expected)
transform.animateCamera(maplibreMap, update, 100, callback)
mainLooper.idle()
verify { nativeMapView.flyTo(target, -1.0, -1.0, -1.0, null, 100) }
verify { callback.onFinish() }
}
@Test
fun testAnimateCameraToSamePosition() {
val maplibreMap = mockk<MapLibreMap>()
every { maplibreMap.cameraPosition } answers { CameraPosition.DEFAULT }
val callback = mockk<MapLibreMap.CancelableCallback>()
every { callback.onFinish() } answers {}
val expected = CameraPosition.DEFAULT
val update = CameraUpdateFactory.newCameraPosition(expected)
transform.moveCamera(maplibreMap, update, null)
transform.animateCamera(maplibreMap, update, 100, callback)
verify(exactly = 0, verifyBlock = { nativeMapView.flyTo(any(), any(), any(), any(), any(), any()) })
verify { callback.onFinish() }
}
@Test
fun testMinZoom() {
transform.minZoom = 10.0
verify { nativeMapView.minZoom = 10.0 }
}
@Test
fun testMaxZoom() {
transform.maxZoom = 10.0
verify { nativeMapView.maxZoom = 10.0 }
}
@Test
fun testMinPitch() {
transform.minPitch = 10.0
verify { nativeMapView.minPitch = 10.0 }
}
@Test
fun testMaxPitch() {
transform.maxPitch = 10.0
verify { nativeMapView.maxPitch = 10.0 }
}
@Test
fun testCancelNotInvokedFromOnFinish() {
val slot = slot<MapView.OnCameraDidChangeListener>()
every { mapView.addOnCameraDidChangeListener(capture(slot)) } answers { slot.captured.onCameraDidChange(true) }
every { mapView.removeOnCameraDidChangeListener(any()) } answers {}
// regression test for https://github.com/mapbox/mapbox-gl-native/issues/13735
val maplibreMap = mockk<MapLibreMap>()
every { maplibreMap.cameraPosition } answers { CameraPosition.DEFAULT }
val target = LatLng(1.0, 2.0)
val expected = CameraPosition.Builder().target(target).build()
val callback = object : MapLibreMap.CancelableCallback {
override fun onCancel() {
throw IllegalStateException("onCancel shouldn't be called from onFinish")
}
override fun onFinish() {
transform.animateCamera(maplibreMap, CameraUpdateFactory.newCameraPosition(expected), 500, null)
}
}
transform.animateCamera(maplibreMap, CameraUpdateFactory.newCameraPosition(expected), 500, callback)
}
}

View File

@@ -0,0 +1,726 @@
package org.maplibre.android.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 org.maplibre.android.camera.CameraPosition
import org.maplibre.android.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 maplibreMapOptions: MapLibreMapOptions? = 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)
}
}

View File

@@ -0,0 +1,54 @@
package org.maplibre.android.module.http
import org.maplibre.android.MapLibreInjector
import org.maplibre.android.http.HttpRequestUrl
import org.maplibre.android.utils.ConfigUtils
import io.mockk.mockk
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class HttpRequestUrlTest {
@Before
fun setUp() {
MapLibreInjector.inject(mockk(relaxed = true), "pk.foobar", ConfigUtils.getMockedOptions())
}
@Test
fun testOfflineFlagMapboxCom() {
val expected = "http://mapbox.com/path/of/no/return.pbf?offline=true"
val actual = HttpRequestUrl.buildResourceUrl("mapbox.com", "http://mapbox.com/path/of/no/return.pbf", 0, true)
assertEquals(expected, actual)
}
@Test
fun testOfflineFlagMapboxCn() {
val expected = "http://mapbox.cn/path/of/no/return.pbf?offline=true"
val actual = HttpRequestUrl.buildResourceUrl("mapbox.cn", "http://mapbox.cn/path/of/no/return.pbf", 0, true)
assertEquals(expected, actual)
}
@Test
fun testOfflineFlagInvalidHost() {
val expected = "http://foobar.com/path/of/no/return.pbf"
val actual = HttpRequestUrl.buildResourceUrl("foobar.com", "http://foobar.com/path/of/no/return.pbf", 0, true)
assertEquals(expected, actual)
}
@Test
fun testOnlineInvalidHost() {
val expected = "http://foobar.com/path/of/no/return.pbf"
val actual = HttpRequestUrl.buildResourceUrl("foobar.com", "http://foobar.com/path/of/no/return.pbf", 0, false)
assertEquals(expected, actual)
}
@After
fun tearDown() {
MapLibreInjector.clear()
}
}

View File

@@ -0,0 +1,38 @@
package org.maplibre.android.module.http
import org.maplibre.android.MapLibreInjector
import org.maplibre.android.utils.ConfigUtils
import io.mockk.mockk
import okhttp3.OkHttpClient
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class HttpRequestUtilTest {
@Test
fun replaceHttpClient() {
MapLibreInjector.inject(mockk(relaxed = true), "", ConfigUtils.getMockedOptions())
assertEquals(HttpRequestImpl.DEFAULT_CLIENT, HttpRequestImpl.client)
val httpMock = mockk<OkHttpClient>()
HttpRequestUtil.setOkHttpClient(httpMock)
assertEquals(
"Http client should have set to the mocked client",
httpMock,
HttpRequestImpl.client
)
HttpRequestUtil.setOkHttpClient(null)
assertEquals(
"Http client should have been reset to the default client",
HttpRequestImpl.DEFAULT_CLIENT,
HttpRequestImpl.client
)
MapLibreInjector.clear()
}
}

View File

@@ -0,0 +1,22 @@
package org.maplibre.android.utils
import android.graphics.Color
import org.junit.Assert
import org.junit.Test
class ColorUtilsTest {
@Test
fun rgbaToColor_decimalComponent() {
val input = "rgba(255,128.0000952303,0,0.7)"
val result = ColorUtils.rgbaToColor(input)
Assert.assertEquals(Color.argb(255, 128, 0, (0.7 * 255).toInt()), result)
}
@Test
fun rgbaToColor_decimalComponent_floor() {
val input = "rgba(255,128.70123,0,0.7)"
val result = ColorUtils.rgbaToColor(input)
Assert.assertEquals(Color.argb(255, 128, 0, (0.7 * 255).toInt()), result)
}
}

View File

@@ -0,0 +1,46 @@
package org.maplibre.android.utils
import org.maplibre.android.util.DefaultStyle
import org.maplibre.android.util.TileServerOptions
class ConfigUtils {
companion object {
@JvmStatic
fun getMockedOptions(): TileServerOptions {
val defaultStyles = arrayOf(
DefaultStyle("maptiler://maps/streets", "Streets", 1),
DefaultStyle("maptiler://maps/outdoor", "Outdoor", 1),
DefaultStyle("maptiler://maps/basic", "Basic", 1),
DefaultStyle("maptiler://maps/bright", "Bright", 1),
DefaultStyle("maptiler://maps/pastel", "Pastel", 1),
DefaultStyle("maptiler://maps/hybrid", "Satellite Hybrid", 1),
DefaultStyle("maptiler://maps/topo", "Satellite Topo", 1)
)
val defaultStyle = defaultStyles[0].name
return TileServerOptions(
"https://api.maptiler.com",
"maptiler",
"{path}",
"sources",
null,
"/maps{path}/style.json",
"maps",
null,
"/maps{path}",
"sprites",
null,
"/fonts{path}",
"fonts",
null,
"{path}",
"tiles",
null,
"key",
true,
defaultStyle,
defaultStyles
)
}
}
}

View File

@@ -0,0 +1,169 @@
package org.maplibre.android.utils
import android.os.Parcel
import android.os.Parcelable
import org.junit.Assert.*
import org.mockito.ArgumentMatchers
import org.mockito.Mockito.*
import org.mockito.stubbing.Answer
object MockParcel {
@JvmOverloads
fun obtain(`object`: Parcelable, describeContentsValue: Int = 0): Parcelable? {
testDescribeContents(`object`, describeContentsValue)
testParcelableArray(`object`)
return testParcelable(`object`)
}
fun testParcelable(`object`: Parcelable): Parcelable? {
val parcel = ParcelMocker.obtain(`object`)
`object`.writeToParcel(parcel, 0)
parcel.setDataPosition(0)
return try {
val field = `object`.javaClass.getDeclaredField("CREATOR")
field.isAccessible = true
val creatorClass = field.type
val fieldValue = field[`object`]
val myMethod = creatorClass.getDeclaredMethod("createFromParcel", Parcel::class.java)
myMethod.invoke(fieldValue, parcel) as Parcelable
} catch (exception: Exception) {
null
}
}
fun testParcelableArray(`object`: Parcelable) {
val objects = arrayOf(`object`)
val parcel = ParcelMocker.obtain(objects)
parcel.writeParcelableArray(objects, 0)
parcel.setDataPosition(0)
val parcelableArray = parcel.readParcelableArray(`object`.javaClass.classLoader)
assertArrayEquals("parcel should match initial object", objects, parcelableArray)
}
fun testDescribeContents(`object`: Parcelable, describeContentsValue: Int) {
if (describeContentsValue == 0) {
assertEquals("""
Expecting a describeContents() value of 0 for a ${`object`.javaClass.simpleName} instance.
You can provide a different value for describeContentValue through the obtain method.""",
0,
`object`.describeContents().toLong())
} else {
assertEquals("Expecting a describeContents() value of $describeContentsValue",
describeContentsValue.toLong(),
`object`.describeContents().toLong())
}
}
private class ParcelMocker private constructor(private val `object`: Any) {
private val objects: MutableList<Any>
private val mockedParcel: Parcel
private var position = 0
init {
mockedParcel = mock(Parcel::class.java)
objects = ArrayList()
setupMock()
}
private fun setupMock() {
setupWrites()
setupReads()
setupOthers()
}
private fun setupWrites() {
val writeValueAnswer: Answer<Void> = Answer { invocation ->
val parameter = invocation.arguments[0]
objects.add(parameter)
null
}
val writeArrayAnswer: Answer<Void> = Answer { invocation ->
val parameters = invocation.arguments[0] as Array<Any>
objects.add(parameters.size)
for (o in parameters) {
objects.add(o)
}
null
}
val writeIntArrayAnswer: Answer<Void> = Answer { invocation ->
val parameters = invocation.arguments[0] as IntArray
if (parameters != null) {
objects.add(parameters.size)
for (o in parameters) {
objects.add(o)
}
} else {
objects.add(-1)
}
null
}
doAnswer(writeValueAnswer).`when`(mockedParcel).writeByte(ArgumentMatchers.anyByte())
doAnswer(writeValueAnswer).`when`(mockedParcel).writeLong(ArgumentMatchers.anyLong())
doAnswer(writeValueAnswer).`when`(mockedParcel).writeString(ArgumentMatchers.anyString())
doAnswer(writeValueAnswer).`when`(mockedParcel).writeInt(ArgumentMatchers.anyInt())
doAnswer(writeIntArrayAnswer).`when`(mockedParcel).writeIntArray(ArgumentMatchers.any(IntArray::class.java))
doAnswer(writeValueAnswer).`when`(mockedParcel).writeDouble(ArgumentMatchers.anyDouble())
doAnswer(writeValueAnswer).`when`(mockedParcel).writeFloat(ArgumentMatchers.anyFloat())
doAnswer(writeValueAnswer).`when`(mockedParcel).writeParcelable(ArgumentMatchers.any(Parcelable::class.java), ArgumentMatchers.eq(0))
doAnswer(writeArrayAnswer).`when`(mockedParcel).writeParcelableArray(ArgumentMatchers.any(Array<Parcelable>::class.java), ArgumentMatchers.eq(0))
}
private fun setupReads() {
`when`(mockedParcel.readInt()).then { objects[position++] as Int }
`when`(mockedParcel.readByte()).thenAnswer { objects[position++] as Byte }
`when`(mockedParcel.readLong()).thenAnswer { objects[position++] as Long }
`when`(mockedParcel.readString()).thenAnswer { objects[position++] as String }
`when`(mockedParcel.readDouble()).thenAnswer { objects[position++] as Double }
`when`(mockedParcel.readFloat()).thenAnswer { objects[position++] as Float }
`when`<Any?>(mockedParcel.readParcelable(Parcelable::class.java.classLoader)).thenAnswer { objects[position++] as Parcelable }
`when`(mockedParcel.readParcelableArray(Parcelable::class.java.classLoader)).thenAnswer {
val size = objects[position++] as Int
val field = `object`.javaClass.getDeclaredField("CREATOR")
field.isAccessible = true
val creatorClass = field.type
val fieldValue = field[`object`]
val myMethod = creatorClass.getDeclaredMethod("newArray", Int::class.javaPrimitiveType)
val array = myMethod.invoke(fieldValue, size) as Array<Any>
for (i in 0 until size) {
array[i] = objects[position++]
}
array
}
`when`(mockedParcel.createIntArray()).then(Answer {
val size = objects[position++] as Int
if (size == -1) {
return@Answer null
}
val array = IntArray(size)
for (i in 0 until size) {
array[i] = objects[position++] as Int
}
array
})
}
private fun setupOthers() {
doAnswer { invocation ->
position = invocation.arguments[0] as Int
null
}.`when`(mockedParcel).setDataPosition(ArgumentMatchers.anyInt())
}
companion object {
fun obtain(target: Parcelable): Parcel {
val parcel = ParcelMocker(target).mockedParcel
target.writeToParcel(parcel, 0)
parcel.setDataPosition(0)
return parcel
}
fun obtain(targets: Array<Parcelable>): Parcel {
require(targets.size != 0) { "The passed argument may not be empty" }
val parcel = ParcelMocker(targets[0]).mockedParcel
parcel.writeParcelableArray(targets, 0)
parcel.setDataPosition(0)
return parcel
}
}
}
}

View File

@@ -0,0 +1,14 @@
package org.maplibre.testUtils
const val DELTA_FLOAT: Float = 1e-15f
const val DELTA_DOUBLE: Double = 1e-15
object Assert {
fun assertEquals(expected: Double, actual: Double) {
org.junit.Assert.assertEquals(expected, actual, DELTA_DOUBLE)
}
fun assertEquals(expected: Float, actual: Float) {
org.junit.Assert.assertEquals(expected, actual, DELTA_FLOAT)
}
}