X-Git-Url: https://gerrit.o-ran-sc.org/r/gitweb?a=blobdiff_plain;f=dmaap-mediator-producer%2Finternal%2Fjobs%2Fjobs_test.go;h=3bb25787890ab46c14a69072784195898f13d451;hb=47d0ee37691eddc290a1f9e34091dfd2020db07f;hp=0941033897d2b0893cfa79771d24363863d59e4c;hpb=f0e49a07dad877f94f635dda4ab477b9636536c8;p=nonrtric.git diff --git a/dmaap-mediator-producer/internal/jobs/jobs_test.go b/dmaap-mediator-producer/internal/jobs/jobs_test.go index 09410338..3bb25787 100644 --- a/dmaap-mediator-producer/internal/jobs/jobs_test.go +++ b/dmaap-mediator-producer/internal/jobs/jobs_test.go @@ -21,14 +21,20 @@ package jobs import ( + "bytes" + "io/ioutil" + "net/http" "os" "path/filepath" + "sync" "testing" + "time" "github.com/stretchr/testify/require" + "oransc.org/nonrtric/dmaapmediatorproducer/internal/restclient" ) -const type1Schema = `{"title": "Type 1"}` +const typeDefinition = `{"types": [{"id": "type1", "dmaapTopicUrl": "events/unauthenticated.SEC_FAULT_OUTPUT/dmaapmediatorproducer/type1"}]}` func TestGetTypes_filesOkShouldReturnSliceOfTypesAndProvideSupportedTypes(t *testing.T) { assertions := require.New(t) @@ -40,17 +46,18 @@ func TestGetTypes_filesOkShouldReturnSliceOfTypesAndProvideSupportedTypes(t *tes os.RemoveAll(typesDir) clearAll() }) - typeDir = typesDir - fname := filepath.Join(typesDir, "type1.json") - if err = os.WriteFile(fname, []byte(type1Schema), 0666); err != nil { - t.Errorf("Unable to create temporary files for types due to: %v", err) + fname := filepath.Join(typesDir, "type_config.json") + configFile = fname + if err = os.WriteFile(fname, []byte(typeDefinition), 0666); err != nil { + t.Errorf("Unable to create temporary config file for types due to: %v", err) } types, err := GetTypes() - wantedType := Type{ - TypeId: "type1", - Schema: type1Schema, + wantedType := TypeData{ + TypeId: "type1", + DMaaPTopicURL: "events/unauthenticated.SEC_FAULT_OUTPUT/dmaapmediatorproducer/type1", + Jobs: make(map[string]JobInfo), } - wantedTypes := []*Type{&wantedType} + wantedTypes := []TypeData{wantedType} assertions.EqualValues(wantedTypes, types) assertions.Nil(err) @@ -60,11 +67,7 @@ func TestGetTypes_filesOkShouldReturnSliceOfTypesAndProvideSupportedTypes(t *tes func TestAddJobWhenTypeIsSupported_shouldAddJobToAllJobsMap(t *testing.T) { assertions := require.New(t) - allJobs["type1"] = make(map[string]JobInfo) - t.Cleanup(func() { - clearAll() - }) - jobInfo := JobInfo{ + wantedJob := JobInfo{ Owner: "owner", LastUpdated: "now", InfoJobIdentity: "job1", @@ -72,11 +75,18 @@ func TestAddJobWhenTypeIsSupported_shouldAddJobToAllJobsMap(t *testing.T) { InfoJobData: "{}", InfoTypeIdentity: "type1", } + allTypes["type1"] = TypeData{ + TypeId: "type1", + Jobs: map[string]JobInfo{"job1": wantedJob}, + } + t.Cleanup(func() { + clearAll() + }) - err := AddJob(jobInfo) + err := AddJob(wantedJob) assertions.Nil(err) - assertions.Equal(1, len(allJobs["type1"])) - assertions.Equal(jobInfo, allJobs["type1"]["job1"]) + assertions.Equal(1, len(allTypes["type1"].Jobs)) + assertions.Equal(wantedJob, allTypes["type1"].Jobs["job1"]) } func TestAddJobWhenTypeIsNotSupported_shouldReturnError(t *testing.T) { @@ -92,7 +102,9 @@ func TestAddJobWhenTypeIsNotSupported_shouldReturnError(t *testing.T) { func TestAddJobWhenJobIdMissing_shouldReturnError(t *testing.T) { assertions := require.New(t) - allJobs["type1"] = make(map[string]JobInfo) + allTypes["type1"] = TypeData{ + TypeId: "type1", + } t.Cleanup(func() { clearAll() }) @@ -102,12 +114,14 @@ func TestAddJobWhenJobIdMissing_shouldReturnError(t *testing.T) { err := AddJob(jobInfo) assertions.NotNil(err) - assertions.Equal("missing required job identity: { type1}", err.Error()) + assertions.Equal("missing required job identity: { type1}", err.Error()) } func TestAddJobWhenTargetUriMissing_shouldReturnError(t *testing.T) { assertions := require.New(t) - allJobs["type1"] = make(map[string]JobInfo) + allTypes["type1"] = TypeData{ + TypeId: "type1", + } jobInfo := JobInfo{ InfoTypeIdentity: "type1", InfoJobIdentity: "job1", @@ -115,6 +129,94 @@ func TestAddJobWhenTargetUriMissing_shouldReturnError(t *testing.T) { err := AddJob(jobInfo) assertions.NotNil(err) - assertions.Equal("missing required target URI: { job1 type1}", err.Error()) + assertions.Equal("missing required target URI: { job1 type1}", err.Error()) clearAll() } +func TestPollAndDistributeMessages(t *testing.T) { + assertions := require.New(t) + jobInfo := JobInfo{ + InfoTypeIdentity: "type1", + InfoJobIdentity: "job1", + TargetUri: "http://consumerHost/target", + } + allTypes["type1"] = TypeData{ + TypeId: "type1", + DMaaPTopicURL: "topicUrl", + Jobs: map[string]JobInfo{"job1": jobInfo}, + } + t.Cleanup(func() { + clearAll() + }) + + wg := sync.WaitGroup{} + wg.Add(2) // Two calls should be made to the server, one to poll and one to distribute + messages := `[{"message": {"data": "data"}}]` + clientMock := NewTestClient(func(req *http.Request) *http.Response { + if req.URL.String() == "http://mrAddr/topicUrl" { + assertions.Equal(req.Method, "GET") + wg.Done() + return &http.Response{ + StatusCode: 200, + Body: ioutil.NopCloser(bytes.NewReader([]byte(messages))), + Header: make(http.Header), // Must be set to non-nil value or it panics + } + } else if req.URL.String() == "http://consumerHost/target" { + assertions.Equal(req.Method, "POST") + assertions.Equal(messages, getBodyAsString(req)) + assertions.Equal("application/json; charset=utf-8", req.Header.Get("Content-Type")) + wg.Done() + return &http.Response{ + StatusCode: 200, + Body: ioutil.NopCloser(bytes.NewBufferString(`OK`)), + Header: make(http.Header), // Must be set to non-nil value or it panics + } + } + t.Error("Wrong call to client: ", req) + t.Fail() + return nil + }) + + restclient.Client = clientMock + + pollAndDistributeMessages("http://mrAddr") + + if waitTimeout(&wg, 100*time.Millisecond) { + t.Error("Not all calls to server were made") + t.Fail() + } +} + +type RoundTripFunc func(req *http.Request) *http.Response + +func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req), nil +} + +//NewTestClient returns *http.Client with Transport replaced to avoid making real calls +func NewTestClient(fn RoundTripFunc) *http.Client { + return &http.Client{ + Transport: RoundTripFunc(fn), + } +} + +// waitTimeout waits for the waitgroup for the specified max timeout. +// Returns true if waiting timed out. +func waitTimeout(wg *sync.WaitGroup, timeout time.Duration) bool { + c := make(chan struct{}) + go func() { + defer close(c) + wg.Wait() + }() + select { + case <-c: + return false // completed normally + case <-time.After(timeout): + return true // timed out + } +} + +func getBodyAsString(req *http.Request) string { + buf := new(bytes.Buffer) + buf.ReadFrom(req.Body) + return buf.String() +}