From ae4b3d585d2ee7257d36425e0dbe0736684ee2b1 Mon Sep 17 00:00:00 2001 From: rootile Date: Mon, 9 Mar 2026 20:19:38 +0100 Subject: [PATCH] f2/nix: provide a high-level wrapper for calling builtins Change-Id: I357bd7630b96e55d000fbff1032efcf8c98dfb7b --- tests/functional2/testlib/fixtures/nix.py | 14 ++++++++++++++ tests/functional2/testlib/fixtures/test_nix.py | 13 ++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/tests/functional2/testlib/fixtures/nix.py b/tests/functional2/testlib/fixtures/nix.py index 2a3d8d50a..7591bf8e3 100644 --- a/tests/functional2/testlib/fixtures/nix.py +++ b/tests/functional2/testlib/fixtures/nix.py @@ -238,6 +238,20 @@ class Nix: self._settings = orig return cmd.run() + def eval_builtin(self, name: str, *args: _NixValue) -> CommandResult: + """ + This is a high-level wrapper, to easily evaluate and obtain the result of a builtin. + + In the background, it calls `nix eval --json --expr builtins.{name} {args}` + It is recommended to call `.json()` on the return value. + + :param name: name of the builtin + :param args: list of arguments to provide to the builtin + :return: result of the evaluation + """ + args = [serialise_nix(arg) for arg in args] + return self.eval(f"builtins.{name} {' '.join(args)}") + @property def store_dir(self) -> Path: """ diff --git a/tests/functional2/testlib/fixtures/test_nix.py b/tests/functional2/testlib/fixtures/test_nix.py index f3a2952d4..ceab86673 100644 --- a/tests/functional2/testlib/fixtures/test_nix.py +++ b/tests/functional2/testlib/fixtures/test_nix.py @@ -3,7 +3,7 @@ from pathlib import Path import pytest from testlib.fixtures.env import ManagedEnv -from testlib.fixtures.nix import NixSettings, serialise_nix +from testlib.fixtures.nix import NixSettings, Nix, serialise_nix from textwrap import dedent @@ -119,6 +119,17 @@ def test_nix_settings_to_env_overlay_no_store_dir(tmp_path: Path): assert "store = local?root=/some/path\n" in env._env["NIX_CONFIG"] +class TestNixEvalBuiltins: + def test_add(self, nix: Nix): + assert nix.eval_builtin("add", 1, 2).ok().stdout_plain == "3" + + def test_attrnames(self, nix: Nix): + assert nix.eval_builtin("attrNames", {"a": "b", "c": 1}).json() == ["a", "c"] + + def test_attrvalues(self, nix: Nix): + assert nix.eval_builtin("attrValues", {"a": "b", "c": 1}).json() == ["b", 1] + + class TestSerialiseNix: def test_list(self): assert serialise_nix(["a", 1, None]) == '["a" 1 null]'