Skip to content

Commit 573a858

Browse files
authored
Improve plugin unit tests (#175)
* Add test for getTarget * Fix typo in method name * Add basic unit test for JUnitPointGenerator * Add test to test SonarQube hasReport method * Add unit test to check if results are found from build log
1 parent dbe56f4 commit 573a858

File tree

8 files changed

+299
-25
lines changed

8 files changed

+299
-25
lines changed

doc/available_metrics.md

+18-18
Original file line numberDiff line numberDiff line change
@@ -69,27 +69,27 @@ Tags specific for this measurement:
6969
In order to publish data for this measurement, your job needs to set an environment variable
7070
`LOG_JUNIT_RESULTS` to `true`.
7171

72-
| Metric | Type | Description | Introduced in |
73-
| --- | --- | --- | --- |
74-
| suite_name | string | Testsuite name | |
75-
| test_name | string | Test function name | Changed in 3.0 |
76-
| test_full_class_name | string | Test fully-qualified class name (`pacakge.ClassName`) | 3.0 |
77-
| pipeline_step | string | Pipeline steps, separated by ` / ` | 3.0 |
78-
| test_status | string | PASSED, SKIPPED, FAILED, FIXED, REGRESSION | |
79-
| test_status_ordinal | integer | 0-4 in order of test_status | |
80-
| test_duration | float | test duration in seconds | |
81-
| test_duration | float | test duration in seconds | 3.1 |
82-
| test_count | long | Test counter; Useful for aggregations. | 3.1 |
72+
| Metric | Type | Description | Introduced in |
73+
|----------------------| --- | --- | --- |
74+
| suite_name | string | Testsuite name | |
75+
| test_name | string | Test function name | Changed in 3.0 |
76+
| test_class_full_name | string | Test fully-qualified class name (`pacakge.ClassName`) | 3.0 |
77+
| pipeline_step | string | Pipeline steps, separated by ` / ` | 3.0 |
78+
| test_status | string | PASSED, SKIPPED, FAILED, FIXED, REGRESSION | |
79+
| test_status_ordinal | integer | 0-4 in order of test_status | |
80+
| test_duration | float | test duration in seconds | |
81+
| test_duration | float | test duration in seconds | 3.1 |
82+
| test_count | long | Test counter; Useful for aggregations. | 3.1 |
8383

8484
Tags specific for this measurement:
8585

86-
| Tag | Description | Introduced in |
87-
| --- | --- | --- |
88-
| suite_name | Testsuite name | |
89-
| test_name | Test function name | Changed in 3.0 |
90-
| test_full_class_name | Test fully-qualified class name (`pacakge.ClassName`) | 3.0 |
91-
| pipeline_step | Pipeline steps, separated by ` / ` | 3.0 |
92-
| test_status | Test result | |
86+
| Tag | Description | Introduced in |
87+
|----------------------| --- | --- |
88+
| suite_name | Testsuite name | |
89+
| test_name | Test function name | Changed in 3.0 |
90+
| test_class_full_name | Test fully-qualified class name (`pacakge.ClassName`) | 3.0 |
91+
| pipeline_step | Pipeline steps, separated by ` / ` | 3.0 |
92+
| test_status | Test result | |
9393

9494
#### `sonarqube_data` (since 1.11)
9595

src/main/java/jenkinsci/plugins/influxdb/generators/SonarQubePointGenerator.java

+20-5
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,22 @@ public SonarQubePointGenerator(Run<?, ?> build, TaskListener listener,
113113
this.env = env;
114114
}
115115

116+
public String getProjectKey() {
117+
return projectKey;
118+
}
119+
120+
public String getSonarBuildURL() {
121+
return sonarBuildURL;
122+
}
123+
124+
public String getSonarBuildTaskIdUrl() {
125+
return sonarBuildTaskIdUrl;
126+
}
127+
128+
public String getSonarBuildTaskId() {
129+
return sonarBuildTaskId;
130+
}
131+
116132
/**
117133
* @return true, if environment variable LOG_SONAR_QUBE_RESULTS is set to true and SQ Reports exist
118134
*/
@@ -310,15 +326,14 @@ private String[] getSonarProjectFromBuildLog(Run<?, ?> build) throws IOException
310326
}
311327
match = p_qg_url_v4_8.matcher(line);
312328
if (match.matches()) {
313-
url = match.group(1);
314-
//Task already executed. No need to search for other lines
315-
break;
329+
url = match.group(1); // https://<url>/dashboard?id=<id>
330+
url = url.substring(0,url.lastIndexOf(('/'))); // strip '/dashboard?id=<id>'
331+
continue;
316332
}
317333
match = p_qg_url_timeout.matcher(line);
318334
if (match.matches()) {
319335
url = match.group(1);
320-
//Task already executed. No need to search for other lines
321-
break;
336+
continue;
322337
}
323338
match = p_analysis_url.matcher(line);
324339
if (match.matches()) {

src/test/java/jenkinsci/plugins/influxdb/InfluxDbPublisherTest.java

+12
Original file line numberDiff line numberDiff line change
@@ -68,4 +68,16 @@ public void testConfigRoundTripShouldPreserveSelectedTarget() throws Exception {
6868
InfluxDbPublisher after = project.getPublishersList().get(InfluxDbPublisher.class);
6969
j.assertEqualBeans(before, after, "selectedTarget");
7070
}
71+
72+
@Test
73+
public void testGetTargetShouldReturnFirstTargetWithNull() {
74+
InfluxDbGlobalConfig globalConfig = InfluxDbGlobalConfig.getInstance();
75+
76+
Target target1 = new Target();
77+
target1.setDescription("Target1");
78+
globalConfig.addTarget(target1);
79+
80+
InfluxDbPublisher publisher = new InfluxDbPublisher(null);
81+
assertEquals(target1, publisher.getTarget());
82+
}
7183
}

