aboutsummaryrefslogtreecommitdiffstats
path: root/models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/impl/BidirectionalTopicOperationTest.java
blob: 587564a2e891ad595100f1d7d64afb07521c6d12 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
/*-
 * ============LICENSE_START=======================================================
 * ONAP
 * ================================================================================
 * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.controlloop.actorserviceprovider.impl;

import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.tuple.Pair;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
import org.onap.policy.common.utils.coder.Coder;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.coder.StandardCoderObject;
import org.onap.policy.common.utils.time.PseudoExecutor;
import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
import org.onap.policy.controlloop.actorserviceprovider.parameters.BidirectionalTopicConfig;
import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
import org.onap.policy.controlloop.actorserviceprovider.topic.BidirectionalTopicHandler;
import org.onap.policy.controlloop.actorserviceprovider.topic.Forwarder;
import org.onap.policy.controlloop.policy.PolicyResult;

public class BidirectionalTopicOperationTest {
    private static final CommInfrastructure SINK_INFRA = CommInfrastructure.NOOP;
    private static final IllegalStateException EXPECTED_EXCEPTION = new IllegalStateException("expected exception");
    private static final String ACTOR = "my-actor";
    private static final String OPERATION = "my-operation";
    private static final String REQ_ID = "my-request-id";
    private static final String TEXT = "some text";
    private static final String SUB_REQID = "my-sub-request-id";
    private static final int TIMEOUT_SEC = 10;
    private static final long TIMEOUT_MS = 1000 * TIMEOUT_SEC;
    private static final int MAX_REQUESTS = 100;

    private static final StandardCoder coder = new StandardCoder();

    @Mock
    private BidirectionalTopicConfig config;
    @Mock
    private BidirectionalTopicHandler handler;
    @Mock
    private Forwarder forwarder;

    @Captor
    private ArgumentCaptor<BiConsumer<String, StandardCoderObject>> listenerCaptor;

    private ControlLoopOperationParams params;
    private OperationOutcome outcome;
    private StandardCoderObject stdResponse;
    private String responseText;
    private PseudoExecutor executor;
    private int ntimes;
    private BidirectionalTopicOperation<MyRequest, MyResponse> oper;

    /**
     * Sets up.
     */
    @Before
    public void setUp() throws CoderException {
        MockitoAnnotations.initMocks(this);

        when(config.getTopicHandler()).thenReturn(handler);
        when(config.getForwarder()).thenReturn(forwarder);
        when(config.getTimeoutMs()).thenReturn(TIMEOUT_MS);

        when(handler.send(any())).thenReturn(true);
        when(handler.getSinkTopicCommInfrastructure()).thenReturn(SINK_INFRA);

        executor = new PseudoExecutor();

        params = ControlLoopOperationParams.builder().actor(ACTOR).operation(OPERATION).executor(executor).build();
        outcome = params.makeOutcome();

        responseText = coder.encode(new MyResponse());
        stdResponse = coder.decode(responseText, StandardCoderObject.class);

        ntimes = 1;

        oper = new MyOperation();
    }

    @Test
    public void testConstructor_testGetTopicHandler_testGetForwarder_testGetTopicParams() {
        assertEquals(ACTOR, oper.getActorName());
        assertEquals(OPERATION, oper.getName());
        assertSame(handler, oper.getTopicHandler());
        assertSame(forwarder, oper.getForwarder());
        assertEquals(TIMEOUT_MS, oper.getTimeoutMs());
        assertSame(MyResponse.class, oper.getResponseClass());
    }

    @Test
    public void testStartOperationAsync() throws Exception {

        // tell it to expect three responses
        ntimes = 3;

        CompletableFuture<OperationOutcome> future = oper.startOperationAsync(1, outcome);
        assertFalse(future.isDone());

        assertEquals(SUB_REQID, outcome.getSubRequestId());

        verify(forwarder).register(eq(Arrays.asList(REQ_ID)), listenerCaptor.capture());

        verify(forwarder, never()).unregister(any(), any());

        verify(handler).send(any());

        // provide first response
        listenerCaptor.getValue().accept(responseText, stdResponse);
        assertTrue(executor.runAll(MAX_REQUESTS));
        assertFalse(future.isDone());

        // provide second response
        listenerCaptor.getValue().accept(responseText, stdResponse);
        assertTrue(executor.runAll(MAX_REQUESTS));
        assertFalse(future.isDone());

        // provide final response
        listenerCaptor.getValue().accept(responseText, stdResponse);
        assertTrue(executor.runAll(MAX_REQUESTS));
        assertTrue(future.isDone());

        assertSame(outcome, future.get());
        assertEquals(PolicyResult.SUCCESS, outcome.getResult());

        verify(forwarder).unregister(eq(Arrays.asList(REQ_ID)), eq(listenerCaptor.getValue()));
    }

    /**
     * Tests startOperationAsync() when the publisher throws an exception.
     */
    @Test
    public void testStartOperationAsyncException() throws Exception {
        // indicate that nothing was published
        when(handler.send(any())).thenReturn(false);

        assertThatIllegalStateException().isThrownBy(() -> oper.startOperationAsync(1, outcome));

        verify(forwarder).register(eq(Arrays.asList(REQ_ID)), listenerCaptor.capture());

        // must still unregister
        verify(forwarder).unregister(eq(Arrays.asList(REQ_ID)), eq(listenerCaptor.getValue()));
    }

    @Test
    public void testGetTimeoutMsInteger() {
        // use default
        assertEquals(TIMEOUT_MS, oper.getTimeoutMs(null));
        assertEquals(TIMEOUT_MS, oper.getTimeoutMs(0));

        // use provided value
        assertEquals(5000, oper.getTimeoutMs(5));
    }

    @Test
    public void testPublishRequest() {
        assertThatCode(() -> oper.publishRequest(new MyRequest())).doesNotThrowAnyException();
    }

    /**
     * Tests publishRequest() when nothing is published.
     */
    @Test
    public void testPublishRequestUnpublished() {
        when(handler.send(any())).thenReturn(false);
        assertThatIllegalStateException().isThrownBy(() -> oper.publishRequest(new MyRequest()));
    }

    /**
     * Tests publishRequest() when the request type is a String.
     */
    @Test
    public void testPublishRequestString() {
        MyStringOperation oper2 = new MyStringOperation();
        assertThatCode(() -> oper2.publishRequest(TEXT)).doesNotThrowAnyException();
    }

    /**
     * Tests publishRequest() when the coder throws an exception.
     */
    @Test
    public void testPublishRequestException() {
        setOperCoderException();
        assertThatIllegalArgumentException().isThrownBy(() -> oper.publishRequest(new MyRequest()));
    }

    /**
     * Tests processResponse() when it's a success and the response type is a String.
     */
    @Test
    public void testProcessResponseSuccessString() {
        MyStringOperation oper2 = new MyStringOperation();

        assertSame(outcome, oper2.processResponse(outcome, TEXT, null));
        assertEquals(PolicyResult.SUCCESS, outcome.getResult());
    }

    /**
     * Tests processResponse() when it's a success and the response type is a
     * StandardCoderObject.
     */
    @Test
    public void testProcessResponseSuccessSco() {
        MyScoOperation oper2 = new MyScoOperation();

        assertSame(outcome, oper2.processResponse(outcome, responseText, stdResponse));
        assertEquals(PolicyResult.SUCCESS, outcome.getResult());
    }

    /**
     * Tests processResponse() when it's a failure.
     */
    @Test
    public void testProcessResponseFailure() throws CoderException {
        // indicate error in the response
        MyResponse resp = new MyResponse();
        resp.setOutput("error");

        responseText = coder.encode(resp);
        stdResponse = coder.decode(responseText, StandardCoderObject.class);

        assertSame(outcome, oper.processResponse(outcome, responseText, stdResponse));
        assertEquals(PolicyResult.FAILURE, outcome.getResult());
    }

    /**
     * Tests processResponse() when the decoder succeeds.
     */
    @Test
    public void testProcessResponseDecodeOk() throws CoderException {
        assertSame(outcome, oper.processResponse(outcome, responseText, stdResponse));
        assertEquals(PolicyResult.SUCCESS, outcome.getResult());
    }

    /**
     * Tests processResponse() when the decoder throws an exception.
     */
    @Test
    public void testProcessResponseDecodeExcept() throws CoderException {
        // @formatter:off
        assertThatIllegalArgumentException().isThrownBy(
            () -> oper.processResponse(outcome, "{invalid json", stdResponse));
        // @formatter:on
    }

    @Test
    public void testPostProcessResponse() {
        assertThatCode(() -> oper.postProcessResponse(outcome, null, null)).doesNotThrowAnyException();
    }

    @Test
    public void testMakeCoder() {
        assertNotNull(oper.makeCoder());
    }

    /**
     * Creates a new {@link #oper} whose coder will throw an exception.
     */
    private void setOperCoderException() {
        oper = new MyOperation() {
            @Override
            protected Coder makeCoder() {
                return new StandardCoder() {
                    @Override
                    public String encode(Object object, boolean pretty) throws CoderException {
                        throw new CoderException(EXPECTED_EXCEPTION);
                    }
                };
            }
        };
    }

    @Getter
    @Setter
    public static class MyRequest {
        private String theRequestId = REQ_ID;
        private String input;
    }

    @Getter
    @Setter
    public static class MyResponse {
        private String requestId = REQ_ID;
        private String output;
    }


    private class MyStringOperation extends BidirectionalTopicOperation<String, String> {

        public MyStringOperation() {
            super(BidirectionalTopicOperationTest.this.params, config, String.class);
        }

        @Override
        protected Pair<String, String> makeRequest(int attempt) {
            return Pair.of(SUB_REQID, TEXT);
        }

        @Override
        protected List<String> getExpectedKeyValues(int attempt, String request) {
            return Arrays.asList(REQ_ID);
        }

        @Override
        protected Status detmStatus(String rawResponse, String response) {
            return (response != null ? Status.SUCCESS : Status.FAILURE);
        }
    }


    private class MyScoOperation extends BidirectionalTopicOperation<MyRequest, StandardCoderObject> {
        public MyScoOperation() {
            super(BidirectionalTopicOperationTest.this.params, config, StandardCoderObject.class);
        }

        @Override
        protected Pair<String, MyRequest> makeRequest(int attempt) {
            return Pair.of(SUB_REQID, new MyRequest());
        }

        @Override
        protected List<String> getExpectedKeyValues(int attempt, MyRequest request) {
            return Arrays.asList(REQ_ID);
        }

        @Override
        protected Status detmStatus(String rawResponse, StandardCoderObject response) {
            return (response.getString("output") == null ? Status.SUCCESS : Status.FAILURE);
        }
    }


    private class MyOperation extends BidirectionalTopicOperation<MyRequest, MyResponse> {
        public MyOperation() {
            super(BidirectionalTopicOperationTest.this.params, config, MyResponse.class);
        }

        @Override
        protected Pair<String, MyRequest> makeRequest(int attempt) {
            return Pair.of(SUB_REQID, new MyRequest());
        }

        @Override
        protected List<String> getExpectedKeyValues(int attempt, MyRequest request) {
            return Arrays.asList(REQ_ID);
        }

        @Override
        protected Status detmStatus(String rawResponse, MyResponse response) {
            if (--ntimes <= 0) {
                return (response.getOutput() == null ? Status.SUCCESS : Status.FAILURE);
            }

            return Status.STILL_WAITING;
        }
    }
}