Fix component startup
[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     private void useVfc(ApplicationReadyEvent event) {
100         ConfigurableApplicationContext context = Mockito.mock(ConfigurableApplicationContext.class);
101         ConfigurableEnvironment environment = Mockito.mock(ConfigurableEnvironment.class);
102         when(context.getEnvironment()).thenReturn(environment);
103         when(event.getApplicationContext()).thenReturn(context);
104         when(environment.getActiveProfiles()).thenReturn(new String[]{});
105     }
106
107     private void useVfc(ContextClosedEvent event) {
108         ApplicationContext context = Mockito.mock(ApplicationContext.class);
109         when(context.getEnvironment()).thenReturn(environment);
110         when(event.getApplicationContext()).thenReturn(context);
111         when(environment.getActiveProfiles()).thenReturn(new String[]{});
112     }
113
114     /**
115      * Assert that the self de-registration process is started after the servlet has been ramped down
116      */
117     @Test
118     public void testUnRegistrationIsCalledAfterComponentIsUp() throws Exception {
119         //given
120         ContextClosedEvent event = Mockito.mock(ContextClosedEvent.class);
121         useVfc(event);
122         //when
123         selfUnregistrationTriggerer.onApplicationEvent(event);
124         //verify
125         InOrder inOrder = Mockito.inOrder(jobManagerForVfc, jobManagerForSo, selfRegistrationManagerForVfc);
126         inOrder.verify(jobManagerForVfc).prepareForShutdown();
127         inOrder.verify(jobManagerForSo).prepareForShutdown();
128         inOrder.verify(selfRegistrationManagerForVfc).deRegister();
129         verify(logger).info("Self de-registration started");
130         verify(logger).info("Self de-registration finished");
131         // this forces the event to be fired after the servlet is down (prevents refactor)
132         assertTrue(ContextClosedEvent.class.isAssignableFrom(event.getClass()));
133     }
134
135     /**
136      * Assert that the self registration process is started after the servlet is up and is able to answer REST requests.
137      */
138     @Test
139     public void testPreparingForShutdownDoesNotStartRegistration() throws Exception {
140         //given
141         ApplicationReadyEvent event = Mockito.mock(ApplicationReadyEvent.class);
142         when(jobManagerForVfc.isPreparingForShutDown()).thenReturn(true);
143         //when
144         selfRegistrationTriggerer.onApplicationEvent(event);
145         //verify
146         verify(selfRegistrationManagerForVfc, never()).register();
147     }
148
149     /**
150      * Failures in registration is logged and propagated
151      */
152     @Test
153     @SuppressWarnings("squid:S2925") //the execution is asynchronous no other way to wait
154     public void failedFirstRegistration() {
155         //given
156
157         Set<RuntimeException> expectedException = new HashSet<>();
158         doAnswer(new Answer() {
159             @Override
160             public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
161                 if (expectedException.size() == 0) {
162                     RuntimeException e = new RuntimeException();
163                     expectedException.add(e);
164                     throw e;
165                 }
166                 return null;
167             }
168         }).when(selfRegistrationManagerForVfc).register();
169         ApplicationReadyEvent event = Mockito.mock(ApplicationReadyEvent.class);
170         useVfc(event);
171         //when
172         selfRegistrationTriggerer.onApplicationEvent(event);
173         //verify
174         //wait for the registration to succeed
175         boolean success = false;
176         while (!success) {
177             try {
178                 verify(logger).info("Self registration finished");
179                 success = true;
180                 Thread.sleep(10);
181             } catch (Exception e2) {
182             } catch (Error e) {
183             }
184         }
185         verify(logger, times(2)).info("Self registration started");
186         verify(logger).error("Self registration failed", expectedException.iterator().next());
187     }
188
189     /**
190      * Failures in de-registration is logged and propagated
191      */
192     @Test
193     public void failedDeRegistration() {
194         //given
195         RuntimeException expectedException = new RuntimeException();
196         Mockito.doThrow(expectedException).when(selfRegistrationManagerForVfc).deRegister();
197         ContextClosedEvent event = Mockito.mock(ContextClosedEvent.class);
198         useVfc(event);
199         //when
200         try {
201             selfUnregistrationTriggerer.onApplicationEvent(event);
202             //verify
203             fail();
204         } catch (RuntimeException e) {
205             assertEquals(e, expectedException);
206         }
207         verify(logger).error("Self de-registration failed", expectedException);
208     }
209
210     /**
211      * Spring will instantiate using reflection
212      */
213     @Test
214     public void testUseStaticWay() throws Exception {
215         //verify
216         //the constructor is public even if has no private fields
217         new NokiaSvnfmApplication();
218     }
219
220     /**
221      * test spring application bootstrapping
222      */
223     @Test
224     public void useless() throws Exception {
225         String[] args = new String[0];
226         SpringApplication springApplicaiton = Mockito.mock(SpringApplication.class);
227         SystemFunctions systemFunctions = SystemFunctions.systemFunctions();
228         when(this.systemFunctions.newSpringApplication(NokiaSvnfmApplication.class)).thenReturn(springApplicaiton);
229         //when
230         NokiaSvnfmApplication.main(args);
231         //verify
232         verify(springApplicaiton).run(args);
233     }
234 }