Orbit Arcade Stage C: unit tests for the foundation
Store (round trip, top 10, corrupt and missing files, resets, file names), Household Records (copy, never rewritten, old keys untouched), session and reset state machines, input repeat guard, audio ceiling, Kids filter matrix, and best-on-exit for each wrapped game. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
package tv.orbit.classic.arcade
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class ArcadeAudioTest {
|
||||
@Test fun orbitsQuietSettingsAreACeiling() {
|
||||
assertEquals(1f, arcadeCeiling(identQuiet = false, windDown = false), 0f)
|
||||
assertEquals(.4f, arcadeCeiling(identQuiet = true, windDown = false), 0f)
|
||||
assertEquals(WIND_DOWN_CEILING, arcadeCeiling(identQuiet = false, windDown = true), 0f)
|
||||
assertEquals(WIND_DOWN_CEILING, arcadeCeiling(identQuiet = true, windDown = true), 0f)
|
||||
}
|
||||
|
||||
@Test fun nothingIsLouderThanTheCeilingWhateverIsChosen() {
|
||||
val prefs = listOf(AudioPrefs(), AudioPrefs(music = false), AudioPrefs(effects = false), AudioPrefs(muteAll = true))
|
||||
for (p in prefs) for (q in listOf(false, true)) for (w in listOf(false, true)) for (on in listOf(false, true)) for (base in listOf(.3f, .7f, 1f, 1.5f)) {
|
||||
val ceiling = arcadeCeiling(q, w)
|
||||
assertTrue(musicLevel(base, p, on, ceiling) <= ceiling * base + 1e-6f && musicLevel(base, p, on, ceiling) <= 1f)
|
||||
assertTrue(effectsLevel(base, p, on, ceiling) <= ceiling * base + 1e-6f && effectsLevel(base, p, on, ceiling) <= 1f)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun muteMusicEffectsAndTheGamesOwnSwitch() {
|
||||
assertEquals(.5f, musicLevel(.5f, AudioPrefs(), true, 1f), 1e-6f)
|
||||
assertEquals(.2f, musicLevel(.5f, AudioPrefs(), true, .4f), 1e-6f)
|
||||
assertEquals(0f, musicLevel(.5f, AudioPrefs(music = false), true, 1f), 0f)
|
||||
assertEquals(.7f, musicLevel(.7f, AudioPrefs(effects = false), true, 1f), 1e-6f)
|
||||
assertEquals(0f, effectsLevel(.7f, AudioPrefs(effects = false), true, 1f), 0f)
|
||||
assertEquals(0f, effectsLevel(.7f, AudioPrefs(muteAll = true), true, 1f), 0f)
|
||||
assertEquals(0f, musicLevel(.7f, AudioPrefs(muteAll = true), true, 1f), 0f)
|
||||
// The game's own Sound: Off (Star Chase, Brick Break, Comet Trail's Music).
|
||||
assertEquals(0f, effectsLevel(.7f, AudioPrefs(), gameOn = false, ceiling = 1f), 0f)
|
||||
}
|
||||
|
||||
@Test fun prefsReadFromAProfilesSettings() {
|
||||
assertEquals(AudioPrefs(), AudioPrefs.of(emptyMap()))
|
||||
assertEquals(AudioPrefs(music = false, effects = true, muteAll = true), AudioPrefs.of(mapOf("music" to false, "muteAll" to true)))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package tv.orbit.classic.arcade
|
||||
|
||||
import android.view.KeyEvent
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class ArcadeInputTest {
|
||||
@Test fun theRemoteMapsToArcadeKeys() {
|
||||
assertEquals(ArcadeKey.Ok, arcadeKey(KeyEvent.KEYCODE_DPAD_CENTER)); assertEquals(ArcadeKey.Ok, arcadeKey(KeyEvent.KEYCODE_ENTER))
|
||||
assertEquals(ArcadeKey.Back, arcadeKey(KeyEvent.KEYCODE_BACK)); assertEquals(ArcadeKey.Menu, arcadeKey(KeyEvent.KEYCODE_MENU))
|
||||
assertEquals(ArcadeKey.Down, arcadeKey(KeyEvent.KEYCODE_DPAD_DOWN)); assertEquals(ArcadeKey.Other, arcadeKey(KeyEvent.KEYCODE_VOLUME_UP))
|
||||
// Back and play/pause pause a game; nothing else does.
|
||||
assertTrue(pausesGame(ArcadeKey.Back)); assertTrue(pausesGame(ArcadeKey.PlayPause)); assertFalse(pausesGame(ArcadeKey.Ok))
|
||||
}
|
||||
|
||||
@Test fun holdingOkActsOnce() {
|
||||
val g = RepeatGuard()
|
||||
assertTrue(g.accept(ArcadeKey.Ok, down = true, repeatCount = 0))
|
||||
// The remote repeating a held OK: ignored.
|
||||
assertFalse(g.accept(ArcadeKey.Ok, true, 1)); assertFalse(g.accept(ArcadeKey.Ok, true, 7))
|
||||
// Some remotes send another "down" with no repeat count and no release: ignored too.
|
||||
assertFalse(g.accept(ArcadeKey.Ok, true, 0))
|
||||
// Let go, press again: acts.
|
||||
assertFalse(g.accept(ArcadeKey.Ok, down = false, repeatCount = 0))
|
||||
assertTrue(g.accept(ArcadeKey.Ok, true, 0))
|
||||
}
|
||||
|
||||
@Test fun movesStillRepeatAndDownCanBeGuardedToo() {
|
||||
val g = RepeatGuard()
|
||||
repeat(5) { assertTrue(g.accept(ArcadeKey.Left, true, it)) }
|
||||
assertTrue(g.accept(ArcadeKey.Down, true, 3))
|
||||
val both = RepeatGuard(setOf(ArcadeKey.Ok, ArcadeKey.Down))
|
||||
assertTrue(both.accept(ArcadeKey.Down, true, 0)); assertFalse(both.accept(ArcadeKey.Down, true, 1))
|
||||
}
|
||||
|
||||
@Test fun losingTheWindowForgetsWhatWasHeld() {
|
||||
val g = RepeatGuard()
|
||||
assertTrue(g.accept(ArcadeKey.Ok, true, 0))
|
||||
// A dialog took the remote and the release went to it.
|
||||
g.reset()
|
||||
assertTrue(g.accept(ArcadeKey.Ok, true, 0))
|
||||
}
|
||||
|
||||
@Test fun aLoopRunsOnlyInPlayAliveAndOnScreen() {
|
||||
assertTrue(loopRuns(paused = false, alive = true, shown = true))
|
||||
assertFalse(loopRuns(true, true, true)); assertFalse(loopRuns(false, false, true)); assertFalse(loopRuns(false, true, false))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package tv.orbit.classic.arcade
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class ArcadeSessionTest {
|
||||
private fun run(vararg events: SessionEvent, from: SessionState = SessionState.Title) = events.fold(from) { s, e -> reduceSession(s, e) }
|
||||
|
||||
@Test fun aFirstGameShowsHowToPlayFirstAndLaterGamesGoStraightIn() {
|
||||
assertEquals(SessionState.Title, sessionStart(GameRecord()))
|
||||
assertEquals(SessionState.Play, sessionStart(GameRecord(firstRunSeen = true)))
|
||||
assertEquals(SessionState.Title, sessionStart(GameRecord(firstRunSeen = true, howToEveryTime = true)))
|
||||
}
|
||||
|
||||
@Test fun backPausesAndNeverLeavesMidGame() {
|
||||
assertEquals(SessionState.Pause(), run(SessionEvent.Start, SessionEvent.Back))
|
||||
assertEquals(SessionState.Play, run(SessionEvent.Start, SessionEvent.Back, SessionEvent.Back))
|
||||
assertEquals(SessionState.Pause(), run(SessionEvent.Start, SessionEvent.Hidden))
|
||||
// How to Play from the pause menu: Back closes it, back to the pause menu.
|
||||
assertEquals(SessionState.Pause(howTo = true), run(SessionEvent.Start, SessionEvent.Back, SessionEvent.HowTo))
|
||||
assertEquals(SessionState.Pause(), run(SessionEvent.Start, SessionEvent.Back, SessionEvent.HowTo, SessionEvent.Back))
|
||||
assertTrue(run(SessionEvent.Start).running); assertFalse(run(SessionEvent.Start, SessionEvent.Back).running)
|
||||
}
|
||||
|
||||
@Test fun pauseMenuChoices() {
|
||||
val paused = run(SessionEvent.Start, SessionEvent.Back)
|
||||
assertEquals(SessionState.Play, reduceSession(paused, SessionEvent.Resume))
|
||||
assertEquals(SessionState.Play, reduceSession(paused, SessionEvent.Restart))
|
||||
assertEquals(SessionState.Exited, reduceSession(paused, SessionEvent.Exit))
|
||||
// Nothing finishes while paused.
|
||||
assertEquals(paused, reduceSession(paused, SessionEvent.Finish(RunEnd(10, true), false)))
|
||||
}
|
||||
|
||||
@Test fun aResultOffersPlayAgainOrBackToTheArcade() {
|
||||
val end = RunEnd(330, true)
|
||||
val result = run(SessionEvent.Start, SessionEvent.Finish(end, newBest = true))
|
||||
assertEquals(SessionState.Result(end, true), result)
|
||||
assertEquals(SessionState.Play, reduceSession(result, SessionEvent.PlayAgain))
|
||||
assertEquals(SessionState.Exited, reduceSession(result, SessionEvent.Back))
|
||||
}
|
||||
|
||||
@Test fun theTitleStartsOrLeaves() {
|
||||
assertEquals(SessionState.Play, run(SessionEvent.Start))
|
||||
assertEquals(SessionState.Exited, run(SessionEvent.Back))
|
||||
assertEquals(SessionState.Exited, reduceSession(SessionState.Exited, SessionEvent.Start))
|
||||
}
|
||||
|
||||
private val all = { _: ResetAction -> true }
|
||||
|
||||
@Test fun resetAsksFirstWithCancelChosen() {
|
||||
var s = reduceReset(ResetState(), ResetEvent.ChooseGame("Snake"), all)
|
||||
s = reduceReset(s, ResetEvent.Choose(ResetAction.ClearHighScores), all)
|
||||
assertEquals(ResetAction.ClearHighScores, s.confirming); assertFalse(s.focusOnConfirm)
|
||||
// OK straight away presses Cancel: nothing happens.
|
||||
val cancelled = reduceReset(s, ResetEvent.Press, all)
|
||||
assertNull(cancelled.confirming); assertNull(cancelled.done)
|
||||
// Moving to the red button and pressing it does it.
|
||||
val done = reduceReset(reduceReset(s, ResetEvent.Toggle, all), ResetEvent.Press, all)
|
||||
assertEquals(ResetAction.ClearHighScores, done.done); assertNull(done.confirming)
|
||||
// Back in the dialog cancels; Back on the list goes back to choosing a game.
|
||||
assertNull(reduceReset(s, ResetEvent.Back, all).confirming)
|
||||
assertNull(reduceReset(reduceReset(s, ResetEvent.Back, all), ResetEvent.Back, all).gameId)
|
||||
}
|
||||
|
||||
@Test fun eachOfTheFourActionsIsSeparateAndRefusedOnesDoNothing() {
|
||||
val chosen = reduceReset(ResetState(), ResetEvent.ChooseGame("Snake"), all)
|
||||
ResetAction.entries.forEach { a -> assertEquals(a, reduceReset(chosen, ResetEvent.Choose(a), all).confirming) }
|
||||
assertNull(reduceReset(chosen, ResetEvent.Choose(ResetAction.RestartLevel)) { it != ResetAction.RestartLevel }.confirming)
|
||||
// No game chosen yet: nothing to confirm.
|
||||
assertNull(reduceReset(ResetState(), ResetEvent.Choose(ResetAction.ClearHighScores), all).confirming)
|
||||
}
|
||||
|
||||
@Test fun everyoneResetsOnlyTheirOwnAndOnlyWhatMeansSomething() {
|
||||
val snake = ArcadeGames.Snake; val sky = ArcadeGames.Sky; val hive = ArcadeGames.Hive
|
||||
// Someone else's data: never, for any action (a Kids profile can only ever reset its own).
|
||||
ResetAction.entries.forEach { assertFalse(resetAllowed(it, snake, "kids", "grown", inGame = true)) }
|
||||
assertTrue(resetAllowed(ResetAction.ClearHighScores, snake, "kids", "kids", inGame = false))
|
||||
assertTrue(resetAllowed(ResetAction.ResetSettings, snake, "kids", "kids", inGame = false))
|
||||
// Restart level only inside a game.
|
||||
assertFalse(resetAllowed(ResetAction.RestartLevel, snake, "kids", "kids", inGame = false))
|
||||
assertTrue(resetAllowed(ResetAction.RestartLevel, snake, "kids", "kids", inGame = true))
|
||||
// Level progress only where a game keeps it; BumbleHive's only once its saves are per profile.
|
||||
assertFalse(resetAllowed(ResetAction.ResetLevelProgress, snake, "p", "p", false))
|
||||
assertTrue(resetAllowed(ResetAction.ResetLevelProgress, sky, "p", "p", false))
|
||||
assertFalse(resetAllowed(ResetAction.ResetLevelProgress, hive, "p", "p", false, hiveProfileSaves = false))
|
||||
assertTrue(resetAllowed(ResetAction.ResetLevelProgress, hive, "p", "p", false, hiveProfileSaves = true))
|
||||
// A coming-soon card has nothing to clear.
|
||||
assertFalse(resetAllowed(ResetAction.ClearHighScores, ArcadeGames.OrbiRaiders, "p", "p", false))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package tv.orbit.classic.arcade
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import java.io.File
|
||||
|
||||
class ArcadeStoreTest {
|
||||
@get:Rule val temp = TemporaryFolder()
|
||||
|
||||
private fun store(dir: File = temp.root) = ArcadeStore(dir)
|
||||
|
||||
@Test fun aSaveSurvivesBeingWrittenAndRead() {
|
||||
var d = ArcadeProfileData("p1", settings = mapOf("music" to false), recent = listOf("Snake", "OrbMan"))
|
||||
d = recordRun(d, "Snake", ScoreKind.Points, RunEnd(140, true, "Level 2"), 1_000)
|
||||
d = recordRun(d, "Sky", ScoreKind.Solved, RunEnd(2, true, "Today's puzzle"), 2_000)
|
||||
d = d.withGame("Sky") { it.copy(level = mapOf("daily" to "2026-11-08"), unlocks = setOf("a"), settings = mapOf("sound" to true), firstRunSeen = true, howToEveryTime = true) }
|
||||
d = applyReset(d, "Snake", ResetAction.ResetSettings, 3_000)
|
||||
val text = encodeArcade(d)
|
||||
assertEquals(ARCADE_SCHEMA, org.json.JSONObject(text).getInt("schema"))
|
||||
assertEquals(d, decodeArcade(text, "p1"))
|
||||
}
|
||||
|
||||
@Test fun pointsKeepTheTopTenBestFirstAndALeftRunStillCounts() {
|
||||
var d = ArcadeProfileData("p1")
|
||||
(1..14).forEach { d = recordRun(d, "Snake", ScoreKind.Points, RunEnd(it * 10, finished = it % 2 == 0), it.toLong()) }
|
||||
val runs = d.game("Snake").runs
|
||||
assertEquals(TOP_RUNS, runs.size)
|
||||
assertEquals((14 downTo 5).map { it * 10 }, runs.map { it.score })
|
||||
assertEquals(140, bestOf(d.game("Snake"), ScoreKind.Points))
|
||||
// A run left part-way (the audit: Leave threw away a record) is saved like any other.
|
||||
d = recordRun(d, "Snake", ScoreKind.Points, RunEnd(900, finished = false), 99)
|
||||
assertEquals(900, bestOf(d.game("Snake"), ScoreKind.Points))
|
||||
// Nothing scored, nothing saved, but it still counts as played.
|
||||
val before = d.game("Snake").runs
|
||||
d = recordRun(d, "Snake", ScoreKind.Points, RunEnd(0, finished = true), 120)
|
||||
assertEquals(before, d.game("Snake").runs); assertEquals(120L, d.game("Snake").lastPlayedMs)
|
||||
}
|
||||
|
||||
@Test fun movesWinsAndSolvesCountOnlyWhenTheGameWasFinished() {
|
||||
var d = ArcadeProfileData("p1")
|
||||
d = recordRun(d, "Pairs", ScoreKind.FewestMoves, RunEnd(12, finished = false), 1)
|
||||
assertEquals(0, bestOf(d.game("Pairs"), ScoreKind.FewestMoves))
|
||||
d = recordRun(d, "Pairs", ScoreKind.FewestMoves, RunEnd(22, finished = true), 2)
|
||||
d = recordRun(d, "Pairs", ScoreKind.FewestMoves, RunEnd(18, finished = true), 3)
|
||||
assertEquals(18, bestOf(d.game("Pairs"), ScoreKind.FewestMoves))
|
||||
d = recordRun(d, "Patience", ScoreKind.Wins, RunEnd(140, finished = false), 4)
|
||||
d = recordRun(d, "Patience", ScoreKind.Wins, RunEnd(120, finished = true), 5)
|
||||
assertEquals(1, bestOf(d.game("Patience"), ScoreKind.Wins))
|
||||
d = recordRun(d, "Sky", ScoreKind.Solved, RunEnd(3, finished = true), 6)
|
||||
d = recordRun(d, "Sky", ScoreKind.Solved, RunEnd(1, finished = false), 7)
|
||||
assertEquals(1, bestOf(d.game("Sky"), ScoreKind.Solved))
|
||||
}
|
||||
|
||||
@Test fun profilesKeepTheirOwnFiles() {
|
||||
val s = store()
|
||||
s.update("grown") { recordRun(it, "Snake", ScoreKind.Points, RunEnd(50, true), 1) }
|
||||
s.update("kids") { recordRun(it, "Snake", ScoreKind.Points, RunEnd(70, true), 1) }
|
||||
val fresh = store()
|
||||
assertEquals(50, bestOf(fresh.load("grown").game("Snake"), ScoreKind.Points))
|
||||
assertEquals(70, bestOf(fresh.load("kids").game("Snake"), ScoreKind.Points))
|
||||
assertTrue(File(temp.root, "grown.json").isFile); assertTrue(File(temp.root, "kids.json").isFile)
|
||||
// Written whole through SafeWrite: nothing half-written is left beside it.
|
||||
assertFalse(temp.root.listFiles()!!.any { it.name.endsWith(".writing") })
|
||||
}
|
||||
|
||||
@Test fun aMissingOrUnreadableSaveStartsAfreshWithoutThrowing() {
|
||||
assertEquals(ArcadeProfileData("nobody"), store().load("nobody"))
|
||||
File(temp.root, "p1.json").writeText("{ this is not json")
|
||||
val s = store()
|
||||
assertEquals(ArcadeProfileData("p1"), s.load("p1"))
|
||||
// Kept to look at, never read again.
|
||||
assertEquals("{ this is not json", File(temp.root, "p1.json.unreadable").readText())
|
||||
// Then saving works as normal.
|
||||
s.update("p1") { recordRun(it, "Snake", ScoreKind.Points, RunEnd(30, true), 1) }
|
||||
assertEquals(30, bestOf(store().load("p1").game("Snake"), ScoreKind.Points))
|
||||
// Not a save at all (no schema), and an empty file: the same.
|
||||
File(temp.root, "p2.json").writeText("""{"games":{}}""")
|
||||
assertEquals(ArcadeProfileData("p2"), store().load("p2"))
|
||||
File(temp.root, "p3.json").writeText("")
|
||||
assertEquals(ArcadeProfileData("p3"), store().load("p3"))
|
||||
}
|
||||
|
||||
@Test fun partlyDamagedSavesKeepWhatTheyCan() {
|
||||
val text = """{"schema":1,"games":{"Snake":{"runs":[{"score":40,"at":5},"junk",{"at":1}],"count":-3,"settings":{"music":false,"bad":"x"}},"Broken":7},"recent":["Snake",3]}"""
|
||||
val d = decodeArcade(text, "p1")!!
|
||||
assertEquals(listOf(ArcadeRun(40, 5)), d.game("Snake").runs)
|
||||
assertEquals(0, d.game("Snake").count)
|
||||
assertEquals(mapOf("music" to false), d.game("Snake").settings)
|
||||
assertEquals(listOf("Snake"), d.recent)
|
||||
assertFalse("Broken" in d.games)
|
||||
}
|
||||
|
||||
@Test fun resetsClearOnlyWhatTheySayAndRememberWhen() {
|
||||
var d = ArcadeProfileData("p1")
|
||||
d = recordRun(d, "Sky", ScoreKind.Solved, RunEnd(2, true), 1)
|
||||
d = d.withGame("Sky") { it.copy(level = mapOf("daily" to "2026-11-08"), settings = mapOf("x" to false), howToEveryTime = true, firstRunSeen = true) }
|
||||
d = recordRun(d, "Snake", ScoreKind.Points, RunEnd(80, true), 1)
|
||||
val scores = applyReset(d, "Sky", ResetAction.ClearHighScores, 100)
|
||||
assertEquals(0, scores.game("Sky").count); assertTrue(scores.game("Sky").runs.isEmpty()); assertEquals(100L, scores.game("Sky").scoresResetMs)
|
||||
assertEquals(d.game("Sky").level, scores.game("Sky").level); assertEquals(d.game("Snake"), scores.game("Snake"))
|
||||
val levels = applyReset(d, "Sky", ResetAction.ResetLevelProgress, 200)
|
||||
assertTrue(levels.game("Sky").level.isEmpty()); assertEquals(1, levels.game("Sky").count); assertEquals(200L, levels.game("Sky").levelsResetMs)
|
||||
val settings = applyReset(d, "Sky", ResetAction.ResetSettings, 300)
|
||||
assertTrue(settings.game("Sky").settings.isEmpty()); assertFalse(settings.game("Sky").howToEveryTime); assertTrue(settings.game("Sky").firstRunSeen)
|
||||
assertEquals(300L, settings.game("Sky").settingsResetMs)
|
||||
assertEquals(d, applyReset(d, "Sky", ResetAction.RestartLevel, 400))
|
||||
}
|
||||
|
||||
@Test fun recentlyPlayedIsNewestFirstAndShort() {
|
||||
var d = ArcadeProfileData("p1")
|
||||
listOf("A", "B", "C", "D", "E", "F", "G", "B").forEachIndexed { i, id -> d = markPlayed(d, id, i.toLong()) }
|
||||
assertEquals(listOf("B", "G", "F", "E", "D", "C"), d.recent)
|
||||
}
|
||||
|
||||
@Test fun profileIdsMakeSafeFileNamesThatNeverClashWithTheHouseholdFile() {
|
||||
assertEquals("p2abc9.json", arcadeFileName("p2abc9"))
|
||||
assertEquals("etcpasswd.json", arcadeFileName("../../etc/passwd"))
|
||||
assertEquals("unknown.json", arcadeFileName("///"))
|
||||
assertEquals("p-household-records.json", arcadeFileName("household-records"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package tv.orbit.classic.arcade
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import java.time.ZoneId
|
||||
import java.time.ZonedDateTime
|
||||
|
||||
class ArcadeWordsTest {
|
||||
private val zone = ZoneId.of("Europe/London")
|
||||
private fun ms(day: Int, hour: Int = 12) = ZonedDateTime.of(2026, 11, day, hour, 0, 0, 0, zone).toInstant().toEpochMilli()
|
||||
|
||||
@Test fun scoresReadAsTheGameCountsThem() {
|
||||
assertEquals("12,450", formatScore(ScoreKind.Points, 12_450))
|
||||
assertEquals("18 moves", formatScore(ScoreKind.FewestMoves, 18))
|
||||
assertEquals("3 won", formatScore(ScoreKind.Wins, 3))
|
||||
assertEquals("41 solved", formatScore(ScoreKind.Solved, 41))
|
||||
assertNull(bestLine(ArcadeGames.Snake, GameRecord()))
|
||||
}
|
||||
|
||||
@Test fun householdRecordsAreNamelessAndOnlyFromTheOldKeys() {
|
||||
val records = mapOf("snake_best" to HouseholdRecord("snake_best", 142, null, "orbit_settings/snake_best", 1), "pairs_best" to HouseholdRecord("pairs_best", 0, null, "x", 1))
|
||||
assertEquals("142", householdLine(ArcadeGames.Snake, records))
|
||||
// Pairs at 0 means no record; BumbleHive and the new games never had one.
|
||||
assertNull(householdLine(ArcadeGames.Pairs, records)); assertNull(householdLine(ArcadeGames.Hive, records)); assertNull(householdLine(ArcadeGames.OrbiRaiders, records))
|
||||
}
|
||||
|
||||
@Test fun playedReadsLikeAPerson() {
|
||||
val now = ms(8, 18)
|
||||
assertEquals("Today", playedLabel(ms(8, 9), now, zone))
|
||||
assertEquals("Yesterday", playedLabel(ms(7), now, zone))
|
||||
assertEquals("Tue", playedLabel(ms(3), now, zone))
|
||||
assertEquals("1 Nov", playedLabel(ms(1), now, zone))
|
||||
assertEquals("", playedLabel(0, now, zone))
|
||||
}
|
||||
|
||||
@Test fun topThreeFromTheProfilesRuns() {
|
||||
var d = ArcadeProfileData("p")
|
||||
listOf(50, 90, 70, 10).forEach { d = recordRun(d, "Snake", ScoreKind.Points, RunEnd(it, true), 1) }
|
||||
assertEquals(listOf("90", "70", "50"), topThree(ArcadeGames.Snake, d.game("Snake")))
|
||||
d = recordRun(d, "Patience", ScoreKind.Wins, RunEnd(100, true), 1)
|
||||
assertEquals(listOf("1 won"), topThree(ArcadeGames.Patience, d.game("Patience")))
|
||||
assertTrue(topThree(ArcadeGames.Pairs, GameRecord()).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun resetWordsSayWhoseAndWhat() {
|
||||
assertEquals("Alfie's top scores for this game go.", resetDetail(ResetAction.ClearHighScores, ArcadeGames.Snake, "Alfie", true))
|
||||
assertEquals("BumbleHive's levels are one save for the whole TV for now.", resetDetail(ResetAction.ResetLevelProgress, ArcadeGames.Hive, "Alfie", false))
|
||||
assertEquals("From a game's pause menu, while you play.", resetDetail(ResetAction.RestartLevel, ArcadeGames.Snake, "Alfie", false))
|
||||
}
|
||||
|
||||
@Test fun gameSettingsStartFromTheOldBoxWideChoice() {
|
||||
val music = ArcadeGames.Snake.settings.first()
|
||||
val legacy = { key: String, default: Boolean -> if (key == "snake_music") false else default }
|
||||
assertFalse(settingFor(GameRecord(), music, legacy))
|
||||
assertTrue(settingFor(GameRecord(settings = mapOf("music" to true)), music, legacy))
|
||||
assertTrue(settingFor(GameRecord(), GameSetting("x", "X"), legacy))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package tv.orbit.classic.arcade
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import tv.orbit.classic.BlastGame
|
||||
import tv.orbit.classic.BlockGame
|
||||
import tv.orbit.classic.BrickGame
|
||||
import tv.orbit.classic.OrbGame
|
||||
import tv.orbit.classic.PairsGame
|
||||
import tv.orbit.classic.PatienceGame
|
||||
import tv.orbit.classic.SkyGame
|
||||
import tv.orbit.classic.SnakeGame
|
||||
import tv.orbit.classic.skyMake
|
||||
|
||||
/**
|
||||
* A run is saved whenever it ends, including Leave / Exit (audit finding 3): each wrapped game's screen reports the run
|
||||
* in progress through a [RunTracker] when it goes away. These follow each game from a real mid-game state to its save.
|
||||
*/
|
||||
class BestOnExitTest {
|
||||
private val random = java.util.Random(4)
|
||||
|
||||
/** What a game's screen does: begin when a run starts, report the run in progress when the player leaves. */
|
||||
private fun leaveMidRun(gameId: String, inProgress: RunEnd): ArcadeProfileData {
|
||||
val game = ArcadeGames.byId(gameId)!!
|
||||
var data = ArcadeProfileData("p1")
|
||||
val tracker = RunTracker { end -> data = recordRun(data, gameId, game.scoreKind, end, 1_000) }
|
||||
tracker.begin()
|
||||
tracker.end(inProgress)
|
||||
// Leaving also disposes the screen, which reports again: only the first counts.
|
||||
tracker.end(inProgress.copy(score = inProgress.score + 1))
|
||||
return data
|
||||
}
|
||||
|
||||
@Test fun pointsGamesKeepTheScoreWhenThePlayerLeaves() {
|
||||
val cases = listOf(
|
||||
"Snake" to SnakeGame.start(30, 22, random).copy(score = 140).score,
|
||||
"OrbMan" to OrbGame.start().copy(score = 2_350).score,
|
||||
"Bricks" to BrickGame.start().copy(score = 610).score,
|
||||
"Blocks" to BlockGame.start(random).copy(score = 900).score,
|
||||
// Blast Off: a real placed shape scores its cells.
|
||||
"Blast" to BlastGame.start(random).press(random).score,
|
||||
)
|
||||
for ((id, score) in cases) {
|
||||
assertTrue(id, score > 0)
|
||||
val data = leaveMidRun(id, RunEnd(score, finished = false))
|
||||
assertEquals(id, score, bestOf(data.game(id), ScoreKind.Points))
|
||||
assertEquals(id, 1, data.game(id).runs.size)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun movesWinsAndSolvesCountOnlyAFinishedGame() {
|
||||
// Leaving Pairs, Patience or Skydoku part-way saves no best (there's no "fewest moves" for a board not cleared).
|
||||
val pairs = PairsGame.deal(random).copy(moves = 9)
|
||||
assertEquals(0, bestOf(leaveMidRun("Pairs", RunEnd(pairs.moves, finished = pairs.done)).game("Pairs"), ScoreKind.FewestMoves))
|
||||
val cleared = pairs.copy(matched = pairs.cards.indices.toSet(), moves = 14)
|
||||
assertTrue(cleared.done)
|
||||
assertEquals(14, bestOf(leaveMidRun("Pairs", RunEnd(cleared.moves, finished = cleared.done)).game("Pairs"), ScoreKind.FewestMoves))
|
||||
val patience = PatienceGame.deal(random)
|
||||
assertEquals(0, bestOf(leaveMidRun("Patience", RunEnd(patience.moves, finished = patience.won)).game("Patience"), ScoreKind.Wins))
|
||||
assertEquals(1, bestOf(leaveMidRun("Patience", RunEnd(88, finished = true)).game("Patience"), ScoreKind.Wins))
|
||||
val sky = SkyGame(skyMake(random))
|
||||
assertEquals(0, bestOf(leaveMidRun("Sky", RunEnd(sky.hearts, finished = sky.done)).game("Sky"), ScoreKind.Solved))
|
||||
assertEquals(1, bestOf(leaveMidRun("Sky", RunEnd(3, finished = true)).game("Sky"), ScoreKind.Solved))
|
||||
}
|
||||
|
||||
@Test fun aRunIsReportedOnceAndOnlyAfterItBegan() {
|
||||
val seen = mutableListOf<RunEnd>()
|
||||
val t = RunTracker { seen += it }
|
||||
t.end(RunEnd(5, false))
|
||||
assertTrue(seen.isEmpty())
|
||||
t.begin(); assertTrue(t.open)
|
||||
t.end(RunEnd(10, true)); t.end(RunEnd(11, false))
|
||||
assertEquals(listOf(RunEnd(10, true)), seen)
|
||||
// Play again: a new run.
|
||||
t.begin(); t.end(RunEnd(20, true))
|
||||
assertEquals(2, seen.size)
|
||||
}
|
||||
|
||||
@Test fun eachWrappedGameRanksTheWayItsOldBestDid() {
|
||||
assertEquals(ScoreKind.Points, ArcadeGames.Snake.scoreKind); assertEquals(ScoreKind.Points, ArcadeGames.OrbMan.scoreKind)
|
||||
assertEquals(ScoreKind.Points, ArcadeGames.Bricks.scoreKind); assertEquals(ScoreKind.Points, ArcadeGames.Blocks.scoreKind)
|
||||
assertEquals(ScoreKind.Points, ArcadeGames.Blast.scoreKind); assertEquals(ScoreKind.FewestMoves, ArcadeGames.Pairs.scoreKind)
|
||||
assertEquals(ScoreKind.Wins, ArcadeGames.Patience.scoreKind); assertEquals(ScoreKind.Solved, ArcadeGames.Sky.scoreKind)
|
||||
assertEquals(ScoreKind.Points, ArcadeGames.Hive.scoreKind)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package tv.orbit.classic.arcade
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
|
||||
class HouseholdRecordsTest {
|
||||
@get:Rule val temp = TemporaryFolder()
|
||||
|
||||
private val legacy = mutableMapOf<String, Any?>("snake_best" to 142, "orb_man_best" to 30450, "pairs_best" to 16, "skydoku_daily" to "2026-11-05",
|
||||
"snake_music" to true, "recent_games" to "Snake")
|
||||
|
||||
@Test fun theSnapshotCopiesTheOldScoresWithWhereAndWhenTheyCameFrom() {
|
||||
val before = legacy.toMap()
|
||||
val records = HouseholdRecords.snapshotIfAbsent(temp.root, { legacy[it] }, 1_000)
|
||||
assertEquals(setOf("snake_best", "orb_man_best", "pairs_best", "skydoku_daily"), records.keys)
|
||||
assertEquals(142, records["snake_best"]!!.number)
|
||||
assertEquals("orbit_settings/snake_best", records["snake_best"]!!.source)
|
||||
assertEquals(1_000L, records["snake_best"]!!.copiedAtMs)
|
||||
assertEquals("2026-11-05", records["skydoku_daily"]!!.text)
|
||||
// Read back the same, and the old keys themselves were only read.
|
||||
assertEquals(records, HouseholdRecords.load(temp.root))
|
||||
assertEquals(before, legacy)
|
||||
// No profile's name anywhere in it.
|
||||
assertFalse(HouseholdRecords.file(temp.root).readText().contains("profile", ignoreCase = true))
|
||||
}
|
||||
|
||||
@Test fun itIsTakenOnceAndNeverRewritten() {
|
||||
HouseholdRecords.snapshotIfAbsent(temp.root, { legacy[it] }, 1_000)
|
||||
val file = HouseholdRecords.file(temp.root)
|
||||
val bytes = file.readBytes(); val modified = file.lastModified()
|
||||
legacy["snake_best"] = 999
|
||||
val again = HouseholdRecords.snapshotIfAbsent(temp.root, { legacy[it] }, 5_000)
|
||||
assertEquals(142, again["snake_best"]!!.number)
|
||||
assertArrayEquals(bytes, file.readBytes()); assertEquals(modified, file.lastModified())
|
||||
}
|
||||
|
||||
@Test fun anUnreadableSnapshotShowsNothingAndIsLeftAlone() {
|
||||
val file = HouseholdRecords.file(temp.root)
|
||||
file.writeText("garbage")
|
||||
assertTrue(HouseholdRecords.snapshotIfAbsent(temp.root, { legacy[it] }, 1_000).isEmpty())
|
||||
assertEquals("garbage", file.readText())
|
||||
}
|
||||
|
||||
@Test fun aBoxWithNoOldScoresGetsAnEmptySnapshot() {
|
||||
assertTrue(HouseholdRecords.snapshotIfAbsent(temp.root, { null }, 1_000).isEmpty())
|
||||
assertTrue(HouseholdRecords.file(temp.root).isFile)
|
||||
assertTrue(HouseholdRecords.load(temp.root).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun nothingInTheAppWritesTheOldScoreKeysAnyMore() {
|
||||
// The old box-wide keys are only read (into Household Records); every game now saves per profile.
|
||||
val src = java.io.File("src/main/java/tv/orbit/classic")
|
||||
val setters = listOf("snakeBest", "blockDropBest", "brickBreakBest", "pairsBest", "patienceWins", "orbManBest", "blastBest", "skydokuSolved", "skydokuDaily")
|
||||
val offenders = src.walk().filter { it.isFile && it.extension == "kt" && it.name != "Settings.kt" }.flatMap { f ->
|
||||
f.readLines().filter { line -> setters.any { s -> Regex("\\.$s\\s*=[^=]").containsMatchIn(line) } }.map { "${f.name}: ${it.trim()}" }
|
||||
}.toList()
|
||||
assertEquals(emptyList<String>(), offenders)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package tv.orbit.classic.arcade
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import tv.orbit.classic.DefaultProfiles
|
||||
import tv.orbit.classic.KidsArcade
|
||||
import tv.orbit.classic.Profile
|
||||
import tv.orbit.classic.ProfileKind
|
||||
import tv.orbit.classic.Profiles
|
||||
import tv.orbit.classic.arcadeForKidsLine
|
||||
|
||||
class KidsArcadeTest {
|
||||
private val grown = DefaultProfiles.first { it.kind == ProfileKind.Grown }
|
||||
private val kids = DefaultProfiles.first { it.kind == ProfileKind.Kids }
|
||||
private fun ids(p: Profile?) = arcadeVisible(p).map { it.id }
|
||||
|
||||
@Test fun grownUpsSeeEveryGame() {
|
||||
assertEquals(ArcadeGames.all.map { it.id }, ids(grown))
|
||||
assertEquals(13, ids(grown).size)
|
||||
// A grown-up's Arcade for Kids setting means nothing.
|
||||
assertEquals(ArcadeGames.all.map { it.id }, ids(grown.withKidsArcade(KidsArcade.Off)))
|
||||
assertEquals(ArcadeGames.all.map { it.id }, ids(null))
|
||||
}
|
||||
|
||||
@Test fun theKidsMatrix() {
|
||||
// Off: no games, and no Arcade in the top bar.
|
||||
val off = kids.withKidsArcade(KidsArcade.Off)
|
||||
assertTrue(ids(off).isEmpty()); assertFalse(arcadeOpenFor(off))
|
||||
// Kids-suitable: Blast Off and Skydoku are left out completely (frame 03), everything else is there.
|
||||
val suitable = kids.withKidsArcade(KidsArcade.KidsSuitable)
|
||||
assertEquals(ArcadeGames.all.filter { it.kidsSuitable }.map { it.id }, ids(suitable))
|
||||
assertFalse("Blast" in ids(suitable)); assertFalse("Sky" in ids(suitable))
|
||||
assertEquals(6, arcadeVisible(suitable).count { !it.original })
|
||||
// Chosen: exactly the games chosen, even one that isn't marked kids-suitable (a grown-up chose it).
|
||||
val chosen = kids.withKidsArcade(KidsArcade.Chosen, setOf("Snake", "Sky"))
|
||||
assertEquals(listOf("Sky", "Snake"), ids(chosen))
|
||||
// Chosen with nothing chosen: no Arcade.
|
||||
assertFalse(arcadeOpenFor(kids.withKidsArcade(KidsArcade.Chosen, emptySet())))
|
||||
}
|
||||
|
||||
@Test fun profilesFromBeforeArcadeForKidsKeepTheirMeaning() {
|
||||
assertEquals(KidsArcade.KidsSuitable, kids.copy(arcade = true).kidsArcade)
|
||||
assertEquals(KidsArcade.Off, kids.copy(arcade = false).kidsArcade)
|
||||
// And a new mode keeps the old switch right for rooms on an older Orbit.
|
||||
assertFalse(kids.withKidsArcade(KidsArcade.Off).arcade)
|
||||
assertTrue(kids.withKidsArcade(KidsArcade.Chosen, setOf("Pairs")).arcade)
|
||||
}
|
||||
|
||||
@Test fun arcadeForKidsSurvivesSavingAndReading() {
|
||||
val list = listOf(grown, kids.withKidsArcade(KidsArcade.Chosen, setOf("Pairs", "Hive")))
|
||||
assertEquals(list, Profiles.decode(Profiles.encode(list)))
|
||||
// A list saved before Stage C reads as before.
|
||||
val old = """[{"id":"grown","name":"Adult","picture":"sil-blue","kind":"Grown","channels":[],"arcade":true,"driveIn":false,"u":0},
|
||||
{"id":"kids","name":"Kids","picture":"ollie","kind":"Kids","channels":[],"arcade":false,"driveIn":false,"u":0}]"""
|
||||
val read = Profiles.decode(old)
|
||||
assertNull(read[1].arcadeMode); assertEquals(KidsArcade.Off, read[1].kidsArcade)
|
||||
}
|
||||
|
||||
@Test fun pickRecentAndHighScoresFollowTheFilter() {
|
||||
val chosen = kids.withKidsArcade(KidsArcade.Chosen, setOf("Pairs", "Snake", "OrbiRaiders"))
|
||||
val visible = arcadeVisible(chosen)
|
||||
// Star Chase isn't chosen, so it can't be the pick.
|
||||
assertEquals("Snake", arcadePick(visible)!!.id)
|
||||
assertEquals("OrbMan", arcadePick(arcadeVisible(grown))!!.id)
|
||||
// Recent keeps only games this profile can still see and play.
|
||||
assertEquals(listOf("Pairs", "Snake"), recentVisible(listOf("Blast", "Pairs", "OrbiRaiders", "Snake", "Gone"), visible).map { it.id })
|
||||
assertNull(arcadePick(emptyList()))
|
||||
}
|
||||
|
||||
@Test fun theFamilyLineSaysWhatKidsReallySee() {
|
||||
// The audit: "On: the games chosen for Kids" promised a choice that didn't exist.
|
||||
assertEquals("Off: no Arcade for Kids", arcadeForKidsLine(kids.withKidsArcade(KidsArcade.Off)))
|
||||
assertEquals("Kids-suitable games: 7 to play", arcadeForKidsLine(kids.withKidsArcade(KidsArcade.KidsSuitable)))
|
||||
assertEquals("Chosen games: 2 to play", arcadeForKidsLine(kids.withKidsArcade(KidsArcade.Chosen, setOf("Pairs", "Sky", "OrbiRaiders"))))
|
||||
assertEquals("Chosen games: none chosen yet, so no Arcade", arcadeForKidsLine(kids.withKidsArcade(KidsArcade.Chosen, emptySet())))
|
||||
}
|
||||
|
||||
@Test fun everyGameIsDescribed() {
|
||||
assertEquals(ArcadeGames.all.size, ArcadeGames.all.map { it.id }.toSet().size)
|
||||
assertEquals(5, ArcadeGames.originals.size); assertEquals(8, ArcadeGames.classics.size)
|
||||
// Only BumbleHive of the Originals plays in Stage C; every Classic does.
|
||||
assertEquals(listOf("Hive"), ArcadeGames.originals.filter { it.launchable }.map { it.id })
|
||||
assertTrue(ArcadeGames.classics.all { it.launchable })
|
||||
ArcadeGames.all.forEach { g ->
|
||||
assertTrue(g.id, g.controls.isNotEmpty()); assertTrue(g.id, g.title.isNotBlank()); assertTrue(g.id, g.goal.isNotBlank())
|
||||
assertTrue(g.id, g.controls.any { it.keys == "Back" })
|
||||
}
|
||||
// Each Classic's Household Record comes from its old key.
|
||||
assertEquals(LegacyRecordKeys.toSet() - "skydoku_daily", ArcadeGames.classics.mapNotNull { it.legacyRecordKey }.toSet())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user