X-Git-Url: https://gerrit.o-ran-sc.org/r/gitweb?a=blobdiff_plain;f=dmaap-mediator-producer%2Finternal%2Fjobs%2Fjobs_test.go;h=066823d5ab3c2a523b37046fb1769854a97f7665;hb=c873fa9306739a14d05454d2ec27bc2fde497058;hp=3bb25787890ab46c14a69072784195898f13d451;hpb=b65d86fc9b02415e1adf2415f8c4a257378e9c09;p=nonrtric.git diff --git a/dmaap-mediator-producer/internal/jobs/jobs_test.go b/dmaap-mediator-producer/internal/jobs/jobs_test.go index 3bb25787..066823d5 100644 --- a/dmaap-mediator-producer/internal/jobs/jobs_test.go +++ b/dmaap-mediator-producer/internal/jobs/jobs_test.go @@ -31,42 +31,41 @@ import ( "time" "github.com/stretchr/testify/require" - "oransc.org/nonrtric/dmaapmediatorproducer/internal/restclient" + "oransc.org/nonrtric/dmaapmediatorproducer/internal/config" ) const typeDefinition = `{"types": [{"id": "type1", "dmaapTopicUrl": "events/unauthenticated.SEC_FAULT_OUTPUT/dmaapmediatorproducer/type1"}]}` -func TestGetTypes_filesOkShouldReturnSliceOfTypesAndProvideSupportedTypes(t *testing.T) { +func TestJobsManagerGetTypes_filesOkShouldReturnSliceOfTypesAndProvideSupportedTypes(t *testing.T) { assertions := require.New(t) typesDir, err := os.MkdirTemp("", "configs") if err != nil { t.Errorf("Unable to create temporary directory for types due to: %v", err) } + fname := filepath.Join(typesDir, "type_config.json") + managerUnderTest := NewJobsManagerImpl(fname, nil, "", nil) t.Cleanup(func() { os.RemoveAll(typesDir) - clearAll() }) - 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 := TypeData{ - TypeId: "type1", - DMaaPTopicURL: "events/unauthenticated.SEC_FAULT_OUTPUT/dmaapmediatorproducer/type1", - Jobs: make(map[string]JobInfo), + types, err := managerUnderTest.LoadTypesFromConfiguration() + wantedType := config.TypeDefinition{ + Id: "type1", + DmaapTopicURL: "events/unauthenticated.SEC_FAULT_OUTPUT/dmaapmediatorproducer/type1", } - wantedTypes := []TypeData{wantedType} + wantedTypes := []config.TypeDefinition{wantedType} assertions.EqualValues(wantedTypes, types) assertions.Nil(err) - supportedTypes := GetSupportedTypes() + supportedTypes := managerUnderTest.GetSupportedTypes() assertions.EqualValues([]string{"type1"}, supportedTypes) } -func TestAddJobWhenTypeIsSupported_shouldAddJobToAllJobsMap(t *testing.T) { +func TestJobsManagerAddJobWhenTypeIsSupported_shouldAddJobToChannel(t *testing.T) { assertions := require.New(t) + managerUnderTest := NewJobsManagerImpl("", nil, "", nil) wantedJob := JobInfo{ Owner: "owner", LastUpdated: "now", @@ -75,95 +74,111 @@ func TestAddJobWhenTypeIsSupported_shouldAddJobToAllJobsMap(t *testing.T) { InfoJobData: "{}", InfoTypeIdentity: "type1", } - allTypes["type1"] = TypeData{ - TypeId: "type1", - Jobs: map[string]JobInfo{"job1": wantedJob}, + jobsHandler := jobsHandler{ + addJobCh: make(chan JobInfo)} + managerUnderTest.allTypes["type1"] = TypeData{ + TypeId: "type1", + jobsHandler: &jobsHandler, } - t.Cleanup(func() { - clearAll() - }) - err := AddJob(wantedJob) + var err error + go func() { + err = managerUnderTest.AddJob(wantedJob) + }() + assertions.Nil(err) - assertions.Equal(1, len(allTypes["type1"].Jobs)) - assertions.Equal(wantedJob, allTypes["type1"].Jobs["job1"]) + addedJob := <-jobsHandler.addJobCh + assertions.Equal(wantedJob, addedJob) } -func TestAddJobWhenTypeIsNotSupported_shouldReturnError(t *testing.T) { +func TestJobsManagerAddJobWhenTypeIsNotSupported_shouldReturnError(t *testing.T) { assertions := require.New(t) + managerUnderTest := NewJobsManagerImpl("", nil, "", nil) jobInfo := JobInfo{ InfoTypeIdentity: "type1", } - err := AddJob(jobInfo) + err := managerUnderTest.AddJob(jobInfo) assertions.NotNil(err) assertions.Equal("type not supported: type1", err.Error()) } -func TestAddJobWhenJobIdMissing_shouldReturnError(t *testing.T) { +func TestJobsManagerAddJobWhenJobIdMissing_shouldReturnError(t *testing.T) { assertions := require.New(t) - allTypes["type1"] = TypeData{ + managerUnderTest := NewJobsManagerImpl("", nil, "", nil) + managerUnderTest.allTypes["type1"] = TypeData{ TypeId: "type1", } - t.Cleanup(func() { - clearAll() - }) + jobInfo := JobInfo{ InfoTypeIdentity: "type1", } - - err := AddJob(jobInfo) + err := managerUnderTest.AddJob(jobInfo) assertions.NotNil(err) assertions.Equal("missing required job identity: { type1}", err.Error()) } -func TestAddJobWhenTargetUriMissing_shouldReturnError(t *testing.T) { +func TestJobsManagerAddJobWhenTargetUriMissing_shouldReturnError(t *testing.T) { assertions := require.New(t) - allTypes["type1"] = TypeData{ + managerUnderTest := NewJobsManagerImpl("", nil, "", nil) + managerUnderTest.allTypes["type1"] = TypeData{ TypeId: "type1", } + jobInfo := JobInfo{ InfoTypeIdentity: "type1", InfoJobIdentity: "job1", } - - err := AddJob(jobInfo) + err := managerUnderTest.AddJob(jobInfo) assertions.NotNil(err) assertions.Equal("missing required target URI: { job1 type1}", err.Error()) - clearAll() } -func TestPollAndDistributeMessages(t *testing.T) { + +func TestJobsManagerDeleteJob_shouldSendDeleteToChannel(t *testing.T) { assertions := require.New(t) - jobInfo := JobInfo{ - InfoTypeIdentity: "type1", - InfoJobIdentity: "job1", - TargetUri: "http://consumerHost/target", + managerUnderTest := NewJobsManagerImpl("", nil, "", nil) + jobsHandler := jobsHandler{ + deleteJobCh: make(chan string)} + managerUnderTest.allTypes["type1"] = TypeData{ + TypeId: "type1", + jobsHandler: &jobsHandler, } - 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 + go managerUnderTest.DeleteJob("job2") + + assertions.Equal("job2", <-jobsHandler.deleteJobCh) +} + +func TestAddJobToJobsManager_shouldStartPollAndDistributeMessages(t *testing.T) { + assertions := require.New(t) + + called := false messages := `[{"message": {"data": "data"}}]` - clientMock := NewTestClient(func(req *http.Request) *http.Response { + pollClientMock := NewTestClient(func(req *http.Request) *http.Response { if req.URL.String() == "http://mrAddr/topicUrl" { assertions.Equal(req.Method, "GET") - wg.Done() + body := "[]" + if !called { + called = true + body = messages + } return &http.Response{ StatusCode: 200, - Body: ioutil.NopCloser(bytes.NewReader([]byte(messages))), + Body: ioutil.NopCloser(bytes.NewReader([]byte(body))), Header: make(http.Header), // Must be set to non-nil value or it panics } - } else if req.URL.String() == "http://consumerHost/target" { + } + t.Error("Wrong call to client: ", req) + t.Fail() + return nil + }) + + wg := sync.WaitGroup{} + 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")) + assertions.Equal("application/json", req.Header.Get("Content-Type")) wg.Done() return &http.Response{ StatusCode: 200, @@ -175,17 +190,74 @@ func TestPollAndDistributeMessages(t *testing.T) { t.Fail() return nil }) + jobsHandler := newJobsHandler("type1", "/topicUrl", pollClientMock, distributeClientMock) + + jobsManager := NewJobsManagerImpl("", pollClientMock, "http://mrAddr", distributeClientMock) + jobsManager.allTypes["type1"] = TypeData{ + DMaaPTopicURL: "/topicUrl", + TypeId: "type1", + jobsHandler: jobsHandler, + } - restclient.Client = clientMock + jobsManager.StartJobs() + + jobInfo := JobInfo{ + InfoTypeIdentity: "type1", + InfoJobIdentity: "job1", + TargetUri: "http://consumerHost/target", + } - pollAndDistributeMessages("http://mrAddr") + wg.Add(1) // Wait till the distribution has happened + jobsManager.AddJob(jobInfo) - if waitTimeout(&wg, 100*time.Millisecond) { + if waitTimeout(&wg, 2*time.Second) { t.Error("Not all calls to server were made") t.Fail() } } +func TestJobsHandlerDeleteJob_shouldDeleteJobFromJobsMap(t *testing.T) { + jobToDelete := newJob(JobInfo{}, nil) + go jobToDelete.start() + jobsHandler := newJobsHandler("type1", "/topicUrl", nil, nil) + jobsHandler.jobs["job1"] = jobToDelete + + go jobsHandler.monitorManagementChannels() + + jobsHandler.deleteJobCh <- "job1" + + deleted := false + for i := 0; i < 100; i++ { + if len(jobsHandler.jobs) == 0 { + deleted = true + break + } + time.Sleep(time.Microsecond) // Need to drop control to let the job's goroutine do the job + } + require.New(t).True(deleted, "Job not deleted") +} + +func TestJobsHandlerEmptyJobMessageBufferWhenItIsFull(t *testing.T) { + job := newJob(JobInfo{ + InfoJobIdentity: "job", + }, nil) + + jobsHandler := newJobsHandler("type1", "/topicUrl", nil, nil) + jobsHandler.jobs["job1"] = job + + fillMessagesBuffer(job.messagesChannel) + + jobsHandler.distributeMessages([]byte("sent msg")) + + require.New(t).Len(job.messagesChannel, 0) +} + +func fillMessagesBuffer(mc chan []byte) { + for i := 0; i < cap(mc); i++ { + mc <- []byte("msg") + } +} + type RoundTripFunc func(req *http.Request) *http.Response func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {