Выпуск WDTT Plus v16
This commit is contained in:
1 parent
3038b8ddc0
commit
4be5f36c88
102 files changed
+21554
-1427
No files matched your search
@@ -1,6 +1,7 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
@@ -75,6 +76,45 @@ class ClientNetworkDiagnosticsTest {
|
||||
assertEquals(DeviceCheckAction.NetworkSettings, result.action)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun privateDnsWarningAppearsOnlyWhenPrivateDnsAndNetworkProblemMeet() {
|
||||
assertNull(
|
||||
buildPrivateDnsProblemItem(
|
||||
state = AndroidPrivateDnsState(active = false),
|
||||
dnsProblem = true,
|
||||
httpsProblem = true,
|
||||
)
|
||||
)
|
||||
assertNull(
|
||||
buildPrivateDnsProblemItem(
|
||||
state = AndroidPrivateDnsState(active = true, serverName = "dns.example"),
|
||||
dnsProblem = false,
|
||||
httpsProblem = false,
|
||||
)
|
||||
)
|
||||
|
||||
val item = buildPrivateDnsProblemItem(
|
||||
state = AndroidPrivateDnsState(active = true, serverName = "dns.google"),
|
||||
dnsProblem = true,
|
||||
httpsProblem = false,
|
||||
)
|
||||
|
||||
assertEquals("Android Private DNS", item?.title)
|
||||
assertEquals("включён (dns.google)", item?.status)
|
||||
assertEquals(DeviceCheckSeverity.Warning, item?.severity)
|
||||
assertEquals(DeviceCheckAction.NetworkSettings, item?.action)
|
||||
assertTrue(item?.recommendation?.contains("Частный DNS") == true)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun privateDnsRecommendationTailIsConditional() {
|
||||
assertEquals("", privateDnsRecommendationTail(AndroidPrivateDnsState(active = false)))
|
||||
assertEquals(
|
||||
", а также Android Private DNS",
|
||||
privateDnsRecommendationTail(AndroidPrivateDnsState(active = true, serverName = "dns.google")),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dnsQuery_containsExpectedHeaderNameAndARecordType() {
|
||||
val query = buildDnsQuery(clientDnsProbeHost, 0x1234)
|
||||
|
||||
@@ -44,6 +44,31 @@ class LogSeverityTest {
|
||||
assertNull(result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun vkCallsStreamPreflightLogs_arePresentedAsUserStatus() {
|
||||
for (streamId in listOf(100, 200, 300, 400)) {
|
||||
val start = classifyVkCallsLog("[STREAM $streamId] [VKCalls] preflight 1/2")
|
||||
assertEquals("vkcalls_start", start?.key)
|
||||
assertEquals("[VKCalls] Пробуем основной бескапчевый провайдер...", start?.message)
|
||||
assertEquals(false, start?.warning)
|
||||
}
|
||||
|
||||
val retry = classifyVkCallsLog(
|
||||
"[STREAM 300] [VKCalls] первая анонимная сессия не принята; повторяем один раз с новой идентичностью"
|
||||
)
|
||||
val fallback = classifyVkCallsLog(
|
||||
"[STREAM 400] [VKCalls] preflight не сработал после безопасного повтора: timeout; продолжаем резервную legacy-цепочку",
|
||||
isError = true,
|
||||
)
|
||||
|
||||
assertEquals("vkcalls_retry", retry?.key)
|
||||
assertEquals("[VKCalls] Повторяем проверку с новой анонимной сессией...", retry?.message)
|
||||
assertEquals(false, retry?.warning)
|
||||
assertEquals("vkcalls_fallback", fallback?.key)
|
||||
assertEquals("[VKCalls] Основной провайдер временно недоступен — пробуем совместимый резерв", fallback?.message)
|
||||
assertEquals(false, fallback?.warning)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun warningDoesNotCountAsUnreadError() {
|
||||
val warning = LogEntry("warning", "Повторяем", severity = LogSeverity.Warning)
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.util.Base64
|
||||
|
||||
class NativeClientStartupConfigTest {
|
||||
@Test
|
||||
fun startupSecretsAreEncodedOutsideProcessArguments() {
|
||||
val secrets = NativeClientStartupSecrets(
|
||||
vkHashes = "https://example.invalid/join/test",
|
||||
connectionPassword = "connection-secret",
|
||||
customVkClientId = "1234567",
|
||||
customVkClientSecret = "client-secret",
|
||||
)
|
||||
|
||||
val line = nativeClientStartupConfigLine(secrets)
|
||||
|
||||
assertTrue(line.startsWith("START_CONFIG|"))
|
||||
assertFalse(line.contains(secrets.vkHashes))
|
||||
assertFalse(line.contains(secrets.connectionPassword))
|
||||
assertFalse(line.contains(secrets.customVkClientSecret))
|
||||
|
||||
val decoded = String(
|
||||
Base64.getUrlDecoder().decode(line.substringAfter("START_CONFIG|")),
|
||||
Charsets.UTF_8,
|
||||
)
|
||||
val json = JSONObject(decoded)
|
||||
assertEquals(secrets.vkHashes, json.getString("vk_hashes"))
|
||||
assertEquals(secrets.connectionPassword, json.getString("connection_password"))
|
||||
assertEquals(secrets.customVkClientId, json.getString("custom_vk_client_id"))
|
||||
assertEquals(secrets.customVkClientSecret, json.getString("custom_vk_client_secret"))
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,53 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import java.security.MessageDigest
|
||||
import java.util.Base64
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ServerMigrationTest {
|
||||
@Test
|
||||
fun currentServerSnapshotWithBackupPolicyIsAccepted() {
|
||||
fun file(path: String, value: String): JSONObject {
|
||||
val data = value.toByteArray()
|
||||
val sha256 = MessageDigest.getInstance("SHA-256")
|
||||
.digest(data)
|
||||
.joinToString("") { "%02x".format(it) }
|
||||
return JSONObject()
|
||||
.put("path", path)
|
||||
.put("mode", 384)
|
||||
.put("size", data.size)
|
||||
.put("sha256", sha256)
|
||||
.put("data_b64", Base64.getEncoder().encodeToString(data))
|
||||
}
|
||||
val keys = List(4) { "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" }.joinToString("\n")
|
||||
val response = JSONObject()
|
||||
.put("format", "wdtt-server-snapshot")
|
||||
.put("version", 3)
|
||||
.put("id", "20260902T151523Z-d43d8a6dd6ab")
|
||||
.put("created_at", 1_778_000_000L)
|
||||
.put("reason", "manual")
|
||||
.put("server_version", "16")
|
||||
.put("password_count", 0)
|
||||
.put("device_count", 0)
|
||||
.put(
|
||||
"files",
|
||||
JSONArray()
|
||||
.put(file("passwords.json", "{}"))
|
||||
.put(file("wg-keys.dat", keys))
|
||||
.put(file("backup-policy.json", "{\"enabled\":false,\"interval_hours\":24,\"retention_count\":14}"))
|
||||
)
|
||||
|
||||
val parsed = ServerAdminClient.parseBackupDocument(response)
|
||||
|
||||
assertEquals(3, parsed.files.size)
|
||||
assertTrue(parsed.files.any { it.path == "backup-policy.json" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun skippedVersionsAccumulateLatestServerMigration() {
|
||||
val result = resolveServerMigrationInitialization(
|
||||
@@ -98,6 +140,38 @@ class ServerMigrationTest {
|
||||
assertEquals(15, latestServerMigrationLevel(15))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun updateFrom15To16RequiresServerMigration() {
|
||||
val result = resolveServerMigrationInitialization(
|
||||
currentVersionCode = 16,
|
||||
isUpdatedInstall = true,
|
||||
storedLastSeenAppVersionCode = 15,
|
||||
storedPendingLevel = 15,
|
||||
storedAcknowledgedLevel = 15,
|
||||
legacyAcknowledgedLevel = 5
|
||||
)
|
||||
|
||||
assertEquals(16, result.pendingLevel)
|
||||
assertEquals(15, result.acknowledgedLevel)
|
||||
assertEquals(16, latestServerMigrationLevel(16))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun reinstallSameVersionDoesNotCreateServerMigrationNotice() {
|
||||
val result = resolveServerMigrationInitialization(
|
||||
currentVersionCode = 16,
|
||||
isUpdatedInstall = true,
|
||||
storedLastSeenAppVersionCode = 16,
|
||||
storedPendingLevel = 15,
|
||||
storedAcknowledgedLevel = 15,
|
||||
legacyAcknowledgedLevel = 5
|
||||
)
|
||||
|
||||
assertEquals(15, result.pendingLevel)
|
||||
assertEquals(15, result.acknowledgedLevel)
|
||||
assertEquals(16, latestServerMigrationLevel(16))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stateSeparatesReadNoticeFromCompletedDeployment() {
|
||||
val state = ServerMigrationState(
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import com.wdtt.plus.ui.adjustSleepTimerHours
|
||||
import com.wdtt.plus.ui.adjustSleepTimerMinutes
|
||||
import com.wdtt.plus.ui.formatSleepTimerDuration
|
||||
import com.wdtt.plus.ui.replaceSleepTimerMinuteComponent
|
||||
import com.wdtt.plus.ui.sleepBatteryModeDiagnosticText
|
||||
@@ -41,6 +42,15 @@ class SleepTimerPolicyTest {
|
||||
assertEquals(24 * 60, adjustSleepTimerHours(totalMinutes = 23 * 60 + 30, hoursDelta = 1))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun tvDpadAdjustsSleepTimerInFiveMinuteStepsWithinBounds() {
|
||||
assertEquals(40, adjustSleepTimerMinutes(totalMinutes = 35, direction = 1))
|
||||
assertEquals(30, adjustSleepTimerMinutes(totalMinutes = 35, direction = -1))
|
||||
assertEquals(0, adjustSleepTimerMinutes(totalMinutes = 0, direction = -1))
|
||||
assertEquals(24 * 60, adjustSleepTimerMinutes(totalMinutes = 24 * 60, direction = 1))
|
||||
assertEquals(35, adjustSleepTimerMinutes(totalMinutes = 35, direction = 0))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dialReplacesMinutesAndCountsFullTurnsAsHours() {
|
||||
assertEquals(165, replaceSleepTimerMinuteComponent(totalMinutes = 125, minute = 45))
|
||||
|
||||
@@ -34,10 +34,10 @@ class TunnelRecoveryPolicyTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun vkCallsPreflightFailuresKeepTheirCooldownAcrossNativeRestarts() {
|
||||
fun onlyConfirmedVkCallsFloodKeepsCooldownAcrossNativeRestarts() {
|
||||
assertEquals(60_000L, vkCallsPreflightCooldownForLog("[VKCalls] VK временно ограничил анонимный вход"))
|
||||
assertEquals(120_000L, vkCallsPreflightCooldownForLog("[VKCalls] VKCalls запросил CAPTCHA; временно не повторяем preflight"))
|
||||
assertEquals(45_000L, vkCallsPreflightCooldownForLog("[VKCalls] preflight не сработал: timeout; временно не повторяем его"))
|
||||
assertEquals(0L, vkCallsPreflightCooldownForLog("[VKCalls] две современные анонимные сессии запросили CAPTCHA"))
|
||||
assertEquals(0L, vkCallsPreflightCooldownForLog("[VKCalls] preflight не сработал после безопасного повтора: timeout"))
|
||||
assertEquals(0L, vkCallsPreflightCooldownForLog("[VKCalls] TURN credentials получены"))
|
||||
}
|
||||
|
||||
@@ -123,6 +123,53 @@ class TunnelRecoveryPolicyTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun firstStatsSampleOnlyInitializesBaselineAndDoesNotFakeInboundTraffic() {
|
||||
assertEquals(
|
||||
TrafficSignatureDelta(
|
||||
initializeBaseline = true,
|
||||
downstreamChanged = false,
|
||||
upstreamChanged = false,
|
||||
),
|
||||
classifyTrafficSignatureDelta(
|
||||
previousDownstream = "",
|
||||
previousUpstream = "",
|
||||
currentDownstream = "0.08",
|
||||
currentUpstream = "0.04",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun onlyARealCounterChangeBecomesFreshTrafficEvidence() {
|
||||
assertEquals(
|
||||
TrafficSignatureDelta(
|
||||
initializeBaseline = false,
|
||||
downstreamChanged = true,
|
||||
upstreamChanged = false,
|
||||
),
|
||||
classifyTrafficSignatureDelta(
|
||||
previousDownstream = "0.08",
|
||||
previousUpstream = "0.04",
|
||||
currentDownstream = "0.09",
|
||||
currentUpstream = "0.04",
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
TrafficSignatureDelta(
|
||||
initializeBaseline = false,
|
||||
downstreamChanged = false,
|
||||
upstreamChanged = false,
|
||||
),
|
||||
classifyTrafficSignatureDelta(
|
||||
previousDownstream = "0.08",
|
||||
previousUpstream = "0.04",
|
||||
currentDownstream = "0.08",
|
||||
currentUpstream = "0.04",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun firstRecoveryIsTransportOnly() {
|
||||
assertEquals(
|
||||
@@ -633,6 +680,38 @@ class TunnelRecoveryPolicyTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun repeatedTransportTimeoutsEnterRecoveryInsteadOfImmediateCriticalStop() {
|
||||
assertEquals(
|
||||
true,
|
||||
shouldDeferRepeatedTransportErrorStop(
|
||||
line = "TURN UDP подключение 91.231.135.175:19302: dial udp: connect: network is unreachable",
|
||||
refusedCount = 400,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
true,
|
||||
shouldDeferRepeatedTransportErrorStop(
|
||||
line = "read udp timeout",
|
||||
refusedCount = 400,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
false,
|
||||
shouldDeferRepeatedTransportErrorStop(
|
||||
line = "read udp timeout",
|
||||
refusedCount = 399,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
false,
|
||||
shouldDeferRepeatedTransportErrorStop(
|
||||
line = "FATAL_AUTH неверный пароль",
|
||||
refusedCount = 400,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun confirmedFailureTimestampMustExistAndMatchRequestedWindow() {
|
||||
assertEquals(false, hasConfirmedNetworkFailureAtOrAfter(true, 0L, 0L))
|
||||
@@ -688,6 +767,64 @@ class TunnelRecoveryPolicyTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun wakeRecoveryRequiresFreshServerPathAndHasBoundedFinalDecision() {
|
||||
assertEquals(
|
||||
WakeRescueAction.HEALTHY,
|
||||
decideWakeRescueAction(
|
||||
freshTransportPath = true,
|
||||
activeWorkers = 9,
|
||||
confirmedNetworkFailure = false,
|
||||
finalCheck = false,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
WakeRescueAction.RECONNECT,
|
||||
decideWakeRescueAction(
|
||||
freshTransportPath = false,
|
||||
activeWorkers = 0,
|
||||
confirmedNetworkFailure = false,
|
||||
finalCheck = false,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
WakeRescueAction.WAIT_FOR_PROBE,
|
||||
decideWakeRescueAction(
|
||||
freshTransportPath = false,
|
||||
activeWorkers = 9,
|
||||
confirmedNetworkFailure = false,
|
||||
finalCheck = false,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
WakeRescueAction.RECONNECT,
|
||||
decideWakeRescueAction(
|
||||
freshTransportPath = false,
|
||||
activeWorkers = 9,
|
||||
confirmedNetworkFailure = false,
|
||||
finalCheck = true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun wakeRecoveryIncludesPongThatArrivedBeforeRescueJobStarted() {
|
||||
assertEquals(
|
||||
10_000L,
|
||||
wakeRecoveryReferenceAt(
|
||||
lastDeviceWakeAtMs = 10_000L,
|
||||
nowMs = 10_250L,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
80_001L,
|
||||
wakeRecoveryReferenceAt(
|
||||
lastDeviceWakeAtMs = 10_000L,
|
||||
nowMs = 80_001L,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun tunnelHealthIsNotJudgedDuringSleepOrWakeStabilization() {
|
||||
assertEquals(
|
||||
|
||||
@@ -4,6 +4,11 @@ import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class TunnelStartConfigTest {
|
||||
@Test
|
||||
fun `wireguard config is required before workers for every profile`() {
|
||||
assertEquals(true, shouldUseConfigFirstStart())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `tile and widgets stop both active and trusted wifi waiting tunnel`() {
|
||||
assertEquals(
|
||||
@@ -44,4 +49,24 @@ class TunnelStartConfigTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `stop action is selected before any permission probe`() {
|
||||
assertEquals(
|
||||
TunnelToggleAction.STOP,
|
||||
tunnelToggleAction(
|
||||
running = true,
|
||||
trustedWifiWaiting = false,
|
||||
vpnPermissionRequired = true,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
TunnelToggleAction.STOP,
|
||||
tunnelToggleAction(
|
||||
running = false,
|
||||
trustedWifiWaiting = true,
|
||||
vpnPermissionRequired = true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -82,6 +82,39 @@ class VpnAddressRoutingTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rejectsDomainZonesAndIncompleteSingleLabelNamesWithClearReason() {
|
||||
listOf("ru", "su", "рф", "xn--p1ai", "https://ru/").forEach { value ->
|
||||
val error = assertThrows(IllegalArgumentException::class.java) {
|
||||
normalizeVpnAddressRules(value)
|
||||
}
|
||||
assertTrue(error.message.orEmpty().contains("доменная зона"))
|
||||
assertTrue(error.message.orEmpty().contains("точный домен"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun legacySingleLabelRuleCanStillBeDecodedWithoutSilentDataLoss() {
|
||||
val encoded = encodeVpnAddressRules(
|
||||
listOf(VpnAddressRule(VpnAddressType.DOMAIN, "ru"))
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
listOf(VpnAddressRule(VpnAddressType.DOMAIN, "ru")),
|
||||
decodeVpnAddressRules(encoded),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun multilineAddressValidationReportsBadLine() {
|
||||
val error = assertThrows(IllegalArgumentException::class.java) {
|
||||
normalizeVpnAddressRules("example.org\nru\n192.0.2.1")
|
||||
}
|
||||
|
||||
assertTrue(error.message.orEmpty().startsWith("Строка 2:"))
|
||||
assertTrue(error.message.orEmpty().contains("доменная зона"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun codecPreservesValidatedRules() {
|
||||
val rules = listOf(
|
||||
@@ -106,6 +139,78 @@ class VpnAddressRoutingTest {
|
||||
assertEquals(document, decodeVpnRoutingDocument(encodeVpnRoutingDocument(document)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun routingDocumentExportNormalizesDataAndRemainsImportable() {
|
||||
val encoded = encodeVpnRoutingDocument(
|
||||
VpnRoutingDocument(
|
||||
isWhitelist = false,
|
||||
blacklistApps = listOf(" app.black ", "app.black"),
|
||||
whitelistApps = emptyList(),
|
||||
blacklistAddresses = listOf(
|
||||
VpnAddressRule(VpnAddressType.SUBNET, "192.168.1.77/24"),
|
||||
VpnAddressRule(VpnAddressType.SUBNET, "192.168.1.0/24"),
|
||||
),
|
||||
whitelistAddresses = emptyList(),
|
||||
),
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
VpnRoutingDocument(
|
||||
isWhitelist = false,
|
||||
blacklistApps = listOf("app.black"),
|
||||
whitelistApps = emptyList(),
|
||||
blacklistAddresses = listOf(VpnAddressRule(VpnAddressType.SUBNET, "192.168.1.0/24")),
|
||||
whitelistAddresses = emptyList(),
|
||||
),
|
||||
decodeVpnRoutingDocument(encoded),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun routingDocumentExportNeverSilentlyDropsOversizedAddressLists() {
|
||||
val addresses = (0..128).map { index ->
|
||||
VpnAddressRule(
|
||||
VpnAddressType.IP,
|
||||
"192.0.${index / 256}.${index % 256}",
|
||||
)
|
||||
}
|
||||
|
||||
val error = assertThrows(IllegalArgumentException::class.java) {
|
||||
encodeVpnRoutingDocument(
|
||||
VpnRoutingDocument(false, emptyList(), emptyList(), addresses, emptyList())
|
||||
)
|
||||
}
|
||||
|
||||
assertTrue(error.message.orEmpty().contains("не больше 128"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun routingDocumentExportNeverCreatesAnUnimportableApplicationList() {
|
||||
val packages = (0..5_000).map { index -> "app.exported.p$index" }
|
||||
|
||||
val error = assertThrows(IllegalArgumentException::class.java) {
|
||||
encodeVpnRoutingDocument(
|
||||
VpnRoutingDocument(false, packages, emptyList(), emptyList(), emptyList())
|
||||
)
|
||||
}
|
||||
|
||||
assertTrue(error.message.orEmpty().contains("слишком большой"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun routingDocumentExportNeverExceedsItsOwnImportByteLimit() {
|
||||
val longSegment = "a".repeat(235)
|
||||
val packages = (0 until 5_000).map { index -> "app.${longSegment}p$index" }
|
||||
|
||||
val error = assertThrows(IllegalArgumentException::class.java) {
|
||||
encodeVpnRoutingDocument(
|
||||
VpnRoutingDocument(false, packages, emptyList(), emptyList(), emptyList())
|
||||
)
|
||||
}
|
||||
|
||||
assertTrue(error.message.orEmpty().contains("слишком большая для экспорта"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun routingDocumentRejectsInvalidPackagesAndMissingLists() {
|
||||
val valid = JSONObject(encodeVpnRoutingDocument(
|
||||
|
||||
@@ -25,7 +25,7 @@ class VpnAppRoutingTest {
|
||||
|
||||
assertTrue(routing.included.isEmpty())
|
||||
assertEquals(
|
||||
setOf(ownPackage, "com.vkontakte.android", "com.vk.calls", "app.one"),
|
||||
setOf(ownPackage, "app.one"),
|
||||
routing.excluded
|
||||
)
|
||||
}
|
||||
@@ -39,7 +39,7 @@ class VpnAppRoutingTest {
|
||||
ownPackageName = ownPackage
|
||||
)
|
||||
|
||||
assertEquals(setOf("app.two"), routing.included)
|
||||
assertEquals(setOf("app.two", "com.vkontakte.android"), routing.included)
|
||||
assertTrue(routing.excluded.isEmpty())
|
||||
}
|
||||
|
||||
@@ -72,7 +72,7 @@ class VpnAppRoutingTest {
|
||||
|
||||
assertTrue(routing.included.isEmpty())
|
||||
assertEquals(
|
||||
setOf(ownPackage, "com.vkontakte.android", "com.vk.calls"),
|
||||
setOf(ownPackage),
|
||||
routing.excluded,
|
||||
)
|
||||
assertTrue(!routing.blocksAllApps)
|
||||
@@ -99,7 +99,7 @@ class VpnAppRoutingTest {
|
||||
@Test
|
||||
fun importedRoutingCannotKeepHiddenRequiredBypassPackages() {
|
||||
assertEquals(
|
||||
listOf("app.one", "app.two"),
|
||||
listOf("app.one", "app.two", "com.vk.calls", "com.vkontakte.android"),
|
||||
sanitizeVpnRoutingPackages(
|
||||
packageNames = listOf(
|
||||
ownPackage,
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class VpnSlotHandoverPolicyTest {
|
||||
@Test
|
||||
fun `safe establish refusal yields instead of retrying or taking the slot`() {
|
||||
assertTrue(
|
||||
shouldYieldVpnSlotAfterSafeEstablishFailure(
|
||||
SafeGoBackend.VpnSlotUnavailableException(),
|
||||
),
|
||||
)
|
||||
assertTrue(
|
||||
shouldYieldVpnSlotAfterSafeEstablishFailure(
|
||||
IllegalStateException("start failed", SafeGoBackend.VpnSlotUnavailableException()),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `ordinary tunnel failure keeps the established recovery path available`() {
|
||||
assertFalse(
|
||||
shouldYieldVpnSlotAfterSafeEstablishFailure(
|
||||
IllegalStateException("DNS unavailable"),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import java.io.File
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class DeployDataSafetyTest {
|
||||
@Test
|
||||
fun `deploy script keeps all config and never accepts secret process arguments`() {
|
||||
val script = sequenceOf(
|
||||
File("app/src/main/assets/deploy.sh"),
|
||||
File("src/main/assets/deploy.sh")
|
||||
).first(File::isFile).readText()
|
||||
|
||||
assertTrue("legacy free-form process arguments remain", "WDTT_ARGS" !in script)
|
||||
assertTrue("preserve mode must keep the whole config tree", "всё содержимое /etc/wdtt сохранено" in script)
|
||||
assertTrue("existing database reset guard is missing", "Найдена существующая база WDTT" in script)
|
||||
assertTrue("staged server version is not checked before replacement", "staged_version" in script)
|
||||
assertTrue("failed service start does not fail deployment", "Сервис wdtt не прошёл проверку запуска" in script)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `destructive reset opens a separate hold dialog and prepares rollback`() {
|
||||
val source = sequenceOf(
|
||||
File("app/src/main/java/com/wdtt/plus/ui/DeployTab.kt"),
|
||||
File("src/main/java/com/wdtt/plus/ui/DeployTab.kt")
|
||||
).first(File::isFile).readText()
|
||||
|
||||
assertTrue("reset must open a separate confirmation dialog", "ServerResetConfirmDialog(" in source)
|
||||
assertTrue("reset must use the shared hold guard", "actionLabel = \"Начать с нуля\"" in source)
|
||||
assertFalse("legacy reset phrase must not clutter the main dialog", "Для сброса введите СБРОСИТЬ" in source)
|
||||
assertTrue(
|
||||
"managed Android reset must prepare rollback",
|
||||
"mode == DeployMode.ResetAll && ownership == DeploymentOwnership.AndroidDeploy" in source
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `dangerous server hold confirms once only after three uninterrupted seconds`() {
|
||||
val start = advanceDangerousServerHold(
|
||||
current = DangerousServerHoldState(),
|
||||
pressed = true,
|
||||
safetyReady = true,
|
||||
nowElapsedMs = 1_000L
|
||||
)
|
||||
val early = advanceDangerousServerHold(start.state, true, true, 3_999L)
|
||||
val complete = advanceDangerousServerHold(early.state, true, true, 4_000L)
|
||||
val repeated = advanceDangerousServerHold(complete.state, true, true, 5_000L)
|
||||
|
||||
assertEquals(DANGEROUS_SERVER_HOLD_MS, start.remainingMs)
|
||||
assertFalse(start.confirmed)
|
||||
assertEquals(1L, early.remainingMs)
|
||||
assertFalse(early.confirmed)
|
||||
assertEquals(0L, complete.remainingMs)
|
||||
assertTrue(complete.confirmed)
|
||||
assertFalse("one continuous press must not execute twice", repeated.confirmed)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `dangerous server hold resets on release or lost safety condition`() {
|
||||
val started = advanceDangerousServerHold(
|
||||
current = DangerousServerHoldState(),
|
||||
pressed = true,
|
||||
safetyReady = true,
|
||||
nowElapsedMs = 10_000L
|
||||
)
|
||||
val released = advanceDangerousServerHold(started.state, false, true, 12_500L)
|
||||
val restarted = advanceDangerousServerHold(released.state, true, true, 20_000L)
|
||||
val connectionLost = advanceDangerousServerHold(restarted.state, true, false, 22_900L)
|
||||
val afterReconnect = advanceDangerousServerHold(connectionLost.state, true, true, 23_000L)
|
||||
|
||||
assertEquals(DangerousServerHoldState(), released.state)
|
||||
assertEquals(DANGEROUS_SERVER_HOLD_MS, released.remainingMs)
|
||||
assertFalse(released.confirmed)
|
||||
assertEquals(DangerousServerHoldState(), connectionLost.state)
|
||||
assertEquals(DANGEROUS_SERVER_HOLD_MS, connectionLost.remainingMs)
|
||||
assertEquals(DANGEROUS_SERVER_HOLD_MS, afterReconnect.remainingMs)
|
||||
assertFalse(afterReconnect.confirmed)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `backup settings expose a dirty state until saved values match`() {
|
||||
assertFalse(
|
||||
hasUnsavedServerBackupSettings(
|
||||
savedEnabled = true,
|
||||
savedIntervalHours = 24,
|
||||
savedRetentionCount = 14,
|
||||
enabledInput = true,
|
||||
intervalInput = "24",
|
||||
retentionInput = "14"
|
||||
)
|
||||
)
|
||||
assertTrue(
|
||||
hasUnsavedServerBackupSettings(
|
||||
savedEnabled = true,
|
||||
savedIntervalHours = 24,
|
||||
savedRetentionCount = 14,
|
||||
enabledInput = false,
|
||||
intervalInput = "24",
|
||||
retentionInput = "14"
|
||||
)
|
||||
)
|
||||
assertTrue(serverBackupSettingsAreValid("6", "90"))
|
||||
assertFalse(serverBackupSettingsAreValid("5", "14"))
|
||||
assertFalse(serverBackupSettingsAreValid("24", ""))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `restore scroll aligns title to viewport and every restore creates a new request`() {
|
||||
assertEquals(
|
||||
510,
|
||||
restoreSectionScrollTarget(
|
||||
currentScroll = 100,
|
||||
titleTopInWindow = 500f,
|
||||
viewportTopInWindow = 80f,
|
||||
revealOffsetPx = 10f,
|
||||
maxScroll = 2_000
|
||||
)
|
||||
)
|
||||
|
||||
val source = sequenceOf(
|
||||
File("app/src/main/java/com/wdtt/plus/ui/DeployTab.kt"),
|
||||
File("src/main/java/com/wdtt/plus/ui/DeployTab.kt")
|
||||
).first(File::isFile).readText()
|
||||
assertTrue("each successful restore must retrigger scrolling", "restoreScrollRequestId += 1" in source)
|
||||
assertTrue("scrolling must use the restore title coordinates", "titleModifier = Modifier.onGloballyPositioned" in source)
|
||||
val backupCardSource = source
|
||||
.substringAfter("private fun ServerBackupManagementCard(")
|
||||
.substringBefore("private fun ServerBackupPanel(")
|
||||
assertTrue(
|
||||
"backup settings status height must animate to zero",
|
||||
"targetValue = if (hasUnsavedSettings) 58.dp else 0.dp" in backupCardSource &&
|
||||
".height(unsavedSettingsAreaHeight)" in backupCardSource
|
||||
)
|
||||
assertFalse(
|
||||
"backup settings status must not use its old permanently reserved height",
|
||||
".fillMaxWidth()\n .height(48.dp)" in backupCardSource
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `backup history keeps information in pager and actions in a separate selected panel`() {
|
||||
val source = sequenceOf(
|
||||
File("app/src/main/java/com/wdtt/plus/ui/DeployTab.kt"),
|
||||
File("src/main/java/com/wdtt/plus/ui/DeployTab.kt")
|
||||
).first(File::isFile).readText()
|
||||
val historySource = source
|
||||
.substringAfter("private fun ServerBackupsPager(")
|
||||
.substringBefore("private fun ServerBackupSwipeHint(")
|
||||
val cardSource = historySource
|
||||
.substringAfter("private fun ServerBackupCard(")
|
||||
.substringBefore("private fun ColumnScope.ServerBackupActions(")
|
||||
val actionsSource = historySource.substringAfter("private fun ColumnScope.ServerBackupActions(")
|
||||
|
||||
assertFalse("scrolling backup cards must not contain action buttons", "onRestore" in cardSource)
|
||||
assertTrue("selected backup actions must be rendered separately", "onRestore(backup)" in actionsSource)
|
||||
assertTrue("backup card must show verified content metadata", "contentMetadataAvailable" in cardSource)
|
||||
assertTrue("selected backup must follow the pager selection", "val selectedBackup = backups[selectedBackupIndex]" in source)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `portable backup device count matches client view and excludes owner or orphan records`() {
|
||||
val database = JSONObject()
|
||||
.put(
|
||||
"admin_profile",
|
||||
JSONObject().put("device_ids", org.json.JSONArray().put("owner-phone"))
|
||||
)
|
||||
.put(
|
||||
"devices",
|
||||
JSONObject()
|
||||
.put("client-phone", JSONObject())
|
||||
.put("owner-phone", JSONObject())
|
||||
.put("orphan", JSONObject())
|
||||
)
|
||||
.put(
|
||||
"passwords",
|
||||
JSONObject().put(
|
||||
"ABCDEFGHJKLMNPQR",
|
||||
JSONObject()
|
||||
.put("device_id", "client-phone")
|
||||
.put(
|
||||
"bind_history",
|
||||
org.json.JSONArray()
|
||||
.put(JSONObject().put("device_id", "client-phone").put("bound_at", 10).put("status", "active"))
|
||||
.put(JSONObject().put("device_id", "old-client-phone").put("bound_at", 5).put("status", "unbound"))
|
||||
.put(JSONObject().put("device_id", "rejected-phone").put("status", "denied_mismatch"))
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
assertEquals(2, clientDeviceCountForBackup(database))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `backup history uses the established client carousel layout`() {
|
||||
val source = sequenceOf(
|
||||
File("app/src/main/java/com/wdtt/plus/ui/DeployTab.kt"),
|
||||
File("src/main/java/com/wdtt/plus/ui/DeployTab.kt")
|
||||
).first(File::isFile).readText()
|
||||
|
||||
assertTrue("backup carousel is missing", "private fun ServerBackupsPager(" in source)
|
||||
assertTrue("backup cards must use HorizontalPager", "HorizontalPager(" in source)
|
||||
assertTrue("neighboring backup cards must remain visible", "contentPadding = PaddingValues(horizontal = 18.dp)" in source)
|
||||
assertTrue("backup carousel arrows and dots are missing", "private fun ServerBackupSwipeHint(" in source)
|
||||
assertTrue("unsaved policy state is not visible", "Изменения не сохранены" in source)
|
||||
assertTrue("restore result must scroll to its next step", "migrationImportTopInWindow" in source)
|
||||
assertFalse("duplicate backup heading must be removed", "Резервные копии сервера" in source)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `backup cards use correct russian count forms`() {
|
||||
assertEquals("1 клиент", backupClientCountLabel(1))
|
||||
assertEquals("2 клиента", backupClientCountLabel(2))
|
||||
assertEquals("5 клиентов", backupClientCountLabel(5))
|
||||
assertEquals("11 клиентов", backupClientCountLabel(11))
|
||||
assertEquals("21 клиент", backupClientCountLabel(21))
|
||||
assertEquals("1 устройство", backupDeviceCountLabel(1))
|
||||
assertEquals("3 устройства", backupDeviceCountLabel(3))
|
||||
assertEquals("14 устройств", backupDeviceCountLabel(14))
|
||||
assertEquals("22 устройства", backupDeviceCountLabel(22))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `server backup management keeps secrets off argv and uses guarded destructive actions`() {
|
||||
val adminSource = sequenceOf(
|
||||
File("app/src/main/java/com/wdtt/plus/ServerAdminClient.kt"),
|
||||
File("src/main/java/com/wdtt/plus/ServerAdminClient.kt")
|
||||
).first(File::isFile).readText()
|
||||
val deploySource = sequenceOf(
|
||||
File("app/src/main/java/com/wdtt/plus/ui/DeployTab.kt"),
|
||||
File("src/main/java/com/wdtt/plus/ui/DeployTab.kt")
|
||||
).first(File::isFile).readText()
|
||||
|
||||
assertTrue("admin requests must use the protected stdin contract", "--request-stdin" in adminSource)
|
||||
assertTrue("Android must accept the current server snapshot format", "require(version in 1..3)" in adminSource)
|
||||
assertTrue("SSH admin output must have a hard resource limit", "MAX_COMMAND_OUTPUT_CHARS" in adminSource)
|
||||
assertTrue(
|
||||
"main password must not be interpolated into the admin command",
|
||||
"--main-password ${'$'}{shellQuote(target.mainPassword)}" !in adminSource
|
||||
)
|
||||
assertTrue("destructive restore must use the shared hold guard", "actionLabel = if (isDeploy) \"Продолжить\" else \"Заменить\"" in deploySource)
|
||||
assertTrue("backup deletion must use the shared hold guard", "guardKey = backup.id" in deploySource)
|
||||
assertFalse("legacy restore phrase must be removed", "Для замены введите ВОССТАНОВИТЬ" in deploySource)
|
||||
assertFalse("legacy delete phrase must be removed", "Введите УДАЛИТЬ" in deploySource)
|
||||
assertTrue("server must receive the delete confirmation too", "\"--confirm\", \"УДАЛИТЬ\"" in adminSource)
|
||||
assertTrue("backup download must use Android document storage", "ActivityResultContracts.CreateDocument" in deploySource)
|
||||
assertTrue("backup upload must use Android document selection", "ActivityResultContracts.GetContent" in deploySource)
|
||||
assertTrue("restore must create a persistent safety copy", "createPersistentSafetyBackup(request, \"pre_restore\")" in deploySource)
|
||||
assertTrue("deploy must create a persistent safety copy", "reason = \"pre_deploy\"" in deploySource)
|
||||
assertTrue("restore must wait for the live admin socket", "[ -S /run/wdtt/admin.sock ] && break" in deploySource)
|
||||
assertTrue("current full backups must restore an absent outbound profile", "backup.formatVersion >= 3" in deploySource)
|
||||
assertTrue("stale outbound profiles must be removed during exact restore", "rm -f /etc/wdtt/outbound-profile.env" in deploySource)
|
||||
assertTrue("full backups must restore automatic backup settings", "backup.backupPolicyJson" in deploySource)
|
||||
assertTrue("backup policy restore must use an atomic replacement", ".backup-policy.json.import" in deploySource)
|
||||
assertTrue("backup dialogs must use a close icon", "DialogTitleWithClose(" in deploySource)
|
||||
assertFalse("backup export dialog must not keep a bottom cancel button", "TextButton(onClick = onDismiss, enabled = !busy) { Text(\"Отмена\") }" in deploySource)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `prepared deploy database preserves clients and unknown compatible fields`() {
|
||||
val current = JSONObject()
|
||||
.put("main_password", "old-owner")
|
||||
.put("admin_id", "old-admin")
|
||||
.put("bot_token", "old-token")
|
||||
.put("dns", "1.1.1.1")
|
||||
.put("max_passwords", 50)
|
||||
.put("default_ports", "56000,56001,9000")
|
||||
.put("future_compatible_field", "keep-me")
|
||||
.put(
|
||||
"passwords",
|
||||
JSONObject().put(
|
||||
"ABCDEFGHJKLMNPQR",
|
||||
JSONObject()
|
||||
.put("device_id", "")
|
||||
.put("expires_at", 0)
|
||||
.put("down_bytes", 10)
|
||||
.put("up_bytes", 20)
|
||||
)
|
||||
)
|
||||
.put("devices", JSONObject())
|
||||
|
||||
val prepared = JSONObject(
|
||||
prepareDeployDatabaseJson(
|
||||
currentJson = current.toString(),
|
||||
mainPassword = "new-owner",
|
||||
adminId = "",
|
||||
botToken = "",
|
||||
dns = "9.9.9.9",
|
||||
ports = "56100,56101,9100"
|
||||
)
|
||||
)
|
||||
|
||||
assertEquals("new-owner", prepared.getString("main_password"))
|
||||
assertEquals("old-admin", prepared.getString("admin_id"))
|
||||
assertEquals("old-token", prepared.getString("bot_token"))
|
||||
assertEquals("9.9.9.9", prepared.getString("dns"))
|
||||
assertEquals("56100,56101,9100", prepared.getString("default_ports"))
|
||||
assertEquals("keep-me", prepared.getString("future_compatible_field"))
|
||||
assertTrue(prepared.getJSONObject("passwords").has("ABCDEFGHJKLMNPQR"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `deploy DNS is normalized and legacy default upgrade is not a conflict`() {
|
||||
assertEquals("1.1.1.1,1.0.0.1", normalizedDeployDns(" 1.1.1.1 ", "1.0.0.1"))
|
||||
assertTrue(isLegacyDefaultDnsUpgrade("1.1.1.1", "1.1.1.1,1.0.0.1"))
|
||||
assertFalse(isLegacyDefaultDnsUpgrade("8.8.8.8", "1.1.1.1,1.0.0.1"))
|
||||
|
||||
val invalid = runCatching { normalizedDeployDns("1.1.1.1; reboot", "") }
|
||||
assertTrue("invalid DNS characters must be rejected", invalid.isFailure)
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException::class)
|
||||
fun `new deploy refuses empty owner password`() {
|
||||
prepareDeployDatabaseJson(
|
||||
currentJson = null,
|
||||
mainPassword = "",
|
||||
adminId = "",
|
||||
botToken = "",
|
||||
dns = "1.1.1.1",
|
||||
ports = "56000,56001,9000"
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import android.content.pm.ApplicationInfo
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
@@ -52,6 +53,8 @@ class ExceptionsTabBehaviorTest {
|
||||
"com.octopod.russianpost.client.android",
|
||||
"ru.nspk.mirpay",
|
||||
"ru.nspk.sbpay",
|
||||
"com.vkontakte.android",
|
||||
"com.vk.calls",
|
||||
"logo.com.mbanking",
|
||||
"ru.rzd.pass",
|
||||
"ru.tutu.tutu_emp",
|
||||
@@ -93,4 +96,60 @@ class ExceptionsTabBehaviorTest {
|
||||
assertTrue(matchesQuickExclusionApp("Сателлит Online", "store.variant"))
|
||||
assertFalse(matchesQuickExclusionApp("Калькулятор", "com.example.calculator"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `known user apps stay visible when firmware marks them as system apps`() {
|
||||
assertFalse(isVpnRoutingSystemApp("com.vkontakte.android", ApplicationInfo.FLAG_SYSTEM))
|
||||
assertFalse(isVpnRoutingSystemApp("com.vk.calls", ApplicationInfo.FLAG_UPDATED_SYSTEM_APP))
|
||||
assertTrue(isVpnRoutingSystemApp("com.android.settings", ApplicationInfo.FLAG_SYSTEM))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `selected system apps stay visible when the switch is off`() {
|
||||
val visible = visibleAppsWithSystemSelected(
|
||||
listOf(
|
||||
AppItem(
|
||||
name = "VK",
|
||||
packageName = "com.vkontakte.android",
|
||||
icon = null,
|
||||
isSystem = false,
|
||||
),
|
||||
AppItem(
|
||||
name = "Android Settings",
|
||||
packageName = "com.android.settings",
|
||||
icon = null,
|
||||
isSystem = true,
|
||||
),
|
||||
),
|
||||
selectedPackages = setOf("com.android.settings"),
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
listOf("com.vkontakte.android", "com.android.settings"),
|
||||
visible.map(AppItem::packageName),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `selected apps are sorted first and each group stays alphabetical`() {
|
||||
val sorted = sortAppsForRoutingList(
|
||||
listOf(
|
||||
AppItem(name = "Яндекс", packageName = "ru.yandex.searchplugin", icon = null, isSystem = false),
|
||||
AppItem(name = "Банк", packageName = "ru.bank", icon = null, isSystem = false),
|
||||
AppItem(name = "Авито", packageName = "com.avito.android", icon = null, isSystem = false),
|
||||
AppItem(name = "Настройки", packageName = "com.android.settings", icon = null, isSystem = true),
|
||||
),
|
||||
selectedPackages = setOf("ru.yandex.searchplugin", "com.android.settings"),
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
listOf(
|
||||
"com.android.settings",
|
||||
"ru.yandex.searchplugin",
|
||||
"com.avito.android",
|
||||
"ru.bank",
|
||||
),
|
||||
sorted.map(AppItem::packageName),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -66,6 +66,20 @@ class OutboundProfileComparisonTest {
|
||||
assertTrue(outboundProfilesDiffer(server, local))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun savedProxyFields_withoutProxyConfig_areNotReportedAsConfigured() {
|
||||
val server = snapshot(
|
||||
externalProxyHost = "proxy.example.org",
|
||||
externalProxyProfileSaved = true,
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
OutboundModeIndicator(OutboundModeVisualState.Warning, "поля сохранены"),
|
||||
outboundModeIndicator(server, OutboundDialog.ExternalProxy)
|
||||
)
|
||||
assertFalse(server.externalProxyPresent)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun configuredTunInterfaceChange_isReported() {
|
||||
val server = snapshot(mode = "tun_interface", tunInterface = "xray0")
|
||||
@@ -210,6 +224,7 @@ class OutboundProfileComparisonTest {
|
||||
externalProxyPort: String = "",
|
||||
externalProxyLogin: String = "",
|
||||
externalProxyPassword: String = "",
|
||||
externalProxyProfileSaved: Boolean = false,
|
||||
wireGuardPresent: Boolean = false,
|
||||
wireGuardActive: Boolean = false,
|
||||
wireGuardExitHost: String = "",
|
||||
@@ -241,6 +256,7 @@ class OutboundProfileComparisonTest {
|
||||
externalProxyPort = externalProxyPort,
|
||||
externalProxyLogin = externalProxyLogin,
|
||||
externalProxyPassword = externalProxyPassword,
|
||||
externalProxyProfileSaved = externalProxyProfileSaved,
|
||||
wireGuardPresent = wireGuardPresent,
|
||||
wireGuardActive = wireGuardActive,
|
||||
wireGuardExitHost = wireGuardExitHost,
|
||||
|
||||
@@ -192,12 +192,14 @@ class OutboundTunInterfaceTest {
|
||||
val diagnostics = serverDiagnosticsScript()
|
||||
|
||||
assertTrue("WDTT_TUN_INTERFACE_B64" in snapshot)
|
||||
assertTrue("WDTT_TUN_PROFILE_SAVED" in snapshot)
|
||||
assertTrue("WDTT_TUN_POLICY_RULE_ACTIVE" in snapshot)
|
||||
assertTrue("WDTT_TUN_FORWARD_RULES_ACTIVE" in snapshot)
|
||||
assertTrue("WDTT_TUN_IP_FORWARD_ACTIVE" in snapshot)
|
||||
assertTrue("WDTT_TUN_FAIL_CLOSED_ACTIVE" in snapshot)
|
||||
assertTrue("[ -e \"${'$'}WDTT_TUN_OWNER_FILE\" ]" in snapshot)
|
||||
assertTrue("[ -e \"${'$'}WDTT_TUN_CONFIG_FILE\" ]" in snapshot)
|
||||
assertTrue("TUN_OWNED=0" in snapshot)
|
||||
assertTrue("WDTT_TUN_EXIT_V1" in snapshot)
|
||||
assertTrue("Сохранённое поле имени нужно лишь для повторного включения" in snapshot)
|
||||
assertTrue("Автозапуск TUN-выхода" in status)
|
||||
assertTrue("Пересылка IPv4-пакетов" in status)
|
||||
assertTrue("Аварийная блокировка прямого выхода" in status)
|
||||
@@ -264,9 +266,53 @@ class OutboundTunInterfaceTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun savedTunNameWithoutOwnedRouting_isNotReportedAsConfigured() {
|
||||
val savedNameOnly = snapshot(
|
||||
mode = "direct",
|
||||
tunPresent = false,
|
||||
tunProfileSaved = true,
|
||||
tunInterfaceActive = false,
|
||||
tunServiceActive = false,
|
||||
tunServiceEnabled = false,
|
||||
tunPolicyRuleActive = false,
|
||||
tunDefaultRouteActive = false,
|
||||
tunForwardRulesActive = false,
|
||||
tunIpForwardActive = false,
|
||||
tunFailClosedActive = false
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
OutboundModeIndicator(OutboundModeVisualState.Off, "выключен"),
|
||||
outboundModeIndicator(savedNameOnly, OutboundDialog.TunInterface)
|
||||
)
|
||||
assertFalse(savedNameOnly.tunHealthy)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun snapshotParser_keepsSavedTunNameSeparateFromConfiguredRouting() {
|
||||
val parsed = parseOutboundServerSnapshot(
|
||||
"""
|
||||
WDTT_OUTBOUND_MODE=direct
|
||||
WDTT_TUN_INTERFACE_B64=eHJheQ==
|
||||
WDTT_TUN_PROFILE_SAVED=1
|
||||
WDTT_TUN_PRESENT=0
|
||||
""".trimIndent()
|
||||
)
|
||||
|
||||
assertEquals("xray", parsed.tunInterface)
|
||||
assertTrue(parsed.tunProfileSaved)
|
||||
assertFalse(parsed.tunPresent)
|
||||
assertEquals(
|
||||
OutboundModeIndicator(OutboundModeVisualState.Off, "выключен"),
|
||||
outboundModeIndicator(parsed, OutboundDialog.TunInterface)
|
||||
)
|
||||
}
|
||||
|
||||
private fun snapshot(
|
||||
mode: String,
|
||||
tunPresent: Boolean,
|
||||
tunProfileSaved: Boolean = false,
|
||||
tunInterfaceActive: Boolean,
|
||||
tunServiceActive: Boolean,
|
||||
tunServiceEnabled: Boolean,
|
||||
@@ -304,6 +350,7 @@ class OutboundTunInterfaceTest {
|
||||
warpMtu = "",
|
||||
importedWireGuardConfig = "",
|
||||
tunInterface = "xray0",
|
||||
tunProfileSaved = tunProfileSaved,
|
||||
tunPresent = tunPresent,
|
||||
tunInterfaceActive = tunInterfaceActive,
|
||||
tunServiceActive = tunServiceActive,
|
||||
|
||||
@@ -310,10 +310,208 @@ class OutboundWireGuardTest {
|
||||
assertShellSyntax(script, shell = "sh")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun standaloneOwnershipProbe_requiresBothOwnedMarkersAndHasSafeShellSyntax() {
|
||||
val script = standaloneInstallerOwnershipProbeScript()
|
||||
|
||||
assertTrue("/var/lib/wdtt-server-installer/ownership" in script)
|
||||
assertTrue("/etc/systemd/system/wdtt.service" in script)
|
||||
assertTrue("Managed by WDTT Plus standalone server installer" in script)
|
||||
assertTrue("WDTT_STANDALONE_MANAGED=1" in script)
|
||||
assertTrue("WDTT_STANDALONE_MANAGED=0" in script)
|
||||
assertTrue("WDTT_ANDROID_DEPLOY_MANAGED=1" in script)
|
||||
assertTrue("Managed by WDTT Plus Android deploy" in script)
|
||||
assertTrue("WDTT_LEGACY_ANDROID_DEPLOY_CANDIDATE=1" in script)
|
||||
assertTrue("WDTT_INSTALL_TRACE=1" in script)
|
||||
assertTrue("-config-dir[[:space:]]+/etc/wdtt" in script)
|
||||
assertTrue("grep -Fq 'wdtt0'" in script)
|
||||
assertTrue("[ ! -L" in script)
|
||||
assertShellSyntax(script)
|
||||
|
||||
val process = ProcessBuilder("bash", "-c", script)
|
||||
.redirectErrorStream(true)
|
||||
.start()
|
||||
val output = process.inputStream.bufferedReader().use { it.readText() }
|
||||
assertEquals(0, process.waitFor())
|
||||
assertFalse("probe must print real lines, not literal \\n sequences", "\\n" in output)
|
||||
assertEquals(1, Regex("(?m)^WDTT_STANDALONE_MANAGED=[01]$").findAll(output).count())
|
||||
assertEquals(1, Regex("(?m)^WDTT_ANDROID_DEPLOY_MANAGED=[01]$").findAll(output).count())
|
||||
assertEquals(1, Regex("(?m)^WDTT_LEGACY_ANDROID_DEPLOY_CANDIDATE=[01]$").findAll(output).count())
|
||||
assertEquals(1, Regex("(?m)^WDTT_INSTALL_TRACE=[01]$").findAll(output).count())
|
||||
deploymentOwnershipFromProbe(output)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun existingInstallActions_failClosedForUnknownOrFailedOwnershipCheck() {
|
||||
val unknown = existingInstallOwnershipFromFlags(
|
||||
standaloneManaged = false,
|
||||
androidDeployManaged = false,
|
||||
legacyAndroidDeployCandidate = false
|
||||
)
|
||||
assertFalse(
|
||||
existingInstallAllowsPreservingUpdate(
|
||||
ownership = unknown,
|
||||
checkSucceeded = true
|
||||
)
|
||||
)
|
||||
assertFalse(existingInstallAllowsReset(ownership = unknown, checkSucceeded = true))
|
||||
|
||||
val standalone = existingInstallOwnershipFromFlags(
|
||||
standaloneManaged = true,
|
||||
androidDeployManaged = false,
|
||||
legacyAndroidDeployCandidate = false
|
||||
)
|
||||
assertFalse(
|
||||
existingInstallAllowsPreservingUpdate(
|
||||
ownership = standalone,
|
||||
checkSucceeded = true
|
||||
)
|
||||
)
|
||||
assertFalse(existingInstallAllowsReset(ownership = standalone, checkSucceeded = true))
|
||||
|
||||
val legacy = existingInstallOwnershipFromFlags(
|
||||
standaloneManaged = false,
|
||||
androidDeployManaged = false,
|
||||
legacyAndroidDeployCandidate = true
|
||||
)
|
||||
assertTrue(
|
||||
existingInstallAllowsPreservingUpdate(
|
||||
ownership = legacy,
|
||||
checkSucceeded = true
|
||||
)
|
||||
)
|
||||
assertFalse(existingInstallAllowsReset(ownership = legacy, checkSucceeded = true))
|
||||
|
||||
val android = existingInstallOwnershipFromFlags(
|
||||
standaloneManaged = false,
|
||||
androidDeployManaged = true,
|
||||
legacyAndroidDeployCandidate = true
|
||||
)
|
||||
assertEquals(DeploymentOwnership.AndroidDeploy, android)
|
||||
assertTrue(existingInstallAllowsReset(ownership = android, checkSucceeded = true))
|
||||
assertFalse(existingInstallAllowsReset(ownership = android, checkSucceeded = false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun ownershipProbe_recognizesRealLegacyV14AndroidUnitForPreservingUpdate() {
|
||||
val root = Files.createTempDirectory("wdtt-v14-owner-probe").toFile()
|
||||
try {
|
||||
val binary = File(root, "usr/local/bin/wdtt-server")
|
||||
val config = File(root, "etc/wdtt")
|
||||
val unit = File(root, "etc/systemd/system/wdtt.service")
|
||||
requireNotNull(binary.parentFile).mkdirs()
|
||||
config.mkdirs()
|
||||
requireNotNull(unit.parentFile).mkdirs()
|
||||
binary.writeText("#!/bin/sh\nexit 0\n")
|
||||
binary.setExecutable(true)
|
||||
File(config, "passwords.json").writeText("{}\n")
|
||||
File(config, "wg-keys.dat").writeText("test-only\n")
|
||||
unit.writeText(
|
||||
"""
|
||||
[Service]
|
||||
ExecStartPre=-/usr/bin/env bash -c "ip link show wdtt0 >/dev/null 2>&1 && ip link del wdtt0 || true"
|
||||
ExecStart=/usr/local/bin/wdtt-server -listen 0.0.0.0:56000 -wg-port 56001 -config-dir /etc/wdtt -max-passwords 50
|
||||
""".trimIndent()
|
||||
)
|
||||
|
||||
val process = ProcessBuilder(
|
||||
"bash",
|
||||
"-c",
|
||||
standaloneInstallerOwnershipProbeScript(root.absolutePath)
|
||||
).redirectErrorStream(true).start()
|
||||
val output = process.inputStream.bufferedReader().use { it.readText() }
|
||||
assertEquals(0, process.waitFor())
|
||||
val ownership = deploymentOwnershipFromProbe(output)
|
||||
assertEquals(DeploymentOwnership.LegacyAndroidDeploy, ownership)
|
||||
assertTrue(existingInstallAllowsPreservingUpdate(ownership, checkSucceeded = true))
|
||||
assertFalse(existingInstallAllowsReset(ownership, checkSucceeded = true))
|
||||
} finally {
|
||||
root.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun deploymentOwnership_allowsOnlyStrictLegacyAndroidShapeForPreserveMigration() {
|
||||
assertEquals(
|
||||
DeploymentOwnership.LegacyAndroidDeploy,
|
||||
deploymentOwnershipFromProbe(
|
||||
"""
|
||||
WDTT_STANDALONE_MANAGED=0
|
||||
WDTT_ANDROID_DEPLOY_MANAGED=0
|
||||
WDTT_LEGACY_ANDROID_DEPLOY_CANDIDATE=1
|
||||
WDTT_INSTALL_TRACE=1
|
||||
""".trimIndent()
|
||||
)
|
||||
)
|
||||
assertEquals(
|
||||
DeploymentOwnership.UnknownExisting,
|
||||
deploymentOwnershipFromProbe(
|
||||
"""
|
||||
WDTT_STANDALONE_MANAGED=0
|
||||
WDTT_ANDROID_DEPLOY_MANAGED=0
|
||||
WDTT_LEGACY_ANDROID_DEPLOY_CANDIDATE=0
|
||||
WDTT_INSTALL_TRACE=1
|
||||
""".trimIndent()
|
||||
)
|
||||
)
|
||||
assertEquals(
|
||||
DeploymentOwnership.NoInstall,
|
||||
deploymentOwnershipFromProbe(
|
||||
"""
|
||||
WDTT_STANDALONE_MANAGED=0
|
||||
WDTT_ANDROID_DEPLOY_MANAGED=0
|
||||
WDTT_LEGACY_ANDROID_DEPLOY_CANDIDATE=0
|
||||
WDTT_INSTALL_TRACE=0
|
||||
""".trimIndent()
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun ownershipProbe_doesNotTreatSudoDiscoveryAsSudoInvocation() {
|
||||
val command = rootCommand("printf 'probe\\n'")
|
||||
|
||||
assertTrue("command -v sudo >/dev/null 2>&1" in command)
|
||||
assertTrue("sudo -S -p '' bash -c" in command)
|
||||
assertShellSyntax(command)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun connectWithoutInstall_usesStandaloneDatabaseNotInstallerOwnership() {
|
||||
val connection = selectExistingServerConnection(
|
||||
dbJson = """
|
||||
{
|
||||
"main_password":"SafeOwnerPassword42",
|
||||
"admin_id":"",
|
||||
"bot_token":"",
|
||||
"dns":"1.1.1.1,1.0.0.1",
|
||||
"max_passwords":50,
|
||||
"default_ports":"56000,56001,9000",
|
||||
"public_ip":"203.0.113.10",
|
||||
"passwords":{},
|
||||
"devices":{}
|
||||
}
|
||||
""".trimIndent(),
|
||||
fallbackHost = "198.51.100.10",
|
||||
adminMainPassword = "SafeOwnerPassword42"
|
||||
)
|
||||
|
||||
assertEquals("203.0.113.10", connection.host)
|
||||
assertEquals("SafeOwnerPassword42", connection.password)
|
||||
assertEquals(56000, connection.ports.first)
|
||||
assertEquals(56001, connection.ports.second)
|
||||
assertEquals(9000, connection.ports.third)
|
||||
assertEquals("1.1.1.1", connection.dns1)
|
||||
assertEquals("1.0.0.1", connection.dns2)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun externalProxyTransparentCheck_doesNotCaptureRootXrayTraffic() {
|
||||
val script = outboundShellPrelude()
|
||||
|
||||
assertTrue("umask 077" in script)
|
||||
assertTrue("install -d -m 0700 /etc/wdtt /etc/wdtt/outbound" in script)
|
||||
assertTrue("chmod 0600 /etc/wdtt/outbound.json" in script)
|
||||
assertTrue("WDTT_PROXY_TEST_SOURCE=\"${'$'}test_source\"" in script)
|
||||
assertTrue("iptables -t nat -I OUTPUT -s \"${'$'}test_source\" -p tcp -j WDTT_PROXY_TEST" in script)
|
||||
assertTrue("curl --interface \"${'$'}test_source\"" in script)
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import com.wdtt.plus.ServerAdminProfileInfo
|
||||
import com.wdtt.plus.ServerStoredBackupDocument
|
||||
import com.wdtt.plus.ServerStoredBackupFile
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
@@ -414,7 +416,7 @@ class ServerMigrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun versionTwoBackupRoundTripVerifiesIntegrity() {
|
||||
fun currentBackupRoundTripVerifiesIntegrity() {
|
||||
val source = database("client-a", "Телефон")
|
||||
val keys = List(4) { "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" }.joinToString("\n")
|
||||
val encoded = backupToJson(
|
||||
@@ -428,12 +430,130 @@ class ServerMigrationTest {
|
||||
|
||||
val decoded = parseBackupFile(encoded)
|
||||
|
||||
assertEquals(2, decoded.formatVersion)
|
||||
assertEquals(4, decoded.formatVersion)
|
||||
assertTrue(decoded.integrityVerified)
|
||||
assertTrue(decoded.hasWgKeys)
|
||||
assertEquals(source.toString(), decoded.passwordsJson)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun currentBackupPreservesAndVerifiesOutboundProfile() {
|
||||
val profile = "VERSION=1\nIMPORTED_WG_CONFIG_B64=YWJj\nUPDATED_AT=2026-09-02T12:00:00Z\n"
|
||||
val backup = parseBackup(
|
||||
passwordsJson = database("client-a", "Телефон").toString(),
|
||||
wgKeysDat = List(4) { "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" }.joinToString("\n"),
|
||||
createdAt = "02.09.2026 12:00",
|
||||
sourceHost = "old.example.org",
|
||||
outboundProfileEnv = profile,
|
||||
backupPolicyJson = "{\"enabled\":true,\"interval_hours\":12,\"retention_count\":7}"
|
||||
)
|
||||
|
||||
val decoded = parseBackupFile(backupToJson(backup))
|
||||
|
||||
assertEquals(profile, decoded.outboundProfileEnv)
|
||||
assertEquals(true, JSONObject(decoded.backupPolicyJson.orEmpty()).getBoolean("enabled"))
|
||||
assertEquals(12, JSONObject(decoded.backupPolicyJson.orEmpty()).getInt("interval_hours"))
|
||||
assertEquals(4, decoded.formatVersion)
|
||||
assertTrue(decoded.integrityVerified)
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException::class)
|
||||
fun currentBackupRejectsChangedOutboundProfile() {
|
||||
val encoded = JSONObject(
|
||||
backupToJson(
|
||||
parseBackup(
|
||||
passwordsJson = database("client-a", "Телефон").toString(),
|
||||
wgKeysDat = null,
|
||||
createdAt = "02.09.2026 12:00",
|
||||
sourceHost = "old.example.org",
|
||||
outboundProfileEnv = "VERSION=1\n"
|
||||
)
|
||||
)
|
||||
)
|
||||
encoded.put(
|
||||
"outbound_profile_env_b64",
|
||||
Base64.getEncoder().encodeToString("VERSION=2\n".toByteArray())
|
||||
)
|
||||
|
||||
parseBackupFile(encoded.toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun serverManagedSnapshotBecomesPortableFullBackup() {
|
||||
val database = database("client-a", "Телефон").toString()
|
||||
val keys = List(4) { "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" }.joinToString("\n")
|
||||
val outbound = "VERSION=1\n"
|
||||
val policy = "{\"enabled\":true,\"interval_hours\":12,\"retention_count\":7}"
|
||||
fun stored(path: String, value: String) = ServerStoredBackupFile(
|
||||
path = path,
|
||||
mode = 384,
|
||||
size = value.toByteArray().size.toLong(),
|
||||
sha256 = "",
|
||||
data = value.toByteArray()
|
||||
)
|
||||
val snapshot = ServerStoredBackupDocument(
|
||||
id = "20260902T120000Z-abcdef123456",
|
||||
createdAt = 1_778_000_000L,
|
||||
reason = "scheduled",
|
||||
serverVersion = "16",
|
||||
passwordCount = 1,
|
||||
deviceCount = 0,
|
||||
files = listOf(
|
||||
stored("passwords.json", database),
|
||||
stored("wg-keys.dat", keys),
|
||||
stored("outbound-profile.env", outbound),
|
||||
stored("backup-policy.json", policy)
|
||||
)
|
||||
)
|
||||
|
||||
val portable = portableBackupFromServerSnapshot(snapshot, "new.example.org")
|
||||
|
||||
assertTrue(portable.hasWgKeys)
|
||||
assertEquals(outbound, portable.outboundProfileEnv)
|
||||
assertEquals(policy, portable.backupPolicyJson)
|
||||
assertEquals("new.example.org", portable.sourceHost)
|
||||
assertEquals(1, portable.passwordCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sameServerSnapshotRestoreKeepsItsExactServerSettings() {
|
||||
val source = database("client-a", "Телефон")
|
||||
.put("main_password", "backup-owner")
|
||||
.put("dns", "9.9.9.9")
|
||||
.put("default_ports", "57000,57001,9100")
|
||||
.put("public_ip", "saved.example.org")
|
||||
val backup = parseBackup(
|
||||
passwordsJson = source.toString(),
|
||||
wgKeysDat = null,
|
||||
createdAt = "02.09.2026 12:00",
|
||||
sourceHost = "saved.example.org"
|
||||
).copy(serverManagedSnapshot = true)
|
||||
val request = DeployRequest(
|
||||
host = "ssh.example.org",
|
||||
user = "root",
|
||||
pass = "ssh-password",
|
||||
privateKey = "",
|
||||
keyPassphrase = "",
|
||||
allowPasswordAuthentication = true,
|
||||
sshPort = 22,
|
||||
mainPass = "current-owner",
|
||||
adminId = "current-admin",
|
||||
botToken = "current-token",
|
||||
dtlsPort = 56000,
|
||||
wgPort = 56001,
|
||||
localPort = 9000,
|
||||
dns1 = "1.1.1.1",
|
||||
dns2 = "1.0.0.1"
|
||||
)
|
||||
|
||||
val restored = JSONObject(normalizeDbForTarget(backup, null, ServerImportMode.Replace, request))
|
||||
|
||||
assertEquals("backup-owner", restored.getString("main_password"))
|
||||
assertEquals("9.9.9.9", restored.getString("dns"))
|
||||
assertEquals("57000,57001,9100", restored.getString("default_ports"))
|
||||
assertEquals("saved.example.org", restored.getString("public_ip"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun versionTwoBackupKeepsOwnerProfileSourceMarker() {
|
||||
val backup = parseBackup(
|
||||
|
||||
@@ -31,11 +31,24 @@ class TunnelPowerVisualStateTest {
|
||||
state(
|
||||
running = true,
|
||||
activeWorkers = 1,
|
||||
vpnInterfaceUp = true,
|
||||
underlyingNetworkAvailable = true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun workersWithoutWireguardInterfaceRemainConnecting() {
|
||||
assertEquals(
|
||||
TunnelPowerVisualState.Connecting,
|
||||
state(
|
||||
running = true,
|
||||
activeWorkers = 18,
|
||||
vpnInterfaceUp = false,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun deliberateStopAndTrustedWifiWaitingKeepTheirOwnStates() {
|
||||
assertEquals(
|
||||
@@ -54,6 +67,7 @@ class TunnelPowerVisualStateTest {
|
||||
starting: Boolean = false,
|
||||
stopping: Boolean = false,
|
||||
activeWorkers: Int = 0,
|
||||
vpnInterfaceUp: Boolean = false,
|
||||
underlyingNetworkAvailable: Boolean = true,
|
||||
hasConnectionError: Boolean = false,
|
||||
cooldownActive: Boolean = false,
|
||||
@@ -63,6 +77,7 @@ class TunnelPowerVisualStateTest {
|
||||
starting = starting,
|
||||
stopping = stopping,
|
||||
activeWorkers = activeWorkers,
|
||||
vpnInterfaceUp = vpnInterfaceUp,
|
||||
underlyingNetworkAvailable = underlyingNetworkAvailable,
|
||||
hasConnectionError = hasConnectionError,
|
||||
cooldownActive = cooldownActive,
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import android.content.res.Configuration
|
||||
import com.wdtt.plus.isTelevisionUiMode
|
||||
import com.wdtt.plus.shouldShowPhonePermissionOnboarding
|
||||
import com.wdtt.plus.shouldUseTelevisionControls
|
||||
import java.io.File
|
||||
import javax.imageio.ImageIO
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class TvRemoteSupportTest {
|
||||
private fun projectFile(path: String): File = listOf(
|
||||
File(path),
|
||||
File("app/$path"),
|
||||
).first(File::isFile)
|
||||
|
||||
@Test
|
||||
fun televisionModeIsDetectedWithAdditionalUiModeFlags() {
|
||||
val televisionNightMode =
|
||||
Configuration.UI_MODE_TYPE_TELEVISION or Configuration.UI_MODE_NIGHT_YES
|
||||
|
||||
assertTrue(isTelevisionUiMode(televisionNightMode))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun ordinaryAndroidModesRemainNonTelevision() {
|
||||
assertFalse(isTelevisionUiMode(Configuration.UI_MODE_TYPE_NORMAL))
|
||||
assertFalse(isTelevisionUiMode(Configuration.UI_MODE_TYPE_CAR))
|
||||
assertFalse(isTelevisionUiMode(Configuration.UI_MODE_TYPE_WATCH))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun leanbackFeatureCoversTvFirmwareWithoutTelevisionUiMode() {
|
||||
assertTrue(
|
||||
shouldUseTelevisionControls(
|
||||
uiMode = Configuration.UI_MODE_TYPE_NORMAL,
|
||||
hasLeanbackFeature = true,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun ordinaryAndroidDoesNotEnableTvControlsFromOrientationIndependentMode() {
|
||||
assertFalse(
|
||||
shouldUseTelevisionControls(
|
||||
uiMode = Configuration.UI_MODE_TYPE_NORMAL,
|
||||
hasLeanbackFeature = false,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun phonePermissionOnboardingIsSkippedOnlyForTelevision() {
|
||||
assertTrue(shouldShowPhonePermissionOnboarding(television = false))
|
||||
assertFalse(shouldShowPhonePermissionOnboarding(television = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dpadScrollUsesSmallRepeatableViewportStep() {
|
||||
assertEquals(
|
||||
160f,
|
||||
tvDpadScrollDeltaPx(
|
||||
forward = true,
|
||||
canScrollBackward = false,
|
||||
canScrollForward = true,
|
||||
viewportSizePx = 1_000,
|
||||
minimumStepPx = 80f,
|
||||
),
|
||||
0f,
|
||||
)
|
||||
assertEquals(
|
||||
-80f,
|
||||
tvDpadScrollDeltaPx(
|
||||
forward = false,
|
||||
canScrollBackward = true,
|
||||
canScrollForward = true,
|
||||
viewportSizePx = 200,
|
||||
minimumStepPx = 80f,
|
||||
),
|
||||
0f,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dpadScrollReleasesFocusNavigationAtEdges() {
|
||||
assertEquals(
|
||||
0f,
|
||||
tvDpadScrollDeltaPx(
|
||||
forward = true,
|
||||
canScrollBackward = true,
|
||||
canScrollForward = false,
|
||||
viewportSizePx = 1_000,
|
||||
minimumStepPx = 80f,
|
||||
),
|
||||
0f,
|
||||
)
|
||||
assertEquals(
|
||||
0f,
|
||||
tvDpadScrollDeltaPx(
|
||||
forward = false,
|
||||
canScrollBackward = false,
|
||||
canScrollForward = true,
|
||||
viewportSizePx = 1_000,
|
||||
minimumStepPx = 80f,
|
||||
),
|
||||
0f,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun televisionBannerProvidesEveryRequiredDensityAtSixteenByNine() {
|
||||
val expectedSizes = mapOf(
|
||||
"mdpi" to (160 to 90),
|
||||
"hdpi" to (240 to 135),
|
||||
"xhdpi" to (320 to 180),
|
||||
"xxhdpi" to (480 to 270),
|
||||
"xxxhdpi" to (640 to 360),
|
||||
)
|
||||
val manifest = projectFile("src/main/AndroidManifest.xml").readText()
|
||||
|
||||
expectedSizes.forEach { (density, size) ->
|
||||
val banner = ImageIO.read(
|
||||
projectFile("src/main/res/drawable-$density/tv_banner.png")
|
||||
)
|
||||
assertEquals(size.first, banner.width)
|
||||
assertEquals(size.second, banner.height)
|
||||
}
|
||||
assertTrue(manifest.contains("android:banner=\"@drawable/tv_banner\""))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class TvSteppedSliderTest {
|
||||
@Test
|
||||
fun dpadChangesSliderByOneStep() {
|
||||
assertEquals(27f, steppedSliderValue(18f, 9f..45f, 9f, 1), 0f)
|
||||
assertEquals(9f, steppedSliderValue(18f, 9f..45f, 9f, -1), 0f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dpadSliderStopsAtBounds() {
|
||||
assertEquals(9f, steppedSliderValue(9f, 9f..45f, 9f, -1), 0f)
|
||||
assertEquals(45f, steppedSliderValue(45f, 9f..45f, 9f, 1), 0f)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user