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

Provide Hamcrest matchers as alternatives to built-in JenkinsRule run assertions #878

Merged
merged 3 commits into from
Nov 27, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
119 changes: 119 additions & 0 deletions src/main/java/jenkins/test/RunMatchers.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
/*
* The MIT License
*
* Copyright 2024 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package jenkins.test;

import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.model.Result;
import hudson.model.Run;
import java.io.IOException;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.jvnet.hudson.test.JenkinsRule;

/**
* Matchers for {@link Run} objects.
*/
public final class RunMatchers {
private RunMatchers() {}

/**
* Creates a matcher checking whether a build is successful.
*/
public static Matcher<Run<?,?>> isSuccessful() {
return new RunResultMatcher(Result.SUCCESS);
}

/**
* Creates a matcher checking whether a build has a specific outcome.
*/
public static Matcher<Run<?,?>> hasStatus(Result result) {
return new RunResultMatcher(result);
}

/**
* Creates a matcher checking whether build logs contain a specific message.
* @param message the expected message
*/
public static Matcher<Run<?,?>> logContains(String message) {
return new RunLogMatcher(message);
}

private static class RunResultMatcher extends TypeSafeMatcher<Run<?,?>> {
@NonNull
private final Result expectedResult;

public RunResultMatcher(@NonNull Result expectedResult) {
this.expectedResult = expectedResult;
}

@Override
public void describeTo(Description description) {
description.appendText("a build with result " + expectedResult);
}

@Override
protected boolean matchesSafely(Run run) {
return run.getResult() == expectedResult;
}

@Override
protected void describeMismatchSafely(Run<?, ?> item, Description mismatchDescription) {
mismatchDescription.appendText("was ").appendValue(item.getResult());
}
}

private static class RunLogMatcher extends TypeSafeMatcher<Run<?, ?>> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about waitForMessage? This has special behavior for a completed build; not sure if that can be carried over to Awaitility.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It has a fail-early mechanism in case a build is complete, but I don't see how to replicate that using Awaitibility and matchers.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess something like

await().until(b, completed());
assertThat(b, logContains("foo"));

would be equivalent to the current waitForMessage

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, because waitForMessage can be used to wait for a line in a running build.

I was just wondering if there was something in Awaitility that a matcher can use to indicate that not only does the condition not match now, we can be sure it will not match later. https://javadoc.io/static/org.awaitility/awaitility/4.2.2/org/awaitility/core/FailFastCondition.html maybe? No Javadoc 😢

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So something like

await().failFast(() -> !b.isLogUpdated()).until(() -> b, logContains("foo"));

?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, that forces the tricky logic to be put into the call site, and only works for a message which you expect to be printed in a running build. I was hoping for something that could be built into the harness that would provide the same functionality as waitForMessage but integrated into Awaitility: pass if the message appears; fail immediately if the build terminates without the message ever appearing.

@NonNull
private final String message;

private RunLogMatcher(@NonNull String message) {
this.message = message;
}

@Override
protected boolean matchesSafely(Run<?, ?> run) {
try {
return JenkinsRule.getLog(run).contains(message);
} catch (IOException x) {
return false;
}
}

@Override
protected void describeMismatchSafely(Run<?, ?> item, Description mismatchDescription) {
mismatchDescription.appendText("was \n");
try {
mismatchDescription.appendText(JenkinsRule.getLog(item));
} catch (IOException e) {
mismatchDescription.appendText("<unreadable>");
}
}

@Override
public void describeTo(Description description) {
description.appendText("log containing ").appendValue(message);
}
}
}
6 changes: 6 additions & 0 deletions src/main/java/org/jvnet/hudson/test/JenkinsRule.java
Original file line number Diff line number Diff line change
Expand Up @@ -1509,6 +1509,8 @@ public <C extends Cloud> C configRoundtrip(C cloud) throws Exception {

/**
* Asserts that the outcome of the build is a specific outcome.
* <p>
* Consider {@link jenkins.test.RunMatchers#hasStatus(Result)} as an alternative.
*/
public <R extends Run> R assertBuildStatus(Result status, R r) throws Exception {
if (status == r.getResult()) {
Expand Down Expand Up @@ -1583,13 +1585,17 @@ public FreeStyleBuild buildAndAssertSuccess(@NonNull FreeStyleProject job) throw

/**
* Asserts that the console output of the build contains the given substring.
* <p>
* Consider {@link jenkins.test.RunMatchers#logContains(String)} as an alternative.
*/
public void assertLogContains(String substring, Run run) throws IOException {
assertThat(getLog(run), containsString(substring));
}

/**
* Asserts that the console output of the build does not contain the given substring.
* <p>
* Consider {@link org.hamcrest.Matchers#not} and {@link jenkins.test.RunMatchers#logContains(String)} as an alternative.
*/
public void assertLogNotContains(String substring, Run run) throws IOException {
assertThat(getLog(run), not(containsString(substring)));
Expand Down
71 changes: 71 additions & 0 deletions src/test/java/jenkins/test/RunMatchersTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
* The MIT License
*
* Copyright 2024 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package jenkins.test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.not;
import static jenkins.test.RunMatchers.logContains;
import static jenkins.test.RunMatchers.hasStatus;
import static jenkins.test.RunMatchers.isSuccessful;

import hudson.Functions;
import hudson.model.Result;
import hudson.tasks.BatchFile;
import hudson.tasks.Shell;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.FailureBuilder;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.SleepBuilder;

public class RunMatchersTest {
@Rule
public JenkinsRule j = new JenkinsRule();

@Test
public void buildSuccessful() throws Exception {
var p = j.createFreeStyleProject();
p.getBuildersList().add(new SleepBuilder(1000));
var b = p.scheduleBuild2(0).waitForStart();
assertThat(j.waitForCompletion(b), isSuccessful());
jglick marked this conversation as resolved.
Show resolved Hide resolved
}

@Test
public void buildFailure() throws Exception {
var p = j.createFreeStyleProject();
p.getBuildersList().add(new FailureBuilder());
var b = p.scheduleBuild2(0).waitForStart();
assertThat(j.waitForCompletion(b), hasStatus(Result.FAILURE));
}

@Test
public void assertThatLogContains() throws Exception {
var p = j.createFreeStyleProject();
p.getBuildersList().add(Functions.isWindows() ? new BatchFile("echo hello") : new Shell("echo hello"));
var b = p.scheduleBuild2(0).get();
System.out.println(b.getDisplayName() + " completed");
assertThat(b, allOf(logContains("echo hello"), not(logContains("echo bye"))));
}
}
Loading