Progmasoft Git

tazel

A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.

Clonegit clone https://git.progmasoft.com/tazel

Do not run a passed test again while what it runs with is the same

A test that passed is remembered by a key over its program and the shared
libraries beside it by content, its data, arguments and environment, its
shards, timeout and retries, and the output root of its platform and mode.
While the key is the same, tazel test shows it as PASSED (cached) with the
log of its last run. A test tagged no-cache runs every time; a flaky pass is
not remembered, and tazel coverage runs every test.
Commit
576359cd4986ba3e94accb7dbe3f0cd9c966646d
Author
Leitwolf11 ·
Parents
f200feb603d1

Files · Download .tar.gz

Changes

 CHANGELOG.md                                   |  2 +
 docs/commands.md                               |  5 ++
 src/Progmasoft.Tazel/Cli/Commands.cs           |  2 +-
 src/Progmasoft.Tazel/Cli/Help.cs               |  6 ++-
 src/Progmasoft.Tazel/Driver/TestRunner.cs      | 71 +++++++++++++++++++++++++-
 src/Progmasoft.Tazel/Output/Reporter.cs        |  4 ++
 tests/Progmasoft.Tazel.Tests/TestCacheTests.cs | 49 ++++++++++++++++++
 7 files changed, 135 insertions(+), 4 deletions(-)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index a8fbfbb..2099e26 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,6 +27,8 @@ The first version of Tazel, written in C# for .NET 10.
 - The MicroVM: with `sandboxing-with-microvm`, `tazel custom` runs in a Linux guest under Cloud Hypervisor on KVM
   that sees the module and the host's `/usr`, read-only, and nothing else; its agent `tazel-guest`, and
   `microvm/build.cs`, which builds the guest image.
+- A test that passed is not run again while its program, the shared libraries beside it, its data, arguments,
+  environment, shards, timeout and retries are the same; `no-cache` runs it every time.
 - Plugins: `Progmasoft.Tazel.PluginApi`, the project SDK `Progmasoft.Tazel.PluginSdk` that packs a plugin with
   `dotnet pack`, the template `dotnet new tazel-plugin`, local plugins loaded each into its own load context, and build
   steps that plugins and `BUILD.csx` files declare.
