feat (events): new test helpers: CloudEventFromFile, CloudEventFromBuf

pull/3251/head
Jim 3 years ago committed by Timothy Messier
parent c4b31313a6
commit 7161569955
No known key found for this signature in database
GPG Key ID: EFD2F184F7600572

@ -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.

@ -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)
}

Loading…
Cancel
Save