|
| 1 | +package policy |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "testing" |
| 6 | + |
| 7 | + "github.com/docker/attest/attestation" |
| 8 | + v1 "github.com/google/go-containerregistry/pkg/v1" |
| 9 | + "github.com/open-policy-agent/opa/tester" |
| 10 | + "github.com/stretchr/testify/assert" |
| 11 | + "github.com/stretchr/testify/require" |
| 12 | +) |
| 13 | + |
| 14 | +func TestPolicy(t *testing.T) { |
| 15 | + paths := []string{"testdata/policies/test"} |
| 16 | + modules, store, err := tester.Load(paths, nil) |
| 17 | + require.NoError(t, err) |
| 18 | + resolver := &NullAttestationResolver{} |
| 19 | + |
| 20 | + opts := NewRegoFunctionOptions(resolver, nil) |
| 21 | + ctx := context.Background() |
| 22 | + ch, err := tester.NewRunner(). |
| 23 | + SetStore(store). |
| 24 | + AddCustomBuiltins(RegoFunctions(opts)). |
| 25 | + CapturePrintOutput(true). |
| 26 | + RaiseBuiltinErrors(true). |
| 27 | + EnableTracing(true). |
| 28 | + SetModules(modules). |
| 29 | + RunTests(ctx, nil) |
| 30 | + require.NoError(t, err) |
| 31 | + require.NoError(t, err) |
| 32 | + results := buffer(ch) |
| 33 | + assert.Equalf(t, 1, len(results), "expected 1 results, got %d", len(results)) |
| 34 | + assert.Truef(t, results[0].Pass(), "expected result 1 to pass, got %v", results[0]) |
| 35 | + assert.True(t, resolver.called) |
| 36 | +} |
| 37 | + |
| 38 | +func buffer[T any](ch chan T) []T { |
| 39 | + var out []T |
| 40 | + for v := range ch { |
| 41 | + out = append(out, v) |
| 42 | + } |
| 43 | + return out |
| 44 | +} |
| 45 | + |
| 46 | +type NullAttestationResolver struct { |
| 47 | + called bool |
| 48 | +} |
| 49 | + |
| 50 | +func (r *NullAttestationResolver) ImageName(_ context.Context) (string, error) { |
| 51 | + return "", nil |
| 52 | +} |
| 53 | + |
| 54 | +func (r *NullAttestationResolver) ImagePlatform(_ context.Context) (*v1.Platform, error) { |
| 55 | + return v1.ParsePlatform("") |
| 56 | +} |
| 57 | + |
| 58 | +func (r *NullAttestationResolver) ImageDescriptor(_ context.Context) (*v1.Descriptor, error) { |
| 59 | + return nil, nil |
| 60 | +} |
| 61 | + |
| 62 | +func (r *NullAttestationResolver) Attestations(_ context.Context, _ string) ([]*attestation.Envelope, error) { |
| 63 | + r.called = true |
| 64 | + return nil, nil |
| 65 | +} |
0 commit comments