X-Git-Url: https://gerrit.o-ran-sc.org/r/gitweb?a=blobdiff_plain;f=dmaap-mediator-producer%2Finternal%2Fjobs%2Fjobs_test.go;h=6ca39b275b6a058a1b69e9b50bbc48d0ee665c85;hb=f1cee0f81c6bc482f73182c8f4c903e8376381e8;hp=b53d85e66612e0174f7dc8b471abb6ff9d541867;hpb=280385634f160bb78a8944998e9106a2f6549eb0;p=nonrtric.git diff --git a/dmaap-mediator-producer/internal/jobs/jobs_test.go b/dmaap-mediator-producer/internal/jobs/jobs_test.go index b53d85e6..6ca39b27 100644 --- a/dmaap-mediator-producer/internal/jobs/jobs_test.go +++ b/dmaap-mediator-producer/internal/jobs/jobs_test.go @@ -26,16 +26,15 @@ import ( "net/http" "os" "path/filepath" + "sync" "testing" "time" - "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" - "oransc.org/nonrtric/dmaapmediatorproducer/internal/restclient" - "oransc.org/nonrtric/dmaapmediatorproducer/mocks" + "oransc.org/nonrtric/dmaapmediatorproducer/internal/config" ) -const typeDefinition = `{"id": "type1", "dmaapTopic": "unauthenticated.SEC_FAULT_OUTPUT", "schema": {"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) @@ -43,32 +42,31 @@ func TestGetTypes_filesOkShouldReturnSliceOfTypesAndProvideSupportedTypes(t *tes if err != nil { t.Errorf("Unable to create temporary directory for types due to: %v", err) } + fname := filepath.Join(typesDir, "type_config.json") + handlerUnderTest := NewJobHandlerImpl(fname, nil, nil) t.Cleanup(func() { os.RemoveAll(typesDir) - clearAll() + handlerUnderTest.clearAll() }) - typeDir = typesDir - fname := filepath.Join(typesDir, "type1.json") if err = os.WriteFile(fname, []byte(typeDefinition), 0666); err != nil { - t.Errorf("Unable to create temporary files for types due to: %v", err) + t.Errorf("Unable to create temporary config file for types due to: %v", err) } - types, err := GetTypes() - wantedType := Type{ - TypeId: "type1", - DMaaPTopic: "unauthenticated.SEC_FAULT_OUTPUT", - Schema: `{"title":"Type 1"}`, - Jobs: make(map[string]JobInfo), + types, err := handlerUnderTest.GetTypes() + wantedType := config.TypeDefinition{ + Id: "type1", + DmaapTopicURL: "events/unauthenticated.SEC_FAULT_OUTPUT/dmaapmediatorproducer/type1", } - wantedTypes := []*Type{&wantedType} + wantedTypes := []config.TypeDefinition{wantedType} assertions.EqualValues(wantedTypes, types) assertions.Nil(err) - supportedTypes := GetSupportedTypes() + supportedTypes := handlerUnderTest.GetSupportedTypes() assertions.EqualValues([]string{"type1"}, supportedTypes) } func TestAddJobWhenTypeIsSupported_shouldAddJobToAllJobsMap(t *testing.T) { assertions := require.New(t) + handlerUnderTest := NewJobHandlerImpl("", nil, nil) wantedJob := JobInfo{ Owner: "owner", LastUpdated: "now", @@ -77,110 +75,183 @@ func TestAddJobWhenTypeIsSupported_shouldAddJobToAllJobsMap(t *testing.T) { InfoJobData: "{}", InfoTypeIdentity: "type1", } - allJobs["type1"] = Type{ + handlerUnderTest.allTypes["type1"] = TypeData{ TypeId: "type1", Jobs: map[string]JobInfo{"job1": wantedJob}, } t.Cleanup(func() { - clearAll() + handlerUnderTest.clearAll() }) - err := AddJob(wantedJob) + err := handlerUnderTest.AddJob(wantedJob) assertions.Nil(err) - assertions.Equal(1, len(allJobs["type1"].Jobs)) - assertions.Equal(wantedJob, allJobs["type1"].Jobs["job1"]) + assertions.Equal(1, len(handlerUnderTest.allTypes["type1"].Jobs)) + assertions.Equal(wantedJob, handlerUnderTest.allTypes["type1"].Jobs["job1"]) } func TestAddJobWhenTypeIsNotSupported_shouldReturnError(t *testing.T) { assertions := require.New(t) + handlerUnderTest := NewJobHandlerImpl("", nil, nil) jobInfo := JobInfo{ InfoTypeIdentity: "type1", } - err := AddJob(jobInfo) + err := handlerUnderTest.AddJob(jobInfo) assertions.NotNil(err) assertions.Equal("type not supported: type1", err.Error()) } func TestAddJobWhenJobIdMissing_shouldReturnError(t *testing.T) { assertions := require.New(t) - allJobs["type1"] = Type{ + handlerUnderTest := NewJobHandlerImpl("", nil, nil) + handlerUnderTest.allTypes["type1"] = TypeData{ TypeId: "type1", } t.Cleanup(func() { - clearAll() + handlerUnderTest.clearAll() }) + jobInfo := JobInfo{ InfoTypeIdentity: "type1", } - - err := AddJob(jobInfo) + err := handlerUnderTest.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"] = Type{ + handlerUnderTest := NewJobHandlerImpl("", nil, nil) + handlerUnderTest.allTypes["type1"] = TypeData{ TypeId: "type1", } + t.Cleanup(func() { + handlerUnderTest.clearAll() + }) + jobInfo := JobInfo{ InfoTypeIdentity: "type1", InfoJobIdentity: "job1", } - - err := AddJob(jobInfo) + err := handlerUnderTest.AddJob(jobInfo) assertions.NotNil(err) - assertions.Equal("missing required target URI: { job1 type1}", err.Error()) - clearAll() + assertions.Equal("missing required target URI: { job1 type1}", err.Error()) +} + +func TestDeleteJob(t *testing.T) { + assertions := require.New(t) + handlerUnderTest := NewJobHandlerImpl("", nil, nil) + jobToKeep := JobInfo{ + InfoJobIdentity: "job1", + InfoTypeIdentity: "type1", + } + jobToDelete := JobInfo{ + InfoJobIdentity: "job2", + InfoTypeIdentity: "type1", + } + handlerUnderTest.allTypes["type1"] = TypeData{ + TypeId: "type1", + Jobs: map[string]JobInfo{"job1": jobToKeep, "job2": jobToDelete}, + } + t.Cleanup(func() { + handlerUnderTest.clearAll() + }) + + handlerUnderTest.DeleteJob("job2") + assertions.Equal(1, len(handlerUnderTest.allTypes["type1"].Jobs)) + assertions.Equal(jobToKeep, handlerUnderTest.allTypes["type1"].Jobs["job1"]) } func TestPollAndDistributeMessages(t *testing.T) { assertions := require.New(t) + + wg := sync.WaitGroup{} + messages := `[{"message": {"data": "data"}}]` + pollClientMock := NewTestClient(func(req *http.Request) *http.Response { + if req.URL.String() == "http://mrAddr/topicUrl" { + assertions.Equal(req.Method, "GET") + wg.Done() // Signal that the poll call has been made + 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 + } + } + t.Error("Wrong call to client: ", req) + t.Fail() + return nil + }) + distributeClientMock := NewTestClient(func(req *http.Request) *http.Response { + 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() // Signal that the distribution call has been made + 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 + }) + handlerUnderTest := NewJobHandlerImpl("", pollClientMock, distributeClientMock) jobInfo := JobInfo{ InfoTypeIdentity: "type1", InfoJobIdentity: "job1", TargetUri: "http://consumerHost/target", } - allJobs["type1"] = Type{ - TypeId: "type1", - DMaaPTopic: "topic", - Jobs: map[string]JobInfo{"job1": jobInfo}, + handlerUnderTest.allTypes["type1"] = TypeData{ + TypeId: "type1", + DMaaPTopicURL: "topicUrl", + Jobs: map[string]JobInfo{"job1": jobInfo}, } t.Cleanup(func() { - clearAll() + handlerUnderTest.clearAll() }) - body := ioutil.NopCloser(bytes.NewReader([]byte(`[{"message": {"data": "data"}}]`))) - clientMock := mocks.HTTPClient{} - clientMock.On("Get", mock.Anything).Return(&http.Response{ - StatusCode: http.StatusOK, - Body: body, - }, nil) - - clientMock.On("Do", mock.Anything).Return(&http.Response{ - StatusCode: http.StatusOK, - }, nil) - - restclient.Client = &clientMock - - pollAndDistributeMessages("http://mrAddr") - - time.Sleep(100 * time.Millisecond) - - var actualRequest *http.Request - clientMock.AssertCalled(t, "Get", "http://mrAddr/events/topic/users/dmaapmediatorproducer") - clientMock.AssertNumberOfCalls(t, "Get", 1) - - clientMock.AssertCalled(t, "Do", mock.MatchedBy(func(req *http.Request) bool { - actualRequest = req - return true - })) - assertions.Equal(http.MethodPost, actualRequest.Method) - assertions.Equal("consumerHost", actualRequest.URL.Host) - assertions.Equal("/target", actualRequest.URL.Path) - assertions.Equal("application/json; charset=utf-8", actualRequest.Header.Get("Content-Type")) - actualBody, _ := ioutil.ReadAll(actualRequest.Body) - assertions.Equal([]byte(`[{"message": {"data": "data"}}]`), actualBody) - clientMock.AssertNumberOfCalls(t, "Do", 1) + wg.Add(2) // Two calls should be made to the server, one to poll and one to distribute + handlerUnderTest.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() }