mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-19 12:56:06 +00:00
Merge remote-tracking branch 'origin/main' into pr1067
This commit is contained in:
commit
1ee597e07f
538 files changed
+38465
-3751
No files matched your search
@@ -6,9 +6,11 @@ import android.os.Handler
|
||||
import android.os.Looper
|
||||
import com.droiddeck.launcher.session.QuestExperimental
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.gpu.TpUbwcHint
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
@@ -17,11 +19,15 @@ import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.shadows.ShadowBuild
|
||||
import org.robolectric.util.ReflectionHelpers
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class DriverMenusAutoTest {
|
||||
@Before fun reset() {
|
||||
ReflectionHelpers.setStaticField(TpUbwcHint::class.java, "resolved", false)
|
||||
ReflectionHelpers.setStaticField(TpUbwcHint::class.java, "cached", null)
|
||||
ReflectionHelpers.setStaticField(TpUbwcHint::class.java, "activeMode", null)
|
||||
RuntimeEnvironment.getApplication().getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||
.edit().clear().commit()
|
||||
ShadowBuild.setModel("Quest 3")
|
||||
@@ -53,4 +59,36 @@ class DriverMenusAutoTest {
|
||||
assertEquals("chosen-display", SessionPrefs.androidDriver(activity))
|
||||
assertEquals("chosen-linux", SessionPrefs.linuxDriver(activity))
|
||||
}
|
||||
|
||||
@Test fun driverMenusCanBeConstructedBeforeActivityContextIsAttached() {
|
||||
val menus = DriverMenus(Activity(), Handler(Looper.getMainLooper()))
|
||||
assertEquals(SessionPrefs.TP_UBWC_AUTO, menus.tpUbwcMode)
|
||||
}
|
||||
|
||||
@Test fun refreshingDriversLoadsTheSavedUbwcModeAfterContextAttachment() {
|
||||
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
|
||||
SessionPrefs.setTpUbwcMode(activity, SessionPrefs.TP_UBWC_ON)
|
||||
val menus = DriverMenus(activity, Handler(Looper.getMainLooper()))
|
||||
menus.refreshDrivers()
|
||||
assertEquals(SessionPrefs.TP_UBWC_ON, menus.tpUbwcMode)
|
||||
assertFalse(menus.state().tpUbwcRestartRequired)
|
||||
}
|
||||
|
||||
@Test fun changingUbwcBeforeTheFirstSessionDoesNotRequireRestart() {
|
||||
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
|
||||
val menus = DriverMenus(activity, Handler(Looper.getMainLooper()))
|
||||
menus.refreshDrivers()
|
||||
SessionPrefs.setTpUbwcMode(activity, SessionPrefs.TP_UBWC_ON)
|
||||
menus.refreshDrivers()
|
||||
assertFalse(menus.state().tpUbwcRestartRequired)
|
||||
}
|
||||
|
||||
@Test fun recreatingTheMenuKeepsTheActiveHintRestartWarning() {
|
||||
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
|
||||
TpUbwcHint.forThisDevice(activity)
|
||||
SessionPrefs.setTpUbwcMode(activity, SessionPrefs.TP_UBWC_ON)
|
||||
val menus = DriverMenus(activity, Handler(Looper.getMainLooper()))
|
||||
menus.refreshDrivers()
|
||||
assertTrue(menus.state().tpUbwcRestartRequired)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import androidx.compose.ui.geometry.Rect
|
||||
import com.droiddeck.launcher.frontend.AutoComponents
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.ProtonExtras
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.session.SessionPhase
|
||||
import com.droiddeck.launcher.session.LoadingState
|
||||
import com.droiddeck.launcher.ui.LaunchOrigin
|
||||
import com.droiddeck.launcher.ui.Motion
|
||||
import org.json.JSONObject
|
||||
import org.junit.After
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.Robolectric
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.util.ReflectionHelpers
|
||||
import java.io.File
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class ProtonMenuAutoTest {
|
||||
private val online = AutoComponents.online
|
||||
private val constrained = AutoComponents.unfavourable
|
||||
private lateinit var activity: Activity
|
||||
private lateinit var menu: ProtonMenu
|
||||
private lateinit var root: File
|
||||
private val attempts = mutableListOf<String>()
|
||||
private var idle = true
|
||||
|
||||
@Before fun setup() {
|
||||
activity = Robolectric.buildActivity(Activity::class.java).setup().get()
|
||||
root = LinuxRuntime.rootDir(activity)
|
||||
for (path in listOf("usr/bin/gamescope", "usr/local/bin/droiddeck-session", "opt/android-host/proot", "opt/android-host/loader")) {
|
||||
File(root, path).apply { parentFile!!.mkdirs(); writeText("") }
|
||||
}
|
||||
AutoComponents.online = { true }
|
||||
AutoComponents.unfavourable = { false }
|
||||
SessionState.running = false
|
||||
SessionState.phase = SessionPhase.IDLE
|
||||
SessionState.stopRequested = false
|
||||
LaunchOrigin.take()
|
||||
LaunchOrigin.flooding = null
|
||||
val latest = JSONObject()
|
||||
for (tool in ProtonExtras.tools) latest.put(tool.id, JSONObject()
|
||||
.put("tag", "${tool.prefix}-11-12").put("at", System.currentTimeMillis()))
|
||||
File(activity.filesDir, "proton-latest.json").writeText(latest.toString())
|
||||
menu = ProtonMenu(activity, Handler(Looper.getMainLooper())) { idle }
|
||||
menu.installer = { tool, progress ->
|
||||
progress("Installing ${tool.name}", 50)
|
||||
install("${tool.prefix}-11-12")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
@After fun reset() {
|
||||
AutoComponents.online = online
|
||||
AutoComponents.unfavourable = constrained
|
||||
SessionState.running = false
|
||||
SessionState.phase = SessionPhase.IDLE
|
||||
SessionState.stopRequested = false
|
||||
LaunchOrigin.take()
|
||||
LaunchOrigin.flooding = null
|
||||
}
|
||||
|
||||
private fun install(name: String): File = File(root, "root/.local/share/Steam/compatibilitytools.d/$name").apply {
|
||||
mkdirs()
|
||||
File(this, "toolmanifest.vdf").writeText("manifest")
|
||||
}
|
||||
|
||||
private fun waitUntil(done: () -> Boolean) {
|
||||
val deadline = System.nanoTime() + 5_000_000_000L
|
||||
while (System.nanoTime() < deadline) {
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
if (done()) return
|
||||
Thread.sleep(10)
|
||||
}
|
||||
fail("Proton work did not finish")
|
||||
}
|
||||
|
||||
@Test fun aCachedCheckUpdatesOnlyInstalledFamiliesAndReplacesOlderDroidDeckProton() {
|
||||
val older = install("DroidDeck-Proton-11-11.1")
|
||||
val request = File(root, "root/.local/share/droiddeck-compat/request.json").apply {
|
||||
parentFile!!.mkdirs()
|
||||
writeText("{\"seq\":1,\"dir\":\"DroidDeck-Proton-11-11.1\",\"valve\":false}")
|
||||
}
|
||||
val before = request.readText()
|
||||
assertFalse(ProtonExtras.checkLatest(activity))
|
||||
menu.checkUpdates()
|
||||
waitUntil { menu.protonRows.singleOrNull { it.id == "droiddeck" }?.installed == "DroidDeck-Proton-11-12" && menu.protonBusyId == null && !older.exists() }
|
||||
assertEquals(listOf("DroidDeck-Proton-11-12"), ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == "droiddeck" }))
|
||||
assertEquals(before, request.readText())
|
||||
assertTrue(ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == "ge" }).isEmpty())
|
||||
assertTrue(ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == "cachyos" }).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun downloadsWaitForTheSessionNetworkPowerAndOtherInstallWork() {
|
||||
install("DroidDeck-Proton-11-11.1")
|
||||
menu.installer = { tool, _ -> attempts.add(tool.id); "failed" }
|
||||
SessionState.running = true
|
||||
menu.ensureAutoUpdates()
|
||||
SessionState.running = false
|
||||
AutoComponents.online = { false }
|
||||
menu.ensureAutoUpdates()
|
||||
AutoComponents.online = { true }
|
||||
AutoComponents.unfavourable = { true }
|
||||
menu.ensureAutoUpdates()
|
||||
AutoComponents.unfavourable = { false }
|
||||
idle = false
|
||||
menu.ensureAutoUpdates()
|
||||
assertNull(menu.protonBusyId)
|
||||
assertTrue(attempts.isEmpty())
|
||||
idle = true
|
||||
menu.ensureAutoUpdates()
|
||||
waitUntil { menu.protonBusyId == null }
|
||||
assertEquals(listOf("droiddeck"), attempts)
|
||||
}
|
||||
|
||||
@Test fun aFailedUpdateDoesNotLoopOrBlockOtherInstalledFamilies() {
|
||||
val ge = install("GE-Proton11-11")
|
||||
install("DroidDeck-Proton-11-11.1")
|
||||
menu.installer = { tool, _ ->
|
||||
attempts.add(tool.id)
|
||||
if (tool.id == "ge") throw IllegalStateException("download failed")
|
||||
install("${tool.prefix}-11-12")
|
||||
null
|
||||
}
|
||||
menu.ensureAutoUpdates()
|
||||
waitUntil { menu.protonBusyId == null }
|
||||
menu.ensureAutoUpdates()
|
||||
waitUntil { menu.protonBusyId == null }
|
||||
assertEquals(listOf("ge", "droiddeck"), attempts)
|
||||
assertTrue(ge.isDirectory)
|
||||
assertEquals(listOf("DroidDeck-Proton-11-12"), ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == "droiddeck" }))
|
||||
assertNull(menu.protonStage)
|
||||
assertEquals(-1, menu.protonPercent)
|
||||
}
|
||||
|
||||
@Test fun anUninstalledRuntimeOrCurrentProtonDoesNotStartADownload() {
|
||||
install("DroidDeck-Proton-11-12")
|
||||
menu.installer = { tool, _ -> attempts.add(tool.id); null }
|
||||
menu.ensureAutoUpdates()
|
||||
assertTrue(attempts.isEmpty())
|
||||
install("GE-Proton11-11")
|
||||
File(root, "usr/bin/gamescope").delete()
|
||||
menu.ensureAutoUpdates()
|
||||
assertTrue(attempts.isEmpty())
|
||||
assertNull(menu.protonBusyId)
|
||||
}
|
||||
|
||||
@Test fun aFailedReleaseIsNotRetriedAfterRecreatingTheLauncher() {
|
||||
install("DroidDeck-Proton-11-11.1")
|
||||
menu.installer = { tool, _ -> attempts.add(tool.id); "failed" }
|
||||
menu.ensureAutoUpdates()
|
||||
waitUntil { menu.protonBusyId == null }
|
||||
val recreated = Robolectric.buildActivity(Activity::class.java).setup().get()
|
||||
val next = ProtonMenu(recreated, Handler(Looper.getMainLooper()))
|
||||
next.installer = { tool, _ -> attempts.add(tool.id); "failed" }
|
||||
next.ensureAutoUpdates()
|
||||
assertNull(next.protonBusyId)
|
||||
assertEquals(listOf("droiddeck"), attempts)
|
||||
}
|
||||
|
||||
@Test fun automaticUpdatesWaitForEveryNonEndedSessionPhaseEvenWhenRunningIsFalse() {
|
||||
install("DroidDeck-Proton-11-11.1")
|
||||
for (phase in SessionPhase.entries.filter { it != SessionPhase.IDLE && it != SessionPhase.FAILED }) {
|
||||
SessionState.phase = phase
|
||||
menu.ensureAutoUpdates()
|
||||
assertNull("Must wait during $phase", menu.protonBusyId)
|
||||
}
|
||||
SessionState.phase = SessionPhase.FAILED
|
||||
menu.ensureAutoUpdates()
|
||||
waitUntil { menu.protonBusyId == null }
|
||||
assertEquals("DroidDeck-Proton-11-12", ProtonExtras.installed(activity, ProtonExtras.tools.first { it.id == "droiddeck" }))
|
||||
}
|
||||
|
||||
@Test fun droidDeckProtonIsInstalledWhenMissingUnlessTheUserRemovedIt() {
|
||||
menu.installer = { tool, _ -> attempts.add(tool.id); install("${tool.prefix}-11-12"); null }
|
||||
ProtonExtras.setDeclined(activity, true)
|
||||
menu.ensureAutoUpdates()
|
||||
assertNull(menu.protonBusyId)
|
||||
assertTrue(attempts.isEmpty())
|
||||
ProtonExtras.setDeclined(activity, false)
|
||||
menu.ensureAutoUpdates()
|
||||
waitUntil { menu.protonBusyId == null }
|
||||
assertEquals(listOf("droiddeck"), attempts)
|
||||
assertEquals("DroidDeck-Proton-11-12", ProtonExtras.installed(activity, ProtonExtras.tools.first { it.id == "droiddeck" }))
|
||||
assertTrue(ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == "ge" }).isEmpty())
|
||||
menu.removeProton("droiddeck")
|
||||
waitUntil { menu.protonBusyId == null }
|
||||
assertTrue(ProtonExtras.declined(activity))
|
||||
menu.installer = { _, _ -> "failed" }
|
||||
menu.installProton("droiddeck")
|
||||
waitUntil { menu.protonBusyId == null }
|
||||
assertTrue(ProtonExtras.declined(activity))
|
||||
menu.installer = { tool, _ -> install("${tool.prefix}-11-12"); null }
|
||||
menu.installProton("droiddeck")
|
||||
waitUntil { menu.protonBusyId == null }
|
||||
assertFalse(ProtonExtras.declined(activity))
|
||||
}
|
||||
|
||||
@Test fun aPendingAnimatedLaunchPreventsAnAutomaticInstall() {
|
||||
install("DroidDeck-Proton-11-11.1")
|
||||
val launcher = Robolectric.buildActivity(FrontEndActivity::class.java).get()
|
||||
val protons = ReflectionHelpers.getField<ProtonMenu>(launcher, "protons")
|
||||
protons.installer = { tool, _ -> attempts.add(tool.id); "failed" }
|
||||
Motion.refresh(launcher)
|
||||
LaunchOrigin.mark(Rect(0f, 0f, 100f, 100f), "game")
|
||||
launcher.startActivity(Intent(launcher, SessionActivity::class.java))
|
||||
assertNotNull(ReflectionHelpers.callInstanceMethod<Any?>(launcher, "getFlood"))
|
||||
assertNull(shadowOf(launcher).nextStartedActivity)
|
||||
protons.ensureAutoUpdates()
|
||||
assertNull(protons.protonBusyId)
|
||||
assertTrue(attempts.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun anAnimatedLaunchRechecksTheProtonInstallGuardBeforeStarting() {
|
||||
val launcher = Robolectric.buildActivity(FrontEndActivity::class.java).get()
|
||||
Motion.refresh(launcher)
|
||||
LaunchOrigin.mark(Rect(0f, 0f, 100f, 100f), "game")
|
||||
launcher.startActivity(Intent(launcher, SessionActivity::class.java))
|
||||
val pending = requireNotNull(ReflectionHelpers.callInstanceMethod<Any?>(launcher, "getFlood"))
|
||||
ReflectionHelpers.getField<ProtonMenu>(launcher, "protons").protonBusyId = "droiddeck"
|
||||
FrontEndActivity::class.java.getDeclaredMethod("launchFlooded", pending.javaClass)
|
||||
.apply { isAccessible = true }.invoke(launcher, pending)
|
||||
assertNull(shadowOf(launcher).nextStartedActivity)
|
||||
assertNull(ReflectionHelpers.callInstanceMethod<Any?>(launcher, "getFlood"))
|
||||
assertNull(LaunchOrigin.flooding)
|
||||
}
|
||||
|
||||
@Test fun aCancellationDuringTeardownCannotPublishIdleEarly() {
|
||||
val session = watchCancellation(SessionPhase.STOPPING)
|
||||
assertEquals(SessionPhase.STOPPING, SessionState.phase)
|
||||
assertTrue(SessionState.stopRequested)
|
||||
assertFalse(session.isFinishing)
|
||||
}
|
||||
|
||||
@Test fun cancellationBeforeSessionStartupStillFinishesTheActivity() {
|
||||
val session = watchCancellation(SessionPhase.PREPARING)
|
||||
assertEquals(SessionPhase.IDLE, SessionState.phase)
|
||||
assertFalse(SessionState.stopRequested)
|
||||
assertTrue(session.isFinishing)
|
||||
}
|
||||
|
||||
private fun watchCancellation(phase: SessionPhase): SessionActivity {
|
||||
val session = Robolectric.buildActivity(SessionActivity::class.java).get()
|
||||
ReflectionHelpers.setField(session, "loading", LoadingState(session).apply { visible = false })
|
||||
SessionState.phase = phase
|
||||
SessionState.stopRequested = true
|
||||
try {
|
||||
ReflectionHelpers.callInstanceMethod<Void>(session, "watchSession")
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
} finally {
|
||||
ReflectionHelpers.setField(session, "watching", false)
|
||||
shadowOf(Looper.getMainLooper()).idleFor(500, TimeUnit.MILLISECONDS)
|
||||
}
|
||||
return session
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@ import androidx.compose.ui.semantics.SemanticsProperties
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.ProotFastPath
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.*
|
||||
import org.junit.After
|
||||
@@ -179,6 +181,31 @@ class AgentSecurityTest {
|
||||
assertEquals(listOf("TEST=old", "STICKY=1"), AgentEnv.beginSession(context))
|
||||
}
|
||||
|
||||
@Test fun fastPathLibraryIsValidatedAndSelectedForOneSession() {
|
||||
AgentAccess.setCommandsEnabled(context, true)
|
||||
val source = File(AgentEnv.inbox(context).apply { mkdirs() }, "libblfastpath.so")
|
||||
source.writeText("wrong architecture")
|
||||
refused("INVALID_LIBRARY") { AgentEnv.override(context, source.name) }
|
||||
val header = ByteArray(64)
|
||||
byteArrayOf(0x7f, 0x45, 0x4c, 0x46, 2, 1, 1).copyInto(header)
|
||||
header[16] = 3
|
||||
header[18] = 183.toByte()
|
||||
source.writeBytes(header)
|
||||
SessionState.running = true
|
||||
try {
|
||||
refused("SESSION_ACTIVE") { AgentEnv.override(context, source.name) }
|
||||
} finally {
|
||||
SessionState.running = false
|
||||
}
|
||||
val response = AgentEnv.override(context, source.name)
|
||||
assertEquals(64, response.getString("sha256").length)
|
||||
assertEquals(ProotFastPath.LIBRARY, AgentEnv.fastPathLibrary(context))
|
||||
AgentEnv.beginSession(context)
|
||||
assertEquals("/opt/droiddeck-agent/bin/libblfastpath.so", AgentEnv.fastPathLibrary(context))
|
||||
AgentEnv.endSession(context)
|
||||
assertEquals(ProotFastPath.LIBRARY, AgentEnv.fastPathLibrary(context))
|
||||
}
|
||||
|
||||
@Test fun environmentValuesAreNotLogged() {
|
||||
AgentAccess.setCommandsEnabled(context, true)
|
||||
AgentEnv.set(context, listOf("CUSTOM=synthetic-private-value"), false)
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.droiddeck.launcher.audio
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.util.ReflectionHelpers
|
||||
import java.io.File
|
||||
import java.util.function.Consumer
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28])
|
||||
class DirectAudioMicrophoneTest {
|
||||
@get:Rule val folder = TemporaryFolder()
|
||||
|
||||
@Test fun toggleOnlyChangesTheSessionCaptureControl() {
|
||||
val fifo = File(folder.root, "mic.fifo")
|
||||
val relay = DirectAudioRelayComponent(File(folder.root, "relay.sock"), fifo)
|
||||
val changes = mutableListOf<Boolean>()
|
||||
relay.onMicEnabled = Consumer { changes.add(it) }
|
||||
val control = File(folder.root, "mic-enabled")
|
||||
assertTrue(relay.setMicEnabled(false))
|
||||
assertEquals("0", control.readText())
|
||||
assertTrue(changes.isEmpty())
|
||||
log(relay, "DA-Relay: mic enabled=0")
|
||||
assertEquals(listOf(false), changes)
|
||||
assertTrue(relay.setMicEnabled(true))
|
||||
assertEquals("1", control.readText())
|
||||
log(relay, "DA-Relay: mic enabled=1")
|
||||
assertEquals(listOf(false, true), changes)
|
||||
assertFalse(fifo.exists())
|
||||
}
|
||||
|
||||
@Test fun sessionWithoutCaptureCannotEnableIt() {
|
||||
val relay = DirectAudioRelayComponent(File(folder.root, "relay.sock"), null)
|
||||
assertFalse(relay.setMicEnabled(true))
|
||||
assertFalse(File(folder.root, "mic-enabled").exists())
|
||||
}
|
||||
|
||||
@Test fun captureDemandDoesNotOverrideTheAcknowledgedToggle() {
|
||||
val relay = DirectAudioRelayComponent(File(folder.root, "relay.sock"), File(folder.root, "mic.fifo"))
|
||||
val changes = mutableListOf<Boolean>()
|
||||
relay.onMicEnabled = Consumer { changes.add(it) }
|
||||
log(relay, "DA-Relay: mic enabled=0")
|
||||
log(relay, "DA-Relay: mic start (game wants it, 1 consumer(s))")
|
||||
log(relay, "DA-Relay: mic stop (game)")
|
||||
assertEquals(listOf(false), changes)
|
||||
assertTrue(relay.awaitMicReleased(0))
|
||||
}
|
||||
|
||||
@Test fun controlWriteFailureStillStartsPlaybackWithCaptureDisabled() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val info = context.applicationInfo
|
||||
val previous = info.nativeLibraryDir
|
||||
val nativeDir = folder.newFolder("native")
|
||||
val args = File(folder.root, "arguments")
|
||||
File(nativeDir, DirectAudioRelayComponent.BINARY).apply {
|
||||
writeText("#!/bin/sh\nprintf '%s\\n' \"\$@\" > '${args.path}.new'\nmv '${args.path}.new' '${args.path}'\n")
|
||||
setExecutable(true)
|
||||
}
|
||||
val fifo = folder.newFile("mic.fifo")
|
||||
File(folder.root, "mic-enabled.new").mkdir()
|
||||
val relay = DirectAudioRelayComponent(File(folder.root, "relay.sock"), fifo)
|
||||
relay.attach(context)
|
||||
try {
|
||||
info.nativeLibraryDir = nativeDir.path
|
||||
relay.start()
|
||||
val deadline = System.nanoTime() + 3_000_000_000L
|
||||
while (!args.isFile && System.nanoTime() < deadline) Thread.sleep(10)
|
||||
assertTrue("Playback helper did not start", args.isFile)
|
||||
val command = args.readLines()
|
||||
assertTrue(command.contains("--socket"))
|
||||
assertFalse(command.contains("--mic-fifo"))
|
||||
assertEquals(listOf("--mic-control", "/dev/null"), command.takeLast(2))
|
||||
} finally {
|
||||
info.nativeLibraryDir = previous
|
||||
}
|
||||
}
|
||||
|
||||
private fun log(relay: DirectAudioRelayComponent, line: String) =
|
||||
ReflectionHelpers.callInstanceMethod<Unit>(relay, "trackMic", ReflectionHelpers.ClassParameter.from(String::class.java, line))
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertThrows
|
||||
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 = [28], manifest = Config.NONE)
|
||||
class BackgroundAppLimitTest {
|
||||
@Test fun theLimitIsActivityManagersCachedProcessCap() {
|
||||
assertEquals("device_config get activity_manager max_cached_processes", BackgroundAppLimit.readCommand())
|
||||
assertEquals("device_config put activity_manager max_cached_processes 4", BackgroundAppLimit.setCommand(4))
|
||||
assertEquals("device_config put activity_manager max_cached_processes 0", BackgroundAppLimit.setCommand(0))
|
||||
assertThrows(IllegalArgumentException::class.java) { BackgroundAppLimit.setCommand(-1) }
|
||||
}
|
||||
|
||||
@Test fun whatWasThereIsWhatGoesBack() {
|
||||
assertNull(BackgroundAppLimit.parse("null\n"))
|
||||
assertNull(BackgroundAppLimit.parse(""))
|
||||
assertEquals("16", BackgroundAppLimit.parse("16\n"))
|
||||
assertEquals("device_config delete activity_manager max_cached_processes", BackgroundAppLimit.restoreCommand(null))
|
||||
assertEquals("device_config put activity_manager max_cached_processes 16", BackgroundAppLimit.restoreCommand("16"))
|
||||
}
|
||||
|
||||
@Test fun setupOffersOffAndDeveloperOptionsOwnLimits() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
assertEquals(BackgroundAppLimit.OFF, SessionPrefs.backgroundAppLimit(context))
|
||||
for (limit in listOf(4, 1, 0, BackgroundAppLimit.OFF)) {
|
||||
SessionPrefs.setBackgroundAppLimit(context, limit)
|
||||
assertEquals(limit, SessionPrefs.backgroundAppLimit(context))
|
||||
}
|
||||
assertThrows(IllegalArgumentException::class.java) { SessionPrefs.setBackgroundAppLimit(context, 7) }
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class CpuAllocationDefaultsTest {
|
||||
private val thor = (0..7).associateWith { when (it) { in 0..2 -> 2.016; in 3..6 -> 2.8032; else -> 3.1872 } }
|
||||
|
||||
@Test fun gen2UsesTheFourMiddleCoresAndOnePrime() {
|
||||
for (model in listOf("SM8550", "QCS8550", "sm8550-ac")) {
|
||||
assertEquals(CpuAllocationDefaults.Allocation("7", "3,4,5,6"), CpuAllocationDefaults.forDevice(model, "", thor))
|
||||
}
|
||||
assertEquals(CpuAllocationDefaults.Allocation("7", "3,4,5,6"), CpuAllocationDefaults.forDevice("", "kalama", thor))
|
||||
}
|
||||
|
||||
@Test fun coreNumbersAndClockVariantsAreDetectedInsteadOfHardcoded() {
|
||||
val reordered = mapOf(0 to 3.36, 1 to 2.0, 2 to 2.0, 3 to 2.0, 4 to 2.8, 5 to 2.8, 6 to 2.8, 7 to 2.8)
|
||||
assertEquals(CpuAllocationDefaults.Allocation("0", "4,5,6,7"), CpuAllocationDefaults.forDevice("SM8550-AC", "kalama", reordered))
|
||||
}
|
||||
|
||||
@Test fun anotherOrUnknownChipDoesNotAcquireThisDefault() {
|
||||
assertNull(CpuAllocationDefaults.forDevice("SM8650", "pineapple", thor))
|
||||
assertNull(CpuAllocationDefaults.forDevice("SM8650", "kalama", thor))
|
||||
assertNull(CpuAllocationDefaults.forDevice("", "", thor))
|
||||
}
|
||||
|
||||
@Test fun missingOrUnexpectedTopologyKeepsTheSchedulerDefault() {
|
||||
assertNull(CpuAllocationDefaults.forDevice("SM8550", "kalama", thor - 7))
|
||||
assertNull(CpuAllocationDefaults.forDevice("SM8550", "kalama", thor + (7 to null)))
|
||||
assertNull(CpuAllocationDefaults.forDevice("SM8550", "kalama", thor + (7 to 0.0)))
|
||||
assertNull(CpuAllocationDefaults.forDevice("SM8550", "kalama", thor + (7 to Double.NaN)))
|
||||
assertNull(CpuAllocationDefaults.forDevice("SM8550", "kalama", (0..7).associateWith { 2.8 }))
|
||||
}
|
||||
|
||||
@Test fun allCoreGamesUndoTheClientsInheritedRestriction() {
|
||||
val all = CpuCores.listOrAll("")
|
||||
assertEquals(all, CpuCores.gameLaunchList("", clientPinned = true))
|
||||
assertEquals(all, CpuCores.gameLaunchList(all, clientPinned = true))
|
||||
assertEquals("", CpuCores.gameLaunchList("", clientPinned = false))
|
||||
assertEquals("0", CpuCores.gameLaunchList("0", clientPinned = true))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import java.net.InetSocketAddress
|
||||
import java.net.Proxy
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
class DownloadSourceProxyTest {
|
||||
@Test fun hostAndPortBecomeAnHttpProxy() {
|
||||
val proxy = DownloadSource.proxyOf("127.0.0.1:9910")
|
||||
assertEquals(Proxy.Type.HTTP, proxy?.type())
|
||||
val address = proxy?.address() as InetSocketAddress
|
||||
assertEquals("127.0.0.1", address.hostString)
|
||||
assertEquals(9910, address.port)
|
||||
}
|
||||
|
||||
@Test fun missingOrInvalidPortIsIgnored() {
|
||||
assertNull(DownloadSource.proxyOf(""))
|
||||
assertNull(DownloadSource.proxyOf("127.0.0.1"))
|
||||
assertNull(DownloadSource.proxyOf("127.0.0.1:"))
|
||||
assertNull(DownloadSource.proxyOf("127.0.0.1:notaport"))
|
||||
}
|
||||
|
||||
@Test fun normalizationAcceptsSchemeAndTrailingSlash() {
|
||||
assertEquals("127.0.0.1:9910", DownloadSource.normalizeProxy(" http://127.0.0.1:9910/ "))
|
||||
assertEquals("192.168.1.2:8080", DownloadSource.normalizeProxy("192.168.1.2:8080"))
|
||||
}
|
||||
|
||||
@Test fun invalidInputDisablesTheProxy() {
|
||||
assertEquals("", DownloadSource.normalizeProxy(""))
|
||||
assertEquals("", DownloadSource.normalizeProxy("127.0.0.1"))
|
||||
assertEquals("", DownloadSource.normalizeProxy("127.0.0.1:70000"))
|
||||
assertEquals("", DownloadSource.normalizeProxy("http://127.0.0.1:notaport"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class HostProcessTest {
|
||||
@get:Rule val temporary = TemporaryFolder()
|
||||
|
||||
@Test fun appendsBothOutputStreamsToTheExistingLog() {
|
||||
val windows = System.getProperty("os.name").orEmpty().startsWith("Windows")
|
||||
val log = temporary.newFile("session.log").apply { writeText("guest output\n") }
|
||||
val script = temporary.newFile(if (windows) "tracer.cmd" else "tracer.sh").apply {
|
||||
writeText(if (windows) "@echo off\r\necho tracer stdout\r\necho tracer stderr>&2\r\n"
|
||||
else "printf 'tracer stdout\\n'\nprintf 'tracer stderr\\n' >&2\n")
|
||||
}
|
||||
val finished = CountDownLatch(1)
|
||||
var exitCode = -1
|
||||
val shell = if (windows) "cmd.exe /c" else "/bin/sh"
|
||||
HostProcess.start("$shell ${script.name}", null, temporary.root, {
|
||||
exitCode = it
|
||||
finished.countDown()
|
||||
}, null, log)
|
||||
assertTrue(finished.await(5, TimeUnit.SECONDS))
|
||||
assertEquals(0, exitCode)
|
||||
assertEquals(listOf("guest output", "tracer stdout", "tracer stderr"), log.readLines())
|
||||
}
|
||||
}
|
||||
@@ -195,6 +195,7 @@ class LogRedactorTest {
|
||||
"auth: login=maskeduser42&remember=1",
|
||||
"accountName: maskeduser42",
|
||||
"{\"username\": \"masked user 42\"}",
|
||||
"[Clubs] {Main} Club membership subscription created: |accountId=maskeduser42",
|
||||
)
|
||||
for (line in lines) {
|
||||
val out = LogRedactor.redactForShare(line)
|
||||
|
||||
@@ -14,20 +14,6 @@ class ZramSupportTest {
|
||||
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")))
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import java.io.File
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
|
||||
class FileManagerNavigationTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
@Test fun backCannotNavigateAboveTheCurrentDriveRoot() {
|
||||
val drive = tmp.newFolder("drive")
|
||||
val child = File(drive, "folder").apply { mkdir() }
|
||||
|
||||
assertTrue(canNavigateUp(child, drive))
|
||||
assertFalse(canNavigateUp(drive, drive))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import java.io.File
|
||||
import java.util.concurrent.CancellationException
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
class FileOpsCancellationTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
@Test fun cancellingCopyRemovesAnIncompleteNewFile() {
|
||||
val source = tmp.newFile("source").apply { writeBytes(ByteArray(5 * 1024 * 1024)) }
|
||||
val destination = File(tmp.root, "destination")
|
||||
var cancelled = false
|
||||
|
||||
assertThrows(CancellationException::class.java) {
|
||||
FileOps.copyWithProgress(source, destination, { _, _ -> cancelled = true }) { cancelled }
|
||||
}
|
||||
|
||||
assertTrue(source.exists())
|
||||
assertFalse(destination.exists())
|
||||
}
|
||||
|
||||
@Test fun cancellingMoveFallbackPreservesTheSourceAndExistingDestination() {
|
||||
val source = tmp.newFile("source").apply { writeText("replacement") }
|
||||
val destination = tmp.newFile("destination").apply { writeText("original") }
|
||||
var cancelled = false
|
||||
|
||||
assertThrows(CancellationException::class.java) {
|
||||
FileOps.moveWithProgress(source, destination, { _, _ -> cancelled = true }) { cancelled }
|
||||
}
|
||||
|
||||
assertEquals("replacement", source.readText())
|
||||
assertEquals("original", destination.readText())
|
||||
}
|
||||
|
||||
@Test fun aCommittedMoveFinishesRemovingTheSourceDespiteCancellation() {
|
||||
val source = tmp.newFile("source").apply { writeText("replacement") }
|
||||
val destination = tmp.newFile("destination").apply { writeText("original") }
|
||||
val isCancelled = { destination.readText() == "replacement" }
|
||||
|
||||
assertTrue(FileOps.moveWithProgress(source, destination, null, isCancelled))
|
||||
|
||||
assertTrue(isCancelled())
|
||||
assertEquals("replacement", destination.readText())
|
||||
assertFalse(source.exists())
|
||||
assertEquals(setOf("destination"), tmp.root.list()!!.toSet())
|
||||
}
|
||||
|
||||
@Test fun cancellingTheSizeScanStopsBeforeCreatingTheDestination() {
|
||||
val source = tmp.newFolder("source")
|
||||
repeat(3) { File(source, "file-$it").writeText("content") }
|
||||
val destination = File(tmp.root, "destination")
|
||||
var checks = 0
|
||||
|
||||
assertThrows(CancellationException::class.java) {
|
||||
FileOps.copyWithProgress(source, destination, null) {
|
||||
assertFalse(destination.exists())
|
||||
++checks > 2
|
||||
}
|
||||
}
|
||||
|
||||
assertEquals(3, checks)
|
||||
assertFalse(destination.exists())
|
||||
assertEquals(3, source.listFiles()?.size)
|
||||
}
|
||||
|
||||
@Test fun cancellingCopyRemovesANewDestinationDirectory() {
|
||||
val source = tmp.newFolder("source")
|
||||
val payload = File(source, "nested/payload").apply {
|
||||
parentFile!!.mkdirs()
|
||||
writeText("content")
|
||||
}
|
||||
val destination = File(tmp.root, "destination")
|
||||
|
||||
assertThrows(CancellationException::class.java) {
|
||||
FileOps.copyWithProgress(source, destination, { _, _ -> throw CancellationException("cancel") })
|
||||
}
|
||||
|
||||
assertEquals("content", payload.readText())
|
||||
assertFalse(destination.exists())
|
||||
}
|
||||
|
||||
@Test fun cancellingCopyPreservesAnExistingDestinationDirectory() {
|
||||
val source = tmp.newFolder("source")
|
||||
File(source, "nested/payload").apply {
|
||||
parentFile!!.mkdirs()
|
||||
writeText("replacement")
|
||||
}
|
||||
val destination = tmp.newFolder("destination")
|
||||
val existing = File(destination, "keep").apply { writeText("original") }
|
||||
|
||||
assertThrows(CancellationException::class.java) {
|
||||
FileOps.copyWithProgress(source, destination, { _, _ -> throw CancellationException("cancel") })
|
||||
}
|
||||
|
||||
assertEquals("original", existing.readText())
|
||||
assertEquals(setOf("keep"), destination.list()!!.toSet())
|
||||
}
|
||||
|
||||
@Test fun cancellingRecursiveDeleteStopsBeforeTheNextFile() {
|
||||
val directory = tmp.newFolder("directory")
|
||||
repeat(3) { File(directory, "file-$it").writeText("content") }
|
||||
var checks = 0
|
||||
|
||||
assertThrows(CancellationException::class.java) {
|
||||
FileOps.delete(directory) { ++checks > 3 }
|
||||
}
|
||||
|
||||
assertTrue(directory.exists())
|
||||
assertEquals(2, directory.listFiles()?.size)
|
||||
}
|
||||
}
|
||||
@@ -53,27 +53,25 @@ class FileOpsCopyTest {
|
||||
assertEquals("replacement", src.readText())
|
||||
}
|
||||
|
||||
@Test fun cancellingStopsATreeOfEmptyFiles() {
|
||||
@Test fun cancellingRemovesANewTreeOfEmptyFiles() {
|
||||
val src = tmp.newFolder("source")
|
||||
for (name in listOf("a", "b", "c")) File(src, name).createNewFile()
|
||||
val dst = File(tmp.root, "dest")
|
||||
var checks = 0
|
||||
assertThrows(CancellationException::class.java) {
|
||||
FileOps.copyWithProgress(src, dst, null) { checks++ > 1 }
|
||||
FileOps.copyWithProgress(src, dst, null) { dst.list()?.isNotEmpty() == true }
|
||||
}
|
||||
assertEquals(1, dst.list()!!.size)
|
||||
assertFalse(dst.exists())
|
||||
assertEquals(3, src.list()!!.size)
|
||||
}
|
||||
|
||||
@Test fun cancellingStopsATreeOfEmptyFolders() {
|
||||
@Test fun cancellingRemovesANewTreeOfEmptyFolders() {
|
||||
val src = tmp.newFolder("source")
|
||||
for (name in listOf("a", "b", "c")) File(src, name).mkdir()
|
||||
val dst = File(tmp.root, "dest")
|
||||
var checks = 0
|
||||
assertThrows(CancellationException::class.java) {
|
||||
FileOps.copyWithProgress(src, dst, null) { checks++ > 1 }
|
||||
FileOps.copyWithProgress(src, dst, null) { dst.list()?.isNotEmpty() == true }
|
||||
}
|
||||
assertEquals(1, dst.list()!!.size)
|
||||
assertFalse(dst.exists())
|
||||
}
|
||||
|
||||
@Test fun aCompletedCopyReplacesTheDestination() {
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class StorageRootsTest {
|
||||
@Test fun usbAndSdMountsAreFound() {
|
||||
val mounts = """
|
||||
/dev/fuse /mnt/user/0/emulated fuse rw,nosuid,nodev 0 0
|
||||
/dev/block/vold/public:8,1 /mnt/media_rw/A1B2-C3D4 vfat rw,dirsync 0 0
|
||||
/mnt/media_rw/A1B2-C3D4 /storage/A1B2-C3D4 fuse rw,nosuid,nodev 0 0
|
||||
/dev/block/vold/public:179,65 /mnt/media_rw/9C33-1A2B exfat rw,dirsync 0 0
|
||||
/mnt/media_rw/9C33-1A2B /storage/9C33-1A2B fuse rw,nosuid,nodev 0 0
|
||||
/dev/block/dm-5 /data ext4 rw,seclabel 0 0
|
||||
""".trimIndent()
|
||||
|
||||
val points = StorageRoots.parseExternalMounts(mounts).map { it.path }
|
||||
|
||||
assertTrue(points.contains("/storage/A1B2-C3D4"))
|
||||
assertTrue(points.contains("/storage/9C33-1A2B"))
|
||||
assertTrue(points.contains("/mnt/media_rw/A1B2-C3D4"))
|
||||
}
|
||||
|
||||
@Test fun voldLocationsCountWhateverTheFstypeIs() {
|
||||
val mounts = """
|
||||
/dev/block/sda1 /storage/0D19-CC0A fuse rw,nosuid,nodev 0 0
|
||||
/dev/block/sda1 /mnt/media_rw/0D19-CC0A exfat rw,dirsync 0 0
|
||||
""".trimIndent()
|
||||
|
||||
val points = StorageRoots.parseExternalMounts(mounts).map { it.path }
|
||||
|
||||
assertTrue(points.contains("/storage/0D19-CC0A"))
|
||||
assertTrue(points.contains("/mnt/media_rw/0D19-CC0A"))
|
||||
}
|
||||
|
||||
@Test fun usbMountsDirectlyUnderMntAreFound() {
|
||||
val mounts = """
|
||||
/dev/block/sda1 /mnt/usb_storage exfat rw,dirsync 0 0
|
||||
tmpfs /mnt/media_rw tmpfs rw,seclabel 0 0
|
||||
/dev/fuse /mnt/user/0/emulated fuse rw,nosuid,nodev 0 0
|
||||
""".trimIndent()
|
||||
|
||||
val points = StorageRoots.parseExternalMounts(mounts).map { it.path }
|
||||
|
||||
assertTrue(points.contains("/mnt/usb_storage"))
|
||||
assertEquals(1, points.size)
|
||||
}
|
||||
|
||||
@Test fun emulatedAndSystemMountsAreIgnored() {
|
||||
val mounts = """
|
||||
/dev/fuse /mnt/user/0/emulated fuse rw,nosuid,nodev 0 0
|
||||
/mnt/media_rw/emulated /storage/emulated sdcardfs rw,nosuid,nodev 0 0
|
||||
tmpfs /storage/self tmpfs rw,seclabel 0 0
|
||||
overlay /system ext4 ro,seclabel 0 0
|
||||
/dev/block/sda1 /data ext4 rw,seclabel 0 0
|
||||
""".trimIndent()
|
||||
|
||||
assertEquals(emptyList<String>(), StorageRoots.parseExternalMounts(mounts).map { it.path })
|
||||
}
|
||||
|
||||
@Test fun escapedSpacesAndNtfsAreHandled() {
|
||||
val mounts = "/dev/block/vold/public:8,1 /mnt/media_rw/My\\040USB ntfs rw,dirsync 0 0\n" +
|
||||
"/mnt/media_rw/My\\040USB /storage/My\\040USB fuse rw,nosuid,nodev 0 0\n"
|
||||
|
||||
val points = StorageRoots.parseExternalMounts(mounts).map { it.path }
|
||||
|
||||
assertTrue(points.contains("/mnt/media_rw/My USB"))
|
||||
assertTrue(points.contains("/storage/My USB"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import com.droiddeck.launcher.frontend.AddedGameArt.Slot
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
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.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import java.io.File
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class AddedGameArtFillTest {
|
||||
private val app get() = RuntimeEnvironment.getApplication()
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
private val coverBytes = byteArrayOf(9, 9, 9)
|
||||
|
||||
private fun game(name: String, appId: Long, cover: Boolean = true, source: String = Library.ADDED): AddedGames.Game {
|
||||
val dir = tmp.newFolder(name)
|
||||
File(dir, "steam_appid.txt").writeText("504230")
|
||||
if (cover) File(dir, "cover.jpg").writeBytes(coverBytes)
|
||||
val exe = File(dir, "$name.exe").apply { writeText("x") }
|
||||
return AddedGames.Game(dir, name, exe, "/g/$name.exe", "/g", appId, appId, emptyList(), source = source)
|
||||
}
|
||||
|
||||
private class Calls {
|
||||
val steam = ArrayList<Set<Slot>>()
|
||||
val sgdb = ArrayList<Set<Slot>>()
|
||||
var lookups = 0
|
||||
var store = 0
|
||||
}
|
||||
|
||||
private val steamNames = mapOf(Slot.COVER to "p.jpg", Slot.WIDE to "header.jpg", Slot.BACKGROUND to "hero.jpg", Slot.LOGO to "logo.png")
|
||||
|
||||
private fun sources(
|
||||
calls: Calls, steamHas: Set<Slot> = emptySet(), sgdbHas: Set<Slot> = emptySet(),
|
||||
storeHas: Boolean = false, sgdbFails: Boolean = false,
|
||||
) = AddedGameArt.Sources(
|
||||
storeLogo = { g ->
|
||||
calls.store++
|
||||
if (storeHas) File(g.folder, "logo.png").writeBytes(byteArrayOf(4))
|
||||
storeHas
|
||||
},
|
||||
steamSearch = { fail("searched although the game names its appid"); null },
|
||||
steam = { id, cache, slots ->
|
||||
assertEquals("504230", id)
|
||||
calls.steam += slots
|
||||
(slots intersect steamHas).onEach { File(cache, steamNames.getValue(it)).writeBytes(byteArrayOf(1)) }.isNotEmpty()
|
||||
},
|
||||
sgdbGame = { _, steamId, _ ->
|
||||
calls.lookups++
|
||||
assertEquals(504230, steamId)
|
||||
77
|
||||
},
|
||||
sgdb = { _, id, cache, slots ->
|
||||
assertEquals(77, id)
|
||||
if (sgdbFails) throw SteamGridDb.Failed(SteamGridDb.Status.OFFLINE)
|
||||
calls.sgdb += slots
|
||||
(slots intersect sgdbHas).onEach { File(cache, SteamGridDb.cacheName(it)).writeBytes(byteArrayOf(2)) }.isNotEmpty()
|
||||
},
|
||||
)
|
||||
|
||||
@Test fun aGameWithItsOwnCoverStillGetsItsLogoAndIcon() {
|
||||
val g = game("Celeste", 0x81000001L)
|
||||
val calls = Calls()
|
||||
assertTrue(AddedGameArt.fetchMissing(app, listOf(g), "key", sources(calls, steamHas = setOf(Slot.LOGO), sgdbHas = setOf(Slot.ICON))))
|
||||
assertEquals(listOf(setOf(Slot.LOGO)), calls.steam)
|
||||
assertEquals(listOf(setOf(Slot.ICON)), calls.sgdb)
|
||||
assertEquals(0, calls.store)
|
||||
val cache = AddedGameArt.cacheDir(app, g)
|
||||
assertFalse(File(cache, "p.jpg").exists())
|
||||
assertArrayEquals(coverBytes, File(g.folder, "cover.jpg").readBytes())
|
||||
val art = AddedGameArt.resolve(app, g)
|
||||
assertEquals(File(g.folder, "cover.jpg"), art.portrait)
|
||||
assertEquals(File(cache, "logo.png"), art.logo)
|
||||
assertEquals(File(cache, "icon-sgdb.png"), art.icon)
|
||||
assertFalse(File(cache, AddedGameArt.EXTRAS_TRIED).exists())
|
||||
}
|
||||
|
||||
@Test fun filledOrChosenSlotsAreNeverAskedFor() {
|
||||
val g = game("Hades", 0x81000002L)
|
||||
File(g.folder, "logo.png").writeBytes(byteArrayOf(5))
|
||||
val picked = File(tmp.root, "mine.png").apply { writeBytes(byteArrayOf(6)) }
|
||||
assertTrue(AddedGameArt.store(AddedGameArt.cacheDir(app, g), Slot.ICON, AddedGameArt.Option(AddedGameArt.FILE, picked.path, picked.path)))
|
||||
val calls = Calls()
|
||||
assertFalse(AddedGameArt.fetchMissing(app, listOf(g), "key", sources(calls, steamHas = Slot.values().toSet(), sgdbHas = Slot.values().toSet())))
|
||||
assertTrue(calls.steam.isEmpty() && calls.sgdb.isEmpty() && calls.lookups == 0)
|
||||
assertArrayEquals(byteArrayOf(5), File(g.folder, "logo.png").readBytes())
|
||||
}
|
||||
|
||||
@Test fun withoutAKeyAMissingIconAloneAsksNothing() {
|
||||
val g = game("Inside", 0x81000003L)
|
||||
File(g.folder, "logo.png").writeBytes(byteArrayOf(5))
|
||||
val calls = Calls()
|
||||
assertFalse(AddedGameArt.fetchMissing(app, listOf(g), "", sources(calls)))
|
||||
assertTrue(calls.steam.isEmpty() && calls.sgdb.isEmpty() && calls.lookups == 0)
|
||||
assertFalse(AddedGameArt.cacheDir(app, g).exists())
|
||||
}
|
||||
|
||||
@Test fun aMissIsAskedAgainOnlyAfterAWeek() {
|
||||
val g = game("Limbo", 0x81000004L)
|
||||
val calls = Calls()
|
||||
assertFalse(AddedGameArt.fetchMissing(app, listOf(g), "key", sources(calls)))
|
||||
assertEquals(listOf(setOf(Slot.LOGO)), calls.steam)
|
||||
assertEquals(listOf(setOf(Slot.LOGO, Slot.ICON)), calls.sgdb)
|
||||
AddedGameArt.fetchMissing(app, listOf(g), "key", sources(calls))
|
||||
assertEquals(1, calls.steam.size)
|
||||
assertEquals(1, calls.sgdb.size)
|
||||
val tried = File(AddedGameArt.cacheDir(app, g), AddedGameArt.EXTRAS_TRIED)
|
||||
assertTrue(tried.setLastModified(System.currentTimeMillis() - 8L * 24 * 3600 * 1000))
|
||||
assertTrue(AddedGameArt.fetchMissing(app, listOf(g), "key", sources(calls, steamHas = setOf(Slot.LOGO), sgdbHas = setOf(Slot.ICON))))
|
||||
assertEquals(2, calls.steam.size)
|
||||
assertEquals(setOf(Slot.ICON), calls.sgdb.last())
|
||||
assertFalse(tried.exists())
|
||||
}
|
||||
|
||||
@Test fun theStoresOwnLogoComesFirst() {
|
||||
val g = game("Metalstorm", 0x81000005L, source = "gog")
|
||||
val calls = Calls()
|
||||
assertTrue(AddedGameArt.fetchMissing(app, listOf(g), "key", sources(calls, storeHas = true, steamHas = setOf(Slot.LOGO), sgdbHas = setOf(Slot.ICON))))
|
||||
assertEquals(1, calls.store)
|
||||
assertTrue(calls.steam.isEmpty())
|
||||
assertEquals(listOf(setOf(Slot.ICON)), calls.sgdb)
|
||||
assertEquals(File(g.folder, "logo.png"), AddedGameArt.resolve(app, g).logo)
|
||||
}
|
||||
|
||||
@Test fun aGameWithoutACoverStillGetsEverySlot() {
|
||||
val g = game("Tunic", 0x81000006L, cover = false)
|
||||
val calls = Calls()
|
||||
assertTrue(AddedGameArt.fetchMissing(app, listOf(g), "key",
|
||||
sources(calls, steamHas = setOf(Slot.COVER, Slot.WIDE, Slot.BACKGROUND), sgdbHas = setOf(Slot.LOGO, Slot.ICON))))
|
||||
assertEquals(listOf(setOf(Slot.COVER, Slot.WIDE, Slot.BACKGROUND, Slot.LOGO)), calls.steam)
|
||||
assertEquals(listOf(setOf(Slot.LOGO, Slot.ICON)), calls.sgdb)
|
||||
assertTrue(AddedGameArt.missing(app, g).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun aSteamGridDbFailureIsNotRememberedAndStopsThePass() {
|
||||
val first = game("Gris", 0x81000007L)
|
||||
val second = game("Hollow", 0x81000008L)
|
||||
val calls = Calls()
|
||||
AddedGameArt.fetchMissing(app, listOf(first, second), "key", sources(calls, sgdbFails = true))
|
||||
assertEquals(2, calls.steam.size)
|
||||
assertEquals(1, calls.lookups)
|
||||
assertFalse(File(AddedGameArt.cacheDir(app, first), AddedGameArt.EXTRAS_TRIED).exists())
|
||||
assertFalse(File(AddedGameArt.cacheDir(app, second), AddedGameArt.EXTRAS_TRIED).exists())
|
||||
}
|
||||
|
||||
@Test fun nothingIsFetchedWhenArtIsOff() {
|
||||
SessionPrefs.setAddedGamesArt(app, false)
|
||||
val calls = Calls()
|
||||
assertFalse(AddedGameArt.fetchMissing(app, listOf(game("Off", 0x81000009L)), "key", sources(calls)))
|
||||
assertTrue(calls.steam.isEmpty())
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import com.droiddeck.launcher.BuildConfig
|
||||
import com.droiddeck.launcher.stores.CredentialCipher
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
@@ -92,8 +93,9 @@ class AddedGameArtLookupTest {
|
||||
assertEquals("build", SteamGridDb.pick("", "build"))
|
||||
assertEquals("build", SteamGridDb.pick(" ", "build"))
|
||||
assertEquals("", SteamGridDb.pick("", ""))
|
||||
assertEquals("", SteamGridDb.builtInKey())
|
||||
assertEquals("", SteamGridDb.key(app))
|
||||
val builtIn = SteamGridDb.builtInKey()
|
||||
assertTrue(builtIn == BuildConfig.SGDB_API_KEY)
|
||||
assertTrue(SteamGridDb.key(app) == builtIn.trim())
|
||||
}
|
||||
|
||||
@Test fun theUsersKeyIsSealedOnDiskAndClears() {
|
||||
@@ -106,7 +108,7 @@ class AddedGameArtLookupTest {
|
||||
assertEquals("abcdef0123456789secretkey", SteamGridDb.key(app))
|
||||
SteamGridDb.setUserKey(app, "")
|
||||
assertFalse(file.exists())
|
||||
assertEquals("", SteamGridDb.key(app))
|
||||
assertTrue(SteamGridDb.key(app) == SteamGridDb.builtInKey().trim())
|
||||
}
|
||||
|
||||
@Test fun aFailedLookupIsNotRememberedAsNoMatch() {
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import java.io.File
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
|
||||
class AddedGamesAccountTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
private fun steamRoot(vararg blocks: Pair<Long, Map<String, String>>): File = tmp.newFolder("Steam").also { root ->
|
||||
File(root, "config").mkdirs()
|
||||
File(root, "userdata/123/config").mkdirs()
|
||||
File(root, "userdata/456/config").mkdirs()
|
||||
val body = blocks.joinToString("") { (account, keys) ->
|
||||
"\t\"${76561197960265728L + account}\"\n\t{\n" + keys.entries.joinToString("") { "\t\t\"${it.key}\"\t\t\"${it.value}\"\n" } + "\t}\n"
|
||||
}
|
||||
File(root, "config/loginusers.vdf").writeText("\"users\"\n{\n$body}\n")
|
||||
}
|
||||
|
||||
@Test fun theAccountMarkedMostRecentIsUsed() {
|
||||
val root = steamRoot(123L to mapOf("MostRecent" to "1", "AutoLogin" to "0", "timestamp" to "100"),
|
||||
456L to mapOf("MostRecent" to "0", "AutoLogin" to "1", "timestamp" to "200"))
|
||||
assertEquals(File(root, "userdata/123/config"), AddedGames.accountConfig(root))
|
||||
}
|
||||
|
||||
@Test fun withoutMostRecentTheAccountThatSignsInIsUsed() {
|
||||
val root = steamRoot(123L to mapOf("AutoLogin" to "1", "timestamp" to "100"), 456L to mapOf("AutoLogin" to "0", "timestamp" to "200"))
|
||||
assertEquals(File(root, "userdata/123/config"), AddedGames.accountConfig(root))
|
||||
}
|
||||
|
||||
@Test fun withoutEitherMarkTheAccountUsedLastIsUsed() {
|
||||
val root = steamRoot(456L to mapOf("AutoLogin" to "0", "timestamp" to "100"), 123L to mapOf("AutoLogin" to "0", "timestamp" to "200"))
|
||||
assertEquals(File(root, "userdata/123/config"), AddedGames.accountConfig(root))
|
||||
}
|
||||
|
||||
@Test fun twoAccountsWithoutAnyMarkGiveNoAccount() {
|
||||
val root = steamRoot(123L to mapOf("AccountName" to "a"), 456L to mapOf("AccountName" to "b"))
|
||||
assertNull(AddedGames.accountConfig(root))
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.app.Activity
|
||||
import com.droiddeck.launcher.LauncherIcon
|
||||
import com.droiddeck.launcher.MainActivity
|
||||
import com.droiddeck.launcher.FrontEndActivity
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
@@ -54,7 +54,7 @@ class GameShortcutIntentTest {
|
||||
|
||||
assertEquals(Intent.ACTION_VIEW, intent.action)
|
||||
assertEquals(Uri.parse("droiddeck://game/$id"), intent.data)
|
||||
assertEquals(MainActivity::class.java.name, intent.component?.className)
|
||||
assertEquals(FrontEndActivity::class.java.name, intent.component?.className)
|
||||
assertEquals(android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP or android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP, intent.flags)
|
||||
}
|
||||
|
||||
@@ -69,8 +69,8 @@ class GameShortcutIntentTest {
|
||||
val launch = requireNotNull(shortcut.intent)
|
||||
assertEquals("game:8400", shortcut.id)
|
||||
assertEquals("Geometry Wars: Retro Evolved", shortcut.shortLabel.toString())
|
||||
assertEquals("com.droiddeck.launcher.LauncherDark", shortcut.activity?.className)
|
||||
assertEquals(MainActivity::class.java.name, launch.component?.className)
|
||||
assertEquals("com.droiddeck.launcher.MainActivity", shortcut.activity?.className)
|
||||
assertEquals(FrontEndActivity::class.java.name, launch.component?.className)
|
||||
assertEquals(Intent.ACTION_VIEW, launch.action)
|
||||
assertEquals(Uri.parse("droiddeck://game/8400"), launch.data)
|
||||
assertEquals(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP, launch.flags)
|
||||
@@ -93,4 +93,38 @@ class GameShortcutIntentTest {
|
||||
|
||||
assertNotNull(GameShortcuts.result(activity, game))
|
||||
}
|
||||
|
||||
@Test fun theDefaultLauncherEntryKeepsTheMainActivityName() {
|
||||
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
|
||||
val launchers = activity.packageManager.queryIntentActivities(
|
||||
Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER).setPackage(activity.packageName), 0)
|
||||
|
||||
assertEquals(listOf("com.droiddeck.launcher.MainActivity"), launchers.map { it.activityInfo.name })
|
||||
assertEquals(android.content.ComponentName(activity, "com.droiddeck.launcher.MainActivity"), LauncherIcon.activity(activity))
|
||||
}
|
||||
|
||||
@Test fun repairDropsTheDefaultIconLeftBesideAChosenLightIcon() {
|
||||
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
|
||||
val pm = activity.packageManager
|
||||
pm.setComponentEnabledSetting(android.content.ComponentName(activity, "com.droiddeck.launcher.LauncherLight"),
|
||||
android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED, android.content.pm.PackageManager.DONT_KILL_APP)
|
||||
val dark = android.content.ComponentName(activity, "com.droiddeck.launcher.MainActivity")
|
||||
|
||||
LauncherIcon.repair(activity, dark)
|
||||
assertEquals(android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, pm.getComponentEnabledSetting(dark))
|
||||
|
||||
LauncherIcon.repair(activity, android.content.ComponentName(activity, "com.droiddeck.launcher.LauncherLight"))
|
||||
assertEquals(android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED, pm.getComponentEnabledSetting(dark))
|
||||
assertEquals(LauncherIcon.LIGHT, LauncherIcon.current(activity))
|
||||
}
|
||||
|
||||
@Test fun repairLeavesASingleIconAlone() {
|
||||
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
|
||||
val dark = android.content.ComponentName(activity, "com.droiddeck.launcher.MainActivity")
|
||||
|
||||
LauncherIcon.repair(activity, null)
|
||||
|
||||
assertEquals(android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, activity.packageManager.getComponentEnabledSetting(dark))
|
||||
assertEquals(LauncherIcon.DARK, LauncherIcon.current(activity))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
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.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import java.io.File
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class GameLogoTest {
|
||||
private val app get() = RuntimeEnvironment.getApplication()
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
@Before fun noGamesFolders() {
|
||||
AddedGamesPublisher.now = true
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
SessionPrefs.setAddedGamesDirs(app, emptyList())
|
||||
}
|
||||
|
||||
private fun image(name: String) = File(tmp.root, name).apply { parentFile?.mkdirs(); writeBytes(ByteArray(8) { 1 }) }
|
||||
|
||||
@Test fun steamsCachedLogoIsFoundInTheAppFolderOrAHashedOne() {
|
||||
val cache = tmp.newFolder("librarycache")
|
||||
val logo = File(cache, "620/3f1c/logo.png").apply { parentFile?.mkdirs(); writeBytes(ByteArray(4) { 1 }) }
|
||||
assertEquals(logo, Library.steamCacheImage(cache, 620, Library.STEAM_LOGOS))
|
||||
File(cache, "730").mkdirs()
|
||||
File(cache, "730/logo.png").writeBytes(ByteArray(0))
|
||||
assertNull(Library.steamCacheImage(cache, 730, Library.STEAM_LOGOS))
|
||||
}
|
||||
|
||||
@Test fun aSteamScanKeepsEveryArtworkSlotAndSeesNewHashDirectories() {
|
||||
val root = SessionPrefs.steamRoot(app, "arm64")
|
||||
File(root, "steamapps/appmanifest_620.acf").apply {
|
||||
parentFile!!.mkdirs()
|
||||
writeText("\"AppState\"\n{\n\"name\" \"Portal 2\"\n\"StateFlags\" \"4\"\n}\n")
|
||||
}
|
||||
val cache = File(root, "appcache/librarycache/620")
|
||||
fun cached(path: String) = File(cache, path).apply {
|
||||
parentFile!!.mkdirs()
|
||||
writeBytes(byteArrayOf(1))
|
||||
}
|
||||
val cover = cached("library_capsule.jpg")
|
||||
val hero = cached("hash/library_hero.jpg")
|
||||
val icon = cached("${"a".repeat(40)}.jpg")
|
||||
val game = Library.steamGames(app, arch = "arm64").single()
|
||||
assertEquals(listOf(cover, hero, icon, null), listOf(game.art, game.hero, game.icon, game.logo))
|
||||
|
||||
val logo = cached("new-hash/logo.png")
|
||||
val refreshed = Library.steamGames(app, arch = "arm64").single()
|
||||
assertEquals(listOf(cover, hero, icon, logo), listOf(refreshed.art, refreshed.hero, refreshed.icon, refreshed.logo))
|
||||
}
|
||||
|
||||
@Test fun aChosenLogoWinsOverSteamsAndKeepsTheRest() {
|
||||
val stock = image("logo.png")
|
||||
val game = Library.SteamGame(620, "Portal 2", null, "Steam library", logo = stock)
|
||||
assertTrue(SteamGameArt.withOverrides(app, game) === game)
|
||||
val picked = image("mine.png")
|
||||
assertTrue(SteamGameArt.choose(app, game, AddedGameArt.Slot.LOGO, AddedGameArt.Option(AddedGameArt.FILE, picked.path, picked.path)))
|
||||
val shown = SteamGameArt.withOverrides(app, game)
|
||||
assertTrue(shown.logo!!.name.startsWith("chosen-logo"))
|
||||
assertNull(shown.art)
|
||||
SteamGameArt.reset(app, game, AddedGameArt.Slot.LOGO)
|
||||
assertEquals(stock, SteamGameArt.withOverrides(app, game).logo)
|
||||
}
|
||||
|
||||
@Test fun anAddedGameShowsItsFolderLogoUnlessOneWasChosen() {
|
||||
val dir = tmp.newFolder("Celeste")
|
||||
val own = File(dir, "logo.png").apply { writeBytes(ByteArray(4) { 1 }) }
|
||||
val exe = File(dir, "Celeste.exe").apply { writeText("x") }
|
||||
val g = AddedGames.Game(dir, "Celeste", exe, "/g/Celeste.exe", "/g", 0x82000001L, 0x82000001L, emptyList(), source = "gog")
|
||||
assertEquals(own, Library.addedGame(app, g, emptyList()).logo)
|
||||
val picked = image("pick.png")
|
||||
assertTrue(AddedGameArt.choose(app, g, AddedGameArt.Slot.LOGO, AddedGameArt.Option(AddedGameArt.FILE, picked.path, picked.path)))
|
||||
assertTrue(Library.addedGame(app, g, emptyList()).logo!!.name.startsWith("chosen-logo"))
|
||||
val bare = AddedGames.Game(tmp.newFolder("Bare"), "Bare", exe, "/g/Bare.exe", "/g", 0x82000002L, 0x82000002L, emptyList())
|
||||
assertNull(Library.addedGame(app, bare, emptyList()).logo)
|
||||
}
|
||||
|
||||
@Test fun theLibraryCacheKeepsTheLogoAndReadsOlderEntries() {
|
||||
val logo = image("logo.png")
|
||||
val game = Library.SteamGame(620, "Portal 2", null, "Steam library", logo = logo)
|
||||
LibraryCache.save(app, listOf(game, Library.SteamGame(730, "CS2", null, "Steam library")))
|
||||
val back = LibraryCache.load(app)
|
||||
assertEquals(logo, back[0].logo)
|
||||
assertNull(back[1].logo)
|
||||
assertEquals(logo, game.withArt(null, null, null).logo)
|
||||
val file = File(app.filesDir, "library-cache.json")
|
||||
file.writeText(JSONArray().put(JSONObject().put("appId", 1).put("name", "Old").put("library", "x").put("gameId", 1L)).toString())
|
||||
assertNull(LibraryCache.load(app).single().logo)
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,20 @@ class LibraryArchTest {
|
||||
assertEquals(emptyList<String>(), Library.launchableGames(app, added = emptyList(), arch = "arm64").map { it.name })
|
||||
}
|
||||
|
||||
@Test fun aGameTheOtherClientSharesIsListedFromItsFiles() {
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
val apps = File(SessionPrefs.steamRoot(app, "x86_64"), "steamapps").apply { mkdirs() }
|
||||
File(apps, "common/Team Fortress 2").mkdirs()
|
||||
val manifest = "\"AppState\"\n{\n\t\"appid\"\t\t\"440\"\n\t\"name\"\t\t\"Team Fortress 2\"\n\t\"StateFlags\"\t\t\"4\"\n\t\"installdir\"\t\t\"Team Fortress 2\"\n}\n"
|
||||
File(apps, "appmanifest_440.acf").writeText(manifest)
|
||||
val view = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app), "root/.droiddeck-x64/shared/x86-64/steamapps").apply { mkdirs() }
|
||||
File(view, "appmanifest_440.acf").writeText(manifest)
|
||||
val shared = Library.steamGames(app, arch = "arm64").single()
|
||||
assertEquals("Team Fortress 2", shared.name)
|
||||
assertEquals(File(apps, "common/Team Fortress 2"), shared.gameFiles)
|
||||
assertEquals(listOf("Team Fortress 2"), Library.steamGames(app, arch = "x86_64").map { it.name })
|
||||
}
|
||||
|
||||
@Test fun anAddedGameSteamAlreadyListsFromItsFolderIsShownOnce() {
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
val folder = File(app.filesDir, "games/Example").apply { mkdirs() }
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.File
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import org.junit.Assert.assertEquals
|
||||
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 LibraryShortcutsLastPlayedTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
private fun steamRoot(): File = tmp.newFolder("Steam").also { root ->
|
||||
File(root, "config").mkdirs()
|
||||
File(root, "config/loginusers.vdf").writeText(
|
||||
"\"users\"\n{\n\t\"76561198352563669\"\n\t{\n\t\t\"AccountName\"\t\t\"a\"\n\t\t\"MostRecent\"\t\t\"1\"\n\t}\n}\n")
|
||||
}
|
||||
|
||||
private class Vdf {
|
||||
val out = ByteArrayOutputStream()
|
||||
fun key(type: Int, k: String) { out.write(type); out.write(k.toByteArray()); out.write(0) }
|
||||
fun map(k: String, body: Vdf.() -> Unit) { key(0, k); body(); out.write(8) }
|
||||
fun str(k: String, v: String) { key(1, k); out.write(v.toByteArray()); out.write(0) }
|
||||
fun int(k: String, v: Long) { key(2, k); out.write(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(v.toInt()).array()) }
|
||||
}
|
||||
|
||||
@Test fun readsEachShortcutsLastPlayTimeByUnsignedAppId() {
|
||||
val root = steamRoot()
|
||||
val vdf = Vdf().apply {
|
||||
map("shortcuts") {
|
||||
map("0") { int("appid", 3388195926L); str("AppName", "Rayman 2"); int("LastPlayTime", 1792931476L) }
|
||||
map("1") { int("appid", 2228102537L); str("AppName", "Do Not Disturb"); int("LastPlayTime", 0L) }
|
||||
map("2") { int("appid", 1234L); str("appname", "Old"); int("lastplaytime", 1700000000L) }
|
||||
}
|
||||
out.write(8)
|
||||
}
|
||||
File(root, "userdata/392297941/config").apply { mkdirs() }.resolve("shortcuts.vdf").writeBytes(vdf.out.toByteArray())
|
||||
assertEquals(mapOf(3388195926L to 1792931476L, 1234L to 1700000000L), Library.shortcutsLastPlayed(root))
|
||||
}
|
||||
|
||||
@Test fun missingOrBrokenShortcutsGiveNothing() {
|
||||
val root = steamRoot()
|
||||
assertEquals(emptyMap<Long, Long>(), Library.shortcutsLastPlayed(root))
|
||||
File(root, "userdata/392297941/config").apply { mkdirs() }.resolve("shortcuts.vdf").writeBytes(byteArrayOf(0, 's'.code.toByte()))
|
||||
assertEquals(emptyMap<Long, Long>(), Library.shortcutsLastPlayed(root))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import android.os.Looper
|
||||
import com.droiddeck.launcher.FrontEndActivity
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.Robolectric
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.LooperMode
|
||||
import java.io.File
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28])
|
||||
@LooperMode(LooperMode.Mode.PAUSED)
|
||||
class ModeSettingsLoadingTest {
|
||||
@Test fun steamPublishesItsShaderChoiceThroughTheMainQueue() {
|
||||
val activity = Robolectric.buildActivity(FrontEndActivity::class.java).get()
|
||||
SessionPrefs.setShaderPrecache(activity, false)
|
||||
load(activity, SessionService.MODE_STEAM)
|
||||
awaitRead()
|
||||
assertNull(value(activity))
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
assertEquals(false, value(activity))
|
||||
}
|
||||
|
||||
@Test fun desktopDoesNotConsumeSteamsAppliedShaderChoice() {
|
||||
val activity = Robolectric.buildActivity(FrontEndActivity::class.java).get()
|
||||
SessionPrefs.setShaderPrecache(activity, false)
|
||||
val applied = File(LinuxRuntime.rootDir(activity), "root/.bl-shader-precache-applied")
|
||||
applied.parentFile!!.mkdirs()
|
||||
applied.writeText("0")
|
||||
load(activity, SessionService.MODE_DESKTOP)
|
||||
awaitRead()
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
assertTrue(applied.isFile)
|
||||
assertNull(value(activity))
|
||||
}
|
||||
|
||||
@Test fun switchingToDesktopDiscardsAQueuedSteamResult() {
|
||||
val activity = Robolectric.buildActivity(FrontEndActivity::class.java).get()
|
||||
load(activity, SessionService.MODE_STEAM)
|
||||
awaitRead()
|
||||
load(activity, SessionService.MODE_DESKTOP)
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
assertNull(value(activity))
|
||||
}
|
||||
|
||||
private fun load(activity: FrontEndActivity, mode: String) {
|
||||
FrontEndActivity::class.java.getDeclaredMethod("loadShaderPrecache", String::class.java)
|
||||
.apply { isAccessible = true }.invoke(activity, mode)
|
||||
}
|
||||
|
||||
private fun value(activity: FrontEndActivity): Boolean? =
|
||||
FrontEndActivity::class.java.getDeclaredMethod("getShaderPrecache")
|
||||
.apply { isAccessible = true }.invoke(activity) as Boolean?
|
||||
|
||||
private fun awaitRead() {
|
||||
Thread.getAllStackTraces().keys.filter { it.name == "shader-precache" }.forEach {
|
||||
it.join(5_000)
|
||||
assertFalse("Shader settings read did not finish", it.isAlive)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import java.io.File
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
|
||||
class SteamCacheImagesTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
private fun image(path: String, bytes: ByteArray = byteArrayOf(1)): File =
|
||||
File(tmp.root, path).apply { parentFile!!.mkdirs(); writeBytes(bytes) }
|
||||
|
||||
private class CountingDirectory(directory: File) : File(directory.path) {
|
||||
var listings = 0
|
||||
private set
|
||||
|
||||
override fun listFiles(): Array<File>? {
|
||||
listings++
|
||||
return super.listFiles()?.sortedByDescending { it.name }?.toTypedArray()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun allArtworkAndTheHashIconShareOneDirectoryListing() {
|
||||
val cover = image("620/library_capsule.jpg")
|
||||
val hero = image("620/b/library_hero.jpg")
|
||||
val logo = image("620/a/logo.png")
|
||||
val icon = image("620/${"a".repeat(40)}.png")
|
||||
val directory = CountingDirectory(File(tmp.root, "620"))
|
||||
val images = Library.SteamCacheImages(directory)
|
||||
|
||||
assertEquals(cover, images.find(listOf("library_capsule.jpg", "library_600x900.jpg")))
|
||||
assertEquals(hero, images.find(listOf("library_hero.jpg")))
|
||||
assertEquals(logo, images.find(Library.STEAM_LOGOS))
|
||||
assertEquals(icon, images.icon())
|
||||
assertEquals(1, directory.listings)
|
||||
}
|
||||
|
||||
@Test fun preferredFilenamesWinEvenWhenOnlyTheAlternativeIsInTheRoot() {
|
||||
image("620/library_600x900.jpg")
|
||||
val preferred = image("620/hash/library_capsule.jpg")
|
||||
|
||||
assertEquals(preferred, Library.steamCacheImage(
|
||||
tmp.root, 620, listOf("library_capsule.jpg", "library_600x900.jpg"),
|
||||
))
|
||||
}
|
||||
|
||||
@Test fun theRootWinsOverHashDirectoriesForTheSameFilename() {
|
||||
image("620/hash/logo.png")
|
||||
val root = image("620/logo.png")
|
||||
|
||||
assertEquals(root, Library.steamCacheImage(tmp.root, 620, Library.STEAM_LOGOS))
|
||||
}
|
||||
|
||||
@Test fun hashDirectoriesAreSearchedByNameNotListingOrder() {
|
||||
image("620/z/logo.png")
|
||||
val first = image("620/a/logo.png")
|
||||
val directory = CountingDirectory(File(tmp.root, "620"))
|
||||
|
||||
assertEquals(first, Library.SteamCacheImages(directory).find(Library.STEAM_LOGOS))
|
||||
assertEquals(1, directory.listings)
|
||||
}
|
||||
|
||||
@Test fun emptyFilesAndDirectoriesAreNotArtwork() {
|
||||
image("620/logo.png", byteArrayOf())
|
||||
File(tmp.root, "620/a/logo.png").mkdirs()
|
||||
val valid = image("620/b/logo.png")
|
||||
|
||||
assertEquals(valid, Library.steamCacheImage(tmp.root, 620, Library.STEAM_LOGOS))
|
||||
}
|
||||
|
||||
@Test fun namedIconsKeepTheirFilenamePriorityOverHashIcons() {
|
||||
image("620/${"a".repeat(40)}.png")
|
||||
image("620/icon.png")
|
||||
val preferred = image("620/hash/icon.jpg")
|
||||
|
||||
assertEquals(preferred, Library.SteamCacheImages(File(tmp.root, "620")).icon())
|
||||
}
|
||||
|
||||
@Test fun hashIconsKeepTheOriginalRootListingOrderAndAllowEmptyFiles() {
|
||||
image("620/${"0".repeat(40)}.jpg")
|
||||
val first = image("620/${"F".repeat(40)}.png", byteArrayOf())
|
||||
File(tmp.root, "620/${"z".repeat(40)}.png").mkdirs()
|
||||
image("620/${"g".repeat(40)}.png")
|
||||
val directory = CountingDirectory(File(tmp.root, "620"))
|
||||
val images = Library.SteamCacheImages(directory)
|
||||
|
||||
assertEquals(first, images.icon())
|
||||
assertEquals(1, directory.listings)
|
||||
}
|
||||
|
||||
@Test fun hashIconsOutsideTheRootAndInvalidHashesAreIgnored() {
|
||||
image("620/hash/${"a".repeat(40)}.jpg")
|
||||
image("620/${"g".repeat(40)}.png")
|
||||
image("620/${"a".repeat(39)}.png")
|
||||
|
||||
assertNull(Library.SteamCacheImages(File(tmp.root, "620")).icon())
|
||||
}
|
||||
|
||||
@Test fun missingDirectoriesAreListedOnlyOnce() {
|
||||
val directory = CountingDirectory(File(tmp.root, "missing"))
|
||||
val images = Library.SteamCacheImages(directory)
|
||||
|
||||
assertNull(images.find(Library.STEAM_LOGOS))
|
||||
assertNull(images.icon())
|
||||
assertEquals(1, directory.listings)
|
||||
}
|
||||
|
||||
@Test fun aNewLookupSeesHashDirectoriesAddedAfterThePreviousScan() {
|
||||
image("620/unrelated.txt")
|
||||
assertNull(Library.steamCacheImage(tmp.root, 620, Library.STEAM_LOGOS))
|
||||
val added = image("620/new-hash/logo.png")
|
||||
|
||||
assertEquals(added, Library.steamCacheImage(tmp.root, 620, Library.STEAM_LOGOS))
|
||||
}
|
||||
}
|
||||
@@ -238,4 +238,17 @@ class SteamGridTest {
|
||||
assertEquals(names.sorted(), names)
|
||||
assertEquals(5L, AddedGameArt.chosen(dir, AddedGameArt.Slot.COVER)?.length())
|
||||
}
|
||||
|
||||
@Test fun aChoiceSurvivesTheGridFolderBeingWipedAndIsPlacedAgain() {
|
||||
File(LinuxRuntime.rootDir(app), "root/.local/share/Steam/userdata/123/config").mkdirs()
|
||||
val picked = image("mine.png", 12)
|
||||
SteamGameArt.choose(app, game(), AddedGameArt.Slot.COVER, AddedGameArt.Option(AddedGameArt.FILE, picked.path, picked.path))
|
||||
assertEquals(12L, File(grid, "620p.png").length())
|
||||
|
||||
assertTrue(grid.deleteRecursively())
|
||||
grid.mkdirs()
|
||||
assertFalse(SteamGrid.sync(app, listOf(target())))
|
||||
assertEquals(12L, SteamGameArt.chosenFile(app, 620, AddedGameArt.Slot.COVER)?.length())
|
||||
assertEquals(12L, File(grid, "620p.png").length())
|
||||
}
|
||||
}
|
||||
@@ -56,6 +56,17 @@ class WinCompSourcesTest {
|
||||
assertEquals(emptyList<String>(), WinCompSources.epic("Installers/LauncherHelper.exe", "Launcher Helper"))
|
||||
}
|
||||
|
||||
@Test fun xboxGamesAlwaysGetVisualCppAndTheirDeclaredRuntimes() {
|
||||
val folder = tmp.newFolder("xbox")
|
||||
val vc = listOf("vcredist2022" to "VC14", "vcredist2022_arm64" to "VC14")
|
||||
assertEquals(vc, WinCompSources.xbox(folder))
|
||||
File(folder, "MicrosoftGame.Config").writeText("""<Game><DesktopRegistration><DependencyList><KnownDependency Name="VC14"/></DependencyList></DesktopRegistration></Game>""")
|
||||
assertEquals(vc, WinCompSources.xbox(folder))
|
||||
sidecar(folder, Store.XBOX, emptyMap())
|
||||
assertEquals(listOf("vcredist2022" to WinCompSources.Origin.XBOX, "vcredist2022_arm64" to WinCompSources.Origin.XBOX),
|
||||
auto(WinCompSources.forGame(app, game(folder, Store.XBOX.id))).distinct())
|
||||
}
|
||||
|
||||
@Test fun steamworksSharedDepotsMapToComponents() {
|
||||
assertEquals(listOf("vcredist2015_dll" to "VC++ 2015", "d3dx9" to "DirectX (June 2010)"), WinCompSources.steamDepots(listOf("228986", "228990", "999")))
|
||||
}
|
||||
|
||||
@@ -42,6 +42,51 @@ class WinComponentDetectorsTest {
|
||||
assertEquals(emptyList<DependencyDetector.Recommendation>(), SteamRedists.detect(game, 1))
|
||||
}
|
||||
|
||||
@Test fun skyrimGetsTheXactAudioItsInstallScriptRunsOnWindows() {
|
||||
val steamapps = tmp.newFolder("steamapps")
|
||||
val game = File(steamapps, "common/Skyrim Special Edition").apply { mkdirs() }
|
||||
File(steamapps, "appmanifest_489830.acf").writeText("\"AppState\"\n{\n\t\"SharedDepots\"\n\t{\n\t\t\"228990\"\t\t\"228980\"\n\t}\n}\n")
|
||||
val context = androidx.test.core.app.ApplicationProvider.getApplicationContext<android.content.Context>()
|
||||
val found = WinCompSources.steamList(context, game, 489830, "Skyrim Special Edition", auto = true)
|
||||
assertEquals(listOf("d3dx9", "xact_x64"), found.map { it.component })
|
||||
assertTrue(found.all { it.auto && it.origin == WinCompSources.Origin.STEAM })
|
||||
assertEquals(listOf("DirectX XACT audio (64-bit)", "Skyrim Special Edition", "489830"), found.last().args)
|
||||
assertEquals(emptyList<String?>(), WinCompSources.steamList(context, game, 409710, "Other", auto = true).map { it.component })
|
||||
}
|
||||
|
||||
@Test fun theGamesInstallScriptRedistsAreInstalledAsSteamWould() {
|
||||
val steamapps = tmp.newFolder("steamapps")
|
||||
val game = File(steamapps, "common/DiRT 3 Complete Edition").apply { mkdirs() }
|
||||
File(steamapps, "appmanifest_321040.acf").writeText("\"AppState\"\n{\n\t\"SharedDepots\"\n\t{\n\t\t\"228983\"\t\t\"228980\"\n\t}\n}\n")
|
||||
File(game, "installscript.vdf").writeText(
|
||||
"""
|
||||
"InstallScript"
|
||||
{
|
||||
"Registry" { "HKEY_LOCAL_MACHINE\\Software\\Codemasters" { "string" { "Path" "%INSTALLDIR%" } } }
|
||||
"Run Process"
|
||||
{
|
||||
"OpenAL"
|
||||
{
|
||||
"HasRunKey" "HKEY_LOCAL_MACHINE\\Software\\Valve\\Steam\\Apps\\321040"
|
||||
"process 1" "%INSTALLDIR%\\_CommonRedist\\OpenAL\\2.0.7.0\\oalinst.exe"
|
||||
"command 1" "/s"
|
||||
}
|
||||
"VC2010"
|
||||
{
|
||||
"process 1" "%INSTALLDIR%\\_CommonRedist\\vcredist\\2010\\vcredist_x86.exe"
|
||||
}
|
||||
}
|
||||
}
|
||||
""".trimIndent(),
|
||||
)
|
||||
assertEquals(listOf("oalinst", "vcredist2010"), SteamRedists.installScript(game).map { it.first })
|
||||
val context = androidx.test.core.app.ApplicationProvider.getApplicationContext<android.content.Context>()
|
||||
val found = WinCompSources.steamList(context, game, 321040, "DiRT 3 Complete Edition", auto = true)
|
||||
assertEquals(listOf("vcredist2010_dll", "oalinst"), found.map { it.component })
|
||||
assertTrue(found.all { it.auto && it.origin == WinCompSources.Origin.STEAM })
|
||||
assertEquals(emptyList<Pair<String, String>>(), SteamRedists.installScript(File(steamapps, "missing")))
|
||||
}
|
||||
|
||||
@Test fun thePrefixCountsOnlyWhatDroidDeckDidNotPutThere() {
|
||||
val compat = tmp.newFolder("compatdata", "409710")
|
||||
val pfx = File(compat, "pfx")
|
||||
|
||||
@@ -269,6 +269,17 @@ class GlassesUsbTest {
|
||||
assertTrue(Glasses.isGlassesDisplayName("Rokid Max"))
|
||||
}
|
||||
|
||||
@Test fun rokidMax2RequestsPermissionForItsOwnProductId() {
|
||||
val max2 = device(0x2002, 0x04d2, "Rokid Max2")
|
||||
manager.devices[max2.deviceName] = max2
|
||||
refresh(ask = true)
|
||||
assertEquals("Rokid Max2", state.value.model)
|
||||
assertTrue(state.value.controllable)
|
||||
assertEquals(listOf(max2), manager.requests)
|
||||
assertTrue(Glasses.isGlassesDisplayName("Rokid Max 2"))
|
||||
assertEquals(null, Glasses.deviceModel(device(0x2002, 0x04d2, "Generic HID")))
|
||||
}
|
||||
|
||||
private fun device(pid: Int, vid: Int = VitureProtocol.VENDOR_ID, name: String = "VITURE device"): UsbDevice = ReflectionHelpers.callConstructor(
|
||||
UsbDevice::class.java,
|
||||
from(String::class.java, "/dev/bus/usb/$pid"),
|
||||
|
||||
@@ -13,6 +13,10 @@ class RokidProtocolTest {
|
||||
@Test fun identityRequiresRokidProductString() {
|
||||
assertEquals("Rokid Max", RokidModel.model(0x04d2, 0x162f, "Rokid Max")?.name)
|
||||
assertEquals("Rokid Air", RokidModel.model(0x04d2, 0x162f, "Rokid Air")?.name)
|
||||
assertEquals("Rokid Max2", RokidModel.model(0x04d2, 0x2002, "Rokid Max2")?.name)
|
||||
assertNull(RokidModel.model(0x04d2, 0x2002, "USB Keyboard"))
|
||||
assertNull(RokidModel.model(0x04d2, 0x2002, null))
|
||||
assertNull(RokidModel.model(0x1234, 0x2002, "Rokid Max2"))
|
||||
assertNull(RokidModel.model(0x04d2, 0x162f, "USB Keyboard"))
|
||||
assertNull(RokidModel.model(0x04d2, 0x162f, null))
|
||||
assertNull(RokidModel.model(0x04d2, 0x1234, "Rokid Max"))
|
||||
@@ -40,6 +44,21 @@ class RokidProtocolTest {
|
||||
assertEquals(listOf(60), air.rates2d)
|
||||
}
|
||||
|
||||
@Test fun max2UsesMaxModesAndParsesItsCapturedCombinedReport() {
|
||||
val max2 = RokidModel.model(0x04d2, 0x2002, "Rokid Max2")!!
|
||||
assertEquals(RokidModel.MODE_2D_120, max2.mode(120, false, null))
|
||||
assertEquals(RokidModel.MODE_SBS_1080_60, max2.mode(60, true, GlassesResolution(1920, 1080)))
|
||||
assertEquals(RokidModel.MODE_SBS_1200_90, max2.mode(90, true, null))
|
||||
val packet = hex("119ceac6a47b000000542389bf2f430f41de9f6fc000967a38666144bbd0d4413b66661bc2cdcc2c4066e6e142000000ea70a2a47b0000000000006464000000")
|
||||
val sample = RokidProtocol.Parser().parse(packet)!!
|
||||
assertEquals(0x7ba4c6ea9cL, sample.timeNs)
|
||||
assertEquals(8.954f, sample.accel.y, 0.001f)
|
||||
assertEquals(100, sample.brightness)
|
||||
val pose = ImuFusion().update(sample.timeNs, sample.accel, sample.gyro)
|
||||
assertNotNull(pose)
|
||||
assertTrue(pose!!.all { it.isFinite() })
|
||||
}
|
||||
|
||||
@Test fun brightnessStepsRoundTripTheDevicePercent() {
|
||||
assertEquals(8, RokidModel.brightnessStep(80))
|
||||
assertEquals(10, RokidModel.brightnessStep(100))
|
||||
|
||||
@@ -3,13 +3,23 @@ package com.droiddeck.launcher.gpu
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
|
||||
class TpUbwcHintTest {
|
||||
@Test fun a740OnABlobV6xxTurnsTheHintOff() {
|
||||
assertEquals("enable_tp_ubwc_flag_hint=0", TpUbwcHint.features(740, "512.676.53"))
|
||||
assertEquals("enable_tp_ubwc_flag_hint=0", TpUbwcHint.features(740, "512.676.75"))
|
||||
assertEquals("enable_tp_ubwc_flag_hint=0", TpUbwcHint.features(740, "512.676"))
|
||||
assertEquals("enable_tp_ubwc_flag_hint=0", TpUbwcHint.features(740, "512.699.10"))
|
||||
}
|
||||
|
||||
@Test fun a740OnThePocoBlobTurnsTheHintOn() {
|
||||
assertEquals("enable_tp_ubwc_flag_hint=1", TpUbwcHint.features(740, "512.676.76"))
|
||||
assertEquals("enable_tp_ubwc_flag_hint=1", TpUbwcHint.features(740, "512.676.80"))
|
||||
}
|
||||
|
||||
@Test fun a740OnANewerBlobTurnsTheHintOn() {
|
||||
assertEquals("enable_tp_ubwc_flag_hint=1", TpUbwcHint.features(740, "512.700.0"))
|
||||
assertEquals("enable_tp_ubwc_flag_hint=1", TpUbwcHint.features(740, "512.762.10"))
|
||||
}
|
||||
|
||||
@@ -18,6 +28,24 @@ class TpUbwcHintTest {
|
||||
assertEquals("enable_tp_ubwc_flag_hint=1", TpUbwcHint.features(740, null, samsung = true))
|
||||
}
|
||||
|
||||
@Test fun onOverridesThePocoRuleEvenWhenTheVersionIsUnreadable() {
|
||||
for (version in listOf("512.676.1", "512.676.53", "garbage", null)) {
|
||||
assertEquals("enable_tp_ubwc_flag_hint=1", TpUbwcHint.features(740, version, mode = SessionPrefs.TP_UBWC_ON))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun offOverridesSamsungAndNewerBlobs() {
|
||||
assertEquals("enable_tp_ubwc_flag_hint=0", TpUbwcHint.features(740, "512.762.10", mode = SessionPrefs.TP_UBWC_OFF))
|
||||
assertEquals("enable_tp_ubwc_flag_hint=0", TpUbwcHint.features(740, null, samsung = true, mode = SessionPrefs.TP_UBWC_OFF))
|
||||
}
|
||||
|
||||
@Test fun overridesDoNotApplyToOtherGpus() {
|
||||
for (mode in listOf(SessionPrefs.TP_UBWC_ON, SessionPrefs.TP_UBWC_OFF)) {
|
||||
assertNull(TpUbwcHint.features(750, "512.762.10", mode = mode))
|
||||
assertNull(TpUbwcHint.features(0, null, mode = mode))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun otherGpusKeepTheirDriverDefault() {
|
||||
assertNull(TpUbwcHint.features(750, "512.762.10"))
|
||||
assertNull(TpUbwcHint.features(830, "512.676.53"))
|
||||
|
||||
@@ -22,7 +22,7 @@ class DirectTouchHoldTest {
|
||||
}
|
||||
override fun onWheel(steps: Int) {}
|
||||
override fun onLongPress() {}
|
||||
}) { events += "cancel touch" }
|
||||
}) { events += "cancel touch" }.also { it.configure(TouchGestureConfig(longPressEnabled = true, longPressDelay = 500)) }
|
||||
|
||||
@Test fun holdReleasesRawTouchBeforeClickAndConsumesTheLift() {
|
||||
assertFalse(touch(MotionEvent.ACTION_DOWN))
|
||||
@@ -35,6 +35,25 @@ class DirectTouchHoldTest {
|
||||
hold.cancel()
|
||||
}
|
||||
|
||||
@Test fun stillHoldKeepsTheTouchWhenLongPressIsOff() {
|
||||
hold.configure(TouchGestureConfig())
|
||||
assertFalse(touch(MotionEvent.ACTION_DOWN))
|
||||
advance(2000)
|
||||
assertFalse(touch(MotionEvent.ACTION_MOVE))
|
||||
assertFalse(touch(MotionEvent.ACTION_UP))
|
||||
assertTrue(events.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun longPressFollowsTheConfiguredDelay() {
|
||||
hold.configure(TouchGestureConfig(longPressEnabled = true, longPressDelay = 800))
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
advance(700)
|
||||
assertTrue(events.isEmpty())
|
||||
advance(100)
|
||||
assertEquals(listOf("cancel touch", "true at 40.0,30.0"), events)
|
||||
hold.cancel()
|
||||
}
|
||||
|
||||
@Test fun tapDragSecondFingerAndCancellationDoNotRightClick() {
|
||||
for (action in listOf(MotionEvent.ACTION_UP, MotionEvent.ACTION_MOVE,
|
||||
MotionEvent.ACTION_POINTER_DOWN, MotionEvent.ACTION_CANCEL)) {
|
||||
|
||||
@@ -19,6 +19,7 @@ import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.Implementation
|
||||
import org.robolectric.annotation.Implements
|
||||
import org.robolectric.shadows.InputDeviceBuilder
|
||||
import org.robolectric.shadows.ShadowBuild
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34], manifest = Config.NONE, instrumentedPackages = ["com.droiddeck.launcher.input.FakeInputWriter"],
|
||||
@@ -82,6 +83,34 @@ class JoyConPadTest {
|
||||
assertEquals(0, RecordingWriter.grips)
|
||||
}
|
||||
|
||||
@Test fun novaControllerUsesCForTheLeftPaddleAndZForTheRight() {
|
||||
ShadowBuild.setModel("Retroid Pocket Nova")
|
||||
for (product in listOf(0x3001, 0x3002)) {
|
||||
val pad = controller(0x2022, product)
|
||||
assertPaddles(pad, KeyEvent.KEYCODE_BUTTON_C, KeyEvent.KEYCODE_BUTTON_Z)
|
||||
bridge.onDeviceRemoved(pad.id)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun theSameControllerIdsKeepTheDefaultPaddlesOnOtherHandhelds() {
|
||||
for (product in listOf(0x3001, 0x3002)) {
|
||||
val pad = controller(0x2022, product)
|
||||
for (model in listOf("Retroid Pocket 6", "Retroid Pocket 5", "AYN Thor")) {
|
||||
ShadowBuild.setModel(model)
|
||||
assertPaddles(pad, KeyEvent.KEYCODE_BUTTON_Z, KeyEvent.KEYCODE_BUTTON_C)
|
||||
}
|
||||
bridge.onDeviceRemoved(pad.id)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun otherControllerIdsKeepTheDefaultPaddlesOnANova() {
|
||||
ShadowBuild.setModel("Retroid Pocket Nova")
|
||||
for (pad in listOf(controller(0x045e, 0x0b13), controller(0x2022, 0x3003), controller(0x2020, 0x3001))) {
|
||||
assertPaddles(pad, KeyEvent.KEYCODE_BUTTON_Z, KeyEvent.KEYCODE_BUTTON_C)
|
||||
bridge.onDeviceRemoved(pad.id)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun whenOneJoyConLeavesTheOtherKeepsThePlayer() {
|
||||
pair()
|
||||
assertTrue(press(right, KeyEvent.KEYCODE_BUTTON_A, BTN_SOUTH))
|
||||
@@ -140,6 +169,17 @@ class JoyConPadTest {
|
||||
|
||||
private fun pad(slot: Int): PadState = RecordingWriter.pads[slot] ?: PadState()
|
||||
|
||||
private fun assertPaddles(device: InputDevice, leftCode: Int, rightCode: Int) {
|
||||
assertTrue(bridge.onKeyEvent(key(device, leftCode, 0)))
|
||||
assertEquals(DeckControls.L4, RecordingWriter.grips)
|
||||
assertTrue(bridge.onKeyEvent(key(device, rightCode, 0)))
|
||||
assertEquals(DeckControls.L4 or DeckControls.R4, RecordingWriter.grips)
|
||||
assertTrue(bridge.onKeyEvent(key(device, leftCode, 0, KeyEvent.ACTION_UP)))
|
||||
assertEquals(DeckControls.R4, RecordingWriter.grips)
|
||||
assertTrue(bridge.onKeyEvent(key(device, rightCode, 0, KeyEvent.ACTION_UP)))
|
||||
assertEquals(0, RecordingWriter.grips)
|
||||
}
|
||||
|
||||
private fun press(device: InputDevice, code: Int, scanCode: Int): Boolean =
|
||||
bridge.onKeyEvent(JoyCon.normalize(key(device, code, scanCode)))
|
||||
|
||||
@@ -162,10 +202,12 @@ class JoyConPadTest {
|
||||
|
||||
private var nextId = 60
|
||||
|
||||
private fun joyCon(product: Int, vararg axes: Int): InputDevice {
|
||||
private fun joyCon(product: Int, vararg axes: Int): InputDevice = controller(NINTENDO, product, *axes)
|
||||
|
||||
private fun controller(vendor: Int, product: Int, vararg axes: Int): InputDevice {
|
||||
val id = nextId++
|
||||
val builder = InputDeviceBuilder.newBuilder().setId(id).setName("Joy-Con $id").setDescriptor("joycon-$id")
|
||||
.setExternal(true).setVendorId(NINTENDO).setProductId(product)
|
||||
.setExternal(true).setVendorId(vendor).setProductId(product)
|
||||
.setSources(InputDevice.SOURCE_GAMEPAD or InputDevice.SOURCE_JOYSTICK or InputDevice.SOURCE_KEYBOARD)
|
||||
.setKeyboardType(InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC)
|
||||
.setKeyCharacterMap(KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD))
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.view.InputDevice
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class ScreenKeysTest {
|
||||
private val context = RuntimeEnvironment.getApplication()
|
||||
|
||||
@Before fun clearKeys() {
|
||||
ControllerPrefs.setScreenKeys(context, emptyList())
|
||||
}
|
||||
|
||||
@Test fun missesAreForwardedAsTheirOwnTouchStreamWhileAKeyIsHeld() {
|
||||
val sent = mutableListOf<Pair<Int, Boolean>>()
|
||||
val keys = ScreenKeys(context) { code, down -> sent += code to down }
|
||||
keys.layout(0, 0, 1000, 600)
|
||||
keys.add(listOf(KeyEvent.KEYCODE_W))
|
||||
val forwarded = mutableListOf<Pair<Int, Int>>()
|
||||
keys.onTouchMiss = { forwarded += it.actionMasked to it.getPointerId(0) }
|
||||
|
||||
send(keys, MotionEvent.ACTION_DOWN, listOf(0), listOf(300f), listOf(372f))
|
||||
send(keys, MotionEvent.ACTION_POINTER_DOWN or (1 shl MotionEvent.ACTION_POINTER_INDEX_SHIFT), listOf(0, 1), listOf(300f, 900f), listOf(372f, 550f))
|
||||
send(keys, MotionEvent.ACTION_MOVE, listOf(0, 1), listOf(310f, 880f), listOf(372f, 530f))
|
||||
send(keys, MotionEvent.ACTION_POINTER_UP or (1 shl MotionEvent.ACTION_POINTER_INDEX_SHIFT), listOf(0, 1), listOf(310f, 880f), listOf(372f, 530f))
|
||||
send(keys, MotionEvent.ACTION_UP, listOf(0), listOf(310f), listOf(372f))
|
||||
|
||||
assertEquals(
|
||||
listOf(
|
||||
MotionEvent.ACTION_DOWN to 1,
|
||||
MotionEvent.ACTION_MOVE to 1,
|
||||
MotionEvent.ACTION_UP to 1,
|
||||
),
|
||||
forwarded,
|
||||
)
|
||||
assertEquals(listOf(KeyEvent.KEYCODE_W to true, KeyEvent.KEYCODE_W to false), sent)
|
||||
}
|
||||
|
||||
@Test fun gestureRecognizerKeepsOneSplitTargetOwnerUntilItsStreamEnds() {
|
||||
val gate = GestureTouchStreamGate()
|
||||
fun accepts(source: GestureTouchStreamGate.Source, action: Int): Boolean {
|
||||
val event = MotionEvent.obtain(0L, 1L, action, 1f, 1f, 0)
|
||||
return try { gate.accepts(source, event) } finally { event.recycle() }
|
||||
}
|
||||
|
||||
assertTrue(accepts(GestureTouchStreamGate.Source.SURFACE, MotionEvent.ACTION_DOWN))
|
||||
assertFalse(accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, MotionEvent.ACTION_DOWN))
|
||||
assertTrue(accepts(GestureTouchStreamGate.Source.SURFACE, MotionEvent.ACTION_MOVE))
|
||||
assertTrue(accepts(GestureTouchStreamGate.Source.SURFACE, MotionEvent.ACTION_UP))
|
||||
assertTrue(accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, MotionEvent.ACTION_DOWN))
|
||||
assertFalse(accepts(GestureTouchStreamGate.Source.SURFACE, MotionEvent.ACTION_DOWN))
|
||||
assertTrue(accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, MotionEvent.ACTION_CANCEL))
|
||||
assertTrue(accepts(GestureTouchStreamGate.Source.SURFACE, MotionEvent.ACTION_DOWN))
|
||||
assertFalse(accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, MotionEvent.ACTION_DOWN))
|
||||
gate.reset()
|
||||
assertTrue(accepts(GestureTouchStreamGate.Source.SURFACE, MotionEvent.ACTION_DOWN))
|
||||
}
|
||||
|
||||
@Test fun loadingLayoutReleasesLatchedKeysBeforeReplacingEntries() {
|
||||
val sent = mutableListOf<Pair<Int, Boolean>>()
|
||||
val keys = ScreenKeys(context) { code, down -> sent += code to down }
|
||||
keys.layout(0, 0, 1000, 600)
|
||||
keys.add(listOf(KeyEvent.KEYCODE_SHIFT_LEFT))
|
||||
keys.setToggle(listOf(KeyEvent.KEYCODE_SHIFT_LEFT), true)
|
||||
send(keys, MotionEvent.ACTION_DOWN, listOf(0), listOf(300f), listOf(372f))
|
||||
send(keys, MotionEvent.ACTION_UP, listOf(0), listOf(300f), listOf(372f))
|
||||
|
||||
keys.load("")
|
||||
|
||||
assertEquals(listOf(KeyEvent.KEYCODE_SHIFT_LEFT to true, KeyEvent.KEYCODE_SHIFT_LEFT to false), sent)
|
||||
}
|
||||
|
||||
@Test fun hidingTheViewReleasesLatchedKeys() {
|
||||
val sent = mutableListOf<Pair<Int, Boolean>>()
|
||||
val keys = ScreenKeys(context) { code, down -> sent += code to down }
|
||||
keys.layout(0, 0, 1000, 600)
|
||||
keys.add(listOf(KeyEvent.KEYCODE_SHIFT_LEFT))
|
||||
keys.setToggle(listOf(KeyEvent.KEYCODE_SHIFT_LEFT), true)
|
||||
send(keys, MotionEvent.ACTION_DOWN, listOf(0), listOf(300f), listOf(372f))
|
||||
send(keys, MotionEvent.ACTION_UP, listOf(0), listOf(300f), listOf(372f))
|
||||
|
||||
keys.visibility = View.GONE
|
||||
|
||||
assertEquals(listOf(KeyEvent.KEYCODE_SHIFT_LEFT to true, KeyEvent.KEYCODE_SHIFT_LEFT to false), sent)
|
||||
}
|
||||
|
||||
private fun send(view: View, action: Int, ids: List<Int>, xs: List<Float>, ys: List<Float>) {
|
||||
val properties = Array(ids.size) { index ->
|
||||
MotionEvent.PointerProperties().apply {
|
||||
id = ids[index]
|
||||
toolType = MotionEvent.TOOL_TYPE_FINGER
|
||||
}
|
||||
}
|
||||
val coordinates = Array(ids.size) { index ->
|
||||
MotionEvent.PointerCoords().apply {
|
||||
x = xs[index]
|
||||
y = ys[index]
|
||||
pressure = 1f
|
||||
size = 1f
|
||||
}
|
||||
}
|
||||
val event = MotionEvent.obtain(
|
||||
0L, 1L, action, ids.size, properties, coordinates, 0, 0,
|
||||
1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0,
|
||||
)
|
||||
try {
|
||||
view.onTouchEvent(event)
|
||||
} finally {
|
||||
event.recycle()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -172,7 +172,7 @@ class SessionGestureRoutingTest {
|
||||
val event = MotionEvent.obtain(now, now, MotionEvent.ACTION_DOWN, 400f, 300f, 0)
|
||||
try { assertTrue(activity.onTouchEvent(event)) } finally { event.recycle() }
|
||||
val gestureMode = mode == SessionPrefs.TOUCH_GESTURES
|
||||
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(if (gestureMode) 350 else 500))
|
||||
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(if (gestureMode) 350 else 320))
|
||||
assertEquals(if (gestureMode) listOf(18 to true) else emptyList(), keys)
|
||||
assertEquals(if (gestureMode) emptyList() else listOf(PointerGestures.BTN_RIGHT to true), directButtons)
|
||||
ReflectionHelpers.callInstanceMethod<Unit>(activity, "onPause")
|
||||
@@ -220,7 +220,7 @@ class SessionGestureRoutingTest {
|
||||
override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) { directButtons += button to pressed }
|
||||
override fun onWheel(steps: Int) {}
|
||||
override fun onLongPress() {}
|
||||
}) {}
|
||||
}) {}.also { it.configure(config) }
|
||||
setField("directTouchHold", directHold)
|
||||
launcherScroll = ScrollTouchGestures(8f, 50f, object : ScrollTouchGestures.Listener {
|
||||
override fun onMove(x: Float, y: Float) { scrollPositions += x to y }
|
||||
|
||||
@@ -0,0 +1,378 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.session.ComponentsManager
|
||||
import com.droiddeck.launcher.session.GameEnvironmentStore
|
||||
import com.github.luben.zstd.ZstdOutputStream
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
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
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import java.util.zip.CRC32
|
||||
|
||||
private val REGISTRY = """
|
||||
WINE REGISTRY Version 2
|
||||
;; All keys relative to \\Machine
|
||||
|
||||
[Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Battle.net] 1760380000
|
||||
#time=1dc3c6e0a5e1f2a
|
||||
"DisplayName"="Battle.net"
|
||||
"InstallLocation"="C:\\Program Files (x86)\\Battle.net"
|
||||
"UninstallString"="\"C:\\Program Files (x86)\\Battle.net\\Battle.net Uninstaller.exe\" --lang=enUS"
|
||||
|
||||
[Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Diablo IV] 1760380001
|
||||
"DisplayIcon"="C:\\Program Files (x86)\\Diablo IV\\Diablo IV Launcher.exe"
|
||||
"DisplayName"="Diablo\xae IV"
|
||||
"InstallLocation"="C:\\Program Files (x86)\\Diablo IV"
|
||||
"Publisher"="Blizzard Entertainment"
|
||||
"UninstallString"="\"C:\\ProgramData\\Battle.net\\Agent\\Blizzard Uninstaller.exe\" --lang=enUS --uid=fenris --displayname=\"Diablo IV\""
|
||||
|
||||
[Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Overwatch] 1760380002
|
||||
"InstallLocation"="C:\\Program Files (x86)\\Overwatch"
|
||||
"UninstallString"="\"C:\\ProgramData\\Battle.net\\Agent\\Blizzard Uninstaller.exe\" --lang=enUS --uid=prometheus --displayname=\"Overwatch\""
|
||||
|
||||
[Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Steam] 1760380003
|
||||
"InstallLocation"="C:\\Program Files (x86)\\Steam"
|
||||
"UninstallString"="C:\\Program Files (x86)\\Steam\\uninstall.exe --uid=steam"
|
||||
|
||||
[Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Diablo II Resurrected] 1760380004
|
||||
"UninstallString"=str(2):"\"C:\\ProgramData\\Battle.net\\Agent\\Blizzard Uninstaller.exe\" --lang=enUS --uid=osi --displayname=\"Diablo II: Resurrected\""
|
||||
"InstallLocation"="C:/Games/Diablo II Resurrected"
|
||||
|
||||
[Software\\Wine\\Fonts] 1760380005
|
||||
"InstallLocation"="C:\\x"
|
||||
"UninstallString"="Battle.net --uid=wow"
|
||||
""".trimStart()
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class BattleNetTest {
|
||||
private lateinit var context: Context
|
||||
|
||||
@Before fun setUp() {
|
||||
context = RuntimeEnvironment.getApplication()
|
||||
File(context.filesDir, "components").deleteRecursively()
|
||||
LinuxRuntime.rootDir(context).deleteRecursively()
|
||||
}
|
||||
|
||||
@Test fun theIdIsTheShortcutIdTheScriptNames() {
|
||||
val crc = CRC32().apply { update("\"droiddeck-battlenet\"Battle.net".toByteArray()) }.value
|
||||
assertEquals(crc or 0x80000000L, BattleNet.APP_ID)
|
||||
}
|
||||
|
||||
@Test fun theNewestD2rfixIsTheHighestFexThenTheHighestFix() {
|
||||
val items = listOf(
|
||||
item("FEXCore-2610-linux.wcp"),
|
||||
item("FEXCore-2609-d2rfix25-linux.wcp"),
|
||||
item("FEXCore-2610-d2rfix9-linux.wcp"),
|
||||
item("FEXCore-2610-d2rfix28-linux.wcp"),
|
||||
item("FEXCore-2509.1-d2rfix40-linux.wcp"),
|
||||
)
|
||||
assertEquals("FEXCore-2610-d2rfix28-linux.wcp", BattleNet.newestD2rFix(items)?.file)
|
||||
assertEquals("FEXCore-2610.1-d2rfix1-linux.wcp", BattleNet.newestD2rFix(items + item("FEXCore-2610.1-d2rfix1-linux.wcp"))?.file)
|
||||
assertEquals("FexCore-2611-D2RFIX2-linux.wcp", BattleNet.newestD2rFix(items + item("FexCore-2611-D2RFIX2-linux.wcp"))?.file)
|
||||
}
|
||||
|
||||
@Test fun onlyFexD2rfixPackagesCount() {
|
||||
assertNull(BattleNet.newestD2rFix(listOf(item("FEXCore-2610-linux.wcp"), item("FEXCore-2610-d2rfix28-linux.wcp", comp = "dxvk"))))
|
||||
assertNull(BattleNet.d2rfix("FEXCore-2610-d2rfix28-linux.wcp.part"))
|
||||
assertNull(BattleNet.d2rfix("FEXCore-2610-d2rfix-linux.wcp"))
|
||||
assertEquals(listOf(2610L) to 28L, BattleNet.d2rfix("FEXCore-2610-d2rfix28-linux.wcp"))
|
||||
}
|
||||
|
||||
@Test fun theNewestStoredBuildIsSetForThePrefix() {
|
||||
catalog("FEXCore-2609-d2rfix25-linux.wcp", "FEXCore-2610-d2rfix28-linux.wcp", "FEXCore-2610-linux.wcp")
|
||||
store("FEXCore-2610-d2rfix28-linux.wcp")
|
||||
|
||||
assertEquals("FEXCore-2610-d2rfix28-linux.wcp", BattleNet.ensureFex(context, ::noRefresh))
|
||||
|
||||
assertEquals(mapOf("fex" to "FEXCore-2610-d2rfix28-linux.wcp"), ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString()))
|
||||
assertEquals("FEXCore-2610-d2rfix28-linux.wcp", BattleNet.ensureFex(context, ::noRefresh))
|
||||
}
|
||||
|
||||
@Test fun aNewerBuildReplacesTheOldOne() {
|
||||
catalog("FEXCore-2609-d2rfix25-linux.wcp")
|
||||
store("FEXCore-2609-d2rfix25-linux.wcp")
|
||||
BattleNet.ensureFex(context, ::noRefresh)
|
||||
catalog("FEXCore-2609-d2rfix25-linux.wcp", "FEXCore-2610-d2rfix28-linux.wcp")
|
||||
store("FEXCore-2610-d2rfix28-linux.wcp")
|
||||
|
||||
BattleNet.ensureFex(context, ::noRefresh)
|
||||
|
||||
assertEquals("FEXCore-2610-d2rfix28-linux.wcp", ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())["fex"])
|
||||
}
|
||||
|
||||
@Test fun aStaleListingIsFetchedAgain() {
|
||||
catalog("FEXCore-2609-d2rfix25-linux.wcp", fetchedAt = 1)
|
||||
store("FEXCore-2610-d2rfix28-linux.wcp")
|
||||
|
||||
BattleNet.ensureFex(context) { listOf(item("FEXCore-2609-d2rfix25-linux.wcp"), item("FEXCore-2610-d2rfix28-linux.wcp")) }
|
||||
|
||||
assertEquals("FEXCore-2610-d2rfix28-linux.wcp", ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())["fex"])
|
||||
}
|
||||
|
||||
@Test fun aFailedFetchFallsBackOnTheCachedListing() {
|
||||
catalog("FEXCore-2609-d2rfix25-linux.wcp", fetchedAt = 1)
|
||||
store("FEXCore-2609-d2rfix25-linux.wcp")
|
||||
|
||||
assertEquals("FEXCore-2609-d2rfix25-linux.wcp", BattleNet.ensureFex(context) { error("offline") })
|
||||
}
|
||||
|
||||
@Test fun aListingWithoutD2rfixIsAnError() {
|
||||
catalog("FEXCore-2610-linux.wcp")
|
||||
var refreshed = 0
|
||||
assertThrows(IllegalStateException::class.java) { BattleNet.ensureFex(context) { refreshed++; emptyList() } }
|
||||
assertEquals(1, refreshed)
|
||||
assertEquals(emptyMap<String, String>(), ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString()))
|
||||
}
|
||||
|
||||
@Test fun installedIsTheLauncherInThePrefix() {
|
||||
assertFalse(BattleNet.installed(context))
|
||||
launcher().apply { parentFile!!.mkdirs(); writeText("MZ") }
|
||||
assertTrue(BattleNet.installed(context))
|
||||
}
|
||||
|
||||
@Test fun theEnvironmentEditorNamesBattleNetsProfileOnceItIsInstalled() {
|
||||
assertNull(BattleNet.profile(context))
|
||||
launcher().apply { parentFile!!.mkdirs(); writeText("MZ") }
|
||||
assertEquals(BattleNet.APP_ID.toString() to "Battle.net", BattleNet.profile(context))
|
||||
}
|
||||
|
||||
@Test fun removeTakesThePrefixItsMenuEntryAndCacheButNothingItLinksTo() {
|
||||
catalog("FEXCore-2610-d2rfix28-linux.wcp")
|
||||
store("FEXCore-2610-d2rfix28-linux.wcp")
|
||||
BattleNet.ensureFex(context, ::noRefresh)
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
fun put(relative: String) = File(root, relative).apply { parentFile!!.mkdirs(); writeText("x") }
|
||||
launcher().apply { parentFile!!.mkdirs(); writeText("MZ") }
|
||||
val outside = File(context.cacheDir, "bnet-outside").apply { mkdirs() }
|
||||
val kept = File(outside, "kept").apply { writeText("x") }
|
||||
val drives = File(BattleNet.prefix(context), "pfx/dosdevices").apply { mkdirs() }
|
||||
Files.createSymbolicLink(File(drives, "z:").toPath(), outside.toPath())
|
||||
val menu = put("usr/local/share/applications/droiddeck-battlenet.desktop")
|
||||
val otherMenu = put("usr/local/share/applications/other.desktop")
|
||||
val log = put("root/.cache/droiddeck/battlenet/battlenet.log")
|
||||
val otherPrefix = put("root/.local/share/Steam/steamapps/compatdata/123/pfx/system.reg")
|
||||
|
||||
BattleNet.remove(context)
|
||||
|
||||
assertFalse(BattleNet.prefix(context).exists())
|
||||
assertFalse(BattleNet.installed(context))
|
||||
assertTrue(kept.isFile)
|
||||
assertFalse(menu.exists())
|
||||
assertTrue(otherMenu.isFile)
|
||||
assertFalse(log.parentFile!!.exists())
|
||||
assertTrue(otherPrefix.isFile)
|
||||
assertNull(BattleNet.fexInUse(context))
|
||||
outside.deleteRecursively()
|
||||
}
|
||||
|
||||
@Test fun anIdNamesItsTitleWithOrWithoutItsLocale() {
|
||||
assertEquals("Pro", BattleNet.title("prometheus")?.code)
|
||||
assertEquals("D3", BattleNet.title("diablo3_enus")?.code)
|
||||
assertEquals("Fen", BattleNet.title("Fenris")?.code)
|
||||
assertEquals("WTCG", BattleNet.title("hs_beta")?.code)
|
||||
assertEquals("Diablo II: Resurrected", BattleNet.title("osi_dede")?.name)
|
||||
assertEquals("WoWC", BattleNet.title("wow_classic")?.code)
|
||||
assertEquals("WoWC", BattleNet.title("wow_classic_era_enus")?.code)
|
||||
assertNull(BattleNet.title("agent"))
|
||||
assertNull(BattleNet.title("osi_beta"))
|
||||
}
|
||||
|
||||
@Test fun theUninstallEntriesOfBattleNetsGamesAreRead() {
|
||||
val entries = BattleNet.uninstallEntries(REGISTRY.lineSequence())
|
||||
assertEquals(listOf(
|
||||
"fenris" to "C:\\Program Files (x86)\\Diablo IV",
|
||||
"prometheus" to "C:\\Program Files (x86)\\Overwatch",
|
||||
"osi" to "C:/Games/Diablo II Resurrected",
|
||||
), entries)
|
||||
}
|
||||
|
||||
@Test fun productDbsInstallsAreRead() {
|
||||
val db = message(
|
||||
field(1, message(field(1, "agent"), field(2, "agent"), field(3, message(field(1, "C:/ProgramData/Battle.net/Agent"))))),
|
||||
varintField(7, 300),
|
||||
field(1, message(field(1, "hs_beta"), field(2, "wtcg"), varintField(9, 1), field(3, message(field(1, "C:/Program Files (x86)/Hearthstone"), field(2, "US"))))),
|
||||
field(1, message(field(1, "s2"))),
|
||||
field(1, message(field(1, "s1"), field(3, message(field(1, "Z:/mnt/droiddeck-sd/Games/Battle.net/StarCraft"))), field(4, message(field(1, message(varintField(1, 0), varintField(2, 0))))))),
|
||||
field(1, message(field(1, "wow_classic_anniversary"), field(3, message(field(1, "Z:/root/Games/World of Warcraft"))), field(4, message(field(1, message(varintField(1, 1), varintField(2, 1))))))),
|
||||
)
|
||||
assertEquals(listOf("agent" to "C:/ProgramData/Battle.net/Agent", "hs_beta" to "C:/Program Files (x86)/Hearthstone", "wow_classic_anniversary" to "Z:/root/Games/World of Warcraft"),
|
||||
BattleNet.productDbEntries(db))
|
||||
assertEquals(emptyList<Pair<String, String>>(), BattleNet.productDbEntries(db.copyOf(db.size - 3)))
|
||||
assertEquals(emptyList<Pair<String, String>>(), BattleNet.productDbEntries(byteArrayOf(0x0a, 0x7f, 0x01)))
|
||||
}
|
||||
|
||||
@Test fun theGamesAreTheTitlesInstalledInTheirFolders() {
|
||||
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
|
||||
File(pfx, "system.reg").writeText(REGISTRY)
|
||||
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
|
||||
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(message(
|
||||
field(1, message(field(1, "hs_beta"), field(3, message(field(1, "C:/Program Files (x86)/Hearthstone"))))),
|
||||
field(1, message(field(1, "fenris"), field(3, message(field(1, "C:/Program Files (x86)/Diablo IV"))))),
|
||||
field(1, message(field(1, "wow_classic"), field(3, message(field(1, "C:/Program Files (x86)/World of Warcraft"))))),
|
||||
))
|
||||
for (folder in listOf("Program Files (x86)/Diablo IV", "Games/Diablo II Resurrected", "Program Files (x86)/Hearthstone", "Program Files (x86)/World of Warcraft")) {
|
||||
File(pfx, "drive_c/$folder").mkdirs()
|
||||
}
|
||||
val games = BattleNet.games(context)
|
||||
assertEquals(listOf("Fen", "OSI", "WTCG", "WoWC"), games.map { it.code })
|
||||
assertEquals(listOf("Diablo IV", "Diablo II: Resurrected", "Hearthstone", "World of Warcraft Classic"), games.map { it.name })
|
||||
assertEquals(File(pfx, "drive_c/Games/Diablo II Resurrected"), games[1].folder)
|
||||
assertNull(BattleNet.hostFolder(context, "D:\\Games\\X"))
|
||||
assertNull(BattleNet.hostFolder(context, "C:\\..\\..\\etc"))
|
||||
assertNull(BattleNet.hostFolder(context, "Z:\\root\\..\\..\\etc"))
|
||||
assertEquals(File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/Hearthstone"),
|
||||
BattleNet.hostFolder(context, "Z:/root/Games/Stores/Battle.net/Hearthstone/"))
|
||||
}
|
||||
|
||||
@Test fun aGamesShortcutHasBattleNetLaunchItInItsPrefix() {
|
||||
val folder = File(BattleNet.prefix(context), "pfx/drive_c/Program Files (x86)/Diablo IV").apply { mkdirs() }
|
||||
File(folder, "Diablo IV Launcher.exe").writeBytes(byteArrayOf(0x4d, 0x5a))
|
||||
val shortcut = BattleNet.shortcut(context, BattleNet.Game("fenris", "Diablo IV", "Fen", folder))!!
|
||||
val exe = "/root/.local/share/Steam/steamapps/compatdata/2596113170/pfx/drive_c/Program Files (x86)/Battle.net/Battle.net.exe"
|
||||
assertEquals(exe, shortcut.guestExe)
|
||||
assertEquals(exe.substringBeforeLast('/'), shortcut.guestDir)
|
||||
assertEquals("STEAM_COMPAT_DATA_PATH=/root/.local/share/Steam/steamapps/compatdata/2596113170 %command% --exec=\"launch Fen\"", shortcut.launchOptions)
|
||||
val crc = CRC32().apply { update("\"$exe\"Diablo IV".toByteArray()) }.value
|
||||
assertEquals(crc or 0x80000000L, shortcut.appId)
|
||||
assertEquals((shortcut.appId shl 32) or 0x02000000L, shortcut.gameId)
|
||||
assertEquals(com.droiddeck.launcher.stores.Store.BATTLENET.id, shortcut.source)
|
||||
assertEquals("Diablo IV Launcher.exe", shortcut.exe.name)
|
||||
val listing = com.droiddeck.launcher.frontend.AddedGames.writeListing(context, listOf(shortcut)).readText()
|
||||
val entry = JSONArray(listing).getJSONObject(0)
|
||||
assertEquals(com.droiddeck.launcher.stores.Store.BATTLENET.id, entry.getString("store"))
|
||||
assertEquals(shortcut.launchOptions, entry.getString("launch"))
|
||||
assertEquals(exe, entry.getString("exe"))
|
||||
}
|
||||
|
||||
@Test fun titlesSharingALaunchCodeShareTheirArt() {
|
||||
val cover = File(context.filesDir, "battlenet-art/fenris/p.jpg").apply { parentFile!!.mkdirs(); writeBytes(byteArrayOf(1)) }
|
||||
assertEquals(cover, BattleNet.art(context, BattleNet.title("fen")!!).cover)
|
||||
val wide = File(context.filesDir, "battlenet-art/wow_classic/blizzard.jpg").apply { parentFile!!.mkdirs(); writeBytes(byteArrayOf(1)) }
|
||||
assertEquals(wide, BattleNet.art(context, BattleNet.title("wow_classic_anniversary")!!).header)
|
||||
}
|
||||
|
||||
@Test fun theStoreOffersEachTitleOnceAndHidesWhatIsInstalled() {
|
||||
val codes = BattleNet.STORE.map { it.code }
|
||||
assertEquals(codes.distinct(), codes)
|
||||
assertTrue("Fen" in codes && "OSI" in codes && "WTCG" in codes)
|
||||
assertFalse(BattleNet.STORE.any { it.uid == "d3cn" || it.uid == "fen" })
|
||||
assertEquals("fenris", BattleNet.STORE.first { it.code == "Fen" }.uid)
|
||||
assertTrue(BattleNet.STORE.all { it.uid.matches(Regex("[a-z0-9_]{1,32}")) })
|
||||
val installed = listOf("fenris", "diablo3_enus", null)
|
||||
val offered = BattleNet.STORE.filter { BattleNet.notInstalled(it, installed) }.map { it.code }
|
||||
assertFalse("Fen" in offered || "D3" in offered)
|
||||
assertTrue("OSI" in offered)
|
||||
}
|
||||
|
||||
@Test fun aBattleNetGameStartsWithoutSteamThroughItsShortcutUntilThatIsSwitchedOff() {
|
||||
File(context.filesDir, "game-environment.json").delete()
|
||||
val folder = File(BattleNet.prefix(context), "pfx/drive_c/Program Files (x86)/Diablo IV").apply { mkdirs() }
|
||||
File(folder, "Diablo IV Launcher.exe").writeBytes(byteArrayOf(0x4d, 0x5a))
|
||||
val shortcut = BattleNet.shortcut(context, BattleNet.Game("fenris", "Diablo IV", "Fen", folder))!!
|
||||
val game = com.droiddeck.launcher.frontend.Library.SteamGame(
|
||||
shortcut.appId.toInt(), shortcut.name, null, com.droiddeck.launcher.frontend.Library.ADDED, shortcut.gameId,
|
||||
source = com.droiddeck.launcher.stores.Store.BATTLENET.id, storeId = shortcut.storeId)
|
||||
val noSteam = com.droiddeck.launcher.session.NoSteamLaunch
|
||||
assertEquals(BattleNet.APP_ID.toString(), noSteam.scope(game))
|
||||
assertFalse(noSteam.enabled(context, game))
|
||||
assertTrue(BattleNet.ensureNoSteam(context))
|
||||
assertTrue(noSteam.enabled(context, game))
|
||||
val command = noSteam.command(game, shortcut)!!
|
||||
assertEquals(noSteam.BATTLENET, command.program)
|
||||
assertEquals(listOf("launch", "Fen"), command.args)
|
||||
GameEnvironmentStore.setGameNoSteam(context, BattleNet.APP_ID.toString(), false)
|
||||
assertFalse(BattleNet.ensureNoSteam(context))
|
||||
assertFalse(noSteam.enabled(context, game))
|
||||
}
|
||||
|
||||
@Test fun theGamesAreToldOfAFifthOfThePhonesMemory() {
|
||||
assertEquals(2048, BattleNet.videoMemory(11113))
|
||||
assertEquals(1536, BattleNet.videoMemory(7468))
|
||||
assertEquals(2560, BattleNet.videoMemory(15200))
|
||||
assertEquals(3584, BattleNet.videoMemory(60000))
|
||||
assertTrue(BattleNet.videoMemory(Long.MAX_VALUE / 2) < 4096)
|
||||
assertEquals(
|
||||
"dxgi.maxDeviceMemory = 2048; dxgi.maxSharedMemory = 2048; d3d9.maxAvailableMemory = 2048",
|
||||
BattleNet.videoMemoryOptions(2048),
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun theCapIsTheBattleNetProfilesOwnDxvkConfigUnlessItHasOne() {
|
||||
File(context.filesDir, "game-environment.json").delete()
|
||||
val manager = context.getSystemService(android.app.ActivityManager::class.java)
|
||||
org.robolectric.Shadows.shadowOf(manager).setMemoryInfo(android.app.ActivityManager.MemoryInfo().apply { totalMem = 11113L shl 20 })
|
||||
val scope = BattleNet.APP_ID.toString()
|
||||
assertTrue(BattleNet.ensureVideoMemory(context))
|
||||
assertEquals(BattleNet.videoMemoryOptions(2048), GameEnvironmentStore.read(context).games[scope]?.get("DXVK_CONFIG"))
|
||||
val published = File(LinuxRuntime.rootDir(context), "root/.config/droiddeck/game-environment.json").readText()
|
||||
assertTrue("dxgi.maxDeviceMemory = 2048" in JSONObject(published).getJSONObject("games").getJSONObject(scope).getString("DXVK_CONFIG"))
|
||||
assertFalse(BattleNet.ensureVideoMemory(context))
|
||||
for (own in listOf("dxvk.maxFrameRate = 30", null)) {
|
||||
GameEnvironmentStore.save(context, GameEnvironmentStore.read(context).let { it.withEntries(scope, it.entries(scope) + ("DXVK_CONFIG" to own)) })
|
||||
assertFalse(BattleNet.ensureVideoMemory(context))
|
||||
assertEquals(own, GameEnvironmentStore.read(context).games[scope]?.get("DXVK_CONFIG"))
|
||||
}
|
||||
GameEnvironmentStore.save(context, GameEnvironmentStore.read(context).let { it.withEntries(scope, it.entries(scope) - "DXVK_CONFIG") })
|
||||
assertTrue(BattleNet.ensureVideoMemory(context))
|
||||
}
|
||||
|
||||
private fun launcher() = File(BattleNet.prefix(context), "pfx/drive_c/Program Files (x86)/Battle.net/Battle.net Launcher.exe")
|
||||
|
||||
private fun varint(value: Long): ByteArray {
|
||||
val out = java.io.ByteArrayOutputStream()
|
||||
var v = value
|
||||
while (v >= 0x80) { out.write(((v and 0x7f) or 0x80).toInt()); v = v ushr 7 }
|
||||
out.write(v.toInt())
|
||||
return out.toByteArray()
|
||||
}
|
||||
|
||||
private fun field(number: Int, bytes: ByteArray) = varint((number shl 3 or 2).toLong()) + varint(bytes.size.toLong()) + bytes
|
||||
private fun field(number: Int, text: String) = field(number, text.toByteArray())
|
||||
private fun varintField(number: Int, value: Long) = varint((number shl 3).toLong()) + varint(value)
|
||||
private fun message(vararg fields: ByteArray) = fields.fold(ByteArray(0)) { all, f -> all + f }
|
||||
|
||||
private fun noRefresh(context: Context): List<ComponentsManager.CatalogItem> = error("the cached listing was fresh")
|
||||
|
||||
private fun item(file: String, comp: String = "fex") = ComponentsManager.CatalogItem(
|
||||
file, comp, "FexCore-Linux", "https://github.com/The412Banner/Nightlies/releases/download/FexCore-Linux/$file", 4, "sha256:" + "ab".repeat(32),
|
||||
)
|
||||
|
||||
private fun catalog(vararg files: String, fetchedAt: Long = System.currentTimeMillis() / 1000) {
|
||||
val cache = File(context.filesDir, "components/catalog.json")
|
||||
cache.parentFile!!.mkdirs()
|
||||
val items = JSONArray()
|
||||
for (file in files) items.put(JSONObject().put("file", file).put("comp", "fex").put("release", "FexCore-Linux")
|
||||
.put("url", item(file).url).put("size", 4).put("digest", item(file).digest))
|
||||
cache.writeText(JSONObject().put("items", items).put("fetchedAt", fetchedAt).toString())
|
||||
}
|
||||
|
||||
private fun store(file: String) {
|
||||
val wcp = File(context.filesDir, "components/packages/$file")
|
||||
wcp.parentFile!!.mkdirs()
|
||||
TarArchiveOutputStream(ZstdOutputStream(wcp.outputStream())).use { tar ->
|
||||
fun put(name: String, bytes: ByteArray) {
|
||||
tar.putArchiveEntry(TarArchiveEntry(name).apply { size = bytes.size.toLong() })
|
||||
tar.write(bytes)
|
||||
tar.closeArchiveEntry()
|
||||
}
|
||||
put("profile.json", JSONObject().put("type", "FEXCore-Linux").put("versionName", file.removeSuffix(".wcp")).toString().toByteArray())
|
||||
put("files/lib/wine/aarch64-windows/libarm64ecfex.dll", "arm64ec $file".toByteArray())
|
||||
put("files/lib/wine/aarch64-windows/libwow64fex.dll", "wow64 $file".toByteArray())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -119,6 +119,21 @@ class BwrapSpawnerPlanTest {
|
||||
assertEquals("org.example.Game", plan.env["FLATPAK_ID"])
|
||||
}
|
||||
|
||||
@Test fun sandboxedAppsSeeTheSessionsNetworkLink() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val rootfs = LinuxRuntime.rootDir(context)
|
||||
val lib = File(rootfs, "usr/local/lib/libblsession.so").apply { parentFile?.mkdirs(); writeText("") }
|
||||
val preload = File(rootfs, "etc/ld.so.preload").apply { parentFile?.mkdirs(); writeText("/usr/local/lib/libblsession.so\n") }
|
||||
val link = File(rootfs, "etc/droiddeck-net").apply { writeText("if wlan0 2 1500\n") }
|
||||
try {
|
||||
val plan = BwrapSpawner.plan(context, request(op("t" to "dir", "dest" to "/tmp")), dir)
|
||||
assertEquals("/run/droiddeck-preload/libblsession.so", plan.env["LD_PRELOAD"])
|
||||
assertEquals(link.path, plan.binds.single { it.guest == "/etc/droiddeck-net" }.host)
|
||||
} finally {
|
||||
listOf(lib, preload, link).forEach { it.delete() }
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun zypakLaunchesTheBrowserWithoutItsSandbox() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val app = File(runtime, "app").apply { File(this, "bin").mkdirs() }
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import android.content.ContextWrapper
|
||||
import com.droiddeck.launcher.BuildConfig
|
||||
import com.droiddeck.launcher.core.AddonPack
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.File
|
||||
import java.net.ServerSocket
|
||||
import java.security.MessageDigest
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.function.Predicate
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
|
||||
import org.apache.commons.compress.compressors.zstandard.ZstdCompressorOutputStream
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], application = Application::class)
|
||||
class RuntimeInstallRollbackTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
@After fun resetFaults() { RuntimeFileTree.refuseForTest = null }
|
||||
|
||||
private fun put(root: File, rel: String, data: String) = File(root, rel).apply {
|
||||
checkNotNull(parentFile).mkdirs()
|
||||
writeText(data)
|
||||
}
|
||||
|
||||
private data class Attempt(val root: File, val staging: File, val old: File, val result: Boolean)
|
||||
|
||||
private fun attempt(failRollback: Boolean): Attempt {
|
||||
val files = tmp.newFolder("files")
|
||||
val cache = tmp.newFolder("cache")
|
||||
val context = object : ContextWrapper(RuntimeEnvironment.getApplication()) {
|
||||
override fun getFilesDir(): File = files
|
||||
override fun getCacheDir(): File = cache
|
||||
override fun getApplicationContext(): Context = this
|
||||
}
|
||||
for ((pack, pin, required) in listOf(
|
||||
Triple(AddonPack.PROOT, BuildConfig.PACK_PROOT_SHA256, listOf("libproot.so", "libproot-loader.so")),
|
||||
Triple(AddonPack.DIRECTAUDIO, BuildConfig.PACK_DIRECTAUDIO_SHA256,
|
||||
listOf("linux-wine11/version.txt", "linux-wine11-systhread/version.txt")),
|
||||
)) {
|
||||
val version = pin.ifEmpty { "0".repeat(64) }
|
||||
val directory = File(files, "addons/${pack.name}/$version")
|
||||
required.forEach { put(directory, it, "test pack") }
|
||||
put(directory, AddonPack.COMPLETE, version)
|
||||
}
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
val staging = File(files, LinuxRuntime.DIR + ".new")
|
||||
val old = File(files, LinuxRuntime.DIR + ".old")
|
||||
put(root, "root/save.dat", "original user data")
|
||||
put(root, "opt/appimages/user/game/app.AppImage", "original app")
|
||||
put(root, "usr/bin/usable", "previous runtime")
|
||||
|
||||
val payload = ByteArrayOutputStream().also { bytes ->
|
||||
ZstdCompressorOutputStream(bytes).use { zstd ->
|
||||
TarArchiveOutputStream(zstd).use { tar ->
|
||||
for ((name, value) in listOf("root/.bashrc" to "shipped home", "usr/bin/new" to "new runtime",
|
||||
"opt/appimages/user/block" to "shipped app")) {
|
||||
val data = value.toByteArray()
|
||||
tar.putArchiveEntry(TarArchiveEntry(name).apply { size = data.size.toLong() })
|
||||
tar.write(data)
|
||||
tar.closeArchiveEntry()
|
||||
}
|
||||
}
|
||||
}
|
||||
}.toByteArray()
|
||||
val digest = MessageDigest.getInstance("SHA-256").digest(payload).joinToString("") { "%02x".format(it) }
|
||||
val faultSeen = AtomicBoolean()
|
||||
RuntimeFileTree.refuseForTest = Predicate { path ->
|
||||
if (path == File(staging, "opt/appimages/user/block").toPath() && faultSeen.compareAndSet(false, true)) {
|
||||
if (failRollback) put(old, "root/rollback-block", "concurrent data")
|
||||
true
|
||||
} else failRollback && path == File(old, "root/rollback-block").toPath()
|
||||
}
|
||||
val server = ServerSocket(0)
|
||||
val thread = Thread {
|
||||
runCatching {
|
||||
server.accept().use { socket ->
|
||||
socket.soTimeout = 5000
|
||||
val input = socket.getInputStream().bufferedReader(Charsets.ISO_8859_1)
|
||||
while (true) {
|
||||
val line = input.readLine() ?: break
|
||||
if (line.isEmpty()) break
|
||||
}
|
||||
val out = socket.getOutputStream()
|
||||
out.write(("HTTP/1.1 200 OK\r\nContent-Length: ${payload.size}\r\nConnection: close\r\n\r\n").toByteArray())
|
||||
out.write(payload)
|
||||
out.flush()
|
||||
}
|
||||
}
|
||||
}.apply { isDaemon = true; start() }
|
||||
try {
|
||||
val release = LinuxRuntimeInstaller.Release("synthetic", "http://127.0.0.1:${server.localPort}/runtime.tar.zst", digest, payload.size.toLong())
|
||||
val result = LinuxRuntimeInstaller.install(context, release, null)
|
||||
assertTrue("the intended carry fault was not reached", faultSeen.get())
|
||||
return Attempt(root, staging, old, result)
|
||||
} finally {
|
||||
server.close()
|
||||
thread.join(1000)
|
||||
RuntimeFileTree.refuseForTest = null
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun aFailedCarryAndFailedRollbackKeepTheOnlyStagedCopy() {
|
||||
val attempt = attempt(failRollback = true)
|
||||
assertFalse(attempt.result)
|
||||
assertTrue("the only staged copy was deleted", File(attempt.staging, "root/save.dat").isFile)
|
||||
assertEquals("original user data", File(attempt.staging, "root/save.dat").readText())
|
||||
assertEquals("original app", File(attempt.root, "opt/appimages/user/game/app.AppImage").readText())
|
||||
assertEquals("previous runtime", File(attempt.root, "usr/bin/usable").readText())
|
||||
repeat(2) {
|
||||
assertThrows(java.io.IOException::class.java) {
|
||||
LinuxRuntimeInstaller.recoverInterruptedSwap(attempt.root, attempt.staging, attempt.old)
|
||||
}
|
||||
assertEquals("original user data", File(attempt.staging, "root/save.dat").readText())
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun aCompleteRollbackStillRestoresAndCleansTheFailedCandidate() {
|
||||
val attempt = attempt(failRollback = false)
|
||||
assertFalse(attempt.result)
|
||||
assertEquals("original user data", File(attempt.root, "root/save.dat").readText())
|
||||
assertEquals("original app", File(attempt.root, "opt/appimages/user/game/app.AppImage").readText())
|
||||
assertFalse(attempt.staging.exists())
|
||||
}
|
||||
}
|
||||
@@ -69,6 +69,7 @@ class RuntimeRemovalTest {
|
||||
val old = File(dir, "linuxfs.old").apply { File(this, "root").mkdirs() }
|
||||
val staging = File(dir, "linuxfs.new").apply { File(this, "root").mkdirs() }
|
||||
File(staging, "root/save").writeText("user data")
|
||||
File(staging, LinuxRuntimeInstaller.CARRY_MARKER).writeText("1")
|
||||
for (tree in listOf(old, staging))
|
||||
Files.setPosixFilePermissions(tree.toPath(), PosixFilePermissions.fromString("r-xr-xr-x"))
|
||||
LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old)
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.nio.file.Files
|
||||
import org.junit.After
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
|
||||
class RuntimeUserDataCarryTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
@After fun resetFaults() { RuntimeFileTree.refuseForTest = null }
|
||||
|
||||
private fun put(root: File, rel: String, text: String = rel) = File(root, rel).apply { parentFile.mkdirs(); writeText(text) }
|
||||
|
||||
private fun userTree(): File = tmp.newFolder("old").also { old ->
|
||||
put(old, "root/save.dat", "mine")
|
||||
put(old, "opt/appimages/user/app1/app.AppImage")
|
||||
put(old, "opt/droiddeck-apps/game/run.sh")
|
||||
put(old, "usr/local/share/applications/droiddeck-app-game.desktop")
|
||||
put(old, "usr/local/share/applications/droiddeck-appimage-app1.desktop")
|
||||
put(old, "usr/local/share/applications/other.desktop")
|
||||
put(old, "opt/appimages/dolphin.AppImage")
|
||||
put(old, "usr/share/applications/droiddeck-dolphin.desktop")
|
||||
put(old, ".droiddeck-pkg-dolphin", "1.0")
|
||||
put(old, "usr/bin/tool", "old system file")
|
||||
}
|
||||
|
||||
@Test fun anUpdateKeepsImportedAppsCatalogAppImagesAndHome() {
|
||||
val old = userTree()
|
||||
val staging = tmp.newFolder("new").also { put(it, "root/.bashrc", "shipped"); put(it, "usr/bin/tool", "new system file") }
|
||||
|
||||
val moved = RuntimeFileTree.carryUserData(old, staging, false)
|
||||
|
||||
assertEquals("mine", File(staging, "root/save.dat").readText())
|
||||
assertFalse("the shipped home is replaced, not merged", File(staging, "root/.bashrc").exists())
|
||||
for (rel in listOf("opt/appimages/user/app1/app.AppImage", "opt/droiddeck-apps/game/run.sh",
|
||||
"usr/local/share/applications/droiddeck-app-game.desktop", "usr/local/share/applications/droiddeck-appimage-app1.desktop",
|
||||
"opt/appimages/dolphin.AppImage", "usr/share/applications/droiddeck-dolphin.desktop", ".droiddeck-pkg-dolphin")) {
|
||||
assertTrue(rel, File(staging, rel).exists())
|
||||
assertTrue(rel, rel in moved || moved.any { rel.startsWith("$it/") })
|
||||
}
|
||||
assertEquals("system files come from the new runtime", "new system file", File(staging, "usr/bin/tool").readText())
|
||||
assertFalse("only DroidDeck's own menu entries are user data", File(staging, "usr/local/share/applications/other.desktop").exists())
|
||||
}
|
||||
|
||||
@Test fun aFailureHalfwayPutsEverythingBack() {
|
||||
val old = userTree()
|
||||
val staging = tmp.newFolder("new")
|
||||
put(staging, "usr/local", "a file where a folder is needed")
|
||||
|
||||
try {
|
||||
RuntimeFileTree.carryUserData(old, staging, false)
|
||||
fail("expected the carry to fail")
|
||||
} catch (expected: IOException) {
|
||||
}
|
||||
|
||||
assertEquals("mine", File(old, "root/save.dat").readText())
|
||||
assertTrue(File(old, "opt/appimages/user/app1/app.AppImage").exists())
|
||||
assertTrue(File(old, "opt/droiddeck-apps/game/run.sh").exists())
|
||||
assertFalse(File(staging, "root").exists())
|
||||
}
|
||||
|
||||
@Test fun recoveryOnlyFillsWhatIsMissing() {
|
||||
val target = tmp.newFolder("target").also { put(it, "opt/droiddeck-apps/game/run.sh", "kept") }
|
||||
val staging = tmp.newFolder("staging").also {
|
||||
put(it, "opt/droiddeck-apps/game/run.sh", "stale")
|
||||
put(it, "opt/appimages/user/app1/app.AppImage")
|
||||
}
|
||||
|
||||
val moved = RuntimeFileTree.carryUserData(staging, target, true)
|
||||
|
||||
assertEquals(listOf("opt/appimages/user"), moved)
|
||||
assertEquals("kept", File(target, "opt/droiddeck-apps/game/run.sh").readText())
|
||||
assertTrue(File(target, "opt/appimages/user/app1/app.AppImage").exists())
|
||||
}
|
||||
@Test fun recoveryFindsCompanionsWhoseAppImageWasAlreadyPutBack() {
|
||||
val root = tmp.newFolder("runtime")
|
||||
val staging = tmp.newFolder("runtime.new")
|
||||
val old = File(tmp.root, "runtime.old")
|
||||
put(root, "opt/appimages/dolphin.AppImage", "user app")
|
||||
put(staging, LinuxRuntimeInstaller.CARRY_MARKER, "1")
|
||||
put(staging, "usr/share/applications/droiddeck-dolphin.desktop", "menu")
|
||||
put(staging, ".droiddeck-pkg-dolphin", "version")
|
||||
put(staging, ".droiddeck-pkg-desktop-kde", "system package marker")
|
||||
|
||||
LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old)
|
||||
assertEquals("menu", File(root, "usr/share/applications/droiddeck-dolphin.desktop").readText())
|
||||
assertEquals("version", File(root, ".droiddeck-pkg-dolphin").readText())
|
||||
assertFalse(File(root, ".droiddeck-pkg-desktop-kde").exists())
|
||||
assertEquals("user app", File(root, "opt/appimages/dolphin.AppImage").readText())
|
||||
}
|
||||
|
||||
@Test fun unmarkedExtractedStagingDoesNotBlockRecovery() {
|
||||
val root = tmp.newFolder("runtime")
|
||||
val staging = tmp.newFolder("runtime.new")
|
||||
val old = File(tmp.root, "runtime.old")
|
||||
put(root, "root/save.dat", "current user data")
|
||||
put(staging, "root/.bashrc", "shipped home from interrupted extract")
|
||||
|
||||
LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old)
|
||||
assertEquals("current user data", File(root, "root/save.dat").readText())
|
||||
assertEquals("shipped home from interrupted extract", File(staging, "root/.bashrc").readText())
|
||||
}
|
||||
|
||||
@Test fun anUnreadableAppImageDirectoryAbortsBeforeMovingHome() {
|
||||
assumeTrue(Files.getFileStore(tmp.root.toPath()).supportsFileAttributeView("posix"))
|
||||
val old = userTree()
|
||||
val images = File(old, "opt/appimages")
|
||||
val staging = tmp.newFolder("staging")
|
||||
assertTrue(images.setReadable(false, false))
|
||||
assertTrue(images.setExecutable(false, false))
|
||||
try {
|
||||
assertThrows(IOException::class.java) { RuntimeFileTree.carryUserData(old, staging, false) }
|
||||
assertEquals("mine", File(old, "root/save.dat").readText())
|
||||
assertFalse(File(staging, "root/save.dat").exists())
|
||||
} finally {
|
||||
images.setReadable(true, true)
|
||||
images.setExecutable(true, true)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun recoveryRestoresTheRuntimeBeforeTryingAFallibleHomeMove() {
|
||||
val root = File(tmp.root, "runtime")
|
||||
val old = tmp.newFolder("runtime.old")
|
||||
val staging = tmp.newFolder("runtime.new")
|
||||
put(old, "usr/bin/usable", "previous runtime")
|
||||
File(old, "root").mkdirs()
|
||||
put(staging, LinuxRuntimeInstaller.CARRY_MARKER, "1")
|
||||
put(staging, "root/save.dat", "staged user data")
|
||||
RuntimeFileTree.refuseForTest = java.util.function.Predicate { it.fileName.toString() == "root" }
|
||||
|
||||
assertThrows(IOException::class.java) { LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old) }
|
||||
assertTrue("the previous runtime was not restored", root.isDirectory)
|
||||
assertEquals("previous runtime", File(root, "usr/bin/usable").readText())
|
||||
assertEquals("staged user data", File(staging, "root/save.dat").readText())
|
||||
}
|
||||
|
||||
@Test fun conflictingRecoveryDataIsRetainedOnEveryRetry() {
|
||||
val root = tmp.newFolder("runtime")
|
||||
val staging = tmp.newFolder("runtime.new")
|
||||
val old = File(tmp.root, "runtime.old")
|
||||
put(root, "root/current.dat", "current user data")
|
||||
put(staging, LinuxRuntimeInstaller.CARRY_MARKER, "1")
|
||||
put(staging, "root/older.dat", "unrecovered user data")
|
||||
|
||||
repeat(2) {
|
||||
assertThrows(IOException::class.java) { LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old) }
|
||||
assertEquals("current user data", File(root, "root/current.dat").readText())
|
||||
assertEquals("unrecovered user data", File(staging, "root/older.dat").readText())
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun stagedDataWithoutASurvivingRuntimeIsKeptForRecovery() {
|
||||
val root = File(tmp.root, "runtime")
|
||||
val old = File(tmp.root, "runtime.old")
|
||||
val staging = tmp.newFolder("runtime.new")
|
||||
put(staging, LinuxRuntimeInstaller.CARRY_MARKER, "1")
|
||||
put(staging, "root/save.dat", "only surviving user data")
|
||||
assertThrows(IOException::class.java) { LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old) }
|
||||
assertEquals("only surviving user data", File(staging, "root/save.dat").readText())
|
||||
}
|
||||
|
||||
@Test fun conflictingIntendedHomesAreRetainedWithoutProofOfTheirContents() {
|
||||
val root = File(tmp.root, "runtime")
|
||||
val old = tmp.newFolder("runtime.old")
|
||||
val staging = tmp.newFolder("runtime.new")
|
||||
put(old, "root/save.dat", "user data")
|
||||
put(staging, LinuxRuntimeInstaller.CARRY_MARKER, "root")
|
||||
put(staging, "root/.bashrc", "shipped default")
|
||||
|
||||
assertThrows(IOException::class.java) { LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old) }
|
||||
|
||||
assertEquals("user data", File(root, "root/save.dat").readText())
|
||||
assertEquals("shipped default", File(staging, "root/.bashrc").readText())
|
||||
assertTrue(File(staging, LinuxRuntimeInstaller.CARRY_MARKER).exists())
|
||||
}
|
||||
|
||||
@Test fun anUnreadableCarryMarkerStopsRecovery() {
|
||||
val root = tmp.newFolder("runtime")
|
||||
val staging = tmp.newFolder("runtime.new")
|
||||
val old = File(tmp.root, "runtime.old")
|
||||
val marker = File(staging, LinuxRuntimeInstaller.CARRY_MARKER).apply { mkdirs() }
|
||||
|
||||
assertThrows(IOException::class.java) { LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old) }
|
||||
assertTrue(marker.isDirectory)
|
||||
}
|
||||
|
||||
@Test fun recoveryMovesOnlyAnIntendedPathThatWasAlreadyCarried() {
|
||||
val root = File(tmp.root, "runtime")
|
||||
val old = tmp.newFolder("runtime.old")
|
||||
val staging = tmp.newFolder("runtime.new")
|
||||
put(staging, LinuxRuntimeInstaller.CARRY_MARKER, "root")
|
||||
put(staging, "root/save.dat", "moved user data")
|
||||
|
||||
LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old)
|
||||
|
||||
assertEquals("moved user data", File(root, "root/save.dat").readText())
|
||||
assertFalse(File(staging, LinuxRuntimeInstaller.CARRY_MARKER).exists())
|
||||
}
|
||||
|
||||
@Test fun aSymlinkedParentCannotRedirectAUserDataMoveOutsideTheRuntime() {
|
||||
val old = tmp.newFolder("old")
|
||||
val staging = tmp.newFolder("staging")
|
||||
val outside = tmp.newFolder("outside")
|
||||
put(outside, "droiddeck-apps/game/run.sh", "outside data")
|
||||
Files.createSymbolicLink(File(old, "opt").toPath(), outside.toPath())
|
||||
|
||||
assertThrows(IOException::class.java) { RuntimeFileTree.carryUserData(old, staging, false) }
|
||||
|
||||
assertEquals("outside data", File(outside, "droiddeck-apps/game/run.sh").readText())
|
||||
assertFalse(File(staging, "opt/droiddeck-apps").exists())
|
||||
}
|
||||
|
||||
@Test fun anInaccessibleLiveHomeIsNeverTreatedAsMissing() {
|
||||
assumeTrue(Files.getFileStore(tmp.root.toPath()).supportsFileAttributeView("posix"))
|
||||
val root = tmp.newFolder("runtime")
|
||||
val staging = tmp.newFolder("runtime.new")
|
||||
val old = File(tmp.root, "runtime.old")
|
||||
put(root, "root/keep.dat", "current user data")
|
||||
put(staging, LinuxRuntimeInstaller.CARRY_MARKER, "1")
|
||||
put(staging, "root/staged.dat", "staged user data")
|
||||
assertTrue(root.setExecutable(false, false))
|
||||
val failure = try {
|
||||
runCatching { LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old) }.exceptionOrNull()
|
||||
} finally {
|
||||
root.setExecutable(true, true)
|
||||
}
|
||||
|
||||
assertTrue("the existing live home was deleted", File(root, "root/keep.dat").isFile)
|
||||
assertEquals("current user data", File(root, "root/keep.dat").readText())
|
||||
assertEquals("staged user data", File(staging, "root/staged.dat").readText())
|
||||
assertTrue("inaccessible data must abort recovery", failure is IOException)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Test
|
||||
|
||||
class SeededMacTest {
|
||||
@Test
|
||||
fun theAndroidIdSeedsAStableLocalMac() {
|
||||
val mac = LinuxNetworkLinkComponent.seededMac { "0123456789abcdef" }
|
||||
assertEquals(mac, LinuxNetworkLinkComponent.seededMac { "0123456789abcdef" })
|
||||
assertNotEquals(mac, LinuxNetworkLinkComponent.seededMac { null })
|
||||
assertEquals(0x02, mac.substringBefore(':').toInt(16) and 0x03)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRomThatThrowsOnTheAndroidIdReadFallsBackToTheDefaultSeed() {
|
||||
val mac = LinuxNetworkLinkComponent.seededMac { throw IllegalArgumentException("Illegal char: - at offset 8") }
|
||||
assertEquals(LinuxNetworkLinkComponent.seededMac { null }, mac)
|
||||
}
|
||||
}
|
||||
@@ -49,11 +49,25 @@ class BatteryComponentTest {
|
||||
assertEquals("-2000000", File(supplies, "BAT1/current_now").readText().trim())
|
||||
}
|
||||
|
||||
private fun start(supplies: File, vpower: File, currentUa: Long) {
|
||||
@Test fun chargingAtFullLevelIsReportedFullSoSteamStopsSaying99() {
|
||||
val supplies = tmp.newFolder("power_supply")
|
||||
val vpower = tmp.newFolder("vpower")
|
||||
start(supplies, vpower, 2_000_000L, BatteryManager.BATTERY_STATUS_CHARGING, 100)
|
||||
assertEquals("Full", File(supplies, "BAT1/status").readText().trim())
|
||||
assertEquals("Full", File(vpower, "battery_status").readText().trim())
|
||||
battery?.stop()
|
||||
start(supplies, vpower, 2_000_000L, BatteryManager.BATTERY_STATUS_CHARGING, 99)
|
||||
assertEquals("Charging", File(supplies, "BAT1/status").readText().trim())
|
||||
}
|
||||
|
||||
private fun start(
|
||||
supplies: File, vpower: File, currentUa: Long,
|
||||
status: Int = BatteryManager.BATTERY_STATUS_DISCHARGING, level: Int = 50,
|
||||
) {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
context.sendStickyBroadcast(Intent(Intent.ACTION_BATTERY_CHANGED).apply {
|
||||
putExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_DISCHARGING)
|
||||
putExtra(BatteryManager.EXTRA_LEVEL, 50)
|
||||
putExtra(BatteryManager.EXTRA_STATUS, status)
|
||||
putExtra(BatteryManager.EXTRA_LEVEL, level)
|
||||
putExtra(BatteryManager.EXTRA_SCALE, 100)
|
||||
putExtra(BatteryManager.EXTRA_VOLTAGE, 4000)
|
||||
})
|
||||
|
||||
@@ -178,17 +178,39 @@ class BootMovieLibraryTest {
|
||||
assertNull(SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(app)))
|
||||
}
|
||||
|
||||
@Test fun onlyTheThreeStartupMoviesOfSteamAreListed() {
|
||||
listOf("deck_startup", "oled_startup", "startup_machine", "controller_generic_thumbstick_move").forEach {
|
||||
@Test fun onlyTheStartupMoviesOfSteamAreListed() {
|
||||
listOf("deck_startup", "oled_startup", "startup_machine", "steam_os_startup", "controller_generic_thumbstick_move").forEach {
|
||||
File(BootMovieLibrary.steamRoot(app), "steamui/movies/$it.webm").also { f -> f.parentFile!!.mkdirs(); f.writeText("movie") }
|
||||
}
|
||||
val ids = BootMovieLibrary.list(app).map { it.id }.filter { it.startsWith("steam:") }
|
||||
assertEquals(
|
||||
listOf("steam:/movies/deck_startup.webm", "steam:/movies/oled_startup.webm", "steam:/movies/startup_machine.webm"),
|
||||
listOf(
|
||||
"steam:/movies/deck_startup.webm", "steam:/movies/oled_startup.webm", "steam:/movies/startup_machine.webm",
|
||||
"steam:/movies/steam_os_startup.webm",
|
||||
),
|
||||
ids.sorted(),
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun steamsDefaultPickIsTakenOverAsItsOwnStartupMovie() {
|
||||
val native = File(BootMovieLibrary.steamRoot(app), "steamui/movies/steam_os_startup.webm").also { it.parentFile!!.mkdirs(); it.writeText("movie") }
|
||||
movie("a.webm")
|
||||
steamPicksAt(SessionFiles.BOOT_MOVIE_PATH)
|
||||
BootMovie.select(app, "file:a.webm")
|
||||
steamPicksAt("")
|
||||
assertTrue(BootMovie.syncFromSteam(app))
|
||||
assertEquals("steam:/movies/steam_os_startup.webm", BootMovie.choice(app))
|
||||
assertEquals(native, BootMovie.currentFile(app))
|
||||
assertFalse(BootMovie.syncFromSteam(app))
|
||||
}
|
||||
|
||||
@Test fun anEmptySteamPickThatWasNeverSeenChangesNothing() {
|
||||
File(BootMovieLibrary.steamRoot(app), "steamui/movies/steam_os_startup.webm").also { it.parentFile!!.mkdirs(); it.writeText("movie") }
|
||||
steamPicksAt("")
|
||||
assertFalse(BootMovie.syncFromSteam(app))
|
||||
assertEquals(BootMovie.DROIDDECK_30, BootMovie.choice(app))
|
||||
}
|
||||
|
||||
@Test fun aMovieBoughtInThePointsShopIsListedAndAdopted() {
|
||||
val file = File(BootMovieLibrary.steamRoot(app), "appcache/startupmovies/Bought.webm").also { it.parentFile!!.mkdirs(); it.writeText("movie") }
|
||||
val entry = BootMovieLibrary.list(app).first { it.id == "steam:/appcache/startupmovies/Bought.webm" }
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.core.Hashes
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.github.luben.zstd.ZstdOutputStream
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
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
|
||||
import java.io.BufferedOutputStream
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class ComponentImportTest {
|
||||
private lateinit var context: Context
|
||||
|
||||
@Before fun setUp() {
|
||||
context = RuntimeEnvironment.getApplication()
|
||||
File(context.filesDir, "components").deleteRecursively()
|
||||
LinuxRuntime.rootDir(context).deleteRecursively()
|
||||
}
|
||||
|
||||
@Test fun refusesOverwritingReferencedPackageWithDifferentContent() {
|
||||
val wcpA = createWcp("src-a.wcp", "A")
|
||||
val wcpB = createWcp("src-b.wcp", "B")
|
||||
val shaA = Hashes.sha256(wcpA)
|
||||
|
||||
ComponentsManager.importPackage(context, wcpA, "dxvk.wcp")
|
||||
ComponentsManager.setGameComponent(context, "10", "dxvk", "dxvk.wcp")
|
||||
|
||||
assertThrows(IllegalStateException::class.java) {
|
||||
ComponentsManager.importPackage(context, wcpB, "dxvk.wcp")
|
||||
}
|
||||
|
||||
val stored = File(context.filesDir, "components/packages/dxvk.wcp")
|
||||
assertEquals(shaA, Hashes.sha256(stored))
|
||||
assertFalse(File(context.filesDir, "components/packages/dxvk.wcp.part").exists())
|
||||
}
|
||||
|
||||
@Test fun allowsReimportingIdenticalPackageWhileReferenced() {
|
||||
val wcpA = createWcp("src-a.wcp", "A")
|
||||
val shaA = Hashes.sha256(wcpA)
|
||||
|
||||
ComponentsManager.importPackage(context, wcpA, "dxvk.wcp")
|
||||
ComponentsManager.setGameComponent(context, "10", "dxvk", "dxvk.wcp")
|
||||
|
||||
val reimported = ComponentsManager.importPackage(context, wcpA, "dxvk.wcp")
|
||||
assertEquals("A", reimported.version)
|
||||
assertEquals("dxvk.wcp", reimported.file)
|
||||
|
||||
val stored = File(context.filesDir, "components/packages/dxvk.wcp")
|
||||
assertEquals(shaA, Hashes.sha256(stored))
|
||||
assertFalse(File(context.filesDir, "components/packages/dxvk.wcp.part").exists())
|
||||
}
|
||||
|
||||
@Test fun invalidatesUnpackedStoreWhenReplacingUnreferencedPackage() {
|
||||
val wcpA = createWcp("src-a.wcp", "A")
|
||||
val wcpB = createWcp("src-b.wcp", "B")
|
||||
val shaB = Hashes.sha256(wcpB)
|
||||
|
||||
ComponentsManager.importPackage(context, wcpA, "dxvk.wcp")
|
||||
val unpacked = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-components/store/dxvk")
|
||||
unpacked.mkdirs()
|
||||
File(unpacked, ".complete").writeText("ok")
|
||||
assertTrue(File(unpacked, ".complete").isFile)
|
||||
|
||||
val replaced = ComponentsManager.importPackage(context, wcpB, "dxvk.wcp")
|
||||
assertEquals("B", replaced.version)
|
||||
|
||||
val stored = File(context.filesDir, "components/packages/dxvk.wcp")
|
||||
assertEquals(shaB, Hashes.sha256(stored))
|
||||
assertFalse(unpacked.exists())
|
||||
}
|
||||
|
||||
@Test fun deletingAPackageAGameProfileUsesClearsThatProfileEntry() {
|
||||
val wcpA = createWcp("src-a.wcp", "A")
|
||||
ComponentsManager.importPackage(context, wcpA, "dxvk.wcp")
|
||||
writeGameProfile("10", "dxvk", "dxvk.wcp")
|
||||
|
||||
ComponentsManager.deletePackage(context, "dxvk.wcp")
|
||||
|
||||
assertFalse(File(context.filesDir, "components/packages/dxvk.wcp").exists())
|
||||
val state = JSONObject(File(context.filesDir, "components/state.json").readText())
|
||||
assertFalse(state.optJSONObject("profiles")?.optJSONObject("10")?.has("dxvk") == true)
|
||||
}
|
||||
|
||||
private fun writeGameProfile(scope: String, comp: String, file: String) {
|
||||
val state = File(context.filesDir, "components/state.json")
|
||||
state.parentFile!!.mkdirs()
|
||||
state.writeText(
|
||||
JSONObject()
|
||||
.put("active", JSONObject())
|
||||
.put("queued", JSONObject())
|
||||
.put("profiles", JSONObject().put(scope, JSONObject().put(comp, file)))
|
||||
.toString(),
|
||||
)
|
||||
}
|
||||
|
||||
private fun createWcp(fileName: String, version: String): File {
|
||||
val out = File(context.cacheDir, fileName)
|
||||
val profile = JSONObject()
|
||||
.put("type", "DXVK-Linux")
|
||||
.put("versionName", version)
|
||||
.put("description", "DXVK $version")
|
||||
.toString()
|
||||
.toByteArray(Charsets.UTF_8)
|
||||
val dll = "dxvk-dll-$version".toByteArray(Charsets.UTF_8)
|
||||
|
||||
TarArchiveOutputStream(ZstdOutputStream(BufferedOutputStream(FileOutputStream(out)))).use { tar ->
|
||||
tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX)
|
||||
val profEntry = TarArchiveEntry("profile.json").apply { size = profile.size.toLong() }
|
||||
tar.putArchiveEntry(profEntry)
|
||||
tar.write(profile)
|
||||
tar.closeArchiveEntry()
|
||||
|
||||
val dllEntry = TarArchiveEntry("files/lib/wine/dxvk/aarch64-windows/d3d11.dll").apply { size = dll.size.toLong() }
|
||||
tar.putArchiveEntry(dllEntry)
|
||||
tar.write(dll)
|
||||
tar.closeArchiveEntry()
|
||||
}
|
||||
return out
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
class ComponentsCarryOverTest {
|
||||
@Test
|
||||
fun swappedPackagesFollowTheBuildThatReplacesTheirProton() {
|
||||
val state = JSONObject("""
|
||||
{"active": {"DroidDeck-Proton_11-11.2": {
|
||||
"dxvk": {"file": "dxvk-2.7.wcp", "label": "2.7", "protonVersion": "11-11.2"},
|
||||
"vkd3d": {"file": "original 11-11.1", "label": "Original from 11-11.1"},
|
||||
"fex": {"file": "gone.wcp", "label": "old"}}},
|
||||
"queued": {"DroidDeck-Proton_11-11.2": {
|
||||
"vkd3d": {"kind": "package", "file": "vkd3d-3.0.wcp", "label": "3.0"},
|
||||
"fex": {"kind": "original", "protonVersion": "11-11.1", "label": "Original 11-11.1"}}}}
|
||||
""".trimIndent())
|
||||
val carried = ComponentsManager.carried(state, "DroidDeck-Proton_11-11.2") { it != "gone.wcp" }
|
||||
assertEquals(setOf("dxvk", "vkd3d"), carried.keys)
|
||||
assertEquals("package", carried.getValue("dxvk").getString("kind"))
|
||||
assertEquals("dxvk-2.7.wcp", carried.getValue("dxvk").getString("file"))
|
||||
assertEquals("2.7", carried.getValue("dxvk").getString("label"))
|
||||
assertEquals("vkd3d-3.0.wcp", carried.getValue("vkd3d").getString("file"))
|
||||
assertEquals(emptyMap<String, JSONObject>(), ComponentsManager.carried(state, "GE-Proton11-7") { true })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import java.io.File
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
class ComponentsSelectionTest {
|
||||
private val proton = ComponentsManager.Proton("DroidDeck-Proton_11-11.1", "DroidDeck-Proton 11-11.1", File("/p"), "/p", "DroidDeck-Proton-11-11.1", false)
|
||||
private val entry = JSONObject().put("file", "dxvk-low-latency-arm64ec-3.1.1-2-linux.wcp").put("protonVersion", "DroidDeck-Proton-11-11.1")
|
||||
|
||||
@Test
|
||||
fun `a package swapped into an installed Proton is in use`() {
|
||||
assertTrue(ComponentsManager.liveSelection("active", entry, proton))
|
||||
assertTrue(ComponentsManager.liveSelection("queued", JSONObject().put("file", "x.wcp"), proton))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a package left on a removed Proton is not in use`() {
|
||||
assertFalse(ComponentsManager.liveSelection("active", entry, null))
|
||||
assertFalse(ComponentsManager.liveSelection("queued", entry, null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a package from before a Proton update is not in use`() {
|
||||
assertFalse(ComponentsManager.liveSelection("active", JSONObject(entry.toString()).put("protonVersion", "DroidDeck-Proton-11-9.1"), proton))
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.core.CpuAllocationDefaults
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
@@ -14,36 +13,22 @@ import org.robolectric.annotation.Config
|
||||
@Config(sdk = [33])
|
||||
class CoreAllocationPrefsTest {
|
||||
private val app get() = RuntimeEnvironment.getApplication()
|
||||
private val defaults = CpuAllocationDefaults.Allocation("7", "3,4,5,6")
|
||||
private val saved get() = app.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||
|
||||
@Before fun clear() { saved.edit().clear().commit() }
|
||||
|
||||
@Test fun absentPreferencesUseTheDeviceDefaultWithoutWritingIt() {
|
||||
assertEquals(SessionPrefs.CoreAllocation(true, "7", "3,4,5,6"), SessionPrefs.coreAllocation(app, defaults))
|
||||
assertTrue(saved.all.isEmpty())
|
||||
assertEquals(SessionPrefs.CoreAllocation(false, "", ""), SessionPrefs.coreAllocation(app, null))
|
||||
@Test fun absentPreferencesLeaveEveryCoreToTheScheduler() {
|
||||
assertFalse(SessionPrefs.clientCpusOverride(app))
|
||||
assertEquals("", SessionPrefs.clientCpus(app))
|
||||
assertEquals("", SessionPrefs.gameCpus(app))
|
||||
}
|
||||
|
||||
@Test fun explicitDisableAndAllCoreChoicesSurviveAnUpdate() {
|
||||
saved.edit().putBoolean("clientCpusOverride", false).putString("clientCpus", "").putString("gameCpus", "").commit()
|
||||
assertEquals(SessionPrefs.CoreAllocation(false, "", ""), SessionPrefs.coreAllocation(app, defaults))
|
||||
}
|
||||
|
||||
@Test fun existingCustomMasksArePreserved() {
|
||||
saved.edit().putBoolean("clientCpusOverride", true).putString("clientCpus", "0,1").putString("gameCpus", "2,7").commit()
|
||||
assertEquals(SessionPrefs.CoreAllocation(true, "0,1", "2,7"), SessionPrefs.coreAllocation(app, defaults))
|
||||
}
|
||||
|
||||
@Test fun anOldClientMaskIsNotEnabledWithoutAnOverrideChoice() {
|
||||
saved.edit().putString("clientCpus", "0,1").commit()
|
||||
assertEquals(SessionPrefs.CoreAllocation(false, "0,1", "3,4,5,6"), SessionPrefs.coreAllocation(app, defaults))
|
||||
}
|
||||
|
||||
@Test fun changingOneChoiceDoesNotReplaceTheOtherDefaults() {
|
||||
SessionPrefs.setGameCpus(app, "0,1,2,3,4,5,6,7")
|
||||
assertEquals(SessionPrefs.CoreAllocation(true, "7", "0,1,2,3,4,5,6,7"), SessionPrefs.coreAllocation(app, defaults))
|
||||
SessionPrefs.setClientCpusOverride(app, false)
|
||||
assertEquals(SessionPrefs.CoreAllocation(false, "7", "0,1,2,3,4,5,6,7"), SessionPrefs.coreAllocation(app, defaults))
|
||||
@Test fun savedChoicesAreKept() {
|
||||
SessionPrefs.setClientCpusOverride(app, true)
|
||||
SessionPrefs.setClientCpus(app, "7")
|
||||
SessionPrefs.setGameCpus(app, "3,4,5,6")
|
||||
assertTrue(SessionPrefs.clientCpusOverride(app))
|
||||
assertEquals("7", SessionPrefs.clientCpus(app))
|
||||
assertEquals("3,4,5,6", SessionPrefs.gameCpus(app))
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,18 @@ class ForcedPackageTest {
|
||||
LinuxRuntime.rootDir(context).deleteRecursively()
|
||||
}
|
||||
|
||||
@Test fun unpackedCacheNameCannotEscapeStoreDirectory() {
|
||||
assertEquals("dxvk-2.7.1-linux", ComponentsManager.unpackedCacheKey(dxvk2))
|
||||
for (filename in listOf("..wcp", "...wcp")) {
|
||||
try {
|
||||
ComponentsManager.unpackedCacheKey(filename)
|
||||
fail("Expected cache traversal name to be rejected: $filename")
|
||||
} catch (_: IllegalArgumentException) {
|
||||
// Expected: the derived path would be a dot segment.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun adreno6xxForcesDxvk2AndNothingElseDoes() {
|
||||
val rule = ComponentsManager.FORCED_PACKAGES.single { GpuInfo.Family.A6XX in it.families }
|
||||
assertEquals("dxvk", rule.comp)
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
class LoadingStateTest {
|
||||
@Test fun clientDownloadCountsMegabytesWhenTheRuntimeSaysThem() {
|
||||
assertEquals(
|
||||
"45 / 360 MB" to 12,
|
||||
LoadingState.clientDownload("== STEP 17:38:20 downloading Steam: bins_linuxarm64_linuxarm64 (2/17), 45 of 360 MB"),
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun aStalledDownloadStillShowsWhereItIs() {
|
||||
assertEquals(
|
||||
"45 / 360 MB" to 12,
|
||||
LoadingState.clientDownload(
|
||||
"== STEP 17:39:20 downloading Steam: bins_linuxarm64_linuxarm64 (2/17), 45 of 360 MB" +
|
||||
" - interrupted (curl exit 28), trying again in 5 s",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun anOlderRuntimeShowsThePartAndItsNumber() {
|
||||
assertEquals(
|
||||
"bins_linuxarm64_linuxarm64" to 11,
|
||||
LoadingState.clientDownload("== STEP 17:38:17 downloading Steam: bins_linuxarm64_linuxarm64 (2/17)"),
|
||||
)
|
||||
assertEquals("a_all" to 50, LoadingState.clientDownload("== STEP 00:00:00 downloading Steam: a_all (1/2), 0 of 0 MB"))
|
||||
}
|
||||
|
||||
@Test fun otherStepsAreNotClientDownloads() {
|
||||
assertNull(LoadingState.clientDownload("== STEP 17:38:14 checking the Steam client (a first run downloads it)"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class MemoryReadoutTest {
|
||||
private val meminfo = """
|
||||
MemTotal: 11379920 kB
|
||||
MemFree: 527864 kB
|
||||
MemAvailable: 3235768 kB
|
||||
Buffers: 1024 kB
|
||||
SwapTotal: 16777212 kB
|
||||
SwapFree: 10358080 kB
|
||||
""".trimIndent()
|
||||
|
||||
@Test fun memoryAndSwapInUseComeFromMeminfo() {
|
||||
val device = MemoryReadout.parseMeminfo(meminfo)!!
|
||||
assertEquals(11379920L - 3235768L, device.usedKb)
|
||||
assertEquals(16777212L - 10358080L, device.swapUsedKb)
|
||||
assertEquals("7.8", MemoryReadout.gb(device.usedKb))
|
||||
assertEquals("10.9", MemoryReadout.gb(device.totalKb))
|
||||
assertEquals(0L, MemoryReadout.parseMeminfo("MemTotal: 100 kB\nMemAvailable: 40 kB\n")!!.swapUsedKb)
|
||||
assertNull(MemoryReadout.parseMeminfo("MemTotal: 100 kB\n"))
|
||||
}
|
||||
|
||||
@Test fun aProcessCountsItsResidentAnonymousAndSharedMemory() {
|
||||
val status = """
|
||||
Name: Diablo IV.exe
|
||||
VmRSS: 2000000 kB
|
||||
RssAnon: 1500000 kB
|
||||
RssFile: 400000 kB
|
||||
RssShmem: 100000 kB
|
||||
VmSwap: 300000 kB
|
||||
""".trimIndent()
|
||||
assertEquals(1600000L, MemoryReadout.residentKb(status))
|
||||
assertEquals(0L, MemoryReadout.residentKb("Name:\tkthreadd\n"))
|
||||
}
|
||||
|
||||
@Test fun theGameIsWhatRunsInAWinePrefix() {
|
||||
fun env(vararg vars: String) = vars.joinToString("\u0000", postfix = "\u0000").toByteArray()
|
||||
assertTrue(MemoryReadout.inWinePrefix(env("HOME=/root", "WINEPREFIX=/root/pfx", "DISPLAY=:0")))
|
||||
assertTrue(MemoryReadout.inWinePrefix("WINEPREFIX=/x".toByteArray()))
|
||||
assertFalse(MemoryReadout.inWinePrefix(env("HOME=/root", "STEAM_COMPAT_DATA_PATH=/x", "MY_WINEPREFIX=/y")))
|
||||
assertFalse(MemoryReadout.inWinePrefix(ByteArray(0)))
|
||||
}
|
||||
|
||||
@Test fun androidIsWhatIsLeftOfTheMemoryInUse() {
|
||||
val device = MemoryReadout.Device(totalKb = 10_000, availableKb = 3_000, swapTotalKb = 0, swapFreeKb = 0)
|
||||
assertEquals(3_000L, MemoryReadout.androidKb(device, MemoryReadout.Split(gameKb = 2_000, droiddeckKb = 1_000, gpuKb = 1_000)))
|
||||
assertEquals(4_000L, MemoryReadout.androidKb(device, MemoryReadout.Split(gameKb = 2_000, droiddeckKb = 1_000, gpuKb = null)))
|
||||
assertEquals(0L, MemoryReadout.androidKb(device, MemoryReadout.Split(gameKb = 6_000, droiddeckKb = 2_000, gpuKb = 1_000)))
|
||||
}
|
||||
|
||||
@Test fun theLogLineSaysEveryPartInMegabytes() {
|
||||
val device = MemoryReadout.Device(totalKb = 11_379_920, availableKb = 1_048_576, swapTotalKb = 16_777_212, swapFreeKb = 8_388_606)
|
||||
val split = MemoryReadout.Split(gameKb = 2_097_152, droiddeckKb = 524_288, gpuKb = 3_145_728)
|
||||
assertEquals(
|
||||
"used 10089/11113 MB, available 1024 MB, swap 8191/16383 MB | game 2048, droiddeck 512, android 4457, gpu 3072 MB",
|
||||
MemoryLog.line(device, split),
|
||||
)
|
||||
assertTrue(MemoryLog.line(device, split.copy(gpuKb = null)).endsWith("gpu ? MB"))
|
||||
}
|
||||
}
|
||||
@@ -61,6 +61,8 @@ class NoSteamLaunchTest {
|
||||
listOf("--app", "2733369024", "--dir", game.guestDir, "--options", "-windowed", "--", game.guestExe),
|
||||
added.args,
|
||||
)
|
||||
val plain = NoSteamLaunch.addedCommand(AddedGames.Game(game.folder, game.name, game.exe, game.guestExe, game.guestDir, 2733369024L, 0L, emptyList(), source = "gog"))
|
||||
assertEquals(listOf("--app", "2733369024", "--dir", game.guestDir, "--", game.guestExe), plain.args)
|
||||
assertNull(NoSteamLaunch.command(shortcut, null))
|
||||
val steam = NoSteamLaunch.command(steamGame, null)!!
|
||||
assertEquals(listOf("--app", "413150"), steam.args)
|
||||
|
||||
@@ -20,7 +20,7 @@ class OrientationTest {
|
||||
}
|
||||
|
||||
@Test fun landscapeChoicesPersistGloballyAndCanRestoreAutomaticRotation() {
|
||||
assertEquals(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, SessionPrefs.orientation(context))
|
||||
assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, SessionPrefs.orientation(context))
|
||||
for (value in listOf(
|
||||
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
|
||||
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE,
|
||||
@@ -34,7 +34,7 @@ class OrientationTest {
|
||||
@Test fun invalidStoredOrientationFallsBackAndInvalidChoicePreservesTheSavedValue() {
|
||||
val prefs = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||
prefs.edit().putInt("orientation", ActivityInfo.SCREEN_ORIENTATION_PORTRAIT).commit()
|
||||
assertEquals(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, SessionPrefs.orientation(context))
|
||||
assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, SessionPrefs.orientation(context))
|
||||
SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE)
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
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 PerformanceModeTest {
|
||||
private val app get() = RuntimeEnvironment.getApplication()
|
||||
private val session get() = app.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||
|
||||
@Before fun clear() { session.edit().clear().commit() }
|
||||
|
||||
@Test fun offByDefaultAndPerMode() {
|
||||
assertFalse(SessionPrefs.performanceMode(app, SessionService.MODE_STEAM))
|
||||
SessionPrefs.setPerformanceMode(app, SessionService.MODE_STEAM, true)
|
||||
assertTrue(SessionPrefs.performanceMode(app, SessionService.MODE_STEAM))
|
||||
assertFalse(SessionPrefs.performanceMode(app, SessionService.MODE_DESKTOP))
|
||||
}
|
||||
|
||||
@Test fun offKeepsTodaysPacing() {
|
||||
assertEquals(0, SessionPrefs.compositorFpsLimit(0, false))
|
||||
assertEquals(60, SessionPrefs.compositorFpsLimit(60, false))
|
||||
}
|
||||
|
||||
@Test fun onWithoutALimitIsUnpacedAndAChosenLimitStillPaces() {
|
||||
assertEquals(SessionPrefs.FPS_UNPACED, SessionPrefs.compositorFpsLimit(0, true))
|
||||
assertEquals(60, SessionPrefs.compositorFpsLimit(60, true))
|
||||
}
|
||||
|
||||
@Test fun anOldUncappedFrameLimitReadsAsOff() {
|
||||
session.edit().putInt("fpsLimit.steam", -1).commit()
|
||||
assertEquals(0, SessionPrefs.fpsLimit(app, SessionService.MODE_STEAM))
|
||||
assertFalse(SessionPrefs.fpsLimitChoices.any { it.first < 0 })
|
||||
}
|
||||
}
|
||||
@@ -103,4 +103,28 @@ class ProtonDefaultTest {
|
||||
assertNull(ProtonDefault.gameSelectedId(context, "42", listOf(proton("GE-Proton11-7", false))))
|
||||
assertEquals(ProtonDefault.GameChoice(false, "GE-Proton9-1"), ProtonDefault.parseGames(file.readText())["42"])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aReplacedBuildsPerGamePicksMoveToTheNewest() {
|
||||
val old = ProtonDefault.GameChoice(false, "DroidDeck-Proton 11-11.2")
|
||||
val ge = ProtonDefault.GameChoice(false, "GE-Proton11-7")
|
||||
val valve = ProtonDefault.GameChoice(true, "DroidDeck-Proton 11-11.2")
|
||||
val moved = ProtonDefault.movedGames(mapOf("42" to old, "43" to ge, "44" to null, "45" to valve), setOf("DroidDeck-Proton 11-11.2"), "DroidDeck-Proton 11-11.4")
|
||||
assertEquals(mapOf("42" to ProtonDefault.GameChoice(false, "DroidDeck-Proton 11-11.4"), "43" to ge, "44" to null, "45" to valve), moved)
|
||||
assertNull(ProtonDefault.movedGames(mapOf("43" to ge, "44" to null), setOf("DroidDeck-Proton 11-11.2"), "DroidDeck-Proton 11-11.4"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun movingPicksRewritesTheGamesFile() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val file = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-compat/games.json")
|
||||
file.parentFile?.deleteRecursively()
|
||||
ProtonDefault.requestGame(context, "42", proton("DroidDeck-Proton 11-11.2", false))
|
||||
ProtonDefault.requestGame(context, "43", null)
|
||||
ProtonDefault.moveGames(context, setOf("DroidDeck-Proton 11-11.2"), "DroidDeck-Proton 11-11.4")
|
||||
val games = ProtonDefault.parseGames(file.readText())
|
||||
assertEquals(ProtonDefault.GameChoice(false, "DroidDeck-Proton 11-11.4"), games["42"])
|
||||
assertTrue(games.containsKey("43"))
|
||||
assertNull(games["43"])
|
||||
}
|
||||
}
|
||||
@@ -171,4 +171,62 @@ class ProtonExtrasTest {
|
||||
assertEquals(listOf("DroidDeck-Proton 11-7.10"), ProtonExtras.installedAll(context, tool("droiddeck")))
|
||||
assertEquals("DroidDeck-Proton 11-7.10", ProtonExtras.installed(context, tool("droiddeck")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun removingABuildDropsItsStoredOriginalsAndSelections() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val tools = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/compatibilitytools.d")
|
||||
File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-components").mkdirs()
|
||||
installTool(tools, "GE-Proton11-7")
|
||||
val kept = installTool(tools, "GE-Proton11-8").apply {
|
||||
File(this, "files/lib/wine").mkdirs()
|
||||
File(this, "proton").writeText("")
|
||||
}
|
||||
val originals = File(context.filesDir, "components/originals")
|
||||
for (id in listOf("GE-Proton11-7", "GE-Proton11-8")) File(originals, "$id/$id/dxvk.wcp").apply { parentFile?.mkdirs(); writeText("x") }
|
||||
val pick = JSONObject().put("dxvk", JSONObject().put("file", "dxvk.wcp").put("protonVersion", "GE-Proton11-7"))
|
||||
File(context.filesDir, "components/state.json").writeText(JSONObject()
|
||||
.put("active", JSONObject().put("GE-Proton11-7", pick).put("GE-Proton11-8", pick))
|
||||
.put("queued", JSONObject().put("GE-Proton11-7", pick)).toString())
|
||||
ProtonExtras.remove(context, tool("ge"), "GE-Proton11-7")
|
||||
assertFalse(File(originals, "GE-Proton11-7").exists())
|
||||
assertTrue(File(originals, "GE-Proton11-8/GE-Proton11-8/dxvk.wcp").isFile)
|
||||
val state = JSONObject(File(context.filesDir, "components/state.json").readText())
|
||||
assertFalse(state.getJSONObject("active").has("GE-Proton11-7"))
|
||||
assertFalse(state.getJSONObject("queued").has("GE-Proton11-7"))
|
||||
assertTrue(state.getJSONObject("active").has("GE-Proton11-8"))
|
||||
ComponentsManager.forgetProton(context, kept.name)
|
||||
assertTrue(File(originals, "GE-Proton11-8/GE-Proton11-8/dxvk.wcp").isFile)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anUpdateKeepsTheUsersProtonSettingsFile() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val tools = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/compatibilitytools.d")
|
||||
tools.deleteRecursively()
|
||||
File(installTool(tools, "DroidDeck-Proton 11-11.1"), "user_settings.py").writeText("old")
|
||||
File(installTool(tools, "DroidDeck-Proton 11-11.4"), "user_settings.py").writeText("mine")
|
||||
installTool(tools, "DroidDeck-Proton 11-11.5")
|
||||
ProtonExtras.tidy(context)
|
||||
assertEquals(listOf("DroidDeck-Proton 11-11.5"), ProtonExtras.installedAll(context, tool("droiddeck")))
|
||||
assertEquals("mine", File(tools, "DroidDeck-Proton 11-11.5/user_settings.py").readText())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun droidDeckProtonIsFetchedWhenMissingUnlessTheUserRemovedIt() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val tools = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/compatibilitytools.d")
|
||||
tools.deleteRecursively()
|
||||
File(context.filesDir, "proton-latest.json").writeText(
|
||||
"""{"droiddeck":{"tag":"DroidDeck-Proton-11-11.4","at":1},"ge":{"tag":"GE-Proton11-7","at":1}}""")
|
||||
ProtonExtras.setDeclined(context, false)
|
||||
assertEquals("DroidDeck-Proton-11-11.4", ProtonExtras.missing(context, tool("droiddeck")))
|
||||
assertNull(ProtonExtras.missing(context, tool("ge")))
|
||||
ProtonExtras.setDeclined(context, true)
|
||||
assertNull(ProtonExtras.missing(context, tool("droiddeck")))
|
||||
ProtonExtras.setDeclined(context, false)
|
||||
installTool(tools, "DroidDeck-Proton 11-11.2")
|
||||
assertNull(ProtonExtras.missing(context, tool("droiddeck")))
|
||||
assertEquals("DroidDeck-Proton-11-11.4", ProtonExtras.update(context, tool("droiddeck")))
|
||||
}
|
||||
}
|
||||
@@ -96,7 +96,10 @@ class SessionDisplayTest {
|
||||
@Test fun gameStretchAvailabilityMatchesTheRuntimeIncludingRounding() {
|
||||
assertTrue(SessionDisplay.canStretch16x9(960 to 720))
|
||||
assertFalse(SessionDisplay.canStretch16x9(1280 to 720))
|
||||
assertFalse(SessionDisplay.canStretch16x9(1600 to 720))
|
||||
assertTrue(SessionDisplay.canStretch16x9(1600 to 720))
|
||||
assertTrue(SessionDisplay.canStretch16x9(2400 to 1080))
|
||||
assertFalse(SessionDisplay.canStretch16x9(1920 to 1080))
|
||||
assertFalse(SessionDisplay.canStretch16x9(1366 to 768))
|
||||
val wide = SessionDisplay.resolve(1440 to 1080, 0, SessionPrefs.SHAPE_WIDE)
|
||||
assertFalse(SessionDisplay.canStretch16x9(wide))
|
||||
}
|
||||
|
||||
@@ -50,6 +50,34 @@ class SessionLogShareZipTest {
|
||||
assertFalse(zip.exists())
|
||||
}
|
||||
|
||||
@Test fun battleNetAndBlizzardLogsComeAlongScrubbedAndNewestFirst() {
|
||||
val session = File(LinuxRuntime.logDir(app), "2026-10-25-05-battle-net").apply { mkdirs() }
|
||||
File(session, "session.log").writeText("droiddeck-battlenet: open (from the menu)\n")
|
||||
val root = LinuxRuntime.rootDir(app)
|
||||
File(root, "root/.cache/droiddeck/battlenet").apply { mkdirs() }.apply {
|
||||
resolve("battlenet.log").writeText("launching WoW\n")
|
||||
resolve("other.log").writeText("other\n")
|
||||
}
|
||||
val drive = File(com.droiddeck.launcher.runtime.BattleNet.prefix(app), "pfx/drive_c")
|
||||
val client = File(drive, "users/steamuser/AppData/Local/Battle.net/Logs").apply { mkdirs() }
|
||||
val now = System.currentTimeMillis()
|
||||
for (i in 1..8) client.resolve("battle.net-$i.log").apply { writeText("client $i accountId=1:0:5ca1ab1e\n"); setLastModified(now - i * 60_000L) }
|
||||
client.resolve("battle.net-old.log").apply { writeText("old\n"); setLastModified(now - 30L * 86_400_000L) }
|
||||
File(drive, "ProgramData/Battle.net/Agent/Agent.9824/Logs").apply { mkdirs() }.resolve("Agent-1.log").writeText("agent someone@example.com\n")
|
||||
File(drive, "ProgramData/Battle.net/Agent/Agent.9900/Logs").apply { mkdirs() }.resolve("Agent-1.log").writeText("agent 9900\n")
|
||||
File(drive, "ProgramData/Battle.net/Setup/bna_2/Logs").apply { mkdirs() }.resolve("battle.net-setup-1.log").writeText("setup\n")
|
||||
|
||||
val zip = SessionLogShare.zipFolder(app, session)!!
|
||||
val text = ZipFile(zip).use { z -> z.entries().toList().associate { e -> e.name to z.getInputStream(e).bufferedReader().readText() } }
|
||||
assertTrue(text.keys.containsAll(listOf("battlenet/droiddeck/battlenet.log", "battlenet/agent/Agent.9824/Agent-1.log", "battlenet/agent/Agent.9900/Agent-1.log", "battlenet/setup/bna_2/battle.net-setup-1.log")))
|
||||
assertFalse(text.containsKey("battlenet/droiddeck/other.log"))
|
||||
assertEquals((1..6).map { "battlenet/client/battle.net-$it.log" }.toSet(), text.keys.filter { it.startsWith("battlenet/client/") }.toSet())
|
||||
val all = text.values.joinToString("\n")
|
||||
assertFalse(all.contains("5ca1ab1e"))
|
||||
assertFalse(all.contains("someone@example.com"))
|
||||
SessionLogShare.clear(app)
|
||||
}
|
||||
|
||||
@Test fun theSharePassChangesNothingInACleanLine() {
|
||||
val line = "dxvk: Device 0x5 (Adreno 750) https://github.com/doitsujin/dxvk/releases code 403"
|
||||
assertEquals(line, com.droiddeck.launcher.core.LogRedactor.redactForShare(line))
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.os.Looper
|
||||
import java.util.concurrent.AbstractExecutorService
|
||||
import java.util.concurrent.TimeUnit
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.Robolectric
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.LooperMode
|
||||
import org.robolectric.util.ReflectionHelpers
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
@LooperMode(LooperMode.Mode.PAUSED)
|
||||
class SessionSleepRequestTest {
|
||||
private lateinit var service: SessionService
|
||||
private val work = ArrayDeque<Runnable>()
|
||||
private val executor = object : AbstractExecutorService() {
|
||||
override fun execute(command: Runnable) { work.addLast(command) }
|
||||
override fun shutdown() {}
|
||||
override fun shutdownNow(): MutableList<Runnable> = mutableListOf()
|
||||
override fun isShutdown() = false
|
||||
override fun isTerminated() = false
|
||||
override fun awaitTermination(timeout: Long, unit: TimeUnit) = false
|
||||
}
|
||||
|
||||
@Before fun setUp() {
|
||||
service = Robolectric.buildService(SessionService::class.java).get()
|
||||
SessionState.running = true
|
||||
SessionState.suspended = false
|
||||
SessionState.mode = SessionService.MODE_RUN
|
||||
ReflectionHelpers.setField(service, "suspendPolicy", SessionPrefs.SUSPEND_NEVER)
|
||||
ReflectionHelpers.setField(service, "suspendController", SessionSuspendController(
|
||||
sessionRoot = { -1 }, helperRoots = { emptyList() },
|
||||
suspendAudio = {}, resumeAudio = {}, executor = executor,
|
||||
))
|
||||
}
|
||||
|
||||
@After fun tearDown() {
|
||||
SessionState.running = false
|
||||
SessionState.suspended = false
|
||||
SessionState.mode = SessionService.MODE_STEAM
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
work.clear()
|
||||
}
|
||||
|
||||
@Test fun cancelledFreezePreservesAndRetriesANewerSteamRequest() {
|
||||
ReflectionHelpers.setField(service, "steamSleepToken", "old-request")
|
||||
ReflectionHelpers.callInstanceMethod<Void>(service, "updateSuspendPolicy")
|
||||
assertEquals(1, work.size)
|
||||
ReflectionHelpers.setField(service, "freezeCancelled", true)
|
||||
ReflectionHelpers.setField(service, "steamSleepToken", "new-request")
|
||||
work.removeFirst().run()
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
assertEquals("new-request", ReflectionHelpers.getField<String>(service, "steamSleepToken"))
|
||||
assertEquals(1, work.size)
|
||||
assertFalse(ReflectionHelpers.getField(service, "suspendAttemptFailed"))
|
||||
}
|
||||
|
||||
@Test fun cancelledFreezeCompletesItsOwnRequestWithoutRetryingIt() {
|
||||
ReflectionHelpers.setField(service, "steamSleepToken", "old-request")
|
||||
ReflectionHelpers.callInstanceMethod<Void>(service, "updateSuspendPolicy")
|
||||
ReflectionHelpers.setField(service, "freezeCancelled", true)
|
||||
work.removeFirst().run()
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
assertEquals(null, ReflectionHelpers.getField<String?>(service, "steamSleepToken"))
|
||||
assertEquals(0, work.size)
|
||||
assertFalse(ReflectionHelpers.getField(service, "suspendAttemptFailed"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import java.io.File
|
||||
|
||||
class SessionSteamLogsTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
private fun names(files: List<File>) = files.map { it.name }.sorted()
|
||||
|
||||
@Test fun onlyWhatTheSessionWroteIsCollected() {
|
||||
val logs = tmp.newFolder("logs")
|
||||
val session = tmp.newFolder("session")
|
||||
val out = tmp.newFolder("out")
|
||||
File(logs, "console_log.txt").writeText("old line\n")
|
||||
File(logs, "cef_log.txt").writeText("old cef\n")
|
||||
File(logs, "cef_log.previous.txt").writeText("older cef\n")
|
||||
File(logs, "shrunk.txt").writeText("a long old line\n")
|
||||
File(logs, "untouched.txt").writeText("nothing new\n")
|
||||
SessionArtifacts.markSteamLogs(session, logs)
|
||||
|
||||
File(logs, "console_log.txt").appendText("new line\n")
|
||||
File(logs, "cef_log.previous.txt").delete()
|
||||
File(logs, "cef_log.txt").renameTo(File(logs, "cef_log.previous.txt"))
|
||||
File(logs, "cef_log.txt").writeText("this session's cef\n")
|
||||
File(logs, "shrunk.txt").writeText("short\n")
|
||||
File(logs, "content_log.txt").writeText("created this session\n")
|
||||
|
||||
val copied = SessionArtifacts.copySessionLogs(logs, session, out)
|
||||
assertEquals(listOf("cef_log.txt", "console_log.txt", "content_log.txt", "shrunk.txt"), names(copied))
|
||||
assertEquals("new line\n", File(out, "console_log.txt").readText())
|
||||
assertEquals("this session's cef\n", File(out, "cef_log.txt").readText())
|
||||
assertEquals("short\n", File(out, "shrunk.txt").readText())
|
||||
assertFalse(File(out, "cef_log.previous.txt").exists())
|
||||
assertFalse(File(out, "untouched.txt").exists())
|
||||
}
|
||||
|
||||
@Test fun aLineCutByTheMarkIsLeftOut() {
|
||||
val logs = tmp.newFolder("logs")
|
||||
val session = tmp.newFolder("session")
|
||||
val out = tmp.newFolder("out")
|
||||
File(logs, "web.txt").writeText("old\nGET /x?sessionid=")
|
||||
SessionArtifacts.markSteamLogs(session, logs)
|
||||
File(logs, "web.txt").appendText("abcdef123456 200\nnext line\n")
|
||||
SessionArtifacts.copySessionLogs(logs, session, out)
|
||||
assertEquals("next line\n", File(out, "web.txt").readText())
|
||||
}
|
||||
|
||||
@Test fun withoutMarksEveryLogUnderTheCapIsCollectedAndRedacted() {
|
||||
val logs = tmp.newFolder("logs")
|
||||
val out = tmp.newFolder("out")
|
||||
File(logs, "web.txt").writeText("GET /x?sessionid=abcdef123456 200\n")
|
||||
File(logs, "big.txt").outputStream().use { it.write(ByteArray(8 * 1024 * 1024)) }
|
||||
val copied = SessionArtifacts.copySessionLogs(logs, tmp.newFolder("session"), out)
|
||||
assertEquals(listOf("web.txt"), names(copied))
|
||||
assertFalse(File(out, "web.txt").readText().contains("abcdef123456"))
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,66 @@ class SessionSuspendControllerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun pageOutRunsInPreloadedGuestsBeforeTheyStop() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.controller.freeze(pageOut = true) { assertTrue(it) }
|
||||
val urgent = fixture.signals.filter { it.signal == URG }
|
||||
assertEquals(listOf(GAME), urgent.map { it.pid })
|
||||
assertTrue(fixture.signals.indexOfFirst { it.signal == URG } < fixture.signals.indexOfFirst { it.signal == STOP })
|
||||
assertEquals("1", fixture.control.readText())
|
||||
assertEquals(listOf(Triple(1, 1_000_000L, 3_000_000L)), fixture.pagedOut)
|
||||
assertEquals(0, fixture.unacknowledged)
|
||||
assertTrue(fixture.game.threads.all { it.state == 't' })
|
||||
assertFalse(File(fixture.control.parentFile, ".bl-zram.ack.$GAME").exists())
|
||||
}
|
||||
|
||||
@Test fun unchangedSwapIsNotTakenForAFinishedPageOut() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.handlerStalls = true
|
||||
var stoppedEarly = false
|
||||
fixture.afterSleep = {
|
||||
if (fixture.now == 3000L) fixture.handlerStalls = false
|
||||
if (fixture.handlerStalls && fixture.signals.any { it.signal == STOP }) stoppedEarly = true
|
||||
}
|
||||
fixture.controller.freeze(pageOut = true) { assertTrue(it) }
|
||||
assertFalse(stoppedEarly)
|
||||
assertEquals(0, fixture.unacknowledged)
|
||||
}
|
||||
|
||||
@Test fun replacedHandlerIsNotWaitedForPastTheStartWindow() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.handlerReplaced = true
|
||||
fixture.controller.freeze(pageOut = true) { assertTrue(it) }
|
||||
assertEquals(1, fixture.unacknowledged)
|
||||
assertTrue(fixture.now in 2000L..3000L)
|
||||
}
|
||||
|
||||
@Test fun cancelledFreezeRollsBackWithoutStopping() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.handlerStalls = true
|
||||
fixture.afterSleep = { if (fixture.now >= 500) fixture.controller.cancelFreeze() }
|
||||
fixture.controller.freeze(pageOut = true) { assertFalse(it) }
|
||||
assertFalse(fixture.signals.any { it.signal == STOP })
|
||||
assertTrue(fixture.game.threads.all { it.state == 'S' })
|
||||
assertEquals(1, fixture.audioResumes)
|
||||
}
|
||||
|
||||
@Test fun noPageOutWithoutTheRequestOrTheControlFile() {
|
||||
val visible = fixture(17)
|
||||
visible.control.writeText("0")
|
||||
visible.controller.freeze { assertTrue(it) }
|
||||
assertFalse(visible.signals.any { it.signal == URG })
|
||||
assertEquals("0", visible.control.readText())
|
||||
val disabled = fixture(17)
|
||||
disabled.controller.freeze(pageOut = true) { assertTrue(it) }
|
||||
assertFalse(disabled.signals.any { it.signal == URG })
|
||||
assertTrue(disabled.pagedOut.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun cpuMustBeStableAcrossTwoCompleteSnapshots() {
|
||||
val fixture = fixture(17)
|
||||
var changes = 0
|
||||
@@ -253,13 +313,13 @@ class SessionSuspendControllerTest {
|
||||
}
|
||||
|
||||
private fun fixture(count: Int, executor: QueueExecutor = InlineExecutor()) =
|
||||
Fixture(temporary.newFolder(), count, executor)
|
||||
Fixture(temporary.newFolder(), temporary.newFolder(), count, executor)
|
||||
|
||||
private data class Task(val tid: Int, var started: Long, var state: Char, var cpu: Long = 0)
|
||||
private data class Group(val pid: Int, var parent: Int, var tracer: Int, val threads: MutableList<Task>)
|
||||
private data class SentSignal(val pid: Int, val signal: Int)
|
||||
|
||||
private class Fixture(val proc: File, count: Int, executor: QueueExecutor) {
|
||||
private class Fixture(val proc: File, tmp: File, count: Int, executor: QueueExecutor) {
|
||||
val root = Group(ROOT, 9000, 0, mutableListOf(Task(ROOT, 1000, 'S')))
|
||||
val game = Group(GAME, ROOT, ROOT, MutableList(count) { Task(GAME + it, 2000L + it, 'S') })
|
||||
val groups = mutableListOf(root, game)
|
||||
@@ -276,10 +336,23 @@ class SessionSuspendControllerTest {
|
||||
var emptyGameTasks = false
|
||||
var rootGone = false
|
||||
var afterSleep: (() -> Unit)? = null
|
||||
val control = File(tmp, ".bl-zram")
|
||||
val pagedOut = mutableListOf<Triple<Int, Long, Long>>()
|
||||
private var gameResidentKb = 4_000_000L
|
||||
private var gameSwapKb = 0L
|
||||
private var pagingOut = false
|
||||
var unacknowledged = -1
|
||||
var handlerStalls = false
|
||||
var handlerReplaced = false
|
||||
private var continuing = false
|
||||
val controller = SessionSuspendController(
|
||||
{ rootPid }, { helpers }, { audioSuspends++ }, { audioResumes++ },
|
||||
proc, ::signal, ::threadSignal, ::sleep, { now }, executor,
|
||||
zramControl = control,
|
||||
pagedOut = { processes, unacknowledged, resident, swap, _, _ ->
|
||||
pagedOut += Triple(processes, resident, swap)
|
||||
this.unacknowledged = unacknowledged
|
||||
},
|
||||
)
|
||||
|
||||
init { sync() }
|
||||
@@ -293,6 +366,8 @@ class SessionSuspendControllerTest {
|
||||
else group.threads.firstOrNull {
|
||||
it.state !in listOf('T', 't', 'Z', 'X') && !(neverStop && it == game.threads.last())
|
||||
}?.state = 't'
|
||||
} else if (signal == URG) {
|
||||
pagingOut = true
|
||||
} else if (signal == CONT) {
|
||||
continuing = true
|
||||
if (!(pid == GAME && blockGameContinue)) group.threads.forEach { if (it.state != 'Z') it.state = 'S' }
|
||||
@@ -311,6 +386,18 @@ class SessionSuspendControllerTest {
|
||||
|
||||
private fun sleep(millis: Long) {
|
||||
now += millis
|
||||
if (pagingOut && !handlerReplaced) {
|
||||
File(control.parentFile, "${control.name}.ack.$GAME").apply { if (!exists()) writeText("") }
|
||||
}
|
||||
if (pagingOut && !handlerStalls && !handlerReplaced) {
|
||||
if (gameResidentKb > 1_000_000L) {
|
||||
gameResidentKb -= 1_000_000L
|
||||
gameSwapKb += 1_000_000L
|
||||
} else {
|
||||
File(control.parentFile, "${control.name}.ack.$GAME").writeText("1")
|
||||
pagingOut = false
|
||||
}
|
||||
}
|
||||
if (root.threads.first().state != 'T' && !continuing) game.threads.forEach {
|
||||
if (it.state != 'Z') { it.state = 'S'; it.cpu++ }
|
||||
}
|
||||
@@ -326,7 +413,11 @@ class SessionSuspendControllerTest {
|
||||
val stat = File(dir, "stat")
|
||||
if (group == game && missingGameStat) stat.delete()
|
||||
else stat.writeText(stat(group, group.threads.first()))
|
||||
File(dir, "status").writeText("TracerPid: ${group.tracer}\n")
|
||||
File(dir, "status").writeText(
|
||||
"TracerPid: ${group.tracer}\n" +
|
||||
if (group == game) "VmRSS:\t$gameResidentKb kB\nVmSwap:\t$gameSwapKb kB\n" else "",
|
||||
)
|
||||
if (group == game) File(dir, "maps").writeText("7f00000000-7f00001000 r-xp 00000000 fe:05 42 /usr/local/lib/libblsession.so\n")
|
||||
val taskDir = File(dir, "task")
|
||||
if (group == game && missingGameTasks) { taskDir.deleteRecursively(); continue }
|
||||
taskDir.mkdirs()
|
||||
@@ -375,5 +466,6 @@ class SessionSuspendControllerTest {
|
||||
const val GAME = 200
|
||||
const val STOP = 19
|
||||
const val CONT = 18
|
||||
const val URG = 23
|
||||
}
|
||||
}
|
||||
@@ -101,6 +101,28 @@ class SteamDownloadMonitorTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun aLongLogIsFollowedFromWhereTheLastPollStopped() {
|
||||
val root = Files.createTempDirectory("droiddeck-steam-download-").toFile()
|
||||
try {
|
||||
val contentLog = File(root, "root/.local/share/Steam/logs/content_log.txt").apply {
|
||||
check(parentFile?.mkdirs() != false)
|
||||
writeText(buildString {
|
||||
repeat(5_000) { append("[2026-10-06 14:40:00] Detected write gap 64 MB in file \"data_$it.dat\"\r\n") }
|
||||
append("[2026-10-06 14:44:17] AppID 44 App update changed : Running Update,Downloading,\r\n")
|
||||
})
|
||||
}
|
||||
val monitor = SteamDownloadMonitor()
|
||||
|
||||
assertTrue(monitor.poll(root, now = 1_000L))
|
||||
contentLog.appendText("[2026-10-06 14:45:03] AppID 44 App update changed : None\r\n")
|
||||
assertFalse(monitor.poll(root, now = 2_000L))
|
||||
contentLog.appendText("[2026-10-06 14:46:00] AppID 45 App update changed : Running Update,Downloading,\r\n")
|
||||
assertTrue(monitor.poll(root, now = 3_000L))
|
||||
} finally {
|
||||
root.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun theOtherClientsLogIsReadFromItsStart() {
|
||||
val root = Files.createTempDirectory("droiddeck-steam-download-").toFile()
|
||||
try {
|
||||
@@ -203,6 +225,38 @@ class SteamDownloadMonitorTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun theClientIsPendingUntilItIsInstalledAndStamped() {
|
||||
val root = Files.createTempDirectory("droiddeck-steam-client-").toFile()
|
||||
try {
|
||||
val steam = File(root, "root/.local/share/Steam")
|
||||
assertTrue(SteamDownloadMonitor.clientInstallPending(root))
|
||||
File(steam, "steamrtarm64").mkdirs()
|
||||
File(steam, "steamrtarm64/steam").writeText("client")
|
||||
assertTrue(SteamDownloadMonitor.clientInstallPending(root))
|
||||
File(steam, "package").mkdirs()
|
||||
File(steam, "package/droiddeck-installed").writeText("1791686101\n")
|
||||
assertFalse(SteamDownloadMonitor.clientInstallPending(root))
|
||||
} finally {
|
||||
root.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun anOlderStampCountsAndARepairRequestIsPending() {
|
||||
val root = Files.createTempDirectory("droiddeck-steam-client-").toFile()
|
||||
try {
|
||||
val steam = File(root, "root/.local/share/Steam")
|
||||
File(steam, "steamrtarm64").mkdirs()
|
||||
File(steam, "steamrtarm64/steam").writeText("client")
|
||||
File(steam, "package").mkdirs()
|
||||
File(steam, "package/bannerlator-installed").writeText("1\n")
|
||||
assertFalse(SteamDownloadMonitor.clientInstallPending(root))
|
||||
File(root, "root/.bl-steam-repair").writeText("1\n")
|
||||
assertTrue(SteamDownloadMonitor.clientInstallPending(root))
|
||||
} finally {
|
||||
root.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
private fun manifest(root: File, appId: String, downloaded: Long, total: Long, flags: Int): File {
|
||||
val file = File(root, "steamapps/appmanifest_$appId.acf")
|
||||
check(file.parentFile?.mkdirs() != false)
|
||||
|
||||
@@ -13,9 +13,33 @@ class SyncBackendTest {
|
||||
private val context: Context = RuntimeEnvironment.getApplication()
|
||||
|
||||
@Test
|
||||
fun aFreshInstallStartsOnEsync() {
|
||||
assertEquals(SessionPrefs.SYNC_ESYNC, SessionPrefs.syncBackend(context))
|
||||
fun aFreshInstallStartsOnNtsync() {
|
||||
assertEquals(SessionPrefs.SYNC_NTSYNC, SessionPrefs.syncBackend(context))
|
||||
assertEquals(false, SessionPrefs.fsyncFirst(context))
|
||||
SessionPrefs.applyNtsyncDefault(context)
|
||||
assertEquals(SessionPrefs.SYNC_NTSYNC, SessionPrefs.syncBackend(context))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anEarlierChoiceMovesToNtsyncOnce() {
|
||||
for (earlier in listOf(SessionPrefs.SYNC_ESYNC, SessionPrefs.SYNC_FSYNC, SessionPrefs.SYNC_WINESERVER)) {
|
||||
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
|
||||
SessionPrefs.setSyncBackend(context, earlier)
|
||||
SessionPrefs.applyNtsyncDefault(context)
|
||||
assertEquals(SessionPrefs.SYNC_NTSYNC, SessionPrefs.syncBackend(context))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aChoiceMadeAfterTheMoveIsKept() {
|
||||
SessionPrefs.setSyncBackend(context, SessionPrefs.SYNC_ESYNC)
|
||||
SessionPrefs.applyNtsyncDefault(context)
|
||||
SessionPrefs.setSyncBackend(context, SessionPrefs.SYNC_ESYNC)
|
||||
SessionPrefs.applyNtsyncDefault(context)
|
||||
assertEquals(SessionPrefs.SYNC_ESYNC, SessionPrefs.syncBackend(context))
|
||||
SessionPrefs.setSyncBackend(context, SessionPrefs.SYNC_WINESERVER)
|
||||
SessionPrefs.applyNtsyncDefault(context)
|
||||
assertEquals(SessionPrefs.SYNC_WINESERVER, SessionPrefs.syncBackend(context))
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -34,6 +58,7 @@ class SyncBackendTest {
|
||||
|
||||
@Test
|
||||
fun pickingATabTurnsSyncBackOn() {
|
||||
SessionPrefs.setFastSync(context, false)
|
||||
SessionPrefs.setSyncFallback(context, false)
|
||||
SessionPrefs.setFsyncFirst(context, false)
|
||||
assertEquals(SessionPrefs.SYNC_WINESERVER, SessionPrefs.syncBackend(context))
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.gpu.TpUbwcHint
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.util.ReflectionHelpers
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class TpUbwcPrefsTest {
|
||||
private val context: Context get() = RuntimeEnvironment.getApplication()
|
||||
|
||||
@Before fun reset() {
|
||||
ReflectionHelpers.setStaticField(TpUbwcHint::class.java, "resolved", false)
|
||||
ReflectionHelpers.setStaticField(TpUbwcHint::class.java, "cached", null)
|
||||
ReflectionHelpers.setStaticField(TpUbwcHint::class.java, "activeMode", null)
|
||||
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
|
||||
}
|
||||
|
||||
@Test fun missingOrInvalidChoiceUsesAuto() {
|
||||
assertEquals(SessionPrefs.TP_UBWC_AUTO, SessionPrefs.tpUbwcMode(context))
|
||||
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().putString("tpUbwcMode", "invalid").commit()
|
||||
assertEquals(SessionPrefs.TP_UBWC_AUTO, SessionPrefs.tpUbwcMode(context))
|
||||
}
|
||||
|
||||
@Test fun overrideIsStoredWithoutChangingDriverChoices() {
|
||||
SessionPrefs.setAndroidDriver(context, "display")
|
||||
SessionPrefs.setLinuxDriver(context, "runtime")
|
||||
for (mode in listOf(SessionPrefs.TP_UBWC_ON, SessionPrefs.TP_UBWC_OFF, SessionPrefs.TP_UBWC_AUTO)) {
|
||||
SessionPrefs.setTpUbwcMode(context, mode)
|
||||
assertEquals(mode, SessionPrefs.tpUbwcMode(context))
|
||||
assertEquals("display", SessionPrefs.androidDriver(context))
|
||||
assertEquals("runtime", SessionPrefs.linuxDriver(context))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun changingTheSavedChoiceKeepsTheProcessChoiceUntilRestart() {
|
||||
SessionPrefs.setTpUbwcMode(context, SessionPrefs.TP_UBWC_ON)
|
||||
val initial = TpUbwcHint.forThisDevice(context)
|
||||
SessionPrefs.setTpUbwcMode(context, SessionPrefs.TP_UBWC_OFF)
|
||||
assertTrue(TpUbwcHint.restartRequired(context))
|
||||
assertEquals(SessionPrefs.TP_UBWC_ON, TpUbwcHint.activeMode)
|
||||
assertEquals(initial, TpUbwcHint.forThisDevice(context))
|
||||
SessionPrefs.setTpUbwcMode(context, SessionPrefs.TP_UBWC_ON)
|
||||
assertFalse(TpUbwcHint.restartRequired(context))
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,14 @@ class WinComponentsSupportTest {
|
||||
step("install_msi", "url" to "$base/ps-x86.msi"), step("install_msi", "url" to "$base/ps-x64.msi"))))
|
||||
}
|
||||
|
||||
@Test fun builtInArm64RuntimeIsRegistryOnlyInBothViews() {
|
||||
val c = WinComponents.builtInArm64Runtime()
|
||||
assertEquals(Support.READY, support(c))
|
||||
assertEquals(12, c.steps.count { it.action == "set_register_key" })
|
||||
assertEquals(setOf("HKLM\\Software\\Microsoft\\VisualStudio\\14.0\\VC\\Runtimes\\arm64",
|
||||
"HKLM\\Software\\Wow6432Node\\Microsoft\\VisualStudio\\14.0\\VC\\Runtimes\\arm64"), c.steps.map { it.str("key") }.toSet())
|
||||
}
|
||||
|
||||
@Test fun installerWrappersInstallHere() {
|
||||
assertEquals(Support.READY, support(component("vcredist2022",
|
||||
step("install_exe", "url" to "$base/vcredist2022__VC_redist.x86.exe", "file_name" to "VC_redist.x86.exe"),
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class WineProcessesTest {
|
||||
private fun argv(vararg args: String) = args.joinToString("\u0000", postfix = "\u0000").toByteArray()
|
||||
|
||||
@Test fun aWineserverIsKnownByItsProgramOrItsName() {
|
||||
assertTrue(WineProcesses.isWineserver(argv("/root/.local/share/droiddeck-esync/dist/valve-11/files/bin-arm64/wineserver"), "wineserver\n"))
|
||||
assertTrue(WineProcesses.isWineserver(argv("wineserver", "-p0"), null))
|
||||
assertTrue(WineProcesses.isWineserver(null, "wineserver\n"))
|
||||
assertTrue(WineProcesses.isWineserver(ByteArray(0), "wineserver"))
|
||||
}
|
||||
|
||||
@Test fun nothingElseIs() {
|
||||
assertFalse(WineProcesses.isWineserver(argv("C:\\windows\\system32\\services.exe"), "services.exe\n"))
|
||||
assertFalse(WineProcesses.isWineserver(argv("/usr/bin/python3", "/x/files/bin-arm64/wineserver"), "python3\n"))
|
||||
assertFalse(WineProcesses.isWineserver(argv("/opt/wineserver-helper"), "wineserver-help"))
|
||||
assertFalse(WineProcesses.isWineserver(null, null))
|
||||
}
|
||||
}
|
||||
@@ -92,6 +92,30 @@ class SteamStorageTest {
|
||||
assertEquals(emptyMap<String, String>(), SteamStorage.compatMappings("\"x\" {}"))
|
||||
}
|
||||
|
||||
@Test fun readsShaderPrecacheFromConfig() {
|
||||
val vdf = """
|
||||
"InstallConfigStore"
|
||||
{
|
||||
"Software" { "Valve" { "Steam" { "ShaderCacheManager"
|
||||
{
|
||||
"HasCurrentBucket" "1"
|
||||
"DisableShaderCache" "1"
|
||||
} } } }
|
||||
}
|
||||
""".trimIndent()
|
||||
assertEquals(false, SteamStorage.shaderPrecache(vdf))
|
||||
assertEquals(true, SteamStorage.shaderPrecache(vdf.replace("\"DisableShaderCache\"\t\t\"1\"", "\"DisableShaderCache\"\t\t\"0\"")))
|
||||
assertEquals(true, SteamStorage.shaderPrecache("\"InstallConfigStore\" {}"))
|
||||
assertEquals(true, SteamStorage.shaderPrecache("""
|
||||
"InstallConfigStore"
|
||||
{
|
||||
// "DisableShaderCache" "1"
|
||||
"Other" { "DisableShaderCache" "1" }
|
||||
"Software" { "Valve" { "Steam" { "ShaderCacheManager" { "DisableShaderCache" "0" } } } }
|
||||
}
|
||||
""".trimIndent()))
|
||||
}
|
||||
|
||||
@Test fun readsCustomToolName() {
|
||||
val vdf = "\"compatibilitytools\"\n{\n \"compat_tools\"\n {\n \"GE-Proton11-9-aarch64\"\n {\n \"install_path\" \".\"\n }\n }\n}"
|
||||
assertEquals("GE-Proton11-9-aarch64", SteamStorage.compatToolName(vdf))
|
||||
|
||||
@@ -47,4 +47,34 @@ class CloudSavePathsTest {
|
||||
File(profile, "AppData/Local/My-Game").mkdirs()
|
||||
assertEquals(File(profile, "AppData/Local/My-Game").path, CloudSavePaths.epic("{AppData}/MyGame", prefix, install, "acc", "app")!!.path)
|
||||
}
|
||||
|
||||
@Test fun gogGalaxySdkEmptyLocationsUseDefaultLocation() {
|
||||
val loc = CloudSavePaths.gogSaveFromRemote(true, emptyList(), "1")!!
|
||||
assertEquals(
|
||||
"%LocalAppData%/GOG.com/Galaxy/Applications/1/Storage/Shared/Files",
|
||||
loc.template,
|
||||
)
|
||||
assertEquals(CloudSavePaths.GOG_DEFAULT_NAMESPACE, loc.name)
|
||||
val dir = CloudSavePaths.gog(loc.template, prefix, install)
|
||||
assertEquals(
|
||||
File(profile, "AppData/Local/GOG.com/Galaxy/Applications/1/Storage/Shared/Files").path,
|
||||
dir!!.path,
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun gogCloudDisabledOrUnknownClientIsNone() {
|
||||
assertNull(CloudSavePaths.gogSaveFromRemote(false, emptyList(), "1"))
|
||||
assertNull(CloudSavePaths.gogSaveFromRemote(true, emptyList(), ""))
|
||||
assertNull(CloudSavePaths.gogSaveFromRemote(true, listOf("saves" to ""), ""))
|
||||
}
|
||||
|
||||
@Test fun gogNamedLocationKeepsItsNameAndPreferSaves() {
|
||||
val loc = CloudSavePaths.gogSaveFromRemote(
|
||||
true,
|
||||
listOf("other" to "<?SAVED_GAMES?>/A", "Saves" to "<?APPLICATION_DATA_LOCAL_LOW?>/Hyperstrange/ELDERBORN"),
|
||||
"1",
|
||||
)!!
|
||||
assertEquals("<?APPLICATION_DATA_LOCAL_LOW?>/Hyperstrange/ELDERBORN", loc.template)
|
||||
assertEquals("Saves", loc.name)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.droiddeck.launcher.stores
|
||||
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class CloudSavesMigrationTest {
|
||||
private val dir = Files.createTempDirectory("cloud-migrate").toFile()
|
||||
private fun entry(bytes: ByteArray) = CloudPlan.Entry(CloudSaves.md5(bytes), null, 1000L)
|
||||
|
||||
private fun nested(name: String, path: String, text: String): File =
|
||||
File(dir, "$name/$path").apply { parentFile?.mkdirs(); writeText(text) }
|
||||
|
||||
@Test fun movesOnlyFilesTheOldBaselineOwns() {
|
||||
val a = "old save".toByteArray()
|
||||
val game = "game wrote this".toByteArray()
|
||||
nested("saves", "a.dat", String(a))
|
||||
nested("saves", "game.dat", String(game))
|
||||
val base = mapOf("saves/a.dat" to entry(a))
|
||||
val result = CloudSaves.migrateNested(dir, "saves", base)!!
|
||||
assertEquals(1, result.moved)
|
||||
assertEquals(0, result.cleaned)
|
||||
assertEquals(String(a), File(dir, "a.dat").readText())
|
||||
assertEquals(String(game), File(dir, "saves/game.dat").readText())
|
||||
assertTrue("saves/a.dat" !in result.baseline)
|
||||
assertEquals(entry(a), result.baseline["a.dat"])
|
||||
}
|
||||
|
||||
@Test fun anIdenticalLeftoverIsRemovedAndItsBaselineKeyRewritten() {
|
||||
val a = "old save".toByteArray()
|
||||
File(dir, "a.dat").writeText(String(a))
|
||||
nested("saves", "a.dat", String(a))
|
||||
val result = CloudSaves.migrateNested(dir, "saves", mapOf("saves/a.dat" to entry(a)))!!
|
||||
assertEquals(0, result.moved)
|
||||
assertEquals(1, result.cleaned)
|
||||
assertFalse(File(dir, "saves").exists())
|
||||
assertEquals(entry(a), result.baseline["a.dat"])
|
||||
assertTrue("saves/a.dat" !in result.baseline)
|
||||
}
|
||||
|
||||
@Test fun aDifferentDestinationKeepsTheGameFileAndTheBaseline() {
|
||||
val a = "old save".toByteArray()
|
||||
File(dir, "a.dat").writeText("newer game save")
|
||||
nested("saves", "a.dat", String(a))
|
||||
val base = mapOf("saves/a.dat" to entry(a))
|
||||
val result = CloudSaves.migrateNested(dir, "saves", base)!!
|
||||
assertEquals(0, result.moved)
|
||||
assertEquals(0, result.cleaned)
|
||||
assertEquals("newer game save", File(dir, "a.dat").readText())
|
||||
assertEquals(String(a), File(dir, "saves/a.dat").readText())
|
||||
assertEquals(base, result.baseline)
|
||||
}
|
||||
|
||||
@Test fun aSymlinkedAncestorIsNotMigrated() {
|
||||
val outside = Files.createTempDirectory("cloud-outside").toFile()
|
||||
File(outside, "a.dat").writeText("outside")
|
||||
File(dir, "saves").mkdirs()
|
||||
Files.createSymbolicLink(File(dir, "saves/link").toPath(), outside.toPath())
|
||||
val result = CloudSaves.migrateNested(dir, "saves",
|
||||
mapOf("saves/link/a.dat" to entry("outside".toByteArray())))!!
|
||||
assertEquals(0, result.moved)
|
||||
assertEquals(0, result.cleaned)
|
||||
assertTrue(File(outside, "a.dat").isFile)
|
||||
}
|
||||
|
||||
@Test fun aLocationNameThatCanLeaveTheFolderIsRefused() {
|
||||
nested("saves", "a.dat", "x")
|
||||
assertNull(CloudSaves.migrateNested(dir, "../saves", emptyMap()))
|
||||
assertNull(CloudSaves.migrateNested(dir, "..", emptyMap()))
|
||||
assertNull(CloudSaves.migrateNested(dir, "saves/..", emptyMap()))
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import java.io.File
|
||||
import java.util.concurrent.Executor
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
@@ -77,12 +78,22 @@ class CloudSavesTest {
|
||||
assertTrue(CloudSaves.dirty(app).contains(Store.GOG to gameId))
|
||||
CloudSaves.uploadAllDirty(app, "recovery", running = true)
|
||||
assertTrue(CloudSaves.dirty(app).contains(Store.GOG to gameId))
|
||||
com.droiddeck.launcher.stores.gog.GogPrefs.get(app).edit().putString("cloud_template_$gameId", "").apply()
|
||||
com.droiddeck.launcher.stores.gog.GogPrefs.get(app).edit()
|
||||
.putString("cloud_template_$gameId", "none")
|
||||
.putLong("cloud_template_at_$gameId", System.currentTimeMillis())
|
||||
.apply()
|
||||
assertEquals("no-cloud-saves", CloudSaves.uploadDirty(app, Store.GOG, gameId, "exit")!!.reason)
|
||||
assertTrue(CloudSaves.dirty(app).none { it.second == gameId })
|
||||
assertEquals(null, CloudSaves.uploadDirty(app, Store.GOG, gameId, "session-end"))
|
||||
}
|
||||
|
||||
@Test fun aNegativeCloudTemplateIsRetriedAfterADay() {
|
||||
val now = 1_000_000L
|
||||
assertTrue(CloudSaves.noneTemplateIsCurrent(now, now + 60_000L))
|
||||
assertFalse(CloudSaves.noneTemplateIsCurrent(now, now + CloudSaves.TEMPLATE_NONE_TTL_MS))
|
||||
assertFalse(CloudSaves.noneTemplateIsCurrent(0L, now))
|
||||
}
|
||||
|
||||
@Test fun aFirstLaunchWithoutAPrefixIsDeferredNotBlocked() {
|
||||
val deferred = ArrayList<Runnable>()
|
||||
val folder = File(StoreInstallRoot.storeDir(StoreInstallRoot.internalRoot(app), Store.GOG), "ELDERBORN").apply { mkdirs() }
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.droiddeck.launcher.stores
|
||||
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.util.zip.GZIPOutputStream
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class GogCloudKeysTest {
|
||||
@Test fun defaultLocationIsStrippedLikeAnyNamedLocation() {
|
||||
val files = listOf(CloudFile("__default/savegame0.sav", 1L), CloudFile("saves/slot0.sav", 2L))
|
||||
val (chosen, relative) = gogRelativeNames(files, "__default")
|
||||
assertEquals("__default", chosen)
|
||||
assertEquals(listOf("savegame0.sav"), relative.map { it.name })
|
||||
}
|
||||
|
||||
@Test fun gzipGogPutMatchesPythonGzipCompressLevel6Mtime0() {
|
||||
val raw = "savegame0".toByteArray()
|
||||
val expected = "1f8b08000000000000032b4e2c4b4d4fcc4d35000065fc333209000000".hex()
|
||||
assertArrayEquals(expected, gzipGogPut(raw))
|
||||
assertArrayEquals(raw, gunzip(expected))
|
||||
}
|
||||
|
||||
@Test fun contentEncodingGzipIsPeeledOnce() {
|
||||
val raw = "savegame0".toByteArray()
|
||||
val gz = ByteArrayOutputStream().also { GZIPOutputStream(it).use { z -> z.write(raw) } }.toByteArray()
|
||||
assertArrayEquals(raw, gogDecodeCloudBody(gz, "gzip"))
|
||||
assertArrayEquals(raw, gogDecodeCloudBody(raw, "gzip"))
|
||||
}
|
||||
|
||||
@Test fun corruptDeclaredGzipIsRejected() {
|
||||
val corrupt = gzipGogPut("savegame0".toByteArray()).dropLast(2).toByteArray()
|
||||
assertTrue(isGzip(corrupt))
|
||||
assertTrue(runCatching { gogDecodeCloudBody(corrupt, "gzip") }.isFailure)
|
||||
}
|
||||
|
||||
@Test fun isoDateHonorsOffsetAndFractionalSeconds() {
|
||||
val expected = java.time.Instant.parse("2024-01-02T01:04:05.123Z").toEpochMilli()
|
||||
assertEquals(expected, isoDate("2024-01-02T03:04:05.123+02:00"))
|
||||
assertEquals(expected, isoDate("2024-01-02T01:04:05.123"))
|
||||
}
|
||||
|
||||
@Test fun gogPutWrappedBodyWithoutEncodingIsPeeled() {
|
||||
val raw = "savegame0".toByteArray()
|
||||
assertArrayEquals(raw, gogDecodeCloudBody(gzipGogPut(raw), null))
|
||||
assertArrayEquals(raw, gogDecodeCloudBody(raw, null))
|
||||
}
|
||||
|
||||
@Test fun gzipThatIsTheSaveIsLeftIntact() {
|
||||
val raw = "savegame0".toByteArray()
|
||||
val gameGz = ByteArrayOutputStream().also { GZIPOutputStream(it).use { z -> z.write(raw) } }.toByteArray()
|
||||
assertTrue(isGzip(gameGz))
|
||||
assertFalse(gzipGogPut(raw).contentEquals(gameGz))
|
||||
assertArrayEquals(gameGz, gogDecodeCloudBody(gameGz, null))
|
||||
}
|
||||
}
|
||||
|
||||
private fun String.hex() = chunked(2).map { it.toInt(16).toByte() }.toByteArray()
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.droiddeck.launcher.stores
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class GogCloudNamesTest {
|
||||
private fun files(vararg names: String) = names.map { CloudFile(it, 1000L) }
|
||||
|
||||
@Test fun silksongLocationIsDroppedFromThePath() {
|
||||
val (location, mapped) = gogRelativeNames(
|
||||
files("saves/user1.dat", "saves/shared.dat", "saves/Restore_Points1/restoreData2.dat"), "saves")
|
||||
assertEquals("saves", location)
|
||||
assertEquals(listOf("user1.dat", "shared.dat", "Restore_Points1/restoreData2.dat"), mapped.map { it.name })
|
||||
}
|
||||
|
||||
@Test fun anotherLocationIsFilteredOut() {
|
||||
val (_, mapped) = gogRelativeNames(files("saves/a.dat", "__default/settings.ini"), "saves")
|
||||
assertEquals(listOf("a.dat"), mapped.map { it.name })
|
||||
}
|
||||
|
||||
@Test fun theOnlyLocationIsInferredWhenItsNameWasNotCached() {
|
||||
val (location, mapped) = gogRelativeNames(files("saves/a.dat", "saves/b.dat"), null)
|
||||
assertEquals("saves", location)
|
||||
assertEquals(listOf("a.dat", "b.dat"), mapped.map { it.name })
|
||||
}
|
||||
|
||||
@Test fun namesWithoutALocationPrefixAreLeftAlone() {
|
||||
val (location, mapped) = gogRelativeNames(files("a.dat", "b.dat"), null)
|
||||
assertNull(location)
|
||||
assertEquals(listOf("a.dat", "b.dat"), mapped.map { it.name })
|
||||
}
|
||||
|
||||
@Test fun aConfiguredLocationDoesNotYieldToAnotherLocation() {
|
||||
val (location, mapped) = gogRelativeNames(files("__default/settings.ini"), "saves")
|
||||
assertEquals("saves", location)
|
||||
assertTrue(mapped.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun aMixedListingWithOneSubfolderIsLeftAlone() {
|
||||
val (location, mapped) = gogRelativeNames(files("a.dat", "sub/b.dat"), "saves")
|
||||
assertNull(location)
|
||||
assertEquals(listOf("a.dat", "sub/b.dat"), mapped.map { it.name })
|
||||
}
|
||||
|
||||
@Test fun aMissingCachedLocationDoesNotHideUnprefixedNames() {
|
||||
val (location, mapped) = gogRelativeNames(files("a.dat"), "saves")
|
||||
assertNull(location)
|
||||
assertEquals(listOf("a.dat"), mapped.map { it.name })
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,13 @@ class SortCatalogItemsTest {
|
||||
private fun item(id: String, title: String, size: Long = 0, releaseDate: String = "") =
|
||||
CatalogItem(Store.GOG, id, title, imageUrl = null, sizeBytes = size, releaseDate = releaseDate, owned = true)
|
||||
|
||||
private fun sortCatalogItems(
|
||||
items: List<CatalogItem>, sort: String,
|
||||
lastPlayed: (CatalogItem) -> Long = { 0L }, installedAt: (CatalogItem) -> Long = { 0L },
|
||||
) = sortGames(items, sort, { it.title }, { it.releaseDate }, lastPlayed, installedAt, { it.sizeBytes })
|
||||
|
||||
private fun retainCatalogOrder(items: List<CatalogItem>, previous: List<CatalogItem>) = retainOrder(items, previous) { it.key }
|
||||
|
||||
@Test fun titleOrderIsCaseInsensitiveAndDescendingIsItsMirror() {
|
||||
val items = listOf(item("1", "Zelda"), item("2", "alpha"), item("3", "Beta"))
|
||||
assertEquals(listOf("alpha", "Beta", "Zelda"), sortCatalogItems(items, "titleAsc").map { it.title })
|
||||
|
||||
@@ -131,6 +131,25 @@ class StoreAccountsCipherTest {
|
||||
assertEquals("test@example.test", StoreAccounts.signedInAs(app, Store.XBOX))
|
||||
}
|
||||
|
||||
@Test fun xboxShowsTheGamertagElseAMaskedEmail() {
|
||||
StoreAccounts.write(app, Store.XBOX, JSONObject().put("username", "player@example.test"))
|
||||
assertEquals("p•••@example.test", StoreAccounts.displayName(app, Store.XBOX))
|
||||
StoreAccounts.write(app, Store.XBOX, JSONObject().put("username", "player@example.test").put("gamertag", "Some Gamertag"))
|
||||
assertEquals("Some Gamertag", StoreAccounts.displayName(app, Store.XBOX))
|
||||
assertEquals("player@example.test", StoreAccounts.signedInAs(app, Store.XBOX))
|
||||
StoreAccounts.write(app, Store.EPIC, creds)
|
||||
assertEquals("Someone", StoreAccounts.displayName(app, Store.EPIC))
|
||||
assertEquals("n•••", StoreAccounts.maskEmail("nickname"))
|
||||
}
|
||||
|
||||
@Test fun xboxDisplayNameDoesNotRevealEmailWhenCredentialsAreTemporarilyUnavailable() {
|
||||
StoreAccounts.write(app, Store.XBOX, JSONObject().put("username", "player@example.test"))
|
||||
StoreAccounts.keys = Flaky(key, 1) { java.security.ProviderException("busy") }
|
||||
assertEquals(Store.XBOX.label, StoreAccounts.displayName(app, Store.XBOX))
|
||||
assertTrue(StoreAccounts.isUnavailable(Store.XBOX))
|
||||
assertTrue(file(Store.XBOX).exists())
|
||||
}
|
||||
|
||||
@Test fun signOutRemovesTheFile() {
|
||||
StoreAccounts.write(app, Store.GOG, creds)
|
||||
StoreAccounts.clear(app, Store.GOG)
|
||||
@@ -182,4 +201,20 @@ class StoreAccountsCipherTest {
|
||||
assertFalse(StoreAccounts.isUnavailable(Store.AMAZON))
|
||||
assertFalse(file(Store.AMAZON).exists())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun teeEnvelopesUseTheCurrentKeyAndOlderOnesTheLegacyKey() {
|
||||
val legacy = SecretKeySpec(ByteArray(32) { 7 }, "AES")
|
||||
val keys = object : CredentialCipher.KeyProvider {
|
||||
override fun key(): SecretKey = key
|
||||
override fun legacy(): SecretKey = legacy
|
||||
override val version: Int get() = CredentialCipher.VERSION_TEE
|
||||
}
|
||||
val old = CredentialCipher.seal("old", CredentialCipher.KeyProvider { legacy })
|
||||
assertEquals(CredentialCipher.VERSION, old.getInt("v"))
|
||||
assertEquals("old", CredentialCipher.open(old, keys))
|
||||
val new = CredentialCipher.seal("new", keys)
|
||||
assertEquals(CredentialCipher.VERSION_TEE, new.getInt("v"))
|
||||
assertEquals("new", CredentialCipher.open(new, keys))
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,17 @@ class StoreGameSidecarTest {
|
||||
assertEquals("ns", back.extra["namespace"])
|
||||
}
|
||||
|
||||
@Test fun theStoreLogoRoundTripsAndOlderFilesHaveNone() {
|
||||
val withLogo = sample.copy(logo = "https://x/logo.png")
|
||||
val back = StoreGameSidecar.parse(withLogo.toJson().toString())!!
|
||||
assertEquals("https://x/logo.png", back.logo)
|
||||
assertEquals("https://x/logo.png", back.copy(state = StoreGameSidecar.STATE_UPDATING).logo)
|
||||
assertFalse(sample.toJson().has("logo"))
|
||||
assertNull(StoreGameSidecar.parse(sample.toJson().toString())!!.logo)
|
||||
assertNull(StoreGameSidecar.parse("""{"store":"gog","id":"1","title":"T","exe":"game.exe","cover":"c","hero":"h"}""")!!.logo)
|
||||
assertNull(StoreGameSidecar.parse("""{"store":"gog","id":"1","title":"T","exe":"game.exe","logo":""}""")!!.logo)
|
||||
}
|
||||
|
||||
@Test fun defaultsWhenFieldsAreAbsent() {
|
||||
val back = StoreGameSidecar.parse("""{"store":"gog","id":"1","title":"T","exe":"bin\\game.exe","addToSteam":false}""")!!
|
||||
assertEquals("bin/game.exe", back.exe)
|
||||
|
||||
@@ -5,7 +5,10 @@ import com.droiddeck.launcher.session.SessionPrefs
|
||||
import java.io.File
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
@@ -18,6 +21,12 @@ import org.robolectric.shadows.ShadowStatFs
|
||||
class StoreInstallRootTest {
|
||||
private val app get() = RuntimeEnvironment.getApplication()
|
||||
|
||||
@Before fun resetStoragePreferences() {
|
||||
SessionPrefs.setDefaultStorageFolder(app, "", "")
|
||||
SessionPrefs.setDefaultStorage(app, SessionPrefs.DEFAULT_STORAGE_ASK)
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
}
|
||||
|
||||
@Test fun theDefaultRootIsInternalWhateverTheSteamLibrarySettingSays() {
|
||||
val card = File(app.filesDir, "fake-card/steam").apply { mkdirs() }
|
||||
SessionPrefs.setGameStorage(app, card.path, "Card")
|
||||
@@ -26,6 +35,72 @@ class StoreInstallRootTest {
|
||||
assertFalse(StoreInstallRoot.targets(app).first().removable)
|
||||
}
|
||||
|
||||
@Test fun defaultStoragePicksTheInternalOrTheConfiguredExternalTarget() {
|
||||
val library = File(app.filesDir, "default-card/steam").apply { mkdirs() }
|
||||
SessionPrefs.setGameStorage(app, library.path, "Card")
|
||||
val external = File(library, "Games")
|
||||
|
||||
SessionPrefs.setDefaultStorage(app, SessionPrefs.DEFAULT_STORAGE_INTERNAL)
|
||||
assertEquals(StoreInstallRoot.internalRoot(app).absolutePath, StoreInstallRoot.defaultTarget(app)?.root?.absolutePath)
|
||||
|
||||
SessionPrefs.setDefaultStorage(app, SessionPrefs.DEFAULT_STORAGE_EXTERNAL)
|
||||
assertEquals(external.absolutePath, StoreInstallRoot.defaultTarget(app)?.root?.absolutePath)
|
||||
|
||||
SessionPrefs.setDefaultStorage(app, SessionPrefs.DEFAULT_STORAGE_ASK)
|
||||
assertNull(StoreInstallRoot.defaultTarget(app))
|
||||
|
||||
SessionPrefs.setDefaultStorage(app, "bogus")
|
||||
assertEquals(SessionPrefs.DEFAULT_STORAGE_ASK, SessionPrefs.defaultStorage(app))
|
||||
}
|
||||
|
||||
@Test fun defaultExternalStorageFallsBackToTheInstallDialogWhenNoCardIsPresent() {
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
SessionPrefs.setDefaultStorage(app, SessionPrefs.DEFAULT_STORAGE_EXTERNAL)
|
||||
assertNull(StoreInstallRoot.defaultTarget(app))
|
||||
}
|
||||
|
||||
@Test fun aChosenFolderIsUsedForDefaultExternalStorage() {
|
||||
val folder = File(app.filesDir, "usb/SSD").apply { mkdirs() }
|
||||
assertNull(StoreInstallRoot.prepareDefaultFolder(app, folder))
|
||||
val root = File(folder, "Games")
|
||||
assertTrue(root.isDirectory)
|
||||
SessionPrefs.setDefaultStorageFolder(app, folder.path, "SSD")
|
||||
SessionPrefs.setDefaultStorage(app, SessionPrefs.DEFAULT_STORAGE_EXTERNAL)
|
||||
|
||||
assertEquals(root.absolutePath, StoreInstallRoot.defaultTarget(app)?.root?.absolutePath)
|
||||
assertTrue(StoreInstallRoot.targets(app).any { it.root.absolutePath == root.absolutePath && it.folder })
|
||||
assertTrue(StoreInstallRoot.roots(app).any { it.absolutePath == root.absolutePath })
|
||||
assertTrue(StoreInstallRoot.externalRoots(app).any { it.first.absolutePath == root.absolutePath })
|
||||
assertFalse(File(root, ".droiddeck-write-probe").exists())
|
||||
}
|
||||
|
||||
@Test fun aDisconnectedChosenFolderDoesNotFallBackToAnotherTarget() {
|
||||
val card = File(app.filesDir, "card/steam").apply { mkdirs() }
|
||||
SessionPrefs.setGameStorage(app, card.path, "Card")
|
||||
val folder = File(app.filesDir, "usb/SSD").apply { mkdirs() }
|
||||
SessionPrefs.setDefaultStorageFolder(app, folder.path, "SSD")
|
||||
SessionPrefs.setDefaultStorage(app, SessionPrefs.DEFAULT_STORAGE_EXTERNAL)
|
||||
assertNotNull(StoreInstallRoot.defaultTarget(app))
|
||||
|
||||
assertTrue(folder.delete())
|
||||
assertNull(StoreInstallRoot.defaultTarget(app))
|
||||
assertEquals(File(card, "Games").absolutePath, StoreInstallRoot.detectedExternalTarget(app)?.root?.absolutePath)
|
||||
}
|
||||
|
||||
@Test fun filesOnAChosenFolderAreMappedIntoTheGuest() {
|
||||
val folder = File(app.filesDir, "usb/SSD").apply { mkdirs() }
|
||||
SessionPrefs.setDefaultStorageFolder(app, folder.path, "SSD")
|
||||
val game = File(folder, "Games/GOG/Test/game.exe").apply {
|
||||
parentFile?.mkdirs()
|
||||
writeText("MZ")
|
||||
}
|
||||
|
||||
val guest = StoreInstallRoot.externalGuestPath(app, game)
|
||||
assertNotNull(guest)
|
||||
assertTrue(guest!!.startsWith(StoreInstallRoot.GUEST_EXTERNAL + "/"))
|
||||
assertTrue(guest.endsWith("/GOG/Test/game.exe"))
|
||||
}
|
||||
|
||||
@Test fun theSteamLibraryFolderIsOfferedAsAnInstallTarget() {
|
||||
val library = File(app.filesDir, "Documents/Games").apply { mkdirs() }
|
||||
SessionPrefs.setGameStorage(app, library.path, "Games")
|
||||
@@ -38,6 +113,43 @@ class StoreInstallRootTest {
|
||||
assertEquals(1, StoreInstallRoot.targets(app).size)
|
||||
}
|
||||
|
||||
@Test fun externalStoreInstallPathsMapIntoTheirGuestMountWithoutPrefixCollisions() {
|
||||
val cardRoot = File(app.filesDir, "card/Games").apply { mkdirs() }
|
||||
val guestRoot = "/mnt/droiddeck-stores/card"
|
||||
val roots = listOf(cardRoot to guestRoot)
|
||||
|
||||
assertEquals("$guestRoot/Stores/Xbox/Doom", StoreInstallRoot.externalGuestPath(
|
||||
File(cardRoot, "Stores/Xbox/Doom"), roots))
|
||||
assertEquals(null, StoreInstallRoot.externalGuestPath(
|
||||
File(cardRoot.parentFile, "Games-old/Stores/Xbox/Doom"), roots))
|
||||
}
|
||||
|
||||
@Test fun xodusMapsTheSelectedSteamLibraryOnAnExternalVolume() {
|
||||
val library = File(app.filesDir, "card/steam").apply { mkdirs() }
|
||||
val storeRoot = File(library, "Games").apply { mkdirs() }
|
||||
SessionPrefs.setGameStorage(app, library.path, "Card")
|
||||
|
||||
val xodusRoot = StoreInstallRoot.externalRootsForXodus(app).single { it.first.absolutePath == storeRoot.absolutePath }
|
||||
val gameFolder = File(storeRoot, "Xbox/Doom")
|
||||
assertEquals("${xodusRoot.second}/Xbox/Doom", StoreInstallRoot.guestPathForXodus(app, gameFolder))
|
||||
|
||||
val bindSpecs = StoreInstallRoot.externalBindSpecsForXodus(app)
|
||||
assertTrue(bindSpecs.contains("${storeRoot.path}:${xodusRoot.second}"))
|
||||
assertTrue(File(LinuxRuntime.rootDir(app), xodusRoot.second.removePrefix("/")).isDirectory)
|
||||
}
|
||||
|
||||
@Test fun externalStoreBindsCreateGuestTargetsAndSkipUnavailableVolumes() {
|
||||
val host = File(app.filesDir, "card/Games").apply { mkdirs() }
|
||||
val guestRoot = "/mnt/droiddeck-stores/card"
|
||||
val guestFs = File(app.filesDir, "linuxfs").apply { mkdirs() }
|
||||
val missing = File(app.filesDir, "missing/Games")
|
||||
|
||||
assertEquals(listOf("${host.path}:$guestRoot"), StoreInstallRoot.externalBindSpecs(
|
||||
listOf(host to guestRoot, missing to "/mnt/droiddeck-stores/missing"), guestFs))
|
||||
assertTrue(File(guestFs, "mnt/droiddeck-stores/card").isDirectory)
|
||||
assertFalse(File(guestFs, "mnt/droiddeck-stores/missing").exists())
|
||||
}
|
||||
|
||||
@Test fun anExistingInstallWinsOverAFreshFolderUnderTheChosenRoot() {
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
val existing = File(StoreInstallRoot.storeDir(StoreInstallRoot.internalRoot(app), Store.GOG), "Old Name").apply { mkdirs() }
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.droiddeck.launcher.stores
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.Color
|
||||
import com.droiddeck.launcher.stores.amazon.AmazonLibrary
|
||||
import com.droiddeck.launcher.stores.gog.GogBackend
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.File
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
class StoreLogoTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
private fun encoded(format: Bitmap.CompressFormat): ByteArray {
|
||||
val bmp = Bitmap.createBitmap(8, 4, Bitmap.Config.ARGB_8888)
|
||||
bmp.eraseColor(Color.TRANSPARENT)
|
||||
bmp.setPixel(1, 1, Color.RED)
|
||||
return ByteArrayOutputStream().also { bmp.compress(format, 100, it) }.toByteArray()
|
||||
}
|
||||
|
||||
@Test fun aPngLogoIsKeptAsItCameWithItsTransparency() {
|
||||
val png = encoded(Bitmap.CompressFormat.PNG)
|
||||
val dst = File(tmp.root, StoreArt.LOGO)
|
||||
assertTrue(StoreArt.writeLogo(png, dst))
|
||||
assertArrayEquals(png, dst.readBytes())
|
||||
val back = BitmapFactory.decodeFile(dst.path)
|
||||
assertEquals(0, Color.alpha(back.getPixel(0, 0)))
|
||||
assertEquals(Color.RED, back.getPixel(1, 1))
|
||||
assertFalse(File(dst.path + ".tmp").exists())
|
||||
}
|
||||
|
||||
@Test fun anotherImageFormatIsStoredAsPng() {
|
||||
val dst = File(tmp.root, StoreArt.LOGO)
|
||||
assertTrue(StoreArt.writeLogo(encoded(Bitmap.CompressFormat.JPEG), dst))
|
||||
val head = dst.readBytes().take(4)
|
||||
assertEquals(listOf(0x89.toByte(), 'P'.code.toByte(), 'N'.code.toByte(), 'G'.code.toByte()), head)
|
||||
assertEquals(8, BitmapFactory.decodeFile(dst.path).width)
|
||||
}
|
||||
|
||||
@Test fun whatIsNotAnImageIsRefusedAndAnExistingLogoStays() {
|
||||
val dst = File(tmp.root, StoreArt.LOGO)
|
||||
assertFalse(StoreArt.writeLogo("<html>not found</html>".toByteArray(), dst))
|
||||
assertFalse(dst.exists())
|
||||
dst.writeBytes(byteArrayOf(1, 2, 3))
|
||||
assertTrue(StoreArt.writeLogo(encoded(Bitmap.CompressFormat.PNG), dst))
|
||||
assertArrayEquals(byteArrayOf(1, 2, 3), dst.readBytes())
|
||||
assertTrue(StoreArt.fetchLogo(tmp.root, "https://invalid.example/logo.png"))
|
||||
}
|
||||
|
||||
@Test fun gogTakesTheV2LogoLinkOnly() {
|
||||
val v2 = JSONObject("""{"_links":{"logo":{"href":"https://images.gog-statics.com/abc_logo.png"},"galaxyBackgroundImage":{"href":"https://x/bg.jpg"}}}""")
|
||||
assertEquals("https://images.gog-statics.com/abc_logo.png", GogBackend.logoOf(v2))
|
||||
assertEquals("https://images.gog-statics.com/rel.png", GogBackend.logoOf(JSONObject("""{"_links":{"logo":{"href":"//images.gog-statics.com/rel.png"}}}""")))
|
||||
assertNull(GogBackend.logoOf(JSONObject("""{"_links":{}}""")))
|
||||
assertNull(GogBackend.logoOf(JSONObject("""{"images":{"logo2x":"https://x/glx_logo_2x.jpg"}}""")))
|
||||
assertNull(GogBackend.logoOf(JSONObject("""{"_links":{"logo":{"href":"http://x/logo.png"}}}""")))
|
||||
}
|
||||
|
||||
@Test fun amazonKeepsTheLogoFromTheLibraryAndItsCache() {
|
||||
val app = RuntimeEnvironment.getApplication()
|
||||
val fresh = AmazonLibrary.gameFrom(JSONObject().put("productId", "p").put("title", "Game").put("logo", "https://m/logo.png"), null)
|
||||
assertEquals("https://m/logo.png", fresh.logoUrl)
|
||||
assertEquals("https://m/logo.png", AmazonLibrary.toCatalogItem(app, fresh).logoUrl)
|
||||
assertEquals(listOf(fresh), AmazonLibrary.fromCacheJson(AmazonLibrary.toCacheJson(listOf(fresh))))
|
||||
val kept = AmazonLibrary.gameFrom(JSONObject().put("productId", "p").put("title", "Game"), fresh)
|
||||
assertEquals("https://m/logo.png", kept.logoUrl)
|
||||
val none = AmazonLibrary.gameFrom(JSONObject().put("productId", "q").put("title", "Other"), null)
|
||||
assertNull(AmazonLibrary.toCatalogItem(app, none).logoUrl)
|
||||
assertEquals("", AmazonLibrary.fromCacheJson("""[{"productId":"old","title":"Old"}]""").single().logoUrl)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.droiddeck.launcher.stores.battlenet
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
|
||||
class BattleNetRequestTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
@Test fun requestsLeftBeforeThePollAreAllKeptInOrder() {
|
||||
val root = tmp.root
|
||||
assertTrue(BattleNetClient.request(root, listOf("install-game", "wow")))
|
||||
assertTrue(BattleNetClient.request(root, listOf("install-game", "fenris")))
|
||||
assertTrue(BattleNetClient.request(root, listOf("launch", "OSI")))
|
||||
val names = root.list()!!.sorted()
|
||||
assertEquals(3, names.size)
|
||||
assertTrue(names.all { Regex("battlenet-request\\.\\d{20}").matches(it) })
|
||||
assertEquals(listOf("install-game\nwow\n", "install-game\nfenris\n", "launch\nOSI\n"), names.map { java.io.File(root, it).readText() })
|
||||
}
|
||||
|
||||
@Test fun aLineBreakInAnArgumentIsRefused() {
|
||||
assertFalse(BattleNetClient.request(tmp.root, listOf("launch", "OSI\nreboot")))
|
||||
assertEquals(0, tmp.root.list()!!.size)
|
||||
}
|
||||
|
||||
@Test fun aNewSessionClearsEveryLeftRequest() {
|
||||
val root = tmp.root
|
||||
BattleNetClient.request(root, listOf("launch", "WTCG"))
|
||||
java.io.File(root, "battlenet-request").writeText("launch\nPro\n")
|
||||
java.io.File(root, "battlenet-request.1.tmp").writeText("launch\nPro\n")
|
||||
java.io.File(root, "battlenet-fex.request").writeText("x")
|
||||
BattleNetClient.clearRequests(root)
|
||||
assertEquals(listOf("battlenet-fex.request"), root.list()!!.toList())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.droiddeck.launcher.stores.battlenet
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
class BlizzardArtTest {
|
||||
@Test fun theShopsKeyArtIsUsed() {
|
||||
val page = """<meta property="og:image" content="https://blz-contentstack-images.akamaized.net/v3/assets/a/b/c/art.png">"""
|
||||
assertEquals("https://blz-contentstack-images.akamaized.net/v3/assets/a/b/c/art.png", BlizzardArt.imageUrl(page))
|
||||
}
|
||||
|
||||
@Test fun aVideoStillFallsBackToTheFirstThumbnailThatIsNotABundle() {
|
||||
val page = """<meta property="og:image" content="https://img.youtube.com/vi/x/maxresdefault.jpg">""" +
|
||||
"""\"imageUrl\":\"//catalog.blzstatic.com//ff9/a-prod-thumb_bundle.jpg\",""" +
|
||||
"""\"imageUrl\":\"//catalog.blzstatic.com//feb/b-prod-thumb.jpg\""""
|
||||
assertEquals("https://catalog.blzstatic.com//feb/b-prod-thumb.jpg", BlizzardArt.imageUrl(page))
|
||||
}
|
||||
|
||||
@Test fun anOpenGraphImageFromAnotherHostFallsBackToTheThumbnail() {
|
||||
val page = """<meta property="og:image" content="https://example.com/art.png">""" +
|
||||
"""\"imageUrl\":\"//catalog.blzstatic.com//feb/b-prod-thumb.jpg\""""
|
||||
assertEquals("https://catalog.blzstatic.com//feb/b-prod-thumb.jpg", BlizzardArt.imageUrl(page))
|
||||
}
|
||||
|
||||
@Test fun artFromOtherHostsIsRefused() {
|
||||
assertNull(BlizzardArt.imageUrl("""<meta property="og:image" content="https://example.com/art.png">"""))
|
||||
assertNull(BlizzardArt.imageUrl("""\"imageUrl\":\"//catalog.blzstatic.com//ff9/a-prod-thumb_bundle.jpg\""""))
|
||||
}
|
||||
}
|
||||
@@ -16,17 +16,6 @@ import java.security.MessageDigest
|
||||
class EpicClientTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
private fun game(appId: Int, source: String) =
|
||||
com.droiddeck.launcher.frontend.Library.SteamGame(appId, "g$appId", null, "internal", source = source)
|
||||
|
||||
@Test fun theLauncherSitsRightAboveTheFirstEpicGame() {
|
||||
val launcher = game(EpicClient.LAUNCHER_APP_ID, "epic")
|
||||
val games = listOf(game(1, "steam"), game(2, "epic"), game(3, "steam"), game(4, "epic"))
|
||||
assertEquals(listOf(1, 0, 2, 3, 4), EpicClient.withLauncher(games, launcher).map { it.appId })
|
||||
assertEquals(listOf(1, 3, 0), EpicClient.withLauncher(listOf(games[0], games[2]), launcher).map { it.appId })
|
||||
assertEquals(listOf(1, 2), EpicClient.withLauncher(games.take(2), null).map { it.appId })
|
||||
}
|
||||
|
||||
private fun added(name: String, source: String, storeId: String?) =
|
||||
com.droiddeck.launcher.frontend.AddedGames.Game(File(tmp.root, name), name, File(tmp.root, "$name/$name.exe"),
|
||||
"/root/Games/$name/$name.exe", "/root/Games/$name", 3_000_000_000L, 0L, emptyList(), source = source, storeId = storeId)
|
||||
@@ -285,6 +274,28 @@ class EpicClientTest {
|
||||
assertTrue(EpicClient.loopback("http://localhost:5/launcher/authorized?code=1"))
|
||||
}
|
||||
|
||||
@Test fun theManifestLaunchCommandJoinsTheGameArguments() {
|
||||
val store = com.droiddeck.launcher.stores.Store.EPIC
|
||||
val epicArgs = listOf("-EpicPortal", "-epicapp=Fig", "-epicenv=Prod")
|
||||
val installed = com.droiddeck.launcher.stores.StoreGameSidecar(store, "Fig", "Fig Game", exe = "Fig.exe", args = epicArgs)
|
||||
val first = EpicClientLibrary.withLaunchArgs(installed, listOf("-PCStore=EGS"))
|
||||
assertEquals(epicArgs + "-PCStore=EGS", first.args)
|
||||
assertTrue(EpicClientLibrary.withLaunchArgs(first, listOf("-PCStore=EGS")) === first)
|
||||
val updated = EpicClientLibrary.withLaunchArgs(first, listOf("-PCStore=EGS", "-log=a b.txt"))
|
||||
assertEquals(epicArgs + listOf("-PCStore=EGS", "-log=a b.txt"), updated.args)
|
||||
val dropped = EpicClientLibrary.withLaunchArgs(updated, emptyList())
|
||||
assertEquals(epicArgs, dropped.args)
|
||||
assertFalse(dropped.extra.containsKey("launchArgs"))
|
||||
val reinstalled = first.copy(args = epicArgs)
|
||||
assertEquals(epicArgs + "-PCStore=EGS", EpicClientLibrary.withLaunchArgs(reinstalled, listOf("-PCStore=EGS")).args)
|
||||
assertTrue(EpicClientLibrary.withLaunchArgs(installed, emptyList()) === installed)
|
||||
val own = installed.copy(args = epicArgs + "-PCStore=EGS")
|
||||
assertTrue(EpicClientLibrary.withLaunchArgs(own, listOf("-PCStore=EGS")) === own)
|
||||
val ownUpdated = EpicClientLibrary.withLaunchArgs(own, listOf("-PCStore=EGS", "-log=a b.txt"))
|
||||
assertEquals(epicArgs + listOf("-PCStore=EGS", "-log=a b.txt"), ownUpdated.args)
|
||||
assertEquals(epicArgs + "-PCStore=EGS", EpicClientLibrary.withLaunchArgs(ownUpdated, emptyList()).args)
|
||||
}
|
||||
|
||||
@Test fun itemsDescribeTheInstallForTheLauncher() {
|
||||
val install = EpicClientLibrary.Install(
|
||||
"Fig", "ns1", "item1", "Fig Game", "1.0.5", "Binaries/Win64/Fig.exe", "/root/Games/Stores/Epic/Fig Game",
|
||||
@@ -445,4 +456,26 @@ class EpicClientTest {
|
||||
settings.writeText("""{"defaultInstallDir":"/mnt/droiddeck-sd/Stores/Epic"}""")
|
||||
assertEquals("/root/Games/Stores/Epic", EpicClient.prepareInstallDir(context))
|
||||
}
|
||||
|
||||
@Test fun aDisconnectedDefaultFolderKeepsTheLauncherInstallDir() {
|
||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
val previousStorage = com.droiddeck.launcher.session.SessionPrefs.defaultStorage(context)
|
||||
val previousFolder = com.droiddeck.launcher.session.SessionPrefs.defaultStorageFolder(context)
|
||||
val previousLabel = com.droiddeck.launcher.session.SessionPrefs.defaultStorageFolderLabel(context)
|
||||
val settings = File(EpicClient.dataDir(context), "settings/app-settings.json").apply { parentFile!!.mkdirs() }
|
||||
val current = "/mnt/droiddeck-stores/1234/Epic"
|
||||
settings.writeText("""{"defaultInstallDir":"$current"}""")
|
||||
com.droiddeck.launcher.session.SessionPrefs.setDefaultStorage(
|
||||
context, com.droiddeck.launcher.session.SessionPrefs.DEFAULT_STORAGE_EXTERNAL)
|
||||
com.droiddeck.launcher.session.SessionPrefs.setDefaultStorageFolder(
|
||||
context, File(context.filesDir, "missing-${System.nanoTime()}").path, "SSD")
|
||||
try {
|
||||
assertEquals(current, EpicClient.prepareInstallDir(context))
|
||||
assertEquals(current, org.json.JSONObject(settings.readText()).getString("defaultInstallDir"))
|
||||
} finally {
|
||||
com.droiddeck.launcher.session.SessionPrefs.setDefaultStorage(context, previousStorage)
|
||||
if (previousFolder.isBlank()) com.droiddeck.launcher.session.SessionPrefs.clearDefaultStorageFolder(context)
|
||||
else com.droiddeck.launcher.session.SessionPrefs.setDefaultStorageFolder(context, previousFolder, previousLabel)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -83,6 +83,18 @@ class EpicLibraryTest {
|
||||
assertEquals("Fig", EpicLibrary.gameFrom(record, null, null).title)
|
||||
}
|
||||
|
||||
@Test fun theCatalogLogoIsKeptInTheCacheAndHandedToTheInstall() {
|
||||
val record = JSONObject().put("appName", "Fig").put("namespace", "ns").put("catalogItemId", "cat")
|
||||
val fresh = EpicLibrary.gameFrom(record, JSONObject().put("logo", "https://e/logo.png"), null)
|
||||
assertEquals("https://e/logo.png", fresh.artLogo)
|
||||
assertEquals("https://e/logo.png", EpicLibrary.gameFrom(record, JSONObject().put("title", "Fig"), fresh).artLogo)
|
||||
assertEquals(listOf(fresh), EpicLibrary.fromCacheJson(EpicLibrary.toCacheJson(listOf(fresh))))
|
||||
assertEquals("https://e/logo.png", EpicLibrary.toCatalogItem(app, fresh).logoUrl)
|
||||
val plain = EpicGame("Old", "ns", "c", "Old")
|
||||
assertFalse(JSONArray(EpicLibrary.toCacheJson(listOf(plain))).getJSONObject(0).has("artLogo"))
|
||||
assertEquals(null, EpicLibrary.toCatalogItem(app, plain).logoUrl)
|
||||
}
|
||||
|
||||
@Test fun signOutForgetsOnlyTheLibrary() {
|
||||
EpicPrefs.get(app).edit().putString(EpicLibrary.KEY_CACHE, "[]").putLong(EpicLibrary.KEY_SYNCED_AT, 1L)
|
||||
.putString("cloud_template_Fig", "{AppData}/x").commit()
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.droiddeck.launcher.stores.gog
|
||||
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.nio.file.Files
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
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
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class GogInstallerPartsTest {
|
||||
private fun downloads(json: String) = JSONObject("""{"downloads":$json}""").getJSONObject("downloads")
|
||||
|
||||
@Test fun everyFileOfTheWindowsInstallerIsKeptAndThePartsAreNamedAfterItsSetup() {
|
||||
val parts = GogDownloadManager.installerParts(
|
||||
downloads(
|
||||
"""{"installers":[
|
||||
{"os":"windows","language":"en","files":[
|
||||
{"id":"en1installer0","size":1048576,"downlink":"https://api.gog.com/products/1947927225/downlink/installer/en1installer0"},
|
||||
{"id":"en1installer1","size":3786407936,"downlink":"https://api.gog.com/products/1947927225/downlink/installer/en1installer1"}
|
||||
]},
|
||||
{"os":"linux","files":[{"downlink":"https://example.invalid/linux"}]}
|
||||
]}""",
|
||||
),
|
||||
"1947927225",
|
||||
)
|
||||
assertEquals(listOf("setup_1947927225.exe", "setup_1947927225-1.bin"), parts.map { it.filename })
|
||||
assertEquals(listOf(1048576L, 3786407936L), parts.map { it.size })
|
||||
assertTrue(parts[1].url.endsWith("en1installer1"))
|
||||
}
|
||||
|
||||
@Test fun explicitNamesAreKeptAndUnnamedPartsFollowTheFirstSetupExe() {
|
||||
val parts = GogDownloadManager.installerParts(
|
||||
downloads(
|
||||
"""{"installers":[{"os":"windows","files":[
|
||||
{"filename":"setup_witcher_2.1.0.exe","downlink":"https://example.invalid/setup"},
|
||||
{"downlink":"https://example.invalid/data"},
|
||||
{"filename":"readme.bin","downlink":"https://example.invalid/readme"}
|
||||
]}]}""",
|
||||
),
|
||||
"1207658924",
|
||||
)
|
||||
assertEquals(listOf("setup_witcher_2.1.0.exe", "setup_witcher_2.1.0-1.bin", "readme.bin"), parts.map { it.filename })
|
||||
}
|
||||
|
||||
@Test fun aSingleManualInstallerIsNamedForTheGameAndSanitised() {
|
||||
val parts = GogDownloadManager.installerParts(
|
||||
downloads("""{"installers":[{"os":"windows","manualUrl":"https://example.invalid/setup","total_size":42}]}"""),
|
||||
"../game id",
|
||||
)
|
||||
assertEquals(1, parts.size)
|
||||
assertEquals("setup_.._game_id.exe", parts[0].filename)
|
||||
assertEquals(42L, parts[0].size)
|
||||
}
|
||||
|
||||
@Test fun installerPartsStayInsideTheGameFolder() {
|
||||
val root = kotlin.io.path.createTempDirectory("gog-installer").toFile()
|
||||
try {
|
||||
assertEquals(
|
||||
File(root, "setup_1.exe").canonicalFile,
|
||||
GogDownloadManager.installerDestination(root, "setup_1.exe"),
|
||||
)
|
||||
assertThrows(IOException::class.java) {
|
||||
GogDownloadManager.installerDestination(root, "../outside.exe")
|
||||
}
|
||||
val outside = File(root.parentFile, "outside-${System.nanoTime()}.bin").apply { writeText("x") }
|
||||
try {
|
||||
Files.createSymbolicLink(File(root, "setup_1-1.bin").toPath(), outside.toPath())
|
||||
assertThrows(IOException::class.java) {
|
||||
GogDownloadManager.installerDestination(root, "setup_1-1.bin")
|
||||
}
|
||||
} finally {
|
||||
outside.delete()
|
||||
}
|
||||
} finally {
|
||||
root.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun anotherPlatformOrNoDownloadsAddsNothing() {
|
||||
assertEquals(0, GogDownloadManager.installerParts(downloads("""{"installers":[{"os":"linux","manualUrl":"https://example.invalid/x"}]}"""), "1").size)
|
||||
assertEquals(0, GogDownloadManager.installerParts(downloads("{}"), "1").size)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.droiddeck.launcher.stores.itch
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ItchBrowseTest {
|
||||
private fun path(sort: String = ItchBrowse.SORT_POPULAR, price: String = ItchBrowse.PRICE_ANY, platforms: Set<String> = emptySet(), tags: List<String> = emptyList()) =
|
||||
ItchBrowse.path(BrowseQuery(sort, price, platforms, tags))
|
||||
|
||||
@Test fun theDefaultQueryIsTheFrontPage() {
|
||||
assertTrue(BrowseQuery().isDefault)
|
||||
assertFalse(BrowseQuery(sort = ItchBrowse.SORT_NEWEST).isDefault)
|
||||
assertFalse(BrowseQuery(price = ItchBrowse.PRICE_FREE).isDefault)
|
||||
}
|
||||
|
||||
@Test fun sortsUseItchsOwnPaths() {
|
||||
assertEquals("https://itch.io/games", path())
|
||||
assertEquals("https://itch.io/games/new-and-popular", path(sort = ItchBrowse.SORT_NEW_POPULAR))
|
||||
assertEquals("https://itch.io/games/top-sellers", path(sort = ItchBrowse.SORT_TOP_SELLERS))
|
||||
assertEquals("https://itch.io/games/top-rated", path(sort = ItchBrowse.SORT_TOP_RATED))
|
||||
assertEquals("https://itch.io/games/newest", path(sort = ItchBrowse.SORT_NEWEST))
|
||||
}
|
||||
|
||||
@Test fun pricesUseItchsOwnPaths() {
|
||||
assertEquals("https://itch.io/games/free", path(price = ItchBrowse.PRICE_FREE))
|
||||
assertEquals("https://itch.io/games/on-sale", path(price = ItchBrowse.PRICE_SALE))
|
||||
assertEquals("https://itch.io/games/store", path(price = ItchBrowse.PRICE_PAID))
|
||||
assertEquals("https://itch.io/games/5-dollars-or-less", path(price = ItchBrowse.PRICE_UNDER_5))
|
||||
assertEquals("https://itch.io/games/15-dollars-or-less", path(price = ItchBrowse.PRICE_UNDER_15))
|
||||
}
|
||||
|
||||
@Test fun platformsUseItchsOwnNames() {
|
||||
val expected = mapOf(
|
||||
"windows" to "platform-windows", "osx" to "platform-osx", "linux" to "platform-linux", "android" to "platform-android",
|
||||
"ios" to "platform-ios", "web" to "platform-web", "mobile-web" to "platform-mobile-web",
|
||||
)
|
||||
assertEquals(expected.keys.toList(), ItchBrowse.platformNames)
|
||||
for ((name, segment) in expected) assertEquals("https://itch.io/games/$segment", path(platforms = setOf(name)))
|
||||
}
|
||||
|
||||
@Test fun aSortAPriceAndAPlatformCombineInThatOrder() {
|
||||
assertEquals(
|
||||
"https://itch.io/games/top-rated/free/platform-windows",
|
||||
path(ItchBrowse.SORT_TOP_RATED, ItchBrowse.PRICE_FREE, setOf("windows")),
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun aTagIsItsLowercaseNameWithHyphens() {
|
||||
assertEquals("https://itch.io/games/tag-pixel-art", path(tags = listOf("Pixel Art")))
|
||||
assertEquals("pixel-art", ItchBrowse.tagSlug(" Pixel Art "))
|
||||
}
|
||||
|
||||
@Test fun aSortAPricePlatformAndTagCombineInThatOrder() {
|
||||
assertEquals(
|
||||
"https://itch.io/games/top-rated/free/platform-windows/tag-pixel-art.xml",
|
||||
ItchBrowse.url(BrowseQuery(ItchBrowse.SORT_TOP_RATED, ItchBrowse.PRICE_FREE, setOf("windows"), listOf("pixel-art")), 1),
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun severalPlatformsAndTagsAreAllInTheAddress() {
|
||||
assertEquals(
|
||||
"https://itch.io/games/platform-windows/platform-linux/tag-pixel-art/tag-2d",
|
||||
path(platforms = setOf("linux", "windows"), tags = listOf("pixel-art", "2d")),
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun aTypedTagBecomesItsSlug() {
|
||||
assertEquals("visual-novel", ItchBrowse.tagSlug("Visual Novel!"))
|
||||
assertEquals("", ItchBrowse.tagSlug(" !! "))
|
||||
}
|
||||
|
||||
@Test fun theSamePlatformsInAnyOrderGiveTheSameAddress() {
|
||||
assertEquals(path(platforms = setOf("web", "linux")), path(platforms = setOf("linux", "web")))
|
||||
}
|
||||
|
||||
@Test fun laterPagesAskForThePageNumberAndTheFirstDoesNot() {
|
||||
val query = BrowseQuery(sort = ItchBrowse.SORT_TOP_RATED)
|
||||
assertEquals("https://itch.io/games/top-rated.xml", ItchBrowse.url(query, 1))
|
||||
assertEquals("https://itch.io/games/top-rated.xml?page=2", ItchBrowse.url(query, 2))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.droiddeck.launcher.stores.itch
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class)
|
||||
@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class)
|
||||
class ItchGameTest {
|
||||
private fun upload(id: String, filename: String, vararg traits: String, type: String = "default", storage: String = "hosted", demo: Boolean = false, updated: String = "2026-09-16T02:26:06Z") =
|
||||
JSONObject().put("id", id).put("filename", filename).put("size", 1000).put("type", type).put("storage", storage)
|
||||
.put("demo", demo).put("traits", JSONArray(traits.toList())).put("updated_at", updated)
|
||||
|
||||
@Test fun theGameNumberComesFromThePageMeta() {
|
||||
assertEquals("1576684", ItchGame.idFromPage("""<head><meta name="itch:path" content="games/1576684"></head>"""))
|
||||
assertEquals("1576684", ItchGame.idFromPage("""<meta content="games/1576684" name="itch:path">"""))
|
||||
assertNull(ItchGame.idFromPage("<html>no meta here</html>"))
|
||||
}
|
||||
|
||||
@Test fun platformsComeFromTheTraits() {
|
||||
assertEquals(setOf("windows"), ItchUploads.platforms(upload("1", "a.zip", "p_windows")))
|
||||
assertEquals(setOf("linux", "osx"), ItchUploads.platforms(upload("2", "a.zip", "p_linux", "p_osx")))
|
||||
assertEquals(setOf("android"), ItchUploads.platforms(upload("3", "a.apk", "p_android")))
|
||||
assertEquals(setOf("web"), ItchUploads.platforms(upload("4", "a.zip", type = "html")))
|
||||
}
|
||||
|
||||
@Test fun anUploadWithNoPlatformIsTreatedAsWindows() {
|
||||
assertEquals(setOf("windows"), ItchUploads.platforms(upload("5", "a.zip")))
|
||||
}
|
||||
|
||||
@Test fun platformsAlsoReadTheFlagObject() {
|
||||
val flags = JSONObject().put("windows", false).put("linux", true)
|
||||
assertEquals(setOf("linux"), ItchUploads.platforms(JSONObject().put("platforms", flags)))
|
||||
}
|
||||
|
||||
@Test fun buildsSkipExternalUploadsAndPutWindowsFirst() {
|
||||
val uploads = JSONArray()
|
||||
.put(upload("10", "linux.tar.gz", "p_linux", updated = "2026-10-01T00:00:00Z"))
|
||||
.put(upload("11", "win.zip", "p_windows", updated = "2026-09-01T00:00:00Z"))
|
||||
.put(upload("12", "site", "p_windows", storage = "external"))
|
||||
val builds = ItchGame.builds(uploads)
|
||||
assertEquals(listOf("11", "10"), builds.map { it.uploadId })
|
||||
assertTrue(builds[0].installable)
|
||||
assertFalse(builds[1].installable)
|
||||
}
|
||||
|
||||
@Test fun aDemoIsFlagged() {
|
||||
assertTrue(ItchGame.builds(JSONArray().put(upload("20", "demo.zip", "p_windows", demo = true))).single().demo)
|
||||
}
|
||||
|
||||
@Test fun anUploadIsFoundById() {
|
||||
val uploads = JSONArray().put(upload("30", "a.zip")).put(upload("31", "b.zip"))
|
||||
assertEquals("b.zip", ItchUploads.byId(uploads, "31")?.optString("filename"))
|
||||
assertNull(ItchUploads.byId(uploads, "99"))
|
||||
assertNull(ItchUploads.byId(uploads, ""))
|
||||
}
|
||||
|
||||
@Test fun noDownloadKeyMeansNoKeyInTheAddress() {
|
||||
assertEquals("https://api.itch.io/uploads/13619666/download", ItchApi.downloadUrl("13619666", ""))
|
||||
assertEquals("https://api.itch.io/uploads/13619666/download?download_key_id=7", ItchApi.downloadUrl("13619666", "7"))
|
||||
}
|
||||
}
|
||||
@@ -83,13 +83,14 @@ class XboxCatalogTest {
|
||||
assertEquals(mapOf(game to "gamepass", parent to "gamepass"), access(row(game, parent), row(parent, plan), row(plan)))
|
||||
}
|
||||
|
||||
@Test fun onlyPcPlansGrantSubscriptionAccess() {
|
||||
for (pc in listOf("CFQ7TTC0KGQ8", "CFQ7TTC0KHS0", "CFQ7TTC0P85B", "CFQ7TTC0K5DJ", "CFQ7TTC10QFD")) {
|
||||
assertEquals(mapOf(game to "gamepass"), access(row(game, pc), row(pc)))
|
||||
@Test fun everyActivePlanGrantsSubscriptionAccess() {
|
||||
for (plan in listOf("CFQ7TTC0KGQ8", "CFQ7TTC0KHS0", "CFQ7TTC0P85B", "CFQ7TTC0K5DJ", "CFQ7TTC10QFD", "CFQ7TTC0K6L8")) {
|
||||
assertEquals(mapOf(game to "gamepass"), access(row(game, plan), row(plan)))
|
||||
}
|
||||
val console = "CFQ7TTC0K6L8"
|
||||
assertTrue(access(row(game, console), row(console)).isEmpty())
|
||||
assertTrue(XboxCatalog.access(withMembership(envelope(row(game, console)), membership(console)),
|
||||
assertEquals(mapOf(game to "gamepass"), XboxCatalog.access(withMembership(envelope(row(game, console)), membership(console)),
|
||||
"test@example.test", "US", now))
|
||||
assertTrue(XboxCatalog.access(withMembership(envelope(row(game, console)), membership(console).put("status", "Expired")),
|
||||
"test@example.test", "US", now).isEmpty())
|
||||
}
|
||||
|
||||
@@ -165,4 +166,29 @@ class XboxCatalogTest {
|
||||
assertEquals(game, XboxCatalog.product(product("Windows.Desktop", "MSIXVC").put("ProductId", game.lowercase()), mapOf(game to "owned"))!!.id)
|
||||
assertTrue(pc.accessible); assertTrue(pc.subscription); assertFalse(pc.owned)
|
||||
}
|
||||
|
||||
private fun product(id: String, platform: String?) = JSONObject().put("ProductId", id).put("ProductType", "Game")
|
||||
.put("LocalizedProperties", JSONArray().put(JSONObject().put("ProductTitle", "A Game")))
|
||||
.put("DisplaySkuAvailabilities", JSONArray().put(JSONObject().put("Sku", JSONObject().put("Properties", JSONObject()
|
||||
.put("Packages", if (platform == null) JSONArray() else JSONArray().put(JSONObject().put("PackageFormat", "MSIXVC")
|
||||
.put("PlatformDependencies", JSONArray().put(JSONObject().put("PlatformName", platform)))))))))
|
||||
|
||||
@Test fun cloudListsKeepStreamOnlyGamesAndMarkStreamablePcGames() {
|
||||
val cloud = XboxCloudCatalog(gamePass = setOf(game), all = setOf(game, parent))
|
||||
val pc = XboxCatalog.product(product(game, "Windows.Desktop"), mapOf(game to "gamepass"), cloud)!!
|
||||
assertTrue(pc.xboxPc); assertTrue(pc.xboxCloud)
|
||||
val consoleOnly = XboxCatalog.product(product(parent, "Xbox.One"), mapOf(parent to "owned"), cloud)!!
|
||||
assertFalse(consoleOnly.xboxPc); assertTrue(consoleOnly.xboxCloud); assertEquals(0L, consoleOnly.sizeBytes)
|
||||
assertNull(XboxCatalog.product(product(parent, "Xbox.One"), mapOf(parent to "gamepass"), cloud))
|
||||
assertNull(XboxCatalog.product(product(parent, "Xbox.One"), mapOf(parent to "owned"), null))
|
||||
assertFalse(XboxCatalog.product(product(game, "Windows.Desktop"), mapOf(game to "gamepass"), null)!!.xboxCloud)
|
||||
}
|
||||
|
||||
@Test fun aCloudOnlyEditionFoldsIntoThePcCardWithTheSameTitle() {
|
||||
val cloud = XboxCloudCatalog(gamePass = setOf(parent), all = emptySet())
|
||||
val pc = XboxCatalog.product(product(game, "Windows.Desktop"), mapOf(game to "gamepass"), cloud)!!
|
||||
val console = XboxCatalog.product(product(parent, "Xbox.One"), mapOf(parent to "gamepass"), cloud)!!
|
||||
val merged = mergeEditions(listOf(pc, console)).single()
|
||||
assertEquals(game, merged.id); assertTrue(merged.xboxPc); assertTrue(merged.xboxCloud); assertEquals(parent, merged.xboxCloudId)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.droiddeck.launcher.stores.xbox
|
||||
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class)
|
||||
@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class)
|
||||
class XboxCloudTest {
|
||||
@Test fun settingsRoundTripAndOutOfRangeValuesAreClamped() {
|
||||
val settings = XboxCloudSettings(resolution = "720p", bitrateMbps = 20, volume = 200, sharpen = 4, fxaa = true, statsCorner = "left",
|
||||
playerEngine = "native", frameGen = "lsfg3", fpsLimit = 120, fpsCustomOn = true, fpsCustom = 90, smallBuffer = true, zeroCopy = true)
|
||||
assertEquals(settings, XboxCloudSettings.decode(settings.toJson()))
|
||||
val wild = XboxCloudSettings.decode("""{"resolution":"4k","codec":"x","bitrateMbps":900,"volume":5,"statsLevel":9,"gamma":40}""")
|
||||
assertEquals("1080p", wild.resolution); assertEquals("default", wild.codec); assertEquals(100, wild.bitrateMbps)
|
||||
assertEquals(100, wild.volume); assertEquals(4, wild.statsLevel); assertEquals(3f, wild.gamma)
|
||||
assertEquals("right", XboxCloudSettings.decode("""{"statsCorner":"middle"}""").statsCorner)
|
||||
assertEquals("ddfg", XboxCloudSettings.decode("""{"frameGen":"winfg"}""").frameGen)
|
||||
assertEquals(0, XboxCloudSettings.decode("""{"fpsLimit":77,"fpsCustom":500}""").fpsLimit)
|
||||
assertEquals(165, XboxCloudSettings.decode("""{"fpsCustomOn":true,"fpsCustom":500}""").fpsTarget)
|
||||
assertEquals(XboxCloudSettings(), XboxCloudSettings.decode("not json"))
|
||||
assertEquals("android", XboxCloudSettings(resolution = "720p").osName)
|
||||
assertEquals("tizen", XboxCloudSettings(resolution = "1080p_hq").osName)
|
||||
}
|
||||
|
||||
@Test fun addedCloudGamesKeepValidRowsOnly() {
|
||||
val list = listOf(XboxCloudGames.Entry("9AAAAAAAAAAA", "A game", "https://store-images.s-microsoft.com/p", null))
|
||||
val decoded = XboxCloudGames.decode(XboxCloudGames.encode(list))
|
||||
assertEquals(1, decoded.size); assertEquals("A game", decoded[0].title); assertNull(decoded[0].hero)
|
||||
assertTrue(XboxCloudGames.decode("""[{"id":"bad","title":"x"},{"id":"9BBBBBBBBBBB","title":""}]""").isEmpty())
|
||||
assertTrue(XboxCloudGames.decode("nope").isEmpty())
|
||||
assertTrue(XboxCloudGames.rowId("9AAAAAAAAAAA") < 0)
|
||||
}
|
||||
|
||||
@Test fun libraryFilterSplitsOwnedGamePassAndCloud() {
|
||||
fun item(owned: Boolean, pass: Boolean, cloud: Boolean) = CatalogItem(Store.XBOX, "9AAAAAAAAAAA", "A", null,
|
||||
owned = owned, subscription = pass, extra = mapOf("cloud" to if (cloud) "1" else "0"))
|
||||
val owned = item(true, false, false); val pass = item(false, true, true)
|
||||
assertTrue(XboxLibraryFilter.keeps(XboxLibraryFilter.ALL, owned))
|
||||
assertTrue(XboxLibraryFilter.keeps(XboxLibraryFilter.OWNED, owned)); assertFalse(XboxLibraryFilter.keeps(XboxLibraryFilter.OWNED, pass))
|
||||
assertTrue(XboxLibraryFilter.keeps(XboxLibraryFilter.GAME_PASS, pass)); assertFalse(XboxLibraryFilter.keeps(XboxLibraryFilter.GAME_PASS, owned))
|
||||
assertTrue(XboxLibraryFilter.keeps(XboxLibraryFilter.CLOUD, pass)); assertFalse(XboxLibraryFilter.keeps(XboxLibraryFilter.CLOUD, owned))
|
||||
}
|
||||
|
||||
@Test fun cloudLaunchUrlUsesTheStreamingEdition() {
|
||||
assertEquals("https://www.xbox.com/play/launch/ball-x-pit/9BBBBBBBBBBB", XboxCatalog.cloudUrl("9AAAAAAAAAAA", "BALL x PIT", "9BBBBBBBBBBB"))
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ class XboxLibraryCacheTest {
|
||||
private fun game(id: String, subscription: Boolean) = CatalogItem(Store.XBOX, id, "A game", "https://example.test/hero",
|
||||
tallImageUrl = "https://example.test/poster", description = "Description", developer = "Developer", publisher = "Publisher",
|
||||
sizeBytes = 12345, owned = !subscription, subscription = subscription, storeUrl = "https://www.xbox.com/games/store/$id",
|
||||
extra = mapOf("market" to "US", "access" to if (subscription) "gamepass" else "owned"))
|
||||
extra = mapOf("market" to "US", "access" to if (subscription) "gamepass" else "owned", "pc" to "1", "cloud" to "0", "cloudId" to ""))
|
||||
|
||||
@Test fun restartRestoresMetadataWithoutTurningSubscriptionsIntoPurchases() {
|
||||
val games = listOf(game("9AAAAAAAAAAA", false), game("9BBBBBBBBBBB", true))
|
||||
@@ -28,7 +28,7 @@ class XboxLibraryCacheTest {
|
||||
val text = XboxLibraryCache.encode(account, "US", listOf(game("9AAAAAAAAAAA", false)), now)
|
||||
assertNull(XboxLibraryCache.decode(text, "other@example.test", "US", now))
|
||||
assertNull(XboxLibraryCache.decode(text, account, "GB", now))
|
||||
assertNull(XboxLibraryCache.decode(text.replace("\"schema\":1", "\"schema\":2"), account, "US", now))
|
||||
assertNull(XboxLibraryCache.decode(text.replace("\"schema\":2", "\"schema\":1"), account, "US", now))
|
||||
assertNull(XboxLibraryCache.decode("invalid", account, "US", now))
|
||||
assertNull(XboxLibraryCache.decode(text, account, "US", now - 120_000))
|
||||
}
|
||||
@@ -50,4 +50,13 @@ class XboxLibraryCacheTest {
|
||||
XboxLibraryCache.clear(app)
|
||||
assertNull(XboxLibraryCache.read(app, account, "US"))
|
||||
}
|
||||
|
||||
@Test fun cloudFlagsAndTheStreamingEditionSurviveARestart() {
|
||||
val stream = game("9CCCCCCCCCCC", true).copy(extra = mapOf("market" to "US", "access" to "gamepass", "pc" to "0", "cloud" to "1", "cloudId" to ""))
|
||||
val folded = game("9AAAAAAAAAAA", true).copy(extra = mapOf("market" to "US", "access" to "gamepass", "pc" to "1", "cloud" to "1", "cloudId" to "9DDDDDDDDDDD"))
|
||||
val cached = XboxLibraryCache.decode(XboxLibraryCache.encode(account, "US", listOf(stream, folded), now), account, "US", now)!!
|
||||
assertEquals(listOf(stream, folded), cached.games)
|
||||
assertFalse(cached.games[0].xboxPc); assertTrue(cached.games[0].xboxCloud)
|
||||
assertEquals("9DDDDDDDDDDD", cached.games[1].xboxCloudId)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.droiddeck.launcher.stores.xbox
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class)
|
||||
@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class)
|
||||
class XboxSignInMessagesTest {
|
||||
@Test fun ownCheckMessagesAreShownAndOtherTextIsNot() {
|
||||
assertEquals("the Xbox helper stopped with exit code 3", XboxLoginActivity.failure(IllegalStateException("the Xbox helper stopped with exit code 3")))
|
||||
assertEquals("IllegalStateException", XboxLoginActivity.failure(IllegalStateException("Check failed.")))
|
||||
assertEquals("JSONException", XboxLoginActivity.failure(org.json.JSONException("token=secret-value")))
|
||||
assertEquals("IllegalArgumentException", XboxLoginActivity.failure(IllegalArgumentException("secret-value")))
|
||||
}
|
||||
|
||||
@Test fun gamertagMustBeShortPrintableText() {
|
||||
assertTrue(XboxGamertag.valid("Some Gamertag"))
|
||||
assertFalse(XboxGamertag.valid(""))
|
||||
assertFalse(XboxGamertag.valid("a\nb"))
|
||||
assertFalse(XboxGamertag.valid("x".repeat(65)))
|
||||
}
|
||||
|
||||
@Test fun gamertagRefreshIsOncePerAccountGeneration() {
|
||||
val first = "account-generation-one-${System.nanoTime()}"
|
||||
val second = "account-generation-two-${System.nanoTime()}"
|
||||
assertTrue(XboxGamertag.shouldTryRefresh(first))
|
||||
assertFalse(XboxGamertag.shouldTryRefresh(first))
|
||||
assertTrue(XboxGamertag.shouldTryRefresh(second))
|
||||
assertFalse(XboxGamertag.shouldTryRefresh(second))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.droiddeck.launcher.stores.xbox
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class XodusDiagnosticsTest {
|
||||
private val rejected = Regex(Xodus.SIGN_IN_REJECTED)
|
||||
|
||||
@Test fun aContentLicenseRejectionIsRecognised() {
|
||||
assertTrue("Microsoft content licensing rejected sign-in (HTTP 401). Sign in again in Settings.".matches(rejected))
|
||||
}
|
||||
|
||||
@Test fun otherStderrTextIsNotTakenForARejection() {
|
||||
assertFalse("Microsoft content licensing rejected sign-in (HTTP 401). Sign in again in Settings. token=abc".matches(rejected))
|
||||
assertFalse("Microsoft content licensing rejected sign-in (HTTP 403). Sign in again in Settings.".matches(rejected))
|
||||
assertFalse("NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-http 401".matches(rejected))
|
||||
}
|
||||
}
|
||||
@@ -48,7 +48,7 @@ class GamesClientTagTest {
|
||||
DroidDeckTheme {
|
||||
CompositionLocalProvider(LocalFrontFocus provides FrontFocus(), LocalNarrowPane provides narrow) {
|
||||
FocusGlideHost {
|
||||
GamesPage(FrontEndState(
|
||||
LibraryPage(FrontEndState(
|
||||
installed = "r9", ready = true, available = null, busy = false, stage = "", percent = -1,
|
||||
desktopInstalled = true, offlineAccount = null, offline = false, frameGenLabel = "",
|
||||
romsDir = null, logsEnabled = false, steamGames = games, steamGamesX64 = x64, emulators = emptyList(), running = null,
|
||||
@@ -60,7 +60,7 @@ class GamesClientTagTest {
|
||||
onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {},
|
||||
onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> },
|
||||
onSetPhantomProcessLimit = { _, _ -> },
|
||||
), selected = "app:440", onSelect = {}, modifier = Modifier.fillMaxSize())
|
||||
), selected = "games", onSelect = {}, modifier = Modifier.fillMaxSize())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class LibraryEntriesTest {
|
||||
private fun owned(store: Store, id: String, title: String = id) = CatalogItem(store, id, title, imageUrl = null, owned = true)
|
||||
|
||||
@Test fun anInstalledStoreGameClaimsItsOwnedProductSoItShowsOnce() {
|
||||
val games = listOf(
|
||||
Library.SteamGame(440, "Team Fortress 2", null, "Steam library"),
|
||||
Library.SteamGame(-5, "Cyberpunk", null, Library.ADDED, source = "gog", storeId = "1423049311"),
|
||||
)
|
||||
val library = mapOf(Store.GOG to listOf(owned(Store.GOG, "1423049311", "Cyberpunk 2077"), owned(Store.GOG, "1207658924", "Witcher")))
|
||||
val entries = libraryEntries(games, library, emptySet())
|
||||
assertEquals(listOf("app:440", "app:-5", "app:gog:1207658924"), entries.map { it.key })
|
||||
assertEquals("gog:1423049311", entries[1].item?.key)
|
||||
assertTrue(entries[1].installed)
|
||||
assertFalse(entries[2].installed)
|
||||
assertNull(entries[2].game)
|
||||
}
|
||||
|
||||
@Test fun theEpicLauncherIsNotAGame() {
|
||||
val launcher = Library.SteamGame(0, Library.EPIC_LAUNCHER_NAME, null, Library.EPIC_LAUNCHER)
|
||||
assertEquals(emptyList<String>(), libraryEntries(listOf(launcher), emptyMap(), emptySet()).map { it.key })
|
||||
}
|
||||
|
||||
@Test fun aStoreInstallTheLibraryHasNotScannedYetCountsAsInstalled() {
|
||||
val entries = libraryEntries(emptyList(), mapOf(Store.EPIC to listOf(owned(Store.EPIC, "fn"))), setOf("epic:fn"))
|
||||
assertTrue(entries.single().installed)
|
||||
}
|
||||
|
||||
@Test fun installedGamesComeFirstKeepingTheirSortedOrder() {
|
||||
val entries = listOf("a", "b", "c", "d").map { LibraryEntry(it, "steam", it, null, null, installed = it == "b" || it == "d") }
|
||||
assertEquals(listOf("b", "d", "a", "c"), installedFirst(entries).map { it.key })
|
||||
}
|
||||
|
||||
@Test fun gameKeysNameEitherAnAppOrAStoreProduct() {
|
||||
GameRef.parse("app:440").let { assertEquals(440, it.appId); assertNull(it.store) }
|
||||
GameRef.parse("app:-12").let { assertEquals(-12, it.appId) }
|
||||
GameRef.parse("app:gog:1207658924").let { assertEquals(Store.GOG, it.store); assertEquals("1207658924", it.storeId); assertNull(it.appId) }
|
||||
GameRef.parse("xbox:9NBLGGH4R315").let { assertEquals(Store.XBOX, it.store); assertEquals("9NBLGGH4R315", it.storeId) }
|
||||
GameRef.parse("app:nope:1").let { assertNull(it.store); assertNull(it.appId) }
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,17 @@ class PickListingTest {
|
||||
assertEquals(listOf("alarms", "Android", "DCIM", "Documents", "Download", "Games", "Winlator"), listing.folders.map { it.dir.name })
|
||||
}
|
||||
|
||||
@Test fun hiddenDirectoriesAndExecutablesCanBeShownOnRequest() {
|
||||
val root = storage()
|
||||
val hidden = File(root, ".Games").apply { mkdirs() }
|
||||
File(hidden, "Game.exe").writeText("game")
|
||||
assertFalse(pickListing(root, PickKind.EXE).folders.any { it.dir.name == ".Games" })
|
||||
val listing = pickListing(root, PickKind.EXE, showHidden = true)
|
||||
assertTrue(listing.folders.any { it.dir.name == ".Games" })
|
||||
assertTrue(listing.files.any { it.name == ".hidden.exe" })
|
||||
assertEquals(listOf("Game.exe"), pickListing(hidden, PickKind.EXE).files.map { it.name })
|
||||
}
|
||||
|
||||
@Test fun onlyExesForAGameOnlyImagesForArt() {
|
||||
val root = storage()
|
||||
assertEquals(listOf("game.EXE", "Setup.exe"), pickListing(root, PickKind.EXE).files.map { it.name })
|
||||
|
||||
@@ -9,6 +9,7 @@ import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.Button
|
||||
import androidx.compose.ui.test.*
|
||||
import androidx.compose.ui.semantics.SemanticsProperties.StateDescription
|
||||
import androidx.compose.runtime.MutableState
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.SessionActivity
|
||||
@@ -97,6 +98,69 @@ class SessionSecondScreenTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Config(sdk = [34], shadows = [PadBridgeRoutingTest.RegisteredKeyEvent::class])
|
||||
fun drawerShortcutsConsumeRepeatsAndReleasesAfterClosing() {
|
||||
val device = InputDeviceBuilder.newBuilder().setId(43).setName("Drawer shortcut test pad")
|
||||
.setDescriptor("drawer-shortcut-pad").setExternal(true).setSources(InputDevice.SOURCE_GAMEPAD).build()
|
||||
shadowOf(context.getSystemService(InputManager::class.java)).addInputDevice(device)
|
||||
SessionState.mode = SessionService.MODE_STEAM
|
||||
val activity = Robolectric.buildActivity(SessionActivity::class.java).get()
|
||||
val open: MutableState<Boolean> = ReflectionHelpers.getField(activity, "drawerOpen\$delegate")
|
||||
val controller: MutableState<Boolean> = ReflectionHelpers.getField(activity, "drawerControllerActive\$delegate")
|
||||
controller.value = true
|
||||
for (button in listOf(KeyEvent.KEYCODE_BUTTON_SELECT, KeyEvent.KEYCODE_BUTTON_START)) {
|
||||
fun event(action: Int, repeat: Int = 0) = KeyEvent(0L, 0L, action, button, repeat, 0,
|
||||
device.id, 0, 0, InputDevice.SOURCE_GAMEPAD)
|
||||
open.value = true
|
||||
assertTrue(activity.dispatchKeyEvent(event(KeyEvent.ACTION_DOWN)))
|
||||
assertEquals(false, open.value)
|
||||
open.value = true
|
||||
assertTrue(activity.dispatchKeyEvent(event(KeyEvent.ACTION_DOWN, 1)))
|
||||
assertEquals(true, open.value)
|
||||
open.value = false
|
||||
assertTrue(activity.dispatchKeyEvent(event(KeyEvent.ACTION_UP)))
|
||||
val held: Set<Pair<Int, Int>> = ReflectionHelpers.getField(activity, "drawerShortcutKeysDown")
|
||||
assertTrue(held.isEmpty())
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun sessionMicrophoneCanBeTurnedOff() {
|
||||
val changes = mutableListOf<Boolean>()
|
||||
compose.setContent {
|
||||
DroidDeckTheme {
|
||||
SessionDrawer(true, SessionDrawerPage.SESSION, false, {},
|
||||
actions(true, emptyList(), micAvailable = true, micEnabled = true, onMic = changes::add))
|
||||
}
|
||||
}
|
||||
compose.onNodeWithTag("setting-microphone").assertIsEnabled()
|
||||
.assert(SemanticsMatcher.expectValue(StateDescription, context.getString(R.string.widgets_on))).performClick()
|
||||
assertEquals(listOf(false), changes)
|
||||
}
|
||||
|
||||
@Test fun sessionMicrophoneCanBeTurnedBackOn() {
|
||||
val changes = mutableListOf<Boolean>()
|
||||
compose.setContent {
|
||||
DroidDeckTheme {
|
||||
SessionDrawer(true, SessionDrawerPage.SESSION, false, {},
|
||||
actions(true, emptyList(), micAvailable = true, onMic = changes::add))
|
||||
}
|
||||
}
|
||||
compose.onNodeWithTag("setting-microphone").assertIsEnabled()
|
||||
.assert(SemanticsMatcher.expectValue(StateDescription, context.getString(R.string.widgets_off))).performClick()
|
||||
assertEquals(listOf(true), changes)
|
||||
}
|
||||
|
||||
@Test fun sessionWithoutMicrophoneOmitsCaptureControl() {
|
||||
compose.setContent {
|
||||
DroidDeckTheme {
|
||||
SessionDrawer(true, SessionDrawerPage.SESSION, false, {}, actions(false, emptyList()))
|
||||
}
|
||||
}
|
||||
compose.onNodeWithTag("setting-microphone").assertDoesNotExist()
|
||||
compose.onNodeWithText(context.getString(R.string.mode_mic)).assertDoesNotExist()
|
||||
}
|
||||
|
||||
private fun checkModes(steam: Boolean) {
|
||||
SessionState.mode = if (steam) SessionService.MODE_STEAM else SessionService.MODE_DESKTOP
|
||||
val selected = mutableListOf<SecondScreenMode>()
|
||||
@@ -145,8 +209,11 @@ class SessionSecondScreenTest {
|
||||
if (view is ViewGroup) for (index in 0 until view.childCount) yieldAll(descendants(view.getChildAt(index)))
|
||||
}
|
||||
|
||||
private fun actions(steam: Boolean, displays: List<SecondScreenDisplay>, select: (SecondScreenMode) -> Unit = {}) =
|
||||
private fun actions(steam: Boolean, displays: List<SecondScreenDisplay>,
|
||||
micAvailable: Boolean = false, micEnabled: Boolean = false, onMic: (Boolean) -> Unit = {},
|
||||
select: (SecondScreenMode) -> Unit = {}) =
|
||||
DrawerActions(steam = steam, isHomeApp = false, androidApps = emptyList(), hudOn = false,
|
||||
micAvailable = micAvailable, micEnabled = micEnabled, onMicEnabled = onMic,
|
||||
frameGen = FrameGen.Mode.OFF, lossless = Lossless.State.NONE, oscMode = "never",
|
||||
onScreenButtonsVisible = false, suspendPolicy = "auto", backActionsInverted = false,
|
||||
touchMode = "auto", touchAuto = "trackpad", fexPreset = "default",
|
||||
|
||||
@@ -46,9 +46,4 @@ class StoreGridNavigationTest {
|
||||
assertEquals(10, storeGridNeighbor(6, 11, 4, 1, split = 6))
|
||||
assertNull(storeGridNeighbor(1, 11, 4, -1, split = 6))
|
||||
}
|
||||
|
||||
@Test fun installedGamesComeFirstKeepingTheirSortedOrder() {
|
||||
val items = listOf("a", "b", "c", "d").map { com.droiddeck.launcher.stores.CatalogItem(com.droiddeck.launcher.stores.Store.GOG, it, it, null) }
|
||||
assertEquals(listOf("b", "d", "a", "c"), installedFirst(items, setOf("d", "b")).map { it.id })
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class StoreTabsTest {
|
||||
@Test fun libraryAndStoreAmazonLibraryOnly() {
|
||||
assertEquals(listOf("library", "store"), tabsFor(Store.GOG))
|
||||
assertEquals(listOf("library", "store"), tabsFor(Store.ITCH))
|
||||
assertEquals(listOf("library"), tabsFor(Store.AMAZON))
|
||||
assertEquals("library", tabFor(Store.AMAZON, "store"))
|
||||
assertEquals("library", tabFor(Store.GOG, "all"))
|
||||
assertEquals("library", tabFor(Store.EPIC, "installed"))
|
||||
assertEquals("store", tabFor(Store.GOG, "store"))
|
||||
}
|
||||
}
|
||||
@@ -132,4 +132,40 @@ class ThemeColorsTest {
|
||||
assertTrue(Themes.all.any { it.id == Themes.GRADIENT })
|
||||
assertEquals(Themes.GRAPHITE, Themes.byId("nonsense").id)
|
||||
}
|
||||
|
||||
@Test fun innerGamerSitsJustAboveGradientInTheThemeList() {
|
||||
val ids = Themes.all.map { it.id }
|
||||
assertEquals(ids.indexOf(Themes.GRADIENT) - 1, ids.indexOf(Themes.INNER_GAMER))
|
||||
}
|
||||
|
||||
@Test fun innerGamerButtonTextIsReadableAlongTheGradientAtEveryHue() {
|
||||
var hue = 0f
|
||||
while (hue < 360f) {
|
||||
val p = Themes.innerGamer(hue)
|
||||
assertEquals(Themes.INNER_GAMER, p.id)
|
||||
for (i in 0..100) {
|
||||
val f = i / 100f
|
||||
val blend = Color(
|
||||
p.primary.red + (p.primary2.red - p.primary.red) * f,
|
||||
p.primary.green + (p.primary2.green - p.primary.green) * f,
|
||||
p.primary.blue + (p.primary2.blue - p.primary.blue) * f,
|
||||
)
|
||||
assertTrue("hue $hue at $f", contrast(p.onPrimary, blend) >= 4.49f)
|
||||
}
|
||||
hue += Themes.RGB_HUE_STEP
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun innerGamerFollowsTheHueAndTheSpeedIsSavedAndKeptInRange() {
|
||||
Themes.moveRgbHue(120f)
|
||||
assertEquals(Themes.innerGamer(120f).primary, Themes.byId(Themes.INNER_GAMER).primary)
|
||||
Themes.setRgbSpeed(app, 7)
|
||||
assertEquals(7, SessionPrefs.rgbSpeed(app))
|
||||
Themes.setRgbSpeed(app, 99)
|
||||
assertEquals(Themes.RGB_SPEEDS, Themes.rgbSpeed)
|
||||
Themes.setRgbSpeed(app, 0)
|
||||
assertEquals(1, SessionPrefs.rgbSpeed(app))
|
||||
Themes.setRgbSpeed(app, 1)
|
||||
assertTrue(Themes.rgbCycleMillis(1) > Themes.rgbCycleMillis(10))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user