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