|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.IO; |
| 4 | +using System.Linq; |
| 5 | +using BrowserGuard; |
| 6 | +using Xunit; |
| 7 | + |
| 8 | +namespace BrowserGuard.Tests |
| 9 | +{ |
| 10 | + public class EnvDumpTests : IDisposable |
| 11 | + { |
| 12 | + readonly string tempDir; |
| 13 | + |
| 14 | + public EnvDumpTests() |
| 15 | + { |
| 16 | + tempDir = Path.Combine(Path.GetTempPath(), "browserguard-envdump-" + Guid.NewGuid().ToString("N")); |
| 17 | + Directory.CreateDirectory(tempDir); |
| 18 | + } |
| 19 | + |
| 20 | + public void Dispose() |
| 21 | + { |
| 22 | + try { Directory.Delete(tempDir, true); } catch { } |
| 23 | + } |
| 24 | + |
| 25 | + // Built next to the test assembly only when the whole solution is built, |
| 26 | + // so the check is skipped rather than failing a host-only build. |
| 27 | + static string? FindEnvDump() |
| 28 | + { |
| 29 | + var repoRoot = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..")); |
| 30 | + var candidates = new[] { "Debug", "Release" } |
| 31 | + .Select(c => Path.Combine(repoRoot, "tools", "EnvDump", "bin", c, "net8.0", "EnvDump.exe")); |
| 32 | + return candidates.FirstOrDefault(File.Exists); |
| 33 | + } |
| 34 | + |
| 35 | + [Fact] |
| 36 | + public void StartsTheProgramWithTheConfiguredDirectoryAndEnvironment() |
| 37 | + { |
| 38 | + var envDump = FindEnvDump(); |
| 39 | + if (envDump is null) |
| 40 | + { |
| 41 | + return; |
| 42 | + } |
| 43 | + |
| 44 | + var config = new StartupLauncherConfig |
| 45 | + { |
| 46 | + Enabled = true, |
| 47 | + Programs = |
| 48 | + [ |
| 49 | + new StartupProgramConfig |
| 50 | + { |
| 51 | + Path = envDump, |
| 52 | + WorkingDirectory = tempDir, |
| 53 | + EnvironmentVariables = new Dictionary<string, string> |
| 54 | + { |
| 55 | + ["BROWSERGUARD_STARTUP_TEST"] = "from-config", |
| 56 | + }, |
| 57 | + }, |
| 58 | + ], |
| 59 | + }; |
| 60 | + |
| 61 | + Assert.Null(StartupLauncher.Run(config)); |
| 62 | + |
| 63 | + var report = Path.Combine(tempDir, "envdump.txt"); |
| 64 | + Assert.True(WaitForFile(report), "the program did not write its report"); |
| 65 | + |
| 66 | + var lines = File.ReadAllLines(report); |
| 67 | + Assert.Contains($"WorkingDirectory={tempDir}", lines); |
| 68 | + Assert.Contains("BROWSERGUARD_STARTUP_TEST=from-config", lines); |
| 69 | + // The configured variables are added to the inherited environment. |
| 70 | + Assert.Contains(lines, line => line.StartsWith("PATH=", StringComparison.OrdinalIgnoreCase)); |
| 71 | + } |
| 72 | + |
| 73 | + static bool WaitForFile(string path) |
| 74 | + { |
| 75 | + for (var i = 0; i < 100 && !File.Exists(path); i++) |
| 76 | + { |
| 77 | + System.Threading.Thread.Sleep(100); |
| 78 | + } |
| 79 | + return File.Exists(path); |
| 80 | + } |
| 81 | + } |
| 82 | +} |
0 commit comments