Merge remote-tracking branch 'origin/main' into fix/pr-1174-gog-installer

# Conflicts:
#	app/src/main/java/com/droiddeck/launcher/stores/gog/GogBackend.kt
#	app/src/main/java/com/droiddeck/launcher/stores/gog/GogDownloadManager.java
This commit is contained in:
xXJsonDeruloXx committed 2026-10-22 10:16:32 -04:00
commit 6cbf8f4d73
223 files changed
+7406 -1373

No files matched your search

@@ -0,0 +1,57 @@
package com.droiddeck.launcher.core
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class AddonPackTest {
private val context: Context = ApplicationProvider.getApplicationContext()
private val root get() = File(context.filesDir, "addons/sample")
@Before fun clean() {
root.deleteRecursively()
}
private fun installed(version: String, complete: Boolean = true, modified: Long = 1_000L): File =
File(root, version).apply {
mkdirs()
File(this, "tool").writeText("x")
if (complete) File(this, AddonPack.COMPLETE).writeText(version)
setLastModified(modified)
}
@Test fun unpinnedLocalBuildReusesTheNewestCompletePack() {
installed("a".repeat(64), modified = 1_000L)
installed("b".repeat(64), modified = 2_000L)
installed("c".repeat(64), complete = false, modified = 3_000L)
val pack = AddonPack("sample", "", 0L, listOf("tool"), reuseDeviceCopy = true)
assertTrue(pack.installed(context))
assertEquals("b".repeat(64), pack.dir(context).name)
}
@Test fun unpinnedLocalBuildWithNothingInstalledHasNoPack() {
assertFalse(AddonPack("sample", "", 0L, listOf("tool"), reuseDeviceCopy = true).installed(context))
}
@Test fun pinnedBuildIgnoresOtherInstalledVersions() {
installed("b".repeat(64))
val pack = AddonPack("sample", "a".repeat(64), 1L, listOf("tool"))
assertFalse(pack.installed(context))
assertEquals("a".repeat(64), pack.dir(context).name)
}
@Test fun ciBuildWithoutAPinNeverReuses() {
installed("b".repeat(64))
assertFalse(AddonPack("sample", "", 0L, listOf("tool"), reuseDeviceCopy = false).installed(context))
}
}
@@ -167,4 +167,10 @@ class DownloaderResumeTest {
assertEquals(listOf(catalog), DownloadSource.candidates(catalog))
}
@Test fun withoutADigestOnlyTheOriginalUrlIsTried() {
val url = "https://github.com/owner/repo/releases/download/v1/app.AppImage"
assertEquals(listOf(url), Downloader.sources(url, null))
assertEquals(DownloadSource.candidates(url), Downloader.sources(url, "a".repeat(64)))
}
}
@@ -37,6 +37,83 @@ class LogRedactorTest {
assertEquals("login <redacted:email> ok", LogRedactor.redact("login someone@example.com ok"))
}
@Test fun onlyLoaderDiagnosticsKeepHidlSharedLibraryNames() {
val library = "android.hardware.graphics.mapper@4.0.so"
val line = "dlopen failed: library \"$library\" not found"
val pathLine = "dlopen failed: library \"/vendor/lib64/hw/$library\" not found"
assertEquals(line, LogRedactor.redact(line))
assertEquals(line, LogRedactor.redactForShare(line))
assertEquals(pathLine, LogRedactor.redact(pathLine))
assertEquals(pathLine, LogRedactor.redactForShare(pathLine))
}
@Test fun privacyRulesOverrideTheHidlSharedLibraryException() {
val library = "android.hardware.graphics.mapper@4.0.so"
assertEquals("token=<redacted:token>", LogRedactor.redact("token=$library"))
assertEquals("username=<redacted:account>", LogRedactor.redact("username=$library"))
assertEquals("{\"password\":\"<redacted:token>\"}", LogRedactor.redact("{\"password\":\"$library\"}"))
assertEquals("{\"password\":\"<redacted:token>\"}", LogRedactor.redactForShare("{\"password\":\"$library\"}"))
assertEquals("{\"password\":\"<redacted:token>\"}", LogRedactor.redact("{\"password\":\"don't-use-$library\"}"))
assertEquals("{\"password\":\"<redacted:token>\"}", LogRedactor.redactForShare("{\"password\":\"don't-use-$library\"}"))
val mixed = "dlopen failed: library \"$library\" not found; token=abcdef123456; contact=alice!$library; {\"password\":\"library \\\"$library\\\" not found\"}"
val expected = "dlopen failed: library \"$library\" not found; token=<redacted:token>; contact=alice!<redacted:email>; {\"password\":\"<redacted:token>\"}"
assertEquals(expected, LogRedactor.redact(mixed))
assertEquals(expected, LogRedactor.redactForShare(mixed))
val root = java.nio.file.Files.createTempDirectory("hidl-redactor").toFile()
val users = java.io.File(root, "loginusers.vdf")
users.writeText("\"AccountName\" \"$library\"")
try {
LogRedactor.learnAccounts(users)
assertEquals("<redacted:account>", LogRedactor.redact(library))
} finally {
LogRedactor.learnAccounts()
root.deleteRecursively()
}
}
@Test fun hidlSharedLibraryNamesAreRedactedOutsideLoaderDiagnostics() {
val library = "android.hardware.graphics.mapper@4.0.so"
assertEquals("<redacted:email>", LogRedactor.redact(library))
assertEquals("<redacted:email>", LogRedactor.redactForShare(library))
assertEquals("/vendor/lib64/hw/<redacted:email>", LogRedactor.redact("/vendor/lib64/hw/$library"))
for (punctuation in listOf("!", "#", "~", "/", "=")) {
val expected = "contact=alice$punctuation<redacted:email>"
assertEquals(expected, LogRedactor.redact("contact=alice$punctuation$library"))
assertEquals(expected, LogRedactor.redactForShare("contact=alice$punctuation$library"))
}
assertEquals("<redacted:email>", LogRedactor.redact("$library.evil"))
assertEquals("<redacted:email>", LogRedactor.redact("someone@company.so"))
assertEquals("<redacted:email>", LogRedactor.redact("not$library"))
assertEquals("<redacted:email>_debug", LogRedactor.redact("${library}_debug"))
assertEquals("<redacted:email>.1", LogRedactor.redact("${library}.1"))
assertEquals("<redacted:email>@attacker", LogRedactor.redact("${library}@attacker"))
assertEquals("<redacted:email>", LogRedactor.redact("android.hardware.graphics.mapper@4.0.software"))
assertEquals("<redacted:email>", LogRedactor.redact("android.hardware.graphics.mapper@4.0.so.evil"))
}
@Test fun loaderContextRequiresExactWordsAndABoundedAndroidPath() {
val library = "android.hardware.graphics.mapper@4.0.so"
val valid = "library \"/system/lib64/$library\" not found: needed by app"
assertEquals(valid, LogRedactor.redact(valid))
assertEquals(valid, LogRedactor.redactForShare(valid))
for (line in listOf(
"not_library \"$library\" not found",
"library \"$library\" not found_suffix",
"library \"/home/user/$library\" not found",
"library \"relative/$library\" not found",
"library \"/vendor/invalid!/$library\" not found",
"library \"/vendor/" + "a/".repeat(2050) + "$library\" not found",
)) {
val expected = line.replace(library, "<redacted:email>")
assertEquals(expected, LogRedactor.redact(line))
assertEquals(expected, LogRedactor.redactForShare(line))
}
}
@Test fun clockTimeIsNotAnAddress() {
val line = "[2026-09-27 10:03:05] Startup"
assertEquals(line, LogRedactor.redact(line))
@@ -36,7 +36,7 @@ class StoreGameArtTest {
}
@Test fun anArtChoiceOnAStoreGameIsKeptShownAndResetsWithoutTouchingItsTitle() {
for ((store, id, title) in listOf(Triple(Store.GOG, "1207658924", "Heroes III"), Triple(Store.EPIC, "abc", "Celeste"), Triple(Store.AMAZON, "amzn1.x", "Yakuza 0"))) {
for ((store, id, title) in listOf(Triple(Store.GOG, "1207658924", "Heroes III"), Triple(Store.EPIC, "abc", "Celeste"), Triple(Store.AMAZON, "amzn1.x", "Yakuza 0"), Triple(Store.XBOX, "9NBLGGH4X1", "Forza Horizon"), Triple(Store.ITCH, "12345", "Night in the Woods"))) {
val folder = install(store, id, title)
val image = File(tmp.root, "$id.png").apply { writeBytes(ByteArray(9) { 1 }) }
val option = AddedGameArt.Option(AddedGameArt.FILE, image.path, image.path)
@@ -5,6 +5,14 @@ import org.junit.Assert.*
import org.junit.Test
class GlassesRenderingTest {
@Test fun modelTwoDRatesLimitChoicesAndSavedRatesFallBackToAnOfferedOne() {
val rokid = GlassesState(displayId = 2, width = 1920, height = 1080, hz = 60f, rates2d = listOf(60, 120))
assertEquals(listOf(60, 120), GlassesRendering.refreshRates(GlassesSettings(), rokid))
assertEquals(60, GlassesRendering.outputHz(GlassesSettings(refreshHz = 90), rokid))
assertEquals(120, GlassesRendering.outputHz(GlassesSettings(refreshHz = 120), rokid))
assertEquals(listOf(60, 90, 120), GlassesRendering.refreshRates(GlassesSettings(), rokid.copy(rates2d = listOf(60, 90, 120))))
}
private val ultra = GlassesState(
model = "VITURE Luma Ultra", connected = true, controllable = true,
displayId = 2, width = 1920, height = 1200,
@@ -209,6 +209,14 @@ class GlassesUsbTest {
assertEquals(null, Glasses.deviceModel(device(0x043e, 0x1234, "XREAL 1S")))
}
@Test fun rokidMaxRoutesThroughItsOwnModelAndSharedVendorIdNeedsTheName() {
val max = Glasses.deviceModel(device(0x162f, 0x04d2, "Rokid Max"))
assertTrue(max is RokidModel)
assertEquals("Rokid Max", max?.name)
assertEquals(null, Glasses.deviceModel(device(0x162f, 0x04d2, "Generic HID")))
assertTrue(Glasses.isGlassesDisplayName("Rokid Max"))
}
private fun device(pid: Int, vid: Int = VitureProtocol.VENDOR_ID, name: String = "VITURE device"): UsbDevice = ReflectionHelpers.callConstructor(
UsbDevice::class.java,
from(String::class.java, "/dev/bus/usb/$pid"),
@@ -0,0 +1,94 @@
package com.droiddeck.launcher.glasses
import com.droiddeck.launcher.gpu.HeadPose
import org.junit.Assert.*
import org.junit.Test
import java.nio.ByteBuffer
import java.nio.ByteOrder
class RokidProtocolTest {
private fun hex(s: String) = s.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
private fun matrix(q: FloatArray) = HeadPose.fromGlasses(q[0], q[1], q[2], q[3])
@Test fun identityRequiresRokidProductString() {
assertEquals("Rokid Max", RokidModel.model(0x04d2, 0x162f, "Rokid Max")?.name)
assertEquals("Rokid Air", RokidModel.model(0x04d2, 0x162f, "Rokid Air")?.name)
assertNull(RokidModel.model(0x04d2, 0x162f, "USB Keyboard"))
assertNull(RokidModel.model(0x04d2, 0x162f, null))
assertNull(RokidModel.model(0x04d2, 0x1234, "Rokid Max"))
assertTrue(RokidModel.isDisplay("Rokid Max"))
}
@Test fun maxModesFollowRefreshAndStereoResolution() {
val max = RokidModel.model(0x04d2, 0x162f, "Rokid Max")!!
assertEquals(RokidModel.MODE_2D_60, max.mode(60, false, null))
assertEquals(RokidModel.MODE_2D_120, max.mode(120, false, null))
assertEquals(RokidModel.MODE_2D_60, max.mode(90, false, null))
assertEquals(listOf(60, 120), max.rates2d)
assertEquals(RokidModel.MODE_SBS_1200_60, max.mode(60, true, null))
assertEquals(RokidModel.MODE_SBS_1200_90, max.mode(90, true, null))
assertEquals(RokidModel.MODE_SBS_1080_60, max.mode(90, true, GlassesResolution(1920, 1080)))
assertTrue(max.sbs90)
assertFalse(max.hasSunblock)
}
@Test fun airStaysOnSixtyHertzModes() {
val air = RokidModel.model(0x04d2, 0x162f, "Rokid Air")!!
assertEquals(RokidModel.MODE_2D_60, air.mode(120, false, null))
assertEquals(RokidModel.MODE_SBS_1080_60, air.mode(90, true, null))
assertFalse(air.sbs90)
assertEquals(listOf(60), air.rates2d)
}
@Test fun brightnessStepsRoundTripTheDevicePercent() {
assertEquals(8, RokidModel.brightnessStep(80))
assertEquals(10, RokidModel.brightnessStep(100))
assertEquals(3, RokidModel.brightnessStep(32))
assertEquals(0, RokidModel.brightnessStep(0))
assertEquals(30, RokidModel.brightnessRaw(3))
assertEquals(100, RokidModel.brightnessRaw(12))
}
@Test fun capturedMaxCombinedReportParsesAccelGyroAndBrightness() {
val packet = hex("11d09b3e3700000000bb9eb03f9147f0c06e86c340306a43bc9c227b3ad3e6aebb000055c29a99abc1cdccfac10000000000000000000000000000503c000000")
val sample = RokidProtocol.Parser().parse(packet)!!
assertEquals(0x373e9bd0L, sample.timeNs)
assertEquals(1.380f, sample.accel.x, 0.001f)
assertEquals(-7.509f, sample.accel.y, 0.001f)
assertEquals(6.110f, sample.accel.z, 0.001f)
assertEquals(-0.0119f, sample.gyro.x, 0.0001f)
assertEquals(80, sample.brightness)
assertNull(RokidProtocol.Parser().parse(packet.copyOf(32)))
}
@Test fun airSeparateReportsPairOnSharedTimestamp() {
fun report(type: Int, time: Long, v: Vec3) = ByteBuffer.allocate(64).order(ByteOrder.LITTLE_ENDIAN).apply {
put(0, 4); put(1, type.toByte()); putLong(9, time)
putFloat(21, v.x); putFloat(25, v.y); putFloat(29, v.z)
}.array()
val parser = RokidProtocol.Parser()
assertNull(parser.parse(report(1, 500, Vec3(0f, 9.81f, 0f))))
val sample = parser.parse(report(2, 500, Vec3(0.1f, 0f, 0f)))!!
assertEquals(500_000L, sample.timeNs)
assertEquals(9.81f, sample.accel.y, 0f)
assertEquals(0.1f, sample.gyro.x, 0f)
assertNull(sample.brightness)
assertNull(parser.parse(report(2, 600, Vec3(0f, 0f, 0f))))
}
@Test fun capturedRestingGravityStartsUpright() {
val pose = ImuFusion().update(1_000_000, Vec3(0.01f, 9.58f, -2.20f), Vec3(0f, 0f, 0f))!!
assertTrue(kotlin.math.abs(pose[3]) > 0.97f)
}
@Test fun capturedLeftTurnSignLooksLeft() {
val fusion = ImuFusion()
val first = matrix(fusion.update(1_000_000, Vec3(0f, 9.81f, 0f), Vec3(0f, 0f, 0f))!!)
var last = FloatArray(4)
repeat(1000) {
last = fusion.update((it + 2) * 1_000_000L, Vec3(0f, 9.81f, 0f), Vec3(0f, (Math.PI / 6).toFloat(), 0f))!!
}
val view = HeadPose.relative(HeadPose.recenter(first), matrix(last))
assertArrayEquals(floatArrayOf(-0.5f, 0f, -0.8660254f), HeadPose.apply(view, floatArrayOf(0f, 0f, -1f)), 0.01f)
}
}
@@ -62,4 +62,25 @@ class AutoDriverTrialTest {
assertNull(AutoDriverTrial.rollbackDue(context))
assertEquals("banner@r5", AutoDriverTrial.current(context)?.release)
}
@Test fun displayDriverCrashesBeforeSessionStartStillCount() {
AutoDriverTrial.displayStarting(context, "new-display")
assertNull(AutoDriverTrial.rollbackDue(context))
AutoDriverTrial.displayStarting(context, "new-display")
assertEquals(2, AutoDriverTrial.rollbackDue(context)?.starts)
}
@Test fun aNormalStartIsCountedOnce() {
AutoDriverTrial.displayStarting(context, "new-display")
AutoDriverTrial.sessionStarting(context, "new-display", "new-linux")
assertEquals(1, AutoDriverTrial.current(context)?.starts)
AutoDriverTrial.displayStarting(context, "other-display")
assertEquals(1, AutoDriverTrial.current(context)?.starts)
}
@Test fun aTrialStartedBeforeDisplayCountingStillRollsBackOnTheNextCrash() {
AutoDriverTrial.sessionStarting(context, "new-display", "new-linux")
AutoDriverTrial.displayStarting(context, "new-display")
assertEquals(2, AutoDriverTrial.rollbackDue(context)?.starts)
}
}
@@ -0,0 +1,13 @@
package com.droiddeck.launcher.input
import org.junit.Assert.assertEquals
import org.junit.Test
class VrControllersTest {
@Test fun encodesTheKeysTheSteamVrDriverReads() {
assertEquals("emulate=index\nsticks=game\n", VrControllers.encode(VrControllers.Settings()))
assertEquals("emulate=touch\nsticks=hands\n",
VrControllers.encode(VrControllers.Settings(VrControllers.Emulate.TOUCH, sticksMoveHands = true)))
assertEquals(listOf("off", "index", "touch", "vive"), VrControllers.Emulate.entries.map { it.key })
}
}
@@ -118,4 +118,31 @@ class BwrapSpawnerPlanTest {
assertEquals("/app", plan.cwd)
assertEquals("org.example.Game", plan.env["FLATPAK_ID"])
}
@Test fun zypakLaunchesTheBrowserWithoutItsSandbox() {
val context = RuntimeEnvironment.getApplication()
val app = File(runtime, "app").apply { File(this, "bin").mkdirs() }
File(app, "bin/zypak-wrapper.sh").writeText("#!/usr/bin/bash\nexec zypak-helper host - \"\$@\"\n")
Files.createSymbolicLink(File(app, "bin/zypak-wrapper").toPath(), java.nio.file.Paths.get("/app/bin/zypak-wrapper.sh"))
val plan = BwrapSpawner.plan(context, request(
op("t" to "bind", "src" to "/runtime-files/app", "dest" to "/app", "ro" to true),
), dir)
val shim = plan.binds.single { it.guest == "/app/bin/zypak-wrapper.sh" }
assertTrue(shim.host.startsWith(dir.path))
assertTrue(File(shim.host).readText().contains("exec \"\$program\" --no-sandbox \"\$@\""))
assertFalse(plan.binds.any { it.guest == "/app/bin/zypak-wrapper" })
assertTrue(File(app, "bin/zypak-wrapper.sh").readText().contains("zypak-helper"))
}
@Test fun appsWithoutZypakKeepTheirFiles() {
val context = RuntimeEnvironment.getApplication()
File(runtime, "app/bin").mkdirs()
val plan = BwrapSpawner.plan(context, request(
op("t" to "bind", "src" to "/runtime-files/app", "dest" to "/app", "ro" to true),
), dir)
assertFalse(plan.binds.any { it.guest.startsWith("/app/bin/") })
assertFalse(File(dir, "zypak-wrapper").exists())
}
}
@@ -0,0 +1,32 @@
package com.droiddeck.launcher.runtime
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class DeckyChannelTest {
private fun release(tag: String, prerelease: Boolean) =
DeckyManager.Release(tag, prerelease, "PluginLoader-arm64", "https://example.invalid/$tag", null, null, 1, 183)
@Test fun stableSkipsPrereleasesAndPrereleaseTakesTheNewestTag() {
val pre = release("v3.4.0-pre1", true)
val stable = release("v3.3.0", false)
val channels = DeckyManager.ReleaseChannels(listOf(stable), listOf(pre), listOf(pre, stable))
assertEquals("v3.3.0", DeckyManager.latest(channels, DeckyManager.BRANCH_STABLE)?.tag)
assertEquals("v3.4.0-pre1", DeckyManager.latest(channels, DeckyManager.BRANCH_PRERELEASE)?.tag)
}
@Test fun prereleaseFollowsAStableThatShippedAfterTheLastPrerelease() {
val stable = release("v3.3.0", false)
val pre = release("v3.3.0-pre1", true)
val channels = DeckyManager.ReleaseChannels(listOf(stable), listOf(pre), listOf(stable, pre))
assertEquals("v3.3.0", DeckyManager.latest(channels, DeckyManager.BRANCH_PRERELEASE)?.tag)
}
@Test fun stableHasNothingWhenOnlyPrereleasesExist() {
val pre = release("v3.4.0-pre1", true)
assertNull(DeckyManager.latest(DeckyManager.ReleaseChannels(emptyList(), listOf(pre), listOf(pre)), DeckyManager.BRANCH_STABLE))
}
}
@@ -0,0 +1,122 @@
package com.droiddeck.launcher.runtime
import android.content.ContextWrapper
import com.droiddeck.launcher.BuildConfig
import java.io.File
import java.nio.file.Files
import java.nio.file.Paths
import java.util.zip.GZIPInputStream
import org.junit.After
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
@RunWith(RobolectricTestRunner::class)
class DesktopRemovalTest {
private val dir = Files.createTempDirectory("desktop-removal").toFile()
private val context = object : ContextWrapper(RuntimeEnvironment.getApplication()) {
override fun getFilesDir() = File(dir, "files").apply { mkdirs() }
override fun getCacheDir() = File(dir, "cache").apply { mkdirs() }
}
private val root = LinuxRuntime.rootDir(context).apply { mkdirs() }
private val marker = File(root, ".droiddeck-pkg-${DesktopCatalog.DESKTOP_ID}")
private val journal = File(root, marker.name + ".installing")
private val pending = File(root, DesktopRemoval.PENDING)
private val listener = LinuxRuntimeInstaller.ProgressListener { _, _ -> }
@After fun cleanup() { dir.deleteRecursively() }
@Test fun removesTheDesktopWhileKeepingRuntimeAppsGamesAndSettings() {
val desktop = desktopFiles()
marker.writeText(BuildConfig.DESKTOP_KDE_TAG)
val keep = listOf("root/.local/share/Steam/steamapps/common/game/data", "root/.config/kdeglobals",
"opt/appimages/custom.AppImage", "usr/lib/shared.so", "usr/share/plasma/custom")
.map { file(it, "keep") }
assertTrue(DesktopCatalog.desktopPresent(context))
assertNull(DesktopCatalog.removeDesktop(context, listener))
assertFalse(Files.exists(desktop.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS))
keep.forEach { assertEquals("keep", it.readText()) }
assertFalse(DesktopCatalog.desktopPresent(context))
assertFalse(DesktopCatalog.desktopInstalled(context))
}
@Test fun interruptedInstallCanBeRemovedWithoutBeingResumedAtTheNextLaunch() {
desktopFiles()
val entry = DesktopCatalog.desktopEntry(context)
journal.writeText(DesktopCatalog.entryJson(entry).toString())
val download = File(context.cacheDir, "pkg-${entry.id}-${entry.sha256.take(12)}.download").apply { writeText("download") }
val resume = File(download.path + ".resume.properties").apply { writeText("resume") }
val unrelated = file(".droiddeck-pkg-emulators.installing", DesktopCatalog.entryJson(DesktopCatalog.Entry(
"emulators", "Emulators", 1, "1", "tar", "https://example.invalid/emulators", "a".repeat(64), 1L, "", "", "",
)).toString())
assertTrue(DesktopCatalog.desktopPresent(context))
assertNotNull(DesktopCatalog.removeDesktop(context) { _, _ -> error("interrupted") })
assertTrue(pending.exists())
assertTrue(journal.exists())
assertTrue(DesktopCatalog.desktopPresent(context))
assertNull(DesktopCatalog.removeDesktop(context, listener))
assertFalse(journal.exists())
assertFalse(pending.exists())
assertFalse(download.exists())
assertFalse(resume.exists())
assertFalse(DesktopCatalog.desktopPresent(context))
assertEquals(listOf("emulators"), DesktopCatalog.interrupted(context).map { it.id })
assertTrue(unrelated.exists())
}
@Test fun refusesUnknownDesktopVersionsAndMissingRuntimeOwnershipBeforeDeletingAnything() {
val desktop = desktopFiles()
marker.writeText("future-desktop")
assertNotNull(DesktopCatalog.removeDesktop(context, listener))
assertEquals("future-desktop", marker.readText())
marker.writeText(BuildConfig.DESKTOP_KDE_TAG)
journal.writeText(DesktopCatalog.entryJson(DesktopCatalog.desktopEntry(context)).put("version", "future-desktop").toString())
assertNotNull(DesktopCatalog.removeDesktop(context, listener))
assertTrue(journal.exists())
journal.delete()
File(root, "var/lib/pacman/local/base-1/files").delete()
assertNotNull(DesktopCatalog.removeDesktop(context, listener))
assertEquals(BuildConfig.DESKTOP_KDE_TAG, marker.readText())
assertFalse(pending.exists())
assertTrue(Files.isSymbolicLink(desktop.toPath()))
}
@Test fun failedDownloadCleanupKeepsTheInstallRecordSoRemovalCanRetry() {
val entry = DesktopCatalog.desktopEntry(context)
val download = File(context.cacheDir, "pkg-${entry.id}-${entry.sha256.take(12)}.download")
for (blocked in listOf(download, File(download.path + ".resume.properties"))) {
desktopFiles()
journal.writeText(DesktopCatalog.entryJson(entry).toString())
blocked.mkdirs()
val blocker = File(blocked, "blocker").apply { writeText("fixture") }
assertNotNull(DesktopCatalog.removeDesktop(context, listener))
assertTrue(journal.exists())
assertTrue(pending.exists())
assertTrue(blocker.delete())
assertNull(DesktopCatalog.removeDesktop(context, listener))
assertFalse(blocked.exists())
assertFalse(journal.exists())
assertFalse(pending.exists())
}
}
private fun file(path: String, text: String) = File(root, path).apply { parentFile!!.mkdirs(); writeText(text) }
private fun desktopFiles(): File {
file("var/lib/pacman/local/base-1/files", "%FILES%\nusr/lib/shared.so\n")
val entry = GZIPInputStream(context.assets.open("desktop-removal/kde-remove.tsv.gzip")).bufferedReader().use { reader ->
reader.lineSequence().map(DesktopFileRemoval.Entry::parse).first { it.kind == "L" && it.path.startsWith("usr/") }
}
return File(root, entry.path).apply {
parentFile!!.mkdirs()
Files.createSymbolicLink(toPath(), Paths.get(entry.identity))
}
}
}
@@ -0,0 +1,73 @@
package com.droiddeck.launcher.session
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 ComponentsNightlyCatalogTest {
@Test
fun nightlyFilesGoToTheirComponentList() {
val n = ComponentsManager.DD_NIGHTLY
assertEquals("dxvk", ComponentsManager.assetComp(n, "DD-dxvk-3.1.1+153-nightly.wcp"))
assertEquals("dxvk", ComponentsManager.assetComp(n, "DD-dxvk-arm64ec-3.1.1+153-nightly.wcp"))
assertEquals("dxvk", ComponentsManager.assetComp(n, "DD-dxvk-gplasync-3.1.1+153-nightly.wcp"))
assertEquals("vkd3d", ComponentsManager.assetComp(n, "DD-vkd3d-proton-arm64ec-3.0.1+455-nightly.wcp"))
assertEquals("fex", ComponentsManager.assetComp(n, "DD-FEXCore-2610+58-nightly.wcp"))
assertNull(ComponentsManager.assetComp(n, "state.json"))
assertNull(ComponentsManager.assetComp(n, "something-else.wcp"))
assertEquals("dxvk", ComponentsManager.assetComp("Dxvk-gplasync-Linux", "dxvk-gplasync-3.1.1-1-linux.wcp"))
assertNull(ComponentsManager.assetComp("Unknown-Release", "dxvk-3.1.1-linux.wcp"))
}
@Test
fun nightliesListBelowTheStablePackages() {
fun item(file: String, release: String) = ComponentsManager.CatalogItem(file, "dxvk", release, "", 0, "")
val sorted = listOf(
item("DD-dxvk-3.1.1+153-nightly.wcp", ComponentsManager.DD_NIGHTLY),
item("dxvk-2.7.1-linux.wcp", "Dxvk-Linux"),
item("dxvk-3.1.1-linux.wcp", "Dxvk-Linux"),
).sortedWith(ComponentsManager.CATALOG_ORDER).map { it.file }
assertEquals(listOf("dxvk-3.1.1-linux.wcp", "dxvk-2.7.1-linux.wcp", "DD-dxvk-3.1.1+153-nightly.wcp"), sorted)
}
@Test
fun nightliesPairWithTheStableOfTheSameFlavorAndVersion() {
val n = ComponentsManager.DD_NIGHTLY
fun item(file: String, comp: String, release: String) = ComponentsManager.CatalogItem(file, comp, release, "", 0, "")
val dxvk = item("dxvk-3.1.1-linux.wcp", "dxvk", "Dxvk-Linux")
val ec = item("dxvk-arm64ec-3.1.1-linux.wcp", "dxvk", "Dxvk-arm64ec-Linux")
val gpl = item("dxvk-gplasync-3.1.1-1-linux.wcp", "dxvk", "Dxvk-gplasync-Linux")
val fex = item("FEXCore-2610-linux.wcp", "fex", "FexCore-Linux")
val vk = item("vkd3d-proton-3.0.1-linux.wcp", "vkd3d", "Vkd3d-proton-Linux")
val others = listOf(
item("dxvk-low-latency-3.1.1-2-linux.wcp", "dxvk", "Dxvk-Linux"),
item("dxvk-3.1-linux.wcp", "dxvk", "Dxvk-Linux"),
item("dxvk-gplasync-3.1-1-linux.wcp", "dxvk", "Dxvk-gplasync-Linux"),
item("FEXCore-2610-d2rfix28-linux.wcp", "fex", "FexCore-Linux"),
)
val nDxvk = item("DD-dxvk-3.1.1+153-nightly.wcp", "dxvk", n)
val nEc = item("DD-dxvk-arm64ec-3.1.1+153-nightly.wcp", "dxvk", n)
val nGpl = item("DD-dxvk-gplasync-3.1.1+153-nightly.wcp", "dxvk", n)
val nFex = item("DD-FEXCore-2610+58-nightly.wcp", "fex", n)
val nVk = item("DD-vkd3d-proton-3.0.1+455-nightly.wcp", "vkd3d", n)
val nVkEc = item("DD-vkd3d-proton-arm64ec-3.0.1+455-nightly.wcp", "vkd3d", n)
val pairs = ComponentsManager.nightlyPairs(listOf(dxvk, ec, gpl, fex, vk) + others + listOf(nDxvk, nEc, nGpl, nFex, nVk, nVkEc))
assertEquals(mapOf(dxvk to nDxvk, ec to nEc, gpl to nGpl, fex to nFex, vk to nVk), pairs)
// Two nightlies for one stable build: the newer one wins.
val nDxvkNewer = item("DD-dxvk-3.1.1+154-nightly.wcp", "dxvk", n)
assertEquals(mapOf(dxvk to nDxvkNewer), ComponentsManager.nightlyPairs(listOf(dxvk, nDxvkNewer, nDxvk)))
assertEquals(mapOf(dxvk to nDxvkNewer), ComponentsManager.nightlyPairs(listOf(dxvk, nDxvk, nDxvkNewer)))
// A nightly of a version with no stable build pairs with nothing.
assertEquals(emptyMap<Any, Any>(), ComponentsManager.nightlyPairs(listOf(item("dxvk-3.1-linux.wcp", "dxvk", "Dxvk-Linux"), nDxvk)))
}
@Test
fun downloadsOnlyFromTheTwoRepositories() {
assertTrue(ComponentsManager.allowedDownload("https://github.com/The412Banner/Nightlies/releases/download/Dxvk-Linux/dxvk-3.1.1-linux.wcp"))
assertTrue(ComponentsManager.allowedDownload("https://github.com/Droid-Deck/DroidDeck-Components/releases/download/linux-nightly/DD-FEXCore-2610+58-nightly.wcp"))
assertFalse(ComponentsManager.allowedDownload("https://github.com/someone/else/releases/download/x/y.wcp"))
assertFalse(ComponentsManager.allowedDownload("https://github.com/Droid-Deck/DroidDeck-Components-evil/releases/download/x/y.wcp"))
}
}
@@ -20,7 +20,7 @@ class OrientationTest {
}
@Test fun landscapeChoicesPersistGloballyAndCanRestoreAutomaticRotation() {
assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, SessionPrefs.orientation(context))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, SessionPrefs.orientation(context))
for (value in listOf(
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE,
@@ -34,7 +34,7 @@ class OrientationTest {
@Test fun invalidStoredOrientationFallsBackAndInvalidChoicePreservesTheSavedValue() {
val prefs = context.getSharedPreferences("session", Context.MODE_PRIVATE)
prefs.edit().putInt("orientation", ActivityInfo.SCREEN_ORIENTATION_PORTRAIT).commit()
assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, SessionPrefs.orientation(context))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, SessionPrefs.orientation(context))
SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE)
assertThrows(IllegalArgumentException::class.java) {
SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
@@ -32,6 +32,11 @@ class SettingsResetTest {
SessionPrefs.setHdr(app, SessionService.MODE_DESKTOP, true)
SessionPrefs.setResolutionChoice(app, SessionService.MODE_STEAM, "1280x800")
SessionPrefs.setGuestHostname(app, "MyDeck")
SessionPrefs.setHudShowFps(app, false)
SessionPrefs.setHudShowBattery(app, false)
SessionPrefs.setHudShowGraph(app, false)
SessionPrefs.setHudColor(app, "amber")
SessionPrefs.setHudOpacity(app, 40)
ControllerPrefs.setOpacity(app, 40)
AppUiPrefs.setScale(app, 150)
FrameGen.set(app, FrameGen.Mode(FrameGen.ENGINE_DDFG, 3))
@@ -45,6 +50,13 @@ class SettingsResetTest {
assertFalse(SessionPrefs.hdr(app, SessionService.MODE_DESKTOP))
assertFalse(SessionPrefs.resolutionChosen(app, SessionService.MODE_STEAM))
assertEquals(SessionPrefs.DEFAULT_GUEST_HOSTNAME, SessionPrefs.guestHostname(app))
assertTrue(SessionPrefs.hudShowFps(app))
assertTrue(SessionPrefs.hudShowBattery(app))
assertTrue(SessionPrefs.hudShowGraph(app))
assertEquals(SessionPrefs.HUD_COLOR_MINT, SessionPrefs.hudColor(app))
assertEquals(SessionPrefs.HUD_OPACITY_DEFAULT, SessionPrefs.hudOpacity(app))
assertEquals("32.4°C", PerfHud.batteryCelsius(324))
assertNull(PerfHud.batteryCelsius(0))
assertEquals(100, ControllerPrefs.read(app).opacity)
assertEquals(AppUiPrefs.DEFAULT_SCALE, AppUiPrefs.scale(app))
assertEquals(FrameGen.Mode.OFF.engine, FrameGen.engine(app))
@@ -57,6 +57,25 @@ class SteamDownloadMonitorTest {
}
}
@Test fun readsBoundCardLibrariesFromTheirHostPath() {
val root = Files.createTempDirectory("droiddeck-steam-download-").toFile()
try {
val card = File(root, "card").apply { mkdirs() }
File(root, "root/.local/share/Steam/steamapps").apply { mkdirs() }
.resolve("libraryfolders.vdf")
.writeText("\"libraryfolders\" { \"1\" { \"path\" \"/mnt/droiddeck-sd\" } }")
val manifest = manifest(card, "44", downloaded = 10, total = 100, flags = 6)
val monitor = SteamDownloadMonitor()
val mounts = mapOf("/mnt/droiddeck-sd" to card)
assertFalse(monitor.poll(root, now = 1_000L, mounts = mounts))
manifest.writeText(appManifest(downloaded = 20, total = 100, flags = 6))
assertTrue(monitor.poll(root, now = 3_000L, mounts = mounts))
} finally {
root.deleteRecursively()
}
}
@Test fun followsSteamContentActivityWhenManifestProgressIsNotFlushed() {
val root = Files.createTempDirectory("droiddeck-steam-download-").toFile()
try {
@@ -0,0 +1,29 @@
package com.droiddeck.launcher.stores
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class DetailCatalogItemTest {
private fun item(store: Store, id: String, title: String) = CatalogItem(store, id, title, imageUrl = null)
private val shelves = StoreShelves(trending = listOf(item(Store.XBOX, "9SHELF000001", "Shelf game")))
@Test fun aSearchOnlyResultKeepsItsMetadataOnTheDetailPage() {
val found = listOf(item(Store.XBOX, "9SEARCH00001", "Echo Weaver"))
assertEquals("Echo Weaver", detailCatalogItem(Store.XBOX, "9SEARCH00001", emptyList(), found, shelves)?.title)
}
@Test fun theLibraryWinsOverSearchAndShelvesForTheSameProduct() {
val library = listOf(item(Store.XBOX, "9SEARCH00001", "Echo Weaver").copy(owned = true, sizeBytes = 42))
val found = listOf(item(Store.XBOX, "9SEARCH00001", "Echo Weaver").copy(owned = false))
val resolved = detailCatalogItem(Store.XBOX, "9SEARCH00001", library, found, shelves)!!
assertEquals(true, resolved.owned)
assertEquals(42L, resolved.sizeBytes)
}
@Test fun shelvesRemainAFallbackAndTheItemStaysInItsStore() {
assertEquals("Shelf game", detailCatalogItem(Store.XBOX, "9SHELF000001", emptyList(), emptyList(), shelves)?.title)
assertNull(detailCatalogItem(Store.GOG, "9SEARCH00001", emptyList(), listOf(item(Store.XBOX, "9SEARCH00001", "Echo Weaver")), shelves))
assertNull(detailCatalogItem(Store.XBOX, "9UNKNOWN0001", emptyList(), emptyList(), shelves))
}
}
@@ -0,0 +1,29 @@
package com.droiddeck.launcher.stores
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Test
/** Filling a grid one card at a time: what is on screen stays put, what is new lands where its title belongs. */
class StoreCatalogPatchTest {
private fun item(id: String, title: String, image: String? = null) = CatalogItem(Store.GOG, id, title, imageUrl = image, owned = true)
@Test fun onlyTheCardItWasGivenIsReplaced() {
val alpha = item("1", "Alpha")
val beta = item("2", "Beta")
val next = patchItems(listOf(alpha, beta), listOf(item("2", "Beta", "wide.jpg")))
assertEquals(2, next.size)
assertSame(alpha, next[0])
assertEquals("wide.jpg", next[1].imageUrl)
}
@Test fun aCardTheGridDoesNotHaveYetIsAddedInTitleOrder() {
val next = patchItems(listOf(item("1", "Alpha"), item("3", "Gamma")), listOf(item("2", "Beta")))
assertEquals(listOf("Alpha", "Beta", "Gamma"), next.map { it.title })
}
@Test fun anEmptyGridTakesTheCardAsItComes() {
val next = patchItems(null, listOf(item("2", "Beta")))
assertEquals(listOf("Beta"), next.map { it.title })
}
}
@@ -0,0 +1,93 @@
package com.droiddeck.launcher.stores
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 org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.util.Locale
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33], application = android.app.Application::class)
class StoreLanguageTest {
@Test
fun polishDepotIsKeptWhenPolishIsChosen() {
assertTrue(StoreLanguage.depotAccepted(arrayOf("pl-PL"), "pl"))
assertTrue(StoreLanguage.depotAccepted(arrayOf("pl"), "pl-PL"))
assertTrue(StoreLanguage.depotAccepted(arrayOf("polish"), "pl-PL"))
assertTrue(StoreLanguage.depotAccepted(arrayOf("*"), "pl"))
assertTrue(StoreLanguage.depotAccepted(emptyArray(), "pl"))
assertTrue(StoreLanguage.depotAccepted(null, "pl"))
}
@Test
fun englishDepotIsSkippedWhenPolishIsChosen() {
assertFalse(StoreLanguage.depotAccepted(arrayOf("en-US"), "pl-PL"))
assertFalse(StoreLanguage.depotAccepted(arrayOf("en", "english"), "pl"))
assertTrue(StoreLanguage.depotAccepted(arrayOf("en-US"), "en"))
assertTrue(StoreLanguage.depotAccepted(arrayOf("en"), "en-US"))
assertTrue(StoreLanguage.depotAccepted(arrayOf("english"), "en-US"))
}
@Test
fun pickPrefersSystemLanguageThenEnglish() {
val available = listOf("en-US", "de-DE", "pl-PL")
assertEquals("pl-PL", StoreLanguage.pick(available, "pl"))
assertEquals("en-US", StoreLanguage.pick(available, "ja"))
assertEquals("de-DE", StoreLanguage.pick(listOf("de-DE", "fr-FR"), "de"))
assertEquals("wanted", StoreLanguage.pick(emptyList(), "wanted"))
}
@Test
fun pickPrefersExactCodeBeforeTheBaseLanguage() {
val both = listOf("pl", "pl-PL", "en-US")
assertEquals("pl-PL", StoreLanguage.pick(both, "pl-PL"))
assertEquals("pl", StoreLanguage.pick(both, "pl"))
assertEquals("pl-PL", StoreLanguage.pick(listOf("en-US", "pl-PL"), "pl"))
}
@Test
fun resolvedDepotKeepsSharedFilesAndOnlyTheChosenVariant() {
assertTrue(StoreLanguage.depotMatchesResolved(arrayOf("*"), "pl-PL"))
assertTrue(StoreLanguage.depotMatchesResolved(emptyArray(), "pl-PL"))
assertTrue(StoreLanguage.depotMatchesResolved(null, "pl-PL"))
assertTrue(StoreLanguage.depotMatchesResolved(arrayOf("pl-PL", "*"), "pl-PL"))
assertTrue(StoreLanguage.depotMatchesResolved(arrayOf("pl-PL"), "pl-PL"))
assertFalse(StoreLanguage.depotMatchesResolved(arrayOf("pl"), "pl-PL"))
assertFalse(StoreLanguage.depotMatchesResolved(arrayOf("en-US"), "pl-PL"))
assertTrue(StoreLanguage.depotMatchesResolved(arrayOf("polish"), "pl"))
}
@Test
fun tagForFollowsLocale() {
assertEquals("pl-PL", StoreLanguage.tagFor(Locale("pl", "PL")))
assertEquals("pl", StoreLanguage.tagFor(Locale("pl")))
assertEquals("pt-BR", StoreLanguage.tagFor(Locale("pt", "BR")))
assertEquals("es-419", StoreLanguage.tagFor(Locale("es", "MX")))
assertEquals("zh-Hans", StoreLanguage.tagFor(Locale.SIMPLIFIED_CHINESE))
assertEquals("zh-Hant", StoreLanguage.tagFor(Locale.TRADITIONAL_CHINESE))
}
@Test
fun codesFromDepotsSkipStarAndDuplicates() {
val depots = JSONArray()
.put(JSONObject().put("languages", JSONArray().put("*").put("en-US")))
.put(JSONObject().put("languages", JSONArray().put("pl-PL").put("en-US")))
.put(JSONObject().put("languages", JSONArray()))
assertEquals(listOf("en-US", "pl-PL"), StoreLanguage.codesFromDepots(depots))
assertTrue(StoreLanguage.codesFromDepots(null).isEmpty())
}
@Test
fun selectableStoresAreGogAndEpic() {
assertTrue(StoreLanguage.selectable(Store.GOG))
assertTrue(StoreLanguage.selectable(Store.EPIC))
assertFalse(StoreLanguage.selectable(Store.AMAZON))
assertFalse(StoreLanguage.selectable(Store.XBOX))
assertFalse(StoreLanguage.selectable(Store.ITCH))
}
}
@@ -0,0 +1,79 @@
package com.droiddeck.launcher.stores.gog
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/** The account listing: everything the tab needs to draw a library before a product is asked about. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class GogListingTest {
@Test
fun aPageCarriesTheGamesTheAppCanInstall() {
val page = GogLibrary.parseListing(PAGE)!!
assertEquals(2, page.totalPages)
assertEquals(listOf("Shadowrun Returns", "Witcher 3: Wild Hunt, The"), page.games.map { it.title })
val shadowrun = page.games[0]
assertEquals("1207660413", shadowrun.gameId)
assertEquals("https://images-2.gog.com/6c35ecb988f57725cc0f385acf860241082da16eda9fab66115f4da883dae3d1_glx_vertical_cover.webp", shadowrun.verticalCover)
assertEquals("", shadowrun.imageUrl)
assertEquals("Role-playing", shadowrun.category)
assertEquals("2013-07-25", shadowrun.releaseDate)
assertEquals("", shadowrun.description)
}
@Test
fun moviesOtherPlatformsAndGalaxysOwnEntryAreLeftOut() {
assertEquals(listOf("1207660413", "1207664663"), GogLibrary.parseListing(PAGE)!!.games.map { it.gameId })
}
@Test
fun aResponseThatIsNotAListingIsNull() {
assertNull(GogLibrary.parseListing("""{"error":"unauthorized"}"""))
assertNull(GogLibrary.parseListing("not json"))
}
private companion object {
val PAGE = """
{
"sortBy": "title",
"page": 1,
"totalProducts": 6,
"totalPages": 2,
"productsPerPage": 100,
"products": [
{
"id": 1207660413,
"title": "Shadowrun Returns",
"image": "//images-2.gog.com/6c35ecb988f57725cc0f385acf860241082da16eda9fab66115f4da883dae3d1",
"worksOn": { "Windows": true, "Mac": true, "Linux": true },
"category": "Role-playing",
"isComingSoon": false,
"isMovie": false,
"isGame": true,
"slug": "shadowrun_returns",
"dlcCount": 0,
"releaseDate": { "date": "2013-07-25 00:00:00.000000", "timezone_type": 3, "timezone": "Europe/Nicosia" }
},
{
"id": 1207664663,
"title": " Witcher 3: Wild Hunt, The ",
"image": "//images-3.gog.com/60c724a052275a049d857d53957dc38e9347742f52372bb956d992b43efa8fb5",
"worksOn": { "Windows": true, "Mac": false, "Linux": false },
"category": "Role-playing",
"isMovie": false,
"isGame": true,
"releaseDate": { "date": "2015-05-19 02:00:00.000000", "timezone_type": 3, "timezone": "Europe/Nicosia" }
},
{ "id": 1582718039, "title": "A Movie", "image": "//images-1.gog.com/movie", "isMovie": true, "isGame": false },
{ "id": 1430747193, "title": "Mac Only", "image": "//images-1.gog.com/mac", "worksOn": { "Windows": false, "Mac": true }, "isMovie": false, "isGame": true },
{ "id": 1801418160, "title": "GOG Galaxy", "image": "//images-1.gog.com/galaxy", "worksOn": { "Windows": true }, "isMovie": false, "isGame": true },
{ "id": 1401362385, "title": "Soundtrack", "image": "//images-1.gog.com/ost", "worksOn": { "Windows": true }, "isMovie": false, "isGame": false }
]
}
""".trimIndent()
}
}
@@ -19,7 +19,7 @@ class XboxCatalogTest {
private fun envelope(vararg rows: JSONObject) = JSONObject().put("schema", 1).put("account", "test@example.test")
.put("market", "US").put("checkedAt", now.toString()).put("entitlements", JSONArray(rows.toList()))
private fun access(vararg rows: JSONObject) = XboxCatalog.access(envelope(*rows), "test@example.test", "US", now)
private fun membership() = JSONObject().put("productId", plan).put("status", "Active").put("endDate", "2099-01-01T00:00:00Z")
private fun membership(id: String = plan) = JSONObject().put("productId", id).put("status", "Active").put("endDate", "2099-01-01T00:00:00Z")
private fun withMembership(json: JSONObject, vararg plans: JSONObject) = json.put("subscriptions", JSONArray(plans.toList()))
@Test fun separateMembershipRestoresSubscriptionChildrenWithoutInventingOwnership() {
@@ -83,6 +83,16 @@ class XboxCatalogTest {
assertEquals(mapOf(game to "gamepass", parent to "gamepass"), access(row(game, parent), row(parent, plan), row(plan)))
}
@Test fun onlyPcPlansGrantSubscriptionAccess() {
for (pc in listOf("CFQ7TTC0KGQ8", "CFQ7TTC0KHS0", "CFQ7TTC0P85B", "CFQ7TTC0K5DJ", "CFQ7TTC10QFD")) {
assertEquals(mapOf(game to "gamepass"), access(row(game, pc), row(pc)))
}
val console = "CFQ7TTC0K6L8"
assertTrue(access(row(game, console), row(console)).isEmpty())
assertTrue(XboxCatalog.access(withMembership(envelope(row(game, console)), membership(console)),
"test@example.test", "US", now).isEmpty())
}
@Test fun backendRfc3339OffsetsAndNanosecondsAreAccepted() {
val checked = "2026-10-19T19:02:38.173609086+00:00"
val response = envelope(row(game).put("endDate", "2099-01-01T01:00:00.000000001+01:00"))
@@ -120,6 +130,29 @@ class XboxCatalogTest {
assertFalse(card.owned); assertTrue(card.subscription)
}
@Test fun pcSubscriptionAffirmationsOfferAnInstallWithoutClaimingOwnership() {
fun offer(vararg affirmations: String) = JSONObject().put("ProductId", game).put("ProductType", "Game")
.put("LocalizedProperties", JSONArray().put(JSONObject().put("ProductTitle", "A Pass game")
.put("EligibilityProperties", JSONObject().put("Affirmations", JSONArray(affirmations.map {
JSONObject().put("AffirmationProductId", it)
})))))
.put("DisplaySkuAvailabilities", JSONArray().put(JSONObject().put("Sku", JSONObject().put("Properties", JSONObject()
.put("Packages", JSONArray().put(JSONObject().put("PackageFormat", "MSIXVC").put("PlatformDependencies",
JSONArray().put(JSONObject().put("PlatformName", "Windows.Desktop")))))))))
val pc = XboxCatalog.product(offer("CFQ7TTC0KGQ8"), emptyMap())!!
assertEquals("PC Game Pass", pc.includedWith)
assertFalse(pc.accessible); assertTrue(pc.installable)
assertEquals("Game Pass Ultimate", XboxCatalog.product(offer("CFQ7TTC0KHS0"), emptyMap())!!.includedWith)
assertEquals("Xbox Game Pass Premium", XboxCatalog.product(offer("CFQ7TTC0P85B"), emptyMap())!!.includedWith)
assertEquals("Xbox Game Pass Essential", XboxCatalog.product(offer("CFQ7TTC0K5DJ"), emptyMap())!!.includedWith)
assertEquals("Xbox Game Pass (Starter Edition)", XboxCatalog.product(offer("CFQ7TTC10QFD"), emptyMap())!!.includedWith)
val console = XboxCatalog.product(offer("CFQ7TTC0K6L8"), emptyMap())!!
assertEquals("", console.includedWith); assertFalse(console.installable)
assertFalse(XboxCatalog.product(offer(), emptyMap())!!.installable)
}
@Test fun consoleAndUwpOffersAreFilteredOut() {
fun product(platform: String, format: String) = JSONObject().put("ProductId", game).put("ProductType", "Game")
.put("LocalizedProperties", JSONArray().put(JSONObject().put("ProductTitle", "A PC game")))
@@ -0,0 +1,33 @@
package com.droiddeck.launcher.ui
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.CloudSaves
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class CloudMessageTest {
private val ctx get() = RuntimeEnvironment.getApplication()
private fun msg(result: String, files: Int, conflicts: Int, reason: String) =
cloudMessage(ctx, CloudSaves.Result(result, files, 0L, reason, conflicts))
@Test fun aSkippedSyncNeverReadsAsZeroFilesDone() {
assertEquals(ctx.getString(R.string.cloud_signed_out), msg("skipped", 0, 0, "not-signed-in"))
assertEquals(ctx.getString(R.string.cloud_none), msg("skipped", 0, 0, "no-cloud-saves"))
for (reason in listOf("off", "no-baseline", "nothing-local", "store-unreachable", "unresolved")) {
assertEquals(reason, ctx.getString(R.string.cloud_not_synced), msg("skipped", 0, 0, reason))
}
assertEquals(ctx.getString(R.string.cloud_not_synced), msg("failed", 0, 0, "SocketTimeoutException"))
}
@Test fun okResultsSayWhatHappened() {
assertEquals(ctx.getString(R.string.cloud_up_to_date), msg("ok", 0, 0, "up-to-date"))
assertEquals(ctx.getString(R.string.cloud_done, 3), msg("ok", 3, 0, "uploaded"))
assertEquals(ctx.getString(R.string.cloud_conflict_files, 2), msg("ok", 1, 2, "conflict"))
}
}
@@ -4,11 +4,20 @@ import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.InputMode
import androidx.compose.ui.input.InputModeManager
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.platform.LocalInputModeManager
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.assertIsFocused
import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.assertIsNotEnabled
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performKeyInput
import androidx.compose.ui.test.pressKey
import androidx.compose.ui.test.requestFocus
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.ComponentsManager
import org.junit.Assert.assertEquals
@@ -19,10 +28,12 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@OptIn(ExperimentalTestApi::class, androidx.compose.ui.ExperimentalComposeUiApi::class)
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28])
class ComponentDownloadsDrawerTest {
@get:Rule val compose = createRobolectricComposeRule()
private lateinit var inputMode: InputModeManager
private val dxvk = item("dxvk-2.4.1-linux.wcp", "dxvk")
private val stored = item("dxvk-2.3-linux.wcp", "dxvk")
@@ -42,6 +53,40 @@ class ComponentDownloadsDrawerTest {
compose.onNodeWithText("45%").assertExists()
}
@Test fun pairedNightlyRidesOnTheStableRowBehindTheSwitch() {
val stable = ComponentsManager.CatalogItem("dxvk-3.1.1-linux.wcp", "dxvk", "Dxvk-Linux", "https://github.com/example/s", 100, "sha256:test")
val nightly = ComponentsManager.CatalogItem("DD-dxvk-3.1.1+153-nightly.wcp", "dxvk", ComponentsManager.DD_NIGHTLY, "https://github.com/example/n", 100, "sha256:test")
val requested = mutableListOf<ComponentsManager.CatalogItem>()
show(catalog = listOf(stable, nightly), onDownload = requested::add)
compose.onNodeWithTag("cmp-download-dxvk").performClick()
compose.onNodeWithText("dxvk-3.1.1-linux").assertExists()
compose.onNodeWithText("DD-dxvk-3.1.1+153-nightly").assertDoesNotExist()
compose.onNodeWithText(RuntimeEnvironment.getApplication().getString(R.string.comp_channel_nightly)).performClick()
compose.onNodeWithText("dxvk-3.1.1-linux").assertDoesNotExist()
compose.onNodeWithText("DD-dxvk-3.1.1+153-nightly").performClick()
assertEquals(listOf(nightly), requested)
}
@Test fun controllerPicksNightlyOnItsTabThenDownloadsItFromTheRow() {
val stable = ComponentsManager.CatalogItem("dxvk-3.1.1-linux.wcp", "dxvk", "Dxvk-Linux", "https://github.com/example/s", 100, "sha256:test")
val nightly = ComponentsManager.CatalogItem("DD-dxvk-3.1.1+153-nightly.wcp", "dxvk", ComponentsManager.DD_NIGHTLY, "https://github.com/example/n", 100, "sha256:test")
val requested = mutableListOf<ComponentsManager.CatalogItem>()
show(catalog = listOf(stable, nightly), onDownload = requested::add)
compose.onNodeWithTag("cmp-download-dxvk").performClick()
compose.runOnIdle { inputMode.requestInputMode(InputMode.Keyboard) }
compose.onNodeWithText("dxvk-3.1.1-linux").requestFocus().assertIsFocused()
compose.onNodeWithText("dxvk-3.1.1-linux").performKeyInput { pressKey(Key.DirectionRight) }
val nightlyTab = RuntimeEnvironment.getApplication().getString(R.string.comp_channel_nightly)
compose.onNodeWithText(RuntimeEnvironment.getApplication().getString(R.string.comp_channel_stable)).assertIsFocused()
.performKeyInput { pressKey(Key.DirectionRight) }
compose.onNodeWithText(nightlyTab).assertIsFocused().performKeyInput { pressKey(Key.ButtonA) }
compose.onNodeWithText("DD-dxvk-3.1.1+153-nightly").assertExists()
assertEquals(emptyList<ComponentsManager.CatalogItem>(), requested)
compose.onNodeWithText(nightlyTab).performKeyInput { pressKey(Key.DirectionLeft); pressKey(Key.DirectionLeft) }
compose.onNodeWithText("DD-dxvk-3.1.1+153-nightly").assertIsFocused().performKeyInput { pressKey(Key.ButtonA) }
assertEquals(listOf(nightly), requested)
}
@Test fun emptyCatalogOffersRefreshAndDisablesVersionChoicesWhileChecking() {
var refreshes = 0
show(catalog = emptyList(), checking = false, onRefresh = { refreshes++ })
@@ -64,6 +109,7 @@ class ComponentDownloadsDrawerTest {
onDownload: (ComponentsManager.CatalogItem) -> Unit = {},
) {
compose.setContent {
inputMode = LocalInputModeManager.current
DroidDeckTheme {
Column(Modifier.verticalScroll(rememberScrollState())) {
ComponentDownloadsDrawerGroup(
@@ -0,0 +1,101 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertIsNotEnabled
import androidx.compose.ui.test.onAllNodesWithText
import androidx.compose.ui.test.onLast
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], qualifiers = "w1200dp-h752dp-land", application = android.app.Application::class)
class DesktopUninstallTest {
@get:Rule val compose = createRobolectricComposeRule()
private var removals = 0
private var runtimeBlocked by mutableStateOf(false)
@After fun closeConfirmation() { Steps.drop() }
@Test fun uninstallIsAvailableOnTheDesktopPageAndRequiresConfirmation() {
show()
compose.onNodeWithText("Open desktop").assertIsDisplayed()
compose.onNodeWithText("Uninstall").assertIsDisplayed().performClick()
settle()
assertEquals(0, removals)
compose.onNodeWithText("Uninstall the desktop?").assertIsDisplayed()
compose.onAllNodesWithText("Uninstall").onLast().performClick()
assertEquals(1, removals)
}
@Test fun uninstallIsDisabledWhileRuntimeChangesAreBlocked() {
show(blocked = true)
compose.onNodeWithText("Uninstall").assertIsNotEnabled()
}
@Test fun aPartialDesktopStillOffersUninstall() {
show(installed = false)
compose.onNodeWithText("Uninstall").assertIsDisplayed()
}
@Test fun anUninstalledDesktopNoLongerOffersUninstall() {
show(installed = false, present = false)
compose.onNodeWithText("Uninstall").assertDoesNotExist()
}
@Test fun startingRuntimeWorkWhileConfirmingDisablesUninstall() {
show()
compose.onNodeWithText("Uninstall").performClick()
settle()
compose.runOnIdle { runtimeBlocked = true }
settle()
compose.onAllNodesWithText("Uninstall").onLast().assertIsNotEnabled()
assertEquals(0, removals)
}
private fun settle() = compose.mainClock.advanceTimeBy(2_000)
private fun show(installed: Boolean = true, blocked: Boolean = false, present: Boolean = true) {
runtimeBlocked = blocked
compose.mainClock.autoAdvance = false
compose.setContent {
DroidDeckTheme {
CompositionLocalProvider(LocalFrontFocus provides FrontFocus()) {
FocusGlideHost {
Box(Modifier.fillMaxSize()) {
DesktopPage(FrontEndState(
installed = "r9", ready = true, available = null, busy = false, stage = "", percent = -1,
desktopInstalled = installed, desktopPresent = present, runtimeActionsBlocked = runtimeBlocked,
offlineAccount = null, offline = false, frameGenLabel = "", romsDir = null, logsEnabled = false,
steamGames = emptyList(), emulators = emptyList(), running = null,
), FrontEndActions(
onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {},
onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {},
onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {},
onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {},
onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> },
onSetPhantomProcessLimit = { _, _ -> }, onRemoveDesktop = { removals++ },
), Modifier.fillMaxSize(), onSelect = {})
StepsLayer(Offset.Zero)
}
}
}
}
}
settle()
}
}
@@ -0,0 +1,42 @@
package com.droiddeck.launcher.ui
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.material3.Text
import androidx.compose.runtime.remember
import androidx.compose.ui.test.assertHasNoClickAction
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28])
class DialogSemanticsTest {
@get:Rule val compose = createRobolectricComposeRule()
@Test fun dialogTextNodesStaySeparateAndNonClickableInMergedSemanticsTree() {
var closed = 0
compose.setContent {
DroidDeckTheme {
val shown = remember { MutableTransitionState(true) }
AppDialog(shown = shown, close = { closed++ }, label = "testDialog", wide = false) {
Text("Dialog Title")
Text("Dialog Hint")
Text("Body Copy")
}
}
}
compose.onNodeWithText("Dialog Title").assertExists().assertHasNoClickAction()
compose.onNodeWithText("Dialog Hint").assertExists().assertHasNoClickAction()
compose.onNodeWithText("Body Copy").assertExists().assertHasNoClickAction()
compose.onNodeWithText("Dialog Title").performClick()
compose.onNodeWithText("Body Copy").performClick()
compose.waitForIdle()
assertEquals(0, closed)
}
}
@@ -70,7 +70,6 @@ class GestureLocalizationTest {
fun arabicPickerSearchPreservesBindingsAndMirrorsFooter() {
assertEquals(View.LAYOUT_DIRECTION_RTL, context.resources.configuration.layoutDirection)
compose.setContent { DroidDeckTheme { TouchGestureDialog(null, {}, {}) } }
compose.onNodeWithText("إعدادات إيماءات اللمس").assertIsDisplayed()
val save = compose.onNodeWithTag("gesture-save").fetchSemanticsNode().boundsInRoot
val cancel = compose.onNodeWithText(context.getString(R.string.gesture_cancel)).fetchSemanticsNode().boundsInRoot
assertTrue("Save $save and Cancel $cancel should follow the right-to-left layout", save.left < cancel.left)
@@ -1,61 +0,0 @@
package com.droiddeck.launcher.ui
import android.app.Application
import android.content.Intent
import android.hardware.display.DisplayManager
import android.view.Display
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import org.junit.After
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.LooperMode
@RunWith(RobolectricTestRunner::class)
@Config(application = Application::class, manifest = Config.NONE, sdk = [28, 33])
@LooperMode(LooperMode.Mode.PAUSED)
class SecondScreenActivityTest {
@Before fun setUp() {
SessionState.running = true
SessionState.stopRequested = false
}
@After fun tearDown() {
SessionState.running = false
SessionState.stopRequested = false
}
@Test fun removingControlsTaskDoesNotStopTheRunningSession() {
val service = Robolectric.buildService(SessionService::class.java).get()
service.onTaskRemoved(Intent(service, SecondScreenActivity::class.java))
assertTrue(SessionState.running)
assertFalse(SessionState.stopRequested)
}
@Test fun activityRestoredWithoutItsSessionOwnerFinishes() {
val activity = Robolectric.buildActivity(SecondScreenActivity::class.java).create().get()
assertTrue(activity.isFinishing)
assertTrue(SessionState.running)
}
@Test fun closingBeforeTheSecondaryActivityStartsRejectsTheLateLaunch() {
val session = Robolectric.buildActivity(SessionActivity::class.java).get()
val display = session.getSystemService(DisplayManager::class.java).getDisplay(Display.DEFAULT_DISPLAY)
val controls = SecondScreenWindow(session, display, { _, _, _, _ -> }, { _, _ -> }, {}, {}, {}, {})
controls.show()
val intent = shadowOf(session).nextStartedActivity
controls.closeControls()
val activity = Robolectric.buildActivity(SecondScreenActivity::class.java, intent).create().get()
assertTrue(activity.isFinishing)
assertFalse(controls.isShowing)
assertTrue(SessionState.running)
}
}
@@ -0,0 +1,35 @@
package com.droiddeck.launcher.update
import android.content.pm.PackageInfo
import android.content.pm.Signature
import java.security.MessageDigest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
class SelfInstallerSignerTest {
private val cert = byteArrayOf(1, 2, 3, 4, 5)
private val expected = MessageDigest.getInstance("SHA-256").digest(cert).joinToString("") { "%02x".format(it) }
@Suppress("DEPRECATION")
private fun archive() = PackageInfo().apply { signatures = arrayOf(Signature(cert)) }
@Config(sdk = [28, 29])
@Test fun androidNineAndTenUseTheSignaturesWhenSigningInfoIsMissing() {
assertEquals(listOf(expected), SelfInstaller.archiveSignerDigests(archive()))
}
@Config(sdk = [26])
@Test fun androidEightIsCheckedToo() {
assertEquals(listOf(expected), SelfInstaller.archiveSignerDigests(archive()))
}
@Config(sdk = [33])
@Test fun anArchiveWithNoCertificatesHasNoDigests() {
assertTrue(SelfInstaller.archiveSignerDigests(PackageInfo()).isEmpty())
}
}