Add a setup assistant for unconfigured profiles (#174)

A profile without a callsign of its own now starts in a setup assistant instead
of the twelve-tab settings window. It asks for name, login, locator, bands and
chat category, and optionally for antenna and power, log program, rotator and
AirScout. Login and station can each be taken from another configured profile.

The assistant runs in startRuntime after the profile is resolved and before the
ChatController exists. It works on a ChatPreferences of its own, writes
preferences.xml, and the runtime then reads that file like any stored setting.
It never touches a running session. From the Options menu the runtime is torn
down first and the same profile restarted with the assistant in front.

A station set up anew gets only what the operator confirmed: the bundled
template has several integrations enabled, and the assistant switches off what
was not chosen and names it in its summary. A station left unchanged is written
page by page, only for pages the operator opened. A taken station is the whole
station, every setter listed in wizard-station-setters.txt; a test fails when a
new ChatPreferences setter is classified in neither list.

Changes outside the assistant:
- ChatPreferences.readPreferencesFromXmlFile() returns false when the file could
  not be read or parsed, or its root element is not praktiKST. It reads on as
  before, and its two existing callers ignore the return value.
- ApplicationRuntimeLauncher.switchProfile refuses a second switch while one is
  in progress.
- The Log synch tab's file chooser takes an optional owner dialog.

The design and its reasons are in
docs/superpowers/specs/2026-11-18-einrichtungsassistent-design.md.

Written-by: Claude Fable 5.2
Written-by: DeepSeek V4 Pro
Written-by: Gemini 4 Hydrogen (Antigravity)
Written-by: Codex (GPT-6.2 Sol)
This commit is contained in:
Rsclub2_2 authored and GitHub committed 2026-11-18 23:16:52 +01:00
1 parent b0960a3f04
commit 1dd0139e10
36 files changed
+5768 -25

No files matched your search

@@ -0,0 +1,87 @@
package kst4contest.view;
import kst4contest.controller.ActiveOperatorProfile;
import kst4contest.model.OperatorProfile;
import kst4contest.model.OperatorProfileSelection;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The request to show the setup wizard on the next runtime start is honoured exactly once.
* A request that stuck would open the wizard on every later profile switch.
*/
class ApplicationRuntimeLauncherSetupWizardTest {
@Test
void aRequestIsHonouredOnce() {
assertFalse(ApplicationRuntimeLauncher.consumeSetupWizardRequest(), "nothing was requested");
ApplicationRuntimeLauncher.requestSetupWizard();
assertTrue(ApplicationRuntimeLauncher.consumeSetupWizardRequest());
assertFalse(ApplicationRuntimeLauncher.consumeSetupWizardRequest(), "the request must not stick");
}
@Test
void switchGuardAllowsOnlyOneSwitchAtATime() {
try {
assertTrue(ApplicationRuntimeLauncher.beginSwitch());
assertFalse(ApplicationRuntimeLauncher.beginSwitch(),
"a second switch must be refused while one is in progress");
} finally {
ApplicationRuntimeLauncher.endSwitch();
}
try {
assertTrue(ApplicationRuntimeLauncher.beginSwitch(),
"ending the first switch must release the guard");
} finally {
ApplicationRuntimeLauncher.endSwitch();
}
}
@Test
void aRefusedRerunLeavesTheRequestOfTheRunningSwitchAlone() {
OperatorProfileSelection previous = ActiveOperatorProfile.get();
OperatorProfile profile = new OperatorProfile("wizard-guard-test", "Wizard Guard Test", false, false);
ActiveOperatorProfile.set(new OperatorProfileSelection(profile, "preferences.xml", "worked.db", false));
// A first rerun is under way: it holds the guard and its request waits for startRuntime.
assertTrue(ApplicationRuntimeLauncher.beginSwitch());
ApplicationRuntimeLauncher.requestSetupWizard();
try {
// A second one arrives while the first tears its windows down, and is refused.
assertFalse(ApplicationRuntimeLauncher.rerunSetupWizard());
assertTrue(ApplicationRuntimeLauncher.consumeSetupWizardRequest(),
"the refused rerun took the running switch's request with it: that switch "
+ "would end the session and then start without the wizard");
} finally {
ApplicationRuntimeLauncher.endSwitch();
ApplicationRuntimeLauncher.consumeSetupWizardRequest();
ActiveOperatorProfile.set(previous);
}
}
@Test
void aRefusedRerunLeavesNoRequestOfItsOwn() {
OperatorProfileSelection previous = ActiveOperatorProfile.get();
OperatorProfile profile = new OperatorProfile("wizard-guard-test", "Wizard Guard Test", false, false);
ActiveOperatorProfile.set(new OperatorProfileSelection(profile, "preferences.xml", "worked.db", false));
// A plain profile switch is under way; nobody asked for the wizard.
assertTrue(ApplicationRuntimeLauncher.beginSwitch());
try {
assertFalse(ApplicationRuntimeLauncher.rerunSetupWizard());
assertFalse(ApplicationRuntimeLauncher.consumeSetupWizardRequest(),
"a refused rerun must not hand its wizard to the switch that refused it");
} finally {
ApplicationRuntimeLauncher.endSwitch();
ApplicationRuntimeLauncher.consumeSetupWizardRequest();
ActiveOperatorProfile.set(previous);
}
}
}
@@ -28,6 +28,7 @@ class MainMenuModelTest {
override fun setQrgAsNameInChat() { calls += "setQrgAsNameInChat" }
override fun toggleAwayState() { calls += "toggleAwayState" }
override fun toggleSettingsWindow() { calls += "toggleSettingsWindow" }
override fun openSetupWizard() { calls += "openSetupWizard" }
override fun toggleMonitorWindow() { calls += "toggleMonitorWindow" }
override fun toggleStationMap() { calls += "toggleStationMap" }
override fun useDarkDesign() { calls += "useDarkDesign" }
@@ -181,4 +182,19 @@ class MainMenuModelTest {
"every item must reach an action; one of them did nothing",
)
}
@Test
fun theSetupAssistantIsReachableFromOptionsWhateverTheConnection() {
for (connectionState in On4KstConnectionState.values()) {
val actions = RecordingActions()
val model = model(connectionState = connectionState, actions = actions)
val entry = items(model.single { it.title == "Options" }).single { it.label == "Setup assistant..." }
// Like the profile switch: it gives the session up itself, after asking.
assertTrue(entry.enabled, "the assistant must be reachable while $connectionState")
entry.onClick()
assertEquals("openSetupWizard", actions.calls.last())
}
}
}
@@ -55,6 +55,7 @@ class MainMenuRowScreenTest {
override fun setQrgAsNameInChat() { calls += "setQrgAsNameInChat" }
override fun toggleAwayState() { calls += "toggleAwayState" }
override fun toggleSettingsWindow() { calls += "toggleSettingsWindow" }
override fun openSetupWizard() { calls += "openSetupWizard" }
override fun toggleMonitorWindow() { calls += "toggleMonitorWindow" }
override fun toggleStationMap() { calls += "toggleStationMap" }
override fun useDarkDesign() { calls += "useDarkDesign" }
@@ -116,6 +117,7 @@ class MainMenuRowScreenTest {
Triple("Options", "Set QRG as name in Chat (main category)", "setQrgAsNameInChat"),
Triple("Options", "Show me as AWAY FROM chat!", "toggleAwayState"),
Triple("Options", "Show options", "toggleSettingsWindow"),
Triple("Options", "Setup assistant...", "openSetupWizard"),
Triple("Windows", "Show cluster / stranger QSOs", "toggleMonitorWindow"),
Triple("Windows", "Show / hide station map", "toggleStationMap"),
Triple("Windows", "Use dark mode design", "useDarkDesign"),
@@ -0,0 +1,292 @@
package kst4contest.view.compose.wizard
import androidx.compose.ui.test.ComposeUiTest
import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.hasSetTextAction
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performTextReplacement
import androidx.compose.ui.test.runComposeUiTest
import kst4contest.model.ChatCategory
import kst4contest.model.ChatPreferences
import kst4contest.view.compose.Kst4ContestTheme
import kst4contest.view.i18n.LanguageStore
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.nio.file.Path
import java.util.Locale
/**
* The drawn wizard, clicked the way an operator clicks it. The rules live in
* SetupWizardState and are tested there; this holds the wiring -- that a button reaches the
* state, and that a button which must not work does not.
*/
@OptIn(ExperimentalTestApi::class)
class SetupWizardContentScreenTest {
private fun configuredProfile() =
ChatPreferences(Path.of("setup-wizard-screen-test-unused.xml")).apply {
setStn_loginCallSign("DL0TEST")
setStn_loginPassword("secret")
setStn_loginNameMainCat("Philipp")
setStn_loginLocatorMainCat("JO50AA")
setStn_bandActive144(true)
setLoginChatCategoryMain(ChatCategory(2))
// Stated, not left to the compiled-in default: with a second chat and no second
// category the summary could not be saved.
setLoginToSecondChatEnabled(false)
}
private class Recorded {
var later = 0
val saves = mutableListOf<Boolean>()
}
private fun ComposeUiTest.show(state: SetupWizardState, saveFailed: Boolean = false): Recorded {
val recorded = Recorded()
// English, whatever language an earlier test in this JVM left behind.
val english = LanguageStore({ "en" }, {}, Locale.ENGLISH)
setContent {
Kst4ContestTheme(darkMode = false, baseFontSizeSp = 12f) {
SetupWizardContent(
state = state,
languageStore = english,
saveFailed = saveFailed,
onLater = { recorded.later++ },
onSave = { recorded.saves += it },
)
}
}
return recorded
}
@Test
fun nextDoesNothingUntilBothSourcesAreChosen() = runComposeUiTest {
val state = SetupWizardState(configuredProfile())
show(state)
onNodeWithText("Next").performClick()
assertEquals(WizardPage.ENTRY, state.page, "Next worked without a choice")
onNodeWithText("Leave the login unchanged (DL0TEST)").performClick()
onNodeWithText("Leave the station unchanged (locator JO50AA)").performClick()
assertEquals(WizardSource.KEEP, state.loginSource)
assertEquals(WizardSource.KEEP, state.stationSource)
onNodeWithText("Next").performClick()
assertEquals(WizardPage.PERSONAL, state.page)
}
@Test
fun laterIsReportedAndNothingElse() = runComposeUiTest {
val recorded = show(SetupWizardState(configuredProfile()))
onNodeWithText("Later").performClick()
assertEquals(1, recorded.later)
assertTrue(recorded.saves.isEmpty())
}
@Test
fun theSummaryOffersBothWaysOfSaving() = runComposeUiTest {
val state = SetupWizardState(configuredProfile())
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.next()
val recorded = show(state)
onNodeWithText("Save").performClick()
onNodeWithText("Save and connect").performClick()
assertEquals(listOf(false, true), recorded.saves)
}
@Test
fun aFailedSaveIsToldToTheOperator() = runComposeUiTest {
val state = SetupWizardState(configuredProfile())
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.next()
show(state, saveFailed = true)
onNodeWithText("The settings could not be written. Nothing was changed.").assertExists()
}
@Test
fun theSummaryShowsTheChosenLanguage() = runComposeUiTest {
val state = SetupWizardState(configuredProfile().apply { setGuiOptions_language("de") })
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.next()
show(state)
onNodeWithText("DE").assertExists()
}
/** A first installation: the template's credentials, so the wizard starts from scratch. */
private fun firstInstallation() =
ChatPreferences(Path.of("setup-wizard-screen-test-unused.xml")).apply {
setStn_loginCallSign("DO5AMF")
setStn_loginPassword("changeMe")
setLogsynch_wintestNetworkListenerEnabled(false)
setLogsynch_ucxUDPWkdCallListenerEnabled(true)
setLogsynch_fileBasedWkdCallInterpreterEnabled(false)
// Every other switch stated too, so the summary's wording does not hang on a
// compiled-in default.
setTrxSynch_ucxLogUDPListenerEnabled(false)
setLogsynch_wintestQrgSyncEnabled(false)
setNotify_dxClusterServerEnabled(false)
setStn_pstRotatorEnabled(false)
setAirScout_asUDPListenerEnabled(true)
setLoginToSecondChatEnabled(false)
}
private fun SetupWizardState.walkToTheLogPage() {
name = "Philipp"
next()
callsign = "DL0TEST"
password = "secret"
next()
locator = "JO50AA"
setBand(WizardBand.B144, true)
next()
next()
}
@Test
fun choosingALogProgramOnTheDrawnPageReachesTheState() = runComposeUiTest {
val state = SetupWizardState(firstInstallation())
state.walkToTheLogPage()
assertEquals(WizardPage.LOG, state.page)
show(state)
onNodeWithText("Win-Test").performClick()
assertEquals(WizardLogProgram.WINTEST, state.integrations.logProgram)
onNodeWithText("Take my own frequency from the log program").assertExists()
}
@Test
fun nextRefusesAnUnreadableUdpPortAndAcceptsItsCorrection() = runComposeUiTest {
val state = SetupWizardState(firstInstallation())
state.walkToTheLogPage()
state.integrations.chooseLogProgram(WizardLogProgram.UDP)
val originalPort = state.integrations.udpPort
show(state)
val portField = onNode(hasSetTextAction())
val refusal = onNodeWithText(
"Shared UDP port for QSO and TRX messages [default 12060]:: \"abc\" is not a valid entry.",
)
portField.performTextReplacement("abc")
onNodeWithText("Next").performClick()
assertEquals(originalPort, state.integrations.udpPort)
assertEquals(WizardPage.LOG, state.page)
refusal.assertExists()
portField.performTextReplacement("12061")
refusal.assertExists()
onNodeWithText("Next").performClick()
assertEquals(WizardPage.GEAR, state.page)
assertEquals(12061, state.integrations.udpPort)
refusal.assertDoesNotExist()
}
@Test
fun finishRefusesAnUnreadableUdpPort() = runComposeUiTest {
val state = SetupWizardState(firstInstallation())
state.walkToTheLogPage()
state.integrations.chooseLogProgram(WizardLogProgram.UDP)
show(state)
onNode(hasSetTextAction()).performTextReplacement("abc")
onNodeWithText("Finish").performClick()
assertEquals(WizardPage.LOG, state.page)
}
@Test
fun theSummaryNamesWhatANewStationSwitchesOff() = runComposeUiTest {
val state = SetupWizardState(firstInstallation())
state.walkToTheLogPage()
state.finish()
show(state)
onNodeWithText("Will be switched off: network log synchronisation, AirScout.").assertExists()
}
private fun donor(id: String, name: String, callsign: String, locator: String) =
WizardDonor(id, name, ChatPreferences(Path.of("setup-wizard-screen-donor-unused.xml")).apply {
setStn_loginCallSign(callsign)
setStn_loginPassword("secret")
setStn_loginLocatorMainCat(locator)
setStn_bandActive144(true)
setLoginChatCategoryMain(ChatCategory(2))
setLoginToSecondChatEnabled(false)
})
private fun emptyProfile() =
ChatPreferences(Path.of("setup-wizard-screen-test-unused.xml")).apply {
setStn_loginCallSign("")
setStn_loginPassword("")
setStn_loginLocatorMainCat("JO54ME")
setStn_bandActive144(true)
setLoginChatCategoryMain(ChatCategory(2))
setLoginToSecondChatEnabled(false)
}
@Test
fun aSingleDonorIsNamedInTheOptionAndTakenWithOneClick() = runComposeUiTest {
val state = SetupWizardState(emptyProfile(), listOf(donor("a", "Conteststation", "DL0TEST", "JO50AA")))
show(state)
onNodeWithText("Take the login from profile \"Conteststation\" (DL0TEST)").performClick()
onNodeWithText("Take the station from profile \"Conteststation\" (locator JO50AA)").performClick()
assertEquals(WizardSource.TAKE, state.loginSource)
assertEquals("a", state.loginDonor?.profileId)
assertEquals(WizardSource.TAKE, state.stationSource)
onNodeWithText("Next").performClick()
assertEquals(WizardPage.PERSONAL, state.page)
assertEquals("DL0TEST", state.callsign)
}
@Test
fun withSeveralDonorsNextWaitsForAProfile() = runComposeUiTest {
val state = SetupWizardState(
emptyProfile(),
listOf(donor("a", "Conteststation", "DL0TEST", "JO50AA"), donor("b", "Portabel", "DL0TEST/P", "JN58QA")),
)
show(state)
onNodeWithText("Take the login from another profile").performClick()
onNodeWithText("Set up a new station").performClick()
onNodeWithText("Next").performClick()
assertEquals(WizardPage.ENTRY, state.page, "which profile is not said yet")
}
@Test
fun theSummaryShowsTheFallbackBandForSpots() = runComposeUiTest {
val prefs = configuredProfile().apply {
setStn_bandActive144(false)
setStn_bandActive432(true)
setNotify_optionalFrequencyPrefix("144")
}
val state = SetupWizardState(prefs)
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.next()
show(state)
onNodeWithText("144 MHz").assertExists()
}
}
@@ -0,0 +1,446 @@
package kst4contest.view.compose.wizard
import kst4contest.model.ChatCategory
import kst4contest.model.ChatPreferences
import org.junit.jupiter.api.Assertions.assertArrayEquals
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
/**
* Taking the login or the station from another profile: what is offered, what the answers
* become, what the summary says against the own profile, and what reaches the file.
*/
class SetupWizardDonorTest(@param:TempDir private val directory: Path) {
private fun prefs(configure: ChatPreferences.() -> Unit = {}): ChatPreferences =
ChatPreferences(Path.of("setup-wizard-donor-test-unused.xml")).apply(configure)
/** Every integration switch stated, so no test hangs on a compiled-in default. */
private fun ChatPreferences.integrationsOff() {
setLogsynch_wintestNetworkListenerEnabled(false)
setLogsynch_ucxUDPWkdCallListenerEnabled(false)
setLogsynch_fileBasedWkdCallInterpreterEnabled(false)
setTrxSynch_ucxLogUDPListenerEnabled(false)
setLogsynch_wintestQrgSyncEnabled(false)
setNotify_dxClusterServerEnabled(false)
setStn_pstRotatorEnabled(false)
setAirScout_asUDPListenerEnabled(false)
setTrxSynch_so2rEnabled(false)
setStn_pstRotator2Enabled(false)
}
/** An empty profile, as "new profile" creates it: no login, the template's integrations on. */
private fun emptyProfile() = prefs {
integrationsOff()
setStn_loginCallSign("")
setStn_loginPassword("")
setStn_loginLocatorMainCat("JO54ME")
setStn_bandActive144(true)
setLoginChatCategoryMain(ChatCategory(2))
setLoginToSecondChatEnabled(true)
setLoginChatCategorySecond(ChatCategory(3))
setLogsynch_ucxUDPWkdCallListenerEnabled(true)
setAirScout_asUDPListenerEnabled(true)
}
private fun contestStation() = WizardDonor("contest", "Conteststation", prefs {
integrationsOff()
setStn_loginCallSign("DL0TEST")
setStn_loginPassword("secret")
setStn_loginLocatorMainCat("JO50AA")
setStn_bandActive144(true)
setStn_bandActive432(true)
setLoginChatCategoryMain(ChatCategory(2))
setLoginToSecondChatEnabled(false)
setStn_antennaBeamWidthDeg(28.0)
setStn_qtfDefault(270.0)
setLogsynch_wintestNetworkListenerEnabled(true)
setLogsynch_wintestNetworkPort(9871)
setLogsynch_wintestNetworkStationNameOfKST("KST")
setLogsynch_wintestQrgSyncEnabled(true)
setStn_pstRotatorEnabled(true)
setStn_pstRotatorHost("127.0.0.1")
setStn_pstRotatorPort(12000)
})
private fun portable() = WizardDonor("portable", "Portabel", prefs {
integrationsOff()
setStn_loginCallSign("DL0TEST/P")
setStn_loginPassword("secret")
setStn_loginLocatorMainCat("JN58QA")
setStn_bandActive1240(true)
setLoginChatCategoryMain(ChatCategory(3))
setLoginToSecondChatEnabled(false)
})
@Test
fun withoutDonorsNothingChanges() {
val state = SetupWizardState(emptyProfile())
assertEquals(listOf(WizardSource.NEW), state.loginSources)
assertEquals(listOf(WizardSource.NEW, WizardSource.KEEP), state.stationSources)
assertTrue(state.donors.isEmpty())
}
@Test
fun aDonorAddsTakeBetweenNewAndKeep() {
val state = SetupWizardState(emptyProfile(), listOf(contestStation()))
assertEquals(listOf(WizardSource.NEW, WizardSource.TAKE), state.loginSources)
assertEquals(listOf(WizardSource.NEW, WizardSource.TAKE, WizardSource.KEEP), state.stationSources)
assertTrue(state.hasEntryPage)
assertNull(state.loginSource, "with a choice nothing is preselected")
}
@Test
fun aSingleDonorIsChosenWithTheSource() {
val donor = contestStation()
val state = SetupWizardState(emptyProfile(), listOf(donor))
state.chooseLoginSource(WizardSource.TAKE)
state.chooseStationSource(WizardSource.NEW)
assertEquals(donor, state.loginDonor, "one donor needs no second question")
assertTrue(state.canGoNext)
}
@Test
fun severalDonorsNeedAChoice() {
val contest = contestStation()
val state = SetupWizardState(emptyProfile(), listOf(contest, portable()))
state.chooseLoginSource(WizardSource.TAKE)
state.chooseStationSource(WizardSource.NEW)
assertNull(state.loginDonor)
assertFalse(state.canGoNext, "which profile is not said yet")
state.chooseLoginDonor(contest)
assertTrue(state.canGoNext)
}
@Test
fun aDonorThatIsNotOfferedIsNotAccepted() {
val state = SetupWizardState(emptyProfile(), listOf(contestStation()))
state.chooseLoginSource(WizardSource.TAKE)
val first = state.loginDonor
state.chooseLoginDonor(portable())
assertEquals(first, state.loginDonor)
}
@Test
fun takingTheLoginSkipsItsPageAndLeavesItChangeable() {
val state = SetupWizardState(emptyProfile(), listOf(contestStation()))
state.chooseLoginSource(WizardSource.TAKE)
state.chooseStationSource(WizardSource.KEEP)
state.next()
assertEquals("DL0TEST", state.callsign)
assertEquals("secret", state.password)
assertFalse(state.pages.contains(WizardPage.LOGIN))
state.name = "Philipp"
state.next()
assertEquals(WizardPage.SUMMARY, state.page)
state.edit(WizardPage.LOGIN)
state.callsign = "DL0TEST/P"
state.next()
assertEquals("DL0TEST/P", state.callsign, "a taken callsign gets its /P")
}
@Test
fun takingTheStationLoadsEverythingThePagesShow() {
val state = SetupWizardState(emptyProfile(), listOf(contestStation()))
state.chooseLoginSource(WizardSource.NEW)
state.chooseStationSource(WizardSource.TAKE)
state.next()
assertEquals("JO50AA", state.locator)
assertEquals(setOf(WizardBand.B144, WizardBand.B432), state.bands)
assertEquals(2, state.category)
assertFalse(state.secondChat)
assertEquals(28.0, state.antenna.beamWidthDeg)
assertEquals(WizardLogProgram.WINTEST, state.integrations.logProgram)
assertTrue(state.integrations.rotator)
assertTrue(state.summaryQrgFollow)
assertEquals(
listOf(WizardPage.ENTRY, WizardPage.PERSONAL, WizardPage.LOGIN, WizardPage.SUMMARY),
state.pages,
"a taken station shows no page of its own",
)
}
@Test
fun takingAStationNamesWhatTheOwnProfileLoses() {
val state = SetupWizardState(emptyProfile(), listOf(contestStation()))
state.chooseLoginSource(WizardSource.NEW)
state.chooseStationSource(WizardSource.TAKE)
state.next()
// The own profile had the second chat, the network listener and AirScout on; the
// donor has none of them. Win-Test and the rotator come new and are not "switched off".
assertEquals(
listOf(WizardSwitch.SECOND_CHAT, WizardSwitch.LOG_UDP, WizardSwitch.AIRSCOUT),
state.switchedOff,
)
}
@Test
fun aTakenStationKeepsSeveralLogSources() {
val several = WizardDonor("several", "Zwei Quellen", contestStation().prefs.apply {
setLogsynch_fileBasedWkdCallInterpreterEnabled(true)
})
val state = SetupWizardState(emptyProfile(), listOf(several))
state.chooseLoginSource(WizardSource.NEW)
state.chooseStationSource(WizardSource.TAKE)
state.next()
assertFalse(state.logPageEditable, "the page knows one source and would switch the other off")
state.edit(WizardPage.LOG)
assertFalse(state.pages.contains(WizardPage.LOG))
}
@Test
fun changingTheDonorLoadsItsValues() {
val contest = contestStation()
val other = portable()
val state = SetupWizardState(emptyProfile(), listOf(contest, other))
state.chooseLoginSource(WizardSource.NEW)
state.chooseStationSource(WizardSource.TAKE)
state.chooseStationDonor(contest)
state.next()
assertEquals("JO50AA", state.locator)
state.back()
state.chooseStationDonor(other)
state.next()
assertEquals("JN58QA", state.locator)
assertEquals(setOf(WizardBand.B1240), state.bands)
assertEquals(3, state.category)
assertEquals(WizardLogProgram.NONE, state.integrations.logProgram, "nothing of the first donor is left")
assertFalse(state.integrations.rotator)
}
@Test
fun goingBackToNewDropsWhatWasTaken() {
val state = SetupWizardState(emptyProfile(), listOf(contestStation()))
state.chooseLoginSource(WizardSource.NEW)
state.chooseStationSource(WizardSource.TAKE)
state.next()
state.back()
state.chooseStationSource(WizardSource.NEW)
state.next()
assertEquals("", state.locator)
assertTrue(state.bands.isEmpty())
assertEquals(WizardLogProgram.NONE, state.integrations.logProgram)
assertFalse(state.integrations.rotator)
assertTrue(state.pages.contains(WizardPage.LOG))
}
// --- against real files -------------------------------------------------------------
private fun file(name: String, configure: ChatPreferences.() -> Unit): Path {
val path = directory.resolve(name)
ChatPreferences::class.java.getResourceAsStream(ChatPreferences.PREFERENCE_RESOURCE).use { template ->
Files.copy(requireNotNull(template), path, StandardCopyOption.REPLACE_EXISTING)
}
ChatPreferences(path).apply {
assertTrue(readPreferencesFromXmlFile())
configure()
assertTrue(writePreferencesToXmlFile())
}
return path
}
private fun read(path: Path) = ChatPreferences(path).also { assertTrue(it.readPreferencesFromXmlFile()) }
@Test
fun saveWritesTheWholeTakenStationAndTheTakenLoginIntoTheOwnFile() {
val donorFile = file("donor.xml") {
setStn_loginCallSign("DL0TEST")
setStn_loginPassword("secret")
setStn_loginLocatorMainCat("JO50AA")
setStn_bandActive144(true)
setLoginChatCategoryMain(ChatCategory(2))
setLoginToSecondChatEnabled(false)
setStn_qtfDefault(270.0)
setTrxSynch_so2rEnabled(true)
setStn_pstRotator2Enabled(true)
setStn_pstRotator2Port(12020)
setLogsynch_wintestNetworkListenerEnabled(true)
setLogsynch_wintestNetworkStationNameOfWintestClient1("RUN")
}
val ownFile = file("own.xml") {
setStn_loginCallSign("")
setStn_loginPassword("")
setStn_on4kstServersDns("own.example")
}
val donorBytes = Files.readAllBytes(donorFile)
val own = read(ownFile)
val state = SetupWizardState(own, listOf(WizardDonor("contest", "Conteststation", read(donorFile))))
state.chooseLoginSource(WizardSource.TAKE)
state.chooseStationSource(WizardSource.TAKE)
state.next()
state.name = "Philipp"
state.next()
assertEquals(WizardPage.SUMMARY, state.page)
assertTrue(state.writeTo(own))
val restored = read(ownFile)
assertEquals("DL0TEST", restored.getStn_loginCallSign())
assertEquals("secret", restored.getStn_loginPassword())
assertEquals("Philipp", restored.getStn_loginNameMainCat())
assertEquals("JO50AA", restored.getStn_loginLocatorMainCat())
assertEquals(270.0, restored.getStn_qtfDefault(), "a station value the wizard never asks about")
assertTrue(restored.isTrxSynch_so2rEnabled())
assertTrue(restored.isStn_pstRotator2Enabled())
assertEquals(12020, restored.getStn_pstRotator2Port())
assertTrue(restored.isLogsynch_wintestNetworkListenerEnabled())
assertEquals("RUN", restored.getLogsynch_wintestNetworkStationNameOfWintestClient1())
assertEquals("own.example", restored.getStn_on4kstServersDns(), "not part of the station")
assertArrayEquals(donorBytes, Files.readAllBytes(donorFile), "the donor's file was touched")
}
@Test
fun aPageOpenedAfterTakingOverridesTheCopy() {
val donorFile = file("donor.xml") {
setStn_loginCallSign("DL0TEST")
setStn_loginPassword("secret")
setStn_loginLocatorMainCat("JO50AA")
setStn_bandActive144(true)
setLoginChatCategoryMain(ChatCategory(2))
setLoginToSecondChatEnabled(false)
setStn_pstRotatorEnabled(true)
setStn_pstRotatorHost("127.0.0.1")
setStn_pstRotatorPort(12000)
}
val ownFile = file("own.xml") {
setStn_loginCallSign("")
setStn_loginPassword("")
}
val own = read(ownFile)
val state = SetupWizardState(own, listOf(WizardDonor("contest", "Conteststation", read(donorFile))))
state.chooseLoginSource(WizardSource.TAKE)
state.chooseStationSource(WizardSource.TAKE)
state.next()
state.name = "Philipp"
state.next()
state.edit(WizardPage.GEAR)
state.integrations.rotator = false
state.next()
state.edit(WizardPage.SITE)
state.locator = "JN58QA"
state.next()
assertTrue(state.writeTo(own))
val restored = read(ownFile)
assertFalse(restored.isStn_pstRotatorEnabled(), "the operator switched the taken rotator off")
assertEquals("JN58QA", restored.getStn_loginLocatorMainCat(), "the operator changed the taken locator")
}
@Test
fun takingAStationNamesSo2rAndRotatorTwoWhenTheDonorDropsThem() {
val own = emptyProfile().apply {
setTrxSynch_so2rEnabled(true)
setStn_pstRotator2Enabled(true)
}
val donorOff = contestStation()
val donorOn = WizardDonor("both-on", "Beide an", prefs {
integrationsOff()
setStn_loginCallSign("DL0BOTH")
setStn_loginPassword("secret")
setStn_loginLocatorMainCat("JO50AA")
setStn_bandActive144(true)
setLoginChatCategoryMain(ChatCategory(2))
setLoginToSecondChatEnabled(false)
setTrxSynch_so2rEnabled(true)
setStn_pstRotator2Enabled(true)
})
val takeDrops = SetupWizardState(own, listOf(donorOff)).apply {
chooseLoginSource(WizardSource.NEW)
chooseStationSource(WizardSource.TAKE)
next()
}
assertEquals(
listOf(WizardSwitch.SO2R, WizardSwitch.ROTATOR_2),
takeDrops.switchedOff.takeLast(2),
)
val keep = SetupWizardState(own, listOf(donorOff)).apply {
chooseLoginSource(WizardSource.NEW)
chooseStationSource(WizardSource.KEEP)
next()
}
assertFalse(WizardSwitch.SO2R in keep.switchedOff)
assertFalse(WizardSwitch.ROTATOR_2 in keep.switchedOff)
val takeKeeps = SetupWizardState(own, listOf(donorOn)).apply {
chooseLoginSource(WizardSource.NEW)
chooseStationSource(WizardSource.TAKE)
next()
}
assertFalse(WizardSwitch.SO2R in takeKeeps.switchedOff)
assertFalse(WizardSwitch.ROTATOR_2 in takeKeeps.switchedOff)
val ownRotator2WithoutSo2r = emptyProfile().apply {
setTrxSynch_so2rEnabled(false)
setStn_pstRotator2Enabled(true)
}
val noSo2r = SetupWizardState(ownRotator2WithoutSo2r, listOf(donorOff)).apply {
chooseLoginSource(WizardSource.NEW)
chooseStationSource(WizardSource.TAKE)
next()
}
assertFalse(WizardSwitch.ROTATOR_2 in noSo2r.switchedOff)
assertFalse(WizardSwitch.SO2R in noSo2r.switchedOff)
}
@Test
fun theSummaryFallbackBandFollowsTheStationSource() {
val own = emptyProfile().apply { setNotify_optionalFrequencyPrefix("144") }
val donor = WizardDonor("uhf", "UHF", prefs {
integrationsOff()
setStn_loginCallSign("DL0UHF")
setStn_loginPassword("secret")
setStn_loginLocatorMainCat("JO50AA")
setStn_bandActive432(true)
setLoginChatCategoryMain(ChatCategory(2))
setLoginToSecondChatEnabled(false)
setNotify_optionalFrequencyPrefix("432")
})
val take = SetupWizardState(own, listOf(donor)).apply {
chooseLoginSource(WizardSource.NEW)
chooseStationSource(WizardSource.TAKE)
next()
}
assertEquals("432", take.summaryFallbackBand)
val keep = SetupWizardState(own, listOf(donor)).apply {
chooseLoginSource(WizardSource.NEW)
chooseStationSource(WizardSource.KEEP)
next()
}
assertEquals("144", keep.summaryFallbackBand)
val fresh = SetupWizardState(own, listOf(donor)).apply {
chooseLoginSource(WizardSource.NEW)
chooseStationSource(WizardSource.NEW)
next()
}
assertEquals("144", fresh.summaryFallbackBand)
}
}
@@ -0,0 +1,224 @@
package kst4contest.view.compose.wizard
import kst4contest.model.ChatPreferences
import org.junit.jupiter.api.Assertions.assertArrayEquals
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Assumptions
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
/** When the wizard opens at all, decided without a window. */
class SetupWizardLauncherTest(@param:TempDir private val directory: Path) {
private fun templateFile(): Path {
val file = directory.resolve("preferences.xml")
ChatPreferences::class.java.getResourceAsStream(ChatPreferences.PREFERENCE_RESOURCE).use { template ->
Files.copy(requireNotNull(template), file, StandardCopyOption.REPLACE_EXISTING)
}
return file
}
private fun configuredFile(): Path {
val file = templateFile()
ChatPreferences(file).apply {
assertTrue(readPreferencesFromXmlFile())
setStn_loginCallSign("DL0TEST")
setStn_loginPassword("secret")
assertTrue(writePreferencesToXmlFile())
}
return file
}
private val neverShown: (SetupWizardState, ChatPreferences) -> SetupWizardOutcome =
{ _, _ -> throw AssertionError("the wizard must not open here") }
@Test
fun anUnconfiguredProfileOpensTheWizard() {
var shown = 0
val outcome = SetupWizardLauncher.run(ChatPreferences(templateFile()), forced = false) { _, _ ->
shown++
SetupWizardOutcome.LATER
}
assertEquals(1, shown)
assertEquals(SetupWizardOutcome.LATER, outcome)
}
@Test
fun aConfiguredProfileStartsWithoutTheWizard() {
assertEquals(
SetupWizardOutcome.NOT_SHOWN,
SetupWizardLauncher.run(ChatPreferences(configuredFile()), forced = false, neverShown),
)
}
@Test
fun theMenuOpensItOnAConfiguredProfileToo() {
val outcome = SetupWizardLauncher.run(ChatPreferences(configuredFile()), forced = true) { state, _ ->
assertEquals(listOf(WizardSource.NEW, WizardSource.KEEP), state.loginSources)
SetupWizardOutcome.SAVED
}
assertEquals(SetupWizardOutcome.SAVED, outcome)
}
@Test
fun anUnreadableFileNeverOpensTheWizard() {
val garbage = directory.resolve("broken.xml")
Files.writeString(garbage, "this is not xml <<<")
val before = Files.readAllBytes(garbage)
// Forced as well: a wizard over a file it could not read would save over it.
assertEquals(
SetupWizardOutcome.NOT_SHOWN,
SetupWizardLauncher.run(ChatPreferences(garbage), forced = true, neverShown),
)
assertArrayEquals(before, Files.readAllBytes(garbage), "the unreadable file was touched")
}
@Test
fun aFileTheReaderThrowsOnNeverOpensTheWizard() {
val file = templateFile()
val original = Files.readString(file)
assertTrue(original.contains("<ChatCategory>2</ChatCategory>"))
Files.writeString(file, original.replace("<ChatCategory>2</ChatCategory>", "<ChatCategory>2.0</ChatCategory>"))
val before = Files.readAllBytes(file)
assertEquals(
SetupWizardOutcome.NOT_SHOWN,
SetupWizardLauncher.run(ChatPreferences(file), forced = true, neverShown),
)
assertArrayEquals(before, Files.readAllBytes(file), "the unreadable file was touched")
}
@Test
fun aFailedSaveKeepsTheWizardOpen() {
val source = ChatPreferences(templateFile()).apply { assertTrue(readPreferencesFromXmlFile()) }
val state = SetupWizardState(source).apply {
name = "Philipp"
next()
callsign = "DL0TEST"
password = "secret"
next()
locator = "JO50AA"
setBand(WizardBand.B144, true)
}
val unwritable = ChatPreferences(Files.createDirectory(directory.resolve("not-a-file")))
assertNull(saveFromWizard(state, unwritable, connect = true), "a failed write must not close the wizard")
}
@Test
fun aSaveReportsWhetherToConnect() {
val file = templateFile()
val prefs = ChatPreferences(file).apply { assertTrue(readPreferencesFromXmlFile()) }
val state = SetupWizardState(prefs).apply {
name = "Philipp"
next()
callsign = "DL0TEST"
password = "secret"
next()
locator = "JO50AA"
setBand(WizardBand.B144, true)
}
assertEquals(SetupWizardOutcome.SAVED, saveFromWizard(state, prefs, connect = false))
assertEquals(SetupWizardOutcome.SAVED_AND_CONNECT, saveFromWizard(state, prefs, connect = true))
}
private fun profileFile(name: String, callsign: String, password: String): Path {
val file = directory.resolve(name)
ChatPreferences::class.java.getResourceAsStream(ChatPreferences.PREFERENCE_RESOURCE).use { template ->
Files.copy(requireNotNull(template), file, StandardCopyOption.REPLACE_EXISTING)
}
ChatPreferences(file).apply {
assertTrue(readPreferencesFromXmlFile())
setStn_loginCallSign(callsign)
setStn_loginPassword(password)
assertTrue(writePreferencesToXmlFile())
}
return file
}
@Test
fun onlyConfiguredReadableProfilesBecomeDonors() {
val configured = profileFile("configured.xml", "DL0TEST", "secret")
val emptyLogin = profileFile("empty.xml", "", "")
val template = profileFile("template.xml", "DO5AMF", "changeMe")
val garbage = directory.resolve("garbage.xml").also { Files.writeString(it, "this is not xml <<<") }
val donors = loadDonors(
listOf(
DonorCandidate("a", "Conteststation", configured),
DonorCandidate("b", "Leer", emptyLogin),
DonorCandidate("c", "Vorlage", template),
DonorCandidate("d", "Kaputt", garbage),
DonorCandidate("e", "Fehlt", directory.resolve("missing.xml")),
)
)
assertEquals(listOf("a"), donors.map { it.profileId })
assertEquals("Conteststation", donors.single().displayName)
assertEquals("DL0TEST", donors.single().callsign)
}
@Test
fun aMissingDonorFileIsNotCreated() {
val missing = directory.resolve("missing.xml")
loadDonors(listOf(DonorCandidate("e", "Fehlt", missing)))
assertFalse(Files.exists(missing), "looking for a donor must not create its file")
}
@Test
fun readingADonorLeavesItsFileAlone() {
val configured = profileFile("configured.xml", "DL0TEST", "secret")
val before = Files.readAllBytes(configured)
loadDonors(listOf(DonorCandidate("a", "Conteststation", configured)))
assertArrayEquals(before, Files.readAllBytes(configured))
}
@Test
fun donorsAreOnlyLoadedWhenTheWizardOpens() {
var loaded = 0
val donors = { loaded++; emptyList<WizardDonor>() }
SetupWizardLauncher.run(ChatPreferences(configuredFile()), forced = false, donors, neverShown)
assertEquals(0, loaded, "a configured profile starts without reading other profiles")
var seen: List<WizardDonor>? = null
SetupWizardLauncher.run(ChatPreferences(templateFile()), forced = false, donors) { state, _ ->
seen = state.donors
SetupWizardOutcome.LATER
}
assertEquals(1, loaded)
assertEquals(emptyList<WizardDonor>(), seen)
}
@Test
fun aLinkedDirectoryToTheActiveProfileIsNotOfferedAsItsOwnDonor() {
val dirB = Files.createDirectory(directory.resolve("b"))
val fileInB = dirB.resolve("preferences.xml")
Files.copy(configuredFile(), fileInB, StandardCopyOption.REPLACE_EXISTING)
val linkA = directory.resolve("a")
val linked = runCatching { Files.createSymbolicLink(linkA, dirB) }
Assumptions.assumeTrue(
linked.isSuccess,
"file system refused symbolic link: ${linked.exceptionOrNull()?.message}",
)
val candidates = listOf(DonorCandidate("b", "B", fileInB))
assertTrue(loadDonors(candidates, activeFile = linkA.resolve("preferences.xml")).isEmpty())
assertEquals(listOf("b"), loadDonors(candidates).map { it.profileId })
}
}
@@ -0,0 +1,628 @@
package kst4contest.view.compose.wizard
import kst4contest.model.ChatCategory
import kst4contest.model.ChatPreferences
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.nio.file.Path
/**
* The wizard's rules without a window: which pages appear, what they start with, and when
* the operator may go on. Nothing here reads or writes a file.
*/
class SetupWizardStateTest {
/** Preferences that never touch a file: the path is only read by read/write calls. */
private fun prefs(configure: ChatPreferences.() -> Unit = {}): ChatPreferences =
ChatPreferences(Path.of("setup-wizard-state-test-unused.xml")).apply(configure)
private fun freshInstallation() = prefs {
setStn_loginCallSign("DO5AMF")
setStn_loginPassword("changeMe")
setStn_loginNameMainCat("KST4Contest1263")
setStn_loginLocatorMainCat("JO54ME")
setStn_bandActive144(true)
setLoginChatCategoryMain(ChatCategory(2))
setLoginToSecondChatEnabled(true)
setLoginChatCategorySecond(ChatCategory(3))
}
private fun duplicatedProfile() = prefs {
setStn_loginCallSign("")
setStn_loginPassword("")
setStn_loginNameMainCat("Other Operator")
setStn_loginLocatorMainCat("JO50AA")
setStn_bandActive144(true)
setStn_bandActive432(true)
setLoginChatCategoryMain(ChatCategory(2))
setLoginToSecondChatEnabled(false)
}
private fun configuredProfile() = duplicatedProfile().apply {
setStn_loginCallSign("DL0TEST")
setStn_loginPassword("secret")
setStn_loginNameMainCat("Philipp")
}
/** Fills every mandatory answer of a first installation, leaving the wizard on SITE. */
private fun SetupWizardState.fillFirstInstallation() {
name = "Philipp"
next()
callsign = "DL0TEST"
password = "secret"
next()
locator = "JO50AA"
setBand(WizardBand.B144, true)
}
@Test
fun aFreshInstallationHasNoEntryPageAndStartsEmpty() {
val state = SetupWizardState(freshInstallation())
assertFalse(state.hasEntryPage)
assertEquals(WizardPage.PERSONAL, state.page)
assertEquals(
listOf(
WizardPage.PERSONAL, WizardPage.LOGIN, WizardPage.SITE,
WizardPage.ANTENNA, WizardPage.LOG, WizardPage.GEAR, WizardPage.SUMMARY,
),
state.pages,
)
assertEquals("", state.name, "the template's name is nobody's name")
assertEquals("", state.callsign)
assertEquals("", state.locator)
assertTrue(state.bands.isEmpty())
assertNull(state.category)
assertFalse(state.secondChat)
}
@Test
fun aDuplicatedProfileIsAskedOnlyAboutTheStation() {
val state = SetupWizardState(duplicatedProfile())
assertEquals(listOf(WizardSource.NEW), state.loginSources)
assertEquals(listOf(WizardSource.NEW, WizardSource.KEEP), state.stationSources)
assertTrue(state.hasEntryPage)
assertEquals(WizardPage.ENTRY, state.page)
assertEquals(WizardSource.NEW, state.loginSource, "a single option is chosen already")
assertNull(state.stationSource, "nothing is preselected where there is a choice")
assertFalse(state.canGoNext)
}
@Test
fun aConfiguredProfileMayKeepBoth() {
val state = SetupWizardState(configuredProfile())
assertEquals(listOf(WizardSource.NEW, WizardSource.KEEP), state.loginSources)
assertEquals(listOf(WizardSource.NEW, WizardSource.KEEP), state.stationSources)
assertEquals("Philipp", state.name, "a configured profile keeps its operator's name")
}
@Test
fun keepingTheStationSkipsItsStepAndCarriesTheStoredValues() {
val state = SetupWizardState(duplicatedProfile())
state.chooseStationSource(WizardSource.KEEP)
state.next()
assertEquals(
listOf(WizardPage.ENTRY, WizardPage.PERSONAL, WizardPage.LOGIN, WizardPage.SUMMARY),
state.pages,
)
assertEquals("JO50AA", state.locator)
assertEquals(setOf(WizardBand.B144, WizardBand.B432), state.bands)
assertEquals(2, state.category)
}
@Test
fun aNewStationStartsEmptyEvenOnAProfileThatHasOne() {
val state = SetupWizardState(duplicatedProfile())
state.chooseStationSource(WizardSource.NEW)
state.next()
assertEquals("", state.locator)
assertTrue(state.bands.isEmpty())
assertNull(state.category)
assertTrue(state.pages.contains(WizardPage.SITE))
}
@Test
fun goingBackToTheEntryPageAndOnAgainKeepsWhatWasTyped() {
val state = SetupWizardState(duplicatedProfile())
state.chooseStationSource(WizardSource.NEW)
state.next()
state.name = "Philipp"
state.back()
state.next()
assertEquals("Philipp", state.name)
state.next()
state.callsign = "DL0TEST"
state.back()
state.back()
state.chooseStationSource(WizardSource.KEEP)
state.next()
assertEquals("JO50AA", state.locator, "a changed source loads its own values")
state.next()
assertEquals("DL0TEST", state.callsign, "the login source did not change")
}
@Test
fun callsignsWithSuffixAndLowerCaseAreAccepted() {
listOf("DL0TEST", "DL0TEST/P", "DO5AMF-2", "do5amf", " DL0TEST ").forEach {
assertTrue(SetupWizardState.isPlausibleCallsign(it), "'$it' must be accepted")
}
listOf("", "DL", "ABC", "123", "DL0 TEST", "DL0TEST|X", "DL0-TEST-2", "DL0TEST/").forEach {
assertFalse(SetupWizardState.isPlausibleCallsign(it), "'$it' must be refused")
}
}
@Test
fun onlyASixCharacterLocatorIsAccepted() {
listOf("JO50AA", "jo50aa", " JN49FL ").forEach {
assertTrue(SetupWizardState.isLocator(it), "'$it' must be accepted")
}
listOf("", "JO50", "JO50AAA", "SS50AA", "JO50YY", "JO5OAA").forEach {
assertFalse(SetupWizardState.isLocator(it), "'$it' must be refused")
}
}
@Test
fun theCategoryIsSuggestedFromTheLowestBand() {
assertNull(SetupWizardState.suggestCategory(emptySet()))
assertEquals(1, SetupWizardState.suggestCategory(setOf(WizardBand.B50, WizardBand.B144)))
assertEquals(1, SetupWizardState.suggestCategory(setOf(WizardBand.B70)))
assertEquals(2, SetupWizardState.suggestCategory(setOf(WizardBand.B144, WizardBand.B1240)))
assertEquals(2, SetupWizardState.suggestCategory(setOf(WizardBand.B432)))
assertEquals(3, SetupWizardState.suggestCategory(setOf(WizardBand.B1240, WizardBand.B10G)))
}
@Test
fun theSuggestionFollowsTheBandsUntilTheOperatorChooses() {
val state = SetupWizardState(freshInstallation())
state.setBand(WizardBand.B1240, true)
assertEquals(3, state.category)
state.setBand(WizardBand.B144, true)
assertEquals(2, state.category)
state.chooseCategory(3)
state.setBand(WizardBand.B50, true)
assertEquals(3, state.category, "an operator's choice is not overwritten")
assertEquals(1, state.suggestedCategory, "the suggestion is still shown")
}
@Test
fun aSecondChatNeedsADifferentCategory() {
val state = SetupWizardState(freshInstallation())
state.fillFirstInstallation()
assertTrue(state.canGoNext)
state.chooseSecondChat(true)
assertFalse(state.canGoNext, "the second chat has no category yet")
assertFalse(state.secondCategoryOptions.contains(2), "the main category is not offered twice")
state.secondCategory = 3
assertTrue(state.canGoNext)
state.chooseCategory(3)
assertNull(state.secondCategory, "the same chat cannot be opened twice")
assertFalse(state.canGoNext)
}
@Test
fun finishNeedsEveryMandatoryAnswer() {
val state = SetupWizardState(freshInstallation())
state.name = "Philipp"
assertFalse(state.canFinish)
state.next()
state.callsign = "DL0TEST"
state.password = "secret"
assertFalse(state.canFinish, "a new station still lacks its locator")
state.next()
state.locator = "JO50AA"
assertFalse(state.canFinish, "no band yet")
state.setBand(WizardBand.B144, true)
assertTrue(state.canFinish)
state.finish()
assertEquals(WizardPage.SUMMARY, state.page)
assertTrue(state.mandatoryComplete)
assertFalse(state.canFinish, "the summary has Save instead")
}
@Test
fun aKeptStationLetsTheOperatorFinishAfterTheLogin() {
val state = SetupWizardState(duplicatedProfile())
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.name = "Philipp"
state.next()
state.callsign = "DL0TEST/P"
state.password = "secret"
assertTrue(state.canFinish)
}
@Test
fun aRefusedEntryIsOnlyShownOnceSomethingWasTyped() {
val state = SetupWizardState(freshInstallation())
assertFalse(state.callsignRefused, "an empty field is not an error yet")
state.callsign = "DL"
assertTrue(state.callsignRefused)
state.callsign = "DL0TEST"
assertFalse(state.callsignRefused)
assertFalse(state.locatorRefused)
state.locator = "JO50"
assertTrue(state.locatorRefused)
}
@Test
fun changeFromTheSummaryOpensAStepThatWasSkipped() {
val state = SetupWizardState(configuredProfile())
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.next()
assertEquals(WizardPage.SUMMARY, state.page)
state.edit(WizardPage.LOGIN)
assertEquals(WizardPage.LOGIN, state.page)
assertEquals("DL0TEST", state.callsign, "the kept value is there to be changed")
state.callsign = "DL0TEST/P"
state.next()
assertEquals(WizardPage.SUMMARY, state.page)
}
@Test
fun keepingAStationWithMissingLocatorKeepsTheSitePageInTheCourse() {
val state = SetupWizardState(duplicatedProfile().apply { setStn_loginLocatorMainCat("") })
state.chooseStationSource(WizardSource.KEEP)
state.next()
assertTrue(state.pages.contains(WizardPage.SITE))
state.name = "Philipp"
state.next()
state.callsign = "DL0TEST"
state.password = "secret"
state.next()
assertEquals(WizardPage.SITE, state.page)
assertEquals(setOf(WizardBand.B144, WizardBand.B432), state.bands)
assertEquals(2, state.category)
}
@Test
fun keepingALoginWithMissingPasswordKeepsTheLoginPageInTheCourse() {
val state = SetupWizardState(configuredProfile().apply { setStn_loginPassword("") })
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
assertTrue(state.pages.contains(WizardPage.LOGIN))
assertEquals("DL0TEST", state.callsign)
assertEquals("", state.password)
assertFalse(state.mandatoryComplete)
}
@Test
fun keepingAnUnknownCategoryIsIncompleteAndKeepsTheSitePage() {
val state = SetupWizardState(configuredProfile().apply { setLoginChatCategoryMain(ChatCategory(13)) })
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
assertFalse(state.mandatoryComplete)
assertTrue(state.pages.contains(WizardPage.SITE))
}
@Test
fun keepingValidCategoriesOutsideTheBandSuggestionsCompletesAndSkipsSite() {
val state = SetupWizardState(
configuredProfile().apply {
setLoginChatCategoryMain(ChatCategory(7))
setLoginToSecondChatEnabled(true)
setLoginChatCategorySecond(ChatCategory(9))
},
)
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
assertTrue(state.mandatoryComplete)
assertFalse(state.pages.contains(WizardPage.SITE))
}
@Test
fun storablePasswordsAndNamesRejectDelimitersAndOuterWhitespace() {
listOf("secret", "se cret").forEach {
assertTrue(SetupWizardState.isStorablePassword(it), "'$it' must be accepted")
}
listOf("", " ", " secret", "secret ", "se|cret", "se\ncret", "se\rcret").forEach {
assertFalse(SetupWizardState.isStorablePassword(it), "'$it' must be refused")
}
listOf("Philipp", "Philipp W").forEach {
assertTrue(SetupWizardState.isStorableName(it), "'$it' must be accepted")
}
listOf("", " ", "Phil|ipp", "Phil\nipp", "Phil\ripp").forEach {
assertFalse(SetupWizardState.isStorableName(it), "'$it' must be refused")
}
}
@Test
fun aRefusedPasswordOrNameIsReportedAndBlocksCompletion() {
val state = SetupWizardState(freshInstallation())
assertFalse(state.nameRefused)
state.name = " "
assertFalse(state.nameRefused)
assertFalse(state.canGoNext)
state.name = "Phil|ipp"
assertTrue(state.nameRefused)
assertFalse(state.canGoNext)
state.fillFirstInstallation()
state.back()
assertEquals(WizardPage.LOGIN, state.page)
assertFalse(state.passwordRefused)
listOf(" secret", "secret ", " ", "se|cret", "se\ncret").forEach { refused ->
state.password = refused
assertTrue(state.passwordRefused, "'$refused' must set passwordRefused")
assertFalse(state.canGoNext, "'$refused' must block Next on login")
assertFalse(state.mandatoryComplete, "'$refused' must block mandatoryComplete")
}
state.password = ""
assertFalse(state.passwordRefused)
assertFalse(state.canGoNext)
state.password = "se cret"
assertFalse(state.passwordRefused)
assertTrue(state.canGoNext)
assertTrue(state.mandatoryComplete)
}
@Test
fun keepingALoginWithAStorablePasswordSkipsTheLoginPage() {
val state = SetupWizardState(configuredProfile())
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
assertFalse(state.pages.contains(WizardPage.LOGIN))
assertEquals(WizardPage.PERSONAL, state.page)
state.next()
assertEquals(WizardPage.SUMMARY, state.page)
}
/** A first installation whose stored integrations are those of the bundled template. */
private fun freshInstallationLikeTheTemplate() = freshInstallation().apply {
setLogsynch_wintestNetworkListenerEnabled(false)
setLogsynch_ucxUDPWkdCallListenerEnabled(true)
setLogsynch_fileBasedWkdCallInterpreterEnabled(true)
setTrxSynch_ucxLogUDPListenerEnabled(true)
setLogsynch_wintestQrgSyncEnabled(false)
setNotify_dxClusterServerEnabled(true)
setStn_pstRotatorEnabled(false)
setAirScout_asUDPListenerEnabled(true)
setLogsynch_ucxUDPWkdCallListenerPort(12060)
}
/** A duplicated profile at a Win-Test station with a rotator. */
private fun duplicatedWinTestStation() = duplicatedProfile().apply {
setLogsynch_wintestNetworkListenerEnabled(true)
setLogsynch_wintestNetworkPort(9871)
setLogsynch_wintestNetworkStationNameOfKST("KST")
setLogsynch_ucxUDPWkdCallListenerEnabled(false)
setLogsynch_fileBasedWkdCallInterpreterEnabled(false)
setLogsynch_wintestQrgSyncEnabled(true)
setTrxSynch_ucxLogUDPListenerEnabled(false)
setNotify_dxClusterServerEnabled(false)
setStn_pstRotatorEnabled(true)
setStn_pstRotatorHost("127.0.0.1")
setStn_pstRotatorPort(12000)
setAirScout_asUDPListenerEnabled(false)
setTrxSynch_so2rEnabled(false)
}
@Test
fun aNewStationStartsWithEveryIntegrationOff() {
val state = SetupWizardState(freshInstallationLikeTheTemplate())
assertEquals(WizardLogProgram.NONE, state.integrations.logProgram)
assertFalse(state.integrations.qrgFollow)
assertFalse(state.integrations.clusterServer)
assertFalse(state.integrations.rotator)
assertFalse(state.integrations.airScout)
assertEquals(
listOf(
WizardSwitch.SECOND_CHAT, WizardSwitch.LOG_UDP, WizardSwitch.LOG_FILE,
WizardSwitch.QRG_FOLLOW, WizardSwitch.CLUSTER_SERVER, WizardSwitch.AIRSCOUT,
),
state.switchedOff,
"the summary names everything the template had on",
)
}
@Test
fun theNewPagesComeAfterTheLocationAndCanBeWalkedThrough() {
val state = SetupWizardState(freshInstallationLikeTheTemplate())
state.fillFirstInstallation()
state.next()
assertEquals(WizardPage.ANTENNA, state.page)
assertTrue(state.canGoNext, "the antenna values are proposals and valid as they stand")
state.next()
assertEquals(WizardPage.LOG, state.page)
state.next()
assertEquals(WizardPage.GEAR, state.page)
state.next()
assertEquals(WizardPage.SUMMARY, state.page)
state.back()
assertEquals(WizardPage.GEAR, state.page)
}
@Test
fun finishingEarlyStillSwitchesANewStationsIntegrationsOff() {
val state = SetupWizardState(freshInstallationLikeTheTemplate())
state.fillFirstInstallation()
assertTrue(state.canFinish)
state.finish()
assertEquals(WizardPage.SUMMARY, state.page)
assertTrue(state.switchedOff.contains(WizardSwitch.LOG_UDP), "a skipped page of a new station still applies")
assertTrue(state.switchedOff.contains(WizardSwitch.AIRSCOUT))
}
@Test
fun aKeptStationSkipsTheNewPagesAndSwitchesNothingOff() {
val state = SetupWizardState(duplicatedWinTestStation())
state.chooseStationSource(WizardSource.KEEP)
state.next()
assertEquals(
listOf(WizardPage.ENTRY, WizardPage.PERSONAL, WizardPage.LOGIN, WizardPage.SUMMARY),
state.pages,
)
assertEquals(WizardLogProgram.WINTEST, state.integrations.logProgram, "the summary shows what is stored")
assertTrue(state.integrations.rotator)
assertEquals(emptyList<WizardSwitch>(), state.switchedOff)
assertTrue(state.logPageEditable)
}
@Test
fun changeFromTheSummaryOpensANewPageOfAKeptStation() {
val state = SetupWizardState(duplicatedWinTestStation())
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.name = "Philipp"
state.next()
state.callsign = "DL0TEST"
state.password = "secret"
state.next()
assertEquals(WizardPage.SUMMARY, state.page)
state.edit(WizardPage.GEAR)
assertEquals(WizardPage.GEAR, state.page)
state.integrations.rotator = false
state.next()
assertEquals(WizardPage.SUMMARY, state.page)
assertEquals(listOf(WizardSwitch.ROTATOR), state.switchedOff)
}
@Test
fun aKeptStationWithSeveralLogSourcesCannotOpenTheLogPage() {
val state = SetupWizardState(duplicatedProfile().apply {
setLogsynch_wintestNetworkListenerEnabled(false)
setLogsynch_ucxUDPWkdCallListenerEnabled(true)
setLogsynch_fileBasedWkdCallInterpreterEnabled(true)
})
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.name = "Philipp"
state.next()
state.callsign = "DL0TEST"
state.password = "secret"
state.next()
assertFalse(state.logPageEditable, "the page knows one source and would switch the other off")
state.edit(WizardPage.LOG)
assertEquals(WizardPage.SUMMARY, state.page, "the log page must stay shut")
state.edit(WizardPage.GEAR)
assertEquals(WizardPage.GEAR, state.page, "the other pages are not affected")
}
@Test
fun anInvalidOptionalPageBlocksSaving() {
val state = SetupWizardState(freshInstallationLikeTheTemplate())
state.fillFirstInstallation()
state.next()
state.next()
assertEquals(WizardPage.LOG, state.page)
state.integrations.chooseLogProgram(WizardLogProgram.UDP)
state.integrations.udpPort = 0
assertFalse(state.canGoNext)
assertFalse(state.canFinish, "a summary that cannot be saved helps nobody")
assertFalse(state.mandatoryComplete)
state.integrations.udpPort = 12060
assertTrue(state.canGoNext)
assertTrue(state.mandatoryComplete)
}
@Test
fun antennaValuesTypedForANewStationAreGoneWhenTheStationIsKeptAfterAll() {
val profile = duplicatedWinTestStation().apply { setStn_antennaBeamWidthDeg(28.0) }
val state = SetupWizardState(profile)
state.chooseStationSource(WizardSource.NEW)
state.next()
state.name = "Philipp"
state.next()
state.callsign = "DL0TEST"
state.password = "secret"
state.next()
state.locator = "JO50AA"
state.setBand(WizardBand.B144, true)
state.next()
assertEquals(WizardPage.ANTENNA, state.page)
state.antenna.beamWidthDeg = 99.0
repeat(4) { state.back() }
assertEquals(WizardPage.ENTRY, state.page)
state.chooseStationSource(WizardSource.KEEP)
state.next()
assertFalse(state.pages.contains(WizardPage.ANTENNA), "a kept station does not write the antenna page")
assertEquals(
28.0,
state.antenna.beamWidthDeg,
"the summary must not show a value that Save will not write",
)
}
@Test
fun theSummaryOfAKeptStationShowsWhatSaveLeavesOn() {
// No log source, but the DX cluster server and a frequency source are on.
val state = SetupWizardState(duplicatedWinTestStation().apply {
setLogsynch_wintestNetworkListenerEnabled(false)
setLogsynch_wintestQrgSyncEnabled(true)
setNotify_dxClusterServerEnabled(true)
})
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.name = "Philipp"
state.next()
state.callsign = "DL0TEST"
state.password = "secret"
state.next()
assertEquals(WizardPage.SUMMARY, state.page)
assertTrue(state.summaryClusterServer, "Save leaves it on, so the summary must not say no")
assertTrue(state.summaryQrgFollow)
assertFalse(state.switchedOff.contains(WizardSwitch.CLUSTER_SERVER))
// Once the log page is part of the run its answers count, and what they drop is named.
state.edit(WizardPage.LOG)
state.next()
assertFalse(state.summaryClusterServer)
assertFalse(state.summaryQrgFollow)
assertTrue(state.switchedOff.containsAll(listOf(WizardSwitch.QRG_FOLLOW, WizardSwitch.CLUSTER_SERVER)))
}
}
@@ -0,0 +1,115 @@
package kst4contest.view.compose.wizard
import kst4contest.model.ChatPreferences
import kst4contest.testing.Await.awaitUntil
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assumptions.assumeFalse
import org.junit.jupiter.api.Test
import java.awt.Dialog
import java.awt.EventQueue
import java.awt.GraphicsEnvironment
import java.awt.Window
import java.nio.file.Path
import java.time.Duration
import java.util.concurrent.Executors
import java.util.concurrent.Future
import java.util.concurrent.TimeUnit
/**
* The wizard's dialog must open from both threads that open it: `main` at startup, and the
* event thread when the menu rebuilds the runtime. A latch-based wait deadlocked the profile
* picker in exactly the second case; see OperatorProfilePickerWindow.
*/
class SetupWizardWindowTest {
private companion object {
fun prefs() = ChatPreferences(Path.of("setup-wizard-window-test-unused.xml"))
val wizardTitle = wizardLanguageStore(SetupWizardState(prefs())).strings.wizardTitle
}
private fun showingDialog(): Window? =
Window.getWindows().firstOrNull {
it is Dialog && it.isShowing && it.javaClass.name.contains("ComposeDialog") && it.title == wizardTitle
}
/** Removes whatever dialog this test still has showing, without waiting and without failing again. */
private fun disposeLeftoverDialog() {
EventQueue.invokeLater {
showingDialog()?.dispose()
}
}
private fun <T> showWithInterruptedCleanup(show: () -> T): T {
try {
return show()
} catch (interrupted: InterruptedException) {
// invokeAndWait can post the open event after the test's first cleanup was queued.
disposeLeftoverDialog()
throw interrupted
}
}
private val closer = Executors.newSingleThreadExecutor()
/** Closes the dialog the way its X does, as soon as it is on screen. */
private fun closeOnceShowing(): Future<*> =
closer.submit {
awaitUntil(Duration.ofSeconds(10), "the wizard's dialog never appeared") {
showingDialog() != null
}
EventQueue.invokeLater {
val window = showingDialog()
window?.dispatchEvent(java.awt.event.WindowEvent(window, java.awt.event.WindowEvent.WINDOW_CLOSING))
}
}
@Test
fun closingTheWindowCountsAsLater() {
assumeFalse(GraphicsEnvironment.isHeadless(), "needs a display")
val worker = Executors.newSingleThreadExecutor()
try {
val closing = closeOnceShowing()
val prefs = prefs()
val call = worker.submit<SetupWizardOutcome> {
showWithInterruptedCleanup { SetupWizardWindow.show(SetupWizardState(prefs), prefs) }
}
// A dialog that never appears must fail the test, not hang it.
val outcome = call.get(20, TimeUnit.SECONDS)
assertEquals(SetupWizardOutcome.LATER, outcome)
assertEquals("", prefs.getStn_loginCallSign(), "closing the window wrote something")
closing.get(1, TimeUnit.SECONDS)
} finally {
disposeLeftoverDialog()
worker.shutdownNow()
closer.shutdownNow()
}
}
@Test
fun opensAndReturnsWhenCalledOnTheEventThread() {
assumeFalse(GraphicsEnvironment.isHeadless(), "needs a display")
val worker = Executors.newSingleThreadExecutor()
try {
val closing = closeOnceShowing()
val prefs = prefs()
val call = worker.submit {
showWithInterruptedCleanup {
EventQueue.invokeAndWait { SetupWizardWindow.show(SetupWizardState(prefs), prefs) }
}
}
// A deadlock here has no timeout of its own: without one this never completes.
call.get(20, TimeUnit.SECONDS)
closing.get(1, TimeUnit.SECONDS)
} finally {
disposeLeftoverDialog()
worker.shutdownNow()
closer.shutdownNow()
}
}
}
@@ -0,0 +1,339 @@
package kst4contest.view.compose.wizard
import kst4contest.model.ChatCategory
import kst4contest.model.ChatPreferences
import org.junit.jupiter.api.Assertions.assertArrayEquals
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
/**
* What the wizard does to a real preferences file: nothing until Save, exactly the answers
* afterwards, and every setting it never asked about left as it was.
*/
class SetupWizardWriteTest(@param:TempDir private val directory: Path) {
/** A copy of the bundled template, read the way the runtime reads a profile. */
private fun templateFile(): Path {
val file = directory.resolve("preferences.xml")
ChatPreferences::class.java.getResourceAsStream(ChatPreferences.PREFERENCE_RESOURCE).use { template ->
Files.copy(requireNotNull(template), file, StandardCopyOption.REPLACE_EXISTING)
}
return file
}
private fun read(file: Path): ChatPreferences =
ChatPreferences(file).also { assertTrue(it.readPreferencesFromXmlFile(), "reading $file failed") }
/** A profile an operator set up: read the template, change it, write it back. */
private fun configuredFile(change: ChatPreferences.() -> Unit = {}): Path {
val file = templateFile()
read(file).apply {
setStn_loginCallSign("DL0TEST")
setStn_loginPassword("secret")
setStn_loginNameMainCat("Philipp")
setStn_loginNameSecondCat("Philipp")
setStn_loginLocatorMainCat("JO50AA")
setStn_bandActive144(true)
setLoginChatCategoryMain(ChatCategory(2))
setLoginToSecondChatEnabled(false)
change()
assertTrue(writePreferencesToXmlFile())
}
return file
}
private fun SetupWizardState.answerFirstInstallation() {
name = "Philipp"
next()
callsign = "DL0TEST"
password = "secret"
next()
locator = "JO50AA"
setBand(WizardBand.B144, true)
setBand(WizardBand.B1240, true)
finish()
}
@Test
fun nothingIsWrittenBeforeSave() {
val file = templateFile()
val prefs = read(file)
// Taken after the read, so only the wizard is measured here.
val before = Files.readAllBytes(file)
SetupWizardState(prefs).answerFirstInstallation()
assertArrayEquals(before, Files.readAllBytes(file), "the file changed without Save")
assertEquals("DO5AMF", prefs.getStn_loginCallSign(), "the preferences changed without Save")
}
@Test
fun saveWritesExactlyTheAnswers() {
val file = templateFile()
val prefs = read(file)
val state = SetupWizardState(prefs)
state.answerFirstInstallation()
assertTrue(state.writeTo(prefs))
val restored = read(file)
assertEquals("DL0TEST", restored.getStn_loginCallSign())
assertEquals("secret", restored.getStn_loginPassword())
assertEquals("Philipp", restored.getStn_loginNameMainCat())
assertEquals("JO50AA", restored.getStn_loginLocatorMainCat())
assertTrue(restored.isStn_bandActive144())
assertTrue(restored.isStn_bandActive1240())
assertFalse(restored.isStn_bandActive432(), "a band the operator did not tick is off")
assertEquals(2, restored.getLoginChatCategoryMain().categoryNumber)
assertFalse(restored.isLoginToSecondChatEnabled(), "a new station starts without a second chat")
}
@Test
fun whatTheWizardNeverAskedAboutIsLeftAsItWas() {
val file = templateFile()
val prefs = read(file)
val server = prefs.getStn_on4kstServersDns()
val rotatorPort = prefs.getStn_pstRotatorPort()
val beamWidth = prefs.getStn_antennaBeamWidthDeg()
val state = SetupWizardState(prefs)
state.answerFirstInstallation()
assertTrue(state.writeTo(prefs))
val restored = read(file)
assertEquals(server, restored.getStn_on4kstServersDns())
assertEquals(rotatorPort, restored.getStn_pstRotatorPort())
assertEquals(beamWidth, restored.getStn_antennaBeamWidthDeg())
}
@Test
fun aCallsignIsStoredAsTyped() {
val file = templateFile()
val prefs = read(file)
val state = SetupWizardState(prefs)
state.name = "Philipp"
state.next()
state.callsign = " do5amf-2 "
state.password = "secret"
state.next()
state.locator = " jo50aa "
state.setBand(WizardBand.B144, true)
assertTrue(state.writeTo(prefs))
val restored = read(file)
assertEquals("do5amf-2", restored.getStn_loginCallSign(), "only the surrounding blanks go")
assertEquals("jo50aa", restored.getStn_loginLocatorMainCat(), "the Station tab stores it as typed too")
}
@Test
fun aKeptCategoryOutsideTheSuggestionsSurvives() {
val file = configuredFile {
setLoginChatCategoryMain(ChatCategory(7))
setLoginToSecondChatEnabled(true)
setLoginChatCategorySecond(ChatCategory(9))
}
val prefs = read(file)
val state = SetupWizardState(prefs)
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.next()
assertTrue(state.writeTo(prefs))
val restored = read(file)
assertEquals(7, restored.getLoginChatCategoryMain().categoryNumber)
assertTrue(restored.isLoginToSecondChatEnabled())
assertEquals(9, restored.getLoginChatCategorySecond().categoryNumber)
}
@Test
fun theSecondNameFollowsTheFirstUnlessItWasSetApart() {
val following = configuredFile()
val prefs = read(following)
val state = SetupWizardState(prefs)
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.name = "Marc"
state.next()
assertTrue(state.writeTo(prefs))
assertEquals("Marc", read(following).getStn_loginNameSecondCat())
val apart = configuredFile { setStn_loginNameSecondCat("Philipp SHF") }
val apartPrefs = read(apart)
val apartState = SetupWizardState(apartPrefs)
apartState.chooseLoginSource(WizardSource.KEEP)
apartState.chooseStationSource(WizardSource.KEEP)
apartState.next()
apartState.name = "Marc"
apartState.next()
assertTrue(apartState.writeTo(apartPrefs))
assertEquals("Philipp SHF", read(apart).getStn_loginNameSecondCat(), "a name set apart is the operator's")
}
@Test
fun anUntouchedLanguageStaysEvenIfThisBuildDoesNotKnowIt() {
val file = configuredFile { setGuiOptions_language("fr") }
val prefs = read(file)
val state = SetupWizardState(prefs)
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.next()
assertTrue(state.writeTo(prefs))
assertEquals("fr", read(file).getGuiOptions_language())
}
@Test
fun incompleteAnswersAreNotWritten() {
val file = templateFile()
val prefs = read(file)
val before = Files.readAllBytes(file)
val state = SetupWizardState(prefs)
state.name = "Philipp"
assertFalse(state.writeTo(prefs))
assertArrayEquals(before, Files.readAllBytes(file))
assertEquals("DO5AMF", prefs.getStn_loginCallSign())
}
@Test
fun aFailedWriteIsReported() {
val source = read(templateFile())
// A directory where the file should be: the write cannot succeed.
val unwritable = ChatPreferences(Files.createDirectory(directory.resolve("not-a-file")))
val state = SetupWizardState(source)
state.answerFirstInstallation()
assertFalse(state.writeTo(unwritable), "a write that failed must not read as saved")
}
@Test
fun aNewStationWithoutALogProgramHasEverySynchronisationOff() {
val file = templateFile()
val prefs = read(file)
val state = SetupWizardState(prefs)
state.answerFirstInstallation()
assertTrue(state.writeTo(prefs))
val restored = read(file)
assertFalse(restored.isLogsynch_wintestNetworkListenerEnabled())
assertFalse(restored.isLogsynch_ucxUDPWkdCallListenerEnabled())
assertFalse(restored.isLogsynch_fileBasedWkdCallInterpreterEnabled())
assertFalse(restored.isTrxSynch_ucxLogUDPListenerEnabled())
assertFalse(restored.isLogsynch_wintestQrgSyncEnabled())
assertFalse(restored.isNotify_dxClusterServerEnabled())
assertFalse(restored.isStn_pstRotatorEnabled())
assertFalse(restored.isAirScout_asUDPListenerEnabled())
}
@Test
fun theAnswersOfTheNewPagesAreWritten() {
val file = templateFile()
val prefs = read(file)
val state = SetupWizardState(prefs)
state.name = "Philipp"
state.next()
state.callsign = "DL0TEST"
state.password = "secret"
state.next()
state.locator = "JO50AA"
state.setBand(WizardBand.B144, true)
state.next()
state.antenna.beamWidthDeg = 28.0
state.antenna.heightAslText = "612"
state.next()
state.integrations.chooseLogProgram(WizardLogProgram.WINTEST)
state.integrations.wintestPort = 9871
// Stated, not taken from the template: without a name the page could not be left.
state.integrations.wintestStationName = "KST"
state.integrations.qrgFollow = true
state.next()
assertEquals(WizardPage.GEAR, state.page)
state.integrations.rotator = true
state.integrations.rotatorHost = "127.0.0.1"
state.integrations.rotatorPort = 12000
assertTrue(state.writeTo(prefs))
val restored = read(file)
assertEquals(28.0, restored.getStn_antennaBeamWidthDeg())
assertEquals(612.0, restored.getStn_pathAnalysisOwnHeightAslMeters())
assertTrue(restored.isLogsynch_wintestNetworkListenerEnabled())
assertEquals(9871, restored.getLogsynch_wintestNetworkPort())
assertTrue(restored.isLogsynch_wintestQrgSyncEnabled())
assertFalse(restored.isLogsynch_ucxUDPWkdCallListenerEnabled())
assertTrue(restored.isStn_pstRotatorEnabled())
assertFalse(restored.isAirScout_asUDPListenerEnabled())
}
@Test
fun aKeptStationKeepsEveryIntegrationAsItWas() {
// The template's integrations, several log sources among them, under a real login.
val file = configuredFile()
val before = read(file)
val prefs = read(file)
val state = SetupWizardState(prefs)
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.next()
assertTrue(state.writeTo(prefs))
val restored = read(file)
assertEquals(before.isLogsynch_ucxUDPWkdCallListenerEnabled(), restored.isLogsynch_ucxUDPWkdCallListenerEnabled())
assertEquals(
before.isLogsynch_fileBasedWkdCallInterpreterEnabled(),
restored.isLogsynch_fileBasedWkdCallInterpreterEnabled(),
)
assertEquals(before.isTrxSynch_ucxLogUDPListenerEnabled(), restored.isTrxSynch_ucxLogUDPListenerEnabled())
assertEquals(before.isNotify_dxClusterServerEnabled(), restored.isNotify_dxClusterServerEnabled())
assertEquals(before.isAirScout_asUDPListenerEnabled(), restored.isAirScout_asUDPListenerEnabled())
assertEquals(before.getStn_antennaBeamWidthDeg(), restored.getStn_antennaBeamWidthDeg())
assertTrue(
restored.isLogsynch_ucxUDPWkdCallListenerEnabled() && restored.isLogsynch_fileBasedWkdCallInterpreterEnabled(),
"the template has two log sources on; if this fails the template changed and the test needs another example",
)
}
@Test
fun openingOneNewPageOfAKeptStationWritesOnlyThatPage() {
val file = configuredFile()
val before = read(file)
val prefs = read(file)
val state = SetupWizardState(prefs)
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.next()
state.edit(WizardPage.GEAR)
state.integrations.rotator = true
state.integrations.rotatorHost = "127.0.0.1"
state.integrations.rotatorPort = 12000
state.next()
assertTrue(state.writeTo(prefs))
val restored = read(file)
assertTrue(restored.isStn_pstRotatorEnabled())
assertEquals(
before.isLogsynch_fileBasedWkdCallInterpreterEnabled(),
restored.isLogsynch_fileBasedWkdCallInterpreterEnabled(),
"the log page was not opened, so the log sources stay",
)
assertEquals(before.isNotify_dxClusterServerEnabled(), restored.isNotify_dxClusterServerEnabled())
}
}
@@ -0,0 +1,151 @@
package kst4contest.view.compose.wizard
import kst4contest.model.ChatPreferences
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.nio.file.Path
/**
* The antenna and power answers: always proposals taken from what is stored, never empty,
* and the site elevation read the way the Station tab reads it.
*/
class WizardAntennaTest {
private fun prefs(configure: ChatPreferences.() -> Unit = {}): ChatPreferences =
ChatPreferences(Path.of("wizard-antenna-test-unused.xml")).apply(configure)
private fun stored() = prefs {
setStn_antennaBeamWidthDeg(28.0)
setStn_pathAnalysisOwnAntennaGainDbi(16.5)
setStn_pathAnalysisOwnAntennaHeightMeters(18.0)
setStn_pathAnalysisOwnTxPowerWatts(400.0)
setStn_pathAnalysisOwnHeightAslMeters(612.0)
}
@Test
fun theAnswersStartAsTheStoredValues() {
val antenna = WizardAntenna(stored())
assertEquals(28.0, antenna.beamWidthDeg)
assertEquals(16.5, antenna.gainDbi)
assertEquals(18.0, antenna.heightMeters)
assertEquals(400.0, antenna.txPowerWatts)
assertEquals("612", antenna.heightAslText, "a whole number is shown without a decimal point")
assertTrue(antenna.complete)
}
@Test
fun anUnsetSiteElevationIsAnEmptyField() {
val antenna = WizardAntenna(prefs { setStn_pathAnalysisOwnHeightAslMeters(Double.NaN) })
assertEquals("", antenna.heightAslText)
assertFalse(antenna.heightAslRefused, "empty means the elevation model, not an error")
assertTrue(antenna.complete)
}
@Test
fun aFractionalSiteElevationKeepsItsFraction() {
val antenna = WizardAntenna(prefs { setStn_pathAnalysisOwnHeightAslMeters(250.5) })
assertEquals("250.5", antenna.heightAslText)
}
@Test
fun theSiteElevationIsReadTheWayTheStationTabReadsIt() {
val antenna = WizardAntenna(stored())
listOf("", " ", "250", "250,5", "250.5", "-100").forEach {
antenna.heightAslText = it
assertFalse(antenna.heightAslRefused, "'$it' must be accepted")
}
listOf("abc", "99999", "-501", "12 m").forEach {
antenna.heightAslText = it
assertTrue(antenna.heightAslRefused, "'$it' must be refused")
assertFalse(antenna.complete)
}
}
@Test
fun aNumberThatIsNotOneMakesThePageIncomplete() {
val antenna = WizardAntenna(stored())
antenna.gainDbi = Double.NaN
assertFalse(antenna.complete)
antenna.gainDbi = 12.0
antenna.txPowerWatts = Double.POSITIVE_INFINITY
assertFalse(antenna.complete)
}
@Test
fun antennaHeightMustBeNonNegative() {
val antenna = WizardAntenna(stored())
antenna.heightMeters = -5.0
assertFalse(antenna.complete)
antenna.heightMeters = 0.0
assertTrue(antenna.complete)
}
@Test
fun writingPutsTheAnswersIntoThePreferences() {
val target = prefs()
val antenna = WizardAntenna(stored())
antenna.beamWidthDeg = 35.0
antenna.heightAslText = "250,5"
antenna.writeTo(target)
assertEquals(35.0, target.getStn_antennaBeamWidthDeg())
assertEquals(16.5, target.getStn_pathAnalysisOwnAntennaGainDbi())
assertEquals(18.0, target.getStn_pathAnalysisOwnAntennaHeightMeters())
assertEquals(400.0, target.getStn_pathAnalysisOwnTxPowerWatts())
assertEquals(250.5, target.getStn_pathAnalysisOwnHeightAslMeters())
}
@Test
fun anEmptySiteElevationIsWrittenAsUnset() {
val target = prefs { setStn_pathAnalysisOwnHeightAslMeters(612.0) }
val antenna = WizardAntenna(stored())
antenna.heightAslText = ""
antenna.writeTo(target)
assertTrue(target.getStn_pathAnalysisOwnHeightAslMeters().isNaN(), "empty hands the elevation back to the model")
}
@Test
fun loadingTheStoredValuesAgainDropsWhatWasTyped() {
val antenna = WizardAntenna(stored())
antenna.beamWidthDeg = 99.0
antenna.gainDbi = 1.0
antenna.heightMeters = 2.0
antenna.txPowerWatts = 3.0
antenna.heightAslText = "abc"
antenna.loadStored()
assertEquals(28.0, antenna.beamWidthDeg)
assertEquals(16.5, antenna.gainDbi)
assertEquals(18.0, antenna.heightMeters)
assertEquals(400.0, antenna.txPowerWatts)
assertEquals("612", antenna.heightAslText)
assertTrue(antenna.complete)
}
@Test
fun aNegativeStoredAntennaHeightIsClampedToZero() {
val prefs = stored()
val field = ChatPreferences::class.java.getDeclaredField("stn_pathAnalysisOwnAntennaHeightMeters")
field.isAccessible = true
field.setDouble(prefs, -2.0)
val antenna = WizardAntenna(prefs)
assertEquals(0.0, antenna.heightMeters)
assertTrue(antenna.complete)
}
}
@@ -0,0 +1,363 @@
package kst4contest.view.compose.wizard
import kst4contest.model.ChatPreferences
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.nio.file.Path
/**
* The answers about log program, rotator and AirScout: what a new station starts with, what
* a kept one shows, when a page may be left, and what is written.
*/
class WizardIntegrationsTest {
private fun prefs(configure: ChatPreferences.() -> Unit = {}): ChatPreferences =
ChatPreferences(Path.of("wizard-integrations-test-unused.xml")).apply(configure)
/** Everything off, so each test states what it switches on. */
private fun allOff(configure: ChatPreferences.() -> Unit = {}) = prefs {
setLogsynch_wintestNetworkListenerEnabled(false)
setLogsynch_ucxUDPWkdCallListenerEnabled(false)
setLogsynch_fileBasedWkdCallInterpreterEnabled(false)
setTrxSynch_ucxLogUDPListenerEnabled(false)
setLogsynch_wintestQrgSyncEnabled(false)
setNotify_dxClusterServerEnabled(false)
setStn_pstRotatorEnabled(false)
setAirScout_asUDPListenerEnabled(false)
setTrxSynch_so2rEnabled(false)
setStn_pstRotator2Enabled(false)
setLogsynch_ucxUDPWkdCallListenerPort(12060)
setLogsynch_wintestNetworkPort(9871)
setLogsynch_wintestNetworkStationNameOfKST("KST")
setStn_pstRotatorHost("127.0.0.1")
setStn_pstRotatorPort(12000)
setStn_pstRotator2Port(12010)
setAirScout_asCommunicationPort(9872)
setAirScout_asServerNameString("AS")
setAirScout_asClientNameString("KST")
configure()
}
/** What the bundled template switches on. */
private fun likeTheTemplate() = allOff {
setLogsynch_ucxUDPWkdCallListenerEnabled(true)
setLogsynch_fileBasedWkdCallInterpreterEnabled(true)
setTrxSynch_ucxLogUDPListenerEnabled(true)
setNotify_dxClusterServerEnabled(true)
setAirScout_asUDPListenerEnabled(true)
}
private fun winTestStation() = allOff {
setLogsynch_wintestNetworkListenerEnabled(true)
setLogsynch_wintestNetworkPort(9999)
setLogsynch_wintestQrgSyncEnabled(true)
setNotify_dxClusterServerEnabled(true)
setStn_pstRotatorEnabled(true)
}
@Test
fun aKeptStationShowsWhatIsStored() {
val answers = WizardIntegrations(winTestStation())
assertEquals(WizardLogProgram.WINTEST, answers.logProgram)
assertEquals(9999, answers.wintestPort)
assertTrue(answers.qrgFollow)
assertTrue(answers.clusterServer)
assertTrue(answers.rotator)
assertFalse(answers.airScout)
assertFalse(answers.severalStoredLogSources)
}
@Test
fun aNewStationStartsWithEverythingOffButKeepsTheNumbers() {
val answers = WizardIntegrations(winTestStation())
answers.loadFresh()
assertEquals(WizardLogProgram.NONE, answers.logProgram)
assertFalse(answers.qrgFollow)
assertFalse(answers.clusterServer)
assertFalse(answers.rotator)
assertFalse(answers.airScout)
assertEquals(9999, answers.wintestPort, "a port the operator once set is a proposal, not lost")
assertTrue(answers.logComplete)
assertTrue(answers.gearComplete)
}
@Test
fun loadingTheStoredValuesAgainUndoesAFreshStart() {
val answers = WizardIntegrations(winTestStation())
answers.loadFresh()
answers.loadStored()
assertEquals(WizardLogProgram.WINTEST, answers.logProgram)
assertTrue(answers.rotator)
}
@Test
fun severalStoredSourcesMakeTheLogPageUneditable() {
val answers = WizardIntegrations(likeTheTemplate())
assertTrue(answers.severalStoredLogSources, "the template has the network listener and the file on")
// Shown as one of them, the network one first; the state decides not to offer the page.
assertEquals(WizardLogProgram.UDP, answers.logProgram)
}
@Test
fun leavingANetworkProgramDropsWhatOnlyANetworkProgramCanDo() {
val answers = WizardIntegrations(allOff())
answers.chooseLogProgram(WizardLogProgram.UDP)
answers.qrgFollow = true
answers.clusterServer = true
assertTrue(answers.networked)
answers.chooseLogProgram(WizardLogProgram.FILE)
assertFalse(answers.networked)
assertFalse(answers.qrgFollow)
assertFalse(answers.clusterServer)
}
@Test
fun aLogFileNeedsAFile() {
val answers = WizardIntegrations(allOff())
// The compiled-in default names a file, which is a proposal like every stored value.
answers.filePath = ""
answers.chooseLogProgram(WizardLogProgram.FILE)
assertFalse(answers.logComplete)
answers.filePath = "/home/op/log.txt"
assertTrue(answers.logComplete)
}
@Test
fun anInvalidPortMakesItsPageIncomplete() {
val answers = WizardIntegrations(allOff())
answers.chooseLogProgram(WizardLogProgram.UDP)
answers.udpPort = 0
assertFalse(answers.logComplete)
answers.udpPort = 70000
assertFalse(answers.logComplete)
answers.udpPort = 12060
assertTrue(answers.logComplete)
answers.chooseLogProgram(WizardLogProgram.WINTEST)
answers.wintestStationName = " "
assertFalse(answers.logComplete, "Win-Test needs a station name to send from")
answers.wintestStationName = "KST"
answers.wintestPort = -1
assertFalse(answers.logComplete)
// A port of a program that is not chosen is nobody's problem.
answers.chooseLogProgram(WizardLogProgram.NONE)
assertTrue(answers.logComplete)
answers.airScout = true
answers.airScoutPort = 0
assertFalse(answers.gearComplete)
answers.airScoutPort = 9872
answers.airScoutServerName = "A\"S"
assertFalse(answers.gearComplete, "a quotation mark breaks the AirScout message")
answers.airScoutServerName = "AS"
assertTrue(answers.gearComplete)
answers.rotator = true
answers.rotatorHost = " "
assertFalse(answers.gearComplete)
}
@Test
fun aRotatorPortNextToRotatorTwoIsRefusedOnlyWithSo2r() {
val withSo2r = WizardIntegrations(allOff {
setTrxSynch_so2rEnabled(true)
setStn_pstRotator2Enabled(true)
})
withSo2r.rotator = true
withSo2r.rotatorPort = 12011
assertTrue(withSo2r.rotatorPortClashes, "PSTRotator answers on port + 1")
assertFalse(withSo2r.gearComplete)
withSo2r.rotatorPort = 12000
assertFalse(withSo2r.rotatorPortClashes)
assertTrue(withSo2r.gearComplete)
val withoutSo2r = WizardIntegrations(allOff())
withoutSo2r.rotator = true
withoutSo2r.rotatorPort = 12011
assertFalse(withoutSo2r.rotatorPortClashes, "rotator 2 is not in use without SO2R")
assertTrue(withoutSo2r.gearComplete)
}
@Test
fun writingTheLogPageSwitchesExactlyTheChosenSourceOn() {
val target = likeTheTemplate()
val answers = WizardIntegrations(target)
answers.loadFresh()
answers.chooseLogProgram(WizardLogProgram.WINTEST)
answers.wintestPort = 9871
answers.wintestStationName = " KST "
answers.qrgFollow = true
answers.writeLogTo(target)
assertTrue(target.isLogsynch_wintestNetworkListenerEnabled())
assertFalse(target.isLogsynch_ucxUDPWkdCallListenerEnabled())
assertFalse(target.isLogsynch_fileBasedWkdCallInterpreterEnabled())
assertEquals(9871, target.getLogsynch_wintestNetworkPort())
assertEquals("KST", target.getLogsynch_wintestNetworkStationNameOfKST(), "trimmed, as the tab stores it")
assertTrue(target.isLogsynch_wintestQrgSyncEnabled())
assertFalse(target.isTrxSynch_ucxLogUDPListenerEnabled(), "the other program's frequency source goes off")
assertFalse(target.isNotify_dxClusterServerEnabled())
assertTrue(target.isAirScout_asUDPListenerEnabled(), "the log page does not touch AirScout")
}
@Test
fun writingNoLogProgramSwitchesEverySynchronisationOff() {
val target = likeTheTemplate()
val answers = WizardIntegrations(target)
answers.loadFresh()
answers.writeLogTo(target)
assertFalse(target.isLogsynch_wintestNetworkListenerEnabled())
assertFalse(target.isLogsynch_ucxUDPWkdCallListenerEnabled())
assertFalse(target.isLogsynch_fileBasedWkdCallInterpreterEnabled())
assertFalse(target.isTrxSynch_ucxLogUDPListenerEnabled())
assertFalse(target.isLogsynch_wintestQrgSyncEnabled())
assertFalse(target.isNotify_dxClusterServerEnabled())
assertEquals(12060, target.getLogsynch_ucxUDPWkdCallListenerPort(), "an unused port is left alone")
}
@Test
fun writingTheGearPageSetsRotatorAndAirScoutOnly() {
val target = likeTheTemplate()
val answers = WizardIntegrations(target)
answers.loadFresh()
answers.rotator = true
answers.rotatorHost = " 192.168.1.20 "
answers.rotatorPort = 12040
answers.writeGearTo(target)
assertTrue(target.isStn_pstRotatorEnabled())
assertEquals("192.168.1.20", target.getStn_pstRotatorHost())
assertEquals(12040, target.getStn_pstRotatorPort())
assertFalse(target.isAirScout_asUDPListenerEnabled())
assertEquals(9872, target.getAirScout_asCommunicationPort(), "an unused port is left alone")
assertTrue(target.isLogsynch_ucxUDPWkdCallListenerEnabled(), "the gear page does not touch the log sources")
}
@Test
fun theStoredSwitchesAreWhatTheProfileHasOn() {
val template = WizardIntegrations(likeTheTemplate())
assertEquals(
setOf(WizardSwitch.LOG_UDP, WizardSwitch.LOG_FILE, WizardSwitch.QRG_FOLLOW, WizardSwitch.CLUSTER_SERVER),
template.storedLogSwitches(),
)
assertEquals(setOf(WizardSwitch.AIRSCOUT), template.storedGearSwitches())
val nothing = WizardIntegrations(allOff())
assertEquals(emptySet<WizardSwitch>(), nothing.storedLogSwitches())
assertEquals(emptySet<WizardSwitch>(), nothing.storedGearSwitches())
}
@Test
fun theAnsweredSwitchesFollowThePages() {
val answers = WizardIntegrations(likeTheTemplate())
answers.loadFresh()
assertEquals(emptySet<WizardSwitch>(), answers.answeredLogSwitches())
assertEquals(emptySet<WizardSwitch>(), answers.answeredGearSwitches())
answers.chooseLogProgram(WizardLogProgram.WINTEST)
answers.qrgFollow = true
answers.clusterServer = true
answers.rotator = true
assertEquals(
setOf(WizardSwitch.LOG_WINTEST, WizardSwitch.QRG_FOLLOW, WizardSwitch.CLUSTER_SERVER),
answers.answeredLogSwitches(),
)
assertEquals(setOf(WizardSwitch.ROTATOR), answers.answeredGearSwitches())
// The stored side does not move with the answers.
assertEquals(setOf(WizardSwitch.AIRSCOUT), answers.storedGearSwitches())
}
@Test
fun theHighestPortIsNoRotatorPort() {
// PSTRotator answers on port + 1, so the setter stores 1..65534 only and would
// replace 65535 by its factory default without a word.
val target = allOff()
val answers = WizardIntegrations(target)
answers.rotator = true
answers.rotatorPort = 65535
assertFalse(answers.gearComplete, "65535 would be stored as 12000")
answers.rotatorPort = 65534
assertTrue(answers.gearComplete)
answers.writeGearTo(target)
assertEquals(65534, target.getStn_pstRotatorPort(), "an accepted port is stored as entered")
answers.rotatorPort = 0
assertFalse(answers.gearComplete)
}
@Test
fun loadingAgainPutsTheDetailsBackToTheStoredOnes() {
val answers = WizardIntegrations(winTestStation())
val storedFilePath = answers.filePath
answers.udpPort = 1
answers.wintestPort = 2
answers.wintestStationName = "typed"
answers.filePath = "/typed"
answers.rotatorHost = "typed"
answers.rotatorPort = 3
answers.airScoutPort = 4
answers.airScoutServerName = "typed"
answers.airScoutClientName = "typed"
answers.loadFresh()
assertEquals(12060, answers.udpPort)
assertEquals(9999, answers.wintestPort)
assertEquals("KST", answers.wintestStationName)
assertEquals(storedFilePath, answers.filePath)
assertEquals("127.0.0.1", answers.rotatorHost)
assertEquals(12000, answers.rotatorPort)
assertEquals(9872, answers.airScoutPort)
assertEquals("AS", answers.airScoutServerName)
assertEquals("KST", answers.airScoutClientName)
answers.filePath = "/typed"
answers.rotatorPort = 3
answers.loadStored()
assertEquals(storedFilePath, answers.filePath)
assertEquals(12000, answers.rotatorPort)
}
@Test
fun theStoredSwitchesAreKnownWhateverTheLogProgram() {
// The settings window lets the DX cluster server and a frequency source run without
// a log source; the page's own answers cannot express that.
val answers = WizardIntegrations(allOff {
setNotify_dxClusterServerEnabled(true)
setTrxSynch_ucxLogUDPListenerEnabled(true)
})
assertEquals(WizardLogProgram.NONE, answers.logProgram)
assertFalse(answers.clusterServer, "the page shows none of it")
assertTrue(answers.storedClusterServer)
assertTrue(answers.storedQrgFollow)
val off = WizardIntegrations(allOff())
assertFalse(off.storedClusterServer)
assertFalse(off.storedQrgFollow)
}
}
@@ -0,0 +1,182 @@
package kst4contest.view.compose.wizard
import kst4contest.model.ChatCategory
import kst4contest.model.ChatPreferences
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.mockito.Mockito
import java.io.File
import java.lang.reflect.Modifier
import java.nio.file.Path
/**
* What "the station" is when one profile takes it from another.
*
* The two lists under src/test/resources are the decision, one line per ChatPreferences
* setter. A setter in neither list fails the first test, so a new setting cannot be forgotten
* here: somebody has to say whether another operator at the same station should inherit it.
*/
class WizardStationCopyTest {
private fun lines(name: String): Set<String> =
File("src/test/resources/$name").readLines().map { it.trim() }.filter { it.isNotEmpty() }.toSet()
private val stationSetters = lines("wizard-station-setters.txt")
private val otherSetters = lines("wizard-other-setters.txt")
/** Every public setter with one parameter, the shape every preference has. */
private fun allSetters(): Set<String> =
ChatPreferences::class.java.methods
.filter { it.name.startsWith("set") && it.parameterCount == 1 && Modifier.isPublic(it.modifiers) }
.map { it.name }
.toSet()
private fun prefs(configure: ChatPreferences.() -> Unit = {}): ChatPreferences =
ChatPreferences(Path.of("wizard-station-copy-test-unused.xml")).apply(configure)
@Test
fun everySetterIsClassified() {
val all = allSetters()
assertEquals(
emptySet<String>(),
all - stationSetters - otherSetters,
"new ChatPreferences setters: add each to wizard-station-setters.txt (and to copyStation) " +
"or to wizard-other-setters.txt",
)
assertEquals(emptySet<String>(), (stationSetters + otherSetters) - all, "listed setters that no longer exist")
assertEquals(emptySet<String>(), stationSetters.intersect(otherSetters), "a setter cannot be in both lists")
}
@Test
fun copyStationCallsExactlyTheStationSetters() {
val target = Mockito.mock(ChatPreferences::class.java)
copyStation(prefs(), target)
val called = Mockito.mockingDetails(target).invocations
.map { it.method.name }
.filter { it.startsWith("set") }
assertEquals(stationSetters, called.toSet(), "copyStation and wizard-station-setters.txt disagree")
assertEquals(called.size, called.toSet().size, "a setter was called twice")
assertTrue(
Mockito.mockingDetails(target).invocations.none { it.method.name == "writePreferencesToXmlFile" },
"copying must not write a file",
)
}
@Test
fun theStationArrivesIncludingWhatTheWizardNeverAsks() {
val donor = prefs {
setStn_loginLocatorMainCat("JO50AA")
setStn_bandActive144(true)
setStn_bandActive1240(true)
setStn_bandActive432(false)
setLoginChatCategoryMain(ChatCategory(2))
setLoginToSecondChatEnabled(true)
setLoginChatCategorySecond(ChatCategory(3))
setStn_qtfDefault(270.0)
setStn_maxQRBDefault(800.0)
setStn_pathAnalysisDemRootDirectory("/srv/dem")
setStn_pathAnalysisContestMarginDb(9.0)
setTrxSynch_so2rEnabled(true)
setStn_pstRotator2Enabled(true)
setStn_pstRotator2Port(12020)
// Several log sources at once: the wizard's own question could not express this.
setLogsynch_wintestNetworkListenerEnabled(true)
setLogsynch_fileBasedWkdCallInterpreterEnabled(true)
setLogsynch_wintestNetworkStationNameOfWintestClient1("RUN")
setLogsynch_wintestUsePassQrg(true)
setAirScout_asBandString("4320000")
}
val target = prefs {
setStn_bandActive432(true)
setLoginChatCategoryMain(ChatCategory(3))
}
copyStation(donor, target)
assertEquals("JO50AA", target.getStn_loginLocatorMainCat())
assertTrue(target.isStn_bandActive144())
assertTrue(target.isStn_bandActive1240())
assertFalse(target.isStn_bandActive432(), "a band the donor does not have goes off")
assertEquals(2, target.getLoginChatCategoryMain().categoryNumber)
assertTrue(target.isLoginToSecondChatEnabled())
assertEquals(3, target.getLoginChatCategorySecond().categoryNumber)
assertEquals(270.0, target.getStn_qtfDefault())
assertEquals(800.0, target.getStn_maxQRBDefault())
assertEquals("/srv/dem", target.getStn_pathAnalysisDemRootDirectory())
assertEquals(9.0, target.getStn_pathAnalysisContestMarginDb())
assertTrue(target.isTrxSynch_so2rEnabled())
assertTrue(target.isStn_pstRotator2Enabled())
assertEquals(12020, target.getStn_pstRotator2Port())
assertTrue(target.isLogsynch_wintestNetworkListenerEnabled())
assertTrue(target.isLogsynch_fileBasedWkdCallInterpreterEnabled())
assertEquals("RUN", target.getLogsynch_wintestNetworkStationNameOfWintestClient1())
assertTrue(target.isLogsynch_wintestUsePassQrg())
assertEquals("4320000", target.getAirScout_asBandString())
}
@Test
fun whatBelongsToTheOperatorStays() {
val donor = prefs {
setStn_loginCallSign("DL0TEST")
setStn_loginPassword("donor-secret")
setStn_loginNameMainCat("Donor")
setStn_loginNameSecondCat("Donor SHF")
setGuiOptions_language("en")
setGUI_darkModeActiveByDefault(true)
setStn_on4kstServersDns("donor.example")
setNotify_DXCSrv_SpottersCallSign("DL0TEST")
setBcn_beaconTextMainCat("donor beacon")
}
val target = prefs {
setStn_loginCallSign("DM5XX")
setStn_loginPassword("own-secret")
setStn_loginNameMainCat("Own")
setStn_loginNameSecondCat("Own SHF")
setGuiOptions_language("de")
setGUI_darkModeActiveByDefault(false)
setStn_on4kstServersDns("own.example")
setNotify_DXCSrv_SpottersCallSign("DM5XX")
setBcn_beaconTextMainCat("own beacon")
}
copyStation(donor, target)
assertEquals("DM5XX", target.getStn_loginCallSign())
assertEquals("own-secret", target.getStn_loginPassword())
assertEquals("Own", target.getStn_loginNameMainCat())
assertEquals("Own SHF", target.getStn_loginNameSecondCat())
assertEquals("de", target.getGuiOptions_language())
assertFalse(target.isGUI_darkModeActiveByDefault())
assertEquals("own.example", target.getStn_on4kstServersDns())
assertEquals("DM5XX", target.getNotify_DXCSrv_SpottersCallSign().get())
assertEquals("own beacon", target.getBcn_beaconTextMainCat())
}
@Test
fun theDonorIsNotChangedAndSharesNoObjectWithTheTarget() {
val donor = prefs { setLoginChatCategoryMain(ChatCategory(2)) }
val target = prefs()
copyStation(donor, target)
target.getLoginChatCategoryMain().categoryNumber = 7
assertEquals(2, donor.getLoginChatCategoryMain().categoryNumber, "the two profiles must not share a category object")
}
@Test
fun theFallbackBandComesWithTheStation() {
// It completes frequencies given without a band, so it has to fit the station's bands.
val donor = prefs { setNotify_optionalFrequencyPrefix("432") }
val target = prefs { setNotify_optionalFrequencyPrefix("144") }
copyStation(donor, target)
assertEquals("432", target.getNotify_optionalFrequencyPrefix().get())
}
}
@@ -0,0 +1,72 @@
setActualQTF
setBcn_beaconIntervalInMinutesMainCat
setBcn_beaconIntervalInMinutesSecondCat
setBcn_beaconTextMainCat
setBcn_beaconTextSecondCat
setBcn_beaconsEnabledMainCat
setBcn_beaconsEnabledSecondCat
setBcn_contestScoreSum
setChatState
setGUI_darkModeActive
setGUI_darkModeActiveByDefault
setGUIclusterAndQSOMonStage_SceneSizeHW
setGUImainWindowLeftSplitPane_dividerposition
setGUImainWindowRightSplitPane_dividerposition
setGUImessageSectionSplitpane_dividerposition
setGUIpnl_directedMSGWin_dividerpositionDefault
setGUIscn_ChatwindowMainSceneSizeHW
setGUIselectedCallSignSplitPane_dividerposition
setGUIsettingsStageSceneSizeHW
setGUIstage_updateStage_SceneSizeHW
setGUIstationMapAlwaysOnTop
setGUIstationMapClusteringEnabled
setGUIstationMapPathAnalysisVisible
setGUIstationMapStagePositionXY
setGUIstationMapStageSceneSizeHW
setGuiOptions_defaultFilterNothing
setGuiOptions_defaultFilterPmToMe
setGuiOptions_defaultFilterPmToOther
setGuiOptions_defaultFilterPublicMsgs
setGuiOptions_language
setGuiOptions_paletteOverridesDay
setGuiOptions_paletteOverridesEvening
setGuiOptions_rememberWindowPositions
setGuiOptions_showFreshCallHintInBandColumns
setGuiOptions_showGrossFieldWorkedHintInBandColumns
setLogSynch_storeWorkedCallSignsFileNameUDPMessageBackup
setLogsynch_storeWorkedCallSignsFileNameUDPMessageBackup
setLstNotify_QSOSniffer_sniffedPrefixLocList
setLst_txtShortCutBtnList
setLst_txtSnipList
setMYQRGFirstCat
setMYQRGSecondCat
setMessageHandling_autoAnswerEnabled
setMessageHandling_autoAnswerEnabledSecondCat
setMessageHandling_autoAnswerTextMainCat
setMessageHandling_autoAnswerTextSecondCat
setMessageHandling_autoAnswerToQRGRequestEnabled
setMessageHandling_beaconUnworkedstationsPrefix
setMessageHandling_debugModeToFileEnabled
setMessageHandling_unworkedStnRequesterBeaconsEnabled
setMessageHandling_unworkedStnRequesterBeaconsInterval
setMessageHandling_unworkedStnRequesterBeaconsText
setNotify_DXCSrv_SpottersCallSign
setNotify_DXClusterServerTriggerBearing
setNotify_DXClusterServerTriggerOnQRGDetect
setNotify_bandUpgradeHintOnLogEnabled
setNotify_bandUpgradePriorityBoostEnabled
setNotify_momentumWindowSeconds
setNotify_noReplyPenaltyMinutes
setNotify_playCWCallsignsOnRxedPMs
setNotify_playSimpleSounds
setNotify_playVoiceCallsignsOnRxedPMs
setNotify_positiveSignalsPatterns
setProgramVersion
setStn_loginAFKState
setStn_loginCallSign
setStn_loginNameMainCat
setStn_loginNameSecondCat
setStn_loginPassword
setStn_on4kstServersDns
setStn_on4kstServersPort
setStoreAndRestorePreferencesFileName
@@ -0,0 +1,66 @@
setAirScout_asBandString
setAirScout_asClientNameString
setAirScout_asCommunicationPort
setAirScout_asServerNameString
setAirScout_asUDPListenerEnabled
setAirScout_autoBandSelectionEnabled
setLoginChatCategoryMain
setLoginChatCategorySecond
setLoginToSecondChatEnabled
setLogsynch_fileBasedWkdCallInterpreterEnabled
setLogsynch_fileBasedWkdCallInterpreterFileNameReadOnly
setLogsynch_ucxUDPWkdCallListenerEnabled
setLogsynch_ucxUDPWkdCallListenerPort
setLogsynch_wintestNetworkBroadcastAddress
setLogsynch_wintestNetworkListenerEnabled
setLogsynch_wintestNetworkPort
setLogsynch_wintestNetworkSimulationEnabled
setLogsynch_wintestNetworkSkedPushEnabled
setLogsynch_wintestNetworkStationIDOfKST
setLogsynch_wintestNetworkStationNameOfKST
setLogsynch_wintestNetworkStationNameOfWintestClient1
setLogsynch_wintestNetworkStationNameOfWintestClient2
setLogsynch_wintestQrgSyncEnabled
setLogsynch_wintestSkedMode
setLogsynch_wintestUsePassQrg
setNotify_dxClusterServerEnabled
setNotify_dxclusterServerPort
setNotify_optionalFrequencyPrefix
setStn_antennaBeamWidthDeg
setStn_bandActive10G
setStn_bandActive1240
setStn_bandActive144
setStn_bandActive2300
setStn_bandActive3400
setStn_bandActive432
setStn_bandActive50
setStn_bandActive5600
setStn_bandActive70
setStn_loginLocatorMainCat
setStn_maxQRBDefault
setStn_pathAnalysisContestMarginDb
setStn_pathAnalysisDefaultTargetAntennaGainDbi
setStn_pathAnalysisDefaultTargetAntennaHeightMeters
setStn_pathAnalysisDefaultTargetTxPowerWatts
setStn_pathAnalysisDemDatasetId
setStn_pathAnalysisDemRootDirectory
setStn_pathAnalysisDxHighestPointInSquare
setStn_pathAnalysisFeederLossIncreaseDbPer200MHz
setStn_pathAnalysisMaxEstimatedFeederLossPerStationDb
setStn_pathAnalysisOwnAntennaGainDbi
setStn_pathAnalysisOwnAntennaHeightMeters
setStn_pathAnalysisOwnHeightAslMeters
setStn_pathAnalysisOwnTxPowerWatts
setStn_pathAnalysisRequiredCwSignalDbm
setStn_pathAnalysisRequiredSsbSignalDbm
setStn_pathAnalysisVhfFeederLossPerStationDb
setStn_pstRotator2Enabled
setStn_pstRotator2Host
setStn_pstRotator2Port
setStn_pstRotatorEnabled
setStn_pstRotatorHost
setStn_pstRotatorPort
setStn_qtfDefault
setStn_useQtfFilterDirectionAsAntennaHeading
setTrxSynch_so2rEnabled
setTrxSynch_ucxLogUDPListenerEnabled