1 /* Create tests that run in the nix sandbox with additional access to selected host paths
3 This is for example useful for testing hardware where a tests needs access to
4 /sys and optionally more.
6 The following example shows a test that accesses the GPU:
11 testedPackage = "mypackage"; # Or testPath = "mypackage.impureTests.opencl.testDerivation"
13 sandboxPaths = [ "/sys" "/dev/dri" ]; # Defaults to ["/sys"]
14 prepareRunCommands = ""; # (Optional) Setup for the runScript
15 nixFlags = []; # (Optional) nix-build options for the runScript
20 Save as `test.nix` next to a package and reference it from the package:
21 passthru.impureTests = { opencl = callPackage ./test.nix {}; };
23 `makeImpureTest` will return here a script that contains the actual nix-build command including all necessary sandbox flags.
25 It can be executed like this:
26 $(nix-build -A mypackage.impureTests)
28 Rerun an already cached test:
29 $(nix-build -A mypackage.impureTests) --check
36 , testedPackage ? null
37 , testPath ? "${testedPackage}.impureTests.${name}.testDerivation"
38 , sandboxPaths ? [ "/sys" ]
39 , prepareRunCommands ? ""
46 sandboxPathsTests = builtins.map (path: "[[ ! -e '${path}' ]]") sandboxPaths;
47 sandboxPathsTest = lib.concatStringsSep " || " sandboxPathsTests;
48 sandboxPathsList = lib.concatStringsSep " " sandboxPaths;
50 testDerivation = stdenv.mkDerivation (lib.recursiveUpdate
52 name = "test-run-${name}";
54 requiredSystemFeatures = [ "nixos-test" ];
59 if ${sandboxPathsTest}; then
60 echo 'Run this test as *root* with `--option extra-sandbox-paths '"'${sandboxPathsList}'"'`'
68 passthru.runScript = runScript;
70 (builtins.removeAttrs args [
85 runScript = writeShellScript "run-script-${name}" ''
90 sudo nix-build --option extra-sandbox-paths '${sandboxPathsList}' ${lib.escapeShellArgs nixFlags} -A ${testPath} "$@"
93 # The main output is the run script, inject the derivation for the actual test
94 runScript.overrideAttrs (old: {
95 passthru = { inherit testDerivation; };