about summary refs log tree commit diff
path: root/nixos/tests/hostname.nix
blob: dffec956bc0b68438f84f6588aa0a1fb67ddfe32 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
{ system ? builtins.currentSystem
, config ? { }
, pkgs ? import ../.. { inherit system config; }
}:

with import ../lib/testing-python.nix { inherit system pkgs; };
with pkgs.lib;

let
  makeHostNameTest = hostName: domain: fqdnOrNull:
    let
      fqdn = hostName + (optionalString (domain != null) ".${domain}");
      getStr = str: # maybeString2String
        let res = builtins.tryEval str;
        in if (res.success && res.value != null) then res.value else "null";
    in
    makeTest {
      name = "hostname-${fqdn}";
      meta = with pkgs.lib.maintainers; {
        maintainers = [ primeos blitz ];
      };

      nodes.machine = { lib, ... }: {
        networking.hostName = hostName;
        networking.domain = domain;

        environment.systemPackages = with pkgs; [
          inetutils
        ];
      };

      testScript = { nodes, ... }: ''
        start_all()

        machine = ${hostName}

        machine.systemctl("start network-online.target")
        machine.wait_for_unit("network-online.target")

        # Test if NixOS computes the correct FQDN (either a FQDN or an error/null):
        assert "${getStr nodes.machine.networking.fqdn}" == "${getStr fqdnOrNull}"

        # The FQDN, domain name, and hostname detection should work as expected:
        assert "${fqdn}" == machine.succeed("hostname --fqdn").strip()
        assert "${optionalString (domain != null) domain}" == machine.succeed("dnsdomainname").strip()
        assert (
            "${hostName}"
            == machine.succeed(
                'hostnamectl status | grep "Static hostname" | cut -d: -f2'
            ).strip()
        )

        # 127.0.0.1 and ::1 should resolve back to "localhost":
        assert (
            "localhost" == machine.succeed("getent hosts 127.0.0.1 | awk '{print $2}'").strip()
        )
        assert "localhost" == machine.succeed("getent hosts ::1 | awk '{print $2}'").strip()

        # 127.0.0.2 should resolve back to the FQDN and hostname:
        fqdn_and_host_name = "${optionalString (domain != null) "${hostName}.${domain} "}${hostName}"
        assert (
            fqdn_and_host_name
            == machine.succeed("getent hosts 127.0.0.2 | awk '{print $2,$3}'").strip()
        )
      '';
    };

in
{
  noExplicitDomain = makeHostNameTest "ahost" null null;

  explicitDomain = makeHostNameTest "ahost" "adomain" "ahost.adomain";
}