summaryrefslogtreecommitdiff
path: root/internal/api/scripts_test.go
blob: 7da133ebe74feb21e80031f6579680481ccf5989 (plain)
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
package api

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"testing"
)

func TestHandleDeploy_Success(t *testing.T) {
	srv, _ := testServer(t)

	// Create a fake deploy script that exits 0 and prints output.
	scriptDir := t.TempDir()
	scriptPath := filepath.Join(scriptDir, "deploy")
	script := "#!/bin/sh\necho 'deployed successfully'"
	if err := os.WriteFile(scriptPath, []byte(script), 0o755); err != nil {
		t.Fatal(err)
	}
	srv.deployScript = scriptPath

	req := httptest.NewRequest("POST", "/api/scripts/deploy", nil)
	w := httptest.NewRecorder()
	srv.Handler().ServeHTTP(w, req)

	if w.Code != http.StatusOK {
		t.Fatalf("status: want 200, got %d; body: %s", w.Code, w.Body.String())
	}
	var body map[string]interface{}
	if err := json.NewDecoder(w.Body).Decode(&body); err != nil {
		t.Fatalf("decode: %v", err)
	}
	if body["exit_code"] != float64(0) {
		t.Errorf("exit_code: want 0, got %v", body["exit_code"])
	}
	output, _ := body["output"].(string)
	if output == "" {
		t.Errorf("expected non-empty output")
	}
}

func TestHandleDeploy_ScriptFails(t *testing.T) {
	srv, _ := testServer(t)

	scriptDir := t.TempDir()
	scriptPath := filepath.Join(scriptDir, "deploy")
	script := "#!/bin/sh\necho 'build failed' && exit 1"
	if err := os.WriteFile(scriptPath, []byte(script), 0o755); err != nil {
		t.Fatal(err)
	}
	srv.deployScript = scriptPath

	req := httptest.NewRequest("POST", "/api/scripts/deploy", nil)
	w := httptest.NewRecorder()
	srv.Handler().ServeHTTP(w, req)

	if w.Code != http.StatusOK {
		t.Fatalf("status: want 200, got %d; body: %s", w.Code, w.Body.String())
	}
	var body map[string]interface{}
	if err := json.NewDecoder(w.Body).Decode(&body); err != nil {
		t.Fatalf("decode: %v", err)
	}
	if body["exit_code"] == float64(0) {
		t.Errorf("expected non-zero exit_code")
	}
}