calculator: add tests for keypad, graph, converter, widgets and UI
- Commit
3befaa9ed4ebd9d4c0868278961fecad018bb13d- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-07 06:41 UTC (29 days ago)
- Parents
a0857a4
Merged INSTRUCTION coverage rises from 38.16% (10110/26491) to 85.20% (22570/26491), measured with gslot ./gradlew :calculator:createMergedCoverageReport. New tests (12 files, ~70 tests): CalculatorTab unit previews, output-unit selection, memory register and instants; GraphTab function CRUD, markers, viewport transforms and both action adapters; expression coverage for reciprocal/hyperbolic/single/pair functions and quantity remainder/division; UnitConverterTab and CalculatorViewModel under Robolectric including the offline currency-failure state; Compose screens under Robolectric (keypad with 2nd-function keys, display column with history and unit chips, graph screen with native- graphics canvas capture and function-row interactions, unit converter with category/unit dropdowns and currency error retry, unit picker with time picker, landscape and expanded layouts, navigation and widget settings); Glance widget key actions against real Glance state (append/evaluate/clear/backspace, category-list toggle) and widget provideGlance entry points. Test-only dependency: androidx.work:work-testing (existing androidx-work-testing catalog entry). Widget action tests use the synchronous test WorkManager; a cross-sandbox DataStore write in SelectUnitsCategoryAction suspended forever when an earlier test class in the same JVM had claimed the shared preferences file, so that one action is covered only through its state-toggle sibling and the converter tab's persistence tests (see finish report). Verified: gslot ./gradlew :calculator:testDevUnitTest and :createMergedCoverageReport pass (full unit suite green). (cherry picked from commit 5f22dee6dcd1da9628b781165aa8c3e00579895f)
Diff
calculator/build.gradle.kts
diff --git a/calculator/build.gradle.kts b/calculator/build.gradle.ktsindex a5bb587f09..d752376b72 100644--- a/calculator/build.gradle.kts+++ b/calculator/build.gradle.kts@@ -20,4 +20,5 @@ dependencies { // Live currency exchange rates fetched from api.maproj.org via the shared client. implementation(project(":library:network")) implementation(project(":library:widgets"))+ testImplementation(libs.androidx.work.testing) }
calculator/src/test/java/com/vayunmathur/calculator/NavigationAndActivityTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/NavigationAndActivityTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/NavigationAndActivityTest.ktnew file mode 100644index 0000000000..d9c2ced4fe--- /dev/null+++ b/calculator/src/test/java/com/vayunmathur/calculator/NavigationAndActivityTest.kt@@ -0,0 +1,72 @@+package com.vayunmathur.calculator++import android.content.Intent+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.calculator.widget.CalculatorWidgetSettingsActivity+import android.appwidget.AppWidgetManager+import kotlinx.serialization.json.Json+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class NavigationAndActivityTest {++ @Before fun setUp() {+ runCatching {+ androidx.work.testing.WorkManagerTestInitHelper.initializeTestWorkManager(+ ApplicationProvider.getApplicationContext(),+ )+ }+ }++ @Test fun routeSerializationRoundTrips() {+ val json = Json+ assertEquals(+ Route.Graph,+ json.decodeFromString(Route.serializer(), json.encodeToString(Route.serializer(), Route.Graph)),+ )+ assertEquals(+ Route.Units,+ json.decodeFromString(Route.serializer(), json.encodeToString(Route.serializer(), Route.Units)),+ )+ }++ @Test fun mainActivityCreates() {+ val controller = Robolectric.buildActivity(MainActivity::class.java)+ controller.create().start().resume().visible()+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ assertTrue(!controller.get().isFinishing)+ controller.pause().stop().destroy()+ }++ @Test fun mainActivityWithUnitsIntentCreates() {+ val intent = Intent(+ ApplicationProvider.getApplicationContext(),+ MainActivity::class.java,+ ).putExtra(com.vayunmathur.calculator.widget.UnitsGlanceWidget.EXTRA_OPEN_UNITS, true)+ val controller = Robolectric.buildActivity(MainActivity::class.java, intent)+ controller.create().start().resume().visible()+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ assertTrue(!controller.get().isFinishing)+ // A second units deep-link arrives while running.+ controller.newIntent(intent)+ controller.pause().stop().destroy()+ }++ @Test fun widgetSettingsActivityWithIdShowsScreen() {+ val intent = Intent(+ ApplicationProvider.getApplicationContext(),+ CalculatorWidgetSettingsActivity::class.java,+ ).putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, 7)+ val controller = Robolectric.buildActivity(CalculatorWidgetSettingsActivity::class.java, intent)+ controller.create().start().resume()+ assertTrue(!controller.get().isFinishing)+ // The settings screen is set as content; pausing stops it cleanly.+ controller.pause().stop().destroy()+ }+}
calculator/src/test/java/com/vayunmathur/calculator/ui/CalculatorScreensComposeTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/ui/CalculatorScreensComposeTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/ui/CalculatorScreensComposeTest.ktnew file mode 100644index 0000000000..dca9b6c3f9--- /dev/null+++ b/calculator/src/test/java/com/vayunmathur/calculator/ui/CalculatorScreensComposeTest.kt@@ -0,0 +1,359 @@+package com.vayunmathur.calculator.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.hasContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextReplacement+import com.vayunmathur.calculator.util.AngleMode+import com.vayunmathur.calculator.util.CalculatorActions+import com.vayunmathur.calculator.util.CalculatorUiState+import com.vayunmathur.calculator.util.GraphActions+import com.vayunmathur.calculator.util.GraphFunction+import com.vayunmathur.calculator.util.GraphMarker+import com.vayunmathur.calculator.util.FeatureKind+import com.vayunmathur.calculator.util.GraphPoint+import com.vayunmathur.calculator.util.GraphUiState+import com.vayunmathur.calculator.util.HistoryEntry+import com.vayunmathur.calculator.util.UnitConverterActions+import com.vayunmathur.calculator.util.UnitConverterUiState+import com.vayunmathur.calculator.util.UnitRegistry+import androidx.compose.ui.graphics.Color+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class CalculatorScreensComposeTest {++ @get:Rule val rule = createComposeRule()++ // ---- Keypad rows (pure) ----++ @Test fun keypadRowsShapeAndAngleLabel() {+ val rad = buildCalculatorRows(AngleMode.RADIANS)+ assertEquals(8, rad.size)+ assertTrue(rad.all { it.size == 5 })+ assertEquals("RAD", rad[3][4].label)+ assertEquals("DEG", buildCalculatorRows(AngleMode.DEGREES)[3][4].label)+ assertEquals("=", rad[7][4].label)+ }++ @Test fun keyPressesDispatchToActions() {+ val appended = mutableListOf<String>()+ var evaluated = false+ var cleared = false+ val actions = object : CalculatorActions {+ override fun append(text: String) { appended += text }+ override fun evaluate() { evaluated = true }+ override fun clear() { cleared = true }+ }+ val rows = buildCalculatorRows(AngleMode.RADIANS)+ rows[4][0].onPress(actions) // 7+ rows[7][4].onPress(actions) // =+ rows[0][4].onPress(actions) // AC+ assertEquals(listOf("7"), appended)+ assertTrue(evaluated)+ assertTrue(cleared)+ // Second-function presses.+ assertEquals("asin(", run {+ rows[1][0].secondPress!!.invoke(actions); appended.last()+ })+ }++ // ---- Calculator screen ----++ private class RecordingActions : CalculatorActions {+ val appended = mutableListOf<String>()+ var evaluated = 0+ var usedHistory: HistoryEntry? = null+ override fun append(text: String) { appended += text }+ override fun evaluate() { evaluated++ }+ override fun useHistory(entry: HistoryEntry) { usedHistory = entry }+ }++ @Test fun calculatorScreenShowsInputPreviewAndKeys() {+ val actions = RecordingActions()+ rule.setContent {+ CalculatorScreen(+ state = CalculatorUiState(input = "2+3", preview = "5"),+ actions = actions,+ )+ }+ rule.onNodeWithText("2+3").assertIsDisplayed()+ rule.onAllNodesWithText("5")[0].assertIsDisplayed()+ rule.onNodeWithText("7").assertIsDisplayed()+ rule.onNodeWithText("7").performClick()+ assertEquals(listOf("7"), actions.appended)+ rule.onNodeWithText("=").performClick()+ assertEquals(1, actions.evaluated)+ }++ @Test fun calculatorScreenSecondKeySwapsLabels() {+ val actions = RecordingActions()+ rule.setContent {+ CalculatorScreen(state = CalculatorUiState(), actions = actions)+ }+ rule.onNodeWithText("2nd").performClick()+ rule.onNodeWithText("sin⁻¹").assertIsDisplayed()+ rule.onNodeWithText("sin⁻¹").performClick()+ assertEquals(listOf("asin("), actions.appended)+ }++ @Test fun calculatorScreenWithHistoryAndMemory() {+ val actions = RecordingActions()+ rule.setContent {+ CalculatorScreen(+ state = CalculatorUiState(+ input = "10",+ preview = "10",+ memory = 5.0,+ history = listOf(HistoryEntry("2+3", "5")),+ ),+ actions = actions,+ )+ }+ rule.onAllNodesWithText("10")[0].assertIsDisplayed()+ }++ @Test fun calculatorScreenUnitPickerSeededOpen() {+ val actions = RecordingActions()+ rule.setContent {+ CalculatorScreen(+ state = CalculatorUiState(unitCategories = UnitRegistry.categories),+ actions = actions,+ initialShowUnitPicker = true,+ )+ }+ rule.onNodeWithText("Insert unit").assertIsDisplayed()+ rule.onNodeWithText("Length").assertIsDisplayed()+ }++ // ---- Unit picker sheet + date helpers ----++ @Test fun unitPickerChipAppendsToken() {+ val actions = RecordingActions()+ var dismissed = false+ rule.setContent {+ UnitPickerSheet(+ state = CalculatorUiState(unitCategories = UnitRegistry.categories),+ actions = actions,+ onDismiss = { dismissed = true },+ )+ }+ rule.onNodeWithText("Length").assertIsDisplayed()+ // First category (Length) units are shown; tap the metre chip by symbol.+ rule.onAllNodesWithText("m")[0].performClick()+ assertEquals(listOf("m"), actions.appended)+ assertTrue(dismissed)+ }++ @Test fun dateTimeHelpersConvertUtcMidnightToLocal() {+ // 2024-01-15T00:00:00Z+ val utcMidnight = 1705276800000L+ val local = localMidnightSeconds(utcMidnight)+ val zoned = java.time.Instant.ofEpochSecond(local).atZone(java.time.ZoneId.systemDefault())+ assertEquals(15, zoned.dayOfMonth)+ assertEquals(0, zoned.hour)+ val combined = combineDateTimeSeconds(utcMidnight, 13, 30)+ val combinedZoned = java.time.Instant.ofEpochSecond(combined).atZone(java.time.ZoneId.systemDefault())+ assertEquals(13, combinedZoned.hour)+ assertEquals(30, combinedZoned.minute)+ val today = java.time.Instant.ofEpochSecond(todayAtTimeSeconds(9, 15))+ .atZone(java.time.ZoneId.systemDefault())+ assertEquals(java.time.LocalDate.now(), today.toLocalDate())+ assertEquals(9, today.hour)+ }++ // ---- Graph screen ----++ @Test fun graphScreenShowsFunctionEditorAndAngleChip() {+ var added = 0+ val actions = object : GraphActions {+ override fun addFunction() { added++ }+ }+ rule.setContent {+ GraphScreen(+ state = GraphUiState(+ functions = listOf(GraphFunction(id = 0, text = "x", color = Color.Blue)),+ ),+ actions = actions,+ )+ }+ rule.onNodeWithText("RAD").assertIsDisplayed()+ rule.onNodeWithText("Add function").assertIsDisplayed()+ rule.onNodeWithText("x").assertExists()+ rule.onNodeWithText("Add function").performClick()+ assertEquals(1, added)+ }++ @Test fun graphScreenEditsFunctionText() {+ var edited: Pair<Long, String>? = null+ val actions = object : GraphActions {+ override fun updateFunction(id: Long, text: String) { edited = id to text }+ }+ rule.setContent {+ GraphScreen(+ state = GraphUiState(+ functions = listOf(GraphFunction(id = 3, text = "x", color = Color.Red)),+ ),+ actions = actions,+ )+ }+ rule.onNodeWithText("x").performTextReplacement("x^2")+ assertEquals(3L to "x^2", edited)+ }++ @Test fun graphScreenWithMarkerAndPolarFunction() {+ rule.setContent {+ GraphScreen(+ state = GraphUiState(+ functions = listOf(+ GraphFunction(id = 0, text = "x^2", color = Color.Blue),+ GraphFunction(id = 1, text = "sin", color = Color.Red, polar = true, enabled = false),+ ),+ markers = listOf(GraphMarker(GraphPoint(0.0, 0.0), FeatureKind.ROOT, listOf(0))),+ angleMode = AngleMode.DEGREES,+ ),+ actions = GraphActions.Noop,+ )+ }+ rule.onNodeWithText("DEG").assertIsDisplayed()+ rule.onNodeWithText("r=").assertIsDisplayed()+ rule.onNodeWithText("y=").assertIsDisplayed()+ }++ @Test fun graphFunctionRowInteractions() {+ var polarToggled = -1L+ var removed = -1L+ val actions = object : GraphActions {+ override fun togglePolar(id: Long) { polarToggled = id }+ override fun removeFunction(id: Long) { removed = id }+ }+ rule.setContent {+ GraphScreen(+ state = GraphUiState(+ functions = listOf(GraphFunction(id = 5, text = "x", color = Color.Blue)),+ ),+ actions = actions,+ )+ }+ rule.onNodeWithText("y=").performClick()+ assertEquals(5L, polarToggled)+ assertEquals(-1L, removed)+ }++ // ---- Unit converter screen ----++ @Test fun converterScreenShowsResultAndCategories() {+ rule.setContent {+ UnitConverterScreen(+ state = UnitConverterUiState(+ categories = UnitRegistry.categories,+ selectedCategoryIndex = 0,+ fromToken = UnitRegistry.categories[0].units[0].token,+ toToken = UnitRegistry.categories[0].units[1].token,+ inputText = "1",+ outputText = "100",+ ),+ actions = UnitConverterActions.Noop,+ )+ }+ rule.onNodeWithText("Units").assertIsDisplayed()+ rule.onNodeWithText("Length").assertIsDisplayed()+ rule.onNodeWithText("Value").assertIsDisplayed()+ }++ @Test fun converterScreenEditsInput() {+ var input: String? = null+ val actions = object : UnitConverterActions {+ override fun setConverterInput(text: String) { input = text }+ }+ rule.setContent {+ UnitConverterScreen(+ state = UnitConverterUiState(+ categories = UnitRegistry.categories,+ selectedCategoryIndex = 0,+ fromToken = UnitRegistry.categories[0].units[0].token,+ toToken = UnitRegistry.categories[0].units[1].token,+ inputText = "1",+ outputText = "",+ ),+ actions = actions,+ )+ }+ rule.onNodeWithText("1").performTextReplacement("250")+ assertEquals("250", input)+ }++ @Test fun converterCurrencyLoadingAndErrorStates() {+ val currency = com.vayunmathur.calculator.util.UnitCategory("Currency", emptyList(), inEquations = false)+ rule.setContent {+ UnitConverterScreen(+ state = UnitConverterUiState(+ categories = listOf(currency),+ selectedCategoryIndex = 0,+ isCurrencyCategory = true,+ currencyLoading = true,+ ),+ actions = UnitConverterActions.Noop,+ )+ }+ rule.onNodeWithText("Currency").assertIsDisplayed()+ }++ @Test fun converterUnitDropdownSelectsUnit() {+ var fromToken: String? = null+ val actions = object : UnitConverterActions {+ override fun setFrom(token: String) { fromToken = token }+ }+ rule.setContent {+ UnitConverterScreen(+ state = UnitConverterUiState(+ categories = UnitRegistry.categories,+ selectedCategoryIndex = 0,+ fromToken = "m",+ toToken = "cm",+ inputText = "1",+ outputText = "100",+ ),+ actions = actions,+ )+ }+ // The From dropdown shows the selected symbol; opening it lists units.+ rule.onAllNodesWithText("m")[0].performClick()+ rule.onNodeWithText("km — Kilometre").assertIsDisplayed()+ rule.onNodeWithText("km — Kilometre").performClick()+ assertEquals("km", fromToken)+ }++ @Test fun converterCategoryDropdownSelects() {+ var selected = -1+ val actions = object : UnitConverterActions {+ override fun selectCategory(index: Int) { selected = index }+ }+ rule.setContent {+ UnitConverterScreen(+ state = UnitConverterUiState(+ categories = UnitRegistry.categories,+ selectedCategoryIndex = 0,+ fromToken = UnitRegistry.categories[0].units[0].token,+ toToken = UnitRegistry.categories[0].units[1].token,+ inputText = "1",+ outputText = "1",+ ),+ actions = actions,+ )+ }+ rule.onNodeWithText("Length").performClick()+ rule.onNodeWithText("Mass").assertIsDisplayed()+ rule.onNodeWithText("Mass").performClick()+ assertEquals(1, selected)+ }+}
calculator/src/test/java/com/vayunmathur/calculator/ui/FinalCoverageComposeTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/ui/FinalCoverageComposeTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/ui/FinalCoverageComposeTest.ktnew file mode 100644index 0000000000..2c17b237cc--- /dev/null+++ b/calculator/src/test/java/com/vayunmathur/calculator/ui/FinalCoverageComposeTest.kt@@ -0,0 +1,82 @@+package com.vayunmathur.calculator.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.onRoot+import com.vayunmathur.calculator.util.CalculatorUiState+import com.vayunmathur.calculator.util.UnitRegistry+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode+import kotlin.test.Test+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class FinalCoverageComposeTest {++ @get:Rule val rule = createComposeRule()++ @Test fun graphScreenCaptureForcesCanvasDraw() {+ rule.setContent {+ GraphScreen(+ state = com.vayunmathur.calculator.util.GraphUiState(+ functions = listOf(+ com.vayunmathur.calculator.util.GraphFunction(+ id = 0, text = "x^2", color = androidx.compose.ui.graphics.Color.Blue,+ ),+ ),+ markers = listOf(+ com.vayunmathur.calculator.util.GraphMarker(+ com.vayunmathur.calculator.util.GraphPoint(0.0, 0.0),+ com.vayunmathur.calculator.util.FeatureKind.ROOT,+ listOf(0),+ ),+ ),+ ),+ actions = com.vayunmathur.calculator.util.GraphActions.Noop,+ )+ }+ val bitmap = rule.onRoot().captureToImage()+ assertTrue(bitmap.width > 0 && bitmap.height > 0)+ }++ @Test fun unitPickerTimeFlowOpensTimePicker() {+ rule.setContent {+ UnitPickerSheet(+ state = CalculatorUiState(unitCategories = UnitRegistry.categories),+ actions = com.vayunmathur.calculator.util.CalculatorActions.Noop,+ onDismiss = {},+ )+ }+ rule.onNodeWithText("Absolute time").performClick()+ rule.onAllNodesWithText("Time")[1].performClick()+ rule.onNodeWithText("Select time").assertIsDisplayed()+ rule.onNodeWithText("Cancel").performClick()+ }++}++@RunWith(RobolectricTestRunner::class)+@Config(qualifiers = "w1200dp-h800dp")+class ExpandedCalculatorScreenTest {++ @get:Rule val rule = createComposeRule()++ @Test fun expandedWindowUsesSideBySideLayout() {+ rule.setContent {+ CalculatorScreen(+ state = CalculatorUiState(input = "6*7", preview = "42"),+ actions = com.vayunmathur.calculator.util.CalculatorActions.Noop,+ )+ }+ rule.onNodeWithText("6×7").assertIsDisplayed()+ rule.onNodeWithText("7").assertIsDisplayed()+ }+}
calculator/src/test/java/com/vayunmathur/calculator/ui/GraphDrawAndSettingsTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/ui/GraphDrawAndSettingsTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/ui/GraphDrawAndSettingsTest.ktnew file mode 100644index 0000000000..f76b0ffc10--- /dev/null+++ b/calculator/src/test/java/com/vayunmathur/calculator/ui/GraphDrawAndSettingsTest.kt@@ -0,0 +1,71 @@+package com.vayunmathur.calculator.ui++import androidx.compose.ui.graphics.Color+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.click+import com.vayunmathur.calculator.util.FeatureKind+import com.vayunmathur.calculator.util.GraphActions+import com.vayunmathur.calculator.util.GraphFunction+import com.vayunmathur.calculator.util.GraphMarker+import com.vayunmathur.calculator.util.GraphPoint+import com.vayunmathur.calculator.util.GraphUiState+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.GraphicsMode+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class GraphDrawTest {++ @get:Rule val rule = createComposeRule()++ @Test fun graphCanvasDrawsCurvesGridAndMarkers() {+ var tapped: GraphPoint? = null+ var viewSize: Pair<Float, Float>? = null+ val actions = object : GraphActions {+ override fun tapGraph(at: GraphPoint, radius: Double) { tapped = at }+ override fun setViewSize(widthPx: Float, heightPx: Float) { viewSize = widthPx to heightPx }+ }+ rule.setContent {+ GraphScreen(+ state = GraphUiState(+ functions = listOf(+ GraphFunction(id = 0, text = "x^2", color = Color.Blue),+ GraphFunction(id = 1, text = "sin(x)", color = Color.Red, polar = true),+ ),+ markers = listOf(GraphMarker(GraphPoint(0.0, 0.0), FeatureKind.ROOT, listOf(0))),+ ),+ actions = actions,+ )+ }+ rule.onNodeWithText("Add function").assertIsDisplayed()+ assertTrue(viewSize != null)+ // Tapping the canvas reports a graph point near where the tap landed.+ rule.onRoot().performTouchInput { click(center) }+ rule.waitForIdle()+ assertTrue(tapped != null)+ }++ @Test fun graphScreenInDegreesDrawsWithAngleChip() {+ rule.setContent {+ GraphScreen(+ state = GraphUiState(+ functions = listOf(GraphFunction(id = 0, text = "cos(x)", color = Color.Green)),+ angleMode = com.vayunmathur.calculator.util.AngleMode.DEGREES,+ ),+ actions = GraphActions.Noop,+ )+ }+ rule.onNodeWithText("DEG").assertIsDisplayed()+ rule.onNodeWithText("Add function").assertIsDisplayed()+ }+}
calculator/src/test/java/com/vayunmathur/calculator/ui/KeypadDirectComposeTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/ui/KeypadDirectComposeTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/ui/KeypadDirectComposeTest.ktnew file mode 100644index 0000000000..07aca3684a--- /dev/null+++ b/calculator/src/test/java/com/vayunmathur/calculator/ui/KeypadDirectComposeTest.kt@@ -0,0 +1,82 @@+package com.vayunmathur.calculator.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import com.vayunmathur.calculator.util.AngleMode+import com.vayunmathur.calculator.util.CalculatorActions+import com.vayunmathur.calculator.util.CalculatorUiState+import com.vayunmathur.calculator.util.HistoryEntry+import com.vayunmathur.calculator.util.UnitRegistry+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals++@RunWith(RobolectricTestRunner::class)+class KeypadDirectComposeTest {++ @get:Rule val rule = createComposeRule()++ @Test fun displayColumnShowsHistoryUnitsAndHandlesTaps() {+ var used: HistoryEntry? = null+ var selectedUnit: String? = null+ val lengthUnits = UnitRegistry.unitsFor(com.vayunmathur.calculator.util.Dimension.LENGTH)+ val actions = object : CalculatorActions {+ override fun useHistory(entry: HistoryEntry) { used = entry }+ override fun selectOutputUnit(token: String) { selectedUnit = token }+ }+ rule.setContent {+ DisplayColumn(+ state = CalculatorUiState(+ input = "2km",+ preview = "2000 m",+ memory = 5.0,+ history = listOf(HistoryEntry("2+3", "5")),+ unitOptions = lengthUnits,+ selectedUnit = lengthUnits.firstOrNull { it.token == "m" },+ ),+ actions = actions,+ )+ }+ rule.onNodeWithText("2km").assertIsDisplayed()+ rule.onNodeWithText("2000 m").assertIsDisplayed()+ rule.onNodeWithContentDescription("2+3 equals 5").performClick()+ assertEquals(HistoryEntry("2+3", "5"), used)+ // Unit chips: centimetre chip selects cm.+ rule.onNodeWithText("cm").performClick()+ assertEquals("cm", selectedUnit)+ }++ @Test fun keypadColumnRendersAllRowsAndSecondToggle() {+ val appended = mutableListOf<String>()+ var toggles = 0+ val actions = object : CalculatorActions {+ override fun append(text: String) { appended += text }+ }+ rule.setContent {+ KeypadColumn(+ rows = buildCalculatorRows(AngleMode.RADIANS),+ actions = actions,+ second = true,+ onToggleSecond = { toggles++ },+ )+ }+ rule.onNodeWithText("sin⁻¹").assertIsDisplayed()+ rule.onNodeWithText("sin⁻¹").performClick()+ assertEquals(listOf("asin("), appended)+ rule.onNodeWithText("2nd").performClick()+ assertEquals(1, toggles)+ }++ @Test fun pageBindingsRenderWithViewModel() {+ val vm = com.vayunmathur.calculator.util.CalculatorViewModel(+ androidx.test.core.app.ApplicationProvider.getApplicationContext(),+ )+ rule.setContent { CalculatorPage(vm) }+ rule.onNodeWithText("7").assertIsDisplayed()+ }+}
calculator/src/test/java/com/vayunmathur/calculator/ui/LandscapeAndDialogsTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/ui/LandscapeAndDialogsTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/ui/LandscapeAndDialogsTest.ktnew file mode 100644index 0000000000..3d871fa158--- /dev/null+++ b/calculator/src/test/java/com/vayunmathur/calculator/ui/LandscapeAndDialogsTest.kt@@ -0,0 +1,110 @@+package com.vayunmathur.calculator.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import com.vayunmathur.calculator.util.AngleMode+import com.vayunmathur.calculator.util.CalculatorActions+import com.vayunmathur.calculator.util.CalculatorUiState+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class LandscapeAndDialogsTest {++ @get:Rule val rule = createComposeRule()++ @Test fun landscapeDisplayShowsEquationAndPreview() {+ rule.setContent {+ LandscapeDisplay(CalculatorUiState(input = "3*4", preview = "12"))+ }+ rule.onNodeWithText("3×4").assertIsDisplayed()+ rule.onNodeWithText("12").assertIsDisplayed()+ }++ @Test fun landscapeDisplayEmptyShowsZero() {+ rule.setContent { LandscapeDisplay(CalculatorUiState()) }+ rule.onNodeWithText("0").assertIsDisplayed()+ }++ @Test fun landscapeKeypadDispatchesKeys() {+ val appended = mutableListOf<String>()+ val actions = object : CalculatorActions {+ override fun append(text: String) { appended += text }+ }+ rule.setContent {+ LandscapeKeypad(+ rows = buildCalculatorRows(AngleMode.RADIANS),+ actions = actions,+ second = false,+ onToggleSecond = {},+ )+ }+ rule.onNodeWithText("7").assertIsDisplayed()+ rule.onNodeWithText("7").performClick()+ assertEquals(listOf("7"), appended)+ rule.onNodeWithText("sin").assertIsDisplayed()+ }++ @Test fun datePickerModalShowsOkAndCancel() {+ var dismissed = false+ rule.setContent {+ DatePickerModal(onDismiss = { dismissed = true }, onConfirm = {})+ }+ rule.onNodeWithText("OK").assertIsDisplayed()+ rule.onNodeWithText("Cancel").performClick()+ assertTrue(dismissed)+ }++ @Test fun timePickerModalConfirmReportsTime() {+ var confirmed: Pair<Int, Int>? = null+ rule.setContent {+ TimePickerModal(onDismiss = {}, onConfirm = { h, m -> confirmed = h to m })+ }+ rule.onNodeWithText("Select time").assertIsDisplayed()+ rule.onNodeWithText("OK").performClick()+ assertTrue(confirmed != null)+ }++ @Test fun unitPickerAbsoluteTimeTabOpensDatePicker() {+ rule.setContent {+ UnitPickerSheet(+ state = CalculatorUiState(+ unitCategories = com.vayunmathur.calculator.util.UnitRegistry.categories,+ ),+ actions = CalculatorActions.Noop,+ onDismiss = {},+ )+ }+ rule.onNodeWithText("Absolute time").performClick()+ rule.onNodeWithText("Date").assertIsDisplayed()+ rule.onNodeWithText("Date").performClick()+ // The material date picker dialog opens over the sheet.+ rule.onNodeWithText("Cancel").assertIsDisplayed()+ }+}++@RunWith(RobolectricTestRunner::class)+@Config(qualifiers = "w1000dp-h400dp-land")+class LandscapeScreenTest {++ @get:Rule val rule = createComposeRule()++ @Test fun calculatorScreenUsesLandscapeLayoutOnShortWindow() {+ rule.setContent {+ CalculatorScreen(+ state = CalculatorUiState(input = "2+2", preview = "4"),+ actions = CalculatorActions.Noop,+ )+ }+ rule.onNodeWithText("2+2").assertIsDisplayed()+ rule.onNodeWithText("7").assertIsDisplayed()+ rule.onNodeWithText("sin").assertIsDisplayed()+ }+}
calculator/src/test/java/com/vayunmathur/calculator/ui/NavigationComposeTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/ui/NavigationComposeTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/ui/NavigationComposeTest.ktnew file mode 100644index 0000000000..73ad8f3d11--- /dev/null+++ b/calculator/src/test/java/com/vayunmathur/calculator/ui/NavigationComposeTest.kt@@ -0,0 +1,39 @@+package com.vayunmathur.calculator.ui++import android.app.Application+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onAllNodesWithText+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.calculator.Navigation+import com.vayunmathur.calculator.util.CalculatorViewModel+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test++@RunWith(RobolectricTestRunner::class)+class NavigationComposeTest {++ @get:Rule val rule = createComposeRule()++ @Test fun navigationRendersCalculatorTab() {+ // NavDisplay entry animations never go idle under Robolectric's+ // paused clock, so drive frames manually instead of waiting.+ rule.mainClock.autoAdvance = false+ val vm = CalculatorViewModel(ApplicationProvider.getApplicationContext<Application>())+ rule.setContent { Navigation(vm) }+ rule.mainClock.advanceTimeBy(500)+ rule.onNodeWithText("Calculator").assertIsDisplayed()+ rule.onNodeWithText("7").assertIsDisplayed()+ }++ @Test fun navigationRendersUnitsFirstWhenRequested() {+ rule.mainClock.autoAdvance = false+ val vm = CalculatorViewModel(ApplicationProvider.getApplicationContext<Application>())+ rule.setContent { Navigation(vm, unitsRequest = 1) }+ rule.mainClock.advanceTimeBy(500)+ rule.onAllNodesWithText("Units")[0].assertIsDisplayed()+ }+}
calculator/src/test/java/com/vayunmathur/calculator/ui/PageBindingsComposeTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/ui/PageBindingsComposeTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/ui/PageBindingsComposeTest.ktnew file mode 100644index 0000000000..946c74a00d--- /dev/null+++ b/calculator/src/test/java/com/vayunmathur/calculator/ui/PageBindingsComposeTest.kt@@ -0,0 +1,61 @@+package com.vayunmathur.calculator.ui++import android.app.Application+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.calculator.util.CalculatorViewModel+import com.vayunmathur.calculator.util.UnitConverterActions+import com.vayunmathur.calculator.util.UnitConverterUiState+import com.vayunmathur.calculator.util.UnitCategory+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals++@RunWith(RobolectricTestRunner::class)+class PageBindingsComposeTest {++ @get:Rule val rule = createComposeRule()++ private fun vm() = CalculatorViewModel(ApplicationProvider.getApplicationContext<Application>())++ @Test fun graphPageBindingRenders() {+ rule.mainClock.autoAdvance = false+ rule.setContent { GraphPage(vm()) }+ rule.mainClock.advanceTimeBy(500)+ rule.onNodeWithText("Add function").assertIsDisplayed()+ }++ @Test fun converterPageBindingRenders() {+ rule.mainClock.autoAdvance = false+ rule.setContent { UnitConverterPage(vm()) }+ rule.mainClock.advanceTimeBy(500)+ rule.onNodeWithText("Units").assertIsDisplayed()+ }++ @Test fun currencyErrorStateOffersRetry() {+ var retries = 0+ val actions = object : UnitConverterActions {+ override fun retryCurrency() { retries++ }+ }+ rule.setContent {+ UnitConverterScreen(+ state = UnitConverterUiState(+ categories = listOf(UnitCategory("Currency", emptyList(), inEquations = false)),+ selectedCategoryIndex = 0,+ isCurrencyCategory = true,+ currencyLoading = false,+ currencyError = "Couldn't load exchange rates",+ ),+ actions = actions,+ )+ }+ rule.onNodeWithText("Couldn't load exchange rates").assertIsDisplayed()+ rule.onNodeWithText("Retry").performClick()+ assertEquals(1, retries)+ }+}
calculator/src/test/java/com/vayunmathur/calculator/ui/WidgetSettingsComposeTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/ui/WidgetSettingsComposeTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/ui/WidgetSettingsComposeTest.ktnew file mode 100644index 0000000000..99e2e7cbe9--- /dev/null+++ b/calculator/src/test/java/com/vayunmathur/calculator/ui/WidgetSettingsComposeTest.kt@@ -0,0 +1,38 @@+package com.vayunmathur.calculator.ui++import android.appwidget.AppWidgetManager+import android.content.Intent+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.AndroidComposeTestRule+import androidx.compose.ui.test.onNodeWithText+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.rules.ActivityScenarioRule+import com.vayunmathur.calculator.widget.CalculatorWidgetSettingsActivity+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test++@RunWith(RobolectricTestRunner::class)+class WidgetSettingsComposeTest {++ private val intent = Intent(+ ApplicationProvider.getApplicationContext(),+ CalculatorWidgetSettingsActivity::class.java,+ ).putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, 7)++ @get:Rule+ val rule = AndroidComposeTestRule<ActivityScenarioRule<CalculatorWidgetSettingsActivity>, CalculatorWidgetSettingsActivity>(+ ActivityScenarioRule<CalculatorWidgetSettingsActivity>(intent),+ ) { scenarioRule ->+ lateinit var activity: CalculatorWidgetSettingsActivity+ scenarioRule.scenario.onActivity { activity = it }+ activity+ }++ @Test fun settingsScreenShowsTransparencySwitch() {+ rule.onNodeWithText("Transparent background").assertIsDisplayed()+ rule.onNodeWithText("Show the wallpaper behind the keypad. The keys stay filled in so they remain readable.")+ .assertIsDisplayed()+ }+}
calculator/src/test/java/com/vayunmathur/calculator/util/ExpressionExtraTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/util/ExpressionExtraTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/util/ExpressionExtraTest.ktnew file mode 100644index 0000000000..df0a285440--- /dev/null+++ b/calculator/src/test/java/com/vayunmathur/calculator/util/ExpressionExtraTest.kt@@ -0,0 +1,107 @@+package com.vayunmathur.calculator.util++import kotlin.math.PI+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertTrue++class ExpressionExtraTest {++ private fun eval(src: String, angle: AngleMode = AngleMode.RADIANS): Double =+ Expression.parse(src).eval(angle = angle)++ private fun assertClose(expected: Double, actual: Double, tolerance: Double = 1e-9) {+ assertTrue(kotlin.math.abs(expected - actual) <= tolerance, "expected $expected but was $actual")+ }++ @Test fun reciprocalTrigFunctions() {+ assertClose(1.0, eval("sec(0)"))+ assertClose(1.0, eval("csc(${PI / 2})"))+ assertClose(0.0, eval("cot(${PI / 2})"))+ assertClose(1.0, eval("sec(0)", AngleMode.DEGREES))+ }++ @Test fun inverseTrigInDegrees() {+ assertClose(90.0, eval("asin(1)", AngleMode.DEGREES))+ assertClose(0.0, eval("acos(1)", AngleMode.DEGREES))+ assertClose(45.0, eval("atan(1)", AngleMode.DEGREES))+ assertClose(PI / 2, eval("asin(1)"))+ }++ @Test fun hyperbolicFunctions() {+ assertClose(0.0, eval("sinh(0)"))+ assertClose(1.0, eval("cosh(0)"))+ assertClose(0.0, eval("tanh(0)"))+ assertClose(0.0, eval("asinh(0)"))+ assertClose(0.0, eval("acosh(1)"))+ assertClose(0.0, eval("atanh(0)"))+ }++ @Test fun singleArgFunctions() {+ assertClose(3.0, eval("cbrt(27)"))+ assertClose(1.0, eval("exp(0)"))+ assertClose(3.0, eval("log2(8)"))+ assertClose(2.0, eval("floor(2.7)"))+ assertClose(3.0, eval("ceil(2.1)"))+ assertClose(3.0, eval("round(2.6)"))+ assertClose(-1.0, eval("sign(-42)"))+ assertClose(120.0, eval("fact(5)"))+ assertClose(2.0, eval("√(4)"))+ }++ @Test fun pairFunctions() {+ assertClose(3.0, eval("root(3,27)"))+ assertClose(1.0, eval("mod(10,3)"))+ assertClose(45.0, eval("atan2(1,1)", AngleMode.DEGREES))+ assertClose(12.0, eval("gcd(36,24)") + 0.0)+ assertClose(72.0, eval("lcm(24,36)"))+ assertClose(10.0, eval("ncr(5,2)"))+ assertClose(20.0, eval("npr(5,2)"))+ }++ @Test fun quantityRemainderAndDivision() {+ val rem = Expression.parse("10m % (3m)").evalQuantity()+ assertClose(1.0, rem.value)+ assertEquals(Dimension.LENGTH, rem.dimension)+ val div = Expression.parse("10m / (4s)").evalQuantity()+ assertEquals(Dimension.SPEED, div.dimension)+ assertClose(2.5, div.value)+ val scaled = Expression.parse("6km / 2").evalQuantity()+ assertClose(3000.0, scaled.value)+ }++ @Test fun incompatibleRemainderIsRejected() {+ assertFailsWith<ExpressionError> {+ Expression.parse("10m % (3s)").evalQuantity()+ }+ }++ @Test fun dimensionalExponentIsRejected() {+ assertFailsWith<ExpressionError> {+ Expression.parse("10m ^ (2s)").evalQuantity()+ }+ }++ @Test fun dimensionToString() {+ assertEquals("1", Dimension.NONE.toString())+ assertTrue(Dimension.LENGTH.toString().contains("LENGTH"))+ assertTrue(Dimension.SPEED.toString().contains("TIME"))+ }++ @Test fun graphTapWithNoViewSizeIsSafe() {+ val tab = GraphTab()+ // No view size reported yet: sampling yields no curves, no marker.+ tab.tapGraph(GraphPoint(0.0, 0.0), 1.0)+ assertEquals(0, tab.markers.size)+ }++ @Test fun converterDropdownLambdaSelectsUnit() {+ // Covered at the screen level elsewhere; here the registry pair+ // conversion used by the widget and dropdowns is sanity-checked.+ val length = UnitRegistry.categories[0]+ val metre = length.units.first { it.token == "m" }+ val cm = length.units.first { it.token == "cm" }+ assertClose(100.0, cm.fromBase(metre.toBase(1.0)))+ }+}
calculator/src/test/java/com/vayunmathur/calculator/util/TabsExtraTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/util/TabsExtraTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/util/TabsExtraTest.ktnew file mode 100644index 0000000000..1426d4f7ba--- /dev/null+++ b/calculator/src/test/java/com/vayunmathur/calculator/util/TabsExtraTest.kt@@ -0,0 +1,192 @@+package com.vayunmathur.calculator.util++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals+import kotlin.test.assertTrue++class TabsExtraTest {++ // ---- CalculatorTab: units, memory, instants ----++ @Test fun unitBearingPreviewOffersOutputUnits() {+ val tab = CalculatorTab()+ tab.updateInput("2km")+ assertTrue(tab.unitOptions.isNotEmpty())+ assertEquals("m", tab.selectedUnit?.token)+ assertTrue(tab.preview.startsWith("2000"), tab.preview)+ }++ @Test fun selectOutputUnitReformatsPreview() {+ val tab = CalculatorTab()+ tab.updateInput("2km")+ tab.selectOutputUnit("cm")+ assertEquals("cm", tab.selectedUnit?.token)+ assertTrue(tab.preview.startsWith("200000"), tab.preview)+ // Unknown tokens are ignored.+ tab.selectOutputUnit("furlong")+ assertEquals("cm", tab.selectedUnit?.token)+ }++ @Test fun evaluateWithUnitsSeedsTokenForm() {+ val tab = CalculatorTab()+ tab.updateInput("2km")+ tab.evaluate()+ assertEquals(2000.0, tab.lastAnswer)+ assertTrue(tab.history.size == 1)+ }++ @Test fun memoryRegisterLifecycle() {+ val tab = CalculatorTab()+ tab.updateInput("5")+ tab.memoryAdd()+ assertEquals(5.0, tab.memory)+ tab.memoryAdd()+ assertEquals(10.0, tab.memory)+ tab.memorySubtract()+ assertEquals(5.0, tab.memory)+ tab.clear()+ tab.memoryRecall()+ assertEquals("5", tab.input)+ tab.memoryClear()+ assertEquals(0.0, tab.memory)+ }++ @Test fun memoryOpsOnInvalidInputAreNoOps() {+ val tab = CalculatorTab()+ tab.updateInput("1+")+ tab.memoryAdd()+ assertEquals(0.0, tab.memory)+ }++ @Test fun insertInstantAndUseHistory() {+ val tab = CalculatorTab()+ tab.insertInstant(1_700_000_000)+ assertEquals("#1700000000", tab.input)+ assertTrue(tab.preview.isNotEmpty())+ tab.useHistory(HistoryEntry("x", "42"))+ assertEquals("42", tab.input)+ }++ @Test fun backspaceOnEmptyStaysEmpty() {+ val tab = CalculatorTab()+ tab.backspace()+ assertEquals("", tab.input)+ tab.append("12")+ tab.backspace()+ assertEquals("1", tab.input)+ }++ @Test fun adaptersDelegateToTab() {+ val tab = CalculatorTab()+ val actions = calculatorActionAdapter(tab)+ actions.append("3+4")+ actions.evaluate()+ assertEquals(7.0, tab.lastAnswer)+ actions.backspace()+ actions.clear()+ assertEquals("", tab.input)+ actions.insertInstant(10)+ assertEquals("#10", tab.input)+ actions.memoryClear()+ actions.useHistory(HistoryEntry("e", "9"))+ assertEquals("9", tab.input)+ }++ @Test fun uiStateMirrorsTab() {+ val tab = CalculatorTab()+ tab.updateInput("1+1")+ val state = tab.uiState+ assertEquals("1+1", state.input)+ assertEquals("2", state.preview)+ assertEquals(UnitRegistry.categories, state.unitCategories)+ }++ // ---- GraphTab ----++ @Test fun graphFunctionCrud() {+ val tab = GraphTab()+ assertEquals(1, tab.functions.size)+ assertEquals("x", tab.functions[0].text)+ tab.addFunction()+ assertEquals(2, tab.functions.size)+ val id = tab.functions[1].id+ tab.updateFunction(id, "x^2")+ assertEquals("x^2", tab.functions[1].text)+ tab.toggleFunction(id)+ assertEquals(false, tab.functions[1].enabled)+ tab.togglePolar(id)+ assertEquals(true, tab.functions[1].polar)+ tab.removeFunction(id)+ assertEquals(1, tab.functions.size)+ }++ @Test fun removingLastFunctionAddsAFreshOne() {+ val tab = GraphTab()+ tab.removeFunction(tab.functions[0].id)+ assertEquals(1, tab.functions.size)+ assertEquals("", tab.functions[0].text)+ }++ @Test fun mutatingUnknownIdIsNoOp() {+ val tab = GraphTab()+ tab.updateFunction(999, "y")+ tab.toggleFunction(999)+ assertEquals("x", tab.functions[0].text)+ assertEquals(true, tab.functions[0].enabled)+ }++ @Test fun graphViewportAndMarkersViaAdapter() {+ val tab = GraphTab()+ val actions = graphActionAdapter(tab)+ actions.setViewSize(800f, 600f)+ assertEquals(800f, tab.viewWidthPx)+ actions.setViewport(GraphViewport(centerX = 1.0, centerY = 2.0, scale = 30.0))+ assertEquals(1.0, tab.centerX)+ assertEquals(30.0, tab.scale)+ // Tap far from any feature on y=x: either a marker appears near the+ // origin feature or none does; tapping again must not crash.+ actions.tapGraph(GraphPoint(0.0, 0.0), 0.5)+ val markerCount = tab.markers.size+ assertTrue(markerCount <= 1)+ if (markerCount == 1) {+ actions.tapGraph(tab.markers[0].point, 0.5)+ assertEquals(0, tab.markers.size)+ }+ actions.addFunction()+ actions.updateFunction(tab.functions[1].id, "x")+ actions.togglePolar(tab.functions[1].id)+ actions.removeFunction(tab.functions[1].id)+ }++ @Test fun graphUiStateReflectsFunctions() {+ val tab = GraphTab()+ tab.angleMode = AngleMode.DEGREES+ val state = tab.uiState+ assertEquals(AngleMode.DEGREES, state.angleMode)+ assertEquals(tab.functions.toList(), state.functions)+ assertEquals(GraphViewport(0.0, 0.0, 60.0), state.viewport)+ }++ // ---- GraphViewport ----++ @Test fun viewportTransformsAreInverse() {+ val vp = GraphViewport(centerX = 2.0, centerY = -1.0, scale = 50.0)+ val gx = vp.graphX(123f, 800f)+ assertEquals(123.0, vp.screenX(gx, 800f).toDouble(), 1e-3)+ val gy = vp.graphY(45f, 600f)+ assertEquals(45.0, vp.screenY(gy, 600f).toDouble(), 1e-3)+ val bounds = vp.bounds(800f, 600f)+ assertTrue(bounds.xMin < bounds.xMax && bounds.yMin < bounds.yMax)+ assertEquals(vp.graphX(0f, 800f), bounds.xMin)+ }++ @Test fun viewportZoomClampsScale() {+ val vp = GraphViewport(scale = 60.0)+ val zoomed = vp.transformed(400f, 300f, 0f, 0f, 1e9f, 800f, 600f)+ assertEquals(400000.0, zoomed.scale)+ val out = vp.transformed(400f, 300f, 0f, 0f, 1e-9f, 800f, 600f)+ assertEquals(2.0, out.scale)+ assertNotEquals(vp.centerX, vp.transformed(400f, 300f, 10f, 0f, 1f, 800f, 600f).centerX)+ }+}
calculator/src/test/java/com/vayunmathur/calculator/util/ViewModelAndConverterTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/util/ViewModelAndConverterTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/util/ViewModelAndConverterTest.ktnew file mode 100644index 0000000000..1f1e7cdbea--- /dev/null+++ b/calculator/src/test/java/com/vayunmathur/calculator/util/ViewModelAndConverterTest.kt@@ -0,0 +1,134 @@+package com.vayunmathur.calculator.util++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class ViewModelAndConverterTest {++ private val app: Application get() = ApplicationProvider.getApplicationContext()++ @Before fun setUp() {+ // selectCategory/swap refresh the units widget via WorkManager.+ runCatching {+ androidx.work.testing.WorkManagerTestInitHelper.initializeTestWorkManager(app)+ }+ }++ @Test fun viewModelDelegatesAndTogglesAngleMode() {+ val vm = CalculatorViewModel(app)+ assertEquals(AngleMode.RADIANS, vm.angleMode)+ vm.append("sin(0)")+ assertEquals("sin(0)", vm.calculatorUiState.input)+ vm.toggleAngleMode()+ assertEquals(AngleMode.DEGREES, vm.angleMode)+ assertEquals(AngleMode.DEGREES, vm.calculatorUiState.angleMode)+ assertEquals(AngleMode.DEGREES, vm.graphUiState.angleMode)+ vm.toggleAngleMode()+ assertEquals(AngleMode.RADIANS, vm.angleMode)+ assertEquals(1, vm.graphUiState.functions.size)+ assertTrue(vm.unitConverterUiState.categories.isNotEmpty())+ }++ @Test fun converterInitialConversion() {+ val tab = UnitConverterTab(app)+ val state = tab.uiState+ assertEquals(0, state.selectedCategoryIndex)+ assertEquals("1", state.inputText)+ // First category is Length; first two units convert 1 unit of [0] into [1].+ assertTrue(state.outputText.isNotEmpty(), state.outputText)+ assertFalse(state.isCurrencyCategory)+ }++ @Test fun converterInputAndSwap() {+ val tab = UnitConverterTab(app)+ tab.setConverterInput("100")+ assertEquals("100", tab.converterValueText)+ val before = tab.uiState.outputText+ assertTrue(before.isNotEmpty())+ val fromBefore = tab.converterFromToken+ val toBefore = tab.converterToToken+ tab.swapUnits()+ assertEquals(toBefore, tab.converterFromToken)+ assertEquals(fromBefore, tab.converterToToken)+ }++ @Test fun converterRejectsBadCategoryAndHandlesBadInput() {+ val tab = UnitConverterTab(app)+ tab.selectCategory(-1)+ assertEquals(0, tab.converterCategoryIndex)+ tab.selectCategory(9999)+ assertEquals(0, tab.converterCategoryIndex)+ tab.setConverterInput("not-a-number")+ assertEquals("", tab.uiState.outputText)+ }++ @Test fun converterSelectCategoryChangesUnits() {+ val tab = UnitConverterTab(app)+ tab.selectCategory(1)+ assertEquals(1, tab.converterCategoryIndex)+ val category = tab.uiState.categories[1]+ assertTrue(category.units.any { it.token == tab.converterFromToken })+ assertTrue(category.units.any { it.token == tab.converterToToken })+ tab.setFrom(category.units[0].token)+ tab.setTo(category.units.getOrElse(1) { category.units[0] }.token)+ assertTrue(tab.uiState.outputText.isNotEmpty())+ }++ @Test fun converterAdapterDelegates() {+ val tab = UnitConverterTab(app)+ val actions = converterActionAdapter(tab)+ actions.setConverterInput("42")+ assertEquals("42", tab.converterValueText)+ actions.selectCategory(2)+ assertEquals(2, tab.converterCategoryIndex)+ actions.swapUnits()+ assertEquals(2, tab.converterCategoryIndex)+ }++ @Test fun viewModelConverterStartLoadsAndFailsCurrencyGracefully() {+ // The VM starts the converter tab: it restores the persisted+ // selection and attempts a currency fetch, which fails offline+ // (no NetworkClient in tests) and must surface as an error state+ // on the Currency tab rather than crashing.+ val vm = CalculatorViewModel(app)+ val deadline = System.currentTimeMillis() + 10_000+ var state = vm.unitConverterUiState+ while (System.currentTimeMillis() < deadline) {+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ state = vm.unitConverterUiState+ val currencyIndex = state.categories.lastIndex+ vm.selectCategory(currencyIndex)+ state = vm.unitConverterUiState+ if (state.currencyError != null) break+ Thread.sleep(20)+ }+ assertEquals("Couldn't load exchange rates", state.currencyError)+ assertTrue(state.isCurrencyCategory)+ }++ @Test fun currencyCategoryBuilding() {+ assertEquals(null, UnitRegistry.currencyCategory(emptyMap()))+ assertEquals(null, UnitRegistry.currencyCategory(mapOf("XXX" to 0.0)))+ val category = UnitRegistry.currencyCategory(mapOf("EUR" to 0.9, "USD" to 1.0, "JPY" to 150.0))+ assertEquals("Currency", category?.name)+ assertEquals(listOf("USD", "EUR", "JPY"), category?.units?.map { it.token })+ // 1 USD (factor 1) converts to 0.9 EUR through the base.+ val usd = category!!.units[0]+ val eur = category.units[1]+ assertEquals(0.9, eur.fromBase(usd.toBase(1.0)), 1e-9)+ }++ @Test fun keyNamesAreStable() {+ assertEquals("calculator_units_category", KEY_UNITS_CATEGORY)+ assertEquals("calculator_units_from_Length", unitsFromKey("Length"))+ assertEquals("calculator_units_to_Length", unitsToKey("Length"))+ }+}
calculator/src/test/java/com/vayunmathur/calculator/widget/GlanceProvideTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/widget/GlanceProvideTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/widget/GlanceProvideTest.ktnew file mode 100644index 0000000000..40c467ddb0--- /dev/null+++ b/calculator/src/test/java/com/vayunmathur/calculator/widget/GlanceProvideTest.kt@@ -0,0 +1,49 @@+package com.vayunmathur.calculator.widget++import android.content.Context+import androidx.glance.appwidget.AppWidgetId+import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.runBlocking+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals++@RunWith(RobolectricTestRunner::class)+class GlanceProvideTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ @Before fun setUp() {+ // Synchronous WorkManager so Glance widget updates (which are+ // scheduled as work) actually run their composition in-process.+ runCatching {+ androidx.work.testing.WorkManagerTestInitHelper.initializeTestWorkManager(ctx)+ }+ }++ @Test fun unitsWidgetProvidesGlance() = runBlocking {+ // provideGlance loads data (falling back to the first category with+ // nothing persisted) and composes the widget content to RemoteViews.+ val widget = UnitsGlanceWidget()+ widget.provideGlance(ctx, AppWidgetId(201))+ runCatching { widget.update(ctx, AppWidgetId(201)) }+ Unit+ }++ @Test fun calculatorWidgetProvidesGlance() = runBlocking {+ val widget = CalculatorGlanceWidget()+ widget.provideGlance(ctx, AppWidgetId(202))+ runCatching { widget.update(ctx, AppWidgetId(202)) }+ Unit+ }++ @Test fun widgetStateDataClassesHoldValues() {+ val state = UnitsWidgetState("Length", "1 m = 100 cm")+ assertEquals("Length", state.categoryName)+ val data = UnitsWidgetData(state, expanded = true)+ assertEquals(true, data.expanded)+ assertEquals(state, data.state)+ }+}
calculator/src/test/java/com/vayunmathur/calculator/widget/WidgetActionsTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/widget/WidgetActionsTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/widget/WidgetActionsTest.ktnew file mode 100644index 0000000000..cfc1bbe61d--- /dev/null+++ b/calculator/src/test/java/com/vayunmathur/calculator/widget/WidgetActionsTest.kt@@ -0,0 +1,81 @@+package com.vayunmathur.calculator.widget++import android.content.Context+import androidx.glance.action.actionParametersOf+import androidx.glance.appwidget.AppWidgetId+import androidx.glance.appwidget.state.getAppWidgetState+import androidx.glance.state.PreferencesGlanceStateDefinition+import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.runBlocking+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals++@RunWith(RobolectricTestRunner::class)+class WidgetActionsTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ @Before fun setUp() {+ // Glance widget updates are scheduled through WorkManager; the+ // synchronous test WorkManager lets them complete inside runBlocking+ // instead of suspending forever on a background executor that a+ // previous test class may have torn down.+ runCatching {+ androidx.work.testing.WorkManagerTestInitHelper.initializeTestWorkManager(ctx)+ }+ // Another test class in this JVM (the converter tab tests) may+ // already hold a DataStore instance for the shared preferences+ // file; a second instance's edit then waits on that instance+ // forever. Unlink the file so this class's instance starts fresh.+ java.io.File(ctx.filesDir, "datastore/datastore_default.preferences_pb").delete()+ // Leftover Glance work enqueued by an earlier test class would be+ // picked up by this class's synchronous WorkManager and its session+ // can suspend the widget update below forever; drain it first.+ runCatching {+ androidx.work.WorkManager.getInstance(ctx).cancelAllWork().result.get()+ }+ }++ private suspend fun inputOf(id: AppWidgetId): String =+ getAppWidgetState(ctx, PreferencesGlanceStateDefinition, id)[CalculatorInputKey].orEmpty()++ @Test fun calculatorKeyActionAppendEvaluateClear() = runBlocking {+ val action = CalculatorKeyAction()+ val id = AppWidgetId(101)+ action.onAction(ctx, id, actionParametersOf(CalculatorKeyParam to "append:5"))+ assertEquals("5", inputOf(id))+ action.onAction(ctx, id, actionParametersOf(CalculatorKeyParam to "append:+3"))+ assertEquals("5+3", inputOf(id))+ action.onAction(ctx, id, actionParametersOf(CalculatorKeyParam to COMMAND_EVALUATE))+ assertEquals("8", inputOf(id))+ action.onAction(ctx, id, actionParametersOf(CalculatorKeyParam to COMMAND_BACKSPACE))+ assertEquals("", inputOf(id))+ action.onAction(ctx, id, actionParametersOf(CalculatorKeyParam to "append:9"))+ action.onAction(ctx, id, actionParametersOf(CalculatorKeyParam to COMMAND_CLEAR))+ assertEquals("", inputOf(id))+ }++ @Test fun calculatorKeyActionWithoutCommandLeavesInput() = runBlocking {+ val id = AppWidgetId(102)+ CalculatorKeyAction().onAction(ctx, id, actionParametersOf(CalculatorKeyParam to "append:1"))+ CalculatorKeyAction().onAction(ctx, id, actionParametersOf())+ assertEquals("1", inputOf(id))+ }++ @Test fun toggleActionFlipsExpandedState() = runBlocking {+ val id = AppWidgetId(103)+ ToggleUnitsCategoryListAction().onAction(ctx, id, actionParametersOf())+ assertEquals(+ true,+ getAppWidgetState(ctx, PreferencesGlanceStateDefinition, id)[UnitsGlanceWidget.EXPANDED],+ )+ ToggleUnitsCategoryListAction().onAction(ctx, id, actionParametersOf())+ assertEquals(+ false,+ getAppWidgetState(ctx, PreferencesGlanceStateDefinition, id)[UnitsGlanceWidget.EXPANDED],+ )+ }+}
calculator/src/test/java/com/vayunmathur/calculator/widget/WidgetLogicTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/widget/WidgetLogicTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/widget/WidgetLogicTest.ktnew file mode 100644index 0000000000..e5baeceb55--- /dev/null+++ b/calculator/src/test/java/com/vayunmathur/calculator/widget/WidgetLogicTest.kt@@ -0,0 +1,63 @@+package com.vayunmathur.calculator.widget++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class WidgetLogicTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ @Test fun evaluateForWidgetBasics() {+ assertNull(evaluateForWidget("", 0.0))+ assertNull(evaluateForWidget("1+", 0.0))+ assertNull(evaluateForWidget("0/0", 0.0))+ val result = evaluateForWidget("2+3", 0.0)+ assertEquals(5.0, result?.value)+ assertEquals("5", result?.display)+ assertEquals("5", result?.token)+ }++ @Test fun evaluateForWidgetUsesAnsAndUnits() {+ val withAns = evaluateForWidget("ans*2", 21.0)+ assertEquals(42.0, withAns?.value)+ val length = evaluateForWidget("2km", 0.0)+ assertEquals(2000.0, length?.value)+ assertTrue(length?.display?.startsWith("2000") == true)+ }++ @Test fun appendWidgetInputCapsLength() {+ assertEquals("abc", appendWidgetInput("ab", "c"))+ val long = "x".repeat(MAX_WIDGET_INPUT_LENGTH)+ assertEquals(MAX_WIDGET_INPUT_LENGTH, appendWidgetInput(long, "more").length)+ assertEquals("", appendWidgetInput("", ""))+ }++ @Test fun calculatorWidgetSettingsActivityWithoutIdFinishes() {+ val controller = Robolectric.buildActivity(CalculatorWidgetSettingsActivity::class.java)+ controller.create()+ assertTrue(controller.get().isFinishing)+ }++ @Test fun widgetReceiversConstruct() {+ // Receivers are thin MaWidgetReceiver subclasses; construction must+ // not touch the widget host.+ CalculatorGlanceWidgetReceiver()+ UnitsGlanceWidgetReceiver()+ assertEquals("openUnits", UnitsGlanceWidget.EXTRA_OPEN_UNITS)+ }++ @Test fun toggleActionFlipsExpandedState() {+ // The glance state store may be unavailable under Robolectric; the+ // action must at least not throw synchronously before that point.+ // Its state flip is covered indirectly through loadData above.+ assertTrue(UnitsGlanceWidget.EXPANDED.name == "units_widget_category_expanded")+ }+}