Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / vpn / src / test / java / com / vayunmathur / vpn / platform / VpnViewModelTest.kt
VpnViewModelTest.kt252 lines · 13.2 KiBRaw
| 1 | package com.vayunmathur.vpn.platform |
| 2 | |
| 3 | import android.app.Application |
| 4 | import android.content.Context |
| 5 | import android.net.Uri |
| 6 | import androidx.test.core.app.ApplicationProvider |
| 7 | import com.vayunmathur.vpn.data.AppUsageSummary |
| 8 | import com.vayunmathur.vpn.data.ConnectionLogDao |
| 9 | import com.vayunmathur.vpn.data.ConnectionLogEntity |
| 10 | import com.vayunmathur.vpn.data.DomainBytesSummary |
| 11 | import com.vayunmathur.vpn.data.DomainCountSummary |
| 12 | import com.vayunmathur.vpn.data.VpnConfig |
| 13 | import com.vayunmathur.vpn.data.VpnConfigDao |
| 14 | import com.vayunmathur.vpn.data.VpnConfigEntity |
| 15 | import java.io.File |
| 16 | import kotlin.test.Test |
| 17 | import kotlin.test.assertEquals |
| 18 | import kotlin.test.assertNotNull |
| 19 | import kotlin.test.assertNull |
| 20 | import kotlin.test.assertTrue |
| 21 | import kotlinx.coroutines.delay |
| 22 | import kotlinx.coroutines.flow.Flow |
| 23 | import kotlinx.coroutines.flow.MutableStateFlow |
| 24 | import kotlinx.coroutines.flow.first |
| 25 | import kotlinx.coroutines.runBlocking |
| 26 | import kotlinx.coroutines.withTimeout |
| 27 | import org.junit.runner.RunWith |
| 28 | import org.robolectric.RobolectricTestRunner |
| 29 | import org.robolectric.Shadows |
| 30 | import org.robolectric.annotation.GraphicsMode |
| 31 | |
| 32 | @RunWith(RobolectricTestRunner::class) |
| 33 | @GraphicsMode(GraphicsMode.Mode.NATIVE) |
| 34 | class VpnViewModelTest { |
| 35 | private val app: Application get() = ApplicationProvider.getApplicationContext() |
| 36 | |
| 37 | class FakeConfigDao : VpnConfigDao { |
| 38 | val rows = MutableStateFlow<List<VpnConfigEntity>>(emptyList()) |
| 39 | var nextId = 1L |
| 40 | val touched = mutableListOf<Pair<Long, Long>>() |
| 41 | val deleted = mutableListOf<VpnConfigEntity>() |
| 42 | override fun flowAll(): Flow<List<VpnConfigEntity>> = rows |
| 43 | override suspend fun getById(id: Long): VpnConfigEntity? = rows.value.firstOrNull { it.id == id } |
| 44 | override suspend fun getAll(): List<VpnConfigEntity> = rows.value |
| 45 | override suspend fun upsert(entity: VpnConfigEntity): Long { |
| 46 | val id = if (entity.id == 0L) nextId++ else entity.id |
| 47 | rows.value = rows.value.filter { it.id != id } + entity.copy(id = id) |
| 48 | return id |
| 49 | } |
| 50 | override suspend fun delete(entity: VpnConfigEntity): Int { |
| 51 | deleted.add(entity); rows.value = rows.value.filter { it.id != entity.id }; return 1 |
| 52 | } |
| 53 | override suspend fun touch(id: Long, ts: Long) { touched.add(id to ts) } |
| 54 | } |
| 55 | |
| 56 | class FakeLogDao : ConnectionLogDao { |
| 57 | val topApps = MutableStateFlow<List<AppUsageSummary>>(emptyList()) |
| 58 | val byCount = MutableStateFlow<List<DomainCountSummary>>(emptyList()) |
| 59 | val byBytes = MutableStateFlow<List<DomainBytesSummary>>(emptyList()) |
| 60 | var unnamed = emptyList<Int>() |
| 61 | val named = mutableListOf<Triple<Int, String, String>>() |
| 62 | var deleteAllCalls = 0 |
| 63 | override fun flowTopApps(): Flow<List<AppUsageSummary>> = topApps |
| 64 | override fun flowDomainsByCount(): Flow<List<DomainCountSummary>> = byCount |
| 65 | override fun flowDomainsByBytes(): Flow<List<DomainBytesSummary>> = byBytes |
| 66 | override suspend fun unnamedUids(): List<Int> = unnamed |
| 67 | override suspend fun nameUid(uid: Int, packageName: String, appLabel: String) { named.add(Triple(uid, packageName, appLabel)) } |
| 68 | override suspend fun upsertAll(entities: List<ConnectionLogEntity>): List<Long> = entities.map { it.id } |
| 69 | override suspend fun deleteAll() { deleteAllCalls++ } |
| 70 | override suspend fun findIdentical(remoteIp: String, remotePort: Int, protocol: String, localPort: Int): ConnectionLogEntity? = null |
| 71 | } |
| 72 | |
| 73 | private fun vm(dao: FakeConfigDao = FakeConfigDao(), logDao: FakeLogDao = FakeLogDao()) = |
| 74 | VpnViewModel(app, dao, logDao) |
| 75 | |
| 76 | private suspend fun awaitIdle() { Shadows.shadowOf(android.os.Looper.getMainLooper()).idle() } |
| 77 | |
| 78 | @Test fun configsFlowMapsEntitiesToModels() { runBlocking { |
| 79 | val dao = FakeConfigDao() |
| 80 | dao.rows.value = listOf(VpnConfigEntity(id = 3, name = "x", peerEndpoint = "h:1")) |
| 81 | val vm = vm(dao) |
| 82 | val list = withTimeout(5000) { vm.configs.first { it.isNotEmpty() } } |
| 83 | assertEquals("x", list.single().name); assertEquals(3L, list.single().id) |
| 84 | assertNull(vm.connectingId.value); assertNull(vm.status.value) |
| 85 | } } |
| 86 | |
| 87 | @Test fun leaderboardsFlowThrough() { runBlocking { |
| 88 | val logDao = FakeLogDao().apply { |
| 89 | topApps.value = listOf(AppUsageSummary("com.a", "A", 100, 2)) |
| 90 | byCount.value = listOf(DomainCountSummary("a.com", 5)) |
| 91 | byBytes.value = listOf(DomainBytesSummary("a.com", 999)) |
| 92 | } |
| 93 | val vm = vm(logDao = logDao) |
| 94 | assertEquals(100L, withTimeout(5000) { vm.topAppsFlow.first { it.isNotEmpty() } }.single().totalBytes) |
| 95 | assertEquals(5L, withTimeout(5000) { vm.domainsByCountFlow.first { it.isNotEmpty() } }.single().totalCount) |
| 96 | assertEquals(999L, withTimeout(5000) { vm.domainsByBytesFlow.first { it.isNotEmpty() } }.single().totalBytes) |
| 97 | } } |
| 98 | |
| 99 | @Test fun upsertDeleteAndClearStatus() { runBlocking { |
| 100 | val dao = FakeConfigDao(); val vm = vm(dao) |
| 101 | var savedId = -1L |
| 102 | vm.upsert(VpnConfig(name = "new")) { savedId = it } |
| 103 | withTimeout(5000) { while (dao.rows.value.isEmpty()) delay(20) } |
| 104 | assertEquals("new", dao.rows.value.single().name) |
| 105 | val cfg = dao.rows.value.single().let { VpnConfig(id = it.id, name = it.name) } |
| 106 | vm.delete(cfg) |
| 107 | withTimeout(5000) { while (dao.rows.value.isNotEmpty()) delay(20) } |
| 108 | assertEquals(1, dao.deleted.size) |
| 109 | vm.clearStatus(); assertNull(vm.status.value) |
| 110 | } } |
| 111 | |
| 112 | @Test fun deletingLastBundleConfigRemovesBundleFiles() { runBlocking { |
| 113 | val dao = FakeConfigDao(); val vm = vm(dao) |
| 114 | val ctx = app as Context |
| 115 | val bundleDir = File(File(ctx.filesDir, "mavpn-bundles"), "bundle-1").apply { mkdirs() } |
| 116 | File(bundleDir, "manifest.json").writeText("{}") |
| 117 | dao.rows.value = listOf( |
| 118 | VpnConfigEntity(id = 1, name = "a", bundleId = "bundle-1", bundleServerId = "de-1"), |
| 119 | VpnConfigEntity(id = 2, name = "b", bundleId = "bundle-1", bundleServerId = "us-1"), |
| 120 | VpnConfigEntity(id = 3, name = "plain"), |
| 121 | ) |
| 122 | // Deleting one of two bundle configs keeps the bundle files. |
| 123 | vm.delete(VpnConfig(id = 1, name = "a", bundleId = "bundle-1", bundleServerId = "de-1")) |
| 124 | withTimeout(5000) { while (dao.rows.value.any { it.id == 1L }) delay(20) } |
| 125 | delay(100) |
| 126 | assertTrue(bundleDir.exists()) |
| 127 | // Deleting the last bundle config removes them; the plain config is untouched. |
| 128 | vm.delete(VpnConfig(id = 2, name = "b", bundleId = "bundle-1", bundleServerId = "us-1")) |
| 129 | withTimeout(5000) { while (bundleDir.exists()) delay(20) } |
| 130 | assertEquals(listOf(3L), dao.rows.value.map { it.id }) |
| 131 | // Deleting a plain (non-bundle) config never touches bundle storage. |
| 132 | vm.delete(VpnConfig(id = 3, name = "plain")) |
| 133 | withTimeout(5000) { while (dao.rows.value.isNotEmpty()) delay(20) } |
| 134 | } } |
| 135 | |
| 136 | @Test fun deletingBundleConfigToleratesMissingBundleFiles() { runBlocking { |
| 137 | val dao = FakeConfigDao(); val vm = vm(dao) |
| 138 | dao.rows.value = listOf( |
| 139 | VpnConfigEntity(id = 1, name = "a", bundleId = "never-stored", bundleServerId = "de-1"), |
| 140 | ) |
| 141 | vm.delete(VpnConfig(id = 1, name = "a", bundleId = "never-stored", bundleServerId = "de-1")) |
| 142 | withTimeout(5000) { while (dao.rows.value.isNotEmpty()) delay(20) } |
| 143 | assertEquals(1, dao.deleted.size) |
| 144 | } } |
| 145 | |
| 146 | @Test fun stopVpnSetsDisconnectedStatus() { |
| 147 | val vm = vm() |
| 148 | vm.stopVpn() |
| 149 | assertEquals("Disconnected", vm.status.value); assertNull(vm.connectingId.value) |
| 150 | // Shadow of started service: the disconnect intent was fired at the service |
| 151 | val started = Shadows.shadowOf(app).nextStartedService |
| 152 | assertNotNull(started); assertEquals(com.vayunmathur.vpn.service.VpnTunnelService.ACTION_DISCONNECT, started.action) |
| 153 | } |
| 154 | |
| 155 | @Test fun deleteAllLogsClearsDaoAndStatus() { runBlocking { |
| 156 | val logDao = FakeLogDao(); val vm = vm(logDao = logDao) |
| 157 | vm.deleteAllLogs() |
| 158 | assertEquals("Logs cleared", vm.status.value) |
| 159 | withTimeout(5000) { while (logDao.deleteAllCalls == 0) delay(20) } |
| 160 | } } |
| 161 | |
| 162 | @Test fun importFromUriSuccessAndFailures() { runBlocking { |
| 163 | val dao = FakeConfigDao(); val vm = vm(dao) |
| 164 | val ctx = app as Context |
| 165 | val conf = File(ctx.cacheDir, "tunnel1.conf").apply { |
| 166 | writeText("[Interface]\nPrivateKey = abc=\nAddress = 10.0.0.2/32\n[Peer]\nPublicKey = def=\nEndpoint = vpn.example.com:51820\n") |
| 167 | } |
| 168 | vm.importFromUri(ctx, Uri.fromFile(conf)) |
| 169 | withTimeout(8000) { while (dao.rows.value.isEmpty()) delay(25) } |
| 170 | assertEquals("tunnel1", dao.rows.value.single().name) |
| 171 | assertEquals("abc=", dao.rows.value.single().privateKey) |
| 172 | withTimeout(5000) { while (vm.status.value?.startsWith("Imported") != true) delay(25) } |
| 173 | // Bad file |
| 174 | val bad = File(ctx.cacheDir, "bad.conf").apply { writeText("not a config") } |
| 175 | vm.importFromUri(ctx, Uri.fromFile(bad)) |
| 176 | withTimeout(5000) { while (vm.status.value?.startsWith("Import failed") != true) delay(25) } |
| 177 | // Missing file |
| 178 | vm.importFromUri(ctx, Uri.parse("content://missing/x.conf")) |
| 179 | delay(200) |
| 180 | } } |
| 181 | |
| 182 | @Test fun importFromUriMavpnBundle() { runBlocking { |
| 183 | val dao = FakeConfigDao(); val vm = vm(dao) |
| 184 | val ctx = app as Context |
| 185 | val manifest = """{"format":"mavpn/1","provider":"Example VPN","servers":[""" + |
| 186 | """{"id":"de-1","country":"DE","city":"Frankfurt","file":"servers/de-1.conf", """ + |
| 187 | """"endpoint":"manifest.example:9999"}]}""" |
| 188 | val conf = "[Interface]\nPrivateKey = abc=\nAddress = 10.0.0.2/32\n[Peer]\nPublicKey = def=\nEndpoint = conf.example:51820\n" |
| 189 | val bundleFile = File(ctx.cacheDir, "demo.mavpn") |
| 190 | java.util.zip.ZipOutputStream(bundleFile.outputStream()).use { zip -> |
| 191 | for ((name, text) in listOf("manifest.json" to manifest, "servers/de-1.conf" to conf)) { |
| 192 | zip.putNextEntry(java.util.zip.ZipEntry(name)); zip.write(text.encodeToByteArray()); zip.closeEntry() |
| 193 | } |
| 194 | } |
| 195 | vm.importFromUri(ctx, Uri.fromFile(bundleFile)) |
| 196 | withTimeout(8000) { while (dao.rows.value.isEmpty()) delay(25) } |
| 197 | val row = dao.rows.value.single() |
| 198 | assertEquals("Example VPN", row.provider); assertEquals("DE", row.countryCode) |
| 199 | assertEquals("Frankfurt", row.city); assertEquals("de-1", row.bundleServerId) |
| 200 | assertEquals("manifest.example:9999", row.peerEndpoint) |
| 201 | withTimeout(5000) { while (vm.status.value?.startsWith("Imported 1 servers") != true) delay(25) } |
| 202 | assertEquals(listOf("Example VPN"), withTimeout(5000) { vm.importedProviders.first { it.isNotEmpty() } }) |
| 203 | assertEquals("Frankfurt", withTimeout(5000) { vm.geoCountries.first { it.isNotEmpty() } }.single().cities.single().city) |
| 204 | // The bundle was stored in app-private storage under its bundle id. |
| 205 | assertTrue(java.io.File(ctx.filesDir, "mavpn-bundles").listFiles()?.isNotEmpty() == true) |
| 206 | // A corrupt bundle fails cleanly with no new rows. |
| 207 | val badFile = File(ctx.cacheDir, "bad.mavpn").apply { writeBytes("not a zip".encodeToByteArray()) } |
| 208 | vm.importFromUri(ctx, Uri.fromFile(badFile)) |
| 209 | withTimeout(5000) { while (vm.status.value?.startsWith("Import failed") != true) delay(25) } |
| 210 | assertEquals(1, dao.rows.value.size) |
| 211 | } } |
| 212 | |
| 213 | @Test fun importNameFromEndpointWhenNoFileName() { runBlocking { |
| 214 | val dao = FakeConfigDao(); val vm = vm(dao) |
| 215 | val ctx = app as Context |
| 216 | // content uri with no meaningful last segment goes through contentResolver; use a file named ".conf" |
| 217 | val conf = File(ctx.cacheDir, ".conf").apply { |
| 218 | writeText("[Interface]\nPrivateKey = abc=\n[Peer]\nPublicKey = def=\nEndpoint = host.example:1234\n") |
| 219 | } |
| 220 | vm.importFromUri(ctx, Uri.fromFile(conf)) |
| 221 | withTimeout(8000) { while (dao.rows.value.isEmpty()) delay(25) } |
| 222 | val name = dao.rows.value.single().name |
| 223 | assertTrue(name.isNotBlank(), "name=$name") |
| 224 | } } |
| 225 | |
| 226 | @Test fun initPollClearsConnectingWhenServiceStopped() { |
| 227 | val vm = vm() |
| 228 | // The init loop polls VpnTunnelService.isRunning every 500ms and clears |
| 229 | // a stale connecting id; advancing the Robolectric clock runs iterations. |
| 230 | Shadows.shadowOf(android.os.Looper.getMainLooper()).idleFor(1200, java.util.concurrent.TimeUnit.MILLISECONDS) |
| 231 | assertNull(vm.connectingId.value) |
| 232 | } |
| 233 | |
| 234 | @Test fun factoryCreatesAndRejects() { |
| 235 | val factory = VpnViewModelFactory(app, FakeConfigDao(), FakeLogDao()) |
| 236 | assertNotNull(factory.create(VpnViewModel::class.java)) |
| 237 | try { |
| 238 | factory.create(String::class.java as Class<androidx.lifecycle.ViewModel>) |
| 239 | kotlin.test.fail("should reject other VM classes") |
| 240 | } catch (_: IllegalArgumentException) { /* expected */ } |
| 241 | } |
| 242 | |
| 243 | @Test fun bypassListRoundTrip() { runBlocking { |
| 244 | val ctx = app as Context |
| 245 | BypassList.setBypassed(ctx, "com.example.a", true) |
| 246 | withTimeout(5000) { while (!BypassList.load(ctx).contains("com.example.a")) delay(25) } |
| 247 | assertTrue(BypassList.flow(ctx).first().contains("com.example.a")) |
| 248 | BypassList.setBypassed(ctx, "com.example.a", false) |
| 249 | withTimeout(5000) { while (BypassList.load(ctx).contains("com.example.a")) delay(25) } |
| 250 | assertEquals("bypass_packages", BypassList.KEY) |
| 251 | } } |
| 252 | } |