e727602ff56f8a6d3913e55cb27fd87e352fa9db
[vfc/nfvo/driver/vnfm/svnfm.git] / nokiav2 / driver / src / test / java / org / onap / vfc / nfvo / driver / vnfm / svnfm / nokia / TestNokiaSvnfmApplication.java
1 /*
2  * Copyright 2016-2017, Nokia Corporation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia;
17
18 import java.util.HashSet;
19 import java.util.Set;
20 import org.junit.Before;
21 import org.junit.Test;
22 import org.mockito.InOrder;
23 import org.mockito.Mock;
24 import org.mockito.Mockito;
25 import org.mockito.invocation.InvocationOnMock;
26 import org.mockito.stubbing.Answer;
27 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.SystemFunctions;
28 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.JobManagerForSo;
29 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.JobManagerForVfc;
30 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.TestBase;
31 import org.springframework.boot.SpringApplication;
32 import org.springframework.boot.context.event.ApplicationReadyEvent;
33 import org.springframework.context.ApplicationContext;
34 import org.springframework.context.ConfigurableApplicationContext;
35 import org.springframework.context.event.ContextClosedEvent;
36 import org.springframework.core.env.ConfigurableEnvironment;
37
38 import static junit.framework.TestCase.*;
39 import static org.mockito.Mockito.*;
40 import static org.springframework.test.util.ReflectionTestUtils.setField;
41
42
43 public class TestNokiaSvnfmApplication extends TestBase {
44     @Mock
45     private JobManagerForVfc jobManagerForVfc;
46     @Mock
47     private JobManagerForSo jobManagerForSo;
48
49     private NokiaSvnfmApplication.SelfRegistrationTrigger selfRegistrationTriggerer;
50     private NokiaSvnfmApplication.SelfDeRegistrationTrigger selfUnregistrationTriggerer;
51
52
53     @Before
54     public void initMocks() throws Exception {
55         selfRegistrationTriggerer = new NokiaSvnfmApplication.SelfRegistrationTrigger(selfRegistrationManagerForVfc, selfRegistrationManagerForSo, jobManagerForSo, jobManagerForVfc);
56         selfUnregistrationTriggerer = new NokiaSvnfmApplication.SelfDeRegistrationTrigger(selfRegistrationManagerForVfc, selfRegistrationManagerForSo, jobManagerForSo, jobManagerForVfc);
57         setField(NokiaSvnfmApplication.class, "logger", logger);
58     }
59
60     /**
61      * Assert that the entry point of the application does not change
62      */
63     @Test
64     public void doNotRename() {
65         //verify
66         //1. if the entry point is renamed the main class of spring boot in the driverwar must also be changed
67         //2. all classes that use @Autowrire must be in a subpackage relative to this class
68         assertEquals("org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.NokiaSvnfmApplication", NokiaSvnfmApplication.class.getCanonicalName());
69     }
70
71     /**
72      * Assert that the self registration process is started after the servlet is up and is able to answer REST requests.
73      */
74     @Test
75     @SuppressWarnings("squid:S2925") //the execution is asynchronous no other way to wait
76     public void testRegistrationIsCalledAfterComponentIsUp() throws Exception {
77         //given
78         ApplicationReadyEvent event = Mockito.mock(ApplicationReadyEvent.class);
79         useVfc(event);
80         //when
81         selfRegistrationTriggerer.onApplicationEvent(event);
82         //verify
83         boolean success = false;
84         while (!success) {
85             try {
86                 verify(selfRegistrationManagerForVfc).register();
87                 verify(logger).info("Self registration started");
88                 verify(logger).info("Self registration finished");
89                 success = true;
90             } catch (Error e) {
91
92             }
93             Thread.sleep(10);
94         }
95         // this forces the event to be fired after the servlet is up (prevents refactor)
96         assertTrue(ApplicationReadyEvent.class.isAssignableFrom(event.getClass()));
97     }
98
99     /**
100      * Assert that the self registration process is started after the servlet is up and is able to answer REST requests.
101      */
102     @Test
103     @SuppressWarnings("squid:S2925") //the execution is asynchronous no other way to wait
104     public void testRegistrationIsNotCalledIfPreparingForShutdown() throws Exception {
105         //given
106         ApplicationReadyEvent event = Mockito.mock(ApplicationReadyEvent.class);
107         useSo(event);
108         when(jobManagerForSo.isPreparingForShutDown()).thenReturn(true);
109         //when
110         selfRegistrationTriggerer.onApplicationEvent(event);
111         //verify
112         boolean success = false;
113         while (!success) {
114             try {
115                 verify(logger).warn("Component is preparing for shutdown giving up component start");
116                 success = true;
117             } catch (Error e) {
118
119             }
120             Thread.sleep(10);
121         }
122         verify(selfRegistrationManagerForSo, never()).register();
123         // this forces the event to be fired after the servlet is up (prevents refactor)
124         assertTrue(ApplicationReadyEvent.class.isAssignableFrom(event.getClass()));
125     }
126
127
128     /**
129      * Assert that the self registration process is started after the servlet is up and is able to answer REST requests.
130      */
131     @Test
132     @SuppressWarnings("squid:S2925") //the execution is asynchronous no other way to wait
133     public void testRegistrationIsCalledAfterComponentIsUpForSo() throws Exception {
134         //given
135         ApplicationReadyEvent event = Mockito.mock(ApplicationReadyEvent.class);
136         useSo(event);
137         //when
138         selfRegistrationTriggerer.onApplicationEvent(event);
139         //verify
140         boolean success = false;
141         while (!success) {
142             try {
143                 verify(selfRegistrationManagerForSo).register();
144                 verify(logger).info("Self registration started");
145                 verify(logger).info("Self registration finished");
146                 success = true;
147             } catch (Error e) {
148
149             }
150             Thread.sleep(10);
151         }
152         // this forces the event to be fired after the servlet is up (prevents refactor)
153         assertTrue(ApplicationReadyEvent.class.isAssignableFrom(event.getClass()));
154     }
155
156     /**
157      * Failuires in the self registration process is retried for SO
158      */
159     @Test
160     @SuppressWarnings("squid:S2925") //the execution is asynchronous no other way to wait
161     public void testFailuresInRegistrationIsRetriedForSo() throws Exception {
162         //given
163         ApplicationReadyEvent event = Mockito.mock(ApplicationReadyEvent.class);
164         RuntimeException e2 = new RuntimeException();
165         useSo(event);
166         Set<Boolean> calls = new HashSet<>();
167         doAnswer(new Answer() {
168             @Override
169             public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
170                 if (calls.size() == 0) {
171                     calls.add(true);
172                     throw e2;
173                 }
174                 return null;
175             }
176         }).when(selfRegistrationManagerForSo).register();
177         //when
178         selfRegistrationTriggerer.onApplicationEvent(event);
179         //verify
180         boolean success = false;
181         while (!success) {
182             try {
183                 verify(logger).info("Self registration finished");
184                 success = true;
185             } catch (Error e) {
186
187             }
188             Thread.sleep(10);
189         }
190         verify(selfRegistrationManagerForSo, times(2)).register();
191         verify(systemFunctions).sleep(5000);
192         verify(logger, times(2)).info("Self registration started");
193         verify(logger).error("Self registration failed", e2);
194         // this forces the event to be fired after the servlet is up (prevents refactor)
195         assertTrue(ApplicationReadyEvent.class.isAssignableFrom(event.getClass()));
196     }
197
198     /**
199      * Failuires in the self registration process is retried for VFC
200      */
201     @Test
202     @SuppressWarnings("squid:S2925") //the execution is asynchronous no other way to wait
203     public void testFailuresInRegistrationIsRetriedForVfc() throws Exception {
204         //given
205         ApplicationReadyEvent event = Mockito.mock(ApplicationReadyEvent.class);
206         RuntimeException e2 = new RuntimeException();
207         useVfc(event);
208         Set<Boolean> calls = new HashSet<>();
209         doAnswer(new Answer() {
210             @Override
211             public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
212                 if (calls.size() == 0) {
213                     calls.add(true);
214                     throw e2;
215                 }
216                 return null;
217             }
218         }).when(selfRegistrationManagerForVfc).register();
219         //when
220         selfRegistrationTriggerer.onApplicationEvent(event);
221         //verify
222         boolean success = false;
223         while (!success) {
224             try {
225                 verify(logger).info("Self registration finished");
226                 success = true;
227             } catch (Error e) {
228
229             }
230             Thread.sleep(10);
231         }
232         verify(selfRegistrationManagerForVfc, times(2)).register();
233         verify(systemFunctions).sleep(5000);
234         verify(logger, times(2)).info("Self registration started");
235         verify(logger).error("Self registration failed", e2);
236         // this forces the event to be fired after the servlet is up (prevents refactor)
237         assertTrue(ApplicationReadyEvent.class.isAssignableFrom(event.getClass()));
238     }
239
240     private void useSo(ApplicationReadyEvent event) {
241         ConfigurableApplicationContext context = Mockito.mock(ConfigurableApplicationContext.class);
242         ConfigurableEnvironment environment = Mockito.mock(ConfigurableEnvironment.class);
243         when(context.getEnvironment()).thenReturn(environment);
244         when(event.getApplicationContext()).thenReturn(context);
245         when(environment.getActiveProfiles()).thenReturn(new String[]{"direct"});
246     }
247
248     private void useVfc(ApplicationReadyEvent event) {
249         ConfigurableApplicationContext context = Mockito.mock(ConfigurableApplicationContext.class);
250         ConfigurableEnvironment environment = Mockito.mock(ConfigurableEnvironment.class);
251         when(context.getEnvironment()).thenReturn(environment);
252         when(event.getApplicationContext()).thenReturn(context);
253         when(environment.getActiveProfiles()).thenReturn(new String[]{});
254     }
255
256     private void useVfc(ContextClosedEvent event) {
257         ApplicationContext context = Mockito.mock(ApplicationContext.class);
258         when(context.getEnvironment()).thenReturn(environment);
259         when(event.getApplicationContext()).thenReturn(context);
260         when(environment.getActiveProfiles()).thenReturn(new String[]{});
261     }
262
263     private void useSo(ContextClosedEvent event) {
264         ApplicationContext context = Mockito.mock(ApplicationContext.class);
265         when(context.getEnvironment()).thenReturn(environment);
266         when(event.getApplicationContext()).thenReturn(context);
267         when(environment.getActiveProfiles()).thenReturn(new String[]{"direct"});
268     }
269
270     /**
271      * Assert that the self de-registration process is started after the servlet has been ramped down
272      */
273     @Test
274     public void testUnRegistrationIsCalledAfterComponentIsUp() throws Exception {
275         //given
276         ContextClosedEvent event = Mockito.mock(ContextClosedEvent.class);
277         useVfc(event);
278         //when
279         selfUnregistrationTriggerer.onApplicationEvent(event);
280         //verify
281         InOrder inOrder = Mockito.inOrder(jobManagerForVfc, jobManagerForSo, selfRegistrationManagerForVfc);
282         inOrder.verify(jobManagerForVfc).prepareForShutdown();
283         inOrder.verify(jobManagerForSo).prepareForShutdown();
284         inOrder.verify(selfRegistrationManagerForVfc).deRegister();
285         verify(logger).info("Self de-registration started");
286         verify(logger).info("Self de-registration finished");
287         // this forces the event to be fired after the servlet is down (prevents refactor)
288         assertTrue(ContextClosedEvent.class.isAssignableFrom(event.getClass()));
289     }
290
291     /**
292      * Assert that the self de-registration process is started after the servlet has been ramped down
293      */
294     @Test
295     public void testUnRegistrationIsCalledAfterComponentIsUpForSo() throws Exception {
296         //given
297         ContextClosedEvent event = Mockito.mock(ContextClosedEvent.class);
298         useSo(event);
299         //when
300         selfUnregistrationTriggerer.onApplicationEvent(event);
301         //verify
302         InOrder inOrder = Mockito.inOrder(jobManagerForVfc, jobManagerForSo, selfRegistrationManagerForSo);
303         inOrder.verify(jobManagerForVfc).prepareForShutdown();
304         inOrder.verify(jobManagerForSo).prepareForShutdown();
305         inOrder.verify(selfRegistrationManagerForSo).deRegister();
306         verify(logger).info("Self de-registration started");
307         verify(logger).info("Self de-registration finished");
308         // this forces the event to be fired after the servlet is down (prevents refactor)
309         assertTrue(ContextClosedEvent.class.isAssignableFrom(event.getClass()));
310     }
311
312     /**
313      * Assert that the self registration process is started after the servlet is up and is able to answer REST requests.
314      */
315     @Test
316     public void testPreparingForShutdownDoesNotStartRegistration() throws Exception {
317         //given
318         ApplicationReadyEvent event = Mockito.mock(ApplicationReadyEvent.class);
319         when(jobManagerForVfc.isPreparingForShutDown()).thenReturn(true);
320         //when
321         selfRegistrationTriggerer.onApplicationEvent(event);
322         //verify
323         verify(selfRegistrationManagerForVfc, never()).register();
324     }
325
326     /**
327      * Failures in registration is logged and propagated
328      */
329     @Test
330     @SuppressWarnings("squid:S2925") //the execution is asynchronous no other way to wait
331
332     public void failedFirstRegistration() {
333         //given
334         Set<RuntimeException> expectedException = new HashSet<>();
335         doAnswer(new Answer() {
336             @Override
337             public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
338                 if (expectedException.size() == 0) {
339                     RuntimeException e = new RuntimeException();
340                     expectedException.add(e);
341                     throw e;
342                 }
343                 return null;
344             }
345         }).when(selfRegistrationManagerForVfc).register();
346         ApplicationReadyEvent event = Mockito.mock(ApplicationReadyEvent.class);
347         useVfc(event);
348         //when
349         selfRegistrationTriggerer.onApplicationEvent(event);
350         //verify
351         //wait for the registration to succeed
352         boolean success = false;
353         while (!success) {
354             try {
355                 verify(logger).info("Self registration finished");
356                 success = true;
357                 Thread.sleep(10);
358             } catch (Exception e2) {
359             } catch (Error e) {
360             }
361         }
362         verify(logger, times(2)).info("Self registration started");
363         verify(logger).error("Self registration failed", expectedException.iterator().next());
364     }
365
366     /**
367      * Failures in de-registration is logged and propagated
368      */
369     @Test
370     public void failedDeRegistration() {
371         //given
372         RuntimeException expectedException = new RuntimeException();
373         Mockito.doThrow(expectedException).when(selfRegistrationManagerForVfc).deRegister();
374         ContextClosedEvent event = Mockito.mock(ContextClosedEvent.class);
375         useVfc(event);
376         //when
377         try {
378             selfUnregistrationTriggerer.onApplicationEvent(event);
379             //verify
380             fail();
381         } catch (RuntimeException e) {
382             assertEquals(e, expectedException);
383         }
384         verify(logger).error("Self de-registration failed", expectedException);
385     }
386
387     /**
388      * Spring will instantiate using reflection
389      */
390     @Test
391     public void testUseStaticWay() throws Exception {
392         //verify
393         //the constructor is public even if has no private fields
394         new NokiaSvnfmApplication();
395     }
396
397     /**
398      * test spring application bootstrapping
399      */
400     @Test
401     public void useless() throws Exception {
402         String[] args = new String[0];
403         SpringApplication springApplicaiton = Mockito.mock(SpringApplication.class);
404         SystemFunctions systemFunctions = SystemFunctions.systemFunctions();
405         when(this.systemFunctions.newSpringApplication(NokiaSvnfmApplication.class)).thenReturn(springApplicaiton);
406         //when
407         NokiaSvnfmApplication.main(args);
408         //verify
409         verify(springApplicaiton).run(args);
410     }
411 }