|
1 | 1 | // |
2 | | -// Copyright 2023 The Chainloop Authors. |
| 2 | +// Copyright 2023-2026 The Chainloop Authors. |
3 | 3 | // |
4 | 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
5 | 5 | // you may not use this file except in compliance with the License. |
|
16 | 16 | package cmd |
17 | 17 |
|
18 | 18 | import ( |
| 19 | + "os" |
| 20 | + "path/filepath" |
19 | 21 | "testing" |
20 | 22 |
|
| 23 | + "github.com/chainloop-dev/chainloop/pkg/attestation/crafter" |
| 24 | + v1 "github.com/chainloop-dev/chainloop/pkg/attestation/crafter/api/attestation/v1" |
21 | 25 | "github.com/stretchr/testify/assert" |
| 26 | + "github.com/stretchr/testify/require" |
| 27 | + "google.golang.org/protobuf/encoding/protojson" |
22 | 28 | ) |
23 | 29 |
|
| 30 | +func TestOrgFromLocalState(t *testing.T) { |
| 31 | + t.Run("returns org from valid state file", func(t *testing.T) { |
| 32 | + state := &crafter.VersionedCraftingState{ |
| 33 | + CraftingState: &v1.CraftingState{ |
| 34 | + Attestation: &v1.Attestation{ |
| 35 | + Workflow: &v1.WorkflowMetadata{ |
| 36 | + Organization: "my-org", |
| 37 | + }, |
| 38 | + }, |
| 39 | + }, |
| 40 | + } |
| 41 | + |
| 42 | + raw, err := protojson.Marshal(state) |
| 43 | + require.NoError(t, err) |
| 44 | + |
| 45 | + statePath := filepath.Join(t.TempDir(), "state.json") |
| 46 | + require.NoError(t, os.WriteFile(statePath, raw, 0o600)) |
| 47 | + |
| 48 | + assert.Equal(t, "my-org", orgFromLocalState(statePath)) |
| 49 | + }) |
| 50 | + |
| 51 | + t.Run("returns empty for missing file", func(t *testing.T) { |
| 52 | + assert.Empty(t, orgFromLocalState(filepath.Join(t.TempDir(), "nonexistent.json"))) |
| 53 | + }) |
| 54 | + |
| 55 | + t.Run("returns empty for invalid json", func(t *testing.T) { |
| 56 | + statePath := filepath.Join(t.TempDir(), "bad.json") |
| 57 | + require.NoError(t, os.WriteFile(statePath, []byte("not json"), 0o600)) |
| 58 | + assert.Empty(t, orgFromLocalState(statePath)) |
| 59 | + }) |
| 60 | + |
| 61 | + t.Run("returns empty when org not set in state", func(t *testing.T) { |
| 62 | + state := &crafter.VersionedCraftingState{ |
| 63 | + CraftingState: &v1.CraftingState{ |
| 64 | + Attestation: &v1.Attestation{ |
| 65 | + Workflow: &v1.WorkflowMetadata{}, |
| 66 | + }, |
| 67 | + }, |
| 68 | + } |
| 69 | + |
| 70 | + raw, err := protojson.Marshal(state) |
| 71 | + require.NoError(t, err) |
| 72 | + |
| 73 | + statePath := filepath.Join(t.TempDir(), "state.json") |
| 74 | + require.NoError(t, os.WriteFile(statePath, raw, 0o600)) |
| 75 | + |
| 76 | + assert.Empty(t, orgFromLocalState(statePath)) |
| 77 | + }) |
| 78 | +} |
| 79 | + |
24 | 80 | func TestExtractAnnotations(t *testing.T) { |
25 | 81 | testCases := []struct { |
26 | 82 | input []string |
|
0 commit comments