Skip to content

Commit d4284d4

Browse files
authored
Refactor duplicate helpers and brittle tests
Refactor duplicate helpers and replace brittle source-string tests with behavior-focused coverage.
1 parent ebacf0c commit d4284d4

23 files changed

Lines changed: 289 additions & 1430 deletions

‎src/OpenClaw.SetupEngine/ExistingConfigDetector.cs‎

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -44,12 +44,7 @@ public static ExistingConfig Detect(string dataDir, string targetDistroName)
4444
{
4545
var output = proc.StandardOutput.ReadToEnd();
4646
proc.WaitForExit(5000);
47-
var distros = output.Replace("\0", string.Empty)
48-
.Replace("\uFEFF", string.Empty)
49-
.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries)
50-
.Select(d => d.Trim())
51-
.Where(d => d.Length > 0);
52-
hasDistro = distros.Any(d => d.Equals(targetDistroName, StringComparison.OrdinalIgnoreCase));
47+
hasDistro = WslInstallSupport.ContainsDistro(output, targetDistroName);
5348
}
5449
}
5550
catch (Exception ex)

‎src/OpenClaw.SetupEngine/SetupSteps.cs‎

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -580,7 +580,7 @@ private static bool LooksTooOldForVersionCommand(CommandResult result)
580580
}
581581

582582
private static string NormalizeWslOutput(string value)
583-
=> value.Replace("\0", "").Replace("\uFEFF", "");
583+
=> WslInstallSupport.Normalize(value);
584584

585585
private static string FirstUsefulLine(CommandResult result)
586586
{
@@ -1555,21 +1555,15 @@ public override async Task RollbackAsync(SetupContext ctx, CancellationToken ct)
15551555

15561556
// Check if distro is running before trying systemctl stop
15571557
var list = await ctx.Commands.RunAsync(WslConstants.WslExePath, ["--list", "--quiet"], TimeSpan.FromSeconds(15), ct: ct);
1558-
var distros = list.Stdout
1559-
.Replace("\0", "").Replace("\uFEFF", "")
1560-
.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries)
1561-
.Select(d => d.Trim()).Where(d => d.Length > 0).ToList();
1562-
1563-
if (!distros.Any(d => d.Equals(distro, StringComparison.OrdinalIgnoreCase)))
1558+
if (!WslInstallSupport.ContainsDistro(list.Stdout, distro))
15641559
{
15651560
ctx.Logger.Info("[Uninstall] Distro not registered — skipping gateway stop");
15661561
return;
15671562
}
15681563

15691564
// Check distro state — only stop if Running
15701565
var verbose = await ctx.Commands.RunAsync(WslConstants.WslExePath, ["--list", "--verbose"], TimeSpan.FromSeconds(15), ct: ct);
1571-
var isRunning = verbose.Stdout
1572-
.Replace("\0", "").Replace("\uFEFF", "")
1566+
var isRunning = WslInstallSupport.Normalize(verbose.Stdout)
15731567
.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries)
15741568
.Any(line => line.Contains(distro, StringComparison.OrdinalIgnoreCase)
15751569
&& line.Contains("Running", StringComparison.OrdinalIgnoreCase));

‎src/OpenClaw.Tray.WinUI/Pages/UsagePage.xaml.cs‎

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -233,17 +233,10 @@ public void UpdateUsageCost(GatewayCostUsageInfo cost)
233233

234234
private bool ShouldApplyUsageCost(GatewayCostUsageInfo cost)
235235
{
236-
if (cost.Days <= 0)
237-
return true;
238-
239-
// The gateway can compute the requested range inclusively (e.g. 8
240-
// for a 7-day request). Allow ±1 so valid responses are not dropped.
241-
if (Math.Abs(cost.Days - _currentPeriodDays) <= 1)
242-
return true;
243-
244-
// If nothing has ever loaded, accept a mismatched period rather than
245-
// leaving the page spinning forever when an older gateway ignores days.
246-
return !_dailyCostLoading.HasLoaded;
236+
return UsageCostApplicationPolicy.ShouldApply(
237+
cost.Days,
238+
_currentPeriodDays,
239+
_dailyCostLoading.HasLoaded);
247240
}
248241

