c9debdd9984f86c405d7c122f196f81428ff5e40
[policy/distribution.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2018 Intel. All rights reserved.
4  *  Copyright (C) 2019 Nordix Foundation.
5  *  Modifications Copyright (C) 2020 Nordix Foundation
6  * ================================================================================
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.distribution.reception.handling.file;
24
25 import static org.assertj.core.api.Assertions.assertThatCode;
26
27 import com.google.gson.Gson;
28 import com.google.gson.GsonBuilder;
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 import org.junit.After;
36 import org.junit.Before;
37 import org.junit.Rule;
38 import org.junit.Test;
39 import org.junit.rules.TemporaryFolder;
40 import org.junit.runner.RunWith;
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.parameters.ParameterService;
46 import org.onap.policy.distribution.reception.decoding.PolicyDecodingException;
47 import org.onap.policy.distribution.reception.statistics.DistributionStatisticsManager;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 /**
52  * Class to perform unit test of {@link FileSystemReceptionHandler}.
53  */
54 @RunWith(MockitoJUnitRunner.class)
55 public class TestFileSystemReceptionHandler {
56
57     private static final Logger LOGGER = LoggerFactory.getLogger(TestFileSystemReceptionHandler.class);
58
59     @Rule
60     public TemporaryFolder tempFolder = new TemporaryFolder();
61
62     private FileSystemReceptionHandlerConfigurationParameterGroup pssdConfigParameters;
63     private FileSystemReceptionHandler fileSystemHandler;
64
65
66     /**
67      * Setup for the test cases.
68      *
69      * @throws IOException if it occurs
70      * @throws SecurityException if it occurs
71      * @throws NoSuchFieldException if it occurs
72      * @throws IllegalAccessException if it occurs
73      * @throws IllegalArgumentException if it occurs
74      */
75     @Before
76     public final void init() throws IOException, NoSuchFieldException, SecurityException, IllegalArgumentException,
77             IllegalAccessException {
78         DistributionStatisticsManager.resetAllStatistics();
79
80         final Gson gson = new GsonBuilder().create();
81         pssdConfigParameters = gson.fromJson(new FileReader("src/test/resources/handling-filesystem.json"),
82                 FileSystemReceptionHandlerConfigurationParameterGroup.class);
83         ParameterService.register(pssdConfigParameters);
84         fileSystemHandler = new FileSystemReceptionHandler();
85     }
86
87     @After
88     public void teardown() {
89         ParameterService.deregister(pssdConfigParameters);
90     }
91
92     @Test
93     public final void testInit() throws IOException, InterruptedException {
94         final FileSystemReceptionHandler sypHandler = Mockito.spy(fileSystemHandler);
95         Mockito.doNothing().when(sypHandler).initFileWatcher(Mockito.isA(String.class),
96                 Mockito.anyInt());
97         assertThatCode(() -> sypHandler.initializeReception(pssdConfigParameters.getName()))
98             .doesNotThrowAnyException();
99     }
100
101     @Test
102     public final void testDestroy() throws IOException {
103         final FileSystemReceptionHandler sypHandler = Mockito.spy(fileSystemHandler);
104         Mockito.doNothing().when(sypHandler).initFileWatcher(Mockito.isA(String.class),
105                 Mockito.anyInt());
106         assertThatCode(() -> {
107             sypHandler.initializeReception(pssdConfigParameters.getName());
108             sypHandler.destroy();
109         }).doesNotThrowAnyException();
110     }
111
112     @Test
113     public void testMain() throws IOException, PolicyDecodingException {
114         final Object lock = new Object();
115         final String watchPath = tempFolder.getRoot().getAbsolutePath().toString();
116
117         class Processed {
118             public boolean processed = false;
119         }
120
121         final Processed cond = new Processed();
122
123         final FileSystemReceptionHandler sypHandler = Mockito.spy(fileSystemHandler);
124         Mockito.doAnswer(new Answer<Object>() {
125             @Override
126             public Object answer(final InvocationOnMock invocation) {
127                 synchronized (lock) {
128                     cond.processed = true;
129                     lock.notifyAll();
130                 }
131                 return null;
132             }
133         }).when(sypHandler).createPolicyInputAndCallHandler(Mockito.isA(String.class));
134
135         final Thread th = new Thread(() -> {
136             try {
137                 sypHandler.initFileWatcher(watchPath, 2);
138             } catch (final IOException ex) {
139                 LOGGER.error("testMain failed", ex);
140             }
141         });
142
143         th.start();
144         try {
145             // wait until internal watch service started or counter reached
146             final AtomicInteger counter = new AtomicInteger();
147             counter.set(0);
148             synchronized (lock) {
149                 while (!sypHandler.isRunning() && counter.getAndIncrement() < 10) {
150                     lock.wait(1000);
151                 }
152             }
153             Files.copy(Paths.get("src/test/resources/hpaPolicyHugePage.csar"),
154                     Paths.get(watchPath + File.separator + "hpaPolicyHugePage.csar"));
155             // wait until mock method triggered or counter reached
156             counter.set(0);
157             synchronized (lock) {
158                 while (!cond.processed && counter.getAndIncrement() < 10) {
159                     lock.wait(1000);
160                 }
161             }
162             sypHandler.destroy();
163             th.interrupt();
164             th.join();
165         } catch (final InterruptedException ex) {
166             LOGGER.error("testMain failed", ex);
167         }
168         Mockito.verify(sypHandler, Mockito.times(1)).createPolicyInputAndCallHandler(Mockito.isA(String.class));
169
170     }
171 }
172