677 lines
27 KiB
Kotlin
677 lines
27 KiB
Kotlin
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 com.example.data.repository.MaintenanceRepository
|
|
import org.junit.Assert.assertEquals
|
|
import org.junit.Assert.assertNotNull
|
|
import org.junit.Assert.assertTrue
|
|
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<Context>()
|
|
val appName = context.getString(R.string.app_name)
|
|
assertEquals("Gestão Parada OS", appName)
|
|
}
|
|
|
|
@Test
|
|
fun `inspect project sheet`() {
|
|
val context = ApplicationProvider.getApplicationContext<Context>()
|
|
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<Context>()
|
|
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<Context>()
|
|
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 sorting OSs without start date appear at the very end of list`() {
|
|
val testDispatcher = kotlinx.coroutines.test.UnconfinedTestDispatcher()
|
|
kotlinx.coroutines.Dispatchers.setMain(testDispatcher)
|
|
try {
|
|
val context = ApplicationProvider.getApplicationContext<Context>()
|
|
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 actNoStart = com.example.data.model.MaintenanceActivity(
|
|
numeroOs = "OS-NO-START",
|
|
descricao = "OS without start date",
|
|
setor = "Geral",
|
|
equipe = "Mecânica",
|
|
recurso = "Sem Recurso",
|
|
dataInicio = "",
|
|
dataFim = "27/08/2026 17:00",
|
|
percentualExecucao = 0,
|
|
synced = true
|
|
)
|
|
val actValidStart = com.example.data.model.MaintenanceActivity(
|
|
numeroOs = "OS-VALID-START",
|
|
descricao = "OS with valid start date",
|
|
setor = "Geral",
|
|
equipe = "Elétrica",
|
|
recurso = "Sem Recurso",
|
|
dataInicio = "01/01/2026 08:00",
|
|
dataFim = "01/01/2026 17:00",
|
|
percentualExecucao = 0,
|
|
synced = true
|
|
)
|
|
|
|
kotlinx.coroutines.runBlocking {
|
|
db.maintenanceDao().insertActivities(listOf(actNoStart, actValidStart))
|
|
val viewModel = com.example.ui.viewmodel.MaintenanceViewModel(repository)
|
|
|
|
val job = viewModel.viewModelScope.launch {
|
|
viewModel.filteredActivities.collect {}
|
|
}
|
|
|
|
Thread.sleep(200)
|
|
org.robolectric.shadows.ShadowLooper.idleMainLooper()
|
|
|
|
val list = viewModel.filteredActivities.value
|
|
assertEquals(2, list.size)
|
|
assertEquals("OS-VALID-START", list[0].numeroOs)
|
|
assertEquals("OS-NO-START", list[1].numeroOs)
|
|
|
|
job.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<Context>()
|
|
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<Context>()
|
|
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<Context>()
|
|
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 dataInicio: OS-1 (04/08/26 07:00) -> OS-4 (14/08/26 07:00) -> OS-1024 (17/08/26 07:00)
|
|
assertEquals("OS-1", filtered[0].numeroOs)
|
|
assertEquals("OS-4", filtered[1].numeroOs)
|
|
assertEquals("OS-1024", filtered[2].numeroOs)
|
|
|
|
collectionJob.cancel()
|
|
}
|
|
db.close()
|
|
} finally {
|
|
kotlinx.coroutines.Dispatchers.resetMain()
|
|
}
|
|
}
|
|
|
|
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
|
@Test
|
|
fun `test analytics calculation and interactions with project CSV file`() {
|
|
val testDispatcher = kotlinx.coroutines.test.UnconfinedTestDispatcher()
|
|
kotlinx.coroutines.Dispatchers.setMain(testDispatcher)
|
|
try {
|
|
val context = ApplicationProvider.getApplicationContext<Context>()
|
|
val db = androidx.room.Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java).build()
|
|
val repository = MaintenanceRepository(db.maintenanceDao(), context)
|
|
|
|
val csvFile = java.io.File("/home/cesarjhony/dev/projects/gestao_de_manutencao/documentacao/exemplo_testes/GestaoOS_Parada_project.csv")
|
|
assertTrue(csvFile.exists())
|
|
|
|
val inputStream = csvFile.inputStream()
|
|
|
|
kotlinx.coroutines.runBlocking {
|
|
db.maintenanceDao().clearAllActivities()
|
|
db.maintenanceDao().clearAllHistory()
|
|
val result = repository.importCsvFromInputStream(inputStream)
|
|
if (result.isFailure) {
|
|
result.exceptionOrNull()?.printStackTrace()
|
|
}
|
|
assertTrue("Import CSV failed: ${result.exceptionOrNull()?.message}", result.isSuccess)
|
|
|
|
val activitiesList = db.maintenanceDao().getAllActivitiesList()
|
|
println("IMPORTED ACTIVITIES COUNT: ${activitiesList.size}")
|
|
if (activitiesList.isNotEmpty()) {
|
|
println("FIRST ACTIVITY: ${activitiesList.first()}")
|
|
}
|
|
|
|
val viewModel = com.example.ui.viewmodel.MaintenanceViewModel(repository)
|
|
|
|
val collectionJob = viewModel.viewModelScope.launch {
|
|
viewModel.analyticsState.collect {}
|
|
}
|
|
val historyJob = viewModel.viewModelScope.launch {
|
|
viewModel.allHistoryState.collect {}
|
|
}
|
|
|
|
Thread.sleep(500)
|
|
org.robolectric.shadows.ShadowLooper.idleMainLooper()
|
|
Thread.sleep(200)
|
|
|
|
val state = viewModel.analyticsState.value
|
|
println("ANALYTICS STATE TIMELINE DATES: ${state.timelineDates.size}")
|
|
assertNotNull(state)
|
|
assertEquals(5, state.timelineDates.size)
|
|
assertEquals(5, state.plannedProgressPoints.size)
|
|
assertEquals(5, state.realizedProgressPoints.size)
|
|
|
|
// 1. Current Date (July 2026): 0 or 1 overdue OS because CSV activities are in Aug/Sep 2026
|
|
val overdueJuly = state.overdueBySector.sumOf { it.second }
|
|
assertTrue("Expected overdueJuly <= 10.0, got $overdueJuly", overdueJuly <= 10.0)
|
|
|
|
// 2. Simulated Future Date (August 20, 2026): OSs due before Aug 20 start appearing as overdue
|
|
val aug20 = com.example.data.model.parseFullDateTime("20/08/26 18:00")!!
|
|
val stateAug20 = viewModel.calculateAnalyticsState(activitiesList, emptyList(), referenceDateOverride = aug20)
|
|
val overdueAug20 = stateAug20.overdueBySector.sumOf { it.second }
|
|
assertTrue("Expected overdue activities on Aug 20, 2026, got: $overdueAug20", overdueAug20 > 0.0)
|
|
|
|
// 3. Simulated Future Date (September 15, 2026): All incomplete activities in project are overdue
|
|
val sep15 = com.example.data.model.parseFullDateTime("15/09/26 18:00")!!
|
|
val stateSep15 = viewModel.calculateAnalyticsState(activitiesList, emptyList(), referenceDateOverride = sep15)
|
|
val overdueSep15 = stateSep15.overdueBySector.sumOf { it.second }
|
|
assertTrue("Expected most CSV activities to be overdue on Sep 15, got: $overdueSep15", overdueSep15 > 400.0)
|
|
|
|
val targetOs = db.maintenanceDao().getAllActivitiesList().firstOrNull()?.numeroOs ?: "1024"
|
|
repository.updateProgress(
|
|
numeroOs = targetOs,
|
|
novoPercentual = 100,
|
|
observacao = "Test OS completed",
|
|
fotoPath = null,
|
|
recurso = "GTEC 1",
|
|
emailEditor = "test@empresa.com"
|
|
)
|
|
|
|
Thread.sleep(200)
|
|
org.robolectric.shadows.ShadowLooper.idleMainLooper()
|
|
|
|
val historyList = db.maintenanceDao().getAllHistoryList()
|
|
assertTrue("History list size: ${historyList.size}", historyList.any { it.numeroOs == targetOs && it.percentualNovo == 100 })
|
|
|
|
collectionJob.cancel()
|
|
historyJob.cancel()
|
|
}
|
|
db.close()
|
|
} finally {
|
|
kotlinx.coroutines.Dispatchers.resetMain()
|
|
}
|
|
}
|
|
|
|
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
|
@Test
|
|
fun `test database epoch reconciliation and synced flag purge rules`() {
|
|
val testDispatcher = kotlinx.coroutines.test.UnconfinedTestDispatcher()
|
|
kotlinx.coroutines.Dispatchers.setMain(testDispatcher)
|
|
try {
|
|
val context = ApplicationProvider.getApplicationContext<Context>()
|
|
val db = androidx.room.Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
|
.allowMainThreadQueries()
|
|
.setQueryExecutor { it.run() }
|
|
.setTransactionExecutor { it.run() }
|
|
.build()
|
|
val dao = db.maintenanceDao()
|
|
|
|
kotlinx.coroutines.runBlocking {
|
|
dao.clearAllActivities()
|
|
dao.clearAllHistory()
|
|
dao.clearAllFindings()
|
|
|
|
// 1. Create active activity OS-100 and OS-200
|
|
val act1 = com.example.data.model.MaintenanceActivity(
|
|
numeroOs = "OS-100", descricao = "Tarefa 100", setor = "Mecânica", equipe = "Mecânica",
|
|
recurso = "Eng 1", dataInicio = "01/08/2026", dataFim = "02/08/2026", percentualExecucao = 50, synced = true
|
|
)
|
|
dao.insertActivity(act1)
|
|
|
|
// 2. Insert synced history for OS-999 (which is stale/removed remotely)
|
|
val staleSyncedHistory = com.example.data.model.OSUpdateHistory(
|
|
numeroOs = "OS-999", timestamp = 1000L, percentualAnterior = 0, percentualNovo = 50,
|
|
observacao = "Histórico antigo sincronizado", recurso = "Eng 1", synced = true
|
|
)
|
|
dao.insertHistory(staleSyncedHistory)
|
|
|
|
// 3. Insert unsynced history for OS-100 (pending offline change created by user)
|
|
val offlinePendingHistory = com.example.data.model.OSUpdateHistory(
|
|
numeroOs = "OS-100", timestamp = 2000L, percentualAnterior = 50, percentualNovo = 100,
|
|
observacao = "Histórico novo offline", recurso = "Eng 1", synced = false
|
|
)
|
|
dao.insertHistory(offlinePendingHistory)
|
|
|
|
// 4. Insert synced finding for OS-999 (stale) and unsynced finding for OS-100 (pending)
|
|
val staleSyncedFinding = com.example.data.model.OSFinding(
|
|
id = "finding-stale", numeroOs = "OS-999", tipo = "OBS", descricao = "Achado antigo",
|
|
timestamp = 1000L, responsavel = "Eng 1", synced = true
|
|
)
|
|
val offlinePendingFinding = com.example.data.model.OSFinding(
|
|
id = "finding-offline", numeroOs = "OS-100", tipo = "OBS", descricao = "Achado novo offline",
|
|
timestamp = 2000L, responsavel = "Eng 1", synced = false
|
|
)
|
|
dao.insertFinding(staleSyncedFinding)
|
|
dao.insertFinding(offlinePendingFinding)
|
|
|
|
// Verify initial state before epoch purge
|
|
assertEquals(2, dao.getAllHistoryList().size)
|
|
assertEquals(2, dao.getAllFindingsList().size)
|
|
assertEquals(1, dao.getUnsyncedHistory().size)
|
|
|
|
// 5. Execute Epoch purge (deleteAllSyncedHistory and deleteAllSyncedFindings)
|
|
dao.deleteAllSyncedHistory()
|
|
dao.deleteAllSyncedFindings()
|
|
|
|
// 6. Verify that ALL synced entries (OS-999) were purged, while unsynced entries (OS-100) were preserved
|
|
val historyAfterPurge = dao.getAllHistoryList()
|
|
assertEquals(1, historyAfterPurge.size)
|
|
assertEquals("OS-100", historyAfterPurge.first().numeroOs)
|
|
assertEquals(false, historyAfterPurge.first().synced)
|
|
|
|
val findingsAfterPurge = dao.getAllFindingsList()
|
|
assertEquals(1, findingsAfterPurge.size)
|
|
assertEquals("OS-100", findingsAfterPurge.first().numeroOs)
|
|
assertEquals(false, findingsAfterPurge.first().synced)
|
|
|
|
// 7. Test marking history as synced
|
|
val unsyncedHist = historyAfterPurge.first()
|
|
dao.markHistorySyncedByOsAndTimestamp(unsyncedHist.numeroOs, unsyncedHist.timestamp)
|
|
|
|
val historyFinal = dao.getAllHistoryList()
|
|
assertEquals(true, historyFinal.first().synced)
|
|
assertEquals(0, dao.getUnsyncedHistory().size)
|
|
}
|
|
db.close()
|
|
} finally {
|
|
kotlinx.coroutines.Dispatchers.resetMain()
|
|
}
|
|
}
|
|
|
|
@Test
|
|
fun `test fetchDatabaseEpoch graceful fallback`() {
|
|
val context = ApplicationProvider.getApplicationContext<Context>()
|
|
val service = GoogleSheetsSyncService(context)
|
|
val epoch = service.fetchDatabaseEpoch()
|
|
assertTrue("Epoch default should be >= 1, got $epoch", epoch >= 1)
|
|
}
|
|
}
|
|
|