diff --git a/docs/commands.md b/docs/commands.md
index 5955901..ba72db0 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -65,6 +65,11 @@ environment is `PATH`, its `InheritedEnvironmentVariables`, `TEST_TMPDIR`, `TEST
 variables and its `EnvironmentVariables`. Its log is `.tazel/testlogs/<package>/<name>/test.log`. A test tagged
 `exclusive` runs alone.
 
+A test that passed is not run again while what it runs with is the same: its program and the shared libraries
+beside it by content, its data, arguments and environment, its shards, timeout and retries, and the platform and mode.
+It shows as `PASSED (cached)` with the log of its last run. A test tagged `no-cache` runs every time, a flaky pass is
+not remembered, and `tazel coverage` runs every test.
+
 `tazel run` runs the program in its runfiles directory with Tazel's environment and the program's
 `EnvironmentVariables`, its `Arguments` and what follows `--`, and returns its exit status.
 
diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs
index fcfc4ea..8318e71 100644
--- a/src/Progmasoft.Tazel/Cli/Commands.cs
+++ b/src/Progmasoft.Tazel/Cli/Commands.cs
@@ -272,7 +272,7 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector
                 var outcomes = await new TestRunner(planner.Layout, buildOptions.Jobs, reporter, buildOptions.Coverage)
                     .RunAsync(tests, cancel).ConfigureAwait(false);
                 reporter.TestSummary(outcomes);
-                var passed = outcomes.All(outcome => outcome.Status is TestStatus.Passed or TestStatus.Flaky);
+                var passed = outcomes.All(outcome => outcome.Status is TestStatus.Passed or TestStatus.Cached or TestStatus.Flaky);
                 if (kind == BuildKind.Coverage)
                 {
                     var reported = await CoverageReport.WriteAsync(planner, chooser, tests, reporter, cancel).ConfigureAwait(false);
diff --git a/src/Progmasoft.Tazel/Cli/Help.cs b/src/Progmasoft.Tazel/Cli/Help.cs
index d823b7c..19a89a0 100644
--- a/src/Progmasoft.Tazel/Cli/Help.cs
+++ b/src/Progmasoft.Tazel/Cli/Help.cs
@@ -55,8 +55,10 @@ internal static class Help
 
             Builds the tests of the labels and runs each in its runfiles directory, with its own TEST_TMPDIR, the
             shard variables, and a timeout from its TestSize (1, 5, 15, 60 minutes) or its Timeout; a flaky test runs
-            up to three times, and a test tagged exclusive runs alone. Logs go to .tazel/testlogs/; the output of a
-            test that failed is printed, then a table of every test.
+            up to three times, and a test tagged exclusive runs alone. A test that passed is not run again while its
+            program, data, arguments and environment are the same; it shows as PASSED (cached), and a test tagged
+            no-cache runs every time. Logs go to .tazel/testlogs/; the output of a test that failed is printed, then a
+            table of every test.
 
             {Labels}
 
diff --git a/src/Progmasoft.Tazel/Driver/TestRunner.cs b/src/Progmasoft.Tazel/Driver/TestRunner.cs
index 972aaaf..d1dcf0a 100644
--- a/src/Progmasoft.Tazel/Driver/TestRunner.cs
+++ b/src/Progmasoft.Tazel/Driver/TestRunner.cs
@@ -111,6 +111,24 @@ internal sealed class TestRunner(OutputLayout layout, int jobs, Reporter reporte
         var settings = (ITestSettings)target.Settings;
         var runfiles = Runfiles.Prepare(target, products, layout);
         var logDirectory = layout.Full($"{layout.TestLogs}/{Sanitize(target.Label.ToString())}");
+        var passedFile = Path.Combine(layout.Full(layout.TestLogs), ".passed", Sanitize(target.Label.ToString()).Replace('/', '_'));
+        // Coverage needs the run itself, and a test tagged no-cache runs every time.
+        var key = coverage || target.Settings.Tags.Contains("no-cache", StringComparer.Ordinal)
+            ? null
+            : CacheKey(target, settings, products, runfiles);
+        if (key is not null && File.Exists(passedFile) &&
+            await File.ReadAllTextAsync(passedFile, cancel).ConfigureAwait(false) == key &&
+            File.Exists(Path.Combine(logDirectory, "test.log")))
+        {
+            var previous = await File.ReadAllTextAsync(Path.Combine(logDirectory, "test.log"), cancel).ConfigureAwait(false);
+            return new TestOutcome(target.Label.ToString(), TestStatus.Cached, TimeSpan.Zero, previous);
+        }
+
+        if (File.Exists(passedFile))
+        {
+            File.Delete(passedFile);
+        }
+
         if (Directory.Exists(logDirectory))
         {
             Directory.Delete(logDirectory, recursive: true);
@@ -157,6 +175,13 @@ internal sealed class TestRunner(OutputLayout layout, int jobs, Reporter reporte
             if (!failed)
             {
                 var status = attempt == 1 ? TestStatus.Passed : TestStatus.Flaky;
+                // A flaky pass is not remembered: the next run should show whether it is flaky still.
+                if (key is not null && status == TestStatus.Passed)
+                {
+                    Directory.CreateDirectory(Path.GetDirectoryName(passedFile)!);
+                    await File.WriteAllTextAsync(passedFile, key, cancel).ConfigureAwait(false);
+                }
+
                 return new TestOutcome(target.Label.ToString(), status, watch.Elapsed, log.ToString());
             }
 
@@ -172,6 +197,46 @@ internal sealed class TestRunner(OutputLayout layout, int jobs, Reporter reporte
         throw new InvalidOperationException("a test ended without an outcome");
     }
 
+    /// <summary>
+    /// What a run of the test depends on: its program and the shared libraries beside it by content, its data, its
+    /// arguments, its environment less the parts that change every run, its shards, timeout and retries, and where its
+    /// outputs are, which names the platform and mode.
+    /// </summary>
+    private string CacheKey(ProjectTarget target, ITestSettings settings, TargetProducts products, string runfiles)
+    {
+        var text = new StringBuilder();
+        text.Append(CultureInfo.InvariantCulture, $"out {layout.OutRoot}\nprogram {Archive.Sha256Sums.Sha256(layout.Full(products.Executable!))}\n");
+        foreach (var directory in products.SharedLibraryDirectories.Select(layout.Full).Where(Directory.Exists).Order(StringComparer.Ordinal))
+        {
+            foreach (var file in Directory.EnumerateFiles(directory).Order(StringComparer.Ordinal))
+            {
+                text.Append(CultureInfo.InvariantCulture, $"library {Path.GetFileName(file)} {Archive.Sha256Sums.Sha256(file)}\n");
+            }
+        }
+
+        foreach (var file in Directory.EnumerateFiles(runfiles, "*", SearchOption.AllDirectories)
+                     .Select(file => Path.GetRelativePath(runfiles, file).Replace('\\', '/')).Order(StringComparer.Ordinal))
+        {
+            text.Append(CultureInfo.InvariantCulture, $"data {file} {Archive.Sha256Sums.Sha256(Path.Combine(runfiles, file))}\n");
+        }
+
+        foreach (var argument in settings.Arguments)
+        {
+            text.Append(CultureInfo.InvariantCulture, $"argument {argument.Length}:{argument}\n");
+        }
+
+        var environment = Environment(target, settings, "<log>", 0, "<runfiles>");
+        foreach (var (name, value) in environment.Where(e => e.Key is not ("TEST_TMPDIR" or "TMPDIR" or "HOME"))
+                     .OrderBy(e => e.Key, StringComparer.Ordinal))
+        {
+            text.Append(CultureInfo.InvariantCulture, $"env {name}={value.Length}:{value}\n");
+        }
+
+        text.Append(CultureInfo.InvariantCulture,
+            $"shards {settings.ShardCount}\ntimeout {(settings.Timeout ?? TimeoutOf(settings.TestSize)).Ticks}\nflaky {settings.Flaky}\n");
+        return Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString())));
+    }
+
     private static Dictionary<string, string> Environment(
         ProjectTarget target, ITestSettings settings, string logDirectory, int shard, string runfiles)
     {
@@ -185,7 +250,11 @@ internal sealed class TestRunner(OutputLayout layout, int jobs, Reporter reporte
         }
 
         var temporary = Path.Combine(logDirectory, $"tmp{shard}");
-        Directory.CreateDirectory(temporary);
+        if (logDirectory != "<log>")
+        {
+            Directory.CreateDirectory(temporary);
+        }
+
         environment["TEST_TMPDIR"] = temporary;
         environment["TMPDIR"] = temporary;
         environment["HOME"] = temporary;
diff --git a/src/Progmasoft.Tazel/Output/Reporter.cs b/src/Progmasoft.Tazel/Output/Reporter.cs
index ffc5148..d2dd754 100644
--- a/src/Progmasoft.Tazel/Output/Reporter.cs
+++ b/src/Progmasoft.Tazel/Output/Reporter.cs
@@ -25,6 +25,9 @@ internal enum When
 internal enum TestStatus
 {
     Passed,
+
+    /// <summary>It passed before with the same program, data, arguments and environment, so it did not run again.</summary>
+    Cached,
     Failed,
     TimedOut,
     Flaky,
@@ -229,6 +232,7 @@ internal sealed class Reporter
             var status = outcome.Status switch
             {
                 TestStatus.Passed => "[green]PASSED[/]",
+                TestStatus.Cached => "[green]PASSED[/] [grey](cached)[/]",
                 TestStatus.Flaky => "[yellow]FLAKY[/]",
                 TestStatus.TimedOut => "[red]TIMEOUT[/]",
                 TestStatus.NotBuilt => "[red]NOT BUILT[/]",
diff --git a/tests/Progmasoft.Tazel.Tests/TestCacheTests.cs b/tests/Progmasoft.Tazel.Tests/TestCacheTests.cs
new file mode 100644
index 0000000..c344416
--- /dev/null
+++ b/tests/Progmasoft.Tazel.Tests/TestCacheTests.cs
@@ -0,0 +1,49 @@
+// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
+// SPDX-License-Identifier: MIT
+
+using System;
+using System.Threading.Tasks;
+using Progmasoft.Tazel.Driver;
+using Xunit;
+
+namespace Progmasoft.Tazel.Tests;
+
+public sealed class TestCacheTests
+{
+    private const string Build = """
+        using Progmasoft.Tazel.Dsl.Build.Prelude;
+        CC.Test("reads_test", new() { Sources = ["reads.c"], RuntimeData = ["data.txt"], Arguments = ["data.txt"] });
+        CC.Test("always_test", new() { Sources = ["reads.c"], RuntimeData = ["data.txt"], Arguments = ["data.txt"], Tags = ["no-cache"] });
+        """;
+
+    private const string Reads = """
+        #include <stdio.h>
+        int main(int argc, char **argv) { FILE *f = fopen(argv[1], "r"); if (!f) return 1; puts("read it"); fclose(f); return 0; }
+        """;
+
+    [Fact]
+    public async Task APassedTestRunsAgainOnlyWhenWhatItRunsWithChanges()
+    {
+        Assert.SkipWhen(Host.Which("clang") is null && Host.Which("gcc") is null && Host.Which("zig") is null, "no C compiler");
+        using var module = new TemporaryModule().Write("MODULE.csx", TemporaryModule.ModuleFile).Write("BUILD.csx", Build)
+            .Write("reads.c", Reads).Write("data.txt", "one");
+        var (status, output) = await module.TazelAsync(".", "test", "//...");
+        Assert.True(status == 0, output);
+        Assert.DoesNotContain("(cached)", output, StringComparison.Ordinal);
+
+        (status, output) = await module.TazelAsync(".", "test", "//...");
+        Assert.True(status == 0, output);
+        Assert.Matches(@"//:reads_test\s*│?\s*PASSED \(cached\)", output);
+        Assert.DoesNotMatch(@"//:always_test\s*│?\s*PASSED \(cached\)", output);
+
+        module.Write("data.txt", "two");
+        (status, output) = await module.TazelAsync(".", "test", "//:reads_test");
+        Assert.True(status == 0, output);
+        Assert.DoesNotContain("(cached)", output, StringComparison.Ordinal);
+
+        module.Write("BUILD.csx", Build.Replace("Arguments = [\"data.txt\"] });\nCC.Test(\"always", "Arguments = [\"data.txt\", \"x\"] });\nCC.Test(\"always", StringComparison.Ordinal));
+        (status, output) = await module.TazelAsync(".", "test", "//:reads_test");
+        Assert.True(status == 0, output);
+        Assert.DoesNotContain("(cached)", output, StringComparison.Ordinal);
+    }
+}