package com.example import android.content.Context import androidx.test.core.app.ApplicationProvider import com.example.data.local.AppDatabase import com.example.data.remote.GoogleSheetsSyncService import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.test.setMain import kotlinx.coroutines.test.resetMain import androidx.lifecycle.viewModelScope @RunWith(RobolectricTestRunner::class) @Config(sdk = [34]) class ExampleRobolectricTest { @Test fun `read string from context`() { val context = ApplicationProvider.getApplicationContext() val appName = context.getString(R.string.app_name) assertEquals("Gestão Parada OS", appName) } @Test fun `inspect project sheet`() { val context = ApplicationProvider.getApplicationContext() val service = GoogleSheetsSyncService(context) println("--- INSPECTING PROJECT SHEET ---") try { val values = service.fetchValues("project!A1:Z50") println("Fetched ${values.size} rows with columns up to Z") for ((index, row) in values.withIndex()) { println("Row $index: $row") } } catch (e: Exception) { println("Failed to fetch sheet: ${e.message}") e.printStackTrace() } println("--- END INSPECTING ---") } @Test fun `diagnose synchronization backend`() { val context = ApplicationProvider.getApplicationContext() val db = androidx.room.Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java).build() val repository = com.example.data.repository.MaintenanceRepository(db.maintenanceDao(), context) println("--- STARTING SYNCHRONIZE DIAGNOSTIC UPDATED ---") try { val result = kotlinx.coroutines.runBlocking { val r = repository.synchronizeWithBackend() println("Sync Result: $r") val list = repository.allActivities.first() println("Total activities in database: ${list.size}") list.forEach { act -> println(" OS: ${act.numeroOs}, Desc: ${act.descricao}, Setor: ${act.setor}, Equipe: ${act.equipe}, Pct: ${act.percentualExecucao}") } r } } catch (e: Exception) { println("Sync threw exception: ${e.message}") e.printStackTrace() } println("--- END SYNCHRONIZE DIAGNOSTIC ---") db.close() } @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) @Test fun `test quick filters and sorting by predicted end date`() { val testDispatcher = kotlinx.coroutines.test.UnconfinedTestDispatcher() kotlinx.coroutines.Dispatchers.setMain(testDispatcher) try { val context = ApplicationProvider.getApplicationContext() val db = androidx.room.Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java) .allowMainThreadQueries() .setQueryExecutor { it.run() } .setTransactionExecutor { it.run() } .build() val repository = com.example.data.repository.MaintenanceRepository(db.maintenanceDao(), context) val todayStr = java.text.SimpleDateFormat("dd/MM/yyyy HH:mm", java.util.Locale.US).format(java.util.Date()) val act1 = com.example.data.model.MaintenanceActivity( numeroOs = "OS-FUTURE", descricao = "Future OS", setor = "Geral", equipe = "Mecânica", recurso = "Sem Recurso", dataInicio = "27/08/2027 10:00", dataFim = "27/08/2027 17:00", percentualExecucao = 50, synced = true ) val act2 = com.example.data.model.MaintenanceActivity( numeroOs = "OS-OLDEST", descricao = "Oldest OS", setor = "Geral", equipe = "Elétrica", recurso = "Sem Recurso", dataInicio = "25/07/2026 10:00", dataFim = "25/07/2026 17:00", percentualExecucao = 100, synced = true ) val act3 = com.example.data.model.MaintenanceActivity( numeroOs = "OS-TODAY", descricao = "Today OS", setor = "Geral", equipe = "Confiabilidade", recurso = "Sem Recurso", dataInicio = todayStr, dataFim = todayStr, percentualExecucao = 0, synced = true ) kotlinx.coroutines.runBlocking { db.maintenanceDao().insertActivities(listOf(act1, act2, act3)) val allLocal = db.maintenanceDao().getAllActivitiesList() println("ALL LOCAL ACTIVITIES IN DB BEFORE VM: ${allLocal.size}") for (a in allLocal) { println(" - OS: ${a.numeroOs}, dataFim: ${a.dataFim}") } val viewModel = com.example.ui.viewmodel.MaintenanceViewModel(repository) // Start collection to activate stateIn subscription val collectionJob = viewModel.viewModelScope.launch { viewModel.filteredActivities.collect {} } // Let background threads run (like Room flow query) Thread.sleep(200) org.robolectric.shadows.ShadowLooper.idleMainLooper() // 1. Test default sorting by dataFim (oldest first): OS-OLDEST -> OS-TODAY (current day) -> OS-FUTURE (next year) val defaultList = viewModel.filteredActivities.value assertEquals(3, defaultList.size) assertEquals("OS-OLDEST", defaultList[0].numeroOs) assertEquals("OS-TODAY", defaultList[1].numeroOs) assertEquals("OS-FUTURE", defaultList[2].numeroOs) // 2. Test "Pendentes" filter (should return act1 and act3, but not act2) viewModel.setSelectedQuickFilter("Pendentes") Thread.sleep(200) org.robolectric.shadows.ShadowLooper.idleMainLooper() val pendingList = viewModel.filteredActivities.value assertEquals(2, pendingList.size) assert(pendingList.any { it.numeroOs == "OS-FUTURE" }) assert(pendingList.any { it.numeroOs == "OS-TODAY" }) // 3. Test "Hoje" filter (should return act3 only) viewModel.setSelectedQuickFilter("Hoje") Thread.sleep(200) org.robolectric.shadows.ShadowLooper.idleMainLooper() val todayList = viewModel.filteredActivities.value assertEquals(1, todayList.size) assertEquals("OS-TODAY", todayList[0].numeroOs) // 4. Test "Mecânica" filter (should return act1 only) viewModel.setSelectedQuickFilter("Mecânica") Thread.sleep(200) org.robolectric.shadows.ShadowLooper.idleMainLooper() val mechanicalList = viewModel.filteredActivities.value assertEquals(1, mechanicalList.size) assertEquals("OS-FUTURE", mechanicalList[0].numeroOs) collectionJob.cancel() } db.close() } finally { kotlinx.coroutines.Dispatchers.resetMain() } } @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) @Test fun `test analytics state calculations in ViewModel`() { val testDispatcher = kotlinx.coroutines.test.UnconfinedTestDispatcher() kotlinx.coroutines.Dispatchers.setMain(testDispatcher) try { val context = ApplicationProvider.getApplicationContext() val db = androidx.room.Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java) .allowMainThreadQueries() .setQueryExecutor { it.run() } .setTransactionExecutor { it.run() } .build() val repository = com.example.data.repository.MaintenanceRepository(db.maintenanceDao(), context) val act1 = com.example.data.model.MaintenanceActivity( numeroOs = "OS-1", descricao = "Inspection 1", setor = "Geral", equipe = "Mecânica", recurso = "Sem Recurso", dataInicio = "Sex 14/08/26 07:00", dataFim = "Sex 14/08/26 17:00", percentualExecucao = 100, tag = "TAG-MEC", synced = true ) val act2 = com.example.data.model.MaintenanceActivity( numeroOs = "OS-2", descricao = "Repair 2", setor = "Geral", equipe = "Elétrica", recurso = "Sem Recurso", dataInicio = "14/08/2026 08:30", dataFim = "15/08/2026 17:00", percentualExecucao = 50, tag = "TAG-ELE", synced = true ) kotlinx.coroutines.runBlocking { db.maintenanceDao().insertActivities(listOf(act1, act2)) val viewModel = com.example.ui.viewmodel.MaintenanceViewModel(repository) // Start collection to activate stateIn subscription val collectionJob = viewModel.viewModelScope.launch { viewModel.analyticsState.collect {} } // Allow Room flow to emit Thread.sleep(200) org.robolectric.shadows.ShadowLooper.idleMainLooper() val state = viewModel.analyticsState.value // 1. Verify team metrics val mecProductivity = state.teamMetrics.find { it.first == "Mecânica" }?.second val eleProductivity = state.teamMetrics.find { it.first == "Elétrica" }?.second assertEquals(100, mecProductivity) assertEquals(0, eleProductivity) // OS-2 is only 50%, so not completed (>= 100) // 2. Verify timeline dates size (should be 5 steps) assertEquals(5, state.timelineDates.size) // 3. Verify planned progress points has correct count assertEquals(5, state.plannedProgressPoints.size) // 4. Verify realized progress points has correct count assertEquals(5, state.realizedProgressPoints.size) // 5. Verify overdueBySector is present assertNotNull(state.overdueBySector) collectionJob.cancel() } db.close() } finally { kotlinx.coroutines.Dispatchers.resetMain() } } @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) @Test fun `test user access control check in ViewModel`() { val testDispatcher = kotlinx.coroutines.test.UnconfinedTestDispatcher() kotlinx.coroutines.Dispatchers.setMain(testDispatcher) try { val context = ApplicationProvider.getApplicationContext() val db = androidx.room.Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java) .allowMainThreadQueries() .setQueryExecutor { it.run() } .setTransactionExecutor { it.run() } .build() val repository = com.example.data.repository.MaintenanceRepository(db.maintenanceDao(), context) val userAdmin = com.example.data.model.UserAccess("admin@empresa.com", "total") val userEditor = com.example.data.model.UserAccess("editor@empresa.com", "editor") val userViewer = com.example.data.model.UserAccess("viewer@empresa.com", "leitor") kotlinx.coroutines.runBlocking { db.maintenanceDao().insertUserAccessList(listOf(userAdmin, userEditor, userViewer)) val viewModel = com.example.ui.viewmodel.MaintenanceViewModel(repository) // Setup a dummy activity in database val act = com.example.data.model.MaintenanceActivity( numeroOs = "OS-ACCESS", descricao = "Access Test", setor = "Geral", equipe = "Mecânica", recurso = "Sem Recurso", dataInicio = "27/08/2026 10:00", dataFim = "27/08/2026 17:00", percentualExecucao = 0, synced = true ) db.maintenanceDao().insertActivity(act) // Start collection to activate stateIn subscription val collectionJob = viewModel.viewModelScope.launch { viewModel.filteredActivities.collect {} } val collectionJob2 = viewModel.viewModelScope.launch { viewModel.userAccessLevel.collect {} } // Test 1: User not logged in viewModel.selectActivity(act) // Access level should be null assertEquals(null, viewModel.userAccessLevel.value) // Test 2: Log in as viewer (viewer@empresa.com) viewModel.loginUser("viewer@empresa.com", "Viewer User") Thread.sleep(100) org.robolectric.shadows.ShadowLooper.idleMainLooper() assertEquals("leitor", viewModel.userAccessLevel.value) // Attempt to edit progress (should fail because access level is leitor, which is not total or editor) viewModel.updateProgress("OS-ACCESS", 50, "Tentando editar", null, "Viewer User", "viewer@empresa.com") Thread.sleep(100) org.robolectric.shadows.ShadowLooper.idleMainLooper() // OS percentualExecucao should remain 0 val actAfterViewer = db.maintenanceDao().getActivityByOsOneShot("OS-ACCESS") assertEquals(0, actAfterViewer?.percentualExecucao) // Test 3: Log in as editor (editor@empresa.com) viewModel.loginUser("editor@empresa.com", "Editor User") Thread.sleep(100) org.robolectric.shadows.ShadowLooper.idleMainLooper() assertEquals("editor", viewModel.userAccessLevel.value) // Attempt to edit progress (should succeed because access level is editor) viewModel.updateProgress("OS-ACCESS", 80, "Editando com editor", null, "Editor User", "editor@empresa.com") Thread.sleep(100) org.robolectric.shadows.ShadowLooper.idleMainLooper() // OS percentualExecucao should now be 80 val actAfterEditor = db.maintenanceDao().getActivityByOsOneShot("OS-ACCESS") assertEquals(80, actAfterEditor?.percentualExecucao) collectionJob.cancel() collectionJob2.cancel() } db.close() } finally { kotlinx.coroutines.Dispatchers.resetMain() } } @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) @Test fun `test sorting using CSV date formats from GestaoOS_Parada_project`() { val testDispatcher = kotlinx.coroutines.test.UnconfinedTestDispatcher() kotlinx.coroutines.Dispatchers.setMain(testDispatcher) try { val context = ApplicationProvider.getApplicationContext() val db = androidx.room.Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java) .allowMainThreadQueries() .setQueryExecutor { it.run() } .setTransactionExecutor { it.run() } .build() val repository = com.example.data.repository.MaintenanceRepository(db.maintenanceDao(), context) val act1 = com.example.data.model.MaintenanceActivity( numeroOs = "OS-1", descricao = "PARADA ANUAL 2026", setor = "Geral", equipe = "Mecânica", recurso = "Sem Recurso", dataInicio = "ter. 04/08/26 07:00", dataFim = "sex. 11/09/26 16:00", percentualExecucao = 0, synced = true ) val act2 = com.example.data.model.MaintenanceActivity( numeroOs = "OS-1024", descricao = "SUBSTITUIÇÃO DA CHAPA DE FIXAÇÃO DOS APARADORES", setor = "Geral", equipe = "Mecânica", recurso = "GTEC 1", dataInicio = "seg. 17/08/26 07:00", dataFim = "ter. 18/08/26 17:00", percentualExecucao = 0, synced = true ) val act3 = com.example.data.model.MaintenanceActivity( numeroOs = "OS-4", descricao = "B-111113", setor = "Geral", equipe = "Mecânica", recurso = "Sem Recurso", dataInicio = "sex. 14/08/26 07:00", dataFim = "sex. 14/08/26 07:00", percentualExecucao = 0, synced = true ) kotlinx.coroutines.runBlocking { db.maintenanceDao().insertActivities(listOf(act1, act2, act3)) val viewModel = com.example.ui.viewmodel.MaintenanceViewModel(repository) val collectionJob = viewModel.viewModelScope.launch { viewModel.filteredActivities.collect {} } Thread.sleep(200) org.robolectric.shadows.ShadowLooper.idleMainLooper() val filtered = viewModel.filteredActivities.value assertEquals(3, filtered.size) // Order by dataFim: OS-4 (14/08/26 07:00) -> OS-1024 (18/08/26 17:00) -> OS-1 (11/09/26 16:00) assertEquals("OS-4", filtered[0].numeroOs) assertEquals("OS-1024", filtered[1].numeroOs) assertEquals("OS-1", filtered[2].numeroOs) collectionJob.cancel() } db.close() } finally { kotlinx.coroutines.Dispatchers.resetMain() } } }