Poll MR and send messages to consumers
[nonrtric.git] / dmaap-mediator-producer / internal / jobs / jobs_test.go
1 // -
2 //   ========================LICENSE_START=================================
3 //   O-RAN-SC
4 //   %%
5 //   Copyright (C) 2021: Nordix Foundation
6 //   %%
7 //   Licensed under the Apache License, Version 2.0 (the "License");
8 //   you may not use this file except in compliance with the License.
9 //   You may obtain a copy of the License at
10 //
11 //        http://www.apache.org/licenses/LICENSE-2.0
12 //
13 //   Unless required by applicable law or agreed to in writing, software
14 //   distributed under the License is distributed on an "AS IS" BASIS,
15 //   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 //   See the License for the specific language governing permissions and
17 //   limitations under the License.
18 //   ========================LICENSE_END===================================
19 //
20
21 package jobs
22
23 import (
24         "bytes"
25         "io/ioutil"
26         "net/http"
27         "os"
28         "path/filepath"
29         "testing"
30         "time"
31
32         "github.com/stretchr/testify/mock"
33         "github.com/stretchr/testify/require"
34         "oransc.org/nonrtric/dmaapmediatorproducer/internal/restclient"
35         "oransc.org/nonrtric/dmaapmediatorproducer/mocks"
36 )
37
38 const typeDefinition = `{"id": "type1", "dmaapTopic": "unauthenticated.SEC_FAULT_OUTPUT", "schema": {"title": "Type 1"}}`
39
40 func TestGetTypes_filesOkShouldReturnSliceOfTypesAndProvideSupportedTypes(t *testing.T) {
41         assertions := require.New(t)
42         typesDir, err := os.MkdirTemp("", "configs")
43         if err != nil {
44                 t.Errorf("Unable to create temporary directory for types due to: %v", err)
45         }
46         t.Cleanup(func() {
47                 os.RemoveAll(typesDir)
48                 clearAll()
49         })
50         typeDir = typesDir
51         fname := filepath.Join(typesDir, "type1.json")
52         if err = os.WriteFile(fname, []byte(typeDefinition), 0666); err != nil {
53                 t.Errorf("Unable to create temporary files for types due to: %v", err)
54         }
55         types, err := GetTypes()
56         wantedType := Type{
57                 TypeId:     "type1",
58                 DMaaPTopic: "unauthenticated.SEC_FAULT_OUTPUT",
59                 Schema:     `{"title":"Type 1"}`,
60                 Jobs:       make(map[string]JobInfo),
61         }
62         wantedTypes := []*Type{&wantedType}
63         assertions.EqualValues(wantedTypes, types)
64         assertions.Nil(err)
65
66         supportedTypes := GetSupportedTypes()
67         assertions.EqualValues([]string{"type1"}, supportedTypes)
68 }
69
70 func TestAddJobWhenTypeIsSupported_shouldAddJobToAllJobsMap(t *testing.T) {
71         assertions := require.New(t)
72         wantedJob := JobInfo{
73                 Owner:            "owner",
74                 LastUpdated:      "now",
75                 InfoJobIdentity:  "job1",
76                 TargetUri:        "target",
77                 InfoJobData:      "{}",
78                 InfoTypeIdentity: "type1",
79         }
80         allJobs["type1"] = Type{
81                 TypeId: "type1",
82                 Jobs:   map[string]JobInfo{"job1": wantedJob},
83         }
84         t.Cleanup(func() {
85                 clearAll()
86         })
87
88         err := AddJob(wantedJob)
89         assertions.Nil(err)
90         assertions.Equal(1, len(allJobs["type1"].Jobs))
91         assertions.Equal(wantedJob, allJobs["type1"].Jobs["job1"])
92 }
93
94 func TestAddJobWhenTypeIsNotSupported_shouldReturnError(t *testing.T) {
95         assertions := require.New(t)
96         jobInfo := JobInfo{
97                 InfoTypeIdentity: "type1",
98         }
99
100         err := AddJob(jobInfo)
101         assertions.NotNil(err)
102         assertions.Equal("type not supported: type1", err.Error())
103 }
104
105 func TestAddJobWhenJobIdMissing_shouldReturnError(t *testing.T) {
106         assertions := require.New(t)
107         allJobs["type1"] = Type{
108                 TypeId: "type1",
109         }
110         t.Cleanup(func() {
111                 clearAll()
112         })
113         jobInfo := JobInfo{
114                 InfoTypeIdentity: "type1",
115         }
116
117         err := AddJob(jobInfo)
118         assertions.NotNil(err)
119         assertions.Equal("missing required job identity: {     type1}", err.Error())
120 }
121
122 func TestAddJobWhenTargetUriMissing_shouldReturnError(t *testing.T) {
123         assertions := require.New(t)
124         allJobs["type1"] = Type{
125                 TypeId: "type1",
126         }
127         jobInfo := JobInfo{
128                 InfoTypeIdentity: "type1",
129                 InfoJobIdentity:  "job1",
130         }
131
132         err := AddJob(jobInfo)
133         assertions.NotNil(err)
134         assertions.Equal("missing required target URI: {  job1   type1}", err.Error())
135         clearAll()
136 }
137
138 func TestPollAndDistributeMessages(t *testing.T) {
139         assertions := require.New(t)
140         jobInfo := JobInfo{
141                 InfoTypeIdentity: "type1",
142                 InfoJobIdentity:  "job1",
143                 TargetUri:        "http://consumerHost/target",
144         }
145         allJobs["type1"] = Type{
146                 TypeId:     "type1",
147                 DMaaPTopic: "topic",
148                 Jobs:       map[string]JobInfo{"job1": jobInfo},
149         }
150         t.Cleanup(func() {
151                 clearAll()
152         })
153
154         body := ioutil.NopCloser(bytes.NewReader([]byte(`[{"message": {"data": "data"}}]`)))
155         clientMock := mocks.HTTPClient{}
156         clientMock.On("Get", mock.Anything).Return(&http.Response{
157                 StatusCode: http.StatusOK,
158                 Body:       body,
159         }, nil)
160
161         clientMock.On("Do", mock.Anything).Return(&http.Response{
162                 StatusCode: http.StatusOK,
163         }, nil)
164
165         restclient.Client = &clientMock
166
167         pollAndDistributeMessages("http://mrAddr")
168
169         time.Sleep(100 * time.Millisecond)
170
171         var actualRequest *http.Request
172         clientMock.AssertCalled(t, "Get", "http://mrAddr/events/topic/users/dmaapmediatorproducer")
173         clientMock.AssertNumberOfCalls(t, "Get", 1)
174
175         clientMock.AssertCalled(t, "Do", mock.MatchedBy(func(req *http.Request) bool {
176                 actualRequest = req
177                 return true
178         }))
179         assertions.Equal(http.MethodPost, actualRequest.Method)
180         assertions.Equal("consumerHost", actualRequest.URL.Host)
181         assertions.Equal("/target", actualRequest.URL.Path)
182         assertions.Equal("application/json; charset=utf-8", actualRequest.Header.Get("Content-Type"))
183         actualBody, _ := ioutil.ReadAll(actualRequest.Body)
184         assertions.Equal([]byte(`[{"message": {"data": "data"}}]`), actualBody)
185         clientMock.AssertNumberOfCalls(t, "Do", 1)
186 }