a73x

internal/site/cli_test.go

Ref:   Size: 2.6 KiB   History

package site

import (
	"encoding/json"
	"os"
	"path/filepath"
	"strings"
	"testing"

	"github.com/a73x/eitri/internal/server/release"
)

// TestRunCLIBuild renders the site through the command-line entry point,
// exercising the default (no-subcommand) flag path.
func TestRunCLIBuild(t *testing.T) {
	root, docs, siteDir := writeFixture(t)
	out := filepath.Join(root, "out")
	if err := RunCLI([]string{"-docs", docs, "-site", siteDir, "-out", out}); err != nil {
		t.Fatalf("RunCLI build: %v", err)
	}
	if _, err := os.Stat(filepath.Join(out, "index.html")); err != nil {
		t.Errorf("index.html not emitted: %v", err)
	}
}

// TestRunCLIBuildError surfaces a build failure (an absent tree) as an error,
// not a panic.
func TestRunCLIBuildError(t *testing.T) {
	absent := filepath.Join(t.TempDir(), "absent")
	if err := RunCLI([]string{"-docs", absent, "-site", absent, "-out", absent}); err == nil {
		t.Error("build over an absent tree must error")
	}
}

// TestRunCLIManifest writes a release manifest through the "manifest"
// subcommand, to both an explicit -out and the default <dist>/manifest.json.
func TestRunCLIManifest(t *testing.T) {
	dist := t.TempDir()
	if err := os.WriteFile(filepath.Join(dist, "eitri-server_v0.0.1_linux_amd64.tar.gz"), []byte("x"), 0o644); err != nil {
		t.Fatal(err)
	}

	outPath := filepath.Join(dist, "m.json")
	if err := RunCLI([]string{"manifest", "-version", "v0.0.1", "-dist", dist, "-base", "https://eitri.sh/dl/v0.0.1", "-out", outPath}); err != nil {
		t.Fatalf("RunCLI manifest: %v", err)
	}
	raw, err := os.ReadFile(outPath)
	if err != nil {
		t.Fatal(err)
	}
	var m release.Manifest
	if err := json.Unmarshal(raw, &m); err != nil {
		t.Fatalf("manifest not valid json: %v", err)
	}
	if m.Version != "v0.0.1" {
		t.Errorf("manifest version = %q", m.Version)
	}

	// With -out omitted the manifest lands at <dist>/manifest.json.
	if err := RunCLI([]string{"manifest", "-version", "v0.0.1", "-dist", dist, "-base", "https://eitri.sh/dl/v0.0.1"}); err != nil {
		t.Fatalf("RunCLI manifest default out: %v", err)
	}
	if _, err := os.Stat(filepath.Join(dist, "manifest.json")); err != nil {
		t.Errorf("default manifest.json not written: %v", err)
	}
}

// TestRunCLIManifestRequiresFlags names the missing required flags, prefixed so
// the caller can tell a manifest failure from a build failure.
func TestRunCLIManifestRequiresFlags(t *testing.T) {
	err := RunCLI([]string{"manifest", "-version", "v0.0.1"})
	if err == nil || !strings.Contains(err.Error(), "required") {
		t.Errorf("manifest without -dist/-base: got %v", err)
	}
	if err != nil && !strings.Contains(err.Error(), "manifest:") {
		t.Errorf("manifest error must be prefixed: got %v", err)
	}
}