View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  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,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.plugins.enforcer.internal;
20  
21  import javax.inject.Provider;
22  
23  import java.util.List;
24  import java.util.Properties;
25  
26  import org.apache.maven.enforcer.rule.api.EnforcerLevel;
27  import org.apache.maven.enforcer.rule.api.EnforcerRuleBase;
28  import org.apache.maven.execution.MavenSession;
29  import org.apache.maven.plugin.MojoExecution;
30  import org.apache.maven.plugin.descriptor.MojoDescriptor;
31  import org.apache.maven.plugin.descriptor.PluginDescriptor;
32  import org.apache.maven.plugin.logging.Log;
33  import org.apache.maven.plugins.enforcer.TestRule1;
34  import org.apache.maven.plugins.enforcer.TestRule2;
35  import org.codehaus.plexus.PlexusContainer;
36  import org.codehaus.plexus.component.configurator.ComponentConfigurationException;
37  import org.codehaus.plexus.component.configurator.ComponentConfigurator;
38  import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
39  import org.codehaus.plexus.configuration.DefaultPlexusConfiguration;
40  import org.codehaus.plexus.configuration.PlexusConfiguration;
41  import org.junit.jupiter.api.BeforeEach;
42  import org.junit.jupiter.api.Test;
43  import org.junit.jupiter.api.extension.ExtendWith;
44  import org.mockito.ArgumentCaptor;
45  import org.mockito.Mock;
46  import org.mockito.Mockito;
47  import org.mockito.junit.jupiter.MockitoExtension;
48  
49  import static org.assertj.core.api.Assertions.assertThat;
50  import static org.assertj.core.api.Assertions.assertThatCode;
51  import static org.mockito.ArgumentMatchers.any;
52  import static org.mockito.ArgumentMatchers.anyString;
53  import static org.mockito.ArgumentMatchers.eq;
54  import static org.mockito.Mockito.doThrow;
55  import static org.mockito.Mockito.mock;
56  import static org.mockito.Mockito.verify;
57  import static org.mockito.Mockito.when;
58  
59  @ExtendWith(MockitoExtension.class)
60  class EnforcerRuleManagerTest {
61  
62      @Mock
63      private Provider<MavenSession> sessionProvider;
64  
65      @Mock
66      private Provider<MojoExecution> mojoExecutionProvider;
67  
68      @Mock
69      private ComponentConfigurator componentConfigurator;
70  
71      @Mock
72      private PlexusContainer plexusContainer;
73  
74      @Mock
75      private Log mojoLog;
76  
77      private EnforcerRuleManager enforcerRuleManager;
78  
79      @BeforeEach
80      void setup() {
81          enforcerRuleManager =
82                  new EnforcerRuleManager(sessionProvider, mojoExecutionProvider, componentConfigurator, plexusContainer);
83      }
84  
85      void setupMocks() {
86          setupMocks(false);
87      }
88  
89      void setupMocks(Boolean hasComponent) {
90          MojoExecution mojoExecution = mock(MojoExecution.class);
91          when(mojoExecutionProvider.get()).thenReturn(mojoExecution);
92  
93          MojoDescriptor mojoDescriptor = mock(MojoDescriptor.class);
94          when(mojoExecution.getMojoDescriptor()).thenReturn(mojoDescriptor);
95  
96          when(mojoDescriptor.getPluginDescriptor()).thenReturn(mock(PluginDescriptor.class));
97  
98          MavenSession mavenSession = mock(MavenSession.class);
99          when(mavenSession.getSystemProperties()).thenReturn(new Properties());
100         when(mavenSession.getUserProperties()).thenReturn(new Properties());
101         when(sessionProvider.get()).thenReturn(mavenSession);
102 
103         when(plexusContainer.hasComponent(any(Class.class), anyString())).thenReturn(hasComponent);
104     }
105 
106     @Test
107     void nullConfigReturnEmptyRules() {
108 
109         List<EnforcerRuleDesc> rules = enforcerRuleManager.createRules(null, mojoLog);
110 
111         assertThat(rules).isEmpty();
112     }
113 
114     @Test
115     void emptyConfigReturnEmptyRules() {
116 
117         List<EnforcerRuleDesc> rules =
118                 enforcerRuleManager.createRules(new DefaultPlexusConfiguration("rules"), mojoLog);
119 
120         assertThat(rules).isEmpty();
121     }
122 
123     @Test
124     void unKnownRuleThrowException() throws Exception {
125 
126         setupMocks();
127 
128         PlexusConfiguration configuration = new DefaultPlexusConfiguration("rules").addChild("UnKnowRule", null);
129 
130         assertThatCode(() -> enforcerRuleManager.createRules(configuration, mojoLog))
131                 .isInstanceOf(EnforcerRuleManagerException.class)
132                 .hasMessage(
133                         "Failed to create enforcer rules with name: unKnowRule or for class: org.apache.maven.plugins.enforcer.UnKnowRule")
134                 .hasCauseInstanceOf(ClassNotFoundException.class);
135     }
136 
137     @Test
138     void invalidConfigurationThrowException() throws Exception {
139 
140         setupMocks();
141 
142         PlexusConfiguration ruleConfig =
143                 new DefaultPlexusConfiguration("testRule1").addChild("message", "messageValue");
144         PlexusConfiguration configuration = new DefaultPlexusConfiguration("rules");
145         configuration.addChild(ruleConfig);
146 
147         doThrow(ComponentConfigurationException.class)
148                 .when(componentConfigurator)
149                 .configureComponent(any(), any(), any(), any());
150 
151         assertThatCode(() -> enforcerRuleManager.createRules(configuration, mojoLog))
152                 .isInstanceOf(EnforcerRuleManagerException.class)
153                 .hasCauseInstanceOf(ComponentConfigurationException.class);
154     }
155 
156     @Test
157     void createSimpleRule() throws Exception {
158 
159         setupMocks();
160 
161         PlexusConfiguration configuration = new DefaultPlexusConfiguration("rules")
162                 .addChild("TestRule1", null)
163                 .addChild("testRule2", null);
164 
165         List<EnforcerRuleDesc> rules = enforcerRuleManager.createRules(configuration, mojoLog);
166 
167         assertThat(rules)
168                 .hasSize(2)
169                 .map(EnforcerRuleDesc::getRule)
170                 .hasExactlyElementsOfTypes(TestRule1.class, TestRule2.class);
171 
172         assertThat(rules).hasSize(2).map(EnforcerRuleDesc::getName).containsExactly("testRule1", "testRule2");
173     }
174 
175     @Test
176     void createSimpleRuleFromComponentAndClasses() throws Exception {
177 
178         setupMocks();
179 
180         when(plexusContainer.hasComponent(any(Class.class), eq("testRule1"))).thenReturn(true);
181         Mockito.doReturn(new TestRule1()).when(plexusContainer).lookup(EnforcerRuleBase.class, "testRule1");
182 
183         PlexusConfiguration configuration = new DefaultPlexusConfiguration("rules")
184                 .addChild("TestRule1", null)
185                 .addChild("testRule2", null);
186 
187         List<EnforcerRuleDesc> rules = enforcerRuleManager.createRules(configuration, mojoLog);
188 
189         assertThat(rules)
190                 .hasSize(2)
191                 .map(EnforcerRuleDesc::getRule)
192                 .hasExactlyElementsOfTypes(TestRule1.class, TestRule2.class);
193 
194         assertThat(rules).hasSize(2).map(EnforcerRuleDesc::getName).containsExactly("testRule1", "testRule2");
195     }
196 
197     @Test
198     void shouldThrowExceptionFormComponentCreation() throws Exception {
199 
200         setupMocks(true);
201 
202         doThrow(ComponentLookupException.class).when(plexusContainer).lookup(any(Class.class), anyString());
203 
204         PlexusConfiguration configuration = new DefaultPlexusConfiguration("rules").addChild("TestRule1", null);
205 
206         assertThatCode(() -> enforcerRuleManager.createRules(configuration, mojoLog))
207                 .isInstanceOf(EnforcerRuleManagerException.class)
208                 .hasCauseInstanceOf(ComponentLookupException.class);
209     }
210 
211     @Test
212     void createRuleWithImplementation() throws Exception {
213 
214         setupMocks();
215 
216         PlexusConfiguration ruleConfig = new DefaultPlexusConfiguration("testRuleWithImp");
217         ruleConfig.setAttribute("implementation", TestRule1.class.getName());
218 
219         PlexusConfiguration configuration = new DefaultPlexusConfiguration("rules");
220         configuration.addChild(ruleConfig);
221 
222         List<EnforcerRuleDesc> rules = enforcerRuleManager.createRules(configuration, mojoLog);
223 
224         assertThat(rules).hasSize(1).map(EnforcerRuleDesc::getRule).hasExactlyElementsOfTypes(TestRule1.class);
225 
226         assertThat(rules).hasSize(1).map(EnforcerRuleDesc::getName).containsExactly("testRuleWithImp");
227     }
228 
229     @Test
230     void ruleShouldBeConfigured() throws Exception {
231 
232         setupMocks();
233 
234         PlexusConfiguration ruleConfig =
235                 new DefaultPlexusConfiguration("testRule1").addChild("message", "messageValue");
236         PlexusConfiguration configuration = new DefaultPlexusConfiguration("rules");
237         configuration.addChild(ruleConfig);
238 
239         List<EnforcerRuleDesc> rules = enforcerRuleManager.createRules(configuration, mock(Log.class));
240         assertThat(rules).hasSize(1);
241 
242         ArgumentCaptor<EnforcerRuleBase> ruleCaptor = ArgumentCaptor.forClass(EnforcerRuleBase.class);
243         ArgumentCaptor<PlexusConfiguration> configurationCaptor = ArgumentCaptor.forClass(PlexusConfiguration.class);
244 
245         verify(componentConfigurator)
246                 .configureComponent(ruleCaptor.capture(), configurationCaptor.capture(), any(), any());
247 
248         assertThat(ruleCaptor.getValue()).isInstanceOf(TestRule1.class);
249         assertThat(configurationCaptor.getValue()).isSameAs(ruleConfig);
250     }
251 
252     @Test
253     void ruleLevelShouldBeDisoveredFromConfigured() throws Exception {
254 
255         setupMocks();
256 
257         PlexusConfiguration ruleConfig = new DefaultPlexusConfiguration("testRule1").addChild("level", "WARN");
258         PlexusConfiguration configuration = new DefaultPlexusConfiguration("rules");
259         configuration.addChild(ruleConfig);
260 
261         List<EnforcerRuleDesc> rules = enforcerRuleManager.createRules(configuration, mock(Log.class));
262         assertThat(rules).hasSize(1);
263         assertThat(rules.get(0).getLevel()).isEqualTo(EnforcerLevel.ERROR);
264     }
265 }