diff --git a/internal/observability/event/testing.go b/internal/observability/event/testing.go index 2ca6db0f38..3467d78261 100644 --- a/internal/observability/event/testing.go +++ b/internal/observability/event/testing.go @@ -5,6 +5,7 @@ package event import ( "context" + "encoding/json" "io/ioutil" "os" "sync" @@ -14,11 +15,34 @@ import ( pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services" "github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/groups" "github.com/hashicorp/eventlogger" + "github.com/hashicorp/eventlogger/formatter_filters/cloudevents" "github.com/hashicorp/go-hclog" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/protobuf/types/known/wrapperspb" ) +// CloudEventFromFile will marshal a single cloud event from the provided file +// name +func CloudEventFromFile(t testing.TB, fileName string) *cloudevents.Event { + t.Helper() + b, err := os.ReadFile(fileName) + assert.NoError(t, err) + got := &cloudevents.Event{} + err = json.Unmarshal(b, got) + require.NoErrorf(t, err, "json: %s", string(b)) + return got +} + +// CloudEventFromBuf will marshal a single cloud event from the provided buffer +func CloudEventFromBuf(t testing.TB, b []byte) *cloudevents.Event { + t.Helper() + got := &cloudevents.Event{} + err := json.Unmarshal(b, got) + require.NoErrorf(t, err, "json: %s", string(b)) + return got +} + // TestWithoutEventing allows the caller to "disable" all eventing for a test. // You must not run the test in parallel (no calls to t.Parallel) since the // function relies on modifying the system wide default eventer. diff --git a/internal/observability/event/testing_test.go b/internal/observability/event/testing_test.go index 7a3da6d73d..c4d7b7a475 100644 --- a/internal/observability/event/testing_test.go +++ b/internal/observability/event/testing_test.go @@ -6,13 +6,16 @@ package event_test import ( "bytes" "context" + "encoding/json" "fmt" "io" "os" "testing" "github.com/hashicorp/boundary/internal/observability/event" + "github.com/hashicorp/eventlogger/formatter_filters/cloudevents" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_TestWithoutEventing(t *testing.T) { @@ -56,3 +59,28 @@ func Test_TestWithoutEventing(t *testing.T) { event.WriteSysEvent(testCtx, op, "test-event") })) } + +func Test_CloudEventsFromFile_CloudEventFromBuf(t *testing.T) { + assert, require := assert.New(t), require.New(t) + tmpFile, err := os.CreateTemp("./", "tmp-event") + require.NoError(err) + t.Cleanup(func() { + _ = os.Remove(tmpFile.Name()) + }) + + e := &cloudevents.Event{ + ID: "id", + Source: "test", + Data: map[string]any{ + "test": "data", + }, + } + j, err := json.Marshal(e) + require.NoError(err) + require.NoError(os.WriteFile(tmpFile.Name(), j, 0o666)) + got := event.CloudEventFromFile(t, tmpFile.Name()) + assert.Equal(e, got) + + got = event.CloudEventFromBuf(t, j) + assert.Equal(e, got) +}