2 // ========================LICENSE_START=================================
5 // Copyright (C) 2021: Nordix Foundation
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
11 // http://www.apache.org/licenses/LICENSE-2.0
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===================================
33 "github.com/stretchr/testify/require"
34 "oransc.org/nonrtric/dmaapmediatorproducer/internal/restclient"
37 const typeDefinition = `{"types": [{"id": "type1", "dmaapTopicUrl": "events/unauthenticated.SEC_FAULT_OUTPUT/dmaapmediatorproducer/type1"}]}`
39 func TestGetTypes_filesOkShouldReturnSliceOfTypesAndProvideSupportedTypes(t *testing.T) {
40 assertions := require.New(t)
41 typesDir, err := os.MkdirTemp("", "configs")
43 t.Errorf("Unable to create temporary directory for types due to: %v", err)
46 os.RemoveAll(typesDir)
49 fname := filepath.Join(typesDir, "type_config.json")
51 if err = os.WriteFile(fname, []byte(typeDefinition), 0666); err != nil {
52 t.Errorf("Unable to create temporary config file for types due to: %v", err)
54 types, err := GetTypes()
55 wantedType := TypeData{
57 DMaaPTopicURL: "events/unauthenticated.SEC_FAULT_OUTPUT/dmaapmediatorproducer/type1",
58 Jobs: make(map[string]JobInfo),
60 wantedTypes := []TypeData{wantedType}
61 assertions.EqualValues(wantedTypes, types)
64 supportedTypes := GetSupportedTypes()
65 assertions.EqualValues([]string{"type1"}, supportedTypes)
68 func TestAddJobWhenTypeIsSupported_shouldAddJobToAllJobsMap(t *testing.T) {
69 assertions := require.New(t)
73 InfoJobIdentity: "job1",
76 InfoTypeIdentity: "type1",
78 allTypes["type1"] = TypeData{
80 Jobs: map[string]JobInfo{"job1": wantedJob},
86 err := AddJob(wantedJob)
88 assertions.Equal(1, len(allTypes["type1"].Jobs))
89 assertions.Equal(wantedJob, allTypes["type1"].Jobs["job1"])
92 func TestAddJobWhenTypeIsNotSupported_shouldReturnError(t *testing.T) {
93 assertions := require.New(t)
95 InfoTypeIdentity: "type1",
98 err := AddJob(jobInfo)
99 assertions.NotNil(err)
100 assertions.Equal("type not supported: type1", err.Error())
103 func TestAddJobWhenJobIdMissing_shouldReturnError(t *testing.T) {
104 assertions := require.New(t)
105 allTypes["type1"] = TypeData{
112 InfoTypeIdentity: "type1",
115 err := AddJob(jobInfo)
116 assertions.NotNil(err)
117 assertions.Equal("missing required job identity: { <nil> type1}", err.Error())
120 func TestAddJobWhenTargetUriMissing_shouldReturnError(t *testing.T) {
121 assertions := require.New(t)
122 allTypes["type1"] = TypeData{
126 InfoTypeIdentity: "type1",
127 InfoJobIdentity: "job1",
130 err := AddJob(jobInfo)
131 assertions.NotNil(err)
132 assertions.Equal("missing required target URI: { job1 <nil> type1}", err.Error())
136 func TestDeleteJob(t *testing.T) {
137 assertions := require.New(t)
138 jobToKeep := JobInfo{
139 InfoJobIdentity: "job1",
140 InfoTypeIdentity: "type1",
142 jobToDelete := JobInfo{
143 InfoJobIdentity: "job2",
144 InfoTypeIdentity: "type1",
146 allTypes["type1"] = TypeData{
148 Jobs: map[string]JobInfo{"job1": jobToKeep, "job2": jobToDelete},
155 assertions.Equal(1, len(allTypes["type1"].Jobs))
156 assertions.Equal(jobToKeep, allTypes["type1"].Jobs["job1"])
159 func TestPollAndDistributeMessages(t *testing.T) {
160 assertions := require.New(t)
162 InfoTypeIdentity: "type1",
163 InfoJobIdentity: "job1",
164 TargetUri: "http://consumerHost/target",
166 allTypes["type1"] = TypeData{
168 DMaaPTopicURL: "topicUrl",
169 Jobs: map[string]JobInfo{"job1": jobInfo},
175 wg := sync.WaitGroup{}
176 wg.Add(2) // Two calls should be made to the server, one to poll and one to distribute
177 messages := `[{"message": {"data": "data"}}]`
178 clientMock := NewTestClient(func(req *http.Request) *http.Response {
179 if req.URL.String() == "http://mrAddr/topicUrl" {
180 assertions.Equal(req.Method, "GET")
182 return &http.Response{
184 Body: ioutil.NopCloser(bytes.NewReader([]byte(messages))),
185 Header: make(http.Header), // Must be set to non-nil value or it panics
187 } else if req.URL.String() == "http://consumerHost/target" {
188 assertions.Equal(req.Method, "POST")
189 assertions.Equal(messages, getBodyAsString(req))
190 assertions.Equal("application/json; charset=utf-8", req.Header.Get("Content-Type"))
192 return &http.Response{
194 Body: ioutil.NopCloser(bytes.NewBufferString(`OK`)),
195 Header: make(http.Header), // Must be set to non-nil value or it panics
198 t.Error("Wrong call to client: ", req)
203 restclient.Client = clientMock
205 pollAndDistributeMessages("http://mrAddr")
207 if waitTimeout(&wg, 100*time.Millisecond) {
208 t.Error("Not all calls to server were made")
213 type RoundTripFunc func(req *http.Request) *http.Response
215 func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
219 //NewTestClient returns *http.Client with Transport replaced to avoid making real calls
220 func NewTestClient(fn RoundTripFunc) *http.Client {
222 Transport: RoundTripFunc(fn),
226 // waitTimeout waits for the waitgroup for the specified max timeout.
227 // Returns true if waiting timed out.
228 func waitTimeout(wg *sync.WaitGroup, timeout time.Duration) bool {
229 c := make(chan struct{})
236 return false // completed normally
237 case <-time.After(timeout):
238 return true // timed out
242 func getBodyAsString(req *http.Request) string {
243 buf := new(bytes.Buffer)
244 buf.ReadFrom(req.Body)