djangonix/test.nix
2024-06-09 15:20:20 +02:00

86 lines
2.4 KiB
Nix

let
sources = import ./npins;
inherit (sources) nixpkgs;
pkgs = import nixpkgs { };
django = pkgs.python3.withPackages (p: [ p.django ]);
settings = {
SMOKE_TEST = "Hello settings";
JSON_SMOKE_TEST = {
"hello" = "json";
};
DATABASES = {
"default" = {
"ENGINE" = "django.db.backends.sqlite3";
"NAME" = "/var/lib/django-smoketest/db.sqlite3";
};
};
};
secretFile = "${./test_assets/secret}";
secrets = {
SECRETS_SMOKE_TEST = secretFile;
};
project = pkgs.runCommandNoCC "smoketest" { } ''
mkdir -p $out
${django}/bin/django-admin startproject smoketest $out
cp ${./test_assets/views.py} $out/smoketest/views.py
cp ${./test_assets/urls.py} $out/smoketest/urls.py
'';
in
pkgs.testers.runNixOSTest (
{ lib, ... }:
{
name = "djangonix smoke test";
nodes.machine =
{ pkgs, config, ... }:
{
imports = [ ./module.nix ];
services.django.smoketest = {
src = project;
inherit settings secrets;
port = 8000;
};
services.nginx = {
enable = true;
recommendedProxySettings = true;
virtualHosts.netbox = {
default = true;
locations."/".proxyPass = "http://localhost:${toString config.services.django.smoketest.port}";
locations."/static/".alias = config.services.django.smoketest.staticAssets;
};
};
};
testScript = ''
import sys
import time
import json
start_all()
machine.wait_for_unit("django-smoketest.service")
machine.wait_for_unit("nginx.service")
time.sleep(1)
with subtest("Test settings"):
status, out = machine.execute("curl http://127.0.0.1/test_settings/")
print(status, repr(out))
if status != 0 or out != "${settings.SMOKE_TEST}":
sys.exit(1)
with subtest("Test secrets"):
status, out = machine.execute("curl http://127.0.0.1/test_secrets/")
print(status, repr(out))
if status != 0 or out != json.load(open("${secretFile}")):
sys.exit(1)
with subtest("Test json"):
status, out = machine.execute("curl http://127.0.0.1:8000/test_json/")
print(status, repr(out))
if status != 0 or json.loads(out) != json.loads('${builtins.toJSON settings.JSON_SMOKE_TEST}'):
sys.exit(1)
'';
}
)