Merge upstream main into File Manager Test branch

Resolve File Manager conflicts with the upstream copy cancellation and symlink changes. Preserve the original navigation, confirmation, and localization commits. Pass cancellation into move cleanup and retain the upstream empty-file copy behavior.
This commit is contained in:
K11MCH1 committed 2026-10-22 21:15:46 +09:00
commit 7432a4f1a3
225 files changed
+7391 -1222

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))
}
}
@@ -0,0 +1,172 @@
package com.droiddeck.launcher.files
import java.io.File
import java.util.concurrent.CancellationException
import java.nio.file.Files
import java.nio.file.attribute.PosixFilePermissions
import org.junit.Assume.assumeTrue
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class FileOpsCopyTest {
@get:Rule val tmp = TemporaryFolder()
@Test fun cancellingAnOverwritePreservesTheDestinationAndSource() {
val src = tmp.newFile("source").apply { writeText("replacement") }
val dst = tmp.newFile("dest").apply { writeText("original user data") }
assertThrows(CancellationException::class.java) {
FileOps.copyWithProgress(src, dst, { _, _ -> throw CancellationException("cancel") })
}
assertTrue("original destination was removed", dst.exists())
assertEquals("original user data", dst.readText())
assertEquals("replacement", src.readText())
assertEquals(setOf("source", "dest"), tmp.root.list()!!.toSet())
}
@Test fun cancellingANewCopyLeavesNoPartialDestination() {
val src = tmp.newFile("source").apply { writeText("replacement") }
val dst = File(tmp.root, "dest")
assertThrows(CancellationException::class.java) {
FileOps.copyWithProgress(src, dst, { _, _ -> throw CancellationException("cancel") })
}
assertFalse(dst.exists())
assertEquals("replacement", src.readText())
assertEquals(setOf("source"), tmp.root.list()!!.toSet())
}
@Test fun cancellingAMoveFallbackPreservesBothFiles() {
val src = tmp.newFile("source").apply { writeText("replacement") }
val dst = tmp.newFile("dest").apply { writeText("original user data") }
assertThrows(CancellationException::class.java) {
FileOps.moveWithProgress(src, dst, { _, _ -> throw CancellationException("cancel") })
}
assertTrue("original destination was removed", dst.exists())
assertEquals("original user data", dst.readText())
assertEquals("replacement", src.readText())
}
@Test fun cancellingStopsATreeOfEmptyFiles() {
val src = tmp.newFolder("source")
for (name in listOf("a", "b", "c")) File(src, name).createNewFile()
val dst = File(tmp.root, "dest")
var checks = 0
assertThrows(CancellationException::class.java) {
FileOps.copyWithProgress(src, dst, null) { checks++ > 1 }
}
assertEquals(1, dst.list()!!.size)
assertEquals(3, src.list()!!.size)
}
@Test fun cancellingStopsATreeOfEmptyFolders() {
val src = tmp.newFolder("source")
for (name in listOf("a", "b", "c")) File(src, name).mkdir()
val dst = File(tmp.root, "dest")
var checks = 0
assertThrows(CancellationException::class.java) {
FileOps.copyWithProgress(src, dst, null) { checks++ > 1 }
}
assertEquals(1, dst.list()!!.size)
}
@Test fun aCompletedCopyReplacesTheDestination() {
val src = tmp.newFile("source").apply { writeText("replacement") }
val dst = tmp.newFile("dest").apply { writeText("original user data") }
assertTrue(FileOps.copyWithProgress(src, dst, null))
assertEquals("replacement", dst.readText())
assertEquals("replacement", src.readText())
assertEquals(setOf("source", "dest"), tmp.root.list()!!.toSet())
}
@Test fun aLongDestinationNameDoesNotOverflowTheStagingName() {
val src = tmp.newFile("source").apply { writeText("replacement") }
val dst = File(tmp.root, "d".repeat(240))
assertTrue(FileOps.copyWithProgress(src, dst, null))
assertEquals("replacement", dst.readText())
}
@Test fun anOverwritePreservesTheTargetsExecutablePermissions() {
assumeTrue(Files.getFileStore(tmp.root.toPath()).supportsFileAttributeView("posix"))
val src = tmp.newFile("source").apply { writeText("replacement") }
val dst = tmp.newFile("dest").apply { writeText("original") }
val permissions = PosixFilePermissions.fromString("rwxr-x---")
Files.setPosixFilePermissions(dst.toPath(), permissions)
assertTrue(FileOps.copyWithProgress(src, dst, null))
assertEquals("replacement", dst.readText())
assertEquals(permissions, Files.getPosixFilePermissions(dst.toPath()))
}
@Test fun aMoveFallbackPreservesTheTargetsExecutablePermissions() {
assumeTrue(Files.getFileStore(tmp.root.toPath()).supportsFileAttributeView("posix"))
val src = tmp.newFile("source").apply { writeText("replacement") }
val dst = tmp.newFile("dest").apply { writeText("original") }
val permissions = PosixFilePermissions.fromString("rwxr-x---")
Files.setPosixFilePermissions(dst.toPath(), permissions)
assertTrue(FileOps.moveWithProgress(src, dst, null))
assertFalse(src.exists())
assertEquals("replacement", dst.readText())
assertEquals(permissions, Files.getPosixFilePermissions(dst.toPath()))
}
@Test fun anOverwriteStillRefusesAReadOnlyDestination() {
assumeTrue(Files.getFileStore(tmp.root.toPath()).supportsFileAttributeView("posix"))
val src = tmp.newFile("source").apply { writeText("replacement") }
val dst = tmp.newFile("dest").apply { writeText("original") }
Files.setPosixFilePermissions(dst.toPath(), PosixFilePermissions.fromString("r--r--r--"))
try {
assertFalse(FileOps.copyWithProgress(src, dst, null))
assertEquals("original", dst.readText())
assertEquals("replacement", src.readText())
} finally {
dst.setWritable(true)
}
}
@Test fun anEmptyFileCanReplaceAnExistingFile() {
val src = tmp.newFile("source")
val dst = tmp.newFile("dest").apply { writeText("original user data") }
var callbacks = 0
assertTrue(FileOps.copyWithProgress(src, dst, { _, _ -> callbacks++ }))
assertEquals(0, callbacks)
assertEquals(0L, dst.length())
assertTrue(src.exists())
}
@Test fun aFailedPublicationPreservesTheDestinationAndCleansStaging() {
val src = tmp.newFile("source").apply { writeText("replacement") }
val dst = tmp.newFolder("dest")
File(dst, "keep").writeText("original user data")
assertFalse(FileOps.copyWithProgress(src, dst, null))
assertEquals("original user data", File(dst, "keep").readText())
assertEquals("replacement", src.readText())
assertEquals(setOf("source", "dest"), tmp.root.list()!!.toSet())
}
@Test fun aSuccessfulMoveFallbackDeletesTheSourceOnlyAfterCopying() {
val src = tmp.newFile("source").apply { writeText("replacement") }
val dst = tmp.newFile("dest").apply { writeText("original user data") }
assertTrue(FileOps.moveWithProgress(src, dst, null))
assertFalse(src.exists())
assertEquals("replacement", dst.readText())
assertEquals(setOf("dest"), tmp.root.list()!!.toSet())
}
@Test fun overwritingThroughASymlinkKeepsTheLinkAndUpdatesItsTarget() {
assumeTrue(Files.getFileStore(tmp.root.toPath()).supportsFileAttributeView("posix"))
val src = tmp.newFile("source").apply { writeText("replacement") }
val realTarget = tmp.newFile("real-target").apply { writeText("original user data") }
val link = File(tmp.root, "dest-link")
Files.createSymbolicLink(link.toPath(), realTarget.toPath())
assertTrue(FileOps.copyWithProgress(src, link, null))
assertTrue("destination symlink was replaced instead of written through", Files.isSymbolicLink(link.toPath()))
assertEquals("replacement", realTarget.readText())
}
}
@@ -0,0 +1,85 @@
package com.droiddeck.launcher.files
import java.io.File
import java.nio.file.Files
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Assume.assumeTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class FileOpsLinksTest {
@get:Rule val tmp = TemporaryFolder()
private fun link(at: File, target: String): Boolean =
runCatching { Files.createSymbolicLink(at.toPath(), File(target).toPath()) }.isSuccess
@Test fun aMovedFolderKeepsItsLinks() {
val src = tmp.newFolder("game")
File(src, "data.bin").writeText("x")
assumeTrue("symlinks unavailable here", link(File(src, "lib.so"), "data.bin"))
val dst = File(tmp.root, "other/game")
File(dst, "keep").mkdirs()
assertTrue(FileOps.moveWithProgress(src, dst, null))
assertFalse(src.exists())
assertTrue(Files.isSymbolicLink(File(dst, "lib.so").toPath()))
assertEquals("data.bin", Files.readSymbolicLink(File(dst, "lib.so").toPath()).toString())
}
@Test fun aCopiedLinkPointsWhereTheOriginalDoes() {
val src = tmp.newFolder("a")
assumeTrue("symlinks unavailable here", link(File(src, "l"), "/nowhere/target"))
val dst = File(tmp.root, "b")
assertTrue(FileOps.copyWithProgress(src, dst, null))
assertTrue(Files.isSymbolicLink(File(src, "l").toPath()))
assertTrue(Files.isSymbolicLink(File(dst, "l").toPath()))
}
@Test fun copyingALinkPreservesAnUnrelatedStagingName() {
val src = File(tmp.root, "source")
assumeTrue("symlinks unavailable here", link(src, "missing-target"))
val dst = File(tmp.root, "dest")
dst.writeText("old destination")
val sibling = File(tmp.root, ".dest.link-tmp")
sibling.writeText("unrelated user data")
assertTrue(FileOps.copyWithProgress(src, dst, null))
assertEquals("unrelated user data", sibling.readText())
assertEquals("missing-target", Files.readSymbolicLink(dst.toPath()).toString())
assertEquals(setOf("source", "dest", ".dest.link-tmp"), tmp.root.list()!!.toSet())
}
@Test fun anUnrelatedStagingDirectoryDoesNotPreventCopyingALink() {
val src = File(tmp.root, "source")
assumeTrue("symlinks unavailable here", link(src, "missing-target"))
val sibling = tmp.newFolder(".dest.link-tmp")
File(sibling, "keep").writeText("unrelated user data")
assertTrue(FileOps.copyWithProgress(src, File(tmp.root, "dest"), null))
assertEquals("unrelated user data", File(sibling, "keep").readText())
}
@Test fun aLongDestinationNameDoesNotOverflowTheStagingName() {
val src = File(tmp.root, "source")
assumeTrue("symlinks unavailable here", link(src, "missing-target"))
val dst = File(tmp.root, "d".repeat(240))
assertTrue(FileOps.copyWithProgress(src, dst, null))
assertEquals("missing-target", Files.readSymbolicLink(dst.toPath()).toString())
}
@Test fun aLinkThatCannotReplaceTheDestinationLeavesItAlone() {
val src = tmp.newFolder("c")
assumeTrue("symlinks unavailable here", link(File(src, "l"), "x"))
val dst = File(tmp.root, "d")
File(dst, "l").mkdirs()
File(dst, "l/keep.txt").writeText("kept")
assertFalse(FileOps.copyWithProgress(File(src, "l"), File(dst, "l"), null))
assertEquals("kept", File(dst, "l/keep.txt").readText())
assertFalse(File(dst, ".l.link-tmp").exists())
}
}
@@ -132,6 +132,23 @@ class GameFilesTest {
}
}
@Test fun longTitlesKeepTheirEndingAndStayApart() {
val folder = tmp.newFolder()
val first = game("32370", "STAR WARS™ Knights of the Old Republic™")
val second = game("208580", "STAR WARS™ Knights of the Old Republic™ II - The Sith Lords™")
assertEquals("STAR WARS™ Knights of the Old Republic™ II - The Sith Lords™.steam", GameFiles.filename(second))
GameFiles.sync(app, folder, listOf(first, second))
GameFiles.sync(app, folder, listOf(first, second))
assertEquals("32370", File(folder, "STAR WARS™ Knights of the Old Republic™.steam").readText())
assertEquals("208580", File(folder, "STAR WARS™ Knights of the Old Republic™ II - The Sith Lords™.steam").readText())
assertEquals(2, folder.listFiles()!!.count { it.extension == GameFiles.EXTENSION })
assertEquals("a".repeat(200) + ".steam", GameFiles.filename(game(name = "a".repeat(300))))
assertEquals("a".repeat(199) + ".steam", GameFiles.filename(game(name = "a".repeat(199) + " b")))
assertEquals("Game.steam", GameFiles.filename(game(name = " . ")))
assertEquals("Game.steam", GameFiles.filename(game(name = "Game . .")))
assertEquals("a".repeat(197) + ".steam", GameFiles.filename(game(name = "a".repeat(197) + " . b")))
}
@Test fun refusesSymlinksLeavingTheExportFolder() {
val folder = tmp.newFolder()
val outside = tmp.newFile()
@@ -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,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))
@@ -0,0 +1,72 @@
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 SteamClientSetupFailureTest {
private fun find(vararg lines: String) = SteamClientSetupFailure.find(lines.asSequence())
@Test fun aBlockedDownloadCarriesTheLastCurlError() {
val failure = find(
"== STEP 12:35:22 checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)",
"curl: (7) Failed to connect to client-update.steamstatic.com:443 after 3 ms: Could not connect to server",
"curl: (35) Recv failure: Connection reset by peer",
"droiddeck-steam-install: no Steam client CDN answered for steam_client_steamdeck_publicbeta_linuxarm64",
"== steam: the Steam client could not be set up (status 1)",
"[gamescope] [Info] launch: Primary child shut down!",
)!!
assertTrue(failure.download)
assertEquals("curl: (35) Recv failure: Connection reset by peer", failure.curlError)
}
@Test fun aFailureWithoutCurlErrorIsNotCalledADownloadProblem() {
val failure = find(
"== STEP 12:35:22 checking the Steam client (a first run downloads it)",
"== STEP 12:35:30 downloading Steam: bins_linuxarm64_linuxarm64 (2/17)",
"error: cannot create /root/.local/share/Steam/ubuntu12_32/steam-runtime.tar.xz",
"== steam: the Steam client could not be set up (status 50)",
)!!
assertFalse(failure.download)
assertNull(failure.curlError)
}
@Test fun aReadyClientIsNoFailure() {
assertNull(find(
"== STEP 12:35:22 checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)",
"curl: (35) Recv failure: Connection reset by peer",
"== STEP 12:35:40 Steam client ready",
))
}
@Test fun onlyTheLatestCheckCounts() {
assertNull(find(
"== STEP 10:00:00 checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)",
"curl: (6) Could not resolve host: client-update.steamstatic.com",
"== steam: the Steam client could not be set up (status 1)",
"== STEP 10:05:00 checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)",
"== STEP 10:06:00 Steam client ready",
))
val failure = find(
"== STEP 10:00:00 checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)",
"curl: (6) Could not resolve host: client-update.steamstatic.com",
"== steam: the Steam client could not be set up (status 1)",
"== STEP 10:05:00 checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)",
"== steam: the Steam client could not be set up (status 9)",
)!!
assertNull(failure.curlError)
}
@Test fun anArm64SyncErrorIsNotBlamedForTheX64Client() {
val failure = find(
"== STEP 10:00:00 checking the Steam client's arm64 parts (first run downloads them, ~1-2 min)",
"curl: (6) Could not resolve host: client-update.steamstatic.com",
"== STEP 10:00:05 could not update the arm64 client's parts; the x86-64 client keeps its own web helper",
"== STEP 10:00:05 checking the x86-64 Steam client (FEX, experimental; the first run downloads ~2 GB)",
"== steam: the Steam client could not be set up (status 3)",
)!!
assertNull(failure.curlError)
}
}
@@ -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,27 @@
package com.droiddeck.launcher.stores
import android.os.Build
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class StoreLoginUserAgentTest {
@Test fun theDevicesWebViewAgentIsSentAsChrome() {
assertEquals(
"Mozilla/5.0 (Linux; Android 16; NP06J) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.122 Mobile Safari/537.36",
StoreLoginActivity.chromeUserAgent(
"Mozilla/5.0 (Linux; Android 16; NP06J Build/BP2A.250605.031.A3; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/141.0.7390.122 Mobile Safari/537.36",
),
)
}
@Test fun noWebViewAgentFallsBackToChromeWithoutAnotherDevicesModel() {
for (agent in listOf(null, "", "Dalvik/2.1.0 (Linux; U; Android 16)")) {
val ua = StoreLoginActivity.chromeUserAgent(agent)
assertTrue(ua, "Chrome/" in ua)
assertFalse(ua, "SM-S918B" in ua)
assertTrue(ua, "Android ${Build.VERSION.RELEASE}; ${Build.MODEL})" in ua)
}
}
}
@@ -0,0 +1,18 @@
package com.droiddeck.launcher.stores
import com.droiddeck.launcher.stores.gog.GogAuth
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class WebCookiesTest {
@Test fun gogLoginCookiesAreExpiredOnTheLoginHostAndTheDomain() {
val lines = WebCookies.expired("galaxy-login-s=a; galaxy-login-tsa=b; galaxy-login-al=c", GogAuth.COOKIE_DOMAIN, listOf("/"), "login.gog.com")
assertEquals(9, lines.size)
assertTrue(lines.contains("galaxy-login-al=; Max-Age=0; Path=/; Secure"))
assertTrue(lines.contains("galaxy-login-al=; Max-Age=0; Path=/; Secure; Domain=.gog.com"))
assertTrue(lines.contains("galaxy-login-al=; Max-Age=0; Path=/; Secure; Domain=login.gog.com"))
assertTrue(lines.none { it.startsWith("galaxy-login-al=c") })
assertEquals(emptyList<String>(), WebCookies.expired(null, GogAuth.COOKIE_DOMAIN, listOf("/"), "login.gog.com"))
}
}
@@ -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(
@@ -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())
}
}