| 1 | package protocolgen |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "os" |
| 6 | "path/filepath" |
| 7 | "testing" |
| 8 | ) |
| 9 | |
| 10 | func TestGeneratedArtifactsAreDeterministicAndCommitted(t *testing.T) { |
| 11 | first, err := Generate() |
| 12 | if err != nil { |
| 13 | t.Fatal(err) |
| 14 | } |
| 15 | second, err := Generate() |
| 16 | if err != nil { |
| 17 | t.Fatal(err) |
| 18 | } |
| 19 | if len(first) != 4 || len(second) != len(first) { |
| 20 | t.Fatalf("generated %d/%d artifacts, want 4", len(first), len(second)) |
| 21 | } |
| 22 | |
| 23 | temporaryRoot := t.TempDir() |
| 24 | if err := Write(temporaryRoot, first); err != nil { |
| 25 | t.Fatal(err) |
| 26 | } |
| 27 | repositoryRoot := filepath.Clean(filepath.Join("..", "..", "..")) |
| 28 | for i, artifact := range first { |
| 29 | if artifact.Path != second[i].Path || !bytes.Equal(artifact.Data, second[i].Data) { |
| 30 | t.Fatalf("artifact %s is not deterministic", artifact.Path) |
| 31 | } |
| 32 | generated, err := os.ReadFile(filepath.Join(temporaryRoot, filepath.FromSlash(artifact.Path))) |
| 33 | if err != nil { |
| 34 | t.Fatal(err) |
| 35 | } |
| 36 | committed, err := os.ReadFile(filepath.Join(repositoryRoot, filepath.FromSlash(artifact.Path))) |
| 37 | if err != nil { |
| 38 | t.Fatal(err) |
| 39 | } |
| 40 | if !bytes.Equal(generated, committed) { |
| 41 | t.Fatalf("committed artifact drift: %s (run go run ./cmd/extension-protocol-gen -root .)", artifact.Path) |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | func TestCheckRejectsAnyArtifactDrift(t *testing.T) { |
| 47 | artifacts, err := Generate() |
| 48 | if err != nil { |
| 49 | t.Fatal(err) |
| 50 | } |
| 51 | root := t.TempDir() |
| 52 | if err := Write(root, artifacts); err != nil { |
| 53 | t.Fatal(err) |
| 54 | } |
| 55 | if err := Check(root, artifacts); err != nil { |
| 56 | t.Fatalf("freshly generated artifacts failed check: %v", err) |
| 57 | } |
| 58 | drifted := filepath.Join(root, filepath.FromSlash(artifacts[1].Path)) |
| 59 | if err := os.WriteFile(drifted, append(append([]byte(nil), artifacts[1].Data...), '\n'), 0o644); err != nil { |
| 60 | t.Fatal(err) |
| 61 | } |
| 62 | if err := Check(root, artifacts); err == nil { |
| 63 | t.Fatal("Check accepted a drifted generated artifact") |
| 64 | } |
| 65 | } |
| 66 |