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())
135 func TestPollAndDistributeMessages(t *testing.T) {
136 assertions := require.New(t)
138 InfoTypeIdentity: "type1",
139 InfoJobIdentity: "job1",
140 TargetUri: "http://consumerHost/target",
142 allTypes["type1"] = TypeData{
144 DMaaPTopicURL: "topicUrl",
145 Jobs: map[string]JobInfo{"job1": jobInfo},
151 wg := sync.WaitGroup{}
152 wg.Add(2) // Two calls should be made to the server, one to poll and one to distribute
153 messages := `[{"message": {"data": "data"}}]`
154 clientMock := NewTestClient(func(req *http.Request) *http.Response {
155 if req.URL.String() == "http://mrAddr/topicUrl" {
156 assertions.Equal(req.Method, "GET")
158 return &http.Response{
160 Body: ioutil.NopCloser(bytes.NewReader([]byte(messages))),
161 Header: make(http.Header), // Must be set to non-nil value or it panics
163 } else if req.URL.String() == "http://consumerHost/target" {
164 assertions.Equal(req.Method, "POST")
165 assertions.Equal(messages, getBodyAsString(req))
166 assertions.Equal("application/json; charset=utf-8", req.Header.Get("Content-Type"))
168 return &http.Response{
170 Body: ioutil.NopCloser(bytes.NewBufferString(`OK`)),
171 Header: make(http.Header), // Must be set to non-nil value or it panics
174 t.Error("Wrong call to client: ", req)
179 restclient.Client = clientMock
181 pollAndDistributeMessages("http://mrAddr")
183 if waitTimeout(&wg, 100*time.Millisecond) {
184 t.Error("Not all calls to server were made")
189 type RoundTripFunc func(req *http.Request) *http.Response
191 func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
195 //NewTestClient returns *http.Client with Transport replaced to avoid making real calls
196 func NewTestClient(fn RoundTripFunc) *http.Client {
198 Transport: RoundTripFunc(fn),
202 // waitTimeout waits for the waitgroup for the specified max timeout.
203 // Returns true if waiting timed out.
204 func waitTimeout(wg *sync.WaitGroup, timeout time.Duration) bool {
205 c := make(chan struct{})
212 return false // completed normally
213 case <-time.After(timeout):
214 return true // timed out
218 func getBodyAsString(req *http.Request) string {
219 buf := new(bytes.Buffer)
220 buf.ReadFrom(req.Body)