Merge main into feat/viture-xr

This commit is contained in:
maxjivi05 committed 2026-10-13 23:35:29 -04:00
commit 697c75337f
903 files changed
+70115 -47401

No files matched your search

@@ -7,6 +7,7 @@ import android.util.Base64
import androidx.compose.ui.semantics.SemanticsConfiguration
import androidx.compose.ui.semantics.SemanticsProperties
import androidx.compose.ui.text.AnnotatedString
import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONObject
import org.junit.Assert.*
@@ -68,6 +69,13 @@ class AgentSecurityTest {
assertFalse(AgentAccess.commandsAllowed(context))
}
@Test fun theRefusalNamesTheSetupTabThatHoldsTheToggle() {
val refusal = refused("AGENT_COMMANDS_DISABLED") { AgentAccess.requireCommands(context) }
val tab = context.getString(R.string.setup_tab_diagnostics)
val toggle = context.getString(R.string.setup_agent_commands)
assertTrue(refusal.message, refusal.message!!.contains("Setup > $tab > $toggle"))
}
@Test fun runCannotBypassTheToggle() {
refused("AGENT_COMMANDS_DISABLED") { AgentAccess.requireStart(context, JSONObject().put("mode", "run")) }
AgentAccess.requireStart(context, JSONObject().put("mode", "steam"))
@@ -0,0 +1,57 @@
package com.droiddeck.launcher.core
import java.io.File
import java.util.Locale
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class AppLanguageTest {
private fun tag(languageTag: String) = AppLanguage.supportedTag(Locale.forLanguageTag(languageTag))
private val folders = mapOf(
"id" to "in", "ms" to "ms", "cs" to "cs", "da" to "da", "de" to "de", "es" to "es",
"es-419" to "b+es+419", "fr" to "fr", "it" to "it", "hu" to "hu", "nl" to "nl", "nb" to "nb",
"pl" to "pl", "pt-BR" to "pt", "pt-PT" to "pt-rPT", "ro" to "ro", "fi" to "fi", "sv" to "sv",
"vi" to "vi", "tr" to "tr", "el" to "el", "bg" to "bg", "ru" to "ru", "uk" to "uk", "ar" to "ar",
"hi" to "hi", "th" to "th", "ja" to "ja", "ko" to "ko", "zh-CN" to "zh-rCN", "zh-TW" to "zh-rTW",
"zh-HK" to "zh-rHK",
)
@Test fun everyLanguageReadsAsItself() {
AppLanguage.supported.forEach { assertEquals(it, tag(it)) }
}
@Test fun everyLanguageHasItsOwnName() {
val names = AppLanguage.supported.map(AppLanguage::nativeName)
assertEquals(names.size, names.toSet().size)
AppLanguage.supported.forEach { assertTrue(it, AppLanguage.nativeName(it) != it) }
}
@Test fun systemLocalesFindTheirLanguage() {
assertEquals("es-419", tag("es-MX"))
assertEquals("es-419", tag("es-US"))
assertEquals("es", tag("es-ES"))
assertEquals("pt-BR", tag("pt-BR"))
assertEquals("pt-BR", tag("pt"))
assertEquals("pt-PT", tag("pt-PT"))
assertEquals("pt-PT", tag("pt-AO"))
assertEquals("id", tag("in-ID"))
assertEquals("id", tag("id-ID"))
assertEquals("de", tag("de-AT"))
assertEquals("ar", tag("ar-EG"))
assertEquals("zh-HK", tag("zh-MO"))
assertNull(tag("sw-KE"))
assertNull(tag("nn-NO"))
}
@Test fun everyLanguageShipsStringsAndIsOfferedToAndroid() {
assertEquals(AppLanguage.supported.toSet() - "en", folders.keys)
val res = File("src/main/res")
folders.values.forEach { assertTrue(it, File(res, "values-$it/strings.xml").isFile) }
val config = File(res, "xml/locales_config.xml").readText()
val offered = Regex("""android:name="([^"]+)"""").findAll(config).map { it.groupValues[1] }.toList()
assertEquals(AppLanguage.supported, offered)
}
}
@@ -88,7 +88,6 @@ class LogRedactorTest {
}
}
// The Steam UI's own login line (webhelper_js.txt), as the privacy scan found it.
@Test fun loginStateLineLosesAnEmailAccount() {
val line = "[2026-10-07 21:14:03] SteamUI: INFO: Login: OnLoginStateChange someone.masked@example.com 2 1 0 0"
val out = LogRedactor.redact(line)
@@ -13,7 +13,6 @@ class SecretScrubTest {
"0024:warn:seh:dispatch_exception code=c0000005 flags=0 addr=0000000140012345",
"0030:trace:seh:handle_syscall_fault code=80000003 flags=0",
"exception code=0xC0000005 at 0x140012345",
// An exception code stays one even on a line that also carries OAuth keys.
"client_id=abc code=c0000005",
)) assertEquals(line, share(line))
}
@@ -0,0 +1,37 @@
package com.droiddeck.launcher.core
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class ZramSupportTest {
@Test
fun kernelVersionsFromAndroidReleases() {
assertTrue(ZramSupport.kernelAtLeast("6.12.38-android16-5-g665eafb62659-ab14778838-4k", 5, 4))
assertTrue(ZramSupport.kernelAtLeast("5.4.0", 5, 4))
assertFalse(ZramSupport.kernelAtLeast("4.19.157-perf+", 5, 4))
assertFalse(ZramSupport.kernelAtLeast("", 5, 4))
}
@Test
fun underTwelveGbFromAdvertisedOrTotalMemory() {
val gb = 1_000_000_000L
val gib = 1L shl 30
assertTrue(ZramSupport.belowTwelveGb(8 * gb, 0))
assertTrue(ZramSupport.belowTwelveGb(8 * gib, 0))
assertFalse(ZramSupport.belowTwelveGb(12 * gb, 0))
assertFalse(ZramSupport.belowTwelveGb(12 * gib, 0))
assertTrue(ZramSupport.belowTwelveGb(0, 7_400_000L * 1024))
assertTrue(ZramSupport.belowTwelveGb(0, 9_300_000L * 1024))
assertFalse(ZramSupport.belowTwelveGb(0, 11_100_000L * 1024))
assertFalse(ZramSupport.belowTwelveGb(0, 15_600_380L * 1024))
}
@Test
fun swapTotalComesFromMeminfo() {
assertEquals(12582908L, ZramSupport.swapTotalKb(listOf("MemTotal: 15600380 kB", "SwapTotal: 12582908 kB")))
assertEquals(0L, ZramSupport.swapTotalKb(listOf("SwapTotal: 0 kB")))
assertEquals(0L, ZramSupport.swapTotalKb(emptyList()))
}
}
@@ -13,7 +13,6 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
/** The Games tab's +: one picked .exe becomes a game, once, wherever the session can see it. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class AddedExesTest {
@@ -54,7 +53,6 @@ class AddedExesTest {
assertEquals(Library.ADDED, game.source)
assertTrue(File(app.filesDir, "session/added-games.json").readText().contains("Celeste.exe"))
// The same exe again: the game it already is, no second entry.
val again = AddedGames.addExe(app, pick)
assertTrue(again is AddedGames.AddResult.Existing)
assertEquals(game.appId, (again as AddedGames.AddResult.Existing).game.appId)
@@ -83,7 +81,6 @@ class AddedExesTest {
val result = AddedGames.addExe(app, deep)
assertTrue(result is AddedGames.AddResult.Switched)
assertEquals(deep.path, AddedGames.scan(app).single().exe.path)
// The Games folder's game is an entry of its own (GamesFolderMigration); no second one.
assertEquals(listOf(File(games, "Example").path), AddedExes.list(app).map { it.folder })
}
@@ -20,7 +20,6 @@ import java.io.File
import java.security.SecureRandom
import javax.crypto.spec.SecretKeySpec
/** Where an added game's art comes from: its own Steam appid, a matching name, SteamGridDB's key. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class AddedGameArtLookupTest {
@@ -39,7 +38,6 @@ class AddedGameArtLookupTest {
val match = SteamMatch.resolve(app, dir.path, exe, "Palworld") { fail("searched"); null }
assertEquals(1623730, match.appId)
assertEquals(SteamMatch.Certainty.FILES, match.certainty)
// The same record for everyone who asks.
assertEquals(1623730, SteamMatch.get(app, dir.path)!!.appId)
}
@@ -68,7 +66,6 @@ class AddedGameArtLookupTest {
}
@Test fun aStoreResultIsTakenOnlyWhenItsNameMatches() {
// The first result is no longer taken for being first.
assertNull(AddedGameArt.pickStoreResult("My Obscure Game", listOf("10" to "Totally Different", "11" to "Another One")))
assertEquals("20", AddedGameArt.pickStoreResult("Hades", listOf("19" to "Hades II Soundtrack Bundle Extra", "20" to "Hades")))
assertEquals("30", AddedGameArt.pickStoreResult("Skyrim Special Edition Complete Edition", listOf("1" to "Unrelated", "30" to "Skyrim Special Edition")))
@@ -95,7 +92,6 @@ class AddedGameArtLookupTest {
assertEquals("build", SteamGridDb.pick("", "build"))
assertEquals("build", SteamGridDb.pick(" ", "build"))
assertEquals("", SteamGridDb.pick("", ""))
// This test build carries no key.
assertEquals("", SteamGridDb.builtInKey())
assertEquals("", SteamGridDb.key(app))
}
@@ -18,7 +18,6 @@ import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
/** "Add all games in this folder", the editor's writes to the shortcut listing, art choices. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class AddedGameEditsTest {
@@ -52,14 +51,11 @@ class AddedGameEditsTest {
val alpha = result.added.first { it.name == "Alpha" }
assertEquals("Alpha.exe", alpha.exe.name)
assertFalse(alpha.exeUncertain)
// Two lookalikes: the best guess, marked.
assertTrue(result.added.first { it.name == "Beta" }.exeUncertain)
// Entries, not a Games folder.
assertEquals(emptyList<String>(), SessionPrefs.addedGamesDirs(app))
assertEquals(3, AddedExes.list(app).size)
assertTrue(listing().map { it.getString("name") }.containsAll(listOf("Alpha", "Beta", "Celeste")))
// Again: nothing new, all three there already.
val again = AddedGames.addFolder(app, dir)
assertEquals(emptyList<String>(), again.added.map { it.name })
assertEquals(3, again.already)
@@ -84,7 +80,6 @@ class AddedGameEditsTest {
assertEquals(game.appId, entry.getLong("appid"))
assertEquals(game.appId, AddedGameEdits.game(app, folder)!!.appId)
// Back to automatic.
AddedGameEdits.setName(app, folder, "")
assertTrue(AddedGameEdits.setStartIn(app, folder, ""))
val auto = listing().single()
@@ -109,8 +104,6 @@ class AddedGameEditsTest {
assertEquals("/g/Game/data", SessionPrefs.addedGameStartIn(app, folder.path))
assertEquals("-safe", SessionPrefs.addedGameLaunch(app, folder.path))
// The user renames it in the app before Steam's shortcut is written again: the same Steam
// value is not taken a second time.
SessionPrefs.setAddedGameName(app, folder.path, "Mine")
AddedGames.adoptSteamEdits(app, folder, record)
assertEquals("Mine", SessionPrefs.addedGameName(app, folder.path))
@@ -13,7 +13,6 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
/** The .exe picker below a game folder (five levels, past installer folders, ranked) and the names it finds. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class AddedGamesCandidatesTest {
@@ -65,7 +64,6 @@ class AddedGamesCandidatesTest {
val game = tmp.newFolder("Huge")
for (i in 0 until GameExePicker.WALK_BUDGET + 50) File(game, "data/d%04d".format(i)).mkdirs()
exe(game, "zzz/Late.exe")
// data/ alone fills the budget before zzz/ is listed.
assertEquals(emptyList<String>(), names(game))
val small = tmp.newFolder("Small")
exe(small, "x/y/Found.exe")
@@ -136,7 +134,6 @@ class AddedGamesCandidatesTest {
game.setLastModified(game.lastModified() + 10_000)
val after = AddedGames.scan(app).single()
assertEquals("The Witcher 3 - Wild Hunt", after.name)
// Already added under the folder name: the shortcut keeps its id.
assertEquals(before.appId, after.appId)
}
@@ -12,7 +12,6 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
/** Removing an added game stops listing it and keeps it off after a rescan, until it is added again; nothing on disk goes. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class AddedGamesRemoveTest {
@@ -47,7 +46,6 @@ class AddedGamesRemoveTest {
SessionPrefs.setAddedGameRemoved(app, File(games, "Beta").path, true)
assertEquals(listOf("Alpha", "Gamma"), AddedGames.scan(app).map { it.name })
// A rescan does not bring it back.
assertEquals(listOf("Alpha", "Gamma"), AddedGames.scan(app).map { it.name })
SessionPrefs.setAddedGameRemoved(app, File(games, "Beta").path, false)
@@ -66,7 +64,6 @@ class AddedGamesRemoveTest {
assertTrue(!listing.contains("\"Beta\""))
assertTrue(File(beta, "Beta.exe").isFile)
// Added again with the +: it comes back.
assertTrue(AddedGames.addExe(app, File(beta, "Beta.exe")) is AddedGames.AddResult.Switched)
assertEquals(emptyList<String>(), SessionPrefs.removedAddedGames(app))
assertTrue(File(app.filesDir, "session/added-games.json").readText().contains("\"Beta\""))
@@ -13,7 +13,6 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
/** A store install is one more folder the scan finds, named and aimed by its sidecar. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class AddedGamesStoreScanTest {
@@ -38,7 +37,6 @@ class AddedGamesStoreScanTest {
assertEquals("HOMM3.exe", game.exe.name)
assertEquals(Store.GOG.id, game.source)
assertEquals("1207658924", game.storeId)
// Inside the runtime's tree the folder needs no bind: its guest path is its path from the tree's root.
assertEquals("/root/Games/Stores/GOG/Heroes of Might and Magic 3 Complete/HOMM3.exe", game.guestExe)
assertEquals("/root/Games/Stores/GOG/Heroes of Might and Magic 3 Complete", game.guestDir)
}
@@ -19,7 +19,6 @@ class AddedGamesTest {
"\"AppState\"\n{\n\t\"appid\"\t\t\"17410\"\n\t\"installdir\"\t\t\"Mirrors Edge\"\n}\n",
)
assertEquals(setOf("monster_hunter_stories_3_twisted_reflection", "mirrors edge"), AddedGames.steamInstallDirs(common))
// Loose game folders at the library root are never Steam's.
assertEquals(emptySet<String>(), AddedGames.steamInstallDirs(library))
}
}
@@ -30,7 +30,6 @@ class GameFileSyncTest {
assertEquals("8400", File(folder, "Geometry Wars.steam").readText())
assertEquals(folder.path, GameFileSync.folder(context))
assertEquals(1, folder.listFiles()!!.count { it.extension == GameFiles.EXTENSION })
// An unavailable source must leave the existing export intact.
val unavailable = File(steamapps.parentFile, "steamapps-unavailable")
assertTrue(steamapps.renameTo(unavailable))
assertThrows(IllegalStateException::class.java) { GameFileSync.syncConfigured(context) }
@@ -38,11 +37,9 @@ class GameFileSyncTest {
assertTrue(unavailable.renameTo(steamapps))
GameFileSync.syncConfigured(context)
assertTrue(File(folder, "Geometry Wars.steam").exists())
// A genuine uninstall removes the owned export at the next tick.
assertTrue(manifest.delete())
GameFileSync.syncConfigured(context)
assertEquals(0, folder.listFiles()!!.count { it.extension == GameFiles.EXTENSION })
// Disabled sync does not write files for new installs.
GameFileSync.disable(context)
manifest.writeText("\"name\" \"Geometry Wars\"\n\"StateFlags\" \"4\"")
GameFileSync.syncConfigured(context)
@@ -38,7 +38,6 @@ class GameFilesTest {
val provider = LaunchFileProvider(file)
provider.attachInfo(context, android.content.pm.ProviderInfo().apply { authority = "frontend" })
ShadowContentResolver.registerProviderInternal("frontend", provider)
// Providers often give opaque document IDs with no filename extension.
val uri = Uri.parse("content://frontend/document/opaque%3A42")
assertEquals("18446744073709551615", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, uri)))
}
@@ -9,18 +9,13 @@ import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
/**
* Signal-chain coverage for [GameIdentifier]. Pure JVM: builds
* fake game layouts in a temp dir and asserts the right appId/name/source/confidence come back.
* The PE version-resource path is exercised on-device (real .exe), not here.
*/
class GameIdentifierTest {
@get:Rule
val tmp = TemporaryFolder()
private fun exeIn(dir: File, name: String = "game.exe"): File =
File(dir, name).apply { parentFile?.mkdirs(); writeBytes(byteArrayOf(0x4D, 0x5A)) } // "MZ" — not a real PE
File(dir, name).apply { parentFile?.mkdirs(); writeBytes(byteArrayOf(0x4D, 0x5A)) }
@Test
fun steamAppIdTxt_besideExe_givesHighConfidenceAppId() {
@@ -51,7 +46,6 @@ class GameIdentifierTest {
@Test
fun steamManifestAcf_matchedByInstalldir_givesAppIdAndName() {
// steamapps/common/Palworld/Pal/Binaries/Win64/Palworld-Win64-Shipping.exe
val steamapps = tmp.newFolder("steamapps")
File(steamapps, "appmanifest_1623730.acf").writeText(
"""
@@ -63,7 +57,6 @@ class GameIdentifierTest {
}
""".trimIndent()
)
// a decoy manifest that must NOT win
File(steamapps, "appmanifest_570.acf").writeText(
""""AppState" { "appid" "570" "name" "Dota 2" "installdir" "dota 2 beta" }"""
)
@@ -81,9 +74,6 @@ class GameIdentifierTest {
"""{"gameId":"1207658691","name":"The Witcher 3: Wild Hunt","version":1}"""
)
val id = GameIdentifier.identify(exeIn(dir))
// normalizeName() deliberately converts ":" to " - " (a colon is illegal in a Windows
// filename), so the identified name never carries one. The test asserted the raw GOG
// string and had never passed.
assertEquals("The Witcher 3 - Wild Hunt", id.name)
assertEquals("1207658691", id.gogId)
assertNull(id.appId)
@@ -103,7 +93,6 @@ class GameIdentifierTest {
@Test
fun noMarkers_fallsBackToCleanedFolderName_forEngineBinary() {
// UE shipping binary → the folder name is the real title, exe basename is noise.
val dir = tmp.newFolder("Hades")
val id = GameIdentifier.identify(exeIn(dir, "Hades-Win64-Shipping.exe"))
assertEquals("Hades", id.name)
@@ -115,18 +104,16 @@ class GameIdentifierTest {
fun fallbackName_stripsRepackTagsAndVersionTokens() {
val dir = tmp.newFolder("Stardew Valley [FitGirl Repack] v1.5.4")
val id = GameIdentifier.identify(exeIn(dir, "Stardew.exe"))
assertEquals("Stardew", id.name) // exe basename wins (not an engine binary); folder tags irrelevant here
// and a repack-style exe basename is cleaned too:
assertEquals("Stardew", id.name)
val id2 = GameIdentifier.identify(exeIn(tmp.newFolder("g2"), "Game.CODEX.exe"))
assertEquals(GameIdentifier.Source.FILENAME, id2.source)
}
@Test
fun fltIni_gameSettingsAppId_isParsed() {
// Real God of War (FLT release) layout: flt.ini holds the appid under [GameSettings].
val dir = tmp.newFolder("GodOfWar")
File(dir, "flt.ini").writeText("[GameSettings]\nAppId=1593500\nUserName=X\nBuildId=7969425\n")
File(dir, "settings.ini").writeText("[Settings]\nVideoDevice=Wrapper\nMonitor=0\n") // no AppId -> ignored
File(dir, "settings.ini").writeText("[Settings]\nVideoDevice=Wrapper\nMonitor=0\n")
val id = GameIdentifier.identify(exeIn(dir, "GoW.exe"))
assertEquals(1593500, id.appId)
assertEquals(GameIdentifier.Confidence.HIGH, id.confidence)
@@ -141,12 +128,10 @@ class GameIdentifierTest {
@Test
fun bestName_prefersFileDescriptionWhenProductNameIsAbbreviation() {
// God of War ships ProductName "GoW" but FileDescription "God of War".
assertEquals(
"God of War",
PeVersionInfo.bestName(mapOf("ProductName" to "GoW", "FileDescription" to "God of War")),
)
// Normal case: ProductName is the full title -> keep it.
assertEquals(
"Cyberpunk 2077",
PeVersionInfo.bestName(mapOf("ProductName" to "Cyberpunk 2077", "FileDescription" to "Cyberpunk 2077")),
@@ -156,18 +141,15 @@ class GameIdentifierTest {
@Test
fun name_isNormalizedToBeFilesystemSafeAndTidy() {
// Colon → " - " (would otherwise be sanitized to '_' by the shortcut writer).
val d1 = tmp.newFolder("ds")
File(d1, "goggame-1.info").writeText("""{"name":"Dark Souls: Remastered"}""")
assertEquals("Dark Souls - Remastered", GameIdentifier.identify(exeIn(d1)).name)
// Trademark marks (symbol and text forms) stripped.
val d2 = tmp.newFolder("gow2")
File(d2, "goggame-2.info").writeText("""{"name":"God of War™"}""")
assertEquals("God of War", GameIdentifier.identify(exeIn(d2)).name)
val d3 = tmp.newFolder("ds3")
File(d3, "goggame-3.info").writeText("""{"name":"DARK SOULS(TM): REMASTERED"}""")
assertEquals("DARK SOULS - REMASTERED", GameIdentifier.identify(exeIn(d3)).name)
// Trailing PE descriptors dropped (DiRT 3's FileDescription is "DiRT 3 Executable").
val d4 = tmp.newFolder("dirt")
File(d4, "goggame-4.info").writeText("""{"name":"DiRT 3 Executable"}""")
assertEquals("DiRT 3", GameIdentifier.identify(exeIn(d4)).name)
@@ -175,8 +157,6 @@ class GameIdentifierTest {
@Test
fun launcherExe_prefersFolderName_overLauncher() {
// GTA V Enhanced: user picks the Rockstar launcher PlayGTAV.exe (no Steam id, PE = junk on
// a real exe). Fallback must use the folder title, not "PlayGTAV".
val dir = tmp.newFolder("Grand Theft Auto V Enhanced")
val id = GameIdentifier.identify(exeIn(dir, "PlayGTAV.exe"))
assertEquals("Grand Theft Auto V Enhanced", id.name)
@@ -187,12 +167,11 @@ class GameIdentifierTest {
fun launcherExe_withSeparator_prefersFolder_andStripsSiteTag() {
val dir = tmp.newFolder("Grand-Theft-Auto-IV-AnkerGames")
val id = GameIdentifier.identify(exeIn(dir, "Play - GTA IV.exe"))
assertEquals("Grand Theft Auto IV", id.name) // "AnkerGames" site tag stripped
assertEquals("Grand Theft Auto IV", id.name)
}
@Test
fun nonLauncherExe_startingWithPlay_keepsItsOwnName() {
// "PlayerUnknown" must NOT be treated as a launcher (would wrongly use the folder name).
val dir = tmp.newFolder("SomeInstallFolder")
val id = GameIdentifier.identify(exeIn(dir, "PlayerUnknown.exe"))
assertEquals("PlayerUnknown", id.name)
@@ -211,8 +190,7 @@ class GameIdentifierTest {
@Test
fun emptyWhenNothingIdentifiable() {
val dir = tmp.newFolder("x")
val id = GameIdentifier.identify(exeIn(dir, "Game.exe")) // engine-ish base → folder "x"
// "x" is a valid (if useless) fallback name; the point is it must not crash and appId is null.
val id = GameIdentifier.identify(exeIn(dir, "Game.exe"))
assertNull(id.appId)
assertTrue(id.confidence == GameIdentifier.Confidence.LOW)
}
@@ -16,7 +16,6 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
/** Games folders from earlier builds become entries, every game keeping what it had. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class GamesFolderMigrationTest {
@@ -40,7 +39,6 @@ class GamesFolderMigrationTest {
StoreGameSidecar.file(store).writeText("""{"store":"gog","id":"1","title":"Store Game","exe":"Store.exe"}""")
File(pc, "Notes").mkdirs()
SessionPrefs.setAddedGamesDirs(app, listOf(pc.path))
// What earlier scans had kept, by folder.
SessionPrefs.setAddedGameExe(app, beta.path, pick.path)
SessionPrefs.addedGameAppId(app, alpha.path, 0x8123_4567L)
SessionPrefs.addedGameAppId(app, beta.path, 0x8765_4321L)
@@ -63,11 +61,9 @@ class GamesFolderMigrationTest {
assertEquals(0x8765_4321L, games.getValue(beta.path).appId)
assertEquals("Alpha GOTY", games.getValue(alpha.path).name)
assertEquals(pick.path, games.getValue(beta.path).exe.path)
// The same path inside the session as before: the shortcut keeps its target.
assertEquals(AddedGames.GUEST_DIR + "/PC/Alpha/Alpha.exe", games.getValue(alpha.path).guestExe)
assertEquals(AddedGames.GUEST_DIR + "/PC/Beta/bin/Beta64.exe", games.getValue(beta.path).guestExe)
assertTrue(SessionPrefs.removedAddedGames(app).contains(gone.path))
// Not a library any more.
assertTrue(GameStorage.gamesFolderLibraries(app).isEmpty())
}
@@ -17,13 +17,11 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
/** Steam's app info asked anonymously: the answer read, batched, kept, and asked only when needed. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class SteamPicsTest {
private val app get() = RuntimeEnvironment.getApplication()
/** Dragon's Dogma 2's app info as Steam's anonymous PICS answer carried it (recorded 2026-10-10). */
private val recorded: String get() = javaClass.classLoader!!.getResource("steam-pics/app_2054970.vdf")!!.readText()
@After fun tearDown() { SteamAppInfo.pics = { SteamPics.lookup(it) } }
@@ -32,7 +30,6 @@ class SteamPicsTest {
val info = SteamPics.infoFromKeyValues(recorded)!!
assertEquals("Dragon's Dogma 2", info.name)
assertEquals(listOf("228988"), info.sharedDepots)
// VC++ 2019 for the Windows components.
assertEquals(listOf("vcredist2019_dll" to "VC++ 2019"), WinCompSources.steamDepots(info.sharedDepots))
}
@@ -66,11 +63,9 @@ class SteamPicsTest {
val calls = ArrayList<List<Int>>()
SteamAppInfo.pics = { ids -> calls.add(ids); mapOf(2054970 to SteamPics.infoFromKeyValues(recorded), 7 to null) }
assertTrue(SteamAppInfo.lookup(app, listOf(2054970, 7)))
// One connection for both.
assertEquals(listOf(listOf(2054970, 7)), calls)
assertEquals(listOf("228988"), SteamAppInfo.info(app, 2054970)!!.sharedDepots)
assertNull(SteamAppInfo.info(app, 7))
// Kept: nothing asked again (the miss waits a week).
assertFalse(SteamAppInfo.lookup(app, listOf(2054970, 7)))
assertEquals(1, calls.size)
assertEquals("hit", SteamAppInfo.state(app, 2054970))
@@ -78,7 +73,6 @@ class SteamPicsTest {
}
@Test fun noNetworkWhenTheClientsCacheHasTheApp() {
// An appinfo.vdf with the app in it (built as in WinCompSourcesTest).
val file = SteamAppInfo.appinfoFile(app)
WinCompSourcesTest.writeAppinfo(file, 1145360)
SteamAppInfo.pics = { fail("asked Steam"); null }
@@ -20,7 +20,6 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
/** Each source's list of Windows components, how it maps to the catalog, and what turns on by itself. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class WinCompSourcesTest {
@@ -35,7 +34,6 @@ class WinCompSourcesTest {
private fun auto(findings: List<WinCompSources.Finding>) = findings.filter { it.auto }.map { it.component to it.origin }
// ---- mapping tables ----
@Test fun gogDependencyIdsMapToComponents() {
assertEquals(listOf("vcredist2015"), WinCompSources.gog("MSVC2017_x64"))
@@ -62,7 +60,6 @@ class WinCompSourcesTest {
assertEquals(listOf("vcredist2015_dll" to "VC++ 2015", "d3dx9" to "DirectX (June 2010)"), WinCompSources.steamDepots(listOf("228986", "228990", "999")))
}
// ---- per source ----
@Test fun steamTakesItsSharedDepotsAndTurnsThemOn() {
val steamapps = tmp.newFolder("steamapps")
@@ -80,7 +77,6 @@ class WinCompSourcesTest {
sidecar(folder, Store.GOG, mapOf(WinCompSources.GOG_DEPENDENCIES to "MSVC2017_x64,DirectX,ISI"))
val findings = WinCompSources.forGame(app, game(folder, "gog"))
assertEquals(listOf("vcredist2015" to WinCompSources.Origin.GOG, "d3dx9" to WinCompSources.Origin.GOG), auto(findings))
// ISI is none of ours: a suggestion under its own name.
assertEquals(listOf("ISI"), findings.filter { it.component == null }.map { it.original })
}
@@ -105,12 +101,10 @@ class WinCompSourcesTest {
assertEquals(listOf("Activate.exe"), findings.filter { it.component == null }.map { it.original })
}
// ---- Custom: certainty decides ----
private fun appinfo(file: File, appId: Int) = writeAppinfo(file, appId)
companion object {
/** A version 29 appinfo.vdf with one app, whose depots point at two Steamworks Shared ones. */
fun writeAppinfo(file: File, appId: Int) {
val strings = listOf("appinfo", "common", "name", "depots", "228986", "depotfromapp", "228990", "1001", "maxsize")
fun key(s: String) = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(strings.indexOf(s)).array()
@@ -173,7 +167,6 @@ class WinCompSourcesTest {
assertEquals(listOf("vcredist2013" to WinCompSources.Origin.FOLDER), findings.map { it.component to it.origin })
}
// ---- what turns on, and the user's switches ----
private fun ready(name: String) = WinComponents.Component(name, "", "", "ready", emptyList(),
listOf(WinComponents.Step("override_dll", JSONObject().put("dll", "x").put("type", "native"))))
@@ -187,7 +180,6 @@ class WinCompSourcesTest {
WinCompSources.Finding("d3dx9", "d3dx9_43.dll", WinCompSources.Origin.FOLDER, false),
)
val picks = AutoComponents.autoPicks(findings, catalog)
// The detector's name installs as its DLL twin; physx cannot install; the folder scan only recommends.
assertEquals(listOf("vcredist2015_dll"), picks.keys.toList())
assertEquals("GOG", picks.getValue("vcredist2015_dll").kind)
}
@@ -199,11 +191,9 @@ class WinCompSourcesTest {
WinComponents.setUser(app, key, "d3dx9", false)
WinComponents.setUser(app, key, "oalinst_dll", true)
assertEquals(listOf("xact", "oalinst_dll"), WinComponents.picks(app, key))
// A new automatic list keeps the user's switches.
WinComponents.setAuto(app, key, mapOf("d3dx9" to WinComponents.AutoReason("GOG", listOf("DirectX"))))
assertEquals(listOf("oalinst_dll"), WinComponents.picks(app, key))
assertEquals(mapOf("d3dx9" to false, "oalinst_dll" to true), WinComponents.selection(app, key).user)
// What the launch reads stays version 1 with the effective list.
val text = File(app.filesDir, "wincomponents.json").readText()
assertEquals(1, JSONObject(text).getInt("version"))
assertEquals("oalinst_dll", JSONObject(text).getJSONObject("games").getJSONArray(key).getString(0))
@@ -219,10 +209,8 @@ class WinCompSourcesTest {
val folder = tmp.newFolder("Shared")
val exe = File(folder, "Shared.exe").apply { writeText("x") }
val art = AddedGames.Game(folder, "Shared", exe, "/g/Shared.exe", "/g", 0x81234567L, 0L, emptyList())
// The art fetch finds it by name ...
val match = AddedGameArt.steamMatch(app, art) { 4242 }
assertEquals(4242, match.appId)
// ... and the components read the same record.
assertEquals(4242, SteamMatch.get(app, folder.path)!!.appId)
assertEquals(SteamMatch.Certainty.NAME, SteamMatch.get(app, folder.path)!!.certainty)
assertFalse(WinCompSources.forGame(app, game(folder, Library.ADDED)).any { it.auto })
@@ -268,7 +256,6 @@ class WinCompSourcesTest {
@Test fun aSteamListedComponentNotYetDownloadedTurnsOnWhenItLands() = withFakeWorker {
installedNow.add("d3dx9")
val game = payback()
// The user had switched one off: it is never downloaded for an automatic pick.
WinComponents.setUser(app, "1262580", "vcredist2019_dll", false)
AutoComponents.queueGame(app, game, asked = true)
assertEquals(listOf("vcredist2013_dll"), downloaded)
@@ -276,7 +263,6 @@ class WinCompSourcesTest {
assertEquals(setOf("d3dx9", "vcredist2013_dll", "vcredist2019_dll"), sel.auto.keys)
assertEquals(setOf("d3dx9", "vcredist2013_dll"), WinComponents.picks(app, "1262580").toSet())
assertEquals("STEAM", sel.auto.getValue("vcredist2013_dll").kind)
// The list is kept for the page.
assertEquals(3, AutoComponents.cachedFindings(app, "1262580")!!.count { it.auto })
}
@@ -297,7 +283,6 @@ class WinCompSourcesTest {
AutoComponents.unfavourable = { true }
AutoComponents.queueGame(app, game, asked = false)
assertTrue(downloaded.isEmpty())
// The user opens the page: asked for, it goes.
AutoComponents.queueGame(app, game, asked = true)
assertEquals(3, downloaded.size)
}
@@ -311,7 +296,6 @@ class WinCompSourcesTest {
assertEquals(listOf("g:1262580"), AutoComponents.queued())
session = false
AutoComponents.drain(app)
// Each component once, though two games could want it.
assertEquals(downloaded.distinct(), downloaded)
}
@@ -319,7 +303,6 @@ class WinCompSourcesTest {
val game = payback()
AutoComponents.online = { false }
AutoComponents.queueGame(app, game, asked = true)
// The list is worked out offline; the downloads wait.
assertTrue(downloaded.isEmpty())
assertTrue(AutoComponents.queued().all { it.startsWith("c:") })
AutoComponents.online = { true }
@@ -327,7 +310,6 @@ class WinCompSourcesTest {
assertEquals(3, downloaded.size)
}
// ---- older store installs: the list read once from the store ----
@Test fun anOlderGogInstallGetsItsListFromTheStoreOnce() {
val folder = tmp.newFolder("DOOM I Enhanced")
@@ -338,7 +320,6 @@ class WinCompSourcesTest {
try {
assertTrue(StoreListBackfill.fill(app, folder))
assertEquals("MSVC2019_x64,DirectX", StoreGameSidecar.read(folder)!!.extra[WinCompSources.GOG_DEPENDENCIES])
// Kept like a fresh install: not fetched again.
assertFalse(StoreListBackfill.fill(app, folder))
assertEquals(1, fetches)
assertEquals(listOf("vcredist2019" to WinCompSources.Origin.GOG, "d3dx9" to WinCompSources.Origin.GOG), auto(WinCompSources.forGame(app, game(folder, "gog"))))
@@ -377,7 +358,6 @@ class WinCompSourcesTest {
AutoComponents.online = { true }
assertFalse(StoreListBackfill.fill(app, folder))
assertFalse(StoreListBackfill.fill(app, folder))
// Signed out or the store refused: once, then a week's rest; the sidecar is untouched.
assertEquals(1, fetches)
assertTrue(StoreListBackfill.needs(StoreGameSidecar.read(folder)!!))
} finally {
@@ -386,16 +366,13 @@ class WinCompSourcesTest {
}
}
// ---- apps the client never saw ----
@Test fun anAppTheClientLearnsLaterIsReadOnceItsCacheIsWritten() {
val file = SteamAppInfo.appinfoFile(app)
appinfo(file, 1)
file.setLastModified(1_000_000_000_000L)
assertEquals(null, SteamAppInfo.info(app, 1145360))
// Unchanged file: the miss stands (no re-read).
assertEquals(null, SteamAppInfo.info(app, 1145360))
// The client wrote its cache with the app in it: read at once, not a week later.
appinfo(file, 1145360)
file.setLastModified(1_000_000_100_000L)
assertEquals(listOf("228986", "228990"), SteamAppInfo.info(app, 1145360)!!.sharedDepots)
@@ -418,7 +395,6 @@ class WinCompSourcesTest {
assertTrue(StoreListBackfill.needs(StoreGameSidecar.read(older)!!))
}
// ---- a game installed during the session ----
private fun manifest(dir: File, appId: Int, state: Int, time: Long) =
File(dir, "appmanifest_$appId.acf").apply {
@@ -431,7 +407,6 @@ class WinCompSourcesTest {
manifest(steamapps, 12900, 1026, 1_000_000L)
manifest(steamapps, 570, 4, 1_000_000L)
val watch = SessionInstalls.Watch { listOf(steamapps) }
// What was there when the session started is not new.
assertTrue(watch.poll().isEmpty())
assertTrue(watch.poll().isEmpty())
manifest(steamapps, 12900, 4, 2_000_000L)
@@ -448,14 +423,12 @@ class WinCompSourcesTest {
gameUp = true
AutoComponents.queueInSession(app, installed)
assertTrue(downloaded.isEmpty())
// Other work stays paused in the session.
val other = game(tmp.newFolder("Other"), Library.ADDED)
AutoComponents.queueGame(app, other, asked = false)
gameUp = false
AutoComponents.drain(app)
assertEquals(3, downloaded.size)
assertEquals(setOf("d3dx9", "vcredist2013_dll", "vcredist2019_dll"), WinComponents.picks(app, "1262580").toSet())
// Nothing left pending for the launch to wait on; the other game still waits for the session's end.
assertEquals(0, AutoComponents.Pending.read(app).length())
assertEquals(listOf("g:${AutoComponents.appKey(other)}"), AutoComponents.queued())
session = false
@@ -21,7 +21,6 @@ class CardboardTest {
private fun assertVec(expected: FloatArray, actual: FloatArray) = assertArrayEquals(expected, actual, eps)
/** Rotation about a unit axis by an angle, as a quaternion (x, y, z, w). */
private fun quat(ax: Float, ay: Float, az: Float, deg: Double): FloatArray {
val h = deg * PI / 360.0
val s = sin(h).toFloat()
@@ -43,11 +42,8 @@ class CardboardTest {
}
@Test fun lensInsetLinesTheEyesUpWithTheLenses() {
// A 128 mm panel with 64 mm lenses: each viewport centre is 32 mm out, exactly under its lens.
assertEquals(0f, Cardboard.lensInset(128f, 64f), eps)
// A wider 150 mm panel: viewport centres 37.5 mm out, lenses 32 mm: 5.5 mm of a 75 mm viewport inwards.
assertEquals(5.5f / 75f, Cardboard.lensInset(150f, 64f), eps)
// A narrow panel puts the lens centres outside the viewport centres (negative inset).
assertEquals(true, Cardboard.lensInset(110f, 64f) < 0f)
assertEquals(0f, Cardboard.lensInset(0f, 64f), eps)
assertEquals(0f, Cardboard.lensInset(150f, 0f), eps)
@@ -62,7 +58,6 @@ class CardboardTest {
assertEquals(SteamVr.Status.READY, SteamVr.parse(answer("ok" to true, "installed" to true, "driver" to true)))
assertEquals(SteamVr.Status.RUNNING,
SteamVr.parse(answer("ok" to true, "installed" to true, "driver" to true, "running" to true)))
// The helper itself failed: the agent still says ok.
assertEquals(SteamVr.Status.UNAVAILABLE,
SteamVr.parse(answer("ok" to true, "installed" to true, "driver" to true).put("exitCode", 1)))
}
@@ -75,7 +70,6 @@ class CardboardTest {
}
assertTrue(SteamVr.succeeded("start", answer(true, exitCode = 0)))
assertTrue(SteamVr.succeeded("stop", answer(true, exitCode = 0)))
// The agent ran the request, but droiddeck-steamvr start failed (not installed, no driver).
assertFalse(SteamVr.succeeded("start", answer(true, exitCode = 1)))
assertFalse(SteamVr.succeeded("stop", answer(true, exitCode = 2)))
assertFalse(SteamVr.succeeded("start", answer(true)))
@@ -86,19 +80,14 @@ class CardboardTest {
}
@Test fun quaternionMatchesKnownRotations() {
// 90 degrees about z: x -> y.
val m = matrix(quat(0f, 0f, 1f, 90.0))
assertVec(floatArrayOf(0f, 1f, 0f), HeadPose.apply(m, floatArrayOf(1f, 0f, 0f)))
// Rotation vector without w: computed from the other three.
val q = HeadPose.quaternionFromRotationVector(floatArrayOf(0f, 0f, sin(PI / 4).toFloat()))
assertEquals(cos(PI / 4).toFloat(), q[3], eps)
}
@Test fun recenterMakesTheCurrentViewStraightAhead() {
// Phone upright in landscape, screen facing the viewer, who faces north-east-ish.
// Upright device: screen up = world up; looking direction = the screen's -z.
for (heading in listOf(0.0, 37.0, 140.0, -100.0)) {
// Start from "screen faces south, viewer looks north": device x = east, y = up, z = south.
val upright = floatArrayOf(1f, 0f, 0f, 0f, 0f, -1f, 0f, 1f, 0f)
val yaw = matrix(quat(0f, 0f, 1f, heading))
val screenToWorld = HeadPose.multiply(yaw, upright)
@@ -108,7 +97,6 @@ class CardboardTest {
@Test fun recenterKeepsPitchButDropsHeading() {
val upright = floatArrayOf(1f, 0f, 0f, 0f, 0f, -1f, 0f, 1f, 0f)
// Looking 30 degrees down, then turning 50 degrees: after a recentre the view is still 30 degrees down.
val pitched = HeadPose.multiply(upright, matrix(quat(1f, 0f, 0f, -30.0)))
val turned = HeadPose.multiply(matrix(quat(0f, 0f, 1f, 50.0)), pitched)
val pose = HeadPose.relative(HeadPose.recenter(turned), turned)
@@ -121,23 +109,18 @@ class CardboardTest {
@Test fun turningTheHeadTurnsTheView() {
val upright = floatArrayOf(1f, 0f, 0f, 0f, 0f, -1f, 0f, 1f, 0f)
val ref = HeadPose.recenter(upright)
// Turn the head 90 degrees to the left (counter-clockwise seen from above).
val turned = HeadPose.multiply(matrix(quat(0f, 0f, 1f, 90.0)), upright)
val forward = HeadPose.apply(HeadPose.relative(ref, turned), floatArrayOf(0f, 0f, -1f))
// The view now points to the left of the recentred forward direction: -x.
assertVec(floatArrayOf(-1f, 0f, 0f), forward)
}
@Test fun heldFlatTheViewStartsStraightAhead() {
// Screen facing up (device on a table, held like a tray, or lying back looking up at it).
for (m in listOf(HeadPose.IDENTITY, HeadPose.multiply(matrix(quat(0f, 0f, 1f, 30.0)), matrix(quat(1f, 0f, 0f, 20.0))))) {
assertVec(HeadPose.IDENTITY, HeadPose.relative(HeadPose.recenter(m), m))
}
}
@Test fun heldFlatTurningAtTheHipsPans() {
// Held flat, then the body turns 40 degrees to the left about the real vertical: the view
// turns left about its own up axis - it must not roll (the bug: yaw came out as a tilt).
val flat = HeadPose.IDENTITY
val ref = HeadPose.recenter(flat)
val turned = HeadPose.multiply(matrix(quat(0f, 0f, 1f, 40.0)), flat)
@@ -146,7 +129,6 @@ class CardboardTest {
val up = HeadPose.apply(pose, floatArrayOf(0f, 1f, 0f))
assertVec(floatArrayOf(-sin(PI * 40 / 180).toFloat(), 0f, -cos(PI * 40 / 180).toFloat()), forward)
assertVec(floatArrayOf(0f, 1f, 0f), up)
// Tipping the top edge down (pitching the tray towards you) looks down.
val tipped = HeadPose.multiply(flat, matrix(quat(1f, 0f, 0f, -20.0)))
val down = HeadPose.apply(HeadPose.relative(ref, tipped), floatArrayOf(0f, 0f, -1f))
assertEquals(-sin(PI / 9).toFloat(), down[1], eps)
@@ -154,7 +136,6 @@ class CardboardTest {
@Test fun fieldOfViewComesFromThePanelSeenThroughTheLens() {
val v2 = Cardboard.Viewer.CARDBOARD_V2
// A 74.7 mm tall panel 39.3 mm behind the lens: atan(37.35 / 39.3) = 43.5 degrees each way.
assertEquals(87.07f, Cardboard.fovDeg(v2, 74.7f), 0.05f)
assertEquals(v2.fallbackFovDeg, Cardboard.fovDeg(v2, 0f), eps)
assertEquals(Cardboard.Viewer.NONE.fallbackFovDeg, Cardboard.fovDeg(Cardboard.Viewer.NONE, 74.7f), eps)
@@ -165,11 +146,9 @@ class CardboardTest {
val n = sqrt(q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]); floatArrayOf(q[0] / n, q[1] / n, q[2] / n, q[3] / n)
})
assertVec(r, HeadPose.toScreen(r, 0))
// ROTATION_90 (as input/PadMotion maps it): screen x is the device's -y, screen y the device's x.
val s90 = HeadPose.toScreen(r, 1)
assertVec(HeadPose.apply(r, floatArrayOf(0f, -1f, 0f)), HeadPose.apply(s90, floatArrayOf(1f, 0f, 0f)))
assertVec(HeadPose.apply(r, floatArrayOf(1f, 0f, 0f)), HeadPose.apply(s90, floatArrayOf(0f, 1f, 0f)))
// ROTATION_270 is the opposite turn; four quarter turns of 90 give the original back.
val s270 = HeadPose.toScreen(r, 3)
assertVec(HeadPose.apply(r, floatArrayOf(0f, 1f, 0f)), HeadPose.apply(s270, floatArrayOf(1f, 0f, 0f)))
assertVec(r, HeadPose.toScreen(HeadPose.toScreen(HeadPose.toScreen(HeadPose.toScreen(r, 1), 1), 1), 1))
@@ -34,7 +34,6 @@ class DriverBundleTest {
SessionPrefs.setLinuxDriver(context, "")
}
/** Enough of an AArch64 ELF for the importers: the header they read, then the libc they look for. */
private fun library(libc: String) = ByteArray(64).also {
byteArrayOf(0x7f, 'E'.code.toByte(), 'L'.code.toByte(), 'F'.code.toByte(), 2, 1).copyInto(it)
it[18] = 0xB7.toByte()
@@ -60,7 +60,6 @@ class DriverPairsTest {
listOf(
asset("Turnip-r4.zip", "r4", false, DriverPairs.BANNER),
asset("Turnip-r4-Linux.zip", "r4", true, DriverPairs.BANNER),
// The A8xx set's newest display build is r4, but its Linux half is only in r3.
asset("Turnip-r4-A8xx.zip", "r4", false, DriverPairs.BANNER_A8XX),
asset("Turnip-r3-A8xx-Linux.zip", "r3", true, DriverPairs.BANNER_A8XX),
asset("WN-Turnip-1.19-b_Axxx.zip", "v1.19", false, DriverPairs.WN_BALANCED),
@@ -5,7 +5,6 @@ import org.junit.Test
class GpuModelFallbackTest {
@Test fun aPlatformCodeNameGivesItsAdreno() {
// AYANEO's Pocket FIT: KGSL says "Adreno33v2", the platform says pineapple.
assertEquals(750, GpuInfo.platformModel("pineapple"))
assertEquals(740, GpuInfo.platformModel("KALAMA"))
assertEquals(830, GpuInfo.platformModel("sun"))
@@ -8,7 +8,6 @@ class SocNamesTest {
private fun props(vararg pairs: Pair<String, String>): (String) -> String = { pairs.toMap()[it].orEmpty() }
@Test fun theModelIsFoundWhereVendorsPutIt() {
// AYANEO Pocket FIT: ro.soc.model blank, the vendor property set, ro.fota.platform a branch name.
assertEquals("SG8350P", SocNames.model(props("ro.vendor.qti.soc_model" to "SG8350P", "ro.fota.platform" to "MSM_13.0")))
assertEquals("QCS8550", SocNames.model(props("ro.soc.model" to "QCS8550", "ro.vendor.qti.soc_model" to "other")))
assertEquals("", SocNames.model(props("ro.fota.platform" to "MSM_13.0")))
@@ -7,12 +7,6 @@ import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
/**
* The ring paths handed to the guest (FAKE_EVDEV_MEMFD_PATHS) must keep the spelling the session
* tree is bound under. On ColorOS 16 /data/user/0 resolves to /data/data, the guest only has the
* first bound, and a canonical export left every pad dead (#166). A symlinked directory stands in
* for that here.
*/
class FakeInputRingPathTest {
private lateinit var base: File
private lateinit var real: File
@@ -37,7 +31,6 @@ class FakeInputRingPathTest {
@Test fun theExportKeepsTheBoundSpellingThroughALinkedDataDirectory() {
val fakeInputDir = File(link, "files/session/dev/input").apply { mkdirs() }
val ring = FakeInputRingPaths.ringFile(fakeInputDir, 0)!!.apply { parentFile!!.mkdirs(); writeText("") }
// The link really does resolve elsewhere, as /data/user/0 does on the affected devices.
assertTrue(ring.canonicalPath.startsWith(real.canonicalPath + "/"))
val exported = FakeInputRingPaths.exportPath(ring)
assertEquals(File(link, "files/session/dev/fakeinput-rings/ring0").path, exported)
@@ -0,0 +1,55 @@
package com.droiddeck.launcher.input
import android.app.Activity
import android.content.Context
import android.os.Looper
import android.view.inputmethod.InputMethodManager
import android.widget.FrameLayout
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
@RunWith(RobolectricTestRunner::class)
@Config(manifest = Config.NONE)
class KeyboardHostTest {
private lateinit var imm: InputMethodManager
private lateinit var host: KeyboardHost
@Before fun setUp() {
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
host = KeyboardHost(activity)
activity.setContentView(FrameLayout(activity).apply { addView(host) })
idle()
}
@Config(sdk = [33])
@Test fun toggleShowsAKeyboardTheSystemDismissed() {
host.show()
idle()
imm.hideSoftInputFromWindow(host.windowToken, 0)
idle()
host.toggle()
idle()
assertTrue(shadowOf(imm).isSoftInputVisible)
assertTrue(host.shown)
}
@Config(sdk = [28])
@Test fun toggleHidesAKeyboardThatIsShowing() {
host.show()
idle()
host.toggle()
idle()
assertFalse(shadowOf(imm).isSoftInputVisible)
assertFalse(host.shown)
}
private fun idle() = shadowOf(Looper.getMainLooper()).idle()
}
@@ -148,8 +148,6 @@ class PadBridgeRoutingTest {
private companion object { const val COMPOSITE = 0x1002313 }
// Robolectric's default InputEvent shadow has its own nullable device field. Use Android's
// original lookup so key and motion events resolve the registered device by id.
@Implements(KeyEvent::class)
class RegisteredKeyEvent : ShadowKeyEvent() {
@RealObject private lateinit var event: KeyEvent
@@ -6,7 +6,6 @@ import org.junit.Assert.assertTrue
import org.junit.Test
class SteamTouchConfigTest {
// A layout DroidDeck saved for Geometry Wars on the Thor, as Steam keeps it.
private val saved = "0aec0310012218080010011d0000703d255555d53d2d0000803f350000803f2218080110011d6666fe3e255555d53d2d0000803f350000803f2218080210011dba490c3e255c8f423f2d0000803f350000803f2218080410011d9a99593f255c8f423f2d0000803f350000803f2218080510011d8fc2353f25ae47613f2d0000803f350000803f2218080610011d2b87163e25d7a3f03e2d0000803f350000803f2218080710011dba49003f25f958053f2d293ab23f35293ab23f2218080810011d9a99683f25d227dd3e2d0000803f350000803f2218080910011d9a99483f25d227dd3e2d0000803f350000803f2218080a10011d9a99583f254444a43e2d0000803f350000803f2218080b10011d6666ce3e255555d53d2d0000803f350000803f2218080c10011d3333173f255555d53d2d0000803f350000803f2218080d10011d0ad7233e2585eb513e2d0000803f350000803f2218080e10011d3d0a573f2585eb513e2d0000803f350000803f2218080f10011d8fc2753d2585eb513e2d0000803f350000803f2218081010011dd7a3703f2585eb513e2d0000803f350000803f2218081c10011d0000713f255555d53d2d0000803f350000803f2218080310001de17a943e25ae47613f2d0000803f350000803f2a140d0000803f150000803f1d0000803f25cdcccc3e1002"
@Test
@@ -16,7 +16,6 @@ class AppImageManagerTest {
@Before fun setUp() { dir = Files.createTempDirectory("appimage").toFile() }
@After fun tearDown() { dir.deleteRecursively() }
/** An ELF header with the AppImage magic at byte 8 and [machine] at byte 18. */
private fun image(machine: Int, type: Int = 2, magic: Boolean = true): File {
val b = ByteArray(64)
b[0] = 0x7f; b[1] = 'E'.code.toByte(); b[2] = 'L'.code.toByte(); b[3] = 'F'.code.toByte()
@@ -68,7 +68,6 @@ class BwrapSpawnerTest {
}
}
/** The sandbox a Flatpak request describes, built on disk under a temporary directory. */
@RunWith(RobolectricTestRunner::class)
class BwrapSpawnerPlanTest {
private lateinit var dir: File
@@ -76,7 +75,6 @@ class BwrapSpawnerPlanTest {
@Before fun setUp() {
dir = Files.createTempDirectory("bwrap-plan").toFile()
// Flatpak names the runtime by its path inside the rootfs.
runtime = File(LinuxRuntime.rootDir(RuntimeEnvironment.getApplication()), "runtime-files")
File(runtime, "lib").mkdirs()
}
@@ -107,18 +105,14 @@ class BwrapSpawnerPlanTest {
op("t" to "bind", "src" to "/nonexistent-${System.nanoTime()}", "dest" to "/run/x", "try" to true),
), dir)
// The runtime is bound at /usr, not written into.
assertTrue(plan.binds.any { it.guest == "/usr" && File(it.host).canonicalPath == runtime.canonicalPath })
assertFalse(File(runtime, "lib/GL").exists())
// The tmpfs under /usr is a directory of ours, and the link Flatpak makes inside it lands there.
val gl = plan.binds.single { it.guest == "/usr/lib/GL" }
assertTrue(gl.host.startsWith(dir.path))
assertEquals("default/lib/libEGL.so", Files.readSymbolicLink(File(gl.host, "libEGL.so").toPath()).toString())
// Top-level links, directories and files are made in the sandbox root itself.
assertEquals("usr/lib", Files.readSymbolicLink(File(plan.root, "lib").toPath()).toString())
assertTrue(File(plan.root, "tmp").isDirectory)
assertEquals("[Application]\nname=org.example.Game\n", File(plan.root, ".flatpak-info").readText())
// A --bind-try whose source is missing is left out.
assertFalse(plan.binds.any { it.guest == "/run/x" })
assertEquals(listOf("/app/bin/game"), plan.argv)
assertEquals("/app", plan.cwd)
@@ -69,7 +69,6 @@ class DeckyPluginInstallTest {
val plugins = temporary.newFolder()
val old = plugin(plugins, "Unifideck", "Unifideck")
File(old, "old-version").writeText("keep")
// An empty staged directory makes the plugin activation fail after backing up the old one.
val staged = plugin(temporary.newFolder(), "Unifideck", "Unifideck")
staged.deleteRecursively()
val settings = File(temporary.newFolder(), "loader.json").apply { writeText("{}") }
@@ -9,7 +9,6 @@ class ProotFastPathTest {
private val root = File("/data/data/com.droiddeck.launcher/files/linuxfs")
@Test fun aSessionsUsualBindsGetAKey() {
// 87 on a device with two Games folders: past the old limit of 64, which dropped them.
val binds = (1..87).map { "/host/$it:/guest/$it" }
assertNotNull(ProotFastPath.key(root, binds))
}
@@ -107,7 +107,6 @@ class RuntimeRemovalTest {
follower.join(5000)
assertEquals(true, result.get())
assertEquals(true, followerResult.get())
// The last stage is "Linux runtime removed", the only one reported at 100.
assertEquals(100, percents.last())
assertFalse(root.exists())
assertFalse(File(dir, "linuxfs.removing").exists())
@@ -131,7 +130,6 @@ class RuntimeRemovalTest {
val root = runtime()
try {
val removal = LinuxRuntimeInstaller.beginUninstall(null, root)!!
// The first stage names the removal, the second counts its first entry.
var stages = 0
assertFalse(removal.run { _, _ ->
if (++stages == 2)
@@ -170,12 +168,10 @@ class RuntimeRemovalTest {
assertNull(LinuxRuntimeInstaller.removalError())
assertFalse(root.exists())
assertFalse(File(dir, "linuxfs.removing").exists())
// Only the undeletable entry and its parents remain, out of the way.
val trash = File(dir, LinuxRuntimeInstaller.TRASH)
assertEquals(listOf(".steampath"), trash.walk().filter { it.isFile }.map { it.name }.toList())
assertEquals(setOf(LinuxRuntimeInstaller.TRASH), dir.list()!!.toSet())
// Once it can be deleted, the next removal clears the trash too.
RuntimeFileTree.refuseForTest = null
assertTrue(LinuxRuntimeInstaller.beginUninstall(null, root)!!.run(null))
assertFalse(trash.exists())
@@ -35,7 +35,6 @@ class RuntimeRemovalUiTest {
try {
val activity = Robolectric.buildActivity(SessionActivity::class.java).create()
assertTrue(activity.get().isFinishing)
// Even lifecycle callbacks delivered after finish must not touch uninitialised UI.
activity.start().resume().pause().stop().destroy()
assertFalse(SessionState.running)
assertEquals(SessionPhase.IDLE, SessionState.phase)
@@ -61,7 +61,6 @@ class BatteryComponentTest {
val discovered = supplies.listFiles()!!.filter { it.name.contains("BAT") }
assertEquals(listOf("BAT1"), discovered.map { it.name })
fun read(name: String) = File(discovered.single(), name).readText().trim().toLong()
// One 4 Ah battery at 4 V drawing 2 A: 8 W and two hours, regardless of vendor current sign.
assertEquals(8_000_000L, read("power_now"))
assertEquals(16_000_000L, read("energy_now"))
assertEquals(7200L, read("time_to_empty_now"))
@@ -60,7 +60,6 @@ class GameEnvironmentStoreTest {
"d3d9.samplerAnisotropy = 16; d3d11.samplerAnisotropy = 16; d3d9.samplerLodBias = -0.58; d3d11.samplerLodBias = -0.58",
json.getString(GameEnvironmentStore.DXVK_CONFIG),
)
// The user's own entry is untouched; the launcher appends the options at launch.
assertEquals("dxvk.tearFree = True", json.getJSONObject("shared").getString("DXVK_CONFIG"))
assertEquals(GameEnvironment.Config(shared = mapOf("DXVK_CONFIG" to "dxvk.tearFree = True")), GameEnvironmentStore.read(context))
SessionPrefs.setTextureAnisotropy(context, 0)
@@ -102,7 +102,6 @@ class ProtonExtrasTest {
assertTrue(ProtonExtras.compareVersions("DroidDeck-Proton 11-7", "DroidDeck-Proton 11-7.1") < 0)
assertTrue(ProtonExtras.compareVersions("cachyos-11.0-20260703-slr", "cachyos-11.0-20261005-slr") < 0)
assertTrue(ProtonExtras.compareVersions("cachyos-10.0-sunset-slr", "cachyos-11.0-20260601-slr") < 0)
// The architecture in a folder name is not part of its version.
assertEquals(listOf(11L, 7L), ProtonExtras.versionKey("GE-Proton11-7-aarch64"))
assertEquals(listOf(11L, 0L, 20261005L), ProtonExtras.versionKey("proton-cachyos-11.0-20261005-slr-arm64"))
assertEquals(listOf(11L, 7L, 5L), ProtonExtras.versionKey("DroidDeck-Proton 11-7.5"))
@@ -114,9 +113,8 @@ class ProtonExtrasTest {
val tools = temp.newFolder("compatibilitytools.d")
for (name in listOf("GE-Proton11-10", "GE-Proton11-9", "DroidDeck-Proton 11-7.10", "DroidDeck-Proton 11-7.5",
"droiddeck-proton-arm64", "droiddeck-proton-11-arm64", "proton-cachyos-11.0-20261005-slr-arm64")) installTool(tools, name)
File(tools, "DroidDeck-Proton 11-6").mkdirs() // no manifest: half unpacked, not installed
File(tools, "DroidDeck-Proton 11-6").mkdirs()
assertEquals(listOf("GE-Proton11-9", "GE-Proton11-10"), ProtonExtras.installedIn(tools, tool("ge")))
// Ours, not DroidDeck's own droiddeck-proton-* tools: the prefix is matched with its case.
assertEquals(listOf("DroidDeck-Proton 11-7.5", "DroidDeck-Proton 11-7.10"), ProtonExtras.installedIn(tools, tool("droiddeck")))
assertEquals(listOf("proton-cachyos-11.0-20261005-slr-arm64"), ProtonExtras.installedIn(tools, tool("cachyos")))
assertEquals(emptyList<String>(), ProtonExtras.installedIn(File(tools, "missing"), tool("ge")))
@@ -149,13 +147,11 @@ class ProtonExtrasTest {
.put("cachyos", JSONObject().put("tag", "cachyos-11.0-20261005-slr").put("at", now - 60_000))
.put("droiddeck", JSONObject().put("tag", "DroidDeck-Proton-11-7.6").put("at", now - ProtonExtras.CHECK_EVERY_MS + 60_000))
File(context.filesDir, "proton-latest.json").writeText(latest.toString())
// Every source was looked up within the last six hours: nothing goes to GitHub.
assertFalse(ProtonExtras.checkLatest(context, now = now))
assertEquals("DroidDeck-Proton-11-7.6", ProtonExtras.update(context, tool("droiddeck")))
assertNull(ProtonExtras.update(context, tool("ge")))
assertNull(ProtonExtras.update(context, tool("cachyos")))
assertEquals(listOf("DroidDeck-Proton 11-7.5"), ProtonExtras.installedTags(context, tool("droiddeck")))
// The tag recorded at install stands for the folder.
File(context.filesDir, "proton-extras.json").writeText(JSONObject().put("DroidDeck-Proton 11-7.5", "DroidDeck-Proton-11-7.6").toString())
assertEquals(listOf("DroidDeck-Proton-11-7.6"), ProtonExtras.installedTags(context, tool("droiddeck")))
assertNull(ProtonExtras.update(context, tool("droiddeck")))
@@ -168,7 +164,6 @@ class ProtonExtrasTest {
for (name in listOf("DroidDeck-Proton 11-7.5", "DroidDeck-Proton 11-7.6", "DroidDeck-Proton 11-7.10", "GE-Proton11-7")) installTool(tools, name)
ProtonExtras.remove(context, tool("droiddeck"), "DroidDeck-Proton 11-7.6")
assertEquals(listOf("DroidDeck-Proton 11-7.5", "DroidDeck-Proton 11-7.10"), ProtonExtras.installedAll(context, tool("droiddeck")))
// A folder of another source is never removed through this one.
ProtonExtras.remove(context, tool("droiddeck"), "GE-Proton11-7")
assertTrue(File(tools, "GE-Proton11-7").isDirectory)
assertEquals(listOf("DroidDeck-Proton 11-7.5", "DroidDeck-Proton 11-7.10"), ProtonExtras.installedAll(context, tool("droiddeck")))
@@ -23,15 +23,32 @@ class QuestExperimentalTest {
ShadowBuild.setDevice("phone")
}
@Test fun otherDevicesAndQuest2KeepTheirSettings() {
for (model in listOf("Phone", "Quest 2")) {
@Test fun otherDevicesKeepTheirSettings() {
for (model in listOf("Phone", "Quest", "Quest Pro")) {
ShadowBuild.setModel(model)
QuestExperimental.initialize(context)
assertEquals(SessionPrefs.GPU_DRIVERS_AUTO, SessionPrefs.gpuDriverMode(context))
assertEquals("", SessionPrefs.androidDriver(context))
assertFalse(SessionPrefs.hdr(context, "steam"))
}
assertFalse(QuestExperimental.supported("Quest 2", "hollywood", "Oculus"))
assertFalse(QuestExperimental.supported("Phone", "hollywood", "Other"))
}
@Test fun quest2SelectsA6xxInsteadOfQuest3DriverAndPreservesLaterChoices() {
ShadowBuild.setModel("Quest 2")
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
.putBoolean("questDefaultsV1", true).commit()
QuestExperimental.initialize(context)
assertEquals(SessionPrefs.GPU_DRIVERS_MANUAL, SessionPrefs.gpuDriverMode(context))
assertEquals(QuestExperimental.DRIVER_A6XX, SessionPrefs.androidDriver(context))
assertEquals("", SessionPrefs.linuxDriver(context))
assertTrue(SessionPrefs.hdr(context, "steam"))
assertTrue(QuestExperimental.supported("unknown", "hollywood", "Oculus"))
assertTrue(QuestExperimental.supported("unknown", "hollywood", "Meta"))
assertFalse(QuestExperimental.quest2("Quest 3", "eureka", "Meta"))
SessionPrefs.setAndroidDriver(context, "chosen-a6xx-driver")
QuestExperimental.initialize(context)
assertEquals("chosen-a6xx-driver", SessionPrefs.androidDriver(context))
}
@Test fun questDefaultsSelectBothCompatibilityPathsAndAreAppliedOnlyOnce() {
@@ -164,7 +164,6 @@ class RumbleComponentTest {
}
private fun effect(strong: Int = 65535, weak: Int = 65535, slot: Int = 0) {
// Inject a decoded force-feedback packet; transport is outside these tests.
val int = Int::class.javaPrimitiveType
RumbleComponent::class.java.getDeclaredMethod("buzz", int, int, int, int)
.apply { isAccessible = true }.invoke(rumble, strong, weak, 5000, slot)
@@ -12,16 +12,12 @@ class SessionDisplayTest {
}
@Test fun heightPresetsKeepThePanelShapeWithASixteenByNineFloor() {
// 20:9 phone: edge to edge, no bars for the client's interface.
assertEquals(1600 to 720, SessionDisplay.resolveChoice(2400 to 1080, SessionDisplay.DEFAULT_RESOLUTION))
assertEquals(1608 to 720, SessionDisplay.resolveChoice(2412 to 1080, "720p"))
// 1440p phone: bounded by the preset height, not the panel.
assertEquals(1560 to 720, SessionDisplay.resolveChoice(3120 to 1440, "720p"))
assertEquals(2340 to 1080, SessionDisplay.resolveChoice(3120 to 1440, "1080p"))
// Foldable inner panel and 4:3 handhelds: never narrower than 16:9.
assertEquals(1280 to 720, SessionDisplay.resolveChoice(2208 to 1840, "720p"))
assertEquals(1280 to 720, SessionDisplay.resolveChoice(1440 to 1080, "720p"))
// Never taller than the panel.
assertEquals(1280 to 720, SessionDisplay.resolveChoice(1280 to 720, "1080p"))
}
@@ -39,10 +35,8 @@ class SessionDisplayTest {
}
@Test fun unfoldedControlsKeepTheGameSixteenByNineAcrossTheWidth() {
// Fold inner screen held as a tablet, and upright: 16:9 either way, the controls the rest.
assertEquals(1376, SessionDisplay.unfoldedGameHeight(2448, 1848))
assertEquals(1038, SessionDisplay.unfoldedGameHeight(1848, 2448))
// A window near 16:9 itself still leaves the controls a fifth of it.
assertEquals(864, SessionDisplay.unfoldedGameHeight(1920, 1080))
}
@@ -27,7 +27,6 @@ class SessionLogShareTest {
z.entries().toList().associate { it.name.substringAfter('/') to z.getInputStream(it).bufferedReader().readText() }
}
/** A record as the session's ending writes it, listing [files] as they stand now. */
private fun record(folder: File, vararg files: String, rules: Int = LogRedactor.RULES_VERSION) {
File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).writeText(
"rules $rules\n" + files.joinToString("") { val f = File(folder, it); "${f.length()}\t${f.lastModified()}\t$it\n" })
@@ -35,8 +34,6 @@ class SessionLogShareTest {
@Test fun aRecordedUnchangedFileIsScrubbedAgainOnTheWayIntoTheZip() {
val folder = tmp.newFolder("2026-10-06-01-steam")
// A file the ending recorded as scrubbed still gets the share's final pass: the record
// may predate a rule, and a zip is the one way a log leaves the device.
File(folder, "session.log").writeText("$secret\n")
record(folder, "session.log")
assertFalse(zip(folder).getValue("session.log").contains(leaked))
@@ -50,7 +47,6 @@ class SessionLogShareTest {
File(folder, "steam/deep/nested.txt").writeText("$secret\n")
File(folder, ".hidden.txt").writeText("$secret\n")
record(folder, "app.log", "session.log")
// Appended to after the ending (the app's log capture), and touched with an older time.
File(folder, "app.log").appendText("$secret\n")
File(folder, "session.log").apply { writeText("$secret\n".padEnd(3, ' ')); setLastModified(1_000L) }
File(folder, "events.jsonl").writeText("$secret\n")
@@ -109,7 +105,6 @@ class SessionLogShareTest {
@Test fun aFileThatCouldNotBeScrubbedLeavesTheFolderUnrecorded() {
val folder = tmp.newFolder("2026-10-06-06-steam")
File(folder, "session.log").writeText("$secret\n")
// A folder the scrubbed copy cannot be written into: the scrub fails, the original stays.
folder.setWritable(false)
try {
SessionArtifacts.scrubAndMark(folder)
@@ -12,7 +12,6 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
/** A shared zip is scrubbed on the way in, whatever the files on disk still hold. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class SessionLogShareZipTest {
@@ -21,7 +20,6 @@ class SessionLogShareZipTest {
@Test fun everyTextFileInTheZipIsScrubbedAndTheStoresAndToolsLogsComeAlong() {
val logs = LinuxRuntime.logDir(app)
val session = File(logs, "2026-10-08-01-steam").apply { mkdirs() }
// Written raw, as a file from before a rule existed would be.
File(session, "session.log").writeText(
"fetch https://gog-cdn-fastly.gog.com/token=nva=1791500000~dirs=/x~token=0a1b2c3d4e5f/content-system/v2/store/1/ab/cd/f\n" +
"fetch https://epicgames-download1.akamaized.net/Builds/Org/a/ChunksV4/12/ABCD.chunk?__token__=exp=1~hmac=deadbeefcafe\n" +
@@ -40,7 +38,6 @@ class SessionLogShareZipTest {
for (secret in listOf("0a1b2c3d4e5f", "deadbeefcafe", "abcdef123456", "someone@example.com", "AUTHCODE123", "abc.def.ghi", "zzzzzzzz12", "eyabc")) {
assertFalse("$secret survived", all.contains(secret))
}
// What makes a log worth reading stays.
assertTrue(all.contains("kept: EResult 5, app 1086940, steamapps/common/Game"))
assertTrue(all.contains("https://gog-cdn-fastly.gog.com/"))
@@ -53,9 +50,6 @@ class SessionLogShareZipTest {
assertEquals(line, com.droiddeck.launcher.core.LogRedactor.redactForShare(line))
}
// Folders an earlier build scrubbed and marked under older rules, their copied Steam UI log
// still naming the account: one app start (the move out of Download/, then the pass over
// older folders) leaves every one scrubbed on disk under the current rules.
private fun olderFolder(parent: File, name: String, marker: String = ".scrubbed-2"): File {
val dir = File(parent, name).apply { mkdirs() }
File(dir, marker).writeText("scrubbed earlier\n")
@@ -91,12 +85,10 @@ class SessionLogShareZipTest {
val legacy = LinuxRuntime.legacyLogDir().apply { mkdirs() }
val names = (1..9).map { "2026-10-0${it}-01-steam" }
names.forEachIndexed { i, name ->
// Old markers of every kind an earlier build left, one even claiming the current rules.
olderFolder(legacy, name, marker = listOf(".scrubbed-2", ".scrubbed-1", ".scrubbed-r${com.droiddeck.launcher.core.LogRedactor.RULES_VERSION}")[i % 3])
}
File(legacy, "Saves").apply { mkdirs() }.resolve("keep.txt").writeText("save\n")
// What MainActivity runs at start.
LogMigration.run(app)
SessionArtifacts.scrubOlder(app)
@@ -0,0 +1,96 @@
package com.droiddeck.launcher.session
import android.content.Context
import com.droiddeck.launcher.core.AppUiPrefs
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.input.ControllerPrefs
import org.junit.Assert.*
import org.junit.Before
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 SettingsResetTest {
private val app get() = RuntimeEnvironment.getApplication()
private fun prefs(name: String) = app.getSharedPreferences(name, Context.MODE_PRIVATE)
private val session get() = prefs("session")
@Before fun clear() {
listOf("session", "controller", "app-ui", "frame_gen", "steam_touch", "agent").forEach {
prefs(it).edit().clear().commit()
}
}
@Test fun settingsGoBackToTheirDefaults() {
SessionPrefs.setTheme(app, "ocean")
SessionPrefs.setNoXalia(app, false)
SessionPrefs.setFpsLimit(app, SessionService.MODE_STEAM, 30)
SessionPrefs.setHdr(app, SessionService.MODE_DESKTOP, true)
SessionPrefs.setResolutionChoice(app, SessionService.MODE_STEAM, "1280x800")
SessionPrefs.setGuestHostname(app, "MyDeck")
ControllerPrefs.setOpacity(app, 40)
AppUiPrefs.setScale(app, 150)
FrameGen.set(app, FrameGen.Mode(FrameGen.ENGINE_WINFG, 3))
prefs("steam_touch").edit().putBoolean("gyro", false).commit()
assertTrue(SettingsReset.resetAll(app, gameProfiles = false))
assertEquals("graphite", SessionPrefs.theme(app))
assertTrue(SessionPrefs.noXalia(app))
assertEquals(0, SessionPrefs.fpsLimit(app, SessionService.MODE_STEAM))
assertFalse(SessionPrefs.hdr(app, SessionService.MODE_DESKTOP))
assertFalse(SessionPrefs.resolutionChosen(app, SessionService.MODE_STEAM))
assertEquals(SessionPrefs.DEFAULT_GUEST_HOSTNAME, SessionPrefs.guestHostname(app))
assertEquals(100, ControllerPrefs.read(app).opacity)
assertEquals(AppUiPrefs.DEFAULT_SCALE, AppUiPrefs.scale(app))
assertEquals(FrameGen.Mode.OFF.engine, FrameGen.engine(app))
assertFalse(prefs("steam_touch").contains("gyro"))
}
@Test fun libraryAndRecordsAreKept() {
val folder = "/storage/emulated/0/Games/Foo"
SessionPrefs.setAddedGameName(app, folder, "Foo")
SessionPrefs.setAddedGameExe(app, folder, "$folder/foo.exe")
SessionPrefs.addedGameAppId(app, folder, 1234L)
SessionPrefs.setAddedGameRemoved(app, "/storage/emulated/0/Games/Bar", true)
SessionPrefs.setGamesFoldersMigrated(app)
SessionPrefs.setGpuAutoInstalled(app, setOf("turnip-a"))
SessionPrefs.setRomsDir(app, "/storage/emulated/0/ROMs")
SessionPrefs.setGameStorage(app, "/storage/ABCD-1234", "SD Card")
SessionPrefs.setMicAsked(app)
prefs("steam_touch").edit().putString("copiedLayout", "a:1,2").commit()
SettingsReset.resetAll(app, gameProfiles = false)
assertEquals("Foo", SessionPrefs.addedGameName(app, folder))
assertEquals("$folder/foo.exe", SessionPrefs.addedGameExe(app, folder))
assertEquals(1234L, SessionPrefs.addedGameStoredAppId(app, folder))
assertEquals(listOf("/storage/emulated/0/Games/Bar"), SessionPrefs.removedAddedGames(app))
assertTrue(SessionPrefs.gamesFoldersMigrated(app))
assertEquals(setOf("turnip-a"), SessionPrefs.gpuAutoInstalled(app))
assertEquals("/storage/emulated/0/ROMs", SessionPrefs.romsDir(app))
assertEquals("/storage/ABCD-1234", SessionPrefs.gameStorage(app))
assertTrue(SessionPrefs.micAsked(app))
assertEquals("a:1,2", prefs("steam_touch").getString("copiedLayout", null))
}
@Test fun gameTextureFilteringIsKeptUnlessGameProfilesAreReset() {
session.edit().putString("gameTextureFiltering", """{"440":{"anisotropy":16}}""").commit()
SettingsReset.resetAll(app, gameProfiles = false)
assertEquals(16, SessionPrefs.gameTextureFiltering(app, "440").anisotropy)
SettingsReset.resetAll(app, gameProfiles = true)
assertTrue(SessionPrefs.gameTextureFiltering(app).isEmpty())
}
@Test fun perModeKeysAreSettings() {
listOf("resolutionCap.steam", "displayResolution.desktop", "customRes.steam", "hdr.steam", "fpsLimit.desktop", "suspendPolicy.steam")
.forEach { assertTrue(it, SettingsReset.isSessionSetting(it)) }
listOf("addedName:/x", "addedAppId:/x", "gpuAutoInstalled", "romsDir", "gameStorage", "micAsked", "gameTextureFiltering")
.forEach { assertFalse(it, SettingsReset.isSessionSetting(it)) }
}
}
@@ -79,13 +79,11 @@ class SteamDownloadMonitorTest {
var now = 1_000L
assertTrue(monitor.poll(root, now, received))
// Five minutes of a download Steam no longer logs, at 4 MB/s.
while (now < 300_000L) {
now += 2_000L
received += 8_000_000L
assertTrue(monitor.poll(root, now, received))
}
// Traffic stops: the session may suspend once the grace runs out.
assertTrue(monitor.poll(root, now + 90_000L, received))
assertFalse(monitor.poll(root, now + 92_001L, received))
@@ -18,6 +18,18 @@ class SteamLanguageTest {
assertEquals("tchinese", steam("zh-HK"))
}
@Test fun everyAppLanguageButHindiHasSteamsOwn() {
com.droiddeck.launcher.core.AppLanguage.supported.forEach {
val steam = steam(it)
assertTrue("$it -> $steam", (steam == "english") == (it == "en" || it == "hi"))
}
assertEquals("brazilian", steam("pt-BR"))
assertEquals("portuguese", steam("pt-PT"))
assertEquals("latam", steam("es-419"))
assertEquals("indonesian", steam("id"))
assertEquals("malay", steam("ms"))
}
@Test fun chineseFollowsTheScriptBeforeTheRegion() {
assertEquals("tchinese", steam("zh-Hant-CN"))
assertEquals("schinese", steam("zh-Hans-HK"))
@@ -30,7 +42,6 @@ class SteamLanguageTest {
assertEquals("latam", steam("es-MX"))
assertEquals("latam", steam("es-419"))
assertEquals("spanish", steam("es-ES"))
// The app's Spanish has no region; the system's says where the player is.
assertEquals("latam", steam("es", region = "AR"))
assertEquals("spanish", steam("es", region = "ES"))
}
@@ -23,7 +23,6 @@ class WinComponentsSupportTest {
@Test fun windowsInstallerPackagesInstallHere() {
assertEquals(Support.READY, support(component("xna40", step("install_msi", "url" to "$base/xna40.msi"))))
// The catalog names some .msi packages install_exe.
assertEquals(Support.READY, support(component("XLiveRedist",
step("install_exe", "url" to "$base/XLiveRedist.msi", "file_name" to "XLiveRedist1.2.0238.msi"))))
assertEquals(Support.READY, support(component("msxml3", step("delete_dlls", "dest" to "win32"),
@@ -33,12 +32,10 @@ class WinComponentsSupportTest {
}
@Test fun installerWrappersInstallHere() {
// A WiX bundle, a self-extracting cabinet or 7-Zip archive: the packages inside are laid out.
assertEquals(Support.READY, support(component("vcredist2022",
step("install_exe", "url" to "$base/vcredist2022__VC_redist.x86.exe", "file_name" to "VC_redist.x86.exe"),
step("install_exe", "url" to "$base/vcredist2022__VC_redist.x64.exe", "file_name" to "VC_redist.x64.exe"),
step("override_dll", "dll" to "vcruntime140", "type" to "native,builtin"))))
// .NET Framework: "uninstall Wine Mono", the Windows version, the installer, a registry key.
assertEquals(Support.READY, support(component("dotnet40",
step("uninstall", "file_name" to "Wine Mono"), step("set_windows", "version" to "win7"),
step("install_exe", "url" to "https://download.microsoft.com/x/dotNetFx40_Full_x86_x64.exe", "file_name" to "dotNetFx40_Full_x86_x64.exe"),
@@ -48,7 +45,6 @@ class WinComponentsSupportTest {
}
@Test fun nestedCatalogKeysAreRead() {
// A few .NET entries keep url and file_name under "environment".
val nested = WinComponents.Step("install_exe", JSONObject().put("environment", JSONObject()
.put("WINEDLLOVERRIDES", "fusion=b").put("file_name", "ndp48-x86-x64-allos-enu.exe")
.put("url", "https://download.visualstudio.microsoft.com/x/ndp48-x86-x64-allos-enu.exe")))
@@ -67,14 +63,11 @@ class WinComponentsSupportTest {
@Test fun recordedInstallersInstallHere() {
val snapshot = "https://github.com/Droid-Deck/DroidDeck-Components/releases/download/component-snapshots-v1/K-Lite.snapshot.json"
// A setup program with a recording of its result installs from the recording.
val klite = WinComponents.Component("K-Lite", "", "", "ready", emptyList(),
listOf(step("install_exe", "url" to "$base/K-Lite.exe", "file_name" to "K-Lite_1960.exe")), snapshot)
assertEquals(Support.READY, WinComponents.support(klite, mapOf(klite.name to klite)))
// Only a recording on the release counts.
val elsewhere = WinComponents.Component("K-Lite", "", "", "ready", emptyList(), klite.steps, "http://example.com/K-Lite.snapshot.json")
assertEquals(Support.NEEDS_INSTALLER, WinComponents.support(elsewhere, mapOf(elsewhere.name to elsewhere)))
// Its prerequisites still have to be installable.
val sp1 = WinComponents.Component("dotnet20sp1", "", "", "ready", listOf("dotnet20"), emptyList(), snapshot.replace("K-Lite", "dotnet20sp1"))
val base20 = WinComponents.Component("dotnet20", "", "", "ready", emptyList(),
listOf(step("install_exe", "url" to "$base/dotnet20__dotnetfx.exe", "file_name" to "dotnetfx.exe")))
@@ -82,7 +75,6 @@ class WinComponentsSupportTest {
}
@Test fun setupProgramsStillWait() {
// NSIS / InnoSetup installers hold no package to lay out.
assertEquals(Support.NEEDS_INSTALLER, support(component("K-Lite",
step("install_exe", "url" to "$base/K-Lite.exe", "file_name" to "K-Lite_1960.exe"))))
assertEquals(Support.NEEDS_INSTALLER, support(component("plain", step("install_msi", "url" to "http://example.com/a.msi"))))
@@ -12,7 +12,6 @@ class FlathubApiTest {
}
@Test fun refsReadAsWords() {
// The words come from string resources; stand in for them with their English.
val english = mapOf(
R.string.flatpakmgr_ref_runtime_branch to "%1\$s runtime %2\$s",
R.string.flatpakmgr_ref_graphics_drivers to "graphics drivers",
@@ -10,7 +10,6 @@ import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/** The rules that keep a cloud sync from replacing real saves. (Robolectric for org.json.) */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class CloudPlanTest {
@@ -42,20 +41,16 @@ class CloudPlanTest {
@Test fun theSideThatChangedWins() {
val base = mapOf("s" to Entry("a", "a", 1000))
// Only local changed: up sends it, down leaves it.
assertEquals(listOf("s"), CloudPlan.up(mapOf("s" to Local("b")), mapOf("s" to Remote("a", 1000)), base).transfer)
assertTrue(CloudPlan.down(mapOf("s" to Local("b")), mapOf("s" to Remote("a", 1000)), base).transfer.isEmpty())
// Only the cloud changed: down takes it, up leaves it.
assertEquals(listOf("s"), CloudPlan.down(mapOf("s" to Local("a")), mapOf("s" to Remote("c", 9000)), base).transfer)
assertTrue(CloudPlan.up(mapOf("s" to Local("a")), mapOf("s" to Remote("c", 9000)), base).transfer.isEmpty())
// The same bytes on both sides: nothing moves.
assertEquals(listOf("s"), CloudPlan.up(mapOf("s" to Local("c")), mapOf("s" to Remote("c", 9000)), base).same)
}
@Test fun timesAloneDecideWhenTheServiceGivesNoHash() {
val base = mapOf("s" to Entry("a", null, 1000))
assertEquals(listOf("s"), CloudPlan.down(mapOf("s" to Local("a")), mapOf("s" to Remote(null, 60_000)), base).transfer)
// Within two seconds of the baseline: the same cloud copy.
assertTrue(CloudPlan.down(mapOf("s" to Local("a")), mapOf("s" to Remote(null, 2500)), base).transfer.isEmpty())
}
@@ -6,7 +6,6 @@ import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
/** A store's save-location template, made concrete inside the game's prefix (Bannerlator's cases). */
class CloudSavePathsTest {
private val root = Files.createTempDirectory("cloud").toFile()
private val prefix = File(root, "compatdata/3785150007/pfx").apply { mkdirs() }
@@ -45,7 +44,6 @@ class CloudSavePathsTest {
CloudSavePaths.epic("{UserSavedGames}/Studio/{EpicId}/{AppName}", prefix, install, "acc", "app")!!.path)
assertEquals(File(profile, "Documents/G").path, CloudSavePaths.epic("{UserDir}/G", prefix, install, "acc", "app")!!.path)
assertNull(CloudSavePaths.epic("{Nope}/G", prefix, install, "acc", "app"))
// Epic's folder names are matched by letters and digits alone when that names exactly one.
File(profile, "AppData/Local/My-Game").mkdirs()
assertEquals(File(profile, "AppData/Local/My-Game").path, CloudSavePaths.epic("{AppData}/MyGame", prefix, install, "acc", "app")!!.path)
}
@@ -10,7 +10,6 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
/** A sync against a cloud held in memory: the baseline gate, conflicts, backups and the no-prefix deferral. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class CloudSavesTest {
@@ -59,7 +58,6 @@ class CloudSavesTest {
assertEquals(1, up.conflicts)
assertEquals("cloud v2", String(cloud.files.getValue("slot0.sav").first))
assertEquals(listOf("slot0.sav"), CloudSaves.conflicts(app, Store.GOG, game))
// Keep local resolves it.
CloudSaves.upWith(app, Store.GOG, game, dir, cloud, force = true)
assertEquals("local v2", String(cloud.files.getValue("slot0.sav").first))
assertTrue(CloudSaves.conflicts(app, Store.GOG, game).isEmpty())
@@ -70,17 +68,14 @@ class CloudSavesTest {
val folder = File(StoreInstallRoot.storeDir(StoreInstallRoot.internalRoot(app), Store.GOG), "ELDERBORN-mark").apply { mkdirs() }
File(folder, "ELDERBORN.exe").writeText("MZ")
StoreGameSidecar(Store.GOG, gameId, "ELDERBORN", "ELDERBORN.exe").write(folder)
// A save location the store gave, but no prefix yet: the upload cannot run, the mark stays.
com.droiddeck.launcher.stores.gog.GogPrefs.get(app).edit().putString("cloud_template_$gameId", "<?SAVED_GAMES?>/ELDERBORN").apply()
CloudSaves.markDirty(app, Store.GOG, gameId)
assertTrue(CloudSaves.dirty(app).contains(Store.GOG to gameId))
val first = CloudSaves.uploadDirty(app, Store.GOG, gameId, "session-end")!!
assertEquals("no-prefix", first.reason)
assertTrue(CloudSaves.dirty(app).contains(Store.GOG to gameId))
// Recovery waits while a session runs.
CloudSaves.uploadAllDirty(app, "recovery", running = true)
assertTrue(CloudSaves.dirty(app).contains(Store.GOG to gameId))
// The store has no cloud saves for it: a final skip, the mark goes; a second trigger finds nothing.
com.droiddeck.launcher.stores.gog.GogPrefs.get(app).edit().putString("cloud_template_$gameId", "").apply()
assertEquals("no-cloud-saves", CloudSaves.uploadDirty(app, Store.GOG, gameId, "exit")!!.reason)
assertTrue(CloudSaves.dirty(app).none { it.second == gameId })
@@ -7,7 +7,6 @@ import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Test
/** The name match that finds a store game on Steam and HowLongToBeat, and how its facts read. */
class GameFactsTest {
private val saved = Locale.getDefault()
@@ -42,7 +41,6 @@ class GameFactsTest {
val results = listOf("Hades II", "The Witcher 3: Wild Hunt — Songs of the Past", "Hades", "Hades")
assertEquals(2, TitleMatch.pick("Hades", results.withIndex().toList()) { listOf(it.value) }?.index)
assertNull(TitleMatch.pick("Hades", listOf("Hades II", "Hadesville")) { listOf(it) })
// An alias counts as a name.
assertEquals("x", TitleMatch.pick("The Witcher III: Wild Hunt", listOf("x" to "The Witcher 3: Wild Hunt, The Witcher III: Wild Hunt")) { it.second.split(',') }?.first)
}
@@ -4,18 +4,15 @@ import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Test
/** The Installed tab draws what its count counts: the installs on disk. */
class InstalledCardsTest {
private fun install(store: Store, id: String, title: String) =
InstalledStoreGame(StoreGameSidecar(store, id, title, "game.exe", cover = "https://img/$id.jpg"), File("/x/$id"))
@Test fun everyInstallIsACardWhetherOrNotTheLibraryHasLoaded() {
val installed = listOf(install(Store.GOG, "1", "DOOM + DOOM II"), install(Store.GOG, "2", "DOOM I Enhanced"), install(Store.EPIC, "e", "DOOMBLADE"))
// Library not loaded: cards from the sidecars.
val bare = installedCards(Store.GOG, installed, emptyList())
assertEquals(listOf("DOOM + DOOM II", "DOOM I Enhanced"), bare.map { it.title })
assertEquals("https://img/1.jpg", bare.first().tallImageUrl)
// Loaded: the library item wins, by id, or by title when the ids differ.
val library = listOf(
CatalogItem(Store.GOG, "1", "DOOM + DOOM II", imageUrl = "wide1", owned = true),
CatalogItem(Store.GOG, "999", "DOOM I Enhanced", imageUrl = "wide2", owned = true),
@@ -9,7 +9,6 @@ import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/** Mature means what the store's own ratings or tags say; a title without them stays visible. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class MatureContentTest {
@@ -20,7 +19,6 @@ class MatureContentTest {
assertTrue(GogStoreCatalog.isMature(gog("""{"name":"gogRating","ageRating":"18"}""", "")))
assertTrue(GogStoreCatalog.isMature(gog("""{"name":"pegiRating","ageRating":"12"}""", """{"name":"NSFW","slug":"nsfw"}""")))
assertFalse(GogStoreCatalog.isMature(gog("""{"name":"esrbRating","ageRating":"13"},{"name":"uskRating","ageRating":"16"}""", """{"name":"Puzzle","slug":"puzzle"}""")))
// No rating data at all: visible.
assertFalse(GogStoreCatalog.isMature(JSONObject("""{"id":"2","title":"U"}""")))
}
@@ -17,7 +17,6 @@ import java.security.SecureRandom
import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec
/** The stores' sign-in files sealed at rest; a plain key stands in for the AndroidKeyStore. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class StoreAccountsCipherTest {
@@ -44,7 +43,6 @@ class StoreAccountsCipherTest {
assertEquals("AES/GCM", envelope.getString("alg"))
assertFalse(envelope.toString().contains("secret"))
assertEquals(creds.toString(), CredentialCipher.open(envelope, fake))
// A fresh IV every time.
assertFalse(envelope.getString("iv") == CredentialCipher.seal(creds.toString(), fake).getString("iv"))
}
@@ -87,7 +85,6 @@ class StoreAccountsCipherTest {
@Test fun aFileSealedUnderALostKeyReadsAsSignedOutAndIsDeleted() {
StoreAccounts.write(app, Store.AMAZON, creds)
// Data cleared, or a backup restored on another device: the Keystore key is a new one.
val other = newKey()
StoreAccounts.keys = CredentialCipher.KeyProvider { other }
assertNull(StoreAccounts.read(app, Store.AMAZON))
@@ -108,7 +105,6 @@ class StoreAccountsCipherTest {
assertEquals(creds.toString(), StoreAccounts.read(app, Store.EPIC).toString())
assertTrue(StoreAccounts.keystoreFailed)
// The next start, on a Keystore that works.
StoreAccounts.keys = fake
StoreAccounts.keystoreFailed = false
StoreAccounts.encryptAll(app)
@@ -123,7 +119,6 @@ class StoreAccountsCipherTest {
assertNull(StoreAccounts.read(app, Store.GOG))
}
/** A Keystore whose key is there but which fails to hand it over [failures] times first. */
private class Flaky(private val key: SecretKey, var failures: Int, private val error: () -> Exception) : CredentialCipher.KeyProvider {
override fun key(): SecretKey = key
override fun existing(): SecretKey { if (failures > 0) { failures--; throw error() }; return key }
@@ -142,10 +137,8 @@ class StoreAccountsCipherTest {
assertNull(StoreAccounts.read(app, Store.EPIC))
assertTrue(StoreAccounts.isUnavailable(Store.EPIC))
assertEquals(sealed, file(Store.EPIC).readText())
// Still signed in for the page: no sign-in card, and an action says why it failed.
assertEquals("Epic sign-in could not be read: try again.", StoresState.notSignedInLine(Store.EPIC))
// The next access, once the Keystore answers.
assertEquals(creds.toString(), StoreAccounts.read(app, Store.EPIC).toString())
assertFalse(StoreAccounts.isUnavailable(Store.EPIC))
assertEquals("Someone", StoreAccounts.signedInAs(app, Store.EPIC))
@@ -11,7 +11,6 @@ import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/** Sizes kept per version, and a refresh that touches only the cards that changed. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class StoreCacheTest {
@@ -20,7 +19,6 @@ class StoreCacheTest {
@Test fun aSizeIsKeptForItsVersionAndAskedAgainForANewOne() {
val cache = SizeCache.forStore(dir, Store.EPIC)
cache.put("Metalstorm", "1.0.3", 4_400_000_000L)
// Read back from disk by a new instance, as the next app start does.
val again = SizeCache.forStore(dir, Store.EPIC)
assertEquals(4_400_000_000L, again.get("Metalstorm", "1.0.3"))
assertNull(again.get("Metalstorm", "1.0.4"))
@@ -36,14 +34,11 @@ class StoreCacheTest {
val a = CatalogItem(Store.GOG, "1", "A", imageUrl = "x", owned = true)
val b = CatalogItem(Store.GOG, "2", "B", imageUrl = "y", owned = true)
val old = listOf(a, b)
// Nothing changed: the very list shown stays.
assertSame(old, mergeItems(old, listOf(a.copy(), b.copy())))
// One card changed: the other is the same object, the changed one is new.
val merged = mergeItems(old, listOf(a.copy(), b.copy(title = "B2")))
assertSame(a, merged[0])
assertNotSame(b, merged[1])
assertEquals("B2", merged[1].title)
// A first load is the new list as it is.
val fresh = listOf(a)
assertSame(fresh, mergeItems(null, fresh))
}
@@ -9,7 +9,6 @@ import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/** Under Robolectric for a real org.json; the plain unit-test android.jar stubs it out. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class StoreGameSidecarTest {
@@ -37,11 +36,9 @@ class StoreGameSidecarTest {
@Test fun defaultsWhenFieldsAreAbsent() {
val back = StoreGameSidecar.parse("""{"store":"gog","id":"1","title":"T","exe":"bin\\game.exe","addToSteam":false}""")!!
// An older sidecar's Steam switch is read past, not acted on.
assertEquals("bin/game.exe", back.exe)
assertNull(back.launcher)
assertTrue(back.args.isEmpty())
// No state field = an earlier build's finished install.
assertTrue(back.isInstalled)
}
@@ -53,9 +50,7 @@ class StoreGameSidecarTest {
val back = StoreGameSidecar.parse(set.toJson().toString())!!
assertEquals(EpicOptions(eos = true, offline = true), back.epic)
assertFalse(back.epic.wantsCode)
// A sidecar from before the choices existed reads as the defaults.
assertEquals(EpicOptions(), StoreGameSidecar.parse("""{"store":"epic","id":"m","title":"M","exe":"M.exe"}""")!!.epic)
// An earlier build's overlay field is read past.
assertEquals(EpicOptions(), StoreGameSidecar.parse("""{"store":"epic","id":"m","title":"M","exe":"M.exe","epic":{"v":2,"eos":true,"offline":false,"overlay":true}}""")!!.epic)
}
@@ -64,12 +59,10 @@ class StoreGameSidecarTest {
StoreGameSidecar(Store.EPIC, "m", "Metalstorm", "Metalstorm.exe", launcher = ".droiddeck-launch.bat").write(folder)
val written = StoreGameSidecar.updateEpic(folder) { it.copy(offline = true) }!!
assertTrue(written.epic.offline)
// What the Steam-launch helper reads: the file itself.
val onDisk = org.json.JSONObject(java.io.File(folder, StoreGameSidecar.FILE_NAME).readText())
assertTrue(onDisk.getJSONObject("epic").getBoolean("offline"))
assertTrue(onDisk.getJSONObject("epic").getBoolean("eos"))
assertFalse(onDisk.getJSONObject("epic").has("overlay"))
// Everything else in it stays.
assertEquals(".droiddeck-launch.bat", StoreGameSidecar.read(folder)!!.launcher)
assertEquals(null, StoreGameSidecar.updateEpic(java.io.File(folder, "missing")) { it })
}
@@ -89,7 +82,6 @@ class StoreGameSidecarTest {
val back = StoreGameSidecar.parse(started.toJson().toString())!!
assertFalse(back.isInstalled)
assertEquals("", back.exe)
// A finished one must still name its exe.
assertNull(StoreGameSidecar.parse("""{"store":"gog","id":"1","title":"T","exe":""}"""))
assertTrue(StoreGameSidecar.parse(back.copy(exe = "Metalstorm.exe", state = StoreGameSidecar.STATE_INSTALLED).toJson().toString())!!.isInstalled)
}
@@ -98,7 +90,6 @@ class StoreGameSidecarTest {
assertNull(StoreGameSidecar.parse("not json"))
assertNull(StoreGameSidecar.parse("""{"store":"steam","id":"1","title":"T","exe":"a.exe"}"""))
assertNull(StoreGameSidecar.parse("""{"store":"gog","id":"","title":"T","exe":"a.exe"}"""))
// An exe outside the folder is not trusted: a sidecar must not point the shortcut anywhere.
assertNull(StoreGameSidecar.parse("""{"store":"gog","id":"1","title":"T","exe":"../other/a.exe"}"""))
assertNull(StoreGameSidecar.parse("""{"store":"gog","id":"1","title":"T","exe":"/abs/a.exe"}"""))
assertNull(StoreGameSidecar.parse("""{"store":"gog","id":"1","title":"T","exe":"C:\\a.exe"}"""))
@@ -116,10 +107,7 @@ class StoreGameSidecarTest {
assertTrue(text.contains("cd /d \"%~dp0Binaries\\Win64\"\r\n"))
assertTrue(text.contains("set \"FOO=bar\"\r\n"))
assertTrue(text.contains("\r\n\"%~dp0Binaries\\Win64\\Celeste.exe\" -EpicPortal -epicusername=\"Some One\"\r\n"))
// Epic reads the one-shot exchange code the app leaves beside the launcher, then deletes it.
assertTrue(text.contains("set /p DD_X=<\"%~dp0.droiddeck-epic-code\""))
// The code goes on the command line only: the variable is cleared on the very line that
// starts the game (cmd has already expanded it there), so the game inherits none of it.
assertTrue(text.contains("set \"DD_X=\" & \"%~dp0Binaries\\Win64\\Celeste.exe\" -EpicPortal -epicusername=\"Some One\" -AUTH_LOGIN=unused -AUTH_PASSWORD=%DD_X% -AUTH_TYPE=exchangecode\r\n"))
assertFalse(text.contains("AUTH="))
assertFalse(text.contains("DD_AUTH"))
@@ -11,8 +11,8 @@ import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowStatFs
/** Where a store game goes: internal storage unless the user picks a card, and back to its own folder on a rerun. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class StoreInstallRootTest {
@@ -22,7 +22,6 @@ class StoreInstallRootTest {
val card = File(app.filesDir, "fake-card/steam").apply { mkdirs() }
SessionPrefs.setGameStorage(app, card.path, "Card")
assertEquals(File(LinuxRuntime.rootDir(app), "root/Games/Stores").absolutePath, StoreInstallRoot.installRoot(app).absolutePath)
// The library's Games folder is still scanned, for installs an earlier build put there.
assertTrue(StoreInstallRoot.roots(app).any { it.absolutePath == File(card, "Games").absolutePath })
assertFalse(StoreInstallRoot.targets(app).first().removable)
}
@@ -44,9 +43,7 @@ class StoreInstallRootTest {
File(half, "Metalstorm.exe").writeText("MZ")
assertFalse(StoreInstallRoot.isFinished(half))
assertTrue(StoreInstallRoot.unfinished(app).any { it.store == Store.EPIC && it.id == null && it.folder.absolutePath == half.absolutePath })
// Install again, even with another root picked: the same folder, no duplicate.
assertEquals(half.absolutePath, StoreInstallRoot.folderFor(app, Store.EPIC, "abc", "Metalstorm", File(app.filesDir, "card/Games")).absolutePath)
// Begun and finished: the folder becomes a game.
StoreInstalls.begin(half, Store.EPIC, "abc", "Metalstorm", null, null)
assertTrue(StoreInstallRoot.unfinished(app).any { it.id == "abc" })
StoreGameSidecar(Store.EPIC, "abc", "Metalstorm", "Metalstorm.exe").write(half)
@@ -59,4 +56,87 @@ class StoreInstallRootTest {
assertTrue(dir.absolutePath.startsWith(app.cacheDir.absolutePath))
assertEquals("a_b_c", dir.name)
}
@Test fun estimatedBytesNeededUsesKnownInstallSizeForAllStores() {
val item = CatalogItem(Store.EPIC, "game1", "Game 1", imageUrl = null, owned = true, sizeBytes = 10_000_000L)
assertEquals(10_000_000L, StoreInstallRoot.estimatedBytesNeeded(item))
val gogItem = CatalogItem(Store.GOG, "game2", "Game 2", imageUrl = null, owned = true, sizeBytes = 10_000_000L)
assertEquals(10_000_000L, StoreInstallRoot.estimatedBytesNeeded(gogItem))
}
@Test fun checkStorageReportsEnoughWhenSpaceIsUnknownOrAvailable() {
val zeroItem = CatalogItem(Store.EPIC, "game1", "Game 1", imageUrl = null, owned = true, sizeBytes = 0L)
val check = StoreInstallRoot.checkStorage(app, zeroItem, StoreInstallRoot.internalRoot(app))
assertTrue(check.enough)
}
@Test fun availableBytesUsesNearestExistingAncestorWithoutCreatingDirectories() {
val existing = File(app.filesDir, "storage-probe").apply { mkdirs() }
val missing = File(existing, "not-created/another-level/game")
ShadowStatFs.registerStats(existing.path, 1024, 100, 100)
assertTrue(StoreInstallRoot.availableBytes(missing) > 0L)
assertFalse(File(existing, "not-created").exists())
}
@Test fun epicDefersFullSizeChecksToItsManifestDeltaForResume() {
val item = CatalogItem(Store.EPIC, "large", "Large", imageUrl = null, owned = true, sizeBytes = Long.MAX_VALUE)
val check = StoreInstallRoot.checkStorage(app, item, StoreInstallRoot.internalRoot(app))
assertTrue(check.enough)
assertEquals(Long.MAX_VALUE, check.requiredBytes)
}
@Test fun gogAndAmazonResumeChecksUseTheExistingVolumeAndDeferRemainingWork() {
val card = File(app.filesDir, "resume-card").apply { mkdirs() }
SessionPrefs.setGameStorage(app, card.path, "Card")
for (store in listOf(Store.GOG, Store.AMAZON)) {
val item = CatalogItem(store, "resume-${store.id}", "Partial ${store.id}", imageUrl = null, sizeBytes = Long.MAX_VALUE)
val folder = File(StoreInstallRoot.storeDir(File(card, "Games"), store), StoreInstallRoot.folderName(item.title, item.id)).apply { mkdirs() }
StoreInstalls.begin(folder, store, item.id, item.title, null, null)
val check = StoreInstallRoot.checkStorage(app, item, StoreInstallRoot.internalRoot(app))
assertTrue(check.enough)
assertEquals(StoreInstallRoot.availableBytes(folder), check.availableBytes)
assertEquals(folder, StoreInstallRoot.folderFor(app, store, item.id, item.title))
}
}
@Test fun freshGogAndAmazonStillRejectInsufficientCatalogSpace() {
StoreInstallRoot.internalRoot(app).mkdirs()
ShadowStatFs.registerStats(StoreInstallRoot.internalRoot(app).path, 1024, 100, 100)
for (store in listOf(Store.GOG, Store.AMAZON)) {
val item = CatalogItem(store, "too-large-${store.id}", "Too large ${store.id}", imageUrl = null, sizeBytes = Long.MAX_VALUE)
assertFalse(StoreInstallRoot.checkStorage(app, item, StoreInstallRoot.internalRoot(app)).enough)
}
}
@Test fun measuredZeroRejectsFreshGogAndAmazonRatherThanBeingUnknown() {
val root = File(app.filesDir, "zero-space").apply { mkdirs() }
ShadowStatFs.registerStats(root.path, 1024, 0, 0)
val missing = File(root, "not-created/game")
assertEquals(0L, StoreInstallRoot.availableBytes(missing))
assertFalse(File(root, "not-created").exists())
for (store in listOf(Store.GOG, Store.AMAZON)) {
val item = CatalogItem(store, "zero-${store.id}", "Zero ${store.id}", imageUrl = null, sizeBytes = 1L)
val check = StoreInstallRoot.checkStorage(app, item, missing)
assertFalse(check.enough)
assertEquals(0L, check.availableBytes)
}
}
@Test fun failedProbesAreUnknownAndDoNotCreateOrWriteToTargets() {
val root = File(app.filesDir, "read-only-probe").apply { mkdirs() }
val missing = File(root, "not-created/game")
val fail: (File) -> Long = { throw java.io.IOException("unavailable") }
assertEquals(-1L, StoreInstallRoot.probeAvailableBytes(missing, fail, fail))
assertEquals(-1L, StoreInstallRoot.probeAvailableBytes(missing, fail, { 0L }))
assertEquals(42L, StoreInstallRoot.probeAvailableBytes(missing, fail, { 42L }))
assertEquals(0L, StoreInstallRoot.probeAvailableBytes(missing, { 0L }, fail))
assertFalse(File(root, "not-created").exists())
assertTrue(root.listFiles().orEmpty().isEmpty())
assertFalse(StoreInstallRoot.insufficientSpace(1L, -1L))
assertTrue(StoreInstallRoot.insufficientSpace(1L, 0L))
assertFalse(StoreInstallRoot.insufficientSpace(1L, 1L))
assertFalse(StoreInstallRoot.insufficientSpace(0L, 0L))
}
}
@@ -4,7 +4,6 @@ import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Test
/** Store lines reach the Downloads log and logcat; nothing in them may carry a token. */
class StoreLogTest {
@Test fun gogSecureLinkKeepsOnlyTheHost() {
val line = "gog: window 32 in_flight 3 https://gog-cdn-fastly.gog.com/token=nva=1791500000~dirs=/content-system/v2/store/1207658924~token=0a1b2c3d4e5f/content-system/v2/store/1207658924/ab/cd/abcdef 12.1 MB/s"
@@ -24,7 +23,6 @@ class StoreLogTest {
assertEquals("refresh access_token=… refresh_token: '…' code=… hdnts=… __token__=…", out)
assertEquals("Authorization: …", StoreLog.redactLine("Authorization: Bearer eyJhbGciOi"))
assertEquals("""{"access_token":"…","expires_in":7200}""", StoreLog.redactLine("""{"access_token":"eyJ.abc","expires_in":7200}"""))
// Ordinary numbers stay: "HTTP code 403" has no separator to read as a secret.
assertEquals("HTTP code 403 from https://api.gog.com/products/…", StoreLog.redactLine("HTTP code 403 from https://user:pw@api.gog.com/products/1?expand=x"))
}
}
@@ -0,0 +1,43 @@
package com.droiddeck.launcher.stores.amazon
import java.io.File
import java.security.MessageDigest
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.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowStatFs
import com.droiddeck.launcher.stores.StoreInstallRoot
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class AmazonResumeSpaceTest {
@Test fun remainingWorkRejectsMeasuredZeroButNotUnknownSpace() {
val root = File(RuntimeEnvironment.getApplication().filesDir, "amazon-zero").apply { mkdirs() }
ShadowStatFs.registerStats(root.path, 1024, 0, 0)
val files = listOf(AmazonManifest.ManifestFile("missing", 4, 0, null))
val needed = AmazonDownloadManager.remainingInstallBytes(files, root)
assertEquals(4L, needed)
assertTrue(StoreInstallRoot.insufficientSpace(needed, StoreInstallRoot.availableBytes(root)))
assertFalse(StoreInstallRoot.insufficientSpace(needed, StoreInstallRoot.SPACE_UNKNOWN))
}
@Test fun remainingSpaceExcludesVerifiedFilesButIncludesCorruptAndPartialFiles() {
val root = File(RuntimeEnvironment.getApplication().filesDir, "amazon-resume").apply { mkdirs() }
val data = byteArrayOf(1, 2, 3, 4)
val hash = MessageDigest.getInstance("SHA-256").digest(data)
val files = listOf("good", "corrupt", "partial", "missing").map {
AmazonManifest.ManifestFile(it, 4, 0, hash)
}
File(root, "good").writeBytes(data)
File(root, "corrupt").writeBytes(ByteArray(4))
File(root, "partial").writeBytes(byteArrayOf(1))
assertEquals(12L, AmazonDownloadManager.remainingInstallBytes(files, root))
for (file in files) File(root, file.unixPath()).writeBytes(data)
assertEquals(0L, AmazonDownloadManager.remainingInstallBytes(files, root))
}
}
@@ -6,23 +6,19 @@ import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
/** The Downloads row reads the active stage's own progress, and which stages are behind it. */
class DownloadEntryTest {
private val base = DownloadEntry(Store.EPIC, "doomblade", "DOOMBLADE", state = DownloadState.RUNNING)
@Test fun downloadRunsOnBytesAndInstallOnItsOwnCount() {
val dl = base.copy(stage = DownloadStage.DOWNLOAD, bytesDone = 50, bytesTotal = 200)
assertEquals(0.25f, dl.stageFraction, 0.001f)
// Past Download the bytes no longer drive the bar; the stage's own count does.
val inst = dl.copy(stage = DownloadStage.INSTALL, stageDone = 30, stageTotal = 40, stageItems = 3, stageItemsTotal = 4)
assertEquals(0.75f, inst.stageFraction, 0.001f)
assertEquals(75, inst.percent)
// Nothing counted yet: unknown, not empty and not full.
assertEquals(-1f, base.copy(stage = DownloadStage.INSTALL).stageFraction, 0f)
}
@Test fun passedStagesComeFromTheBitsNotTheOrder() {
// Epic checks files before it fetches: Verify is behind Download there.
val e = base.copy(stage = DownloadStage.DOWNLOAD, stagesPassed = (1 shl DownloadStage.MANIFEST.ordinal) or (1 shl DownloadStage.VERIFY.ordinal))
assertTrue(e.passed(DownloadStage.VERIFY))
assertFalse(e.passed(DownloadStage.INSTALL))
@@ -4,7 +4,6 @@ import com.droiddeck.launcher.stores.Store
import org.junit.Assert.assertEquals
import org.junit.Test
/** The notification's line: what the Downloads row says, on one line. */
class DownloadNotificationTextTest {
private val base = DownloadEntry(Store.EPIC, "m", "Metalstorm", state = DownloadState.RUNNING)
@@ -0,0 +1,140 @@
package com.droiddeck.launcher.stores.download
import android.content.Context
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.*
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import org.junit.After
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.json.JSONArray
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowStatFs
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class DownloadQueueRetryTest {
private val app get() = RuntimeEnvironment.getApplication()
@After fun cleanRows() { DownloadQueue.dismissFinished(); StoreSizes.known.clear() }
private fun awaitFailure(key: String, error: String) {
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (System.nanoTime() < until) {
val entry = DownloadQueue.entry(key)
if (entry?.state == DownloadState.FAILED && entry.error == error) return
Thread.sleep(10)
}
fail("Expected failed real job: ${DownloadQueue.entry(key)}")
}
@Test fun storageRetryRechecksThenRunsTheRealBackendAndNormalRetryStillWorks() {
StoreInstallRoot.internalRoot(app).mkdirs()
ShadowStatFs.registerStats(StoreInstallRoot.internalRoot(app).path, 1024, 100, 100)
val item = CatalogItem(Store.GOG, "preflight-retry", "Preflight retry", imageUrl = null, sizeBytes = Long.MAX_VALUE)
val runs = AtomicInteger()
var lastTarget: File? = null
val previous = StoresState.backend(Store.GOG)
val backend = object : StoreBackend {
override val store = Store.GOG
override fun signIn(context: Context) {}
override fun signOut(context: Context) {}
override fun syncLibrary(context: Context, force: Boolean) {}
override fun loadShelves(context: Context, force: Boolean) {}
override fun uninstall(context: Context, game: InstalledStoreGame) {}
override fun install(context: Context, item: CatalogItem, root: File) {
lastTarget = root
DownloadQueue.enqueue(context, DownloadEntry(item.store, item.id, item.title)) {
object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? {
throw IllegalStateException("backend-${runs.incrementAndGet()}")
}
override fun cancel(deleteFiles: Boolean) {}
}
}
}
}
StoresState.register(backend)
try {
StoresState.install(app, item)
assertEquals(DownloadState.FAILED, DownloadQueue.entry(item.key)?.state)
DownloadQueue.retry(app, item.key)
assertEquals(DownloadState.FAILED, DownloadQueue.entry(item.key)?.state)
assertEquals(0, runs.get())
StoreSizes.known[item.key] = 1
DownloadQueue.retry(app, item.key)
awaitFailure(item.key, "backend-1")
DownloadQueue.retry(app, item.key)
awaitFailure(item.key, "backend-2")
DownloadQueue.clear(app, item.key)
assertNull(DownloadQueue.entry(item.key))
// A card resume (including the restored paused path) must retain its real target.
val card = File(app.filesDir, "retry-card").apply { mkdirs() }
SessionPrefs.setGameStorage(app, card.path, "Card")
val target = File(card, "Games")
val folder = File(StoreInstallRoot.storeDir(target, item.store), StoreInstallRoot.folderName(item.title, item.id)).apply { mkdirs() }
StoreInstalls.begin(folder, item.store, item.id, item.title, null, null)
StoreSizes.known[item.key] = Long.MAX_VALUE
StoresState.unfinished = StoreInstallRoot.unfinished(app)
DownloadQueue.holdPaused(item.key)
StoresState.requestInstall(app, item)
assertEquals(target, lastTarget)
assertEquals(DownloadState.PAUSED, DownloadQueue.entry(item.key)?.state)
assertEquals(2, runs.get())
val saved = File(app.filesDir, "store-queue.json")
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
var correctSavedRoot = false
while (!correctSavedRoot && System.nanoTime() < until) {
correctSavedRoot = runCatching {
val rows = JSONArray(saved.readText())
(0 until rows.length()).any { i ->
val row = rows.getJSONObject(i)
row.getJSONObject("item").getString("id") == item.id &&
row.getString("root") == target.absolutePath && row.getBoolean("paused")
}
}.getOrDefault(false)
if (!correctSavedRoot) Thread.sleep(10)
}
assertTrue("Paused saved queue must remember the existing card root", correctSavedRoot)
DownloadQueue.clear(app, item.key)
} finally {
if (previous != null) StoresState.register(previous)
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
StoresState.unfinished = emptyList()
}
}
@Test fun preflightClearRemovesTheRowWithoutRunningItsRetry() {
val entry = DownloadEntry(Store.AMAZON, "clear-preflight", "Clear")
DownloadQueue.recordFailed(app, entry, "storage") { fail("Clear must not retry") }
DownloadQueue.clear(app, entry.key)
assertNull(DownloadQueue.entry(entry.key))
}
@Test fun heldPausedBackendRestoresAndResumesWithoutAPlaceholder() {
val entry = DownloadEntry(Store.GOG, "restored-paused", "Paused")
val ran = CountDownLatch(1)
DownloadQueue.holdPaused(entry.key)
DownloadQueue.enqueue(app, entry) {
object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? {
ran.countDown()
throw IllegalStateException("restored")
}
override fun cancel(deleteFiles: Boolean) {}
}
}
assertEquals(DownloadState.PAUSED, DownloadQueue.entry(entry.key)?.state)
assertEquals(1L, ran.count)
DownloadQueue.resume(app, entry.key)
assertTrue(ran.await(5, TimeUnit.SECONDS))
awaitFailure(entry.key, "restored")
}
}
@@ -0,0 +1,107 @@
package com.droiddeck.launcher.stores.epic
import java.io.File
import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class EpicAdaptivePlanTest {
@get:Rule val temp = TemporaryFolder()
private val mib = 1024L * 1024
private val gib = 1024 * mib
private fun file(name: String, size: Long) = EpicDownloadManager.FileInfo().apply {
filename = name
var left = size
while (left > 0) {
val part = minOf(left, Int.MAX_VALUE.toLong())
parts.add(EpicDownloadManager.ChunkPart().apply { this.size = part.toInt() })
left -= part
}
}
@Test fun netPeakCreditsEachOldCopyAtItsSwapAndLargestReplacedIgnoresFreshFiles() {
val files = listOf(file("a", 10 * gib), file("b", 2 * gib), file("c", 4 * gib))
val old = mapOf("a" to 9 * gib, "c" to 5 * gib)
// Running Σ(new − old): +1, +3, +2 GiB.
assertEquals(3 * gib, EpicDownloadManager.settledNetPeak(files, old))
assertEquals(10 * gib, EpicDownloadManager.largestReplacedFile(files, old))
assertEquals(16 * gib, EpicDownloadManager.settledNetPeak(files, emptyMap()))
assertEquals(0L, EpicDownloadManager.largestReplacedFile(files, emptyMap()))
assertEquals(0L, EpicDownloadManager.largestReplacedFile(files, mapOf("b" to 0L)))
}
@Test fun cacheBudgetIsHalfTheHeadroomCappedAndDefaultsWhenSpaceIsUnknown() {
assertEquals(EpicDownloadManager.ADAPTIVE_CACHE_DEFAULT_BYTES, EpicDownloadManager.adaptiveCacheBudget(-1, 0))
assertEquals(EpicDownloadManager.ADAPTIVE_CACHE_MAX_BYTES, EpicDownloadManager.adaptiveCacheBudget(100 * gib, 10 * gib))
assertEquals(0L, EpicDownloadManager.adaptiveCacheBudget(gib, gib))
val free = 1000 * mib
assertEquals((free - 400 * mib - EpicDownloadManager.ADAPTIVE_TRANSIENT_BYTES) / 2, EpicDownloadManager.adaptiveCacheBudget(free, 400 * mib))
}
@Test fun freshInstallsHaveNoOverlapLimit() {
val plan = EpicDownloadManager.planAdaptiveSpace(20 * gib, 0, 30 * gib, true, 10 * gib)
assertNull(plan.error)
assertEquals(-1L, plan.overlapBudget)
assertEquals(20 * gib, plan.gameNeed)
}
@Test fun updateOverlapBudgetIsTheLeftoverAfterNetGrowthAndCache() {
// Card install, cache on internal: the card's leftover after the net growth is the budget.
val roomy = EpicDownloadManager.planAdaptiveSpace(gib, 4 * gib, 20 * gib, true, 10 * gib)
assertNull(roomy.error)
assertFalse(roomy.cacheBesideGame)
assertEquals(19 * gib, roomy.overlapBudget)
assertEquals(20 * gib, roomy.gameNeed)
// Tight: floored at the largest replaced file, one at a time.
val tight = EpicDownloadManager.planAdaptiveSpace(gib, 4 * gib, 5 * gib, true, 10 * gib)
assertNull(tight.error)
assertEquals(4 * gib, tight.overlapBudget)
// Not even one replaced file fits: the shortfall is named.
val short = EpicDownloadManager.planAdaptiveSpace(gib, 4 * gib, 4 * gib, true, 10 * gib)
assertTrue(short.error!!.contains("game's storage"))
assertTrue(short.error!!.contains("short by 1.0 GB"))
// Unknown free space: one replaced file at a time.
assertEquals(4 * gib, EpicDownloadManager.planAdaptiveSpace(gib, 4 * gib, -1, true, -1).overlapBudget)
}
@Test fun cacheBesideTheGameComesOutOfTheOverlapBudget() {
val plan = EpicDownloadManager.planAdaptiveSpace(gib, 2 * gib, 10 * gib, false, -1)
assertNull(plan.error)
assertTrue(plan.cacheBesideGame)
assertTrue(plan.cacheBudget > 0)
assertEquals(10 * gib - gib - plan.cacheBudget - EpicDownloadManager.ADAPTIVE_TRANSIENT_BYTES, plan.overlapBudget)
assertEquals(10 * gib, plan.gameNeed)
}
@Test fun fullInternalStorageMovesTheCacheBesideTheGameInsteadOfFailing() {
val plan = EpicDownloadManager.planAdaptiveSpace(20 * gib, 0, 30 * gib, true, 100 * mib)
assertNull(plan.error)
assertTrue(plan.cacheBesideGame)
assertEquals(0L, plan.scratchNeed)
assertTrue(plan.cacheBudget > 0)
assertEquals(20 * gib + plan.cacheBudget + EpicDownloadManager.ADAPTIVE_TRANSIENT_BYTES, plan.gameNeed)
}
@Test fun ownedStagingIsRemovedOnlyWhenItHoldsJustItsMarker() {
val root = temp.newFolder("game")
val staging = EpicDownloadManager.recoverOwnedStaging(root, emptyList())
File(staging, "keep.stage").writeText("x")
EpicDownloadManager.releaseOwnedStaging(root)
assertTrue(File(staging, "owner").exists())
File(staging, "keep.stage").delete()
EpicDownloadManager.releaseOwnedStaging(root)
assertFalse(staging.exists())
// A directory without the marker is not ours.
staging.mkdir()
File(staging, "owner").writeText("someone else")
EpicDownloadManager.releaseOwnedStaging(root)
assertTrue(staging.exists())
}
}
@@ -0,0 +1,646 @@
package com.droiddeck.launcher.stores.epic
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstalls
import java.io.File
import java.net.InetAddress
import java.net.ServerSocket
import java.net.SocketException
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.security.MessageDigest
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.net.Socket
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowStatFs
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class EpicBoundedInstallTest {
@get:Rule val temp = TemporaryFolder()
private lateinit var server: ServerSocket
private lateinit var worker: Thread
private lateinit var manifest: EpicDownloadManager.Manifest
private lateinit var root: File
private val requests = AtomicInteger()
private val reject = AtomicBoolean()
private val rejectGuid = AtomicInteger()
private val handlers = Executors.newCachedThreadPool()
private val sockets = ConcurrentHashMap.newKeySet<Socket>()
private var requestBarrier: CountDownLatch? = null
private var deliveryGate: CountDownLatch? = null
private var bytes = ByteArray(256 * 1024) { (it % 251).toByte() }
@Before fun setUp() {
root = temp.newFolder("game")
ShadowStatFs.registerStats(root.path, 1_000_000_000, 1_000_000_000, 1_000_000_000)
server = ServerSocket(0, 8, InetAddress.getByName("127.0.0.1"))
worker = Thread {
while (!server.isClosed) {
val socket = try { server.accept() } catch (e: SocketException) {
if (server.isClosed) break else throw e
}
sockets.add(socket)
handlers.submit {
try {
socket.use {
it.soTimeout = 5000
val reader = it.getInputStream().bufferedReader()
val request = reader.readLine()
while (!reader.readLine().isNullOrEmpty()) { }
requests.incrementAndGet()
requestBarrier?.let { barrier ->
barrier.countDown()
check(barrier.await(5, TimeUnit.SECONDS)) { "Requests did not overlap" }
}
val out = it.getOutputStream()
val rejectedGuid = rejectGuid.get()
if (reject.get() || (rejectedGuid != 0 && request.contains("_%08X".format(rejectedGuid)))) {
out.write("HTTP/1.1 503 Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".toByteArray())
} else {
val header = ByteBuffer.allocate(41).order(ByteOrder.LITTLE_ENDIAN)
.putInt(0xB1FE3AA2.toInt()).putInt(1).putInt(41).putInt(bytes.size)
.put(ByteArray(24)).put(0).array()
out.write("HTTP/1.1 200 OK\r\nContent-Length: ${header.size + bytes.size}\r\nConnection: close\r\n\r\n".toByteArray())
out.write(header)
out.flush()
deliveryGate?.await(5, TimeUnit.SECONDS)
out.write(bytes)
}
out.flush()
}
} catch (_: java.io.IOException) {
// Cancellation disconnects an owned request while this fixture serves it.
} finally { sockets.remove(socket) }
}
}
}.apply { start() }
val chunk = EpicDownloadManager.ChunkInfo().apply {
guid = intArrayOf(1, 0, 0, 0)
windowSize = bytes.size
fileSize = bytes.size.toLong()
sha1 = sha(bytes)
}
manifest = EpicDownloadManager.Manifest().apply {
chunkDir = "chunks"
uniqueChunks = arrayListOf(chunk)
cdnUrls = listOf(EpicDownloadManager.CdnUrl("http://127.0.0.1:${server.localPort}", "", ""))
files = arrayListOf(gameFile("game.bin", 0, bytes.size / 2), gameFile("game.bin.part", bytes.size / 2, bytes.size / 2))
}
}
@After fun tearDown() {
deliveryGate?.countDown()
server.close()
worker.join(6000)
sockets.forEach { it.close() }
handlers.shutdownNow()
assertTrue(handlers.awaitTermination(6, TimeUnit.SECONDS))
assertFalse(worker.isAlive)
}
private fun sha(data: ByteArray) = MessageDigest.getInstance("SHA-1").digest(data)
private fun gameFile(name: String, offset: Int, size: Int) = EpicDownloadManager.FileInfo().apply {
filename = name
sha1 = sha(bytes.copyOfRange(offset, offset + size))
parts.add(EpicDownloadManager.ChunkPart().apply {
guid = intArrayOf(1, 0, 0, 0)
this.offset = offset
this.size = size
})
}
private fun install(cancel: AtomicBoolean = AtomicBoolean(), callback: EpicDownloadManager.Callback =
EpicDownloadManager.Callback { _, _ -> }, cache: String = "") =
EpicDownloadManager.installManifest(manifest, root.path, cache, null, cancel, callback)
private fun oldInstall() {
File(root, "game.bin").writeBytes(byteArrayOf(9, 8, 7))
File(root, "game.bin.part").writeBytes(byteArrayOf(6, 5, 4))
StoreGameSidecar(Store.EPIC, "game", "Game", "game.bin", installVersion = "old").write(root)
}
private fun assertOldInstallIntact() {
assertArrayEquals(byteArrayOf(9, 8, 7), File(root, "game.bin").readBytes())
assertArrayEquals(byteArrayOf(6, 5, 4), File(root, "game.bin.part").readBytes())
assertEquals("old", StoreGameSidecar.read(root)?.installVersion)
assertTrue(StoreGameSidecar.read(root)?.isInstalled == true)
assertTrue(root.walk().none { it.name.endsWith(".stage") })
}
@Test fun networkFailureAfterAcceptedPreflightPreservesInstalledFilesAndRecord() {
oldInstall()
reject.set(true)
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
assertTrue(requests.get() > 0)
assertOldInstallIntact()
}
@Test fun hashFailureAfterAcceptedPreflightPreservesInstalledFilesAndRecord() {
oldInstall()
manifest.files.first().sha1 = ByteArray(20) { 1 }
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
assertOldInstallIntact()
}
@Test fun cancellationWhileStagingPreservesInstalledFilesAndRecord() {
oldInstall()
val cancel = AtomicBoolean()
assertNull(install(cancel, EpicDownloadManager.Callback { message, _ ->
if (message.startsWith("Downloading chunks (")) cancel.set(true)
}))
assertOldInstallIntact()
}
@Test fun laterFailureRetainsVerifiedSwapsAndMarksMixedUpdateResumable() {
oldInstall()
manifest.files.last().sha1 = ByteArray(20) { 1 }
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
assertArrayEquals(bytes.copyOfRange(0, bytes.size / 2), File(root, "game.bin").readBytes())
assertArrayEquals(byteArrayOf(6, 5, 4), File(root, "game.bin.part").readBytes())
val record = StoreGameSidecar.read(root)!!
assertEquals(StoreGameSidecar.STATE_UPDATING, record.state)
assertFalse(record.isInstalled)
assertEquals("", record.installVersion)
StoreInstalls.begin(root, Store.EPIC, "game", "Game", null, null)
assertEquals("game.bin", StoreGameSidecar.read(root)?.exe)
assertEquals(StoreGameSidecar.STATE_UPDATING, StoreGameSidecar.read(root)?.state)
}
@Test fun laterNetworkFailurePreservesTheUnreplacedOldFile() {
oldInstall()
val secondChunk = EpicDownloadManager.ChunkInfo().apply {
guid = intArrayOf(2, 0, 0, 0)
windowSize = bytes.size
fileSize = bytes.size.toLong()
sha1 = sha(bytes)
}
manifest.uniqueChunks.add(secondChunk)
manifest.files.last().parts.single().guid = secondChunk.guid
// Prefetch may fail early, but replacement is still ordered by the writer.
rejectGuid.set(2)
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
assertArrayEquals(bytes.copyOfRange(0, bytes.size / 2), File(root, "game.bin").readBytes())
assertArrayEquals(byteArrayOf(6, 5, 4), File(root, "game.bin.part").readBytes())
assertEquals(StoreGameSidecar.STATE_UPDATING, StoreGameSidecar.read(root)?.state)
assertTrue(root.walk().none { it.name.endsWith(".stage") })
}
@Test fun cancellationAfterFirstSwapLeavesAResumableMixedUpdate() {
oldInstall()
val cancel = AtomicBoolean()
val callback = object : EpicDownloadManager.Callback {
override fun onProgress(message: String, pct: Int) {}
override fun onStage(stage: String, done: Long, total: Long, items: Int, itemsTotal: Int) {
if (stage == "stream" && items == 1) cancel.set(true)
}
}
assertNull(install(cancel, callback))
assertArrayEquals(bytes.copyOfRange(0, bytes.size / 2), File(root, "game.bin").readBytes())
assertArrayEquals(byteArrayOf(6, 5, 4), File(root, "game.bin.part").readBytes())
assertEquals(StoreGameSidecar.STATE_UPDATING, StoreGameSidecar.read(root)?.state)
assertNotNull(install())
assertArrayEquals(bytes.copyOfRange(bytes.size / 2, bytes.size), File(root, "game.bin.part").readBytes())
// Registration, not an individual file swap, restores the installed state.
assertFalse(StoreGameSidecar.read(root)!!.isInstalled)
}
@Test fun atomicRenameFailurePreservesDestinationAndCleansStagingWithoutDeleteFallback() {
val destination = File(root, "game.bin").apply { mkdir() }
File(destination, "old-content").writeText("keep")
val error = assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
assertTrue(error.message.orEmpty().contains("atomically replace"))
assertEquals("keep", File(destination, "old-content").readText())
assertTrue(root.walk().none { it.name.endsWith(".stage") })
}
@Test fun safeStagingSpaceBoundaryRejectsWithoutReclaimingAllOldOutputs() {
// The first staged half-file must coexist with the shared chunk and BOTH old outputs.
val old = ByteArray(bytes.size / 2) { 9 }
File(root, "game.bin").writeBytes(old)
File(root, "game.bin.part").writeBytes(old)
val peak = bytes.size + old.size
ShadowStatFs.registerStats(root.path, 1024, peak / 4096 - 1, peak / 4096 - 1)
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
assertEquals(0, requests.get())
assertArrayEquals(old, File(root, "game.bin").readBytes())
assertArrayEquals(old, File(root, "game.bin.part").readBytes())
ShadowStatFs.registerStats(root.path, 1024, peak / 4096, peak / 4096)
assertNotNull(install())
}
@Test fun zeroSpaceRejectsPendingFilesWhileUnknownSpaceIsNotTreatedAsZero() {
oldInstall()
ShadowStatFs.registerStats(root.path, 1024, 0, 0)
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
assertOldInstallIntact()
assertEquals(0, requests.get())
assertTrue(com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(1, 0))
assertFalse(com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(1, -1))
}
@Test fun zeroScratchSpaceRejectsBeforeFetchWithoutTouchingInstalledOutputs() {
oldInstall()
val cache = temp.newFolder("full-scratch")
ShadowStatFs.registerStats(cache.path, 1024, 0, 0)
val error = assertThrows(EpicDownloadManager.InstallException::class.java) { install(cache = cache.path) }
assertTrue(error.message.orEmpty().contains("Not enough internal space"))
assertOldInstallIntact()
assertEquals(0, requests.get())
}
@Test fun installsSharedChunksAndPreservesLegitimatePartFilename() {
assertNotNull(install())
assertArrayEquals(bytes.copyOfRange(0, bytes.size / 2), File(root, "game.bin").readBytes())
assertArrayEquals(bytes.copyOfRange(bytes.size / 2, bytes.size), File(root, "game.bin.part").readBytes())
assertEquals(1, requests.get())
assertFalse(File(root, ".chunks").exists())
assertNotNull(install())
assertEquals("Verified files must not be downloaded again", 1, requests.get())
}
private fun oversizedUpdate() {
val file = manifest.files[0]
val part = file.parts[0]
file.parts.clear()
repeat(100_000) {
file.parts.add(EpicDownloadManager.ChunkPart().apply {
guid = part.guid
size = Int.MAX_VALUE
})
}
}
@Test fun insufficientInstallSpacePreservesExistingFilesOnBothCacheLayouts() {
val oldGame = byteArrayOf(9, 8, 7)
val oldPart = byteArrayOf(6, 5, 4)
File(root, "game.bin").writeBytes(oldGame)
File(root, "game.bin.part").writeBytes(oldPart)
oversizedUpdate()
assertTrue(manifest.files[0].fileSize() > root.usableSpace)
for (cache in listOf("", temp.newFolder("scratch-rejected").path)) {
if (cache.isNotEmpty()) ShadowStatFs.registerStats(cache, 1_000_000_000, 1_000_000_000, 1_000_000_000)
val error = assertThrows(EpicDownloadManager.InstallException::class.java) { install(cache = cache) }
assertTrue(error.message.orEmpty().contains("Not enough free space"))
assertArrayEquals(oldGame, File(root, "game.bin").readBytes())
assertArrayEquals(oldPart, File(root, "game.bin.part").readBytes())
}
assertEquals(0, requests.get())
}
@Test fun acceptedUpdateReplacesOutdatedFilesWithVerifiedOutputs() {
oldInstall()
assertNotNull(install())
assertArrayEquals(bytes.copyOfRange(0, bytes.size / 2), File(root, "game.bin").readBytes())
assertArrayEquals(bytes.copyOfRange(bytes.size / 2, bytes.size), File(root, "game.bin.part").readBytes())
assertEquals(StoreGameSidecar.STATE_UPDATING, StoreGameSidecar.read(root)?.state)
assertTrue(root.walk().none { it.name.endsWith(".stage") })
}
@Test fun pauseKeepsCompletedFilesAndResumeReusesSharedCache() {
val cancel = AtomicBoolean()
val callback = object : EpicDownloadManager.Callback {
override fun onProgress(message: String, pct: Int) {}
override fun onStage(stage: String, done: Long, total: Long, items: Int, itemsTotal: Int) {
if (stage == "stream" && items == 1) cancel.set(true)
}
}
assertNull(install(cancel, callback))
assertTrue(File(root, "game.bin").exists())
assertFalse(File(root, "game.bin.part").exists())
assertEquals(1, requests.get())
assertNotNull(install())
assertEquals(1, requests.get())
}
@Test fun cancellationDuringChunkDeliveryRemovesIncompleteOutput() {
val cancel = AtomicBoolean()
val callback = object : EpicDownloadManager.Callback {
override fun onProgress(message: String, pct: Int) {
if (message.startsWith("Downloading chunks (")) cancel.set(true)
}
}
assertNull(install(cancel, callback))
assertFalse(File(root, "game.bin").exists())
assertNotNull(install())
assertArrayEquals(bytes.copyOfRange(0, bytes.size / 2), File(root, "game.bin").readBytes())
}
@Test fun fileHashFailureIsExplicitAndRetryRepairsIt() {
val expected = manifest.files[0].sha1
manifest.files[0].sha1 = ByteArray(20) { 1 }
val error = assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
assertTrue(error.message.orEmpty().contains("SHA-1 mismatch"))
assertFalse(File(root, "game.bin").exists())
manifest.files[0].sha1 = expected
assertNotNull(install())
}
@Test fun corruptCacheIsRefetchedAndScratchCacheIsRemovedOnSuccess() {
val cache = temp.newFolder("scratch")
ShadowStatFs.registerStats(cache.path, 1_000_000_000, 1_000_000_000, 1_000_000_000)
File(cache, manifest.uniqueChunks[0].guidStr()).writeBytes(ByteArray(bytes.size))
assertNotNull(install(cache = cache.path))
assertEquals(1, requests.get())
assertFalse(cache.exists())
}
@Test fun networkFailureLeavesNoCompletedFileAndCanBeRetried() {
reject.set(true)
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
assertFalse(File(root, "game.bin").exists())
reject.set(false)
assertNotNull(install())
}
@Test fun boundedProgressNeverReentersDownloadAfterEnteringInstall() {
val events = mutableListOf<String>()
val callback = object : EpicDownloadManager.Callback {
override fun onProgress(message: String, pct: Int) {
if (message.startsWith("Downloading chunks")) events.add("download")
if (message.startsWith("Writing")) events.add("install")
}
override fun onBytes(done: Long, total: Long, speedBps: Long) { events.add("download") }
override fun onStage(stage: String, done: Long, total: Long, items: Int, itemsTotal: Int) {
if (stage == "install") {
assertEquals(total, done)
assertEquals(itemsTotal, items)
events.add("install")
}
}
}
assertNotNull(install(callback = callback))
val firstInstall = events.indexOf("install")
assertTrue(firstInstall > 0)
assertFalse(events.drop(firstInstall).contains("download"))
}
@Test fun sharedChunksDoNotCompleteProgressBeforeTheRemainingFilesAreWritten() {
val samples = mutableListOf<Pair<Long, Long>>()
val callback = object : EpicDownloadManager.Callback {
override fun onProgress(message: String, pct: Int) {}
override fun onBytes(done: Long, total: Long, speedBps: Long) { samples.add(done to total) }
override fun onStage(stage: String, done: Long, total: Long, items: Int, itemsTotal: Int) {
if (stage == "stream" && items < itemsTotal) assertTrue(samples.last().first < samples.last().second)
}
}
assertNotNull(install(callback = callback))
assertEquals(listOf(0L, bytes.size / 2L, bytes.size.toLong()), samples.map { it.first })
assertTrue(samples.all { it.second == bytes.size.toLong() })
}
@Test fun oversizedSharedChunkStaysPinnedAcrossPrefetchedFilesWithoutChangingStages() {
bytes = ByteArray((EpicDownloadManager.MAX_RETAINED_CHUNK_CACHE_BYTES + 1024).toInt()) { (it % 251).toByte() }
manifest.uniqueChunks.single().apply {
windowSize = bytes.size
fileSize = bytes.size.toLong()
sha1 = sha(bytes)
}
manifest.files = (0..2).map { gameFile("part-$it.bin", it * 1024, 1024) }
val chunk = manifest.uniqueChunks.single()
val estimatedPeak = EpicDownloadManager.estimatePeakAdditionalBytes(
manifest.files,
mapOf(chunk.guidStr() to chunk),
emptyMap(),
true,
)
assertEquals(EpicDownloadManager.MAX_RETAINED_CHUNK_CACHE_BYTES + 4 * 1024L, estimatedPeak)
val samples = mutableListOf<Long>()
val stages = mutableListOf<String>()
val callback = object : EpicDownloadManager.Callback {
override fun onProgress(message: String, pct: Int) {}
override fun onBytes(done: Long, total: Long, speedBps: Long) {
assertEquals(3072L, total)
assertFalse(stages.contains("install"))
samples.add(done)
}
override fun onStage(stage: String, done: Long, total: Long, items: Int, itemsTotal: Int) {
stages.add(stage)
if (stage == "stream" && items < itemsTotal) assertTrue(samples.last() < total)
}
}
assertNotNull(install(callback = callback))
assertEquals(1, requests.get())
assertEquals(listOf(0L, 1024L, 2048L, 3072L), samples)
assertEquals("install", stages.last())
repeat(3) { assertArrayEquals(bytes.copyOfRange(it * 1024, (it + 1) * 1024), File(root, "part-$it.bin").readBytes()) }
}
@Test fun hogwartsSizedSequentialPlanFitsAvailableSpaceWithoutFullChunkCache() {
val gib = 1024L * 1024 * 1024
val file = EpicDownloadManager.FileInfo()
val chunks = LinkedHashMap<String, EpicDownloadManager.ChunkInfo>()
repeat(72) { index ->
val chunk = EpicDownloadManager.ChunkInfo().apply {
guid = intArrayOf(index + 1, 0, 0, 0)
windowSize = gib.toInt()
}
chunks[chunk.guidStr()] = chunk
file.parts.add(EpicDownloadManager.ChunkPart().apply {
guid = chunk.guid
size = chunk.windowSize
})
}
val peak = EpicDownloadManager.estimatePeakAdditionalBytes(listOf(file), chunks, emptyMap(), true)
assertEquals(73 * gib, peak)
assertTrue(peak < 96 * gib)
}
@Test fun plannersReclaimEachOldFileOnlyAfterItsOwnVerifiedSwap() {
val chunks = manifest.uniqueChunks.associateBy { it.guidStr() }
val half = bytes.size / 2L
val old = mapOf("game.bin" to half, "game.bin.part" to 100 * half)
assertEquals(bytes.size + half, EpicDownloadManager.estimatePeakAdditionalBytes(manifest.files, chunks, emptyMap(), true, old))
assertEquals(half, EpicDownloadManager.estimateStagedFilePeak(manifest.files, old))
assertEquals(2 * half, EpicDownloadManager.estimateStagedFilePeak(manifest.files, emptyMap()))
assertEquals(bytes.size.toLong(), EpicDownloadManager.estimatePeakAdditionalBytes(manifest.files, chunks, emptyMap(), false, old))
}
private fun distinctFiles(count: Int) {
val template = manifest.uniqueChunks.single()
manifest.uniqueChunks = (1..count).map { id ->
EpicDownloadManager.ChunkInfo().apply {
guid = intArrayOf(id, 0, 0, 0)
windowSize = template.windowSize
fileSize = template.fileSize
sha1 = template.sha1
}
}
manifest.files = manifest.uniqueChunks.mapIndexed { index, chunk ->
gameFile("file-$index.bin", 0, bytes.size).apply { parts.single().guid = chunk.guid }
}
}
@Test fun prefetchOverlapsEightSinglePartFilesButNeverFetchesTheWholeManifest() {
distinctFiles(20)
requestBarrier = CountDownLatch(8)
val cancel = AtomicBoolean()
var sawWindow = false
assertNull(install(cancel, EpicDownloadManager.Callback { message, _ ->
if (message.startsWith("Downloading chunks (")) {
assertEquals(8, requests.get())
val cacheBytes = File(root, ".chunks").listFiles()!!.sumOf { it.length() }
assertTrue(cacheBytes <= 8L * bytes.size)
sawWindow = true
cancel.set(true)
}
}))
assertTrue("An eight-request barrier cannot pass with a sequential downloader", sawWindow)
assertEquals(8, requests.get())
assertTrue(root.walk().none { it.name.endsWith(".stage") || it.name.endsWith(".part") })
}
@Test fun parallelWindowSpaceThresholdIsCheckedBeforeStartingAnyRequest() {
distinctFiles(20)
val cache = temp.newFolder("parallel-scratch")
val peak = EpicDownloadManager.estimatePeakAdditionalBytes(
manifest.files, manifest.uniqueChunks.associateBy { it.guidStr() }, emptyMap(), false,
)
assertEquals(8L * bytes.size, peak)
ShadowStatFs.registerStats(cache.path, 1024, peak.toInt() / 4096 - 1, peak.toInt() / 4096 - 1)
assertThrows(EpicDownloadManager.InstallException::class.java) { install(cache = cache.path) }
assertEquals(0, requests.get())
ShadowStatFs.registerStats(cache.path, 1024, peak.toInt() / 4096, peak.toInt() / 4096)
requestBarrier = CountDownLatch(8)
assertNotNull(install(cache = cache.path))
assertEquals(20, requests.get())
manifest.files.forEach { assertArrayEquals(bytes, File(root, it.filename).readBytes()) }
}
@Test fun cancellationDuringParallelNetworkReadsJoinsWorkersBeforeReturning() {
distinctFiles(20)
requestBarrier = CountDownLatch(8)
deliveryGate = CountDownLatch(1)
val cancel = AtomicBoolean()
val outcome = java.util.concurrent.atomic.AtomicReference<Any?>()
val installer = Thread {
try { outcome.set(install(cancel)) } catch (e: Throwable) { outcome.set(e) }
}.apply { start() }
try {
assertTrue(requestBarrier!!.await(5, TimeUnit.SECONDS))
cancel.set(true)
installer.join(10_000)
assertFalse("Installer must disconnect and join all download workers", installer.isAlive)
assertNull(outcome.get())
val cache = File(root, ".chunks")
val snapshot = cache.listFiles()?.associate { it.name to it.length() }.orEmpty()
deliveryGate!!.countDown()
Thread.sleep(150)
assertEquals(snapshot, cache.listFiles()?.associate { it.name to it.length() }.orEmpty())
assertTrue(snapshot.keys.none { it.endsWith(".part") })
assertTrue(root.walk().none { it.name.endsWith(".stage") })
assertEquals(8, requests.get())
} finally {
cancel.set(true)
deliveryGate!!.countDown()
installer.join(10_000)
}
}
@Test fun failedParallelFetchJoinsOtherNetworkReadersBeforeReturning() {
distinctFiles(20)
requestBarrier = CountDownLatch(8)
deliveryGate = CountDownLatch(1)
rejectGuid.set(1)
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
assertEquals(8, requests.get())
val cache = File(root, ".chunks")
val snapshot = cache.listFiles()?.associate { it.name to it.length() }.orEmpty()
deliveryGate!!.countDown()
Thread.sleep(150)
assertEquals(snapshot, cache.listFiles()?.associate { it.name to it.length() }.orEmpty())
assertTrue(snapshot.keys.none { it.endsWith(".part") })
assertTrue(root.walk().none { it.name.endsWith(".stage") })
}
@Test fun ownedOrphanStagingIsRecoveredBeforeTheSpaceProbeWithoutTouchingManifestFiles() {
val staging = EpicDownloadManager.recoverOwnedStaging(root, manifest.files)
File(staging, "native-123-0.stage").writeBytes(ByteArray(bytes.size))
val legitimate = File(root, ".droiddeck-epic-old.stage").apply { writeText("keep") }
oldInstall()
val peak = 2 * bytes.size
ShadowStatFs.registerStats(root.path, 1024, peak / 4096, peak / 4096)
assertNotNull(install())
assertEquals("keep", legitimate.readText())
// The orphan was recovered, and a finished install removes the then-empty owned namespace.
assertFalse(staging.exists())
}
@Test fun stagingRecoveryRefusesUnownedAndManifestOwnedNamespaces() {
val staging = File(root, EpicDownloadManager.STAGING_DIRECTORY).apply { mkdir() }
val untouched = File(staging, "legitimate.stage").apply { writeText("keep") }
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
assertEquals("keep", untouched.readText())
File(staging, "owner").writeText("DroidDeck Epic staging v1\n")
manifest.files.first().filename = "${EpicDownloadManager.STAGING_DIRECTORY}/legitimate.stage"
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
assertEquals("keep", untouched.readText())
assertEquals(0, requests.get())
}
@Test fun loadedNativeAbiFailureIsExplicitAndNeverFallsBackToJavaDownloads() {
val field = com.droiddeck.launcher.stores.StoresNative::class.java.getDeclaredField("loaded")
field.isAccessible = true
field.set(null, true)
try {
oldInstall()
val error = assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
assertTrue(error.message.orEmpty().contains("Native Epic install failed"))
assertEquals(0, requests.get())
assertOldInstallIntact()
} finally {
com.droiddeck.launcher.stores.StoresNative.forget()
}
}
@Test fun stagingRecoveryRejectsSymlinkNamespaceOwnerAndEntriesWithoutDeletingOutsideData() {
val outside = temp.newFolder("outside-staging")
val externalStage = File(outside, "keep.stage").apply { writeText("keep") }
val externalOwner = File(outside, "owner").apply { writeText("DroidDeck Epic staging v1\n") }
val staging = File(root, EpicDownloadManager.STAGING_DIRECTORY)
try {
java.nio.file.Files.createSymbolicLink(staging.toPath(), outside.toPath())
} catch (e: java.nio.file.FileSystemException) {
org.junit.Assume.assumeNoException("Host does not permit symbolic links", e)
}
try {
val error = assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
assertTrue(error.message.orEmpty().contains("Unsafe Epic staging"))
assertEquals("keep", externalStage.readText())
java.nio.file.Files.delete(staging.toPath())
staging.mkdir()
java.nio.file.Files.createSymbolicLink(File(staging, "owner").toPath(), externalOwner.toPath())
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
java.nio.file.Files.delete(File(staging, "owner").toPath())
File(staging, "owner").writeText("DroidDeck Epic staging v1\n")
val localStage = File(staging, "local.stage").apply { writeText("local") }
java.nio.file.Files.createSymbolicLink(File(staging, "linked.stage").toPath(), externalStage.toPath())
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
assertEquals("local", localStage.readText())
assertEquals("keep", externalStage.readText())
assertEquals(0, requests.get())
} finally {
if (java.nio.file.Files.isSymbolicLink(staging.toPath())) java.nio.file.Files.delete(staging.toPath())
for (name in listOf("owner", "linked.stage")) {
val entry = File(staging, name).toPath()
if (java.nio.file.Files.isSymbolicLink(entry)) java.nio.file.Files.delete(entry)
}
}
}
}
@@ -1,17 +1,152 @@
package com.droiddeck.launcher.stores.epic
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/** The JSON manifest's numbers are blobs; the same values as the Rust engine's manifest tests. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class EpicJsonManifestTest {
@Test
fun boundedInstallPeakReservesParallelIncomingChunksBeforeWriting() {
val first = chunk(1)
val second = chunk(2)
val file = file(part(1, 0, 100), part(2, 0, 100))
val chunks = mapOf(first.guidStr() to first, second.guidStr() to second)
assertEquals(300L, EpicDownloadManager.estimatePeakAdditionalBytes(listOf(file), chunks, emptyMap(), true))
assertEquals(200L, EpicDownloadManager.estimatePeakAdditionalBytes(listOf(file), chunks, emptyMap(), false))
}
@Test
fun sharedCachedChunkIsReclaimedOnlyAfterItsLastPart() {
val shared = chunk(1)
val files = listOf(file(part(1, 0, 60)), file(part(1, 60, 40)))
assertEquals(
100L,
EpicDownloadManager.estimatePeakAdditionalBytes(
files, mapOf(shared.guidStr() to shared), mapOf(shared.guidStr() to 100L), true,
),
)
assertEquals(
200L,
EpicDownloadManager.estimatePeakAdditionalBytes(
files, mapOf(shared.guidStr() to shared), emptyMap(), true,
),
)
}
@Test
fun sharedChunksWithinTheWindowStayPinnedWithinTheCacheCeiling() {
val first = chunk(1).apply { windowSize = 40 * 1024 * 1024 }
val second = chunk(2).apply { windowSize = 40 * 1024 * 1024 }
val files = listOf(
file(part(1, 0, 40 * 1024 * 1024)),
file(part(2, 0, 40 * 1024 * 1024)),
file(part(1, 0, 40 * 1024 * 1024)),
file(part(2, 0, 40 * 1024 * 1024)),
)
val chunks = mapOf(first.guidStr() to first, second.guidStr() to second)
val gamePeak = EpicDownloadManager.estimatePeakAdditionalBytes(files, chunks, emptyMap(), true)
val cachePeak = EpicDownloadManager.estimatePeakAdditionalBytes(files, chunks, emptyMap(), false)
assertEquals(200L * 1024 * 1024, gamePeak)
assertTrue(cachePeak <= EpicDownloadManager.MAX_RETAINED_CHUNK_CACHE_BYTES + 40L * 1024 * 1024)
}
@Test fun scheduleDeduplicatesWindowAndEvictsOnlyUnpinnedReusableChunks() {
val size = 40L * 1024 * 1024
val chunks = (1..12).map { chunk(it).apply { windowSize = size.toInt() } }
.associateBy { it.guidStr() }
val files = (1..12).map { file(part(it, 0, 1)) } + (1..12).map { file(part(it, 0, 1)) }
val schedule = EpicDownloadManager.PrefetchSchedule(files, chunks, emptyMap())
assertEquals(chunks.keys.take(8), schedule.fill())
assertEquals(emptyList<String>(), schedule.fill())
assertEquals(8 * size, schedule.bytes())
assertEquals(emptyList<String>(), schedule.consume())
assertEquals(listOf(chunks.keys.elementAt(8)), schedule.fill())
assertEquals(9 * size, schedule.bytes())
assertEquals(listOf(chunks.keys.first()), schedule.consume())
var refetchedFirst = false
repeat(22) {
val fetched = schedule.fill()
if (chunks.keys.first() in fetched) refetchedFirst = true
assertTrue(schedule.bytes() <= EpicDownloadManager.MAX_RETAINED_CHUNK_CACHE_BYTES + 8 * size)
val released = schedule.consume()
assertTrue(released.none { it in schedule.window() })
}
assertTrue(refetchedFirst)
assertEquals(0L, schedule.bytes())
assertEquals(9 * size, EpicDownloadManager.estimatePeakAdditionalBytes(files, chunks, emptyMap(), false))
}
@Test fun cachedAndOldOutputBytesAreCreditedOnlyWhenTheScheduleReleasesThem() {
val chunks = (1..8).map { chunk(it) }.associateBy { it.guidStr() }
val files = (1..8).map { id -> file(part(id, 0, 100)).apply { filename = "file-$id" } }
val existing = chunks.keys.associateWith { 100L }
val old = files.associate { it.filename to 100L }
assertEquals(800L, EpicDownloadManager.estimatePeakAdditionalBytes(files, chunks, emptyMap(), false))
assertEquals(0L, EpicDownloadManager.estimatePeakAdditionalBytes(files, chunks, existing, false))
assertEquals(900L, EpicDownloadManager.estimatePeakAdditionalBytes(files, chunks, emptyMap(), true, old))
assertEquals(100L, EpicDownloadManager.estimatePeakAdditionalBytes(files, chunks, existing, true, old))
}
@Test
fun resumeCacheDropsCorruptAndUnneededEntriesButKeepsVerifiedChunks() {
val dir = java.io.File(System.getProperty("user.dir"), "build/epic-cache-test-${System.nanoTime()}")
assertTrue(dir.mkdirs())
try {
val bytes = ByteArray(100) { (it % 251).toByte() }
val expectedSha = java.security.MessageDigest.getInstance("SHA-1").digest(bytes)
val valid = chunk(1).apply { sha1 = expectedSha }
val corrupt = chunk(2).apply { sha1 = expectedSha }
java.io.File(dir, valid.guidStr()).writeBytes(bytes)
java.io.File(dir, corrupt.guidStr()).writeBytes(ByteArray(100) { 1 })
java.io.File(dir, "orphan").writeBytes(bytes)
val retained = EpicDownloadManager.prepareBoundedCache(dir, listOf(valid, corrupt))
assertEquals(mapOf(valid.guidStr() to 100L), retained)
assertTrue(java.io.File(dir, valid.guidStr()).exists())
assertFalse(java.io.File(dir, corrupt.guidStr()).exists())
assertFalse(java.io.File(dir, "orphan").exists())
} finally {
EpicDownloadManager.deleteDir(dir)
}
}
@Test
fun referenceCountsIncludeRepeatedPartsSoCancelledFilesCanBeReplanned() {
val pending = listOf(file(part(1, 0, 20), part(1, 20, 20)), file(part(1, 40, 60)))
assertEquals(3, EpicDownloadManager.chunkReferences(pending)["00000001000000000000000000000000"])
}
private fun chunk(id: Int) = EpicDownloadManager.ChunkInfo().apply {
guid = intArrayOf(id, 0, 0, 0)
windowSize = 100
fileSize = 100
}
private fun part(id: Int, offset: Int, size: Int) = EpicDownloadManager.ChunkPart().apply {
guid = intArrayOf(id, 0, 0, 0)
this.offset = offset
this.size = size
}
private fun file(vararg parts: EpicDownloadManager.ChunkPart) = EpicDownloadManager.FileInfo().apply {
filename = "test.bin"
this.parts.addAll(parts)
}
@Test
fun blobNumbersAreDecimalBytesLeastSignificantFirst() {
assertEquals(1L, EpicDownloadManager.blobToNum("001000000000"))
@@ -6,7 +6,6 @@ import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/** Every CDN GOG's secure link offers is used, not only the first. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class GogCdnTest {
@@ -0,0 +1,43 @@
package com.droiddeck.launcher.stores.gog
import java.io.File
import java.security.MessageDigest
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.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowStatFs
import com.droiddeck.launcher.stores.StoreInstallRoot
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class GogResumeSpaceTest {
@Test fun remainingWorkRejectsMeasuredZeroButNotUnknownSpace() {
val root = File(RuntimeEnvironment.getApplication().filesDir, "gog-zero").apply { mkdirs() }
ShadowStatFs.registerStats(root.path, 1024, 0, 0)
val files = listOf(GogDownloadManager.DepotFile("missing").apply { totalSize = 4 })
val needed = GogDownloadManager.remainingInstallBytes(files, root)
assertEquals(4L, needed)
assertTrue(StoreInstallRoot.insufficientSpace(needed, StoreInstallRoot.availableBytes(root)))
assertFalse(StoreInstallRoot.insufficientSpace(needed, StoreInstallRoot.SPACE_UNKNOWN))
}
@Test fun remainingSpaceExcludesVerifiedFilesButIncludesCorruptAndPartialFiles() {
val root = File(RuntimeEnvironment.getApplication().filesDir, "gog-resume").apply { mkdirs() }
val data = byteArrayOf(1, 2, 3, 4)
val hash = MessageDigest.getInstance("MD5").digest(data).joinToString("") { "%02x".format(it) }
val files = listOf("good", "corrupt", "partial", "missing").map {
GogDownloadManager.DepotFile(it).apply { totalSize = 4; md5 = hash }
}
File(root, "good").writeBytes(data)
File(root, "corrupt").writeBytes(ByteArray(4))
File(root, "partial").writeBytes(byteArrayOf(1))
assertEquals(12L, GogDownloadManager.remainingInstallBytes(files, root))
for (file in files) File(root, file.relativePath).writeBytes(data)
assertEquals(0L, GogDownloadManager.remainingInstallBytes(files, root))
}
}
@@ -79,14 +79,11 @@ class FlathubFocusTest {
compose.waitForIdle()
val field = editText(root)!!
compose.runOnIdle {
// Keep a nonempty query, so clearing focus cannot simply dispose the search field.
// Whitespace skips the network search while retaining the field just like typed text.
field.setText(" ")
field.requestFocus()
assertTrue(field.isFocused)
}
compose.waitForIdle()
// Touching a card does not implicitly focus a Compose control or release an AndroidView.
compose.onNodeWithText("Datcord").performSemanticsAction(SemanticsActions.OnClick) { it() }
compose.onNodeWithText(context.getString(R.string.store_install)).assertExists()
compose.runOnIdle {
@@ -8,7 +8,6 @@ import org.junit.Assert.assertTrue
import org.junit.Test
class GamepadGeometryTest {
/** A foldable's unfolded panel (px) and density, as the gamepad gets it under a 16:9 game. */
private data class Panel(val name: String, val width: Int, val height: Int, val density: Float) {
val controlsHeight get() = height - SessionDisplay.unfoldedGameHeight(width, height)
}
@@ -68,7 +67,6 @@ class GamepadGeometryTest {
val right = b.getValue(Slot.RIGHT_MAIN)
assertEquals(panel.name, left.cy, right.cy, 0.5f)
assertEquals(panel.name, left.cx, panel.width - right.cx, 0.5f)
// In the bottom half of their side, nearer the corner than the second controls.
assertTrue(panel.name, left.cx < b.getValue(Slot.LEFT_SECOND).cx)
assertTrue(panel.name, left.cy > panel.controlsHeight / 2f)
}
@@ -77,8 +75,6 @@ class GamepadGeometryTest {
@Test fun middleButtonsKeepTheDeckOrder() {
for (panel in panels) {
val b = boxes(panel)
// View before Menu and Steam before QAM: left of it in a row or two by two, above it
// in a single column.
fun before(a: Slot, c: Slot) = b.getValue(a).let { x -> b.getValue(c).let { y ->
x.cx < y.cx - 0.5f || (kotlin.math.abs(x.cx - y.cx) <= 0.5f && x.cy < y.cy) } }
assertTrue(panel.name, before(Slot.VIEW, Slot.MENU))
@@ -10,7 +10,6 @@ class LiftSheetTest {
}
@Test fun theButtonKeeps16dpAboveIt() {
// A short pane: the edge comes down so the button riding it still clears the top by 16.
val top = sheetTop(150f, 56f, 16f, 3f)
assertEquals(41f, top, 0.01f)
assertEquals(16f, top + 3f - 56f / 2f, 0.01f)
@@ -31,7 +31,6 @@ class MotionTest {
Motion.refresh(context)
assertEquals(0f, Motion.scale, 0f)
assertEquals(0, Motion.ms(300))
// The app's toggle never writes Android's preference.
assertEquals(1.5f, Settings.Global.getFloat(context.contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE), 0f)
SessionPrefs.setAnimationsEnabled(context, true)
Motion.refresh(context)
@@ -13,7 +13,6 @@ class PageExitTest {
}
@Test fun anotherPageSinks() {
// The GPU drivers row in Steam's settings opens Components over the same rail item.
assertEquals(PageExit.Sink, pageExit("steam", "components", PageLeave.Ordinary))
}
@@ -12,7 +12,6 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.io.File
/** What the in-app picker lists in a folder: every folder A-Z, then only the files asked for. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class PickListingTest {
@@ -21,7 +21,6 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
// Render the component without starting runtime services or installing the app crash handler.
@Config(sdk = [28], application = android.app.Application::class)
class PresetScaleTest {
@get:Rule val compose = createRobolectricComposeRule()
@@ -39,7 +38,6 @@ class PresetScaleTest {
}
}
val originalWidth = compose.onNodeWithTag("page-size").fetchSemanticsNode().boundsInRoot.width
// Notify changes driven by the test before asking Compose to become idle again.
compose.runOnIdle {
scale.intValue = 75
Snapshot.sendApplyNotifications()
@@ -9,11 +9,8 @@ import org.robolectric.Shadows.shadowOf
fun createRobolectricComposeRule() = createComposeRule().also {
val context = RuntimeEnvironment.getApplication()
// Register only in Robolectric, without adding a host activity to either APK variant.
shadowOf(context.packageManager).addActivityIfNotPresent(
ComponentName(context, ComponentActivity::class.java),
)
// Pure state tests can leave unapplied snapshots before a Compose host starts its snapshot
// manager. Apply them before the rule's initial idle check, which runs before the test body.
Snapshot.sendApplyNotifications()
}
@@ -4,13 +4,11 @@ import com.droiddeck.launcher.stores.Store
import org.junit.Assert.assertEquals
import org.junit.Test
/** A store's modes are Store, Library and Installed; Amazon has no catalog of its own, so no Store. */
class StoreTabsTest {
@Test fun storeLibraryInstalledAmazonWithoutStore() {
assertEquals(listOf("store", "library", "installed"), tabsFor(Store.GOG))
assertEquals(listOf("library", "installed"), tabsFor(Store.AMAZON))
assertEquals("library", tabFor(Store.AMAZON, "store"))
// An old saved All tab opens Library; Installed is a mode again.
assertEquals("library", tabFor(Store.GOG, "all"))
assertEquals("installed", tabFor(Store.EPIC, "installed"))
assertEquals("store", tabFor(Store.GOG, "store"))