Выпуск WDTT Plus v12
This commit is contained in:
1 parent
b3aad32990
commit
cd441e604e
108 files changed
+22337
-2201
No files matched your search
@@ -3,6 +3,7 @@ package com.wdtt.plus
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
@@ -90,6 +91,44 @@ class AppUpdateTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun updateAssetRequiresOfficialUrlSizeAndDigest() {
|
||||
val safe = AppReleaseAsset(
|
||||
name = "WDTT-Plus-v12-universal-release.apk",
|
||||
downloadUrl = (
|
||||
"https://github.com/Ivan4537/WDTT-Plus/releases/download/" +
|
||||
"v12/WDTT-Plus-v12-universal-release.apk"
|
||||
),
|
||||
sizeBytes = 42L,
|
||||
digest = "sha256:${"a".repeat(64)}",
|
||||
)
|
||||
val release = AppReleaseInfo(
|
||||
versionTag = "v12",
|
||||
releaseUrl = "https://github.com/Ivan4537/WDTT-Plus/releases/tag/v12",
|
||||
source = RemoteVersionSource.Release,
|
||||
assets = listOf(safe),
|
||||
)
|
||||
|
||||
assertEquals(safe, selectUpdateApkAsset(release))
|
||||
assertNull(
|
||||
selectUpdateApkAsset(
|
||||
release.copy(assets = listOf(safe.copy(digest = ""))),
|
||||
),
|
||||
)
|
||||
assertFalse(
|
||||
isTrustedUpdateDownloadUrl(
|
||||
"https://github.com/other/project/releases/download/v12/app.apk",
|
||||
initialRequest = true,
|
||||
),
|
||||
)
|
||||
assertTrue(
|
||||
isTrustedUpdateDownloadUrl(
|
||||
"https://release-assets.githubusercontent.com/opaque",
|
||||
initialRequest = false,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private fun releaseWithHashes(vararg hashes: String): AppReleaseInfo {
|
||||
return AppReleaseInfo(
|
||||
versionTag = "v7",
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class BoundedInputTest {
|
||||
@Test
|
||||
fun `bounded reader stops before accepting an oversized response`() {
|
||||
assertEquals(
|
||||
"данные",
|
||||
"данные".byteInputStream().readUtf8TextLimited(32),
|
||||
)
|
||||
|
||||
runCatching {
|
||||
"x".repeat(33).byteInputStream().readUtf8TextLimited(32)
|
||||
}.onSuccess {
|
||||
throw AssertionError("Oversized response must be rejected")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ClientNetworkDiagnosticsTest {
|
||||
@Test
|
||||
fun vkDiagnosticsTreatModernVkCallsHostsAsPrimaryAndLegacyHostsAsReserve() {
|
||||
assertTrue("api.vk.me" in primaryVkDiagnosticHosts)
|
||||
assertTrue("calls.okcdn.ru" in primaryVkDiagnosticHosts)
|
||||
assertTrue("vk.ru" in reserveVkDiagnosticHosts)
|
||||
assertTrue("login.vk.ru" in reserveVkDiagnosticHosts)
|
||||
assertTrue("api.vk.ru" in reserveVkDiagnosticHosts)
|
||||
assertTrue("id.vk.ru" in reserveVkDiagnosticHosts)
|
||||
assertTrue("static.vk.ru" in reserveVkDiagnosticHosts)
|
||||
assertTrue("vk.com" in reserveVkDiagnosticHosts)
|
||||
assertTrue(primaryVkDiagnosticHosts.intersect(reserveVkDiagnosticHosts).isEmpty())
|
||||
assertEquals("api.vk.me", clientDnsProbeHost)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun clientDnsPath_usesSystemFallbackWithoutReportingFailure() {
|
||||
val result = assessClientDnsPath(emptySet(), systemPrimaryApiWorks = true)
|
||||
|
||||
assertEquals("прямой DNS недоступен, используется системный DNS", result.status)
|
||||
assertEquals(DeviceCheckSeverity.Info, result.severity)
|
||||
assertEquals(null, result.action)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun clientDnsPath_acceptsSecondaryUdpRoute() {
|
||||
val result = assessClientDnsPath(setOf("77.88.8.1 UDP"), systemPrimaryApiWorks = false)
|
||||
|
||||
assertEquals("резервный UDP DNS доступен", result.status)
|
||||
assertEquals(DeviceCheckSeverity.Info, result.severity)
|
||||
assertEquals(null, result.action)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun clientDnsPath_prefersSecondaryUdpOverPrimaryTcp() {
|
||||
val result = assessClientDnsPath(
|
||||
setOf("77.88.8.8 TCP", "77.88.8.1 UDP"),
|
||||
systemPrimaryApiWorks = true
|
||||
)
|
||||
|
||||
assertEquals("резервный UDP DNS доступен", result.status)
|
||||
assertEquals(DeviceCheckSeverity.Info, result.severity)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun clientDnsPath_acceptsTcpFallback() {
|
||||
val result = assessClientDnsPath(setOf("77.88.8.8 TCP"), systemPrimaryApiWorks = false)
|
||||
|
||||
assertEquals("UDP DNS недоступен, TCP отвечает", result.status)
|
||||
assertEquals(DeviceCheckSeverity.Info, result.severity)
|
||||
assertEquals(null, result.action)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun clientDnsPath_keepsPrimaryDirectRouteAheadOfSystemDns() {
|
||||
val result = assessClientDnsPath(setOf("77.88.8.8 UDP"), systemPrimaryApiWorks = true)
|
||||
|
||||
assertEquals("основной UDP DNS доступен", result.status)
|
||||
assertEquals(DeviceCheckSeverity.Ok, result.severity)
|
||||
assertEquals(null, result.action)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun clientDnsPath_reportsFailureOnlyWhenEveryRouteIsUnavailable() {
|
||||
val result = assessClientDnsPath(emptySet(), systemPrimaryApiWorks = false)
|
||||
|
||||
assertEquals("DNS до VK недоступен", result.status)
|
||||
assertEquals(DeviceCheckSeverity.Error, result.severity)
|
||||
assertEquals(DeviceCheckAction.NetworkSettings, result.action)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dnsQuery_containsExpectedHeaderNameAndARecordType() {
|
||||
val query = buildDnsQuery(clientDnsProbeHost, 0x1234)
|
||||
|
||||
assertEquals(0x12, query[0].toInt() and 0xff)
|
||||
assertEquals(0x34, query[1].toInt() and 0xff)
|
||||
assertEquals(1, unsignedShort(query, 4))
|
||||
assertTrue(query.copyOfRange(12, query.size).containsSubsequence(byteArrayOf(3, 'a'.code.toByte(), 'p'.code.toByte(), 'i'.code.toByte())))
|
||||
assertEquals(1, unsignedShort(query, query.size - 4))
|
||||
assertEquals(1, unsignedShort(query, query.size - 2))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dnsResponse_parsesAnswerCountAndFlags() {
|
||||
val response = byteArrayOf(
|
||||
0x12, 0x34,
|
||||
0x83.toByte(), 0x80.toByte(),
|
||||
0x00, 0x01,
|
||||
0x00, 0x02,
|
||||
0x00, 0x00,
|
||||
0x00, 0x00
|
||||
)
|
||||
|
||||
val status = parseDnsResponse(response, 0x1234)
|
||||
|
||||
assertEquals(0, status.responseCode)
|
||||
assertEquals(2, status.answerCount)
|
||||
assertTrue(status.truncated)
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException::class)
|
||||
fun dnsResponse_rejectsDifferentTransaction() {
|
||||
parseDnsResponse(
|
||||
byteArrayOf(
|
||||
0x55, 0x66,
|
||||
0x81.toByte(), 0x80.toByte(),
|
||||
0x00, 0x01,
|
||||
0x00, 0x01,
|
||||
0x00, 0x00,
|
||||
0x00, 0x00
|
||||
),
|
||||
0x1234
|
||||
)
|
||||
}
|
||||
|
||||
private fun unsignedShort(bytes: ByteArray, offset: Int): Int =
|
||||
((bytes[offset].toInt() and 0xff) shl 8) or (bytes[offset + 1].toInt() and 0xff)
|
||||
|
||||
private fun ByteArray.containsSubsequence(expected: ByteArray): Boolean {
|
||||
if (expected.isEmpty() || expected.size > size) return false
|
||||
return indices.any { start ->
|
||||
start + expected.size <= size && expected.indices.all { index -> this[start + index] == expected[index] }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,20 @@ class ClientTransferCodecTest {
|
||||
assertFalse(encoded.contains("host"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun clientTransfer_roundTripsWithoutVkHashes() {
|
||||
val source = ClientTransferPayload(
|
||||
password = "ABCDEFGHJKLMNPQR",
|
||||
label = "Без хеша",
|
||||
vkHash = "",
|
||||
expiresAt = 0,
|
||||
deactivated = false,
|
||||
createdAt = 12345
|
||||
)
|
||||
|
||||
assertEquals(source, ClientTransferCodec.decode(ClientTransferCodec.encode(source)))
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException::class)
|
||||
fun clientTransfer_rejectsUnsafePassword() {
|
||||
ClientTransferCodec.decode(
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class DeviceIdentityTest {
|
||||
@Test
|
||||
fun existingIdentityIsPreservedForActiveInstallations() {
|
||||
val existing = "android-11111111-2222-3333-4444-555555555555"
|
||||
|
||||
val resolved = DeviceIdentity.resolve(
|
||||
existing = existing,
|
||||
platformId = "abcdef0123456789",
|
||||
generatedId = "android-aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
|
||||
)
|
||||
|
||||
assertEquals(existing, resolved)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun freshInstallationUsesStablePlatformIdentity() {
|
||||
val resolved = DeviceIdentity.resolve(
|
||||
existing = null,
|
||||
platformId = "abcdef0123456789",
|
||||
generatedId = "android-aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
|
||||
)
|
||||
|
||||
assertEquals("abcdef0123456789", resolved)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun missingPlatformIdentityUsesValidGeneratedFallback() {
|
||||
val fallback = "android-aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
|
||||
|
||||
val resolved = DeviceIdentity.resolve(
|
||||
existing = "broken",
|
||||
platformId = null,
|
||||
generatedId = fallback,
|
||||
)
|
||||
|
||||
assertEquals(fallback, resolved)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun knownSharedLegacyAndroidIdentityIsRejected() {
|
||||
assertFalse(DeviceIdentity.valid("9774d56d682e549c"))
|
||||
assertFalse(DeviceIdentity.valid("unknown"))
|
||||
assertTrue(DeviceIdentity.valid("abcdef0123456789"))
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,19 @@ package com.wdtt.plus
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class LogSeverityTest {
|
||||
@Test
|
||||
fun wrapHandshakeRetryMessage_doesNotBlameThePassword() {
|
||||
assertEquals(
|
||||
"[WRAP] Отдельные каналы не ответили, выполняется повтор",
|
||||
WRAP_HANDSHAKE_RETRY_MESSAGE
|
||||
)
|
||||
assertFalse(WRAP_HANDSHAKE_RETRY_MESSAGE.contains("парол", ignoreCase = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun repeatedTurnWorkerFailures_useOneRecoverableWarningKey() {
|
||||
val first = classifyRecoverableWorkerRetry(
|
||||
@@ -40,4 +50,11 @@ class LogSeverityTest {
|
||||
|
||||
assertFalse(warning.isError)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun serverExpiredDenialIsRecognizedBeforeLocalizedProtocolMessage() {
|
||||
assertTrue(isExpiredAccessAuthFailure("FATAL_AUTH: DENIED:expired"))
|
||||
assertTrue(isExpiredAccessAuthFailure("FATAL_AUTH: срок действия пароля истёк"))
|
||||
assertFalse(isExpiredAccessAuthFailure("FATAL_AUTH: неверный пароль подключения"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class RemoteActionCatalogTest {
|
||||
@Test
|
||||
fun parse_acceptsOnlyKnownPlacementsAndExactTargets() {
|
||||
val catalog = RemoteActionCatalogGateway.parse(
|
||||
"""
|
||||
{
|
||||
"version": 1,
|
||||
"actions": {
|
||||
"tunnel": {
|
||||
"title": "Дополнительное действие",
|
||||
"message": "Продолжить во внешнем сервисе",
|
||||
"label": "Открыть",
|
||||
"confirmation_title": "Подтверждение",
|
||||
"confirmation_message": "Первый абзац.\n\nВторой абзац.",
|
||||
"confirmation_label": "Продолжить",
|
||||
"progress_label": "Открываю…",
|
||||
"preparing_message": "Подготавливаю...",
|
||||
"stopping_message": "Останавливаю...",
|
||||
"opening_message": "Открываю...",
|
||||
"success_message": "Открыто.",
|
||||
"cancelled_message": "Отменено.",
|
||||
"failure_message": "Не удалось.",
|
||||
"compact_message": "Короткий текст.",
|
||||
"compact_label": "Короткая кнопка",
|
||||
"compact_link_text": "Короткий",
|
||||
"compact_button_visible": false,
|
||||
"cancel_label": "Остановить",
|
||||
"form": {
|
||||
"token": "opaque.form.token_1234567890",
|
||||
"submit_url": "https://example.org/actions/execute",
|
||||
"title": "Введите значение",
|
||||
"message": "Выберите готовое значение или укажите своё.",
|
||||
"choices": [
|
||||
{"label": "Первое", "value": "opaque-choice-1"},
|
||||
{"label": "Второе", "value": "opaque-choice-2"}
|
||||
],
|
||||
"input_label": "Значение",
|
||||
"input_suffix": "",
|
||||
"initial_value": "7",
|
||||
"minimum": 2,
|
||||
"maximum": 19,
|
||||
"max_characters": 2,
|
||||
"supporting_text": "Допустимый диапазон",
|
||||
"invalid_text": "Проверьте значение",
|
||||
"submit_label": "Продолжить — {value}",
|
||||
"busy_label": "Подготавливаем…",
|
||||
"failure_message": "Не удалось продолжить.",
|
||||
"fallback_label": "Открыть страницу"
|
||||
},
|
||||
"url": "https://example.org/start?opaque=1",
|
||||
"fallback": "https://example.org/fallback",
|
||||
"handler": "org.example.client",
|
||||
"alternate_handlers": [
|
||||
"org.example.client.web",
|
||||
"org.example.client.x"
|
||||
]
|
||||
},
|
||||
"unknown": {
|
||||
"title": "Неизвестное место",
|
||||
"message": "Не должно попасть в каталог",
|
||||
"label": "Открыть",
|
||||
"url": "https://example.org/ignored"
|
||||
}
|
||||
}
|
||||
}
|
||||
""".trimIndent()
|
||||
)
|
||||
|
||||
val action = catalog.at("tunnel")!!
|
||||
assertEquals("Дополнительное действие", action.title)
|
||||
assertEquals("https://example.org/start?opaque=1", action.target.primaryUrl)
|
||||
assertEquals("https://example.org/fallback", action.target.fallbackUrl)
|
||||
assertEquals("org.example.client", action.target.preferredHandler)
|
||||
assertEquals(
|
||||
listOf("org.example.client.web", "org.example.client.x"),
|
||||
action.target.alternateHandlers,
|
||||
)
|
||||
assertEquals(
|
||||
listOf(
|
||||
"org.example.client",
|
||||
"org.example.client.web",
|
||||
"org.example.client.x",
|
||||
),
|
||||
action.target.handlerPackages(),
|
||||
)
|
||||
assertEquals("Подтверждение", action.confirmationTitle)
|
||||
assertEquals("Первый абзац.\n\nВторой абзац.", action.confirmationMessage)
|
||||
assertEquals("Продолжить", action.confirmationLabel)
|
||||
assertEquals("Открываю…", action.progressLabel)
|
||||
assertEquals("Подготавливаю...", action.preparingMessage)
|
||||
assertEquals("Останавливаю...", action.stoppingMessage)
|
||||
assertEquals("Открываю...", action.openingMessage)
|
||||
assertEquals("Открыто.", action.successMessage)
|
||||
assertEquals("Отменено.", action.cancelledMessage)
|
||||
assertEquals("Не удалось.", action.failureMessage)
|
||||
assertEquals("Короткий текст.", action.compactMessage)
|
||||
assertEquals("Короткая кнопка", action.compactLabel)
|
||||
assertEquals("Короткий", action.compactLinkText)
|
||||
assertEquals(false, action.compactButtonVisible)
|
||||
assertEquals("Остановить", action.cancelLabel)
|
||||
assertEquals("Введите значение", action.form?.title)
|
||||
assertEquals("opaque-choice-2", action.form?.choices?.get(1)?.value)
|
||||
assertEquals(2L, action.form?.minimum)
|
||||
assertEquals(19L, action.form?.maximum)
|
||||
assertNull(catalog.at("unknown"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parse_rejectsUnsafeOrMalformedActions() {
|
||||
val catalog = RemoteActionCatalogGateway.parse(
|
||||
"""
|
||||
{
|
||||
"version": 1,
|
||||
"actions": {
|
||||
"tunnel": {
|
||||
"title": "Опасная ссылка",
|
||||
"message": "Неподдерживаемая схема",
|
||||
"label": "Открыть",
|
||||
"url": "custom://private-contract"
|
||||
},
|
||||
"profile": {
|
||||
"title": "Неверный обработчик",
|
||||
"message": "Имя пакета не прошло проверку",
|
||||
"label": "Открыть",
|
||||
"url": "https://example.org/start",
|
||||
"handler": "not a package"
|
||||
},
|
||||
"about": {
|
||||
"title": "Неверные резервные обработчики",
|
||||
"message": "Имя пакета не прошло проверку",
|
||||
"label": "Открыть",
|
||||
"url": "https://example.org/start",
|
||||
"alternate_handlers": ["also not a package"]
|
||||
}
|
||||
}
|
||||
}
|
||||
""".trimIndent()
|
||||
)
|
||||
|
||||
assertTrue(catalog.actions.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parse_rejectsUnknownProtocolVersion() {
|
||||
val catalog = RemoteActionCatalogGateway.parse(
|
||||
"""{"version":2,"actions":{}}"""
|
||||
)
|
||||
|
||||
assertTrue(catalog.actions.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parseExecutionTarget_acceptsOnlyExactHttpsTargets() {
|
||||
val target = RemoteActionCatalogGateway.parseExecutionTarget(
|
||||
"""
|
||||
{
|
||||
"version": 1,
|
||||
"url": "https://actions.example.org/opaque",
|
||||
"fallback": "https://example.org/fallback",
|
||||
"handler": ""
|
||||
}
|
||||
""".trimIndent()
|
||||
)
|
||||
|
||||
assertEquals("https://actions.example.org/opaque", target.primaryUrl)
|
||||
assertEquals("https://example.org/fallback", target.fallbackUrl)
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,24 @@ import org.junit.Test
|
||||
import org.json.JSONObject
|
||||
|
||||
class TransferCodecTest {
|
||||
@Test
|
||||
fun connectionLinkCarriesOptionalProfileWorkerPolicy() {
|
||||
val link = WdttTransferCodec.buildConnectionLink(
|
||||
WdttLinkParts(
|
||||
host = "vpn.example.org",
|
||||
dtlsPort = 56000,
|
||||
wgPort = 56001,
|
||||
localPort = 9000,
|
||||
password = "secret",
|
||||
hashes = "1234567890abcdef",
|
||||
maxWorkers = 9
|
||||
)
|
||||
)
|
||||
|
||||
assertEquals(9, WdttDeepLink.parse(link)?.maxWorkers)
|
||||
assertEquals(0, WdttDeepLink.parse(link.replace("&max_workers=9", ""))?.maxWorkers)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun modernConnectionLink_roundTripsSpecialCharacters() {
|
||||
val original = WdttLinkParts(
|
||||
@@ -112,6 +130,14 @@ class TransferCodecTest {
|
||||
assertEquals("", validation.parts?.profileName)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun invalidConnectionLink_helpShowsModernAndLegacyFormats() {
|
||||
val message = WdttDeepLink.validate("not-a-link").userMessage()
|
||||
|
||||
assertTrue(message.contains("Новый: wdtt://connect?v=1"))
|
||||
assertTrue(message.contains("Старый: wdtt://адрес:"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun onlyRenamedProfileIsPreparedForTransfer() {
|
||||
assertEquals("", vpnProfileTransferName(0, listOf("", "", "")))
|
||||
@@ -166,6 +192,44 @@ class TransferCodecTest {
|
||||
assertEquals("Мой сервер", WdttDeepLink.parse(link.orEmpty())?.profileName)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun serverClientLink_withoutVkHashesCanBeSharedAndImportedAsPartialAccess() {
|
||||
val link = buildServerConnectionLink(
|
||||
password = "ABCDEFGHJKLMNPQR",
|
||||
hashes = "",
|
||||
ports = "56000,56001,9000",
|
||||
fallbackHost = "vpn.example.org",
|
||||
publicHost = "",
|
||||
profileName = "Доступ без хеша"
|
||||
)
|
||||
|
||||
assertNotNull(link)
|
||||
assertTrue(link.orEmpty().contains("hashes="))
|
||||
assertFalse(WdttDeepLink.validate(link.orEmpty()).canStartVpn)
|
||||
val partial = WdttDeepLink.parse(link.orEmpty(), allowMissingHashes = true)
|
||||
assertNotNull(partial)
|
||||
assertEquals("", partial?.hashes)
|
||||
assertEquals("Доступ без хеша", partial?.profileName)
|
||||
assertFalse(partial?.hasNonStandardPorts() ?: true)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun importedLinkEnablesCustomPortsOnlyWhenAtLeastOnePortDiffers() {
|
||||
val standard = WdttLinkParts(
|
||||
host = "vpn.example.org",
|
||||
dtlsPort = 56000,
|
||||
wgPort = 56001,
|
||||
localPort = 9000,
|
||||
password = "ABCDEFGHJKLMNPQR",
|
||||
hashes = "hash"
|
||||
)
|
||||
|
||||
assertFalse(standard.hasNonStandardPorts())
|
||||
assertTrue(standard.copy(dtlsPort = 57000).hasNonStandardPorts())
|
||||
assertTrue(standard.copy(wgPort = 57001).hasNonStandardPorts())
|
||||
assertTrue(standard.copy(localPort = 9100).hasNonStandardPorts())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun linkCanBeExtractedFromSharedText() {
|
||||
val value = "Подключение: wdtt://vpn.example.org:56000:56001:9000:secret:1234567890abcdef\nНе передавайте посторонним"
|
||||
@@ -185,6 +249,38 @@ class TransferCodecTest {
|
||||
assertFalse(WdttDeepLink.validate(link).canStartVpn)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun connectionLinkWithoutHashes_canBeStoredButCannotStartVpn() {
|
||||
val link = WdttTransferCodec.buildConnectionLink(
|
||||
WdttLinkParts("vpn.example.org", 56000, 56001, 9000, "secret", "")
|
||||
)
|
||||
|
||||
assertFalse(WdttDeepLink.validate(link).canStartVpn)
|
||||
assertNotNull(WdttDeepLink.parse(link, allowMissingHashes = true))
|
||||
assertTrue(
|
||||
WdttDeepLink.validate(link, allowMissingHashes = true)
|
||||
.userMessage()
|
||||
.contains("Добавьте свой VK-хеш")
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun ordinaryLongWordsAreNeverParsedAsVkHashes() {
|
||||
val link = WdttTransferCodec.buildConnectionLink(
|
||||
WdttLinkParts(
|
||||
"vpn.example.org",
|
||||
56000,
|
||||
56001,
|
||||
9000,
|
||||
"secret",
|
||||
"пользовательский,переподключаются",
|
||||
)
|
||||
)
|
||||
|
||||
assertFalse(WdttDeepLink.validate(link).canStartVpn)
|
||||
assertEquals(null, WdttDeepLink.parse(link, allowMissingHashes = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun malformedModernLink_isNotParsed() {
|
||||
val validation = WdttDeepLink.validate("wdtt://connect?v=1&host=vpn.example.org")
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class TrustedWifiLogTest {
|
||||
@Test
|
||||
fun `repeated trusted wifi event updates one counter`() {
|
||||
TunnelManager.isLoggingEnabled = true
|
||||
TunnelManager.clearLogs()
|
||||
try {
|
||||
TunnelManager.noteTrustedWifiEvent("resume_wait_network", "Ждём рабочую сеть.")
|
||||
TunnelManager.noteTrustedWifiEvent("resume_wait_network", "Ждём рабочую сеть.")
|
||||
|
||||
val entries = TunnelManager.logs.value.filter { it.key == "trusted_wifi_resume_wait_network" }
|
||||
assertEquals(1, entries.size)
|
||||
assertEquals(2, entries.single().count)
|
||||
assertEquals(LogSeverity.Info, entries.single().severity)
|
||||
} finally {
|
||||
TunnelManager.clearLogs()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -123,4 +123,68 @@ class TrustedWifiTest {
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `trusted wifi resume retries keep cpu awake only during fast recovery window`() {
|
||||
assertEquals(
|
||||
TrustedWifiResumeRetryPlan(delayMs = 5_000L, keepCpuAwake = true),
|
||||
trustedWifiResumeRetryPlan(0)
|
||||
)
|
||||
assertEquals(
|
||||
TrustedWifiResumeRetryPlan(delayMs = 5_000L, keepCpuAwake = true),
|
||||
trustedWifiResumeRetryPlan(11)
|
||||
)
|
||||
assertEquals(
|
||||
TrustedWifiResumeRetryPlan(delayMs = 30_000L, keepCpuAwake = false),
|
||||
trustedWifiResumeRetryPlan(12)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `lost trusted wifi is not reused as validated resume network`() {
|
||||
val networks = TrustedWifiValidatedNetworkTracker<String>()
|
||||
networks.update(network = "home", validated = true, wifi = true)
|
||||
assertTrue(networks.hasUsableNetwork())
|
||||
|
||||
networks.forgetWifi()
|
||||
assertFalse(networks.hasUsableNetwork())
|
||||
|
||||
networks.update(network = "cellular", validated = true, wifi = false)
|
||||
assertTrue(networks.hasUsableNetwork())
|
||||
|
||||
networks.lost("cellular")
|
||||
assertFalse(networks.hasUsableNetwork())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `trusted wifi loss preserves an already validated cellular network`() {
|
||||
val networks = TrustedWifiValidatedNetworkTracker<String>()
|
||||
networks.update(network = "home", validated = true, wifi = true)
|
||||
networks.update(network = "cellular", validated = true, wifi = false)
|
||||
|
||||
networks.forgetWifi()
|
||||
|
||||
assertTrue(networks.hasUsableNetwork())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `internet capability without validation is not enough to resume`() {
|
||||
val networks = TrustedWifiValidatedNetworkTracker<String>()
|
||||
networks.update(network = "cellular", validated = false, wifi = false)
|
||||
assertFalse(networks.hasUsableNetwork())
|
||||
|
||||
networks.update(network = "cellular", validated = true, wifi = false)
|
||||
assertTrue(networks.hasUsableNetwork())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `losing trusted wifi does not discard a newly validated untrusted wifi`() {
|
||||
val networks = TrustedWifiValidatedNetworkTracker<String>()
|
||||
networks.update(network = "home", validated = true, wifi = true)
|
||||
networks.update(network = "office", validated = true, wifi = true)
|
||||
|
||||
networks.lost("home")
|
||||
|
||||
assertTrue(networks.hasUsableNetwork())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import com.wdtt.plus.ui.hasTunnelConnectionSource
|
||||
import com.wdtt.plus.ui.isSelectedCompactConnectionReady
|
||||
import com.wdtt.plus.ui.resolveConnectionInputMethod
|
||||
import com.wdtt.plus.ui.usesCompactTunnelInterface
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class TunnelProfilePresentationTest {
|
||||
@Test
|
||||
fun `user role uses compact tunnel interface`() {
|
||||
assertTrue(usesCompactTunnelInterface("user"))
|
||||
assertFalse(usesCompactTunnelInterface("admin"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `empty profiles use role specific default method`() {
|
||||
assertEquals("link", resolveConnectionInputMethod("", false, false, true))
|
||||
assertEquals("manual", resolveConnectionInputMethod("", false, false, false))
|
||||
assertEquals("manual", resolveConnectionInputMethod("", false, true, true))
|
||||
assertEquals("link", resolveConnectionInputMethod("link", false, true, false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `legacy profiles without saved method keep their configured source`() {
|
||||
assertEquals("link", resolveConnectionInputMethod("", true, false, false))
|
||||
assertEquals("link", resolveConnectionInputMethod("", true, true, true))
|
||||
assertEquals("manual", resolveConnectionInputMethod("", false, true, false))
|
||||
assertTrue(
|
||||
isSelectedCompactConnectionReady(
|
||||
selectedMethod = "link",
|
||||
savedMethod = "",
|
||||
storedLinkMode = true,
|
||||
linkPresent = true,
|
||||
linkValid = true,
|
||||
manualValid = false,
|
||||
)
|
||||
)
|
||||
assertTrue(
|
||||
isSelectedCompactConnectionReady(
|
||||
selectedMethod = "manual",
|
||||
savedMethod = "",
|
||||
storedLinkMode = false,
|
||||
linkPresent = false,
|
||||
linkValid = false,
|
||||
manualValid = true,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `manual and link profiles detect their own connection source`() {
|
||||
assertTrue(hasTunnelConnectionSource(false, false, "vpn.example", "secret"))
|
||||
assertFalse(hasTunnelConnectionSource(false, false, "vpn.example", ""))
|
||||
assertTrue(hasTunnelConnectionSource(true, true, "", ""))
|
||||
assertTrue(hasTunnelConnectionSource(true, false, "vpn.example", "secret"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `selected connection method must match configured method`() {
|
||||
assertTrue(
|
||||
isSelectedCompactConnectionReady(
|
||||
selectedMethod = "manual",
|
||||
savedMethod = "manual",
|
||||
storedLinkMode = false,
|
||||
linkPresent = false,
|
||||
linkValid = false,
|
||||
manualValid = true,
|
||||
)
|
||||
)
|
||||
assertFalse(
|
||||
isSelectedCompactConnectionReady(
|
||||
selectedMethod = "link",
|
||||
savedMethod = "manual",
|
||||
storedLinkMode = false,
|
||||
linkPresent = false,
|
||||
linkValid = false,
|
||||
manualValid = true,
|
||||
)
|
||||
)
|
||||
assertTrue(
|
||||
isSelectedCompactConnectionReady(
|
||||
selectedMethod = "link",
|
||||
savedMethod = "link",
|
||||
storedLinkMode = false,
|
||||
linkPresent = false,
|
||||
linkValid = false,
|
||||
manualValid = true,
|
||||
)
|
||||
)
|
||||
assertFalse(
|
||||
isSelectedCompactConnectionReady(
|
||||
selectedMethod = "manual",
|
||||
savedMethod = "link",
|
||||
storedLinkMode = false,
|
||||
linkPresent = false,
|
||||
linkValid = false,
|
||||
manualValid = true,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `incomplete selected method is not ready`() {
|
||||
assertFalse(
|
||||
isSelectedCompactConnectionReady(
|
||||
selectedMethod = "manual",
|
||||
savedMethod = "manual",
|
||||
storedLinkMode = false,
|
||||
linkPresent = false,
|
||||
linkValid = false,
|
||||
manualValid = false,
|
||||
)
|
||||
)
|
||||
assertFalse(
|
||||
isSelectedCompactConnectionReady(
|
||||
selectedMethod = "link",
|
||||
savedMethod = "",
|
||||
storedLinkMode = true,
|
||||
linkPresent = true,
|
||||
linkValid = false,
|
||||
manualValid = true,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `running tunnel keeps launch profile after selection changes`() {
|
||||
assertEquals(
|
||||
0,
|
||||
displayedTunnelProfile(
|
||||
selectedProfile = 2,
|
||||
activeTunnelProfile = 0,
|
||||
running = true,
|
||||
trustedWifiWaiting = false,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `trusted wifi waiting keeps tunnel profile`() {
|
||||
assertEquals(
|
||||
1,
|
||||
displayedTunnelProfile(
|
||||
selectedProfile = 2,
|
||||
activeTunnelProfile = 1,
|
||||
running = false,
|
||||
trustedWifiWaiting = true,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `disconnected interface follows selected profile`() {
|
||||
assertEquals(
|
||||
2,
|
||||
displayedTunnelProfile(
|
||||
selectedProfile = 2,
|
||||
activeTunnelProfile = 0,
|
||||
running = false,
|
||||
trustedWifiWaiting = false,
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class TunnelProfileRuntimeUpdateTest {
|
||||
@Test
|
||||
fun activeRunningProfileRequestsRuntimeUpdate() {
|
||||
assertTrue(
|
||||
shouldRequestTunnelProfileRuntimeUpdate(
|
||||
updatedProfile = 1,
|
||||
activeTunnelProfile = 1,
|
||||
tunnelRunning = true,
|
||||
trustedWifiWaiting = false,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun inactiveProfileDoesNotTouchRunningTunnel() {
|
||||
assertFalse(
|
||||
shouldRequestTunnelProfileRuntimeUpdate(
|
||||
updatedProfile = 2,
|
||||
activeTunnelProfile = 1,
|
||||
tunnelRunning = true,
|
||||
trustedWifiWaiting = false,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stoppedProfileDoesNotStartVpn() {
|
||||
assertFalse(
|
||||
shouldRequestTunnelProfileRuntimeUpdate(
|
||||
updatedProfile = 1,
|
||||
activeTunnelProfile = 1,
|
||||
tunnelRunning = false,
|
||||
trustedWifiWaiting = false,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun trustedWifiWaitingProfileKeepsUpdatedConfigurationForResume() {
|
||||
assertTrue(
|
||||
shouldRequestTunnelProfileRuntimeUpdate(
|
||||
updatedProfile = 1,
|
||||
activeTunnelProfile = 1,
|
||||
tunnelRunning = false,
|
||||
trustedWifiWaiting = true,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun changedConnectionParametersRequireRuntimeReplacement() {
|
||||
val current = params(peer = "old.example:56000")
|
||||
val updated = current.copy(peer = "new.example:56000")
|
||||
|
||||
assertTrue(tunnelProfileRuntimeConfigurationChanged(current, updated))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unchangedConnectionParametersDoNotRestartTransport() {
|
||||
val current = params(peer = "same.example:56000")
|
||||
|
||||
assertFalse(tunnelProfileRuntimeConfigurationChanged(current, current.copy()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anotherProfileCannotReplaceActiveRuntimeConfiguration() {
|
||||
val current = params(peer = "old.example:56000", profileIndex = 0)
|
||||
val updated = current.copy(peer = "new.example:56000", profileIndex = 1)
|
||||
|
||||
assertFalse(tunnelProfileRuntimeConfigurationChanged(current, updated))
|
||||
}
|
||||
|
||||
private fun params(
|
||||
peer: String,
|
||||
profileIndex: Int = 0,
|
||||
) = TunnelParams(
|
||||
peer = peer,
|
||||
vkHashes = "hash",
|
||||
workersPerHash = 9,
|
||||
port = 9000,
|
||||
connectionPassword = "password",
|
||||
profileIndex = profileIndex,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class TunnelRecoveryPolicyTest {
|
||||
@Test
|
||||
fun firstRecoveryIsTransportOnly() {
|
||||
assertEquals(
|
||||
NetworkRecoveryAction.SoftRestart,
|
||||
stableNetworkRecoveryAction(completedAttempts = 0),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun failedTransportRecoveryRecreatesVpnOnce() {
|
||||
assertEquals(
|
||||
NetworkRecoveryAction.RecreateVpn,
|
||||
stableNetworkRecoveryAction(completedAttempts = 1),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun failedVpnRecreationStopsFailOpen() {
|
||||
assertEquals(
|
||||
NetworkRecoveryAction.StopVpn,
|
||||
stableNetworkRecoveryAction(completedAttempts = 2),
|
||||
)
|
||||
assertEquals(
|
||||
NetworkRecoveryAction.StopVpn,
|
||||
stableNetworkRecoveryAction(completedAttempts = 3),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class TunnelStartConfigTest {
|
||||
@Test
|
||||
fun `tile and widgets stop both active and trusted wifi waiting tunnel`() {
|
||||
assertEquals(
|
||||
TunnelToggleAction.STOP,
|
||||
tunnelToggleAction(
|
||||
running = true,
|
||||
trustedWifiWaiting = false,
|
||||
vpnPermissionRequired = false,
|
||||
)
|
||||
)
|
||||
assertEquals(
|
||||
TunnelToggleAction.STOP,
|
||||
tunnelToggleAction(
|
||||
running = false,
|
||||
trustedWifiWaiting = true,
|
||||
vpnPermissionRequired = false,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `tile and widgets request permission before start`() {
|
||||
assertEquals(
|
||||
TunnelToggleAction.REQUEST_VPN_PERMISSION,
|
||||
tunnelToggleAction(
|
||||
running = false,
|
||||
trustedWifiWaiting = false,
|
||||
vpnPermissionRequired = true,
|
||||
)
|
||||
)
|
||||
assertEquals(
|
||||
TunnelToggleAction.START,
|
||||
tunnelToggleAction(
|
||||
running = false,
|
||||
trustedWifiWaiting = false,
|
||||
vpnPermissionRequired = false,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class TunnelStartRequestGateTest {
|
||||
@Test
|
||||
fun `stop invalidates a delayed start`() {
|
||||
val gate = TunnelStartRequestGate()
|
||||
val request = gate.next()
|
||||
|
||||
gate.invalidate()
|
||||
|
||||
assertFalse(gate.isCurrent(request))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `only the latest profile request may finish`() {
|
||||
val gate = TunnelStartRequestGate()
|
||||
val first = gate.next()
|
||||
val second = gate.next()
|
||||
|
||||
assertFalse(gate.isCurrent(first))
|
||||
assertTrue(gate.isCurrent(second))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class TunnelStopCoordinatorTest {
|
||||
@Test
|
||||
fun `only completed stop outcomes allow a destructive follow-up action`() {
|
||||
assertTrue(TunnelStopResult.ALREADY_STOPPED.succeeded)
|
||||
assertTrue(TunnelStopResult.STOPPED.succeeded)
|
||||
assertFalse(TunnelStopResult.TIMED_OUT.succeeded)
|
||||
assertFalse(TunnelStopResult.FAILED.succeeded)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class TunnelWorkerPolicyTest {
|
||||
@Test
|
||||
fun profilePolicyCapsOnlyTheProfileThatCarriesIt() {
|
||||
assertEquals(9, normalizeTunnelWorkerCount(1, profileMaxWorkers = 9))
|
||||
assertEquals(9, normalizeTunnelWorkerCount(27, profileMaxWorkers = 9))
|
||||
assertEquals(18, normalizeTunnelWorkerCount(27, profileMaxWorkers = 18))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun profileWithoutPolicyRetainsFullPowerRange() {
|
||||
assertEquals(18, normalizeTunnelWorkerCount(16))
|
||||
assertEquals(108, normalizeTunnelWorkerCount(108))
|
||||
assertEquals(108, normalizeTunnelWorkerCount(500))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class VkClientCredentialsTest {
|
||||
@Test
|
||||
fun `client id normalization keeps digits only`() {
|
||||
assertEquals("123456", normalizeVkClientId(" 12-ab34 56 "))
|
||||
assertTrue(isValidVkClientId("123456"))
|
||||
assertFalse(isValidVkClientId("123-456"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `disabled custom mode never blocks built in credentials`() {
|
||||
assertNull(customVkCredentialsError(CustomVkClientCredentials(enabled = false)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `enabled custom mode requires both values`() {
|
||||
assertEquals(
|
||||
"Укажите числовой Client ID приложения VK.",
|
||||
customVkCredentialsError(CustomVkClientCredentials(enabled = true))
|
||||
)
|
||||
assertEquals(
|
||||
"Укажите защищённый ключ (Client secret) приложения VK.",
|
||||
customVkCredentialsError(CustomVkClientCredentials(enabled = true, clientId = "123456"))
|
||||
)
|
||||
assertNull(
|
||||
customVkCredentialsError(
|
||||
CustomVkClientCredentials(
|
||||
enabled = true,
|
||||
clientId = "123456",
|
||||
clientSecret = "test-only-secret"
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class VkJoinLinkTest {
|
||||
@Test
|
||||
fun extractsHashFromCurrentVkRuLink() {
|
||||
assertEquals(
|
||||
"current_hash_1234567890",
|
||||
VkJoinLink.extractHash(
|
||||
"https://vk.ru/call/join/current_hash_1234567890?from=share#fragment"
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun keepsVkComLinksAsCompatibilityInput() {
|
||||
assertEquals(
|
||||
"legacy_hash_1234567890",
|
||||
VkJoinLink.extractHash(
|
||||
"https://vk.com/call/join/legacy_hash_1234567890?from=share"
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun keepsRawHashInputSupported() {
|
||||
assertEquals(
|
||||
"raw_hash_1234567890",
|
||||
VkJoinLink.extractHash("raw_hash_1234567890")
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun acceptsOnlyOpaqueAsciiHashValues() {
|
||||
assertTrue(VkJoinLink.isValidHash("3XariaxnHDP9eTiWVFukTMO6ZjCw7c0QQS_J3gYiiaM"))
|
||||
assertTrue(VkJoinLink.isValidHash("short"))
|
||||
assertFalse(VkJoinLink.isValidHash("пользовательский"))
|
||||
assertFalse(VkJoinLink.isValidHash("переподключаются"))
|
||||
assertEquals("", VkJoinLink.extractValidHash("https://vk.ru/call/join/пользовательский"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun validatesCharactersWithoutGuessingVkHashLength() {
|
||||
assertTrue(VkJoinLink.isValidInput("a"))
|
||||
assertTrue(VkJoinLink.isValidInput("https://vk.ru/call/join/a?from=share"))
|
||||
assertFalse(VkJoinLink.isValidInput("хеш"))
|
||||
assertFalse(VkJoinLink.isValidInput("bad/path"))
|
||||
assertFalse(VkJoinLink.isValidInput("https://vk.ru/not-a-call/a"))
|
||||
assertEquals("a,b_C-2", VkJoinLink.normalizeHashes("a, b_C-2"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class WdttDocumentTest {
|
||||
@Test
|
||||
fun `profile file name always has one wdtt extension`() {
|
||||
assertEquals("WDTT-Plus-profile.wdtt", WdttDocument.fileName("WDTT-Plus-profile"))
|
||||
assertEquals("WDTT-Plus-profile.wdtt", WdttDocument.fileName("WDTT-Plus-profile.wdtt"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `picker accepts current mime and compatible legacy document types`() {
|
||||
assertArrayEquals(
|
||||
arrayOf(
|
||||
"application/vnd.wdtt.plus",
|
||||
"application/vnd.wdtt.plus.transfer",
|
||||
"application/vnd.wdtt.plus.client",
|
||||
"application/json",
|
||||
"application/octet-stream",
|
||||
"text/plain",
|
||||
),
|
||||
WdttDocument.acceptedMimeTypes(),
|
||||
)
|
||||
assertTrue(WdttDocument.isAcceptedMimeType("application/vnd.wdtt.plus"))
|
||||
assertTrue(WdttDocument.isAcceptedMimeType("application/octet-stream"))
|
||||
assertTrue(WdttDocument.isAcceptedMimeType("text/plain; charset=utf-8"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import com.wireguard.config.Config
|
||||
import com.wireguard.crypto.Key
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.io.ByteArrayInputStream
|
||||
|
||||
class WireGuardRuntimeConfigTest {
|
||||
private val privateKey = Key.fromBytes(ByteArray(32) { index -> (index + 1).toByte() })
|
||||
.toBase64()
|
||||
private val publicKey = Key.fromBytes(ByteArray(32) { index -> (index + 33).toByte() })
|
||||
.toBase64()
|
||||
|
||||
@Test
|
||||
fun unchangedConfigurationKeepsRunningVpnInterface() {
|
||||
val current = config(endpointPort = 9000)
|
||||
val updated = config(endpointPort = 9000)
|
||||
|
||||
assertTrue(
|
||||
shouldReuseRunningWireGuard(
|
||||
tunnelUp = true,
|
||||
currentConfigFingerprint = wireGuardConfigFingerprint(current),
|
||||
updatedConfig = updated,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun changedConfigurationReplacesVpnInterface() {
|
||||
assertFalse(
|
||||
shouldReuseRunningWireGuard(
|
||||
tunnelUp = true,
|
||||
currentConfigFingerprint = wireGuardConfigFingerprint(
|
||||
config(endpointPort = 9000)
|
||||
),
|
||||
updatedConfig = config(endpointPort = 9001),
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stoppedVpnInterfaceIsNeverReused() {
|
||||
val config = config(endpointPort = 9000)
|
||||
|
||||
assertFalse(
|
||||
shouldReuseRunningWireGuard(
|
||||
tunnelUp = false,
|
||||
currentConfigFingerprint = wireGuardConfigFingerprint(config),
|
||||
updatedConfig = config,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
private fun config(endpointPort: Int): Config {
|
||||
val text = """
|
||||
[Interface]
|
||||
PrivateKey = $privateKey
|
||||
Address = 10.0.0.2/32
|
||||
DNS = 1.1.1.1
|
||||
MTU = 1280
|
||||
|
||||
[Peer]
|
||||
PublicKey = $publicKey
|
||||
AllowedIPs = 0.0.0.0/0
|
||||
Endpoint = 127.0.0.1:$endpointPort
|
||||
PersistentKeepalive = 25
|
||||
""".trimIndent()
|
||||
return Config.parse(ByteArrayInputStream(text.toByteArray()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ExceptionsTabBehaviorTest {
|
||||
@Test
|
||||
fun `header stays collapsed while app list can still scroll to its first item`() {
|
||||
assertEquals(
|
||||
-240f,
|
||||
collapsingHeaderOffsetAfterScroll(
|
||||
currentOffsetPx = -240f,
|
||||
headerHeightPx = 240f,
|
||||
deltaPx = 80f,
|
||||
allowExpand = false,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `header expands after app list reaches its first item`() {
|
||||
assertEquals(
|
||||
-160f,
|
||||
collapsingHeaderOffsetAfterScroll(
|
||||
currentOffsetPx = -240f,
|
||||
headerHeightPx = 240f,
|
||||
deltaPx = 80f,
|
||||
allowExpand = true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `header gesture clamps expansion and collapse to measured height`() {
|
||||
assertEquals(
|
||||
0f,
|
||||
collapsingHeaderOffsetAfterScroll(-40f, 240f, 100f, allowExpand = true),
|
||||
)
|
||||
assertEquals(
|
||||
-240f,
|
||||
collapsingHeaderOffsetAfterScroll(-200f, 240f, -100f, allowExpand = true),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `quick exclusions recognize current whitelist app packages`() {
|
||||
val packages = listOf(
|
||||
"ru.oneme.app",
|
||||
"ru.gosuslugi.goskey",
|
||||
"com.octopod.russianpost.client.android",
|
||||
"ru.nspk.mirpay",
|
||||
"ru.nspk.sbpay",
|
||||
"logo.com.mbanking",
|
||||
"ru.rzd.pass",
|
||||
"ru.tutu.tutu_emp",
|
||||
"ru.vkusvill",
|
||||
"com.icemobile.lenta.prod",
|
||||
"ru.reksoft.okey",
|
||||
"ru.myauchan.droid",
|
||||
"www.metro.com",
|
||||
"ru.tander.magnit",
|
||||
"ru.pyaterochka.app.browser",
|
||||
"ru.perekrestok.app",
|
||||
"club.chizhik",
|
||||
"com.logistic.sdek",
|
||||
"ru.dodopizza.app",
|
||||
"ru.burgerking",
|
||||
"com.apegroup.mcdonaldsrussia",
|
||||
"com.carshering",
|
||||
"youdrive.today",
|
||||
"ru.ivi.client",
|
||||
"ru.more.play",
|
||||
"ru.zen.android",
|
||||
"gpm.tnt_premier",
|
||||
"ru.mts.mtstv",
|
||||
"ru.radioplayer",
|
||||
)
|
||||
|
||||
packages.forEach { packageName ->
|
||||
assertTrue(
|
||||
"Expected $packageName to be a quick exclusion",
|
||||
matchesQuickExclusionApp(name = "Неизвестное название", packageName = packageName),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `quick exclusions match store label aliases without selecting unrelated apps`() {
|
||||
assertTrue(matchesQuickExclusionApp("МАКС: общение, звонки, сервисы", "store.variant"))
|
||||
assertTrue(matchesQuickExclusionApp("Вкусно — и точка", "store.variant"))
|
||||
assertTrue(matchesQuickExclusionApp("Сателлит Online", "store.variant"))
|
||||
assertFalse(matchesQuickExclusionApp("Калькулятор", "com.example.calculator"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class OutboundFormsStoreTest {
|
||||
@Test
|
||||
fun keys_areScopedToVpnProfile() {
|
||||
assertEquals(
|
||||
"profile_0_external_proxy_host",
|
||||
OutboundFormsStore.key(0, "external_proxy_host")
|
||||
)
|
||||
assertEquals(
|
||||
"profile_2_external_proxy_host",
|
||||
OutboundFormsStore.key(2, "external_proxy_host")
|
||||
)
|
||||
assertEquals(
|
||||
"profile_2_external_proxy_host",
|
||||
OutboundFormsStore.key(99, "external_proxy_host")
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun secretKeys_haveSeparateEncryptedStorageName() {
|
||||
assertEquals(
|
||||
"profile_1_imported_wg_config_encrypted",
|
||||
OutboundFormsStore.encryptedKey(1, "imported_wg_config")
|
||||
)
|
||||
assertTrue(OutboundFormsStore.isSecretPlainKey("profile_1_wg_exit_password"))
|
||||
assertTrue(OutboundFormsStore.isSecretPlainKey("local_proxy_password"))
|
||||
assertFalse(OutboundFormsStore.isSecretPlainKey("profile_1_external_proxy_host"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class OutboundProfileComparisonTest {
|
||||
@Test
|
||||
fun unusedGeneratedDefaults_doNotLookLikeServerChanges() {
|
||||
val server = snapshot(
|
||||
localProxyPort = "1080",
|
||||
localProxyLogin = "old-generated-login",
|
||||
localProxyPassword = "old-generated-password",
|
||||
externalProxyKindName = "",
|
||||
externalProxyPort = "",
|
||||
wireGuardExitSshPort = "",
|
||||
wireGuardExitUser = "",
|
||||
wireGuardExitPort = "",
|
||||
wireGuardExitDns = ""
|
||||
)
|
||||
val local = forms(
|
||||
localProxyLogin = "new-generated-login",
|
||||
localProxyPassword = "new-generated-password"
|
||||
)
|
||||
|
||||
assertFalse(outboundProfilesDiffer(server, local))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun configuredValues_areComparedAfterStorageNormalization() {
|
||||
val server = snapshot(
|
||||
mode = "wireguard_vps",
|
||||
wireGuardPresent = true,
|
||||
wireGuardExitHost = "exit.example.org",
|
||||
wireGuardExitSshPort = "22",
|
||||
wireGuardExitUser = "root",
|
||||
wireGuardExitPassword = "secret",
|
||||
wireGuardExitPort = "51820",
|
||||
wireGuardExitDns = "1.1.1.1,8.8.8.8"
|
||||
)
|
||||
val local = forms(
|
||||
wireGuardExitHost = " exit.example.org ",
|
||||
wireGuardExitSshPort = "port 22",
|
||||
wireGuardExitUser = "root",
|
||||
wireGuardExitPassword = "secret",
|
||||
wireGuardExitPort = "51820 ",
|
||||
wireGuardExitDns = "9.9.9.9"
|
||||
)
|
||||
|
||||
// DNS WireGuard-выхода намеренно не сравнивается: DNS клиентов задаётся
|
||||
// в основных настройках WDTT и не применяется этим режимом.
|
||||
assertFalse(outboundProfilesDiffer(server, local))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun configuredProxyChange_isReported() {
|
||||
val server = snapshot(
|
||||
externalProxyPresent = true,
|
||||
externalProxyKindName = "Socks5",
|
||||
externalProxyHost = "old.example.org",
|
||||
externalProxyPort = "1080"
|
||||
)
|
||||
val local = forms(externalProxyHost = "new.example.org")
|
||||
|
||||
assertTrue(outboundProfilesDiffer(server, local))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun orphanedWarpInterface_isAttributedOnlyToWarpAndCanBeDisabledThere() {
|
||||
val server = snapshot(
|
||||
mode = "direct",
|
||||
wireGuardPresent = true,
|
||||
wireGuardActive = true,
|
||||
warpPresent = true
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
OutboundModeIndicator(OutboundModeVisualState.Error, "не отключён"),
|
||||
outboundModeIndicator(server, OutboundDialog.FreeWarp)
|
||||
)
|
||||
assertEquals(
|
||||
OutboundModeVisualState.Off,
|
||||
outboundModeIndicator(server, OutboundDialog.WireGuardVps).state
|
||||
)
|
||||
assertEquals(
|
||||
OutboundModeVisualState.Off,
|
||||
outboundModeIndicator(server, OutboundDialog.ImportedWireGuard).state
|
||||
)
|
||||
assertTrue(canDisableOutboundDialog(server, OutboundDialog.FreeWarp))
|
||||
assertFalse(canDisableOutboundDialog(server, OutboundDialog.WireGuardVps))
|
||||
assertFalse(canDisableOutboundDialog(server, OutboundDialog.ImportedWireGuard))
|
||||
assertTrue(canReturnDirect(server))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun ownerMarker_winsOverUnrelatedWarpRegistration() {
|
||||
val server = snapshot(
|
||||
mode = "direct",
|
||||
wireGuardPresent = true,
|
||||
wireGuardActive = true,
|
||||
warpPresent = true,
|
||||
wireGuardOwnerMode = "imported_wg"
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
OutboundModeVisualState.Error,
|
||||
outboundModeIndicator(server, OutboundDialog.ImportedWireGuard).state
|
||||
)
|
||||
assertEquals(
|
||||
OutboundModeVisualState.Warning,
|
||||
outboundModeIndicator(server, OutboundDialog.FreeWarp).state
|
||||
)
|
||||
assertTrue(canDisableOutboundDialog(server, OutboundDialog.ImportedWireGuard))
|
||||
assertFalse(canDisableOutboundDialog(server, OutboundDialog.FreeWarp))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun partialExternalProxy_isNotReportedAsActiveAndCanBeCleaned() {
|
||||
val server = snapshot(
|
||||
mode = "external_proxy",
|
||||
externalProxyPresent = true,
|
||||
externalProxyServiceActive = true,
|
||||
externalProxyRouteActive = false
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
OutboundModeIndicator(OutboundModeVisualState.Error, "запущен частично"),
|
||||
outboundModeIndicator(server, OutboundDialog.ExternalProxy)
|
||||
)
|
||||
assertTrue(canDisableOutboundDialog(server, OutboundDialog.ExternalProxy))
|
||||
assertTrue(canReturnDirect(server))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun recordedInactiveWireGuardMode_canStillBeDisabledFromItsDialog() {
|
||||
val server = snapshot(
|
||||
mode = "imported_wg",
|
||||
wireGuardPresent = true,
|
||||
wireGuardActive = false
|
||||
)
|
||||
|
||||
assertTrue(canDisableOutboundDialog(server, OutboundDialog.ImportedWireGuard))
|
||||
assertTrue(canReturnDirect(server))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun proxyCredentials_rejectAmbiguousValuesAndEscapeConfig() {
|
||||
assertEquals(
|
||||
"Логин внешнего прокси не должен содержать двоеточие.",
|
||||
externalProxyCredentialsIssue("user:name", "password")
|
||||
)
|
||||
assertTrue(localProxyCredentialsIssue("user", "short") != null)
|
||||
assertEquals("""a\\b\"c""", escapeRedsocksQuotedValue("""a\b"c"""))
|
||||
}
|
||||
|
||||
private fun forms(
|
||||
localProxyPort: String = "1080",
|
||||
localProxyLogin: String = "generated-login",
|
||||
localProxyPassword: String = "generated-password",
|
||||
externalProxyKindName: String = "Socks5",
|
||||
externalProxyHost: String = "",
|
||||
externalProxyPort: String = "1080",
|
||||
externalProxyLogin: String = "",
|
||||
externalProxyPassword: String = "",
|
||||
wireGuardExitHost: String = "",
|
||||
wireGuardExitSshPort: String = "22",
|
||||
wireGuardExitUser: String = "root",
|
||||
wireGuardExitPassword: String = "",
|
||||
wireGuardExitPort: String = "51820",
|
||||
wireGuardExitDns: String = "1.1.1.1,8.8.8.8",
|
||||
importedWireGuardConfig: String = ""
|
||||
) = OutboundProfileForms(
|
||||
localProxyPort = localProxyPort,
|
||||
localProxyLogin = localProxyLogin,
|
||||
localProxyPassword = localProxyPassword,
|
||||
externalProxyKindName = externalProxyKindName,
|
||||
externalProxyHost = externalProxyHost,
|
||||
externalProxyPort = externalProxyPort,
|
||||
externalProxyLogin = externalProxyLogin,
|
||||
externalProxyPassword = externalProxyPassword,
|
||||
wireGuardExitHost = wireGuardExitHost,
|
||||
wireGuardExitSshPort = wireGuardExitSshPort,
|
||||
wireGuardExitUser = wireGuardExitUser,
|
||||
wireGuardExitPassword = wireGuardExitPassword,
|
||||
wireGuardExitPort = wireGuardExitPort,
|
||||
wireGuardExitDns = wireGuardExitDns,
|
||||
importedWireGuardConfig = importedWireGuardConfig
|
||||
)
|
||||
|
||||
private fun snapshot(
|
||||
mode: String = "direct",
|
||||
localProxyPresent: Boolean = false,
|
||||
localProxyPort: String = "",
|
||||
localProxyLogin: String = "",
|
||||
localProxyPassword: String = "",
|
||||
externalProxyPresent: Boolean = false,
|
||||
externalProxyKindName: String = "",
|
||||
externalProxyHost: String = "",
|
||||
externalProxyPort: String = "",
|
||||
externalProxyLogin: String = "",
|
||||
externalProxyPassword: String = "",
|
||||
wireGuardPresent: Boolean = false,
|
||||
wireGuardActive: Boolean = false,
|
||||
wireGuardExitHost: String = "",
|
||||
wireGuardExitSshPort: String = "",
|
||||
wireGuardExitUser: String = "",
|
||||
wireGuardExitPassword: String = "",
|
||||
wireGuardExitPort: String = "",
|
||||
wireGuardExitDns: String = "",
|
||||
importedWireGuardConfig: String = "",
|
||||
warpPresent: Boolean = false,
|
||||
externalProxyServiceActive: Boolean = false,
|
||||
externalProxyRouteActive: Boolean = false,
|
||||
wireGuardOwnerMode: String = ""
|
||||
) = OutboundServerSnapshot(
|
||||
mode = mode,
|
||||
detail = "",
|
||||
updatedAt = "",
|
||||
hasProfile = true,
|
||||
localProxyPresent = localProxyPresent,
|
||||
localProxyActive = false,
|
||||
localProxyPort = localProxyPort,
|
||||
localProxyLogin = localProxyLogin,
|
||||
localProxyPassword = localProxyPassword,
|
||||
externalProxyPresent = externalProxyPresent,
|
||||
externalProxyActive = false,
|
||||
externalProxyKindName = externalProxyKindName,
|
||||
externalProxyHost = externalProxyHost,
|
||||
externalProxyPort = externalProxyPort,
|
||||
externalProxyLogin = externalProxyLogin,
|
||||
externalProxyPassword = externalProxyPassword,
|
||||
wireGuardPresent = wireGuardPresent,
|
||||
wireGuardActive = wireGuardActive,
|
||||
wireGuardExitHost = wireGuardExitHost,
|
||||
wireGuardExitSshPort = wireGuardExitSshPort,
|
||||
wireGuardExitUser = wireGuardExitUser,
|
||||
wireGuardExitPassword = wireGuardExitPassword,
|
||||
wireGuardExitPort = wireGuardExitPort,
|
||||
wireGuardExitDns = wireGuardExitDns,
|
||||
warpPresent = warpPresent,
|
||||
warpMtu = "",
|
||||
importedWireGuardConfig = importedWireGuardConfig,
|
||||
checkedAtMillis = 0L,
|
||||
externalProxyServiceActive = externalProxyServiceActive,
|
||||
externalProxyRouteActive = externalProxyRouteActive,
|
||||
wireGuardOwnerMode = wireGuardOwnerMode
|
||||
)
|
||||
}
|
||||
@@ -51,6 +51,8 @@ class OutboundWireGuardTest {
|
||||
fun freeWarpScript_hasSafeUpdateChecksAndValidShellSyntax() {
|
||||
val script = buildFreeWarpInstallScript(1392)
|
||||
|
||||
assertTrue(WGCF_VERSION == "2.2.32")
|
||||
assertTrue(THREEPROXY_VERSION == "0.9.7")
|
||||
assertTrue("WARP_MTU=1392" in script)
|
||||
assertTrue("checksums.txt" in script)
|
||||
assertTrue("sha256sum" in script)
|
||||
@@ -60,9 +62,60 @@ class OutboundWireGuardTest {
|
||||
assertTrue("WARP_ENDPOINT_CANDIDATES" in script)
|
||||
assertTrue("engage.cloudflareclient.com:2408" in script)
|
||||
assertTrue("rollback after WARP check error" in script)
|
||||
assertTrue("trap wdtt_wg_up_cleanup 0" in script)
|
||||
assertTrue("rollback after WireGuard service start error" in script)
|
||||
assertTrue("WDTT_ERROR=wireguard_exit_service_inactive" in script)
|
||||
assertTrue("ip link delete \"${'$'}WDTT_WG_IFACE\"" in script)
|
||||
assertShellSyntax(script)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun directExitScript_forceCleansPartiallyStartedWireGuard() {
|
||||
val script = disableOutboundExitScript()
|
||||
|
||||
assertTrue("wdtt_clear_external_out" in script)
|
||||
assertTrue("ip link delete \"${'$'}WDTT_WG_IFACE\"" in script)
|
||||
assertTrue("WDTT_ERROR=direct_cleanup_failed" in script)
|
||||
assertTrue("wdtt_write_mode \"direct\"" in script)
|
||||
assertShellSyntax(script)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun outboundCleanupScripts_areScopedAndHaveValidShellSyntax() {
|
||||
val localStop = stopLocalProxyScript()
|
||||
val localRemove = removeLocalProxyScript()
|
||||
val external = deleteExternalProxyScript()
|
||||
val imported = deleteImportedWireGuardExitScript()
|
||||
val currentVps = deleteWireGuardVpsCurrentScript()
|
||||
val foreignVps = deleteWireGuardVpsForeignScript()
|
||||
|
||||
assertTrue("systemctl disable --now wdtt-3proxy" in localStop)
|
||||
assertTrue("local_proxy_service_still_active" in localStop)
|
||||
assertTrue("LOCAL_PROXY_PASSWORD_B64" in localRemove)
|
||||
assertTrue("local_proxy_remove_failed" in localRemove)
|
||||
assertTrue("wdtt_clear_proxy_out" in external)
|
||||
assertTrue("EXTERNAL_PROXY_PASSWORD_B64" in external)
|
||||
assertTrue("external_proxy_remove_failed" in external)
|
||||
assertTrue("OWNS_ACTIVE" in imported)
|
||||
assertTrue("wdtt_clear_wireguard_out" in imported)
|
||||
assertTrue("IMPORTED_WG_CONFIG_B64" in imported)
|
||||
assertTrue("wireguard_vps_current_remove_failed" in currentVps)
|
||||
assertTrue("WDTT_EXIT_FOREIGN" in foreignVps)
|
||||
assertTrue("foreign_wireguard_not_owned" in foreignVps)
|
||||
assertShellSyntax(localStop)
|
||||
assertShellSyntax(localRemove)
|
||||
assertShellSyntax(external)
|
||||
assertShellSyntax(imported)
|
||||
assertShellSyntax(currentVps)
|
||||
assertShellSyntax(foreignVps)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun protocolErrorMarker_isNotCopiedRawToUserLog() {
|
||||
assertFalse(shouldWriteRemoteErrorToUserLog("WDTT_ERROR=local_proxy_check_failed"))
|
||||
assertTrue(shouldWriteRemoteErrorToUserLog("FAIL: служба не запустилась"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun serverDiagnosticsScript_hasPortableChecksAndValidShellSyntax() {
|
||||
val script = serverDiagnosticsScript()
|
||||
@@ -79,12 +132,25 @@ class OutboundWireGuardTest {
|
||||
assertTrue("systemctl" in script)
|
||||
assertTrue("iptables" in script)
|
||||
assertTrue("nft" in script)
|
||||
assertTrue("VK / TURN-зависимости" in script)
|
||||
assertTrue("VK/OK с VPS (справочно)" in script)
|
||||
assertTrue("не влияет на основной VK-вход" in script)
|
||||
assertTrue("login.vk.ru" in script)
|
||||
assertTrue("api.vk.me" in script)
|
||||
assertTrue("api.vk.ru" in script)
|
||||
assertTrue("calls.okcdn.ru" in script)
|
||||
assertTrue("Получение VK-токенов и решение капчи выполняются на телефоне" in script)
|
||||
assertFalse("обязательным узлам VK в зоне .ru" in script)
|
||||
assertTrue("api.telegram.org" in script)
|
||||
assertTrue("Бесплатный WARP" in script)
|
||||
assertTrue("engage.cloudflareclient.com" in script)
|
||||
assertTrue("wdtt_diag_wg_exit_probe" in script)
|
||||
assertTrue("Cloudflare подтвердил warp=" in script)
|
||||
assertTrue("WG_POLICY_RULE_ACTIVE" in script)
|
||||
assertTrue("WG_DEFAULT_ROUTE_ACTIVE" in script)
|
||||
assertTrue("WG_NAT_ACTIVE" in script)
|
||||
assertTrue("WireGuard-выход запущен не полностью" in script)
|
||||
assertTrue("FIREWALL_SEVERITY=\"ERROR\"" in script)
|
||||
assertTrue("NAT прямого выхода отсутствует" in script)
|
||||
assertTrue("WDTT_EXPECTED_DTLS_PORT" in script)
|
||||
assertTrue("wdtt_diag_udp_probe" in script)
|
||||
assertTrue("/dev/net/tun" in script)
|
||||
@@ -93,6 +159,42 @@ class OutboundWireGuardTest {
|
||||
assertShellSyntax(script, shell = "sh")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun externalProxyTransparentCheck_doesNotCaptureRootXrayTraffic() {
|
||||
val script = outboundShellPrelude()
|
||||
|
||||
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)
|
||||
assertFalse("iptables -t nat -I OUTPUT -p tcp -m owner --uid-owner 0 -j WDTT_PROXY_TEST" in script)
|
||||
assertShellSyntax(script)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun outboundSnapshot_preservesExplicitlySavedEmptyFields() {
|
||||
val script = outboundSnapshotScript()
|
||||
|
||||
assertTrue("wdtt_profile_has_key" in script)
|
||||
assertTrue("if wdtt_profile_has_key LOCAL_PROXY_LOGIN_B64" in script)
|
||||
assertTrue("if wdtt_profile_has_key EXTERNAL_PROXY_HOST_B64" in script)
|
||||
assertTrue("if wdtt_profile_has_key WG_VPS_DNS_B64" in script)
|
||||
assertTrue("! wdtt_profile_has_key IMPORTED_WG_CONFIG_B64" in script)
|
||||
assertTrue("WDTT_LOCAL_PROXY_SERVICE_ENABLED" in script)
|
||||
assertTrue("WDTT_EXTERNAL_PROXY_SERVICE_ENABLED" in script)
|
||||
assertTrue("WDTT_WG_SERVICE_ENABLED" in script)
|
||||
assertShellSyntax(script)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun detailedOutboundStatus_reportsRoutesAndAutostart() {
|
||||
val script = outboundStatusScript()
|
||||
|
||||
assertTrue("Автозапуск внешнего TCP-прокси" in script)
|
||||
assertTrue("Правило маршрутизации подсети WDTT" in script)
|
||||
assertTrue("NAT WireGuard-выхода" in script)
|
||||
assertShellSyntax(script)
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException::class)
|
||||
fun freeWarpScript_rejectsUnsafeMtu() {
|
||||
buildFreeWarpInstallScript(1600)
|
||||
|
||||
@@ -2,8 +2,11 @@ package com.wdtt.plus.ui
|
||||
|
||||
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
|
||||
import java.util.Base64
|
||||
|
||||
class ServerMigrationTest {
|
||||
@Test
|
||||
@@ -11,6 +14,64 @@ class ServerMigrationTest {
|
||||
validatePasswordsDbStructure(database("client-a", "Телефон"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun backupValidation_acceptsTrafficImportHistory() {
|
||||
val db = database("client-a", "Телефон")
|
||||
|
||||
validatePasswordsDbStructure(db)
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException::class)
|
||||
fun backupValidation_rejectsMalformedTrafficImportHistory() {
|
||||
val db = database("client-a", "Телефон")
|
||||
db.getJSONObject("passwords").getJSONObject("client-a")
|
||||
.put("traffic_imports", JSONArray())
|
||||
|
||||
validatePasswordsDbStructure(db)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun preserveValidation_recoversEmptyMainPasswordFromCurrentSecrets() {
|
||||
val db = database("client-a", "Телефон").put("main_password", "")
|
||||
|
||||
val needsRecovery = validatePasswordsDbForPreserving(db, "new-owner-password")
|
||||
|
||||
assertTrue(needsRecovery)
|
||||
assertTrue(db.optString("main_password").isEmpty())
|
||||
assertTrue(db.getJSONObject("passwords").has("client-a"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun preserveValidation_recoversMissingMainPasswordFromCurrentSecrets() {
|
||||
val db = database("client-a", "Телефон").apply { remove("main_password") }
|
||||
|
||||
assertTrue(validatePasswordsDbForPreserving(db, "new-owner-password"))
|
||||
assertTrue(!db.has("main_password"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun preserveValidation_keepsValidMainPassword() {
|
||||
val db = database("client-a", "Телефон")
|
||||
|
||||
assertTrue(!validatePasswordsDbForPreserving(db, "new-owner-password"))
|
||||
assertTrue(db.optString("main_password") == "owner-password")
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException::class)
|
||||
fun preserveValidation_rejectsRecoveryWithoutCurrentMainPassword() {
|
||||
val db = database("client-a", "Телефон").put("main_password", "")
|
||||
|
||||
validatePasswordsDbForPreserving(db, "")
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException::class)
|
||||
fun preserveValidation_stillRejectsMalformedClientDataDuringRecovery() {
|
||||
val db = database("client-a", "Телефон").put("main_password", "")
|
||||
db.getJSONObject("passwords").getJSONObject("client-a").put("expires_at", -1L)
|
||||
|
||||
validatePasswordsDbForPreserving(db, "new-owner-password")
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException::class)
|
||||
fun backupValidation_rejectsInvalidOwnerProfile() {
|
||||
val db = database("client-a", "Телефон")
|
||||
@@ -28,6 +89,19 @@ class ServerMigrationTest {
|
||||
validateImportedServerState(source.toString(), null, after.toString(), replace = true)
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException::class)
|
||||
fun replaceImport_detectsChangedTrafficImportHistory() {
|
||||
val source = database("client-a", "Телефон")
|
||||
val after = JSONObject(source.toString())
|
||||
after.getJSONObject("passwords")
|
||||
.getJSONObject("client-a")
|
||||
.getJSONObject("traffic_imports")
|
||||
.getJSONObject("move-1")
|
||||
.put("down_bytes", 999L)
|
||||
|
||||
validateImportedServerState(source.toString(), null, after.toString(), replace = true)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mergeImport_preservesTargetAndAddsMissingClient() {
|
||||
val before = database("target-client", "Существующий")
|
||||
@@ -79,10 +153,120 @@ class ServerMigrationTest {
|
||||
assertTrue(target.getJSONObject("devices").getJSONObject("used-device").getString("ip") == "10.66.66.3")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun replaceAdaptsOwnerAndClientPortsToTarget() {
|
||||
val source = database("client-a", "Телефон")
|
||||
|
||||
val prepared = JSONObject(
|
||||
prepareServerDatabaseForTarget(
|
||||
sourceJson = source.toString(),
|
||||
currentDbJson = null,
|
||||
merge = false,
|
||||
portsSpec = "56100,56101,9100",
|
||||
dnsValue = "9.9.9.9",
|
||||
publicHost = "new.example.org"
|
||||
)
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
"56100,56101,9100",
|
||||
prepared.getJSONObject("passwords").getJSONObject("client-a").getString("ports")
|
||||
)
|
||||
assertEquals("56100,56101,9100", prepared.getJSONObject("admin_profile").getString("ports"))
|
||||
assertEquals(9100, prepared.getJSONObject("admin_profile").getInt("listen_port"))
|
||||
assertEquals("new.example.org", prepared.getString("public_ip"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mergeIntoEmptyServerKeepsWholeSourceDatabase() {
|
||||
val source = database("client-a", "Телефон")
|
||||
.put("admin_down_bytes", 12_345L)
|
||||
.put("admin_up_bytes", 54_321L)
|
||||
|
||||
val prepared = JSONObject(
|
||||
prepareServerDatabaseForTarget(
|
||||
sourceJson = source.toString(),
|
||||
currentDbJson = null,
|
||||
merge = true,
|
||||
portsSpec = "56100,56101,9100",
|
||||
dnsValue = "9.9.9.9",
|
||||
publicHost = "new.example.org"
|
||||
)
|
||||
)
|
||||
|
||||
assertEquals(12_345L, prepared.getLong("admin_down_bytes"))
|
||||
assertEquals(54_321L, prepared.getLong("admin_up_bytes"))
|
||||
assertTrue(prepared.getJSONObject("admin_profile").has("workers_per_hash"))
|
||||
assertTrue(prepared.getJSONObject("passwords").has("client-a"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun versionTwoBackupRoundTripVerifiesIntegrity() {
|
||||
val source = database("client-a", "Телефон")
|
||||
val keys = List(4) { "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" }.joinToString("\n")
|
||||
val encoded = backupToJson(
|
||||
parseBackup(
|
||||
passwordsJson = source.toString(),
|
||||
wgKeysDat = keys,
|
||||
createdAt = "27.07.2026 12:00",
|
||||
sourceHost = "old.example.org"
|
||||
)
|
||||
)
|
||||
|
||||
val decoded = parseBackupFile(encoded)
|
||||
|
||||
assertEquals(2, decoded.formatVersion)
|
||||
assertTrue(decoded.integrityVerified)
|
||||
assertTrue(decoded.hasWgKeys)
|
||||
assertEquals(source.toString(), decoded.passwordsJson)
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException::class)
|
||||
fun versionTwoBackupRejectsChangedDatabase() {
|
||||
val source = database("client-a", "Телефон")
|
||||
val encoded = JSONObject(
|
||||
backupToJson(
|
||||
parseBackup(
|
||||
passwordsJson = source.toString(),
|
||||
wgKeysDat = null,
|
||||
createdAt = "27.07.2026 12:00",
|
||||
sourceHost = "old.example.org"
|
||||
)
|
||||
)
|
||||
)
|
||||
val changed = JSONObject(source.toString()).put("dns", "8.8.8.8").toString()
|
||||
encoded.put(
|
||||
"passwords_json_b64",
|
||||
Base64.getEncoder().encodeToString(changed.toByteArray())
|
||||
)
|
||||
|
||||
parseBackupFile(encoded.toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun versionOneBackupRemainsCompatible() {
|
||||
val source = database("client-a", "Телефон")
|
||||
val legacy = JSONObject()
|
||||
.put("format", "wdtt-server-backup")
|
||||
.put("version", 1)
|
||||
.put("created_at", "05.07.2026 10:00")
|
||||
.put("source_host", "old.example.org")
|
||||
.put(
|
||||
"passwords_json_b64",
|
||||
Base64.getEncoder().encodeToString(source.toString().toByteArray())
|
||||
)
|
||||
|
||||
val decoded = parseBackupFile(legacy.toString())
|
||||
|
||||
assertEquals(1, decoded.formatVersion)
|
||||
assertFalse(decoded.integrityVerified)
|
||||
assertEquals(source.toString(), decoded.passwordsJson)
|
||||
}
|
||||
|
||||
private fun database(password: String, label: String): JSONObject {
|
||||
val entry = JSONObject()
|
||||
.put("device_id", "")
|
||||
.put("expires_at", 0L)
|
||||
.put("expires_at", 2_000_000_000L)
|
||||
.put("down_bytes", 1024L)
|
||||
.put("up_bytes", 2048L)
|
||||
.put("label", label)
|
||||
@@ -94,6 +278,13 @@ class ServerMigrationTest {
|
||||
.put("down_bytes", 1024L)
|
||||
.put("up_bytes", 2048L)
|
||||
))
|
||||
.put("traffic_imports", JSONObject().put(
|
||||
"move-1",
|
||||
JSONObject()
|
||||
.put("down_bytes", 100L)
|
||||
.put("up_bytes", 200L)
|
||||
.put("applied_at", 1_700_000_000L)
|
||||
))
|
||||
.put("bind_history", JSONArray())
|
||||
return JSONObject()
|
||||
.put("main_password", "owner-password")
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class VkClientIdProbeTest {
|
||||
@Test
|
||||
fun legacyProbePrefersVkRuAndKeepsVkComAsCompatibilityFallback() {
|
||||
assertEquals("https://oauth.vk.ru/authorize", vkLegacyOAuthProbeEndpoints.first())
|
||||
assertEquals("https://oauth.vk.com/authorize", vkLegacyOAuthProbeEndpoints.last())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun acceptsLegacyOauthLoginPage() {
|
||||
assertTrue(isVkLegacyClientIdProbeSuccessful(200, "text/html; charset=utf-8"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rejectsJsonErrorsAndHttpFailures() {
|
||||
assertFalse(isVkLegacyClientIdProbeSuccessful(401, "application/json; charset=utf-8"))
|
||||
assertFalse(isVkLegacyClientIdProbeSuccessful(200, "application/json"))
|
||||
assertFalse(isVkLegacyClientIdProbeSuccessful(503, "text/html"))
|
||||
assertTrue(isVkLegacyClientIdProbeRejected(401))
|
||||
assertFalse(isVkLegacyClientIdProbeRejected(429))
|
||||
assertFalse(isVkLegacyClientIdProbeRejected(503))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun cachedProbeResultsKeepStatusAndTimestampSeparate() {
|
||||
val cache = parseVkClientIdCheckResults(
|
||||
"""{"_probe_version":3,"_checked_at":123456,"6287487":"LegacyCompatible","8202606":"LegacyRejected"}"""
|
||||
)
|
||||
|
||||
assertEquals(123456L, cache.checkedAt)
|
||||
assertEquals(
|
||||
mapOf(
|
||||
"6287487" to VkClientIdProbeStatus.LegacyCompatible,
|
||||
"8202606" to VkClientIdProbeStatus.LegacyRejected
|
||||
),
|
||||
cache.results
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun probeCooldownBlocksRapidRepeatedChecks() {
|
||||
assertEquals(10_000L, vkClientIdProbeCooldownRemainingMillis(now = 20_000L, lastStartedAt = 20_000L))
|
||||
assertEquals(1L, vkClientIdProbeCooldownRemainingMillis(now = 29_999L, lastStartedAt = 20_000L))
|
||||
assertEquals(0L, vkClientIdProbeCooldownRemainingMillis(now = 30_000L, lastStartedAt = 20_000L))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun availabilitySummaryExplainsAllProbeCombinations() {
|
||||
val ids = listOf("6287487", "8202606")
|
||||
|
||||
assertEquals(
|
||||
"Все встроенные Client ID доступны для резервного способа",
|
||||
vkClientIdAvailabilityMessage(
|
||||
ids,
|
||||
mapOf(
|
||||
"6287487" to VkClientIdProbeStatus.LegacyCompatible,
|
||||
"8202606" to VkClientIdProbeStatus.LegacyCompatible
|
||||
)
|
||||
)
|
||||
)
|
||||
assertEquals(
|
||||
"Доступны: 6287487. Не принимаются: 8202606.",
|
||||
vkClientIdAvailabilityMessage(
|
||||
ids,
|
||||
mapOf(
|
||||
"6287487" to VkClientIdProbeStatus.LegacyCompatible,
|
||||
"8202606" to VkClientIdProbeStatus.LegacyRejected
|
||||
)
|
||||
)
|
||||
)
|
||||
assertEquals(
|
||||
"Не удалось проверить: 6287487, 8202606.",
|
||||
vkClientIdAvailabilityMessage(
|
||||
ids,
|
||||
mapOf(
|
||||
"6287487" to VkClientIdProbeStatus.CheckFailed,
|
||||
"8202606" to VkClientIdProbeStatus.CheckFailed
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun automaticProbeUsesOnlyCredentialsForSelectedMode() {
|
||||
assertEquals(
|
||||
listOf("6287487", "8202606"),
|
||||
vkClientIdsForAutomaticProbe(false, "123456", "secret")
|
||||
)
|
||||
assertEquals(
|
||||
listOf("123456"),
|
||||
vkClientIdsForAutomaticProbe(true, "123456", "secret")
|
||||
)
|
||||
assertTrue(vkClientIdsForAutomaticProbe(true, "123456", "").isEmpty())
|
||||
assertTrue(vkClientIdsForAutomaticProbe(true, "invalid", "secret").isEmpty())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class VkHashBulkPasteTest {
|
||||
@Test
|
||||
fun parseBulkVkHashesAcceptsCommaSeparatedHashes() {
|
||||
assertEquals(
|
||||
listOf("hash000000000001", "hash000000000002", "hash000000000003", "hash000000000004"),
|
||||
parseBulkVkHashes("hash000000000001,hash000000000002,hash000000000003,hash000000000004")
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parseBulkVkHashesAcceptsEncodedSpacesAndSeparators() {
|
||||
assertEquals(
|
||||
listOf("hash000000000001", "hash000000000002", "hash000000000003", "hash000000000004"),
|
||||
parseBulkVkHashes("hash000000000001%20hash000000000002%2Chash000000000003%0Ahash000000000004")
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parseBulkVkHashesExtractsJoinLinksAndDropsDuplicates() {
|
||||
assertEquals(
|
||||
listOf("hash000000000001", "hash000000000002"),
|
||||
parseBulkVkHashes(
|
||||
"https://vk.com/call/join/hash000000000001 " +
|
||||
"https://vk.ru/call/join/hash000000000002 " +
|
||||
"hash000000000001"
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parseBulkVkHashesRejectsOrdinaryLongWords() {
|
||||
assertEquals(
|
||||
emptyList<String>(),
|
||||
parseBulkVkHashes("пользовательский переподключаются")
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mergeBulkVkHashesFillsOnlyEmptySlotsWithoutOverwritingExisting() {
|
||||
val result = mergeBulkVkHashes(
|
||||
existingSlots = listOf("", "oldHash0000000002", "oldHash0000000003", ""),
|
||||
incomingHashes = listOf("newHash0000000001", "oldHash0000000002", "newHash0000000004"),
|
||||
mode = BulkVkHashPasteMode.FillEmpty
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
listOf("newHash0000000001", "oldHash0000000002", "oldHash0000000003", "newHash0000000004"),
|
||||
result.slots
|
||||
)
|
||||
assertEquals(2, result.insertedCount)
|
||||
assertEquals(1, result.skippedCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mergeBulkVkHashesReplacesAllSlotsWhenRequested() {
|
||||
val result = mergeBulkVkHashes(
|
||||
existingSlots = listOf("", "oldHash0000000002", "oldHash0000000003", ""),
|
||||
incomingHashes = listOf("newHash0000000001", "newHash0000000002", "newHash0000000003", "newHash0000000004"),
|
||||
mode = BulkVkHashPasteMode.ReplaceAll
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
listOf("newHash0000000001", "newHash0000000002", "newHash0000000003", "newHash0000000004"),
|
||||
result.slots
|
||||
)
|
||||
assertEquals(4, result.insertedCount)
|
||||
assertEquals(0, result.skippedCount)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user