feat: switch to module system to evaluate suites & tests

add autodiscovery feature
This commit is contained in:
technofab 2025-06-12 21:23:28 +02:00
parent e8da91ad27
commit 98141a1f5c
No known key found for this signature in database
5 changed files with 312 additions and 95 deletions

View file

@ -1,62 +1,64 @@
{
pkgs,
lib ? pkgs.lib,
self ? "",
...
}: {
mkTest = {
type ? "unit",
name,
description ? "",
format ? "json",
expected ? null,
actual ? null,
actualDrv ? null,
script ? null,
pos ? null,
}: let
inherit (lib) evalModules toList;
in rec {
mkBinary = {
nixtests,
extraParams,
}: let
fileRelative = lib.removePrefix ((toString self) + "/") pos.file;
actual' =
if format == "json"
then actual
else lib.generators.toPretty {} actual;
expected' =
if format == "json"
then expected
else lib.generators.toPretty {} expected;
program = pkgs.callPackage ../package.nix {};
in
assert lib.assertMsg (!(type == "script" && script == null)) "test ${name} has type 'script' but no script was passed"; {
inherit type name description;
actual = actual';
expected = expected';
# discard string context, otherwise it's being built instantly which we don't want
actualDrv = builtins.unsafeDiscardStringContext (actualDrv.drvPath or "");
script =
if script != null
then
builtins.unsafeDiscardStringContext
(pkgs.writeShellScript "nixtest-${name}" ''
# show which line failed the test
set -x
${script}
'').drvPath
else null;
pos =
if pos == null
then ""
else "${fileRelative}:${toString pos.line}";
(pkgs.writeShellScriptBin "nixtests:run" ''
${program}/bin/nixtest --tests=${nixtests} ${extraParams} "$@"
'')
// {
tests = nixtests;
};
mkSuite = name: tests: {
inherit name tests;
};
exportSuites = suites: let
suitesList =
if builtins.isList suites
then suites
else [suites];
testsMapped = builtins.toJSON suitesList;
suitesMapped = builtins.toJSON suitesList;
in
pkgs.runCommand "tests.json" {} ''
echo '${testsMapped}' > $out
echo '${suitesMapped}' > $out
'';
module = import ./module.nix {inherit lib pkgs;};
autodiscover = {
dir,
pattern ? ".*_test.nix",
}: let
files = builtins.readDir dir;
matchingFiles = builtins.filter (name: builtins.match pattern name != null) (builtins.attrNames files);
imports = map (file: /${dir}/${file}) matchingFiles;
in {
inherit imports;
# automatically set the base so test filepaths are easier to read
config.base = builtins.toString dir + "/";
};
mkNixtestConfig = {
modules,
args,
...
}:
(evalModules {
modules =
(toList modules)
++ [
module
{
_module.args = args;
}
];
}).config;
mkNixtest = args: (mkNixtestConfig args).app;
}