src/test/java/jenkinsci/plugins/influxdb/generators/JUnitPointGeneratorTest.java

+47-1
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,27 @@
11
package jenkinsci.plugins.influxdb.generators;
22

3+
import com.influxdb.client.write.Point;
34
import hudson.EnvVars;
45
import hudson.model.Job;
56
import hudson.model.Run;
67
import hudson.model.TaskListener;
8+
import hudson.tasks.junit.CaseResult;
9+
import hudson.tasks.junit.SuiteResult;
710
import hudson.tasks.test.AbstractTestResultAction;
11+
import jenkins.model.Jenkins;
812
import jenkinsci.plugins.influxdb.renderer.ProjectNameRenderer;
913
import org.apache.commons.lang.StringUtils;
1014
import org.junit.Assert;
1115
import org.junit.Before;
1216
import org.junit.Test;
1317
import org.mockito.Mockito;
1418

19+
import java.util.ArrayList;
20+
import java.util.Collections;
21+
import java.util.List;
22+
23+
import static org.junit.Assert.assertTrue;
24+
1525
public class JUnitPointGeneratorTest {
1626

1727
private static final String JOB_NAME = "master";
@@ -22,6 +32,7 @@ public class JUnitPointGeneratorTest {
2232
private TaskListener listener;
2333
private ProjectNameRenderer measurementRenderer;
2434

35+
private CaseResult caseResult;
2536
private long currTime;
2637

2738
@Before
@@ -30,10 +41,12 @@ public void before() {
3041
Job job = Mockito.mock(Job.class);
3142
listener = Mockito.mock(TaskListener.class);
3243
measurementRenderer = new ProjectNameRenderer(CUSTOM_PREFIX, null);
44+
caseResult = Mockito.mock(CaseResult.class);
3345

3446
Mockito.when(build.getNumber()).thenReturn(BUILD_NUMBER);
3547
Mockito.when(build.getParent()).thenReturn(job);
3648
Mockito.when(job.getName()).thenReturn(JOB_NAME);
49+
Mockito.when(job.getRelativeNameFrom(Mockito.nullable(Jenkins.class))).thenReturn("");
3750

3851
currTime = System.currentTimeMillis();
3952
}
@@ -46,7 +59,7 @@ public void hasReport_tests_exist_and_flag_is_true() {
4659
Mockito.when(build.getAction(AbstractTestResultAction.class)).thenReturn(Mockito.mock(AbstractTestResultAction.class));
4760

4861
JUnitPointGenerator junitGen = new JUnitPointGenerator(build, listener, measurementRenderer, currTime, StringUtils.EMPTY, CUSTOM_PREFIX, envVars);
49-
Assert.assertTrue(junitGen.hasReport());
62+
assertTrue(junitGen.hasReport());
5063
}
5164

5265
@Test
@@ -95,4 +108,37 @@ public void hasReport_no_tests_and_flag_is_missing() {
95108
JUnitPointGenerator junitGen = new JUnitPointGenerator(build, listener, measurementRenderer, currTime, StringUtils.EMPTY, CUSTOM_PREFIX, envVars);
96109
Assert.assertFalse(junitGen.hasReport());
97110
}
111+
112+
@Test
113+
public void measurement_successfully_generated() {
114+
CaseResult.Status status = Mockito.mock(CaseResult.Status.class);
115+
SuiteResult suiteResult = Mockito.mock(SuiteResult.class);
116+
Mockito.when(caseResult.getStatus()).thenReturn(status);
117+
List<CaseResult> passedTests = new ArrayList<>();
118+
passedTests.add(caseResult);
119+
AbstractTestResultAction testResultAction = Mockito.mock(AbstractTestResultAction.class);
120+
Mockito.when(testResultAction.getFailedTests()).thenReturn(Collections.emptyList());
121+
Mockito.when(testResultAction.getSkippedTests()).thenReturn(Collections.emptyList());
122+
Mockito.when(testResultAction.getPassedTests()).thenReturn(passedTests);
123+
Mockito.when(build.getAction(AbstractTestResultAction.class)).thenReturn(testResultAction);
124+
Mockito.when(caseResult.getSuiteResult()).thenReturn(suiteResult);
125+
126+
Mockito.when(caseResult.getSuiteResult().getName()).thenReturn("my_suite");
127+
Mockito.when(caseResult.getName()).thenReturn("my_test");
128+
Mockito.when(caseResult.getClassName()).thenReturn("my_class_name");
129+
Mockito.when(caseResult.getStatus().toString()).thenReturn("PASSED");
130+
Mockito.when(caseResult.getStatus().ordinal()).thenReturn(0);
131+
Mockito.when(caseResult.getDuration()).thenReturn(10.0f);
132+
133+
JUnitPointGenerator generator = new JUnitPointGenerator(build, listener, measurementRenderer, currTime, StringUtils.EMPTY, StringUtils.EMPTY, new EnvVars());
134+
Point[] points = generator.generate();
135+
String lineProtocol = points[0].toLineProtocol();
136+
137+
assertTrue(lineProtocol.contains("suite_name=\"my_suite\""));
138+
assertTrue(lineProtocol.contains("test_name=\"my_test\""));
139+
assertTrue(lineProtocol.contains("test_class_full_name=\"my_class_name\""));
140+
assertTrue(lineProtocol.contains("test_status=\"PASSED\""));
141+
assertTrue(lineProtocol.contains("test_status_ordinal=0"));
142+
assertTrue(lineProtocol.contains("test_duration=10.0"));
143+
}
98144
}

src/test/java/jenkinsci/plugins/influxdb/generators/JenkinsBasePointGeneratorTest.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ public void branch_present() {
129129
}
130130

131131
@Test
132-
public void brach_not_present() {
132+
public void branch_not_present() {
133133
Mockito.when(build.getExecutor()).thenReturn(null);
134134
JenkinsBasePointGenerator generator = new JenkinsBasePointGenerator(build, listener, measurementRenderer, currTime, StringUtils.EMPTY, StringUtils.EMPTY, CUSTOM_PREFIX, MEASUREMENT_NAME, mockedEnvVars);
135135
Point[] points = generator.generate();

src/test/java/jenkinsci/plugins/influxdb/generators/SonarQubePointGeneratorTest.java

+51
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,10 @@
1616
import static org.junit.Assert.*;
1717
import static org.mockito.ArgumentMatchers.any;
1818

19+
import java.io.BufferedReader;
20+
import java.io.File;
21+
import java.io.FileReader;
22+
import java.io.IOException;
1923
import java.util.List;
2024
import java.nio.file.Path;
2125
import java.nio.file.Paths;
@@ -44,6 +48,8 @@ public class SonarQubePointGeneratorTest {
4448
private static final String[] customReportPath = {"custom", "report", "path"};
4549
private static final String customReportName = "custom-report.txt";
4650

51+
private File resourceDirectory;
52+
4753
@BeforeClass
4854
public static void beforeClass() {
4955

@@ -86,6 +92,12 @@ public void before() {
8692
listener = Mockito.mock(TaskListener.class);
8793
measurementRenderer = new ProjectNameRenderer(CUSTOM_PREFIX, null);
8894

95+
try {
96+
resourceDirectory = new File(SonarQubePointGeneratorTest.class.getResource(".").toURI());
97+
} catch (Exception ignored) {
98+
resourceDirectory = null;
99+
}
100+
89101
Mockito.when(build.getNumber()).thenReturn(BUILD_NUMBER);
90102
Mockito.when(build.getParent()).thenReturn(job);
91103
Mockito.when(job.getName()).thenReturn(JOB_NAME);
@@ -216,4 +228,43 @@ public void getSonarCustomReportFilePath() {
216228
System.err.println("[InfluxDB Plugin Test] ERROR: Failed to find custom report file path - " + e.getMessage());
217229
}
218230
}
231+
232+
@Test
233+
public void hasReportFindsCorrectInformationFromReportFile() {
234+
EnvVars envVars = new EnvVars();
235+
envVars.put("SONARQUBE_BUILD_REPORT_NAME", "report-task.txt");
236+
envVars.put("WORKSPACE", resourceDirectory.getAbsolutePath());
237+
238+
SonarQubePointGenerator generator = new SonarQubePointGenerator(build, listener, measurementRenderer, currTime, StringUtils.EMPTY, StringUtils.EMPTY, envVars);
239+
boolean hasReport = generator.hasReport();
240+
241+
String id = "123EXAMPLE";
242+
String url = "http://sonarqube:9000";
243+
assertTrue(hasReport);
244+
assertEquals("InfluxDBPlugin",generator.getProjectKey());
245+
assertEquals(url,generator.getSonarBuildURL());
246+
assertEquals(id,generator.getSonarBuildTaskId());
247+
assertEquals(url + "/api/ce/task?id=" + id,generator.getSonarBuildTaskIdUrl());
248+
}
249+
250+
@Test
251+
public void hasReportFindsCorrectInformationFromBuildLogs() throws Exception {
252+
File directory = new File(resourceDirectory, "sonarqube");
253+
File file = new File(directory, "build-log.txt");
254+
BufferedReader reader = new BufferedReader(new FileReader(file));
255+
Mockito.when(build.getLogReader()).thenReturn(reader);
256+
EnvVars envVars = new EnvVars();
257+
envVars.put("WORKSPACE", "mikki hiiri");
258+
259+
SonarQubePointGenerator generator = new SonarQubePointGenerator(build, listener, measurementRenderer, currTime, StringUtils.EMPTY, StringUtils.EMPTY, envVars);
260+
boolean hasReport = generator.hasReport();
261+
262+
String id = "321EXAMPLE";
263+
String url = "http://sonarqube:9001";
264+
assertTrue(hasReport);
265+
assertEquals("InfluxDBPlugin-log",generator.getProjectKey());
266+
assertEquals(url,generator.getSonarBuildURL());
267+
assertEquals(id,generator.getSonarBuildTaskId());
268+
assertEquals(url + "/api/ce/task?id=" + id,generator.getSonarBuildTaskIdUrl());
269+
}
219270
}

0 commit comments

Comments
 (0)