1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.enforcer.rules;
20
21 import org.apache.maven.enforcer.rule.api.EnforcerLogger;
22 import org.apache.maven.enforcer.rule.api.EnforcerRuleException;
23 import org.apache.maven.enforcer.rules.utils.ExpressionEvaluator;
24 import org.apache.maven.plugin.MojoExecution;
25 import org.apache.maven.plugin.descriptor.MojoDescriptor;
26 import org.codehaus.plexus.util.xml.Xpp3Dom;
27 import org.junit.jupiter.api.BeforeEach;
28 import org.junit.jupiter.api.Test;
29 import org.junit.jupiter.api.extension.ExtendWith;
30 import org.mockito.InjectMocks;
31 import org.mockito.Mock;
32 import org.mockito.junit.jupiter.MockitoExtension;
33
34 import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
35 import static org.junit.jupiter.api.Assertions.assertEquals;
36 import static org.junit.jupiter.api.Assertions.assertNotNull;
37 import static org.mockito.ArgumentMatchers.any;
38 import static org.mockito.Mockito.when;
39
40 @ExtendWith(MockitoExtension.class)
41 class TestExternalRules {
42
43 @Mock
44 private MojoExecution mojoExecution;
45
46 @Mock
47 private ExpressionEvaluator evaluator;
48
49 @Mock
50 private EnforcerLogger logger;
51
52 @InjectMocks
53 private ExternalRules rule;
54
55 @BeforeEach
56 void setup() {
57 rule.setLog(logger);
58 }
59
60 @Test
61 void shouldFailIfNoLocationIsSet() {
62 assertThatExceptionOfType(EnforcerRuleException.class)
63 .isThrownBy(() -> rule.getRulesConfig())
64 .withMessage("No location provided");
65 }
66
67 @Test
68 void shouldFailIfClasspathLocationIsNotFound() {
69
70 MojoDescriptor mojoDescriptor = new MojoDescriptor();
71 mojoDescriptor.setRealm(EnforcerTestUtils.getTestClassRealm());
72 when(mojoExecution.getMojoDescriptor()).thenReturn(mojoDescriptor);
73 rule.setLocation("classpath:foo");
74
75 assertThatExceptionOfType(EnforcerRuleException.class)
76 .isThrownBy(() -> rule.getRulesConfig())
77 .withMessage("Location 'foo' not found in classpath");
78 }
79
80 @Test
81 void shouldFailIfFileLocationIsNotFound() {
82 when(evaluator.alignToBaseDirectory(any())).thenAnswer(i -> i.getArgument(0));
83
84 rule.setLocation("blah.xml");
85 assertThatExceptionOfType(EnforcerRuleException.class)
86 .isThrownBy(() -> rule.getRulesConfig())
87 .withMessageMatching("Could not read descriptor in .*blah.xml");
88 }
89
90 @Test
91 void shouldLoadRulesFromClassPath() throws EnforcerRuleException {
92 MojoDescriptor mojoDescriptor = new MojoDescriptor();
93 mojoDescriptor.setRealm(EnforcerTestUtils.getTestClassRealm());
94 when(mojoExecution.getMojoDescriptor()).thenReturn(mojoDescriptor);
95 rule.setLocation("classpath:enforcer-rules/pass.xml");
96
97 Xpp3Dom rulesConfig = rule.getRulesConfig();
98 assertNotNull(rulesConfig);
99 assertEquals(2, rulesConfig.getChildCount());
100 }
101 }