29eb3f7e8d17f0779b9a940c3630c81a3d396949
[policy/distribution.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2018 Intel. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.distribution.reception.handling.sdc;
22
23 import static org.junit.Assert.fail;
24
25 import com.google.gson.Gson;
26 import com.google.gson.GsonBuilder;
27
28 import java.io.File;
29 import java.io.IOException;
30 import java.nio.file.Files;
31 import java.nio.file.Paths;
32 import java.util.concurrent.atomic.AtomicInteger;
33
34 import org.junit.After;
35 import org.junit.Before;
36 import org.junit.Rule;
37 import org.junit.Test;
38 import org.junit.rules.TemporaryFolder;
39 import org.junit.runner.RunWith;
40 import org.mockito.Mock;
41 import org.mockito.Mockito;
42 import org.mockito.invocation.InvocationOnMock;
43 import org.mockito.runners.MockitoJUnitRunner;
44 import org.mockito.stubbing.Answer;
45 import org.onap.policy.common.logging.flexlogger.FlexLogger;
46 import org.onap.policy.common.logging.flexlogger.Logger;
47 import org.onap.policy.common.parameters.ParameterService;
48 import org.onap.policy.distribution.forwarding.PolicyForwarder;
49 import org.onap.policy.distribution.reception.decoding.PolicyDecodingException;
50 import org.onap.policy.distribution.reception.statistics.DistributionStatisticsManager;
51
52 /**
53  * Class to perform unit test of {@link FileSystemReceptionHandler}.
54  */
55 @RunWith(MockitoJUnitRunner.class)
56 public class TestFileSystemReceptionHandler {
57
58     private static final Logger LOGGER = FlexLogger.getLogger(TestFileSystemReceptionHandler.class);
59     private static final String DUMMY_SERVICE_CSAR = "dummyService.csar";
60
61     @Rule
62     public TemporaryFolder tempFolder = new TemporaryFolder();
63
64     private FileSystemReceptionHandlerConfigurationParameterGroup pssdConfigParameters;
65     private FileSystemReceptionHandler fileSystemHandler;
66
67
68     /**
69      * Setup for the test cases.
70      *
71      * @throws IOException if it occurs
72      * @throws SecurityException if it occurs
73      * @throws NoSuchFieldException if it occurs
74      * @throws IllegalAccessException if it occurs
75      * @throws IllegalArgumentException if it occurs
76      */
77     @Before
78     public final void init() throws IOException, NoSuchFieldException, SecurityException, IllegalArgumentException,
79             IllegalAccessException {
80         DistributionStatisticsManager.resetAllStatistics();
81
82         final Gson gson = new GsonBuilder().create();
83         String json = "{ \"name\": \"parameterConfig9\", \"watchPath\": \"";
84         json += tempFolder.getRoot().getAbsolutePath() + "\"}";
85         pssdConfigParameters = gson.fromJson(json,
86                 FileSystemReceptionHandlerConfigurationParameterGroup.class);
87         ParameterService.register(pssdConfigParameters);
88         fileSystemHandler = new FileSystemReceptionHandler();
89     }
90
91     @After
92     public void teardown() {
93         ParameterService.deregister(pssdConfigParameters);
94     }
95
96     @Test
97     public final void testInit() throws IOException {
98         final FileSystemReceptionHandler sypHandler = Mockito.spy(fileSystemHandler);
99         Mockito.doNothing().when(sypHandler).main(Mockito.isA(String.class));
100         sypHandler.initializeReception(pssdConfigParameters.getName());
101         Mockito.verify(sypHandler, Mockito.times(1)).main(Mockito.isA(String.class));
102     }
103
104     @Test
105     public final void testDestroy() throws IOException {
106         try {
107             final FileSystemReceptionHandler sypHandler = Mockito.spy(fileSystemHandler);
108             Mockito.doNothing().when(sypHandler).main(Mockito.isA(String.class));
109             sypHandler.initializeReception(pssdConfigParameters.getName());
110             sypHandler.destroy();
111         } catch (final Exception exp) {
112             LOGGER.error(exp);
113             fail("Test should not throw any exception");
114         }
115
116     }
117
118     @Test
119     public void testMain() throws IOException, PolicyDecodingException {
120         final Object lock = new Object();
121         final String watchPath = tempFolder.getRoot().getAbsolutePath().toString();
122
123         class Processed {
124             public boolean processed = false;
125         }
126
127         Processed cond = new Processed();
128
129         final FileSystemReceptionHandler sypHandler = Mockito.spy(fileSystemHandler);
130         Mockito.doAnswer(new Answer() {
131             public Object answer(InvocationOnMock invocation) {
132                 synchronized (lock) {
133                     cond.processed = true;
134                     lock.notifyAll();
135                 }
136                 return null;
137             }
138         }).when(sypHandler).createPolicyInputAndCallHandler(Mockito.isA(String.class));
139
140         Thread th = new Thread(() -> {
141             try {
142                 sypHandler.main(watchPath);
143             } catch (IOException ex) {
144                 LOGGER.error(ex);
145             }
146         });
147
148         th.start();
149         try {
150             //wait until internal watch service started or counter reached
151             AtomicInteger counter = new AtomicInteger();
152             counter.set(0);
153             synchronized (lock) {
154                 while (!sypHandler.isRunning() && counter.getAndIncrement() < 10) {
155                     lock.wait(1000);
156                 }
157             }
158             Files.copy(Paths.get("src/test/resources/hpaPolicyHugePage.csar"),
159                 Paths.get(watchPath + File.separator + "hpaPolicyHugePage.csar"));
160             //wait until mock method triggered or counter reached
161             counter.set(0);
162             synchronized (lock) {
163                 while (!cond.processed && counter.getAndIncrement() < 10) {
164                     lock.wait(1000);
165                 }
166             }
167             sypHandler.destroy();
168             th.interrupt();
169             th.join();
170         } catch (final InterruptedException ex) {
171             LOGGER.error(ex);
172         }
173         Mockito.verify(sypHandler, Mockito.times(1))
174             .createPolicyInputAndCallHandler(Mockito.isA(String.class));
175
176     }
177 }
178