249242
private void SyncSelectorToServerDays(int days)
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
namespace OpenClawTray.Services;
2+
3+
internal static class UsageCostApplicationPolicy
4+
{
5+
public static bool ShouldApply(int responseDays, int selectedPeriodDays, bool hasLoaded)
6+
{
7+
if (responseDays <= 0)
8+
return true;
9+
10+
// The gateway can compute the requested range inclusively (for example,
11+
// 8 for a 7-day request). Allow +/-1 so valid responses are not dropped.
12+
if (Math.Abs(responseDays - selectedPeriodDays) <= 1)
13+
return true;
14+
15+
// Accept the first response even when an older gateway ignores days, so
16+
// the page does not spin forever waiting for an exact period match.
17+
return !hasLoaded;
18+
}
19+
}

‎tests/OpenClaw.Tray.Tests/AppRefactorContractTests.cs‎

Lines changed: 4 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ public void Setup_IsHostedInTrayAndUsesSelfRestartAfterCompletion()
146146
[Fact]
147147
public void SetupUiPages_DoNotOwnTrayProcessHandoff()
148148
{
149-
var root = GetRepositoryRoot();
149+
var root = TestRepositoryPaths.GetRepositoryRoot();
150150
var setupUiDir = Path.Combine(root, "src", "OpenClaw.SetupEngine.UI");
151151
var source = string.Join(
152152
"\n",
@@ -169,7 +169,7 @@ public void SetupUiPages_DoNotOwnTrayProcessHandoff()
169169
[Fact]
170170
public void SettingsLocalGatewayRemoval_UsesCancelableTrayChildProcess()
171171
{
172-
var root = GetRepositoryRoot();
172+
var root = TestRepositoryPaths.GetRepositoryRoot();
173173
var source = File.ReadAllText(Path.Combine(root, "src", "OpenClaw.Tray.WinUI", "Pages", "SettingsPage.xaml.cs"));
174174

175175
Assert.Contains("ResolveCurrentExecutablePath()", source);
@@ -183,7 +183,7 @@ public void SettingsLocalGatewayRemoval_UsesCancelableTrayChildProcess()
183183
[Fact]
184184
public void SetupUiImages_UseLibraryQualifiedAssetUris()
185185
{
186-
var root = GetRepositoryRoot();
186+
var root = TestRepositoryPaths.GetRepositoryRoot();
187187
var setupUiDir = Path.Combine(root, "src", "OpenClaw.SetupEngine.UI");
188188
var xaml = string.Join(
189189
"\n",
@@ -201,7 +201,7 @@ public void SetupUiImages_UseLibraryQualifiedAssetUris()
201201

202202
private static string ReadAppSources()
203203
{
204-
var root = GetRepositoryRoot();
204+
var root = TestRepositoryPaths.GetRepositoryRoot();
205205
var appDir = Path.Combine(root, "src", "OpenClaw.Tray.WinUI");
206206
return string.Join(
207207
"\n",
@@ -252,24 +252,4 @@ private static void AssertInOrder(string source, params string[] markers)
252252
}
253253
}
254254

255-
private static string GetRepositoryRoot()
256-
{
257-
var env = Environment.GetEnvironmentVariable("OPENCLAW_REPO_ROOT");
258-
if (!string.IsNullOrWhiteSpace(env) && Directory.Exists(env))
259-
return env;
260-
261-
var directory = new DirectoryInfo(AppContext.BaseDirectory);
262-
while (directory != null)
263-
{
264-
if (File.Exists(Path.Combine(directory.FullName, "openclaw-windows-node.slnx")) &&
265-
Directory.Exists(Path.Combine(directory.FullName, "src")))
266-
{
267-
return directory.FullName;
268-
}
269-
270-
directory = directory.Parent;
271-
}
272-
273-
throw new InvalidOperationException("Could not find repository root.");
274-
}
275255
}

‎tests/OpenClaw.Tray.Tests/AsyncListLoadingPageWiringTests.cs‎

Lines changed: 0 additions & 100 deletions
This file was deleted.

‎tests/OpenClaw.Tray.Tests/CapabilitiesPageLocalizationCoverageTests.cs‎

Lines changed: 2 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -12,31 +12,11 @@ public sealed class CapabilitiesPageLocalizationCoverageTests
1212
{
1313
private static readonly XNamespace XNs = "http://schemas.microsoft.com/winfx/2006/xaml";
1414

15-
private static string GetRepositoryRoot()
16-
{
17-
var envRepoRoot = Environment.GetEnvironmentVariable("OPENCLAW_REPO_ROOT");
18-
if (!string.IsNullOrWhiteSpace(envRepoRoot) && Directory.Exists(envRepoRoot))
19-
return envRepoRoot;
20-
21-
var directory = new DirectoryInfo(AppContext.BaseDirectory);
22-
while (directory != null)
23-
{
24-
if ((Directory.Exists(Path.Combine(directory.FullName, ".git")) ||
25-
File.Exists(Path.Combine(directory.FullName, ".git"))) &&
26-
File.Exists(Path.Combine(directory.FullName, "README.md")))
27-
return directory.FullName;
28-
directory = directory.Parent;
29-
}
30-
31-
throw new InvalidOperationException(
32-
"Could not find repository root. Set OPENCLAW_REPO_ROOT to the repo path.");
33-
}
34-
3515
private static string GetCapabilitiesXamlPath() =>
36-
Path.Combine(GetRepositoryRoot(), "src", "OpenClaw.Tray.WinUI", "Pages", "PermissionsPage.xaml");
16+
Path.Combine(TestRepositoryPaths.GetRepositoryRoot(), "src", "OpenClaw.Tray.WinUI", "Pages", "PermissionsPage.xaml");
3717

3818
private static string GetEnUsReswPath() =>
39-
Path.Combine(GetRepositoryRoot(), "src", "OpenClaw.Tray.WinUI", "Strings", "en-us", "Resources.resw");
19+
Path.Combine(TestRepositoryPaths.GetRepositoryRoot(), "src", "OpenClaw.Tray.WinUI", "Strings", "en-us", "Resources.resw");
4020

4121
private static HashSet<string> LoadReswKeys()
4222
{

‎tests/OpenClaw.Tray.Tests/ChatToolCallsToggleContractTests.cs‎

Lines changed: 2 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ public sealed class ChatToolCallsToggleContractTests
88
public void ProductionTimeline_HonorsComposerToolCallVisibilityToggle()
99
{
1010
var source = File.ReadAllText(Path.Combine(
11-
GetRepositoryRoot(),
11+
TestRepositoryPaths.GetRepositoryRoot(),
1212
"src",
1313
"OpenClaw.Tray.WinUI",
1414
"Chat",
@@ -29,7 +29,7 @@ public void ProductionTimeline_HonorsComposerToolCallVisibilityToggle()
2929
public void TaskListToolBurst_LabelsHeaderAndExpandedBodyForScreenReaders()
3030
{
3131
var source = File.ReadAllText(Path.Combine(
32-
GetRepositoryRoot(),
32+
TestRepositoryPaths.GetRepositoryRoot(),
3333
"src",
3434
"OpenClaw.Tray.WinUI",
3535
"Chat",
@@ -46,24 +46,4 @@ public void TaskListToolBurst_LabelsHeaderAndExpandedBodyForScreenReaders()
4646
source);
4747
}
4848

49-
private static string GetRepositoryRoot()
50-
{
51-
var env = Environment.GetEnvironmentVariable("OPENCLAW_REPO_ROOT");
52-
if (!string.IsNullOrWhiteSpace(env) && Directory.Exists(env))
53-
return env;
54-
55-
var directory = new DirectoryInfo(AppContext.BaseDirectory);
56-
while (directory != null)
57-
{
58-
if (File.Exists(Path.Combine(directory.FullName, "openclaw-windows-node.slnx")) &&
59-
Directory.Exists(Path.Combine(directory.FullName, "src")))
60-
{
61-
return directory.FullName;
62-
}
63-
64-
directory = directory.Parent;
65-
}
66-
67-
throw new InvalidOperationException("Could not find repository root.");
68-
}
6949
}

0 commit comments

Comments
 (0)