Conversation
* Cleanup of code and other improvements
…LANServer are allowed to be added in the agent (#577)
…with docker-like container in host-like network mode
…lfsigned and adjusted accordingly in config-admin-agent check
…ch/... for older versions)
#585) * Server: Implement advertisement/getAdvertisementByPlatformSessionID and fully implement advertisement/updatePlatformSessionID * fix previous commit
Signed-off-by: B. Stack <bgstack15@gmail.com>
New test files: - cmd/agent/agent_test.go: SingleFlagSet, flag registration, parsing - cmd/config/config_test.go: SetUpFlagSet, RevertFlagSet, FlushCacheFlagSet, AddCommonFlags, InitSetUp, InitBaseRevert, FlushCacheSingleFlagSet - cmd/config/admin/admin_test.go: SetupFlagSet, RevertFlagSet - configrevert_test.go: NewConfigRevertFlagOptions, Flags, RemoveAll logic, RevertRequiresAdminElevationValues table-driven tests Expanded: - userData/userdata_test.go: Profiles (AoE1, AoE2, missing dir), Metadatas (create, subdirs, all game types), Data getters, TransformPath edge cases, profileFolder per game Coverage improvements: - cmd/agent: 0% -> 100% - cmd/config: 0% -> 100% - cmd/config/admin: 0% -> 100% - userData: 40.5% -> 97.5% - launcher-common root: 39.8% -> 46.4%
New tests: - getTemplate: selfsigned, ca, normal template variants - generateSelfSignedCertificate: read-only dir error (Linux) - generateCertificatePairs: read-only dir, nonexistent path, CA key buffer, normal cert with parent, key create failure (Linux) - GenerateCertificatePairs: server cert failure cleanup, self-signed failure (Linux) Coverage: 74.6% -> 75.4% (read-only tests skip on Windows, run on Linux CI)
New test file: - internal/internal_test.go: error constants sequential/unique, Configuration type fields Expanded: - internal/cmdUtils/config_io_test.go: WriteConfig directory creation, WriteConfig file name incrementing, ExistingServers missing folder, Remove with empty/nil configs, Remove with onlyInvalid skipping valid, Remove with missing folder Coverage: cmdUtils 56.3% -> 59.9%
- TestAddToSlice: basic copy + index increment - TestAddToSliceEmpty: empty source Coverage: internal 42.0% -> 43.8%
New test files: - archive_extra_test.go: extChange, buildName, archToValues, keyFromStrings, archiveToUniversal, overrideWindowsName, mergeBuilds - binary_extra_test.go: Main(), CloneForOperatingSystems, AddMultipleTargets, universalBinaries - copyResources_test.go: BuildResourcePath, ResourcePath Coverage: goreleaser 45.3% -> 50.2%
- TestCookiesFromSetCookieHeader: cookie parsing + MaxAge stripping - TestCookiesEmptyHeader: no cookie header returns empty - TestCookiesInvalidHeader: malformed cookie returns empty - TestDelHeaderRemovesFromBoth: removes from both headers - TestDelHeaderMultipleValues: removes multiple keys - TestRequestMethodAndURL: String() returns 'METHOD URL' Coverage: http 28.6% -> 40.5%
…atchAll New tests: - matchAll: true, false, type mismatch, empty args - ip: valid IPv4/IPv6, invalid - epoch: valid, too old (<2025), too far future (>24h) - dateIso8601, dateRFC3339, dateRFC1123, datePlayfab: valid/invalid - CompareJSON: identical, different non-volatile, volatile epoch/IP/date Coverage: logEntry 33.8% -> 89.2%
1. Taskfile.yml: remove trailing dot in dotenv pattern '{{.ENV}}/.env.'
-> '{{.ENV}}/.env' (was looking for non-existent files)
2. Taskfile.debug.yml: prepare-server used 'cmd:' instead of 'cmds:'
for task invocation (was executing as shell command)
3. Taskfile.debug.yml: add missing {{exeExt}} to genCert build output
path (was generating without .exe on Windows)
…paths New test file: - paths_test.go: GameAoE1/2/3/4, GameAoM Paths() with empty, missing, and populated temp directory structures Expanded: - gameLogs_test.go: sortByModTime, addNewestPath no-match, addNewestPath filters directories, copyFileContent success/missing source, copyPathToDir mkdir failure Coverage: gameLogs 39.7% -> 81.0%
…ants New test file: - state_test.go: error constants unique/non-zero, SetUp state Expanded: - logs_test.go: runSetUp missing --game flag, runFlushCache syntax error, runFlushCache no-flags success, runRevert --all flag accepted Coverage: internal/cmd 6.3% -> 30.7%
…errors New test files: - internal/errors_test.go: error constants unique/non-zero - internal/ipc/cert_test.go: checkCertificateValidity with 15 tests: nil cert, wildcard CN, IDNA CN, IP CN, non-CA, game cert MaxPathLenZero/DNS/KeyUsage/ExtKeyUsage, non-game cert, AoE1/AoE3 game certs, AoE4/AoM non-game certs Coverage: internal/ipc 14.4% -> 29.3%
…alidation New test files: - internal/errors_test.go: error constants unique/non-zero, NewCACert returns nil for AoE1/AoE4 (no CA), non-panic for AoM - internal/cmd/cmd_test.go: runSetUp/runRevert syntax error, missing --game flag, runFlushCache syntax error/empty, runStopAgent Coverage: internal 6.4% -> 9.6%, internal/cmd 8.8% -> 14.3%
- executor/exec, fileLock, logger, game, custom, steam executor at 100% - Injectable vars: osExecutableFn, writePidFn, ioCopyFn, directHostToIPFn, execFn, knownFolderPathFn, osExitFn, parseStatFn, procSignalFn/KillFn - Integration: httptest TLS server for LanServerIP/Host/CheckConnection, real process kill tests, subprocess lock contention via TestMain - Fix Steam libraryFolder/Path unsafe type assertions - CI-safe: mock ShellExecuteEx (no UAC/browser), no skipped tests
…dcast - launcher-common: fix ArgsStore truncate/dedup, optionsFn pointer bug, Profiles suffix handling, suffix determinism, Flags mutation, cert store mock, coverage 52%->87% - battle-server-broadcast: fix Retrieve/Calculate/Clone nil checks, mask handling, Dial/Listen error handling, make testable via netInterfaces/interfaceAddrs/netListenUDP/netDialUDP and cloneAnnouncementsLoop, coverage 40%->98%
- fix configWriter max index (use max not last), marshal error handling - fix resolver doResolveAutoPath missing error when validPath false - fix ssl keyCert early return on !ok - fix connection busy loop add sleep and make timeout injectable - fix executor ports length check, simulationPeriod default, make execWithOptions mockable - fix network GeneratePorts reverse bug, make listenTCP/findUnusedPorts mockable - fix remove return false when file missing - fix start region/name log bug, make runStart dependencies injectable - make clean/remove/removeAll/root testable via vars - add comprehensive tests: executor 0->94%, resolver 0->97%, cmd 9->85%, cmdUtils 59->91%, total 25->88%
- fix WindowsToUnixPath: compare ret!=0 instead of ret!=common.ErrSuccess, handle trailing slash empty component, make Wine calls mockable via findWineProcFn/callWineGetUnixFileNameFn/heapFreeFn/cStringToGoFn/utf16PtrFromStringFn - fix main_windows: make steam/game/Wine/fmt mockable via vars - add comprehensive tests: heapFree, cStringToGo, WindowsToUnixPath 9 cases (empty, not Wine, UTF16 error, success no tail, success with tail, invalid chars, reduced to empty, trailing separators), run configPath true/false/maybe, userProfilePath, windowsToUnixPath, convertAndPrint - coverage 31%->93%
- Export Locker interface in common/fileLock/pidLock.go
- Inject 30+ function variables in runRoot for testability
- Extract validation helpers: validateCanTrustCertificate, validateCanBroadcastBattleServer, validateServerStartValue, validateServerStopValue, validateRequiredTrueFalse
- Fix global mapset mutation bug (Remove('user')/Remove('false') was permanent across calls)
- Add runRoot_test.go with 35+ tests covering error paths, validation, server discovery, cert, host mapping, flush cache
- Add test helper applyOverrides() to reduce boilerplate
- Coverage: runRoot 11.4% -> 72.3%, cmd package 5.8% -> 65.1%
Bugs fixed: - Data race on exitCode shared between signal goroutine and Watch() - now protected by sync.Mutex accessors - Inconsistent sentinel: signal handler used '-' while Watch() used '' to check if BattleServer is disabled - standardized on '' - Double cleanup: signal handler and Watch() defers both ran config revert, revert command, server kill, and battle-server shutdown independently - now shared via sync.Once Refactoring: - Extract injectable function vars in watch.go for all external deps: waitUntilAnyProcessExistFn, waitForProcessesToExitFn, serverKillDoFn, configRevertFn, runRevertCommandFn, removeBattleServerRegionFn, gameLogsCopyFn, rebroadcastFn, commonProcessProcessesByNamesFn, loggerBufferFn - Extract injectable function vars in cmd/root.go: createLockFn, chdirToExeFn, initializeFn, watchFn, signalNotifyFn, commonProcessKillFn, etc. - Make oneMinuteWaitTimeout a var (testable) - Signal handler and Watch() share cleanupOnce to prevent double-execution Tests (watch package: 0% -> 58.8%): - TestWatchGameTimeoutStart: game not found within 1 minute - TestWatchGameFound: normal successful flow - TestWatchWithServerKill: server executable is killed - TestWatchServerKillFailure: kill failure sets ErrFailedStopServer - TestWatchWithLogCopy: game logs copied when paths configured - TestWatchCleanupOncePreventsDoubleCleanup: sync.Once guard - TestWatchWaitFailure: process wait failure - TestWaitUntilAnyProcessExistFound: immediate process discovery - TestWaitUntilAnyProcessExistTimeout: polling timeout
…uncher-config-admin-agent, server, server-genCert and tools
…s fixes Add comprehensive httptest suites in the router package covering every game route (5 game IDs), general/CDN/PlayFab/Api routers, session/login/ host middlewares, and input/series-dependent flows: - httptest_all_routes_test.go: fake in-memory resources, doRequest helper, route registration, auth (401/anon) and middleware tests - httptest_expected_values_test.go: per-route first-element (0/2/-1) assertions across all games - httptest_complex_flows_test.go: chained flows (advertisement host/join, item create/equip, relationship, chat, party, invitation, PlayFab, cloudfiles, wss, readSession, input validation) Add per-package httptest tests for cacert.pem, serverStatus and shutdown. Guard against nil/type panics exposed by the tests with fake data: - advertisement: nil-check battleServer lookup; lazily init observers set in StartObserving/StopObserving - item loadouts, playfab Catalog/Inventory/LoginWithSteam, athens cloud function and CommunityEvents: safe-cast / nil-check before deref
… pattern Replace mutable package globals (isAdminFn, runRevertExec, execFn, etc.) with dependency injection via deps structs, New* constructors and a process-wide Default instance. Package-level wrappers delegate to Default so existing call sites keep working. Tests now inject fakes instead of swapping globals, enabling t.Parallel and avoiding data races.
…eps pattern Move launcher-config-admin IPC connection state and external effect points (bytesToCertificate, runSetUp, runRevert, dialIPC, process, sleep, etc.) from package globals into an Admin struct constructed via NewAdmin/defaultDeps. Package-level Run*/Dial functions defer to the Default instance.
Add httptest coverage for router dispatch, game-specific and middleware paths, plus unit tests for models, playfab SteamAppTicket parsing and text moderation. Extend wss tests for additional robustness.
Cover cmdUtils entry points with temporary ArgsStore fixtures so tests don't touch real state.
Un-export newReverter/newAdmin since they take the unexported deps type; keep Default as the public entry point. Make newReverter fill nil deps with production defaults so a zero/partial deps is safe. Drop DefaultDeps in favor of existing defaultDeps. Replace magic 5-games assertion with game.SupportedGames length. Remove no-op TestConfigAdminAgentRunning_NoProcess. Add t.Parallel to isolated executor and admin-elevation tests.
Synchronize net.Pipe agent goroutines with a WaitGroup and funnel agent-side errors through a channel so tests fail loudly instead of leaking or silently passing. Assert the previously no-op EncodeDataFailure/DecodeFinalFailure paths. Remove a duplicate RevertRequiresAdminElevationValues test already covered by configrevert_test.go.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
No description provided.