Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding more tests #613

Merged
merged 4 commits into from
Jan 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 0 additions & 19 deletions src/main/java/org/jenkinsci/plugins/prometheus/BaseCollector.java

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import java.util.List;
import java.util.stream.Collectors;

public class CodeCoverageCollector extends BaseCollector {
public class CodeCoverageCollector extends Collector {

private static final Logger LOGGER = LoggerFactory.getLogger(CodeCoverageCollector.class);

Expand All @@ -44,9 +44,6 @@ public List<MetricFamilySamples> collect() {
}

private List<MetricFamilySamples> collectCoverageMetricForJob(Job<?,?> job) {
if (job == null) {
return Collections.emptyList();
}

Run<?,?> lastBuild = job.getLastBuild();
if (lastBuild == null || lastBuild.isBuilding()) {
Expand Down
10 changes: 0 additions & 10 deletions src/main/java/org/jenkinsci/plugins/prometheus/util/Runs.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,6 @@ public static boolean includeBuildInMetrics(Run build) {
return include;
}

public static String getResultText(Run run) {
if (run != null) {
Result result = run.getResult();
if (result != null) {
return result.toString();
}
}
return null;
}

public static Map<String, Object> getBuildParameters(Run build) {
List<ParametersAction> actions = build.getActions(ParametersAction.class);
Map<String, Object> answer = new HashMap<>();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
package org.jenkinsci.plugins.prometheus;

import hudson.Plugin;
import hudson.model.Item;
import hudson.model.Job;
import hudson.model.Run;
import io.jenkins.plugins.coverage.metrics.steps.CoverageBuildAction;
import io.prometheus.client.Collector;
import jenkins.model.Jenkins;
import org.jenkinsci.plugins.prometheus.config.PrometheusConfiguration;
import org.jenkinsci.plugins.prometheus.util.ConfigurationUtils;
import org.jenkinsci.plugins.prometheus.util.Jobs;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;

import java.util.List;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;


@ExtendWith(MockitoExtension.class)
class CodeCoverageCollectorTest {

@Mock
private Jenkins jenkins;

@Mock
private PrometheusConfiguration config;

@Test
void shouldNotProduceMetricsWhenNoCoveragePluginDetected() {
try (MockedStatic<Jenkins> jenkinsStatic = mockStatic(Jenkins.class)) {
jenkinsStatic.when(Jenkins::get).thenReturn(jenkins);
when(jenkins.getPlugin("coverage")).thenReturn(null);
CodeCoverageCollector sut = new CodeCoverageCollector();

List<Collector.MetricFamilySamples> collect = sut.collect();
assertEquals(0, collect.size());
}
}

@Test
void shouldNotProduceMetricsWhenItIsNotConfigured() {
try (
MockedStatic<Jenkins> jenkinsStatic = mockStatic(Jenkins.class);
MockedStatic<PrometheusConfiguration> configurationStatic = mockStatic(PrometheusConfiguration.class)
) {
jenkinsStatic.when(Jenkins::get).thenReturn(jenkins);
configurationStatic.when(PrometheusConfiguration::get).thenReturn(config);
when(jenkins.getPlugin("coverage")).thenReturn(new Plugin.DummyImpl());
when(config.isCollectCodeCoverage()).thenReturn(false);

CodeCoverageCollector sut = new CodeCoverageCollector();

List<Collector.MetricFamilySamples> collect = sut.collect();
assertEquals(0, collect.size());
}
}

@Test
void shouldNotProduceMetricsWhenJobIsBuilding() {
try (
MockedStatic<Jenkins> jenkinsStatic = mockStatic(Jenkins.class);
MockedStatic<PrometheusConfiguration> configurationStatic = mockStatic(PrometheusConfiguration.class);
) {
jenkinsStatic.when(Jenkins::get).thenReturn(jenkins);
configurationStatic.when(PrometheusConfiguration::get).thenReturn(config);
Job jobUnderTest = mock(Job.class);
Run lastBuild = mock(Run.class);
when(lastBuild.isBuilding()).thenReturn(true);
when(jobUnderTest.getLastBuild()).thenReturn(lastBuild);
when(jenkins.getAllItems(Job.class)).thenReturn(List.of(jobUnderTest));
when(jenkins.getPlugin("coverage")).thenReturn(new Plugin.DummyImpl());
when(config.isCollectCodeCoverage()).thenReturn(true);

CodeCoverageCollector sut = new CodeCoverageCollector();

List<Collector.MetricFamilySamples> collect = sut.collect();
assertEquals(0, collect.size());
}
}

@Test
void shouldNotProduceMetricsWhenJobHasNoCoverageBuildAction() {
try (
MockedStatic<Jenkins> jenkinsStatic = mockStatic(Jenkins.class);
MockedStatic<PrometheusConfiguration> configurationStatic = mockStatic(PrometheusConfiguration.class);
) {
jenkinsStatic.when(Jenkins::get).thenReturn(jenkins);
configurationStatic.when(PrometheusConfiguration::get).thenReturn(config);
Job jobUnderTest = mock(Job.class);
Run lastBuild = mock(Run.class);
when(lastBuild.isBuilding()).thenReturn(false);
when(jobUnderTest.getLastBuild()).thenReturn(lastBuild);
when(jenkins.getAllItems(Job.class)).thenReturn(List.of(jobUnderTest));
when(jenkins.getPlugin("coverage")).thenReturn(new Plugin.DummyImpl());
when(config.isCollectCodeCoverage()).thenReturn(true);

CodeCoverageCollector sut = new CodeCoverageCollector();

List<Collector.MetricFamilySamples> collect = sut.collect();
assertEquals(0, collect.size());
}
}

@Test
void shouldProduceMetricsWhenJobHasCoverageBuildAction() {
try (
MockedStatic<Jenkins> jenkinsStatic = mockStatic(Jenkins.class);
MockedStatic<PrometheusConfiguration> configurationStatic = mockStatic(PrometheusConfiguration.class);
MockedStatic<ConfigurationUtils> configurationUtils = mockStatic(ConfigurationUtils.class);
) {
configurationUtils.when(ConfigurationUtils::getNamespace).thenReturn("foo");
configurationUtils.when(ConfigurationUtils::getSubSystem).thenReturn("bar");
jenkinsStatic.when(Jenkins::get).thenReturn(jenkins);
configurationStatic.when(PrometheusConfiguration::get).thenReturn(config);
Job jobUnderTest = mock(Job.class);
Run lastBuild = mock(Run.class);
when(lastBuild.isBuilding()).thenReturn(false);
when(jobUnderTest.getLastBuild()).thenReturn(lastBuild);
CoverageBuildAction action = mock(CoverageBuildAction.class);
when(lastBuild.getAction(CoverageBuildAction.class)).thenReturn(action);
when(jenkins.getAllItems(Job.class)).thenReturn(List.of(jobUnderTest));
when(jenkins.getPlugin("coverage")).thenReturn(new Plugin.DummyImpl());
when(config.getJobAttributeName()).thenReturn("jenkins_job");
when(config.isCollectCodeCoverage()).thenReturn(true);

CodeCoverageCollector sut = new CodeCoverageCollector();

List<Collector.MetricFamilySamples> collect = sut.collect();
assertEquals(12, collect.size(), "12 metrics should have been collected");
}
}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
package org.jenkinsci.plugins.prometheus.service;

import hudson.Plugin;
import io.prometheus.client.Collector;
import jenkins.model.Jenkins;
import org.jenkinsci.plugins.prometheus.CodeCoverageCollector;
import org.jenkinsci.plugins.prometheus.config.PrometheusConfiguration;
import org.junit.jupiter.api.Test;
import org.jvnet.hudson.test.Issue;
import org.mockito.MockedStatic;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;


public class PrometheusAsyncWorkerTest {
Expand All @@ -25,6 +35,26 @@ public void shouldCollectMetrics() {
assertEquals("1", actual);

}
@Test
public void testConvertSecondsToMillis() {
try (MockedStatic<PrometheusConfiguration> configurationStatic = mockStatic(PrometheusConfiguration.class)) {

PrometheusConfiguration config = mock(PrometheusConfiguration.class);
configurationStatic.when(PrometheusConfiguration::get).thenReturn(config);
when(config.getCollectingMetricsPeriodInSeconds()).thenReturn(12345L);
PrometheusAsyncWorker sut = new PrometheusAsyncWorker();
long recurrencePeriod = sut.getRecurrencePeriod();
assertEquals(12345000L, recurrencePeriod);
}
}

@Test
@Issue("#157")
public void ensureLoggingLevel() {
PrometheusAsyncWorker sut = new PrometheusAsyncWorker();
Level level = sut.getNormalLoggingLevel();
assertEquals(Level.FINE, level);
}

private static class TestPrometheusMetrics implements PrometheusMetrics {
private final AtomicReference<String> cachedMetrics = new AtomicReference<>("");
Expand Down
114 changes: 114 additions & 0 deletions src/test/java/org/jenkinsci/plugins/prometheus/util/RunsTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package org.jenkinsci.plugins.prometheus.util;

import hudson.model.ParameterValue;
import hudson.model.ParametersAction;
import hudson.model.Result;
import hudson.model.Run;
import org.jenkinsci.plugins.prometheus.config.PrometheusConfiguration;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;

import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

@ExtendWith(MockitoExtension.class)
public class RunsTest {

@Mock
Run mockedRun;

@Test
void testIncludeBuildMetricsReturnsFalseIfRunIsBuilding() {
when(mockedRun.isBuilding()).thenReturn(true);

boolean include = Runs.includeBuildInMetrics(mockedRun);
assertFalse(include);
}

@Test
void testGetBuildParametersWontFailIfNoActionsAvailable() {
when(mockedRun.getActions(ParametersAction.class)).thenReturn(List.of());

Map<String, Object> parameters = Runs.getBuildParameters(mockedRun);
assertEquals(0, parameters.size());
}

@Test
void testGetBuildParametersWontFailIfParameterValueIsNull() {
ParameterValue parameterValue = mock(ParameterValue.class);
when(parameterValue.getName()).thenReturn("failBuildOnError");
when(parameterValue.getValue()).thenReturn(true);
ParametersAction action = new ParametersAction(parameterValue);
when(mockedRun.getActions(ParametersAction.class)).thenReturn(List.of(action));

Map<String, Object> parameters = Runs.getBuildParameters(mockedRun);
assertEquals(1, parameters.size());


assertEquals(true, parameters.get("failBuildOnError"));
}

@ParameterizedTest
@MethodSource("provideBuildResults")
void testIncludeBuildMetrics(Result result) {
when(mockedRun.isBuilding()).thenReturn(false);
when(mockedRun.getResult()).thenReturn(result);
try (MockedStatic<PrometheusConfiguration> prometheusConfigurationStatic = mockStatic(PrometheusConfiguration.class)) {


PrometheusConfiguration configuration = getPrometheusConfigurationForTest(result, true);
prometheusConfigurationStatic.when(PrometheusConfiguration::get).thenReturn(configuration);

boolean include = Runs.includeBuildInMetrics(mockedRun);
assertTrue(include, "Run is aborted and Prometheus is configured to return results for these builds");

configuration = getPrometheusConfigurationForTest(result, false);
prometheusConfigurationStatic.when(PrometheusConfiguration::get).thenReturn(configuration);

include = Runs.includeBuildInMetrics(mockedRun);
assertFalse(include, "Run is aborted and Prometheus is not configured to return results for these builds");
}
}



private static Stream<Arguments> provideBuildResults() {
return Stream.of(
Arguments.of(Result.ABORTED),
Arguments.of(Result.FAILURE),
Arguments.of(Result.NOT_BUILT),
Arguments.of(Result.SUCCESS),
Arguments.of(Result.UNSTABLE)
);
}

private PrometheusConfiguration getPrometheusConfigurationForTest(Result result, boolean prometheusPluginConfiguredToReturn) {
PrometheusConfiguration mockedPrometheusConfiguration = mock(PrometheusConfiguration.class);
if (Result.ABORTED.equals(result)) {
when(mockedPrometheusConfiguration.isCountAbortedBuilds()).thenReturn(prometheusPluginConfiguredToReturn);
}
if (Result.FAILURE.equals(result)) {
when(mockedPrometheusConfiguration.isCountFailedBuilds()).thenReturn(prometheusPluginConfiguredToReturn);
}
if (Result.NOT_BUILT.equals(result)) {
when(mockedPrometheusConfiguration.isCountNotBuiltBuilds()).thenReturn(prometheusPluginConfiguredToReturn);
}
if (Result.SUCCESS.equals(result)) {
when(mockedPrometheusConfiguration.isCountSuccessfulBuilds()).thenReturn(prometheusPluginConfiguredToReturn);
}
if (Result.UNSTABLE.equals(result)) {
when(mockedPrometheusConfiguration.isCountUnstableBuilds()).thenReturn(prometheusPluginConfiguredToReturn);
}
return mockedPrometheusConfiguration;
}
}
Loading