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