7f97c5cfcaccd94a8de3b7550e06cb239730aeb9
[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 import java.io.File;
29 import java.io.FileReader;
30 import java.io.IOException;
31 import java.nio.file.Files;
32 import java.nio.file.Paths;
33 import java.util.concurrent.atomic.AtomicInteger;
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.Mockito;
41 import org.mockito.invocation.InvocationOnMock;
42 import org.mockito.runners.MockitoJUnitRunner;
43 import org.mockito.stubbing.Answer;
44 import org.onap.policy.common.parameters.ParameterService;
45 import org.onap.policy.distribution.reception.decoding.PolicyDecodingException;
46 import org.onap.policy.distribution.reception.statistics.DistributionStatisticsManager;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 /**
51  * Class to perform unit test of {@link FileSystemReceptionHandler}.
52  */
53 @RunWith(MockitoJUnitRunner.class)
54 public class TestFileSystemReceptionHandler {
55
56     private static final Logger LOGGER = LoggerFactory.getLogger(TestFileSystemReceptionHandler.class);
57
58     @Rule
59     public TemporaryFolder tempFolder = new TemporaryFolder();
60
61     private FileSystemReceptionHandlerConfigurationParameterGroup pssdConfigParameters;
62     private FileSystemReceptionHandler fileSystemHandler;
63
64
65     /**
66      * Setup for the test cases.
67      *
68      * @throws IOException if it occurs
69      * @throws SecurityException if it occurs
70      * @throws NoSuchFieldException if it occurs
71      * @throws IllegalAccessException if it occurs
72      * @throws IllegalArgumentException if it occurs
73      */
74     @Before
75     public final void init() throws IOException, NoSuchFieldException, SecurityException, IllegalArgumentException,
76             IllegalAccessException {
77         DistributionStatisticsManager.resetAllStatistics();
78
79         final Gson gson = new GsonBuilder().create();
80         pssdConfigParameters = gson.fromJson(new FileReader("src/test/resources/handling-filesystem.json"),
81                 FileSystemReceptionHandlerConfigurationParameterGroup.class);
82         ParameterService.register(pssdConfigParameters);
83         fileSystemHandler = new FileSystemReceptionHandler();
84     }
85
86     @After
87     public void teardown() {
88         ParameterService.deregister(pssdConfigParameters);
89     }
90
91     @Test
92     public final void testInit() throws IOException, InterruptedException {
93         final FileSystemReceptionHandler sypHandler = Mockito.spy(fileSystemHandler);
94         Mockito.doNothing().when(sypHandler).initFileWatcher(Mockito.isA(String.class),
95                 Mockito.anyInt());
96         try {
97             sypHandler.initializeReception(pssdConfigParameters.getName());
98         } catch (final Exception exp) {
99             LOGGER.error("testInit failed", exp);
100             fail("Test should not throw any exception");
101         }
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).initFileWatcher(Mockito.isA(String.class),
109                     Mockito.anyInt());
110             sypHandler.initializeReception(pssdConfigParameters.getName());
111             sypHandler.destroy();
112         } catch (final Exception exp) {
113             LOGGER.error("testDestroy failed", exp);
114             fail("Test should not throw any exception");
115         }
116
117     }
118
119     @Test
120     public void testMain() throws IOException, PolicyDecodingException {
121         final Object lock = new Object();
122         final String watchPath = tempFolder.getRoot().getAbsolutePath().toString();
123
124         class Processed {
125             public boolean processed = false;
126         }
127
128         final Processed cond = new Processed();
129
130         final FileSystemReceptionHandler sypHandler = Mockito.spy(fileSystemHandler);
131         Mockito.doAnswer(new Answer<Object>() {
132             @Override
133             public Object answer(final InvocationOnMock invocation) {
134                 synchronized (lock) {
135                     cond.processed = true;
136                     lock.notifyAll();
137                 }
138                 return null;
139             }
140         }).when(sypHandler).createPolicyInputAndCallHandler(Mockito.isA(String.class));
141
142         final Thread th = new Thread(() -> {
143             try {
144                 sypHandler.initFileWatcher(watchPath, 2);
145             } catch (final IOException ex) {
146                 LOGGER.error("testMain failed", ex);
147             }
148         });
149
150         th.start();
151         try {
152             // wait until internal watch service started or counter reached
153             final AtomicInteger counter = new AtomicInteger();
154             counter.set(0);
155             synchronized (lock) {
156                 while (!sypHandler.isRunning() && counter.getAndIncrement() < 10) {
157                     lock.wait(1000);
158                 }
159             }
160             Files.copy(Paths.get("src/test/resources/hpaPolicyHugePage.csar"),
161                     Paths.get(watchPath + File.separator + "hpaPolicyHugePage.csar"));
162             // wait until mock method triggered or counter reached
163             counter.set(0);
164             synchronized (lock) {
165                 while (!cond.processed && counter.getAndIncrement() < 10) {
166                     lock.wait(1000);
167                 }
168             }
169             sypHandler.destroy();
170             th.interrupt();
171             th.join();
172         } catch (final InterruptedException ex) {
173             LOGGER.error("testMain failed", ex);
174         }
175         Mockito.verify(sypHandler, Mockito.times(1)).createPolicyInputAndCallHandler(Mockito.isA(String.class));
176
177     }
178 }
179