contexts() {
- return Arrays.asList("/jenkins", "");
- }
+ private JenkinsRule j;
- public ErrorPageTest(String context) {
- j.contextPath = context;
+ @BeforeEach
+ void setUp(JenkinsRule rule) throws Throwable {
+ j = rule;
+
+ j.contextPath = contextPath;
+ j.restart();
}
@Test
@Issue("JENKINS-71087")
- public void nice404ErrorPage() throws Exception {
+ void nice404ErrorPage() throws Exception {
try (JenkinsRule.WebClient wc = j.createWebClient()) {
Dispatcher.TRACE = false;
@@ -151,11 +154,11 @@ public class ErrorPageTest {
@Test
@Issue("JENKINS-71087")
- public void kindaNice404ErrorPageOnResourceDomain() throws Exception {
+ void kindaNice404ErrorPageOnResourceDomain() throws Exception {
final String resourceRoot;
{ // Setup stolen from ResourceDomainTest
URL root = j.getURL(); // which always will use "localhost", see JenkinsRule#getURL()
- Assert.assertTrue(root.toString().contains("localhost")); // to be safe
+ assertTrue(root.toString().contains("localhost")); // to be safe
resourceRoot = root.toString().replace("localhost", "127.0.0.1");
ResourceDomainConfiguration configuration = ExtensionList.lookupSingleton(ResourceDomainConfiguration.class);
diff --git a/test/src/test/java/jenkins/model/JenkinsBuildsAndWorkspacesDirectoriesTest.java b/test/src/test/java/jenkins/model/JenkinsBuildsAndWorkspacesDirectoriesTest.java
index 0efda703a4..712527b0b6 100644
--- a/test/src/test/java/jenkins/model/JenkinsBuildsAndWorkspacesDirectoriesTest.java
+++ b/test/src/test/java/jenkins/model/JenkinsBuildsAndWorkspacesDirectoriesTest.java
@@ -2,17 +2,19 @@ package jenkins.model;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assume.assumeFalse;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assumptions.assumeFalse;
import hudson.Functions;
import hudson.init.InitMilestone;
import hudson.model.FreeStyleBuild;
import hudson.model.FreeStyleProject;
import java.io.File;
+import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -21,47 +23,46 @@ import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.stream.Stream;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.ClassRule;
-import org.junit.Ignore;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+import org.junit.jupiter.api.io.TempDir;
+import org.jvnet.hudson.reactor.ReactorException;
import org.jvnet.hudson.test.Issue;
-import org.jvnet.hudson.test.LoggerRule;
+import org.jvnet.hudson.test.LogRecorder;
import org.jvnet.hudson.test.MockFolder;
-import org.jvnet.hudson.test.RestartableJenkinsRule;
+import org.jvnet.hudson.test.junit.jupiter.JenkinsSessionExtension;
import org.jvnet.hudson.test.recipes.LocalData;
/**
* Since JENKINS-50164, Jenkins#workspacesDir and Jenkins#buildsDir had their associated UI deleted.
* So instead of configuring through the UI, we now have to use sysprops for this.
*
- * So this test class uses a {@link RestartableJenkinsRule} to check the behaviour of this sysprop being
+ * So this test class uses a {@link JenkinsSessionExtension} to check the behaviour of this sysprop being
* present or not between two restarts.
*/
-public class JenkinsBuildsAndWorkspacesDirectoriesTest {
+class JenkinsBuildsAndWorkspacesDirectoriesTest {
private static final String LOG_WHEN_CHANGING_BUILDS_DIR = "Changing builds directories from ";
private static final String LOG_WHEN_CHANGING_WORKSPACES_DIR = "Changing workspaces directories from ";
- @Rule
- public RestartableJenkinsRule story = new RestartableJenkinsRule();
+ @RegisterExtension
+ private final JenkinsSessionExtension story = new JenkinsSessionExtension();
- @Rule
- public LoggerRule loggerRule = new LoggerRule();
+ private final LogRecorder loggerRule = new LogRecorder();
- @ClassRule
- public static TemporaryFolder tmp = new TemporaryFolder();
+ @TempDir
+ private static File tmp;
- @Before
- public void before() {
+ @BeforeEach
+ void before() {
clearSystemProperties();
}
- @After
- public void after() {
+ @AfterEach
+ void after() {
clearSystemProperties();
}
@@ -72,7 +73,7 @@ public class JenkinsBuildsAndWorkspacesDirectoriesTest {
@Issue("JENKINS-53284")
@Test
- public void changeWorkspacesDirLog() throws Exception {
+ void changeWorkspacesDirLog() throws Throwable {
loggerRule.record(Jenkins.class, Level.WARNING)
.record(Jenkins.class, Level.INFO).capture(1000);
@@ -92,7 +93,7 @@ public class JenkinsBuildsAndWorkspacesDirectoriesTest {
@Issue("JENKINS-50164")
@Test
- public void badValueForBuildsDir() {
+ void badValueForBuildsDir() throws Throwable {
story.then(rule -> {
final List badValues = new ArrayList<>(Arrays.asList(
"blah",
@@ -108,14 +109,14 @@ public class JenkinsBuildsAndWorkspacesDirectoriesTest {
} // else perhaps running as root
for (String badValue : badValues) {
- assertThrows(badValue + " should have been rejected", InvalidBuildsDir.class, () -> Jenkins.checkRawBuildsDir(badValue));
+ assertThrows(InvalidBuildsDir.class, () -> Jenkins.checkRawBuildsDir(badValue), badValue + " should have been rejected");
}
});
}
@Issue("JENKINS-50164")
@Test
- public void goodValueForBuildsDir() {
+ void goodValueForBuildsDir() throws Throwable {
story.then(rule -> {
final List badValues = Arrays.asList(
"$JENKINS_HOME/foo/$ITEM_FULL_NAME",
@@ -129,31 +130,29 @@ public class JenkinsBuildsAndWorkspacesDirectoriesTest {
@Issue("JENKINS-50164")
@Test
- public void jenkinsDoesNotStartWithBadSysProp() {
-
+ void jenkinsDoesNotStartWithBadSysProp() throws Throwable {
loggerRule.record(Jenkins.class, Level.WARNING)
.record(Jenkins.class, Level.INFO)
.capture(100);
story.then(rule -> {
- assertTrue(story.j.getInstance().isDefaultBuildDir());
+ assertTrue(rule.getInstance().isDefaultBuildDir());
setBuildsDirProperty("/bluh");
});
- story.thenDoesNotStart();
+ assertThrows(ReactorException.class, () -> story.then(step -> fail("should have failed before reaching here.")));
}
@Issue("JENKINS-50164")
@Test
- public void jenkinsDoesNotStartWithScrewedUpConfigXml() {
-
+ void jenkinsDoesNotStartWithScrewedUpConfigXml() throws Throwable {
loggerRule.record(Jenkins.class, Level.WARNING)
.record(Jenkins.class, Level.INFO)
.capture(100);
story.then(rule -> {
- assertTrue(story.j.getInstance().isDefaultBuildDir());
+ assertTrue(rule.getInstance().isDefaultBuildDir());
// Now screw up the value by writing into the file directly, like one could do using external XML manipulation tools
final Path configFile = rule.jenkins.getRootDir().toPath().resolve("config.xml");
@@ -162,12 +161,12 @@ public class JenkinsBuildsAndWorkspacesDirectoriesTest {
Files.writeString(configFile, screwedUp, StandardCharsets.UTF_8);
});
- story.thenDoesNotStart();
+ assertThrows(ReactorException.class, () -> story.then(step -> fail("should have failed before reaching here.")));
}
@Issue("JENKINS-50164")
@Test
- public void buildsDir() throws Exception {
+ void buildsDir() throws Throwable {
loggerRule.record(Jenkins.class, Level.WARNING)
.record(Jenkins.class, Level.INFO)
.capture(100);
@@ -175,14 +174,14 @@ public class JenkinsBuildsAndWorkspacesDirectoriesTest {
story.then(step -> assertFalse(logWasFound("Using non default builds directories")));
story.then(steps -> {
- assertTrue(story.j.getInstance().isDefaultBuildDir());
+ assertTrue(steps.getInstance().isDefaultBuildDir());
setBuildsDirProperty("$JENKINS_HOME/plouf/$ITEM_FULL_NAME/bluh");
assertFalse(JenkinsBuildsAndWorkspacesDirectoriesTest.this.logWasFound(LOG_WHEN_CHANGING_BUILDS_DIR));
});
story.then(step -> {
- assertFalse(story.j.getInstance().isDefaultBuildDir());
- assertEquals("$JENKINS_HOME/plouf/$ITEM_FULL_NAME/bluh", story.j.getInstance().getRawBuildsDir());
+ assertFalse(step.getInstance().isDefaultBuildDir());
+ assertEquals("$JENKINS_HOME/plouf/$ITEM_FULL_NAME/bluh", step.getInstance().getRawBuildsDir());
assertTrue(logWasFound("Changing builds directories from "));
}
);
@@ -193,7 +192,7 @@ public class JenkinsBuildsAndWorkspacesDirectoriesTest {
@Issue("JENKINS-50164")
@Test
- public void workspacesDir() throws Exception {
+ void workspacesDir() throws Throwable {
loggerRule.record(Jenkins.class, Level.WARNING)
.record(Jenkins.class, Level.INFO)
.capture(1000);
@@ -201,33 +200,32 @@ public class JenkinsBuildsAndWorkspacesDirectoriesTest {
story.then(step -> assertFalse(logWasFound("Using non default workspaces directories")));
story.then(step -> {
- assertTrue(story.j.getInstance().isDefaultWorkspaceDir());
+ assertTrue(step.getInstance().isDefaultWorkspaceDir());
final String workspacesDir = "bluh";
setWorkspacesDirProperty(workspacesDir);
assertFalse(logWasFound("Changing workspaces directories from "));
});
story.then(step -> {
- assertFalse(story.j.getInstance().isDefaultWorkspaceDir());
- assertEquals("bluh", story.j.getInstance().getRawWorkspaceDir());
+ assertFalse(step.getInstance().isDefaultWorkspaceDir());
+ assertEquals("bluh", step.getInstance().getRawWorkspaceDir());
assertTrue(logWasFound("Changing workspaces directories from "));
});
story.then(step -> {
- assertFalse(story.j.getInstance().isDefaultWorkspaceDir());
+ assertFalse(step.getInstance().isDefaultWorkspaceDir());
assertTrue(logWasFound("Using non default workspaces directories"));
}
);
}
- @Ignore("TODO calling restart seems to break Surefire")
+ @Disabled("TODO calling restart seems to break Surefire")
@Issue("JENKINS-50164")
@LocalData
@Test
- public void fromPreviousCustomSetup() {
-
- assumeFalse("Default Windows lifecycle does not support restart.", Functions.isWindows());
+ void fromPreviousCustomSetup() throws Throwable {
+ assumeFalse(Functions.isWindows(), "Default Windows lifecycle does not support restart.");
// check starting point and change config for next run
final String newBuildsDirValueBySysprop = "/tmp/${ITEM_ROOTDIR}/bluh";
@@ -283,20 +281,19 @@ public class JenkinsBuildsAndWorkspacesDirectoriesTest {
@Test
@Issue("JENKINS-17138")
- public void externalBuildDirectoryRenameDelete() throws Exception {
-
+ void externalBuildDirectoryRenameDelete() throws Throwable {
// Hack to get String builds usable in lambda below
final List builds = new ArrayList<>();
story.then(steps -> {
- builds.add(tmp.newFolder().toString());
- assertTrue(story.j.getInstance().isDefaultBuildDir());
+ builds.add(newFolder(tmp, "junit").toString());
+ assertTrue(steps.getInstance().isDefaultBuildDir());
setBuildsDirProperty(builds.get(0) + "/${ITEM_FULL_NAME}");
});
story.then(steps -> {
- assertEquals(builds.get(0) + "/${ITEM_FULL_NAME}", story.j.jenkins.getRawBuildsDir());
- FreeStyleProject p = story.j.jenkins.createProject(MockFolder.class, "d").createProject(FreeStyleProject.class, "prj");
+ assertEquals(builds.get(0) + "/${ITEM_FULL_NAME}", steps.jenkins.getRawBuildsDir());
+ FreeStyleProject p = steps.jenkins.createProject(MockFolder.class, "d").createProject(FreeStyleProject.class, "prj");
FreeStyleBuild b = p.scheduleBuild2(0).get();
File oldBuildDir = new File(builds.get(0), "d/prj");
assertEquals(new File(oldBuildDir, b.getId()), b.getRootDir());
@@ -310,4 +307,13 @@ public class JenkinsBuildsAndWorkspacesDirectoriesTest {
});
}
+ private static File newFolder(File root, String... subDirs) throws IOException {
+ String subFolder = String.join("/", subDirs);
+ File result = new File(root, subFolder);
+ if (!result.mkdirs()) {
+ throw new IOException("Couldn't create folders " + root);
+ }
+ return result;
+ }
+
}
diff --git a/test/src/test/java/jenkins/model/JenkinsLocationConfigurationTest.java b/test/src/test/java/jenkins/model/JenkinsLocationConfigurationTest.java
index 98d9fc2fad..df08cb4e0f 100644
--- a/test/src/test/java/jenkins/model/JenkinsLocationConfigurationTest.java
+++ b/test/src/test/java/jenkins/model/JenkinsLocationConfigurationTest.java
@@ -3,14 +3,16 @@ package jenkins.model;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import hudson.model.FreeStyleProject;
import hudson.model.Label;
+import java.io.File;
import java.io.IOException;
+import java.lang.reflect.Method;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
@@ -22,74 +24,44 @@ import org.htmlunit.html.HtmlForm;
import org.htmlunit.html.HtmlFormUtil;
import org.htmlunit.html.HtmlInput;
import org.htmlunit.html.HtmlPage;
-import org.junit.Rule;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.jupiter.api.extension.RegisterExtension;
+import org.junit.runner.Description;
+import org.junit.runners.model.Statement;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
+import org.jvnet.hudson.test.junit.jupiter.JenkinsSessionExtension;
import org.jvnet.hudson.test.recipes.LocalData;
/**
* @author Kohsuke Kawaguchi
*/
-public class JenkinsLocationConfigurationTest {
+class JenkinsLocationConfigurationTest {
- private String lastRootUrlReturned;
- private boolean lastRootUrlSet;
+ private static String lastRootUrlReturned;
+ private static boolean lastRootUrlSet;
- @Rule
- public JenkinsRule j = new JenkinsRule() {
- @Override
- public URL getURL() throws IOException {
- // first call for the "Running on xxx" log message, Jenkins not being set at that point
- // and the second call is to set the rootUrl of the JLC inside the JenkinsRule#init
- if (Jenkins.getInstanceOrNull() != null) {
- // only useful for doNotAcceptNonHttpBasedRootURL_fromConfigXml
- lastRootUrlReturned = JenkinsLocationConfiguration.getOrDie().getUrl();
- lastRootUrlSet = true;
- }
- return super.getURL();
- }
- };
+ @RegisterExtension
+ public JenkinsSessionExtension session = new CustomJenkinsSessionExtension();
/**
* Makes sure the use of "localhost" in the Hudson URL reports a warning.
*/
@Test
- public void localhostWarning() throws Exception {
- HtmlPage p = j.createWebClient().goTo("configure");
- HtmlInput url = p.getFormByName("config").getInputByName("_.url");
- url.setValue("http://localhost:1234/");
- assertThat(p.getDocumentElement().getTextContent(), containsString("instead of localhost"));
+ void localhostWarning() throws Throwable {
+ session.then(j -> {
+ HtmlPage p = j.createWebClient().goTo("configure");
+ HtmlInput url = p.getFormByName("config").getInputByName("_.url");
+ url.setValue("http://localhost:1234/");
+ assertThat(p.getDocumentElement().getTextContent(), containsString("instead of localhost"));
+ });
}
@Test
@Issue("SECURITY-1471")
- public void doNotAcceptNonHttpBasedRootURL_fromUI() throws Exception {
- // in JenkinsRule, the URL is set to the current URL
- JenkinsLocationConfiguration.getOrDie().setUrl(null);
-
- JenkinsRule.WebClient wc = j.createWebClient();
-
- assertNull(JenkinsLocationConfiguration.getOrDie().getUrl());
-
- settingRootURL("javascript:alert(123);//");
-
- // no impact on the url in memory
- assertNull(JenkinsLocationConfiguration.getOrDie().getUrl());
-
- Path configFile = j.jenkins.getRootDir().toPath().resolve("jenkins.model.JenkinsLocationConfiguration.xml");
- String configFileContent = Files.readString(configFile, StandardCharsets.UTF_8);
- assertThat(configFileContent, containsString("JenkinsLocationConfiguration"));
- assertThat(configFileContent, not(containsString("javascript:alert(123);//")));
- }
-
- @Test
- @Issue("SECURITY-1471")
- public void escapeHatch_acceptNonHttpBasedRootURL_fromUI() throws Exception {
- boolean previousValue = JenkinsLocationConfiguration.DISABLE_URL_VALIDATION;
- JenkinsLocationConfiguration.DISABLE_URL_VALIDATION = true;
-
- try {
+ void doNotAcceptNonHttpBasedRootURL_fromUI() throws Throwable {
+ session.then(j -> {
// in JenkinsRule, the URL is set to the current URL
JenkinsLocationConfiguration.getOrDie().setUrl(null);
@@ -97,100 +69,187 @@ public class JenkinsLocationConfigurationTest {
assertNull(JenkinsLocationConfiguration.getOrDie().getUrl());
- String expectedUrl = "weirdSchema:somethingAlsoWeird";
- settingRootURL(expectedUrl);
+ settingRootURL(j, "javascript:alert(123);//");
- // the method ensures there is an trailing slash
- assertEquals(expectedUrl + "/", JenkinsLocationConfiguration.getOrDie().getUrl());
+ // no impact on the url in memory
+ assertNull(JenkinsLocationConfiguration.getOrDie().getUrl());
Path configFile = j.jenkins.getRootDir().toPath().resolve("jenkins.model.JenkinsLocationConfiguration.xml");
String configFileContent = Files.readString(configFile, StandardCharsets.UTF_8);
assertThat(configFileContent, containsString("JenkinsLocationConfiguration"));
- assertThat(configFileContent, containsString(expectedUrl));
- }
- finally {
- JenkinsLocationConfiguration.DISABLE_URL_VALIDATION = previousValue;
- }
+ assertThat(configFileContent, not(containsString("javascript:alert(123);//")));
+ });
+ }
+
+ @Test
+ @Issue("SECURITY-1471")
+ void escapeHatch_acceptNonHttpBasedRootURL_fromUI() throws Throwable {
+ session.then(j -> {
+ boolean previousValue = JenkinsLocationConfiguration.DISABLE_URL_VALIDATION;
+ JenkinsLocationConfiguration.DISABLE_URL_VALIDATION = true;
+
+ try {
+ // in JenkinsRule, the URL is set to the current URL
+ JenkinsLocationConfiguration.getOrDie().setUrl(null);
+
+ JenkinsRule.WebClient wc = j.createWebClient();
+
+ assertNull(JenkinsLocationConfiguration.getOrDie().getUrl());
+
+ String expectedUrl = "weirdSchema:somethingAlsoWeird";
+ settingRootURL(j, expectedUrl);
+
+ // the method ensures there is an trailing slash
+ assertEquals(expectedUrl + "/", JenkinsLocationConfiguration.getOrDie().getUrl());
+
+ Path configFile = j.jenkins.getRootDir().toPath().resolve("jenkins.model.JenkinsLocationConfiguration.xml");
+ String configFileContent = Files.readString(configFile, StandardCharsets.UTF_8);
+ assertThat(configFileContent, containsString("JenkinsLocationConfiguration"));
+ assertThat(configFileContent, containsString(expectedUrl));
+ } finally {
+ JenkinsLocationConfiguration.DISABLE_URL_VALIDATION = previousValue;
+ }
+ });
}
@Test
@Issue("SECURITY-1471")
@LocalData("xssThroughConfigXml")
- public void doNotAcceptNonHttpBasedRootURL_fromConfigXml() {
- // in JenkinsRule, the URL is set to the current URL, even if coming from LocalData
- // so we need to catch the last value before the getUrl from the JenkinsRule that will be used to set the rootUrl
- assertNull(lastRootUrlReturned);
- assertTrue(lastRootUrlSet);
+ void doNotAcceptNonHttpBasedRootURL_fromConfigXml() throws Throwable {
+ session.then(j -> {
+ // in JenkinsRule, the URL is set to the current URL, even if coming from LocalData
+ // so we need to catch the last value before the getUrl from the JenkinsRule that will be used to set the rootUrl
+ assertNull(lastRootUrlReturned);
+ assertTrue(lastRootUrlSet);
- assertThat(JenkinsLocationConfiguration.getOrDie().getUrl(), not(containsString("javascript")));
+ assertThat(JenkinsLocationConfiguration.getOrDie().getUrl(), not(containsString("javascript")));
+ });
}
@Test
@Issue("SECURITY-1471")
- public void cannotInjectJavaScriptUsingRootUrl_inNewViewLink() throws Exception {
- JenkinsRule.WebClient wc = j.createWebClient();
- j.createFreeStyleProject();
+ void cannotInjectJavaScriptUsingRootUrl_inNewViewLink() throws Throwable {
+ session.then(j -> {
+ JenkinsRule.WebClient wc = j.createWebClient();
+ j.createFreeStyleProject();
- settingRootURL("javascript:alert(123);//");
+ settingRootURL(j, "javascript:alert(123);//");
- // setup the victim
- AtomicReference alertAppeared = new AtomicReference<>(false);
- wc.setAlertHandler((page, s) -> alertAppeared.set(true));
- HtmlPage page = wc.goTo("");
+ // setup the victim
+ AtomicReference alertAppeared = new AtomicReference<>(false);
+ wc.setAlertHandler((page, s) -> alertAppeared.set(true));
+ HtmlPage page = wc.goTo("");
- HtmlAnchor newViewLink = page.getDocumentElement().getElementsByTagName("a").stream()
- .filter(HtmlAnchor.class::isInstance).map(HtmlAnchor.class::cast)
- .filter(a -> a.getHrefAttribute().endsWith("newView"))
- .findFirst().orElseThrow(AssertionError::new);
+ HtmlAnchor newViewLink = page.getDocumentElement().getElementsByTagName("a").stream()
+ .filter(HtmlAnchor.class::isInstance).map(HtmlAnchor.class::cast)
+ .filter(a -> a.getHrefAttribute().endsWith("newView"))
+ .findFirst().orElseThrow(AssertionError::new);
- // last verification
- assertFalse(alertAppeared.get());
+ // last verification
+ assertFalse(alertAppeared.get());
- HtmlElementUtil.click(newViewLink);
+ HtmlElementUtil.click(newViewLink);
- assertFalse(alertAppeared.get());
+ assertFalse(alertAppeared.get());
+ });
}
@Test
@Issue("SECURITY-1471")
- public void cannotInjectJavaScriptUsingRootUrl_inLabelAbsoluteLink() throws Exception {
- String builtInLabel = "builtin-node";
- j.jenkins.setLabelString(builtInLabel);
+ void cannotInjectJavaScriptUsingRootUrl_inLabelAbsoluteLink() throws Throwable {
+ session.then(j -> {
+ String builtInLabel = "builtin-node";
+ j.jenkins.setLabelString(builtInLabel);
- JenkinsRule.WebClient wc = j.createWebClient();
+ JenkinsRule.WebClient wc = j.createWebClient();
- settingRootURL("javascript:alert(123);//");
+ settingRootURL(j, "javascript:alert(123);//");
- // setup the victim
- AtomicReference alertAppeared = new AtomicReference<>(false);
- wc.setAlertHandler((page, s) -> alertAppeared.set(true));
+ // setup the victim
+ AtomicReference alertAppeared = new AtomicReference<>(false);
+ wc.setAlertHandler((page, s) -> alertAppeared.set(true));
- FreeStyleProject p = j.createFreeStyleProject();
- p.setAssignedLabel(Label.get(builtInLabel));
+ FreeStyleProject p = j.createFreeStyleProject();
+ p.setAssignedLabel(Label.get(builtInLabel));
- HtmlPage projectConfigurePage = wc.getPage(p, "/configure");
+ HtmlPage projectConfigurePage = wc.getPage(p, "/configure");
- HtmlAnchor labelAnchor = projectConfigurePage.getDocumentElement().getElementsByTagName("a").stream()
- .filter(HtmlAnchor.class::isInstance).map(HtmlAnchor.class::cast)
- .filter(a -> a.getHrefAttribute().contains("/label/"))
- .findFirst().orElseThrow(AssertionError::new);
+ HtmlAnchor labelAnchor = projectConfigurePage.getDocumentElement().getElementsByTagName("a").stream()
+ .filter(HtmlAnchor.class::isInstance).map(HtmlAnchor.class::cast)
+ .filter(a -> a.getHrefAttribute().contains("/label/"))
+ .findFirst().orElseThrow(AssertionError::new);
- assertFalse(alertAppeared.get());
- HtmlElementUtil.click(labelAnchor);
- assertFalse(alertAppeared.get());
+ assertFalse(alertAppeared.get());
+ HtmlElementUtil.click(labelAnchor);
+ assertFalse(alertAppeared.get());
- String labelHref = labelAnchor.getHrefAttribute();
- assertThat(labelHref, not(containsString("javascript:alert(123)")));
+ String labelHref = labelAnchor.getHrefAttribute();
+ assertThat(labelHref, not(containsString("javascript:alert(123)")));
- String responseContent = projectConfigurePage.getWebResponse().getContentAsString();
- assertThat(responseContent, not(containsString("javascript:alert(123)")));
+ String responseContent = projectConfigurePage.getWebResponse().getContentAsString();
+ assertThat(responseContent, not(containsString("javascript:alert(123)")));
+ });
}
- private void settingRootURL(String desiredRootUrl) throws Exception {
+ private void settingRootURL(JenkinsRule j, String desiredRootUrl) throws Exception {
HtmlPage configurePage = j.createWebClient().goTo("configure");
HtmlForm configForm = configurePage.getFormByName("config");
HtmlInput url = configForm.getInputByName("_.url");
url.setValue(desiredRootUrl);
HtmlFormUtil.submit(configForm);
}
+
+ private static final class CustomJenkinsSessionExtension extends JenkinsSessionExtension {
+
+ private int port;
+ private Description description;
+
+ @Override
+ public void beforeEach(ExtensionContext context) {
+ super.beforeEach(context);
+ description = Description.createTestDescription(
+ context.getTestClass().map(Class::getName).orElse(null),
+ context.getTestMethod().map(Method::getName).orElse(null),
+ context.getTestMethod().map(Method::getAnnotations).orElse(null));
+ }
+
+ @Override
+ public void then(Step s) throws Throwable {
+ CustomJenkinsRule r = new CustomJenkinsRule(getHome(), port);
+ r.apply(
+ new Statement() {
+ @Override
+ public void evaluate() throws Throwable {
+ port = r.getPort();
+ s.run(r);
+ }
+ },
+ description
+ ).evaluate();
+ }
+
+ private static final class CustomJenkinsRule extends JenkinsRule {
+
+ CustomJenkinsRule(File home, int port) {
+ with(() -> home);
+ localPort = port;
+ }
+
+ int getPort() {
+ return localPort;
+ }
+
+ @Override
+ public URL getURL() throws IOException {
+ // first call for the "Running on xxx" log message, Jenkins not being set at that point
+ // and the second call is to set the rootUrl of the JLC inside the JenkinsRule#init
+ if (Jenkins.getInstanceOrNull() != null) {
+ // only useful for doNotAcceptNonHttpBasedRootURL_fromConfigXml
+ lastRootUrlReturned = JenkinsLocationConfiguration.getOrDie().getUrl();
+ lastRootUrlSet = true;
+ }
+ return super.getURL();
+ }
+ }
+ }
}
diff --git a/test/src/test/java/jenkins/model/JenkinsLogRecordsTest.java b/test/src/test/java/jenkins/model/JenkinsLogRecordsTest.java
index 2d81296ac8..3a5cf981e7 100644
--- a/test/src/test/java/jenkins/model/JenkinsLogRecordsTest.java
+++ b/test/src/test/java/jenkins/model/JenkinsLogRecordsTest.java
@@ -13,23 +13,23 @@ import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import jenkins.util.java.JavaUtils;
-import org.junit.Rule;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.MemoryAssert;
-import org.jvnet.hudson.test.RealJenkinsRule;
+import org.jvnet.hudson.test.junit.jupiter.RealJenkinsExtension;
-public class JenkinsLogRecordsTest {
+class JenkinsLogRecordsTest {
- @Rule
- public RealJenkinsRule rr = new RealJenkinsRule();
+ @RegisterExtension
+ private final RealJenkinsExtension rr = new RealJenkinsExtension();
@Test
- public void logRecordsArePresentOnController() throws Throwable {
+ void logRecordsArePresentOnController() throws Throwable {
rr.then(JenkinsLogRecordsTest::_logRecordsArePresentOnController);
}
- private static void _logRecordsArePresentOnController(JenkinsRule r) throws Throwable {
+ private static void _logRecordsArePresentOnController(JenkinsRule r) {
List logRecords = Jenkins.logRecords;
assertThat(logRecords, not(empty()));
assertThat("Records are displayed in reverse order",
diff --git a/test/src/test/java/jenkins/model/JenkinsManagePermissionTest.java b/test/src/test/java/jenkins/model/JenkinsManagePermissionTest.java
index d84515f858..4ace5c2781 100644
--- a/test/src/test/java/jenkins/model/JenkinsManagePermissionTest.java
+++ b/test/src/test/java/jenkins/model/JenkinsManagePermissionTest.java
@@ -8,8 +8,8 @@ import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import hudson.PluginWrapper;
import hudson.cli.CLICommandInvoker;
@@ -29,13 +29,14 @@ import org.hamcrest.Matcher;
import org.htmlunit.WebResponse;
import org.htmlunit.html.HtmlForm;
import org.htmlunit.html.HtmlPage;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Rule;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.MockAuthorizationStrategy;
+import org.jvnet.hudson.test.junit.jupiter.WithJenkins;
import org.jvnet.hudson.test.recipes.WithPlugin;
/**
@@ -43,29 +44,32 @@ import org.jvnet.hudson.test.recipes.WithPlugin;
* with this property activated.
*/
// TODO move tests to indicated test classes when we no longer need to set the system property
-public class JenkinsManagePermissionTest {
+@WithJenkins
+class JenkinsManagePermissionTest {
- @Rule
- public JenkinsRule j = new JenkinsRule();
+ private JenkinsRule j;
- @BeforeClass
- public static void enableManagePermission() {
+ @BeforeAll
+ static void enableManagePermission() {
System.setProperty("jenkins.security.ManagePermission", "true");
}
- @AfterClass
- public static void disableManagePermission() {
- System.clearProperty("jenkins.security.ManagePermission");
+ @BeforeEach
+ void setUp(JenkinsRule rule) {
+ j = rule;
}
+ @AfterAll
+ static void disableManagePermission() {
+ System.clearProperty("jenkins.security.ManagePermission");
+ }
// -----------------------------
// DisablePluginCommandTest
@Issue("JENKINS-60266")
@Test
- @WithPlugin({ "depender-0.0.2.hpi", "dependee-0.0.2.hpi"})
- public void managerCannotDisablePlugin() {
-
+ @WithPlugin({"depender-0.0.2.hpi", "dependee-0.0.2.hpi"})
+ void managerCannotDisablePlugin() {
//GIVEN a user with Jenkins.MANAGE permission
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy()
@@ -88,7 +92,6 @@ public class JenkinsManagePermissionTest {
return new CLICommandInvoker(j, new DisablePluginCommand()).asUser(user).invokeWithArgs(args);
}
-
private void assertPluginEnabled(String name) {
PluginWrapper plugin = j.getPluginManager().getPlugin(name);
assertThat(plugin, is(notNullValue()));
@@ -102,7 +105,7 @@ public class JenkinsManagePermissionTest {
//ComputerTest
@Issue("JENKINS-60266")
@Test
- public void dumpExportTableForbiddenWithoutAdminPermission() throws Exception {
+ void dumpExportTableForbiddenWithoutAdminPermission() throws Exception {
final String READER = "reader";
final String MANAGER = "manager";
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
@@ -122,7 +125,7 @@ public class JenkinsManagePermissionTest {
// HudsonTest
@Issue("JENKINS-60266")
@Test
- public void someGlobalConfigurationIsNotDisplayedWithManagePermission() throws Exception {
+ void someGlobalConfigurationIsNotDisplayedWithManagePermission() throws Exception {
//GIVEN a user with Jenkins.MANAGE permission
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy()
@@ -146,7 +149,7 @@ public class JenkinsManagePermissionTest {
@Issue("JENKINS-60266")
@Test
- public void someGlobalConfigCanNotBeModifiedWithManagePermission() throws Exception {
+ void someGlobalConfigCanNotBeModifiedWithManagePermission() throws Exception {
j.jenkins.addView(new MyView("testView", j.jenkins));
//GIVEN the Global Configuration Form, with some changes unsaved
@@ -164,14 +167,14 @@ public class JenkinsManagePermissionTest {
.grant(Jenkins.MANAGE, Jenkins.READ).everywhere().toEveryone());
j.submit(form);
// THEN the changes on fields forbidden to a Jenkins.MANAGE permission are not saved
- assertEquals("shouldn't be allowed to change the number of executors", currentNumberExecutors, j.getInstance().getNumExecutors());
- assertEquals("shouldn't be allowed to change the shell executable", shell, getShell());
- assertEquals("shouldn't be allowed to change the primary view", view, j.getInstance().getPrimaryView());
+ assertEquals(currentNumberExecutors, j.getInstance().getNumExecutors(), "shouldn't be allowed to change the number of executors");
+ assertEquals(shell, getShell(), "shouldn't be allowed to change the shell executable");
+ assertEquals(view, j.getInstance().getPrimaryView(), "shouldn't be allowed to change the primary view");
}
@Issue("JENKINS-60266")
@Test
- public void globalConfigAllowedWithManagePermission() throws Exception {
+ void globalConfigAllowedWithManagePermission() throws Exception {
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy()
.grant(Jenkins.MANAGE, Jenkins.READ).everywhere().toEveryone());
@@ -184,7 +187,7 @@ public class JenkinsManagePermissionTest {
@Issue("JENKINS-61457")
@Test
- public void managePermissionCanChangeUsageStatistics() throws Exception {
+ void managePermissionCanChangeUsageStatistics() throws Exception {
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy()
.grant(Jenkins.MANAGE, Jenkins.READ).everywhere().toEveryone());
@@ -233,8 +236,7 @@ public class JenkinsManagePermissionTest {
@Issue("JENKINS-63795")
@Test
- public void managePermissionShouldBeAllowedToRestart() throws IOException {
-
+ void managePermissionShouldBeAllowedToRestart() throws IOException {
//GIVEN a Jenkins with 3 users : ADMINISTER, MANAGE and READ
HudsonPrivateSecurityRealm realm = new HudsonPrivateSecurityRealm(false, false, null);
User adminUser = realm.createAccount("Administer", "G0d");
diff --git a/test/src/test/java/jenkins/model/JenkinsTest.java b/test/src/test/java/jenkins/model/JenkinsTest.java
index f4a5b37616..012e8a4800 100644
--- a/test/src/test/java/jenkins/model/JenkinsTest.java
+++ b/test/src/test/java/jenkins/model/JenkinsTest.java
@@ -35,13 +35,13 @@ import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isA;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assume.assumeFalse;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assumptions.assumeFalse;
import hudson.ExtensionList;
import hudson.Functions;
@@ -101,17 +101,17 @@ import org.htmlunit.WebRequest;
import org.htmlunit.WebResponse;
import org.htmlunit.html.HtmlForm;
import org.htmlunit.html.HtmlPage;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import org.jvnet.hudson.reactor.ReactorException;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.JenkinsRule.WebClient;
import org.jvnet.hudson.test.MockAuthorizationStrategy;
-import org.jvnet.hudson.test.SmokeTest;
import org.jvnet.hudson.test.TestExtension;
+import org.jvnet.hudson.test.junit.jupiter.WithJenkins;
import org.jvnet.hudson.test.recipes.WithPlugin;
import org.kohsuke.stapler.HttpResponse;
import org.mockito.ArgumentCaptor;
@@ -123,17 +123,23 @@ import org.mockito.Mockito;
* @see Jenkins
* @see JenkinsRule
*/
-@Category(SmokeTest.class)
+@Tag("SmokeTest")
+@WithJenkins
public class JenkinsTest {
- @Rule public JenkinsRule j = new JenkinsRule();
+ @TempDir
+ private File tmp;
- @Rule
- public TemporaryFolder tmp = new TemporaryFolder();
+ private JenkinsRule j;
+
+ @BeforeEach
+ void setUp(JenkinsRule rule) {
+ j = rule;
+ }
@Test
@Issue("SECURITY-3498")
- public void testPaneToggleCollapse() throws Exception {
+ void testPaneToggleCollapse() {
try (WebClient wc = j.createWebClient()) {
final FailingHttpStatusCodeException ex = assertThrows(FailingHttpStatusCodeException.class, () -> wc.goTo("toggleCollapse?paneId=foo"));
// @POST responds 404 when the verb is wrong; @RequirePOST would respond 405.
@@ -143,12 +149,12 @@ public class JenkinsTest {
@Test
@Issue("SECURITY-3073")
- public void verifyUploadedFingerprintFilePermission() throws Exception {
+ void verifyUploadedFingerprintFilePermission() throws Exception {
assumeFalse(Functions.isWindows());
HtmlPage page = j.createWebClient().goTo("fingerprintCheck");
HtmlForm form = page.getForms().get(0);
- File dir = tmp.newFolder();
+ File dir = newFolder(tmp, "junit");
File plugin = new File(dir, "htmlpublisher.jpi");
// We're using a plugin to have a file above DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD
FileUtils.copyURLToFile(Objects.requireNonNull(getClass().getClassLoader().getResource("plugins/htmlpublisher.jpi")), plugin);
@@ -179,12 +185,12 @@ public class JenkinsTest {
@Issue("SECURITY-406")
@Test
- public void testUserCreationFromUrlForAdmins() throws Exception {
+ void testUserCreationFromUrlForAdmins() throws Exception {
WebClient wc = j.createWebClient();
- assertNull("User not supposed to exist", User.getById("nonexistent", false));
+ assertNull(User.getById("nonexistent", false), "User not supposed to exist");
wc.assertFails("user/nonexistent", 404);
- assertNull("User not supposed to exist", User.getById("nonexistent", false));
+ assertNull(User.getById("nonexistent", false), "User not supposed to exist");
try {
User.ALLOW_USER_CREATION_VIA_URL = true;
@@ -192,7 +198,7 @@ public class JenkinsTest {
// expected to work
wc.goTo("user/nonexistent2");
- assertNotNull("User supposed to exist", User.getById("nonexistent2", false));
+ assertNotNull(User.getById("nonexistent2", false), "User supposed to exist");
} finally {
User.ALLOW_USER_CREATION_VIA_URL = false;
@@ -200,7 +206,7 @@ public class JenkinsTest {
}
@Test
- public void testIsDisplayNameUniqueTrue() throws Exception {
+ void testIsDisplayNameUniqueTrue() throws Exception {
final String curJobName = "curJobName";
final String jobName = "jobName";
FreeStyleProject curProject = j.createFreeStyleProject(curJobName);
@@ -215,7 +221,7 @@ public class JenkinsTest {
}
@Test
- public void testIsDisplayNameUniqueFalse() throws Exception {
+ void testIsDisplayNameUniqueFalse() throws Exception {
final String curJobName = "curJobName";
final String jobName = "jobName";
final String displayName = "displayName";
@@ -231,7 +237,7 @@ public class JenkinsTest {
}
@Test
- public void testIsDisplayNameUniqueSameAsCurrentJob() throws Exception {
+ void testIsDisplayNameUniqueSameAsCurrentJob() throws Exception {
final String curJobName = "curJobName";
final String displayName = "currentProjectDisplayName";
@@ -244,7 +250,7 @@ public class JenkinsTest {
}
@Test
- public void testIsNameUniqueTrue() throws Exception {
+ void testIsNameUniqueTrue() throws Exception {
final String curJobName = "curJobName";
final String jobName = "jobName";
j.createFreeStyleProject(curJobName);
@@ -255,7 +261,7 @@ public class JenkinsTest {
}
@Test
- public void testIsNameUniqueFalse() throws Exception {
+ void testIsNameUniqueFalse() throws Exception {
final String curJobName = "curJobName";
final String jobName = "jobName";
j.createFreeStyleProject(curJobName);
@@ -266,7 +272,7 @@ public class JenkinsTest {
}
@Test
- public void testIsNameUniqueSameAsCurrentJob() throws Exception {
+ void testIsNameUniqueSameAsCurrentJob() throws Exception {
final String curJobName = "curJobName";
final String jobName = "jobName";
j.createFreeStyleProject(curJobName);
@@ -278,7 +284,7 @@ public class JenkinsTest {
}
@Test
- public void testDoCheckDisplayNameUnique() throws Exception {
+ void testDoCheckDisplayNameUnique() throws Exception {
final String curJobName = "curJobName";
final String jobName = "jobName";
FreeStyleProject curProject = j.createFreeStyleProject(curJobName);
@@ -293,7 +299,7 @@ public class JenkinsTest {
}
@Test
- public void testDoCheckDisplayNameSameAsDisplayName() throws Exception {
+ void testDoCheckDisplayNameSameAsDisplayName() throws Exception {
final String curJobName = "curJobName";
final String jobName = "jobName";
final String displayName = "displayName";
@@ -309,7 +315,7 @@ public class JenkinsTest {
}
@Test
- public void testDoCheckDisplayNameSameAsJobName() throws Exception {
+ void testDoCheckDisplayNameSameAsJobName() throws Exception {
final String curJobName = "curJobName";
final String jobName = "jobName";
final String displayName = "displayName";
@@ -325,7 +331,7 @@ public class JenkinsTest {
}
@Test
- public void testDoCheckViewName_GoodName() throws Exception {
+ void testDoCheckViewName_GoodName() {
String[] viewNames = new String[] {
"",
"Jenkins",
@@ -339,7 +345,7 @@ public class JenkinsTest {
}
@Test
- public void testDoCheckViewName_NotGoodName() throws Exception {
+ void testDoCheckViewName_NotGoodName() {
String[] viewNames = new String[] {
"Jenkins?",
"Jenkins*",
@@ -365,8 +371,9 @@ public class JenkinsTest {
/**
* Makes sure access to "/foobar" for UnprotectedRootAction gets through.
*/
- @Test @Issue("JENKINS-14113")
- public void testUnprotectedRootAction() throws Exception {
+ @Test
+ @Issue("JENKINS-14113")
+ void testUnprotectedRootAction() throws Exception {
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
j.jenkins.setAuthorizationStrategy(new FullControlOnceLoggedInAuthorizationStrategy());
WebClient wc = j.createWebClient();
@@ -381,7 +388,7 @@ public class JenkinsTest {
}
@Test
- public void testDoScript() throws Exception {
+ void testDoScript() throws Exception {
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy().
grant(Jenkins.ADMINISTER).everywhere().to("alice").
@@ -411,7 +418,7 @@ public class JenkinsTest {
@Test
@Issue("JENKINS-58548")
- public void testDoScriptTextDoesNotOutputExtraWhitespace() throws Exception {
+ void testDoScriptTextDoesNotOutputExtraWhitespace() throws Exception {
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
WebClient wc = j.createWebClient().login("admin");
TextPage page = wc.getPage(new WebRequest(wc.createCrumbedUrl("scriptText?script=print 'hello'"), HttpMethod.POST));
@@ -419,7 +426,7 @@ public class JenkinsTest {
}
@Test
- public void testDoEval() throws Exception {
+ void testDoEval() throws Exception {
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy().
grant(Jenkins.ADMINISTER).everywhere().to("alice").
@@ -435,15 +442,15 @@ public class JenkinsTest {
wc.withBasicApiToken(User.getById("bob", true));
Page page = eval(wc);
- assertEquals("bob has only READ",
- HttpURLConnection.HTTP_FORBIDDEN,
- page.getWebResponse().getStatusCode());
+ assertEquals(HttpURLConnection.HTTP_FORBIDDEN,
+ page.getWebResponse().getStatusCode(),
+ "bob has only READ");
wc.withBasicApiToken(User.getById("charlie", true));
page = eval(wc);
- assertEquals("charlie has ADMINISTER and READ",
- HttpURLConnection.HTTP_OK,
- page.getWebResponse().getStatusCode());
+ assertEquals(HttpURLConnection.HTTP_OK,
+ page.getWebResponse().getStatusCode(),
+ "charlie has ADMINISTER and READ");
}
private Page eval(WebClient wc) throws Exception {
@@ -491,8 +498,9 @@ public class JenkinsTest {
}
}
- @Test @Issue("JENKINS-20866")
- public void testErrorPageShouldBeAnonymousAccessible() throws Exception {
+ @Test
+ @Issue("JENKINS-20866")
+ void testErrorPageShouldBeAnonymousAccessible() throws Exception {
HudsonPrivateSecurityRealm s = new HudsonPrivateSecurityRealm(false, false, null);
User alice = s.createAccount("alice", "alice");
j.jenkins.setSecurityRealm(s);
@@ -507,7 +515,7 @@ public class JenkinsTest {
.withThrowExceptionOnFailingStatusCode(false);
HtmlPage p = wc.goTo("error/reportError");
- assertEquals(p.asNormalizedText(), HttpURLConnection.HTTP_BAD_REQUEST, p.getWebResponse().getStatusCode()); // not 403 forbidden
+ assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, p.getWebResponse().getStatusCode(), p.asNormalizedText()); // not 403 forbidden
assertTrue(p.getWebResponse().getContentAsString().contains("My car is black"));
}
@@ -534,8 +542,9 @@ public class JenkinsTest {
}
}
- @Test @Issue("JENKINS-23551")
- public void testComputerListenerNotifiedOnRestart() {
+ @Test
+ @Issue("JENKINS-23551")
+ void testComputerListenerNotifiedOnRestart() {
// Simulate restart calling listeners
for (RestartListener listener : RestartListener.all())
listener.onRestart();
@@ -549,7 +558,7 @@ public class JenkinsTest {
public static final ComputerListener listenerMock = Mockito.mock(ComputerListener.class);
@Test
- public void runScriptOnOfflineComputer() throws Exception {
+ void runScriptOnOfflineComputer() throws Exception {
DumbSlave slave = j.createSlave(true);
j.disconnectSlave(slave);
@@ -568,7 +577,7 @@ public class JenkinsTest {
@Test
@Issue("JENKINS-38487")
- public void startupShouldNotFailOnIOExceptionOnlineListener() {
+ void startupShouldNotFailOnIOExceptionOnlineListener() {
// We do nothing, IOExceptionOnOnlineListener & JenkinsRule should cause the
// boot failure if the issue is not fixed.
@@ -589,7 +598,7 @@ public class JenkinsTest {
@Test
@Issue("JENKINS-57111")
- public void startupShouldNotFailOnRuntimeExceptionOnlineListener() {
+ void startupShouldNotFailOnRuntimeExceptionOnlineListener() {
// We do nothing, RuntimeExceptionOnOnlineListener & JenkinsRule should cause the
// boot failure if the issue is not fixed.
assertEquals(1, RuntimeExceptionOnOnlineListener.onOnlineCount);
@@ -608,7 +617,7 @@ public class JenkinsTest {
}
@Test
- public void getComputers() throws Exception {
+ void getComputers() throws Exception {
List agents = new ArrayList<>();
for (String n : List.of("zestful", "bilking", "grouchiest")) {
agents.add(j.createSlave(n, null, null));
@@ -622,7 +631,7 @@ public class JenkinsTest {
@Issue("JENKINS-42577")
@Test
- public void versionIsSavedInSave() throws Exception {
+ void versionIsSavedInSave() throws Exception {
Jenkins.VERSION = "1.0";
j.jenkins.save();
VersionNumber storedVersion = Jenkins.getStoredVersion();
@@ -635,27 +644,28 @@ public class JenkinsTest {
assertNull(nullVersion);
}
+ // Sources: https://github.com/Vlatombe/jenkins-47406
@Issue("JENKINS-47406")
@Test
- @WithPlugin("jenkins-47406.hpi") // Sources: https://github.com/Vlatombe/jenkins-47406
- public void jobCreatedByInitializerIsRetained() {
- assertNotNull("JENKINS-47406 should exist", j.jenkins.getItem("JENKINS-47406"));
+ @WithPlugin("jenkins-47406.hpi")
+ void jobCreatedByInitializerIsRetained() {
+ assertNotNull(j.jenkins.getItem("JENKINS-47406"), "JENKINS-47406 should exist");
}
@Issue("SECURITY-2047")
@Test
- public void testLogin123() throws Exception {
+ void testLogin123() {
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy());
WebClient wc = j.createWebClient();
- FailingHttpStatusCodeException e = assertThrows("Page should be protected.", FailingHttpStatusCodeException.class, () -> wc.goTo("login123"));
+ FailingHttpStatusCodeException e = assertThrows(FailingHttpStatusCodeException.class, () -> wc.goTo("login123"), "Page should be protected.");
assertThat(e.getStatusCode(), is(403));
}
@Issue("SECURITY-2047")
@Test
- public void testLogin123WithRead() throws Exception {
+ void testLogin123WithRead() throws Exception {
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy().
grant(Jenkins.READ).everywhere().to("bob"));
@@ -668,7 +678,7 @@ public class JenkinsTest {
}
@Test
- public void testLogin() throws Exception {
+ void testLogin() throws Exception {
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy().
grant(Jenkins.READ).everywhere().to("bob"));
@@ -681,7 +691,7 @@ public class JenkinsTest {
@Issue("JENKINS-68055")
@Test
- public void testTrimLabelsRetainsLabelExpressions() throws Exception {
+ void testTrimLabelsRetainsLabelExpressions() throws Exception {
Node n = j.createOnlineSlave();
n.setLabelString("test expression");
@@ -695,11 +705,11 @@ public class JenkinsTest {
}
@Test
- public void reloadShouldNotSaveConfig() throws Exception {
+ void reloadShouldNotSaveConfig() throws Exception {
SaveableListenerImpl saveListener = ExtensionList.lookupSingleton(SaveableListenerImpl.class);
saveListener.reset();
j.jenkins.reload();
- assertFalse("Jenkins object should not have been saved.", saveListener.wasCalled());
+ assertFalse(saveListener.wasCalled(), "Jenkins object should not have been saved.");
}
@TestExtension("reloadShouldNotSaveConfig")
@@ -741,7 +751,7 @@ public class JenkinsTest {
}
@Test
- public void checkInitialView() {
+ void checkInitialView() {
assertTrue(CheckInitialViewExtension.hasPrimaryView);
}
@@ -772,7 +782,7 @@ public class JenkinsTest {
}
@Test
- public void reloadViews() throws Exception {
+ void reloadViews() throws Exception {
assertThat(j.jenkins.getPrimaryView(), isA(AllView.class));
assertThat(j.jenkins.getViews(), contains(isA(AllView.class)));
Files.writeString(j.jenkins.getConfigFile().getFile().toPath(), " {
assertThat(r.jenkins.getNodes(), hasSize(0));
var node = new DummyAgent("my-node", "temp", r.createComputerLauncher(null));
diff --git a/test/src/test/java/jenkins/security/BasicHeaderApiTokenAuthenticatorTest.java b/test/src/test/java/jenkins/security/BasicHeaderApiTokenAuthenticatorTest.java
index 940715b0fe..0621875953 100644
--- a/test/src/test/java/jenkins/security/BasicHeaderApiTokenAuthenticatorTest.java
+++ b/test/src/test/java/jenkins/security/BasicHeaderApiTokenAuthenticatorTest.java
@@ -28,8 +28,8 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.xml.HasXPath.hasXPath;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
import hudson.ExtensionComponent;
import hudson.model.User;
@@ -45,21 +45,22 @@ import org.htmlunit.WebRequest;
import org.htmlunit.html.HtmlPage;
import org.htmlunit.html.HtmlTextInput;
import org.htmlunit.xml.XmlPage;
-import org.junit.Rule;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
-import org.jvnet.hudson.test.JenkinsSessionRule;
import org.jvnet.hudson.test.MockAuthorizationStrategy;
import org.jvnet.hudson.test.TestExtension;
+import org.jvnet.hudson.test.junit.jupiter.JenkinsSessionExtension;
-public class BasicHeaderApiTokenAuthenticatorTest {
- @Rule
- public JenkinsSessionRule sessions = new JenkinsSessionRule();
+class BasicHeaderApiTokenAuthenticatorTest {
+
+ @RegisterExtension
+ private final JenkinsSessionExtension sessions = new JenkinsSessionExtension();
@Test
@Issue("SECURITY-896")
- public void legacyToken_regularCase() throws Throwable {
+ void legacyToken_regularCase() throws Throwable {
AtomicReference token = new AtomicReference<>();
sessions.then(j -> {
enableLegacyTokenGenerationOnUserCreation();
@@ -109,7 +110,7 @@ public class BasicHeaderApiTokenAuthenticatorTest {
*/
@Test
@Issue("SECURITY-896")
- public void legacyToken_withoutLastGrantedAuthorities() throws Throwable {
+ void legacyToken_withoutLastGrantedAuthorities() throws Throwable {
AtomicReference token = new AtomicReference<>();
sessions.then(j -> {
enableLegacyTokenGenerationOnUserCreation();
diff --git a/test/src/test/java/jenkins/security/CustomClassFilterTest.java b/test/src/test/java/jenkins/security/CustomClassFilterTest.java
index 4999288071..004cb6bd0b 100644
--- a/test/src/test/java/jenkins/security/CustomClassFilterTest.java
+++ b/test/src/test/java/jenkins/security/CustomClassFilterTest.java
@@ -24,10 +24,13 @@
package jenkins.security;
+import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
+import static org.junit.jupiter.api.Assertions.assertAll;
import hudson.remoting.ClassFilter;
import java.io.File;
+import java.io.IOException;
import java.util.logging.Level;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
@@ -36,61 +39,75 @@ import jenkins.util.BuildListenerAdapter;
import jenkins.util.TreeString;
import jenkins.util.TreeStringBuilder;
import org.apache.commons.io.FileUtils;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-import org.junit.rules.ErrorCollector;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.CleanupMode;
+import org.junit.jupiter.api.io.TempDir;
import org.jvnet.hudson.test.JenkinsRule;
-import org.jvnet.hudson.test.LoggerRule;
-import org.jvnet.hudson.test.SmokeTest;
+import org.jvnet.hudson.test.LogRecorder;
+import org.jvnet.hudson.test.junit.jupiter.WithJenkins;
import org.jvnet.hudson.test.recipes.WithPlugin;
-@Category(SmokeTest.class)
-public class CustomClassFilterTest {
+@Tag("SmokeTest")
+@WithJenkins
+class CustomClassFilterTest {
static {
System.setProperty("hudson.remoting.ClassFilter", "javax.script.SimpleBindings,!jenkins.util.TreeString");
}
- @Rule
- public JenkinsRule r = new JenkinsRule();
+ private final LogRecorder logging = new LogRecorder().record("jenkins.security", Level.FINER);
- @Rule
- public ErrorCollector errors = new ErrorCollector();
+ @TempDir(cleanup = CleanupMode.NEVER)
+ private File tmp;
- @Rule
- public LoggerRule logging = new LoggerRule().record("jenkins.security", Level.FINER);
+ private JenkinsRule r;
+
+ @BeforeEach
+ void setUp(JenkinsRule rule) {
+ r = rule;
+ }
- @Rule
- public TemporaryFolder tmp = new TemporaryFolder();
@WithPlugin("custom-class-filter.jpi")
@Test
- public void smokes() throws Exception {
- assertBlacklisted("enabled via system property", SimpleBindings.class, false);
- assertBlacklisted("enabled via plugin", ScriptException.class, false);
- assertBlacklisted("disabled by ClassFilter.STANDARD", ScriptEngineManager.class, true);
- assertBlacklisted("part of Jenkins core, so why not?", BuildListenerAdapter.class, false);
- // As an aside, the following appear totally unused anyway!
- assertBlacklisted("disabled via system property", TreeString.class, true);
- assertBlacklisted("disabled via plugin", TreeStringBuilder.class, true);
+ void smokes() {
+ assertAll(
+ () -> assertBlacklisted("enabled via system property", SimpleBindings.class, false),
+ () -> assertBlacklisted("enabled via plugin", ScriptException.class, false),
+ () -> assertBlacklisted("disabled by ClassFilter.STANDARD", ScriptEngineManager.class, true),
+ () -> assertBlacklisted("part of Jenkins core, so why not?", BuildListenerAdapter.class, false),
+ // As an aside, the following appear totally unused anyway!
+ () -> assertBlacklisted("disabled via system property", TreeString.class, true),
+ () -> assertBlacklisted("disabled via plugin", TreeStringBuilder.class, true)
+ );
}
@Test
- public void dynamicLoad() throws Exception {
- assertBlacklisted("not yet enabled via plugin", ScriptException.class, true);
- assertBlacklisted("not yet disabled via plugin", TreeStringBuilder.class, false);
- File jpi = tmp.newFile("custom-class-filter.jpi");
- FileUtils.copyURLToFile(CustomClassFilterTest.class.getResource("/plugins/custom-class-filter.jpi"), jpi);
- r.jenkins.pluginManager.dynamicLoad(jpi);
- assertBlacklisted("enabled via plugin", ScriptException.class, false);
- assertBlacklisted("disabled via plugin", TreeStringBuilder.class, true);
+ void dynamicLoad() {
+ assertAll(
+ () -> assertBlacklisted("not yet enabled via plugin", ScriptException.class, true),
+ () -> assertBlacklisted("not yet disabled via plugin", TreeStringBuilder.class, false),
+ () -> {
+ File jpi = newFile(tmp, "custom-class-filter.jpi");
+ FileUtils.copyURLToFile(CustomClassFilterTest.class.getResource("/plugins/custom-class-filter.jpi"), jpi);
+ r.jenkins.pluginManager.dynamicLoad(jpi);
+ },
+ () -> assertBlacklisted("enabled via plugin", ScriptException.class, false),
+ () -> assertBlacklisted("disabled via plugin", TreeStringBuilder.class, true)
+ );
}
private void assertBlacklisted(String message, Class> c, boolean blacklisted) {
String name = c.getName();
- errors.checkThat(name + ": " + message, ClassFilter.DEFAULT.isBlacklisted(c) || ClassFilter.DEFAULT.isBlacklisted(name), is(blacklisted));
+ assertThat(name + ": " + message, ClassFilter.DEFAULT.isBlacklisted(c) || ClassFilter.DEFAULT.isBlacklisted(name), is(blacklisted));
+ }
+
+ private static File newFile(File parent, String child) throws IOException {
+ File result = new File(parent, child);
+ result.createNewFile();
+ return result;
}
}
diff --git a/test/src/test/java/jenkins/security/JettySameSiteCookieSetupTest.java b/test/src/test/java/jenkins/security/JettySameSiteCookieSetupTest.java
index 6557569312..df5fc5bf54 100644
--- a/test/src/test/java/jenkins/security/JettySameSiteCookieSetupTest.java
+++ b/test/src/test/java/jenkins/security/JettySameSiteCookieSetupTest.java
@@ -7,16 +7,22 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import jenkins.model.Jenkins;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.jvnet.hudson.test.FlagRule;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+import org.junit.jupiter.params.Parameter;
+import org.junit.jupiter.params.ParameterizedClass;
+import org.junit.jupiter.params.provider.MethodSource;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.MockAuthorizationStrategy;
+import org.jvnet.hudson.test.junit.jupiter.JenkinsSessionExtension;
+import org.jvnet.hudson.test.junit.jupiter.WithJenkins;
-@RunWith(Parameterized.class)
-public class JettySameSiteCookieSetupTest {
+@WithJenkins
+@ParameterizedClass
+@MethodSource("sameSite")
+class JettySameSiteCookieSetupTest {
private static final Map FLAG_TO_SAMESITE_COOKIE = new HashMap<>() {{
put("", null);
@@ -25,35 +31,49 @@ public class JettySameSiteCookieSetupTest {
put(null, "lax");
}};
- @Rule
- public JenkinsRule j = new JenkinsRule();
+ @RegisterExtension
+ private final JenkinsSessionExtension session = new JenkinsSessionExtension();
- @Rule
- public FlagRule sameSiteCookie;
+ private String sameSiteCookie;
- private final String sameSiteValue;
+ @Parameter
+ private String sameSiteValue;
- public JettySameSiteCookieSetupTest(String sameSiteValue) {
- this.sameSiteValue = sameSiteValue;
- sameSiteCookie = FlagRule.systemProperty(JettySameSiteCookieSetup.class.getName() + ".sameSiteDefault", sameSiteValue);
- }
-
- @Parameterized.Parameters
- public static Set sameSite() {
+ static Set sameSite() {
return FLAG_TO_SAMESITE_COOKIE.keySet();
}
- @Test
- public void testJettyFlagSetsSameSiteCookieProperty() throws Exception {
- String expected = FLAG_TO_SAMESITE_COOKIE.get(this.sameSiteValue);
- j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
- j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy().grant(Jenkins.ADMINISTER).everywhere().to("admin"));
-
- try (JenkinsRule.WebClient wc = j.createWebClient()) {
- wc.login("admin", "admin", true);
-
- assertThat(wc.getCookieManager().getCookie("JSESSIONID").getSameSite(), is(expected));
- assertThat(wc.getCookieManager().getCookie("remember-me").getSameSite(), is(expected));
+ @BeforeEach
+ void setUp() {
+ if (sameSiteValue != null) {
+ sameSiteCookie = System.setProperty(JettySameSiteCookieSetup.class.getName() + ".sameSiteDefault", sameSiteValue);
+ } else {
+ sameSiteCookie = System.clearProperty(JettySameSiteCookieSetup.class.getName() + ".sameSiteDefault");
}
}
+
+ @AfterEach
+ void tearDown() {
+ if (sameSiteCookie != null) {
+ System.setProperty(JettySameSiteCookieSetup.class.getName() + ".sameSiteDefault", sameSiteCookie);
+ } else {
+ System.clearProperty(JettySameSiteCookieSetup.class.getName() + ".sameSiteDefault");
+ }
+ }
+
+ @Test
+ void testJettyFlagSetsSameSiteCookieProperty() throws Throwable {
+ String expected = FLAG_TO_SAMESITE_COOKIE.get(sameSiteValue);
+ session.then(j -> {
+ j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
+ j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy().grant(Jenkins.ADMINISTER).everywhere().to("admin"));
+
+ try (JenkinsRule.WebClient wc = j.createWebClient()) {
+ wc.login("admin", "admin", true);
+
+ assertThat(wc.getCookieManager().getCookie("JSESSIONID").getSameSite(), is(expected));
+ assertThat(wc.getCookieManager().getCookie("remember-me").getSameSite(), is(expected));
+ }
+ });
+ }
}
diff --git a/test/src/test/java/jenkins/security/Security218Test.java b/test/src/test/java/jenkins/security/Security218Test.java
index 9c5efd1552..584f33183b 100644
--- a/test/src/test/java/jenkins/security/Security218Test.java
+++ b/test/src/test/java/jenkins/security/Security218Test.java
@@ -2,33 +2,39 @@ package jenkins.security;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
-import static org.junit.Assert.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import hudson.slaves.DumbSlave;
import java.io.IOException;
-import java.io.Serializable;
import java.util.logging.Level;
import org.codehaus.groovy.runtime.MethodClosure;
-import org.junit.Rule;
-import org.junit.Test;
-import org.jvnet.hudson.test.InboundAgentRule;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
-import org.jvnet.hudson.test.LoggerRule;
+import org.jvnet.hudson.test.LogRecorder;
+import org.jvnet.hudson.test.junit.jupiter.InboundAgentExtension;
+import org.jvnet.hudson.test.junit.jupiter.WithJenkins;
/**
* @author Kohsuke Kawaguchi
*/
@Issue("SECURITY-218")
-public class Security218Test implements Serializable {
- @Rule
- public transient JenkinsRule j = new JenkinsRule();
+@WithJenkins
+class Security218Test {
- @Rule
- public transient InboundAgentRule inboundAgents = new InboundAgentRule();
+ @RegisterExtension
+ private final InboundAgentExtension inboundAgents = new InboundAgentExtension();
- @Rule
- public LoggerRule logging = new LoggerRule().record(ClassFilterImpl.class, Level.FINE);
+ private final LogRecorder logging = new LogRecorder().record(ClassFilterImpl.class, Level.FINE);
+
+ private JenkinsRule j;
+
+ @BeforeEach
+ void setUp(JenkinsRule rule) {
+ j = rule;
+ }
/**
* Makes sure SECURITY-218 fix also applies to agents.
@@ -36,7 +42,7 @@ public class Security218Test implements Serializable {
* This test is for regular static agent
*/
@Test
- public void dumbSlave() throws Exception {
+ void dumbSlave() throws Exception {
check(j.createOnlineSlave());
}
@@ -46,8 +52,8 @@ public class Security218Test implements Serializable {
* This test is for JNLP agent
*/
@Test
- public void jnlpSlave() throws Exception {
- DumbSlave a = (DumbSlave) inboundAgents.createAgent(j, InboundAgentRule.Options.newBuilder().secret().build());
+ void jnlpSlave() throws Exception {
+ DumbSlave a = (DumbSlave) inboundAgents.createAgent(j, InboundAgentExtension.Options.newBuilder().build());
try {
j.createWebClient().goTo("computer/" + a.getNodeName() + "/jenkins-agent.jnlp?encrypt=true", "application/octet-stream");
check(a);
@@ -63,9 +69,9 @@ public class Security218Test implements Serializable {
@SuppressWarnings("ConstantConditions")
private void check(DumbSlave s) {
IOException e = assertThrows(
- "Expected the connection to die",
IOException.class,
- () -> s.getComputer().getChannel().call(new EvilReturnValue()));
+ () -> s.getComputer().getChannel().call(new EvilReturnValue()),
+ "Expected the connection to die");
assertThat(e.getMessage(), containsString(MethodClosure.class.getName()));
}
diff --git a/test/src/test/java/jenkins/security/Security3430Test.java b/test/src/test/java/jenkins/security/Security3430Test.java
index 6eed13cb92..363ad0476e 100644
--- a/test/src/test/java/jenkins/security/Security3430Test.java
+++ b/test/src/test/java/jenkins/security/Security3430Test.java
@@ -7,10 +7,10 @@ import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import hudson.ExtensionList;
import hudson.model.Computer;
@@ -38,37 +38,38 @@ import org.apache.commons.io.IOUtils;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
-import org.jvnet.hudson.test.InboundAgentRule;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+import org.junit.jupiter.api.io.TempDir;
import org.jvnet.hudson.test.JenkinsRule;
-import org.jvnet.hudson.test.RealJenkinsRule;
+import org.jvnet.hudson.test.junit.jupiter.InboundAgentExtension;
+import org.jvnet.hudson.test.junit.jupiter.RealJenkinsExtension;
import org.kohsuke.args4j.Argument;
import org.kohsuke.stapler.Stapler;
-public class Security3430Test {
- @Rule
- public RealJenkinsRule jj = new RealJenkinsRule().withLogger(JarURLValidatorImpl.class, Level.FINEST);
+class Security3430Test {
- @Rule
- public InboundAgentRule agents = new InboundAgentRule();
+ @RegisterExtension
+ private final RealJenkinsExtension jj = new RealJenkinsExtension().withLogger(JarURLValidatorImpl.class, Level.FINEST);
- @Rule
- public TemporaryFolder tmp = new TemporaryFolder();
+ @RegisterExtension
+ private final InboundAgentExtension agents = new InboundAgentExtension();
+
+ @TempDir
+ private File tmp;
@Test
- public void runWithOldestSupportedAgentJar() throws Throwable {
+ void runWithOldestSupportedAgentJar() throws Throwable {
runWithRemoting(RemotingVersionInfo.getMinimumSupportedVersion().toString(), "/old-remoting/remoting-minimum-supported.jar", true);
}
@Test
- public void runWithPreviousAgentJar() throws Throwable {
+ void runWithPreviousAgentJar() throws Throwable {
runWithRemoting("3256.v88a_f6e922152", "/old-remoting/remoting-before-SECURITY-3430-fix.jar", true);
}
@Test
- public void runWithCurrentAgentJar() throws Throwable {
+ void runWithCurrentAgentJar() throws Throwable {
runWithRemoting(Launcher.VERSION, null, false);
}
@@ -93,19 +94,19 @@ public class Security3430Test {
private void createAgent(String name, String remotingResourcePath) throws Throwable {
if (remotingResourcePath != null) {
- var jar = tmp.newFile(name + ".jar");
+ var jar = newFile(tmp, name + ".jar");
FileUtils.copyURLToFile(Security3430Test.class.getResource(remotingResourcePath), jar);
// TODO awkward, especially as InboundAgentRule.getAgentArguments is private;
// would be helpful to have an option for a specific agent JAR:
- var opts = InboundAgentRule.Options.newBuilder().name(name).skipStart().build();
+ var opts = InboundAgentExtension.Options.newBuilder().name(name).skipStart().build();
agents.createAgent(jj, opts);
- agents.start(new InboundAgentRule.AgentArguments(jar, jj.getUrl().toString(), name, jj.runRemotely(Security3430Test::getJnlpMac, name), 1, List.of()), opts);
+ agents.start(new InboundAgentExtension.AgentArguments(jar, jj.getUrl().toString(), name, jj.runRemotely(Security3430Test::getJnlpMac, name), 1, List.of()), opts);
} else {
- agents.createAgent(jj, InboundAgentRule.Options.newBuilder().name(name).build());
+ agents.createAgent(jj, InboundAgentExtension.Options.newBuilder().name(name).build());
}
}
- private static String getJnlpMac(JenkinsRule r, String name) throws Throwable {
+ private static String getJnlpMac(JenkinsRule r, String name) {
return ((SlaveComputer) r.jenkins.getComputer(name)).getJnlpMac();
}
@@ -314,4 +315,10 @@ public class Security3430Test {
mismatchDescription.appendText(item.getMessage());
}
}
+
+ private static File newFile(File parent, String child) throws IOException {
+ File result = new File(parent, child);
+ result.createNewFile();
+ return result;
+ }
}
diff --git a/test/src/test/java/jenkins/security/Security3501Test.java b/test/src/test/java/jenkins/security/Security3501Test.java
index 2128ad3074..080cb40ecc 100644
--- a/test/src/test/java/jenkins/security/Security3501Test.java
+++ b/test/src/test/java/jenkins/security/Security3501Test.java
@@ -2,47 +2,46 @@ package jenkins.security;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.List;
import jenkins.security.security3501Test.Security3501RootAction;
import org.htmlunit.FailingHttpStatusCodeException;
-import org.junit.Assert;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+import org.junit.jupiter.params.Parameter;
+import org.junit.jupiter.params.ParameterizedClass;
+import org.junit.jupiter.params.provider.ValueSource;
import org.jvnet.hudson.test.JenkinsRule;
-import org.jvnet.hudson.test.RealJenkinsRule;
+import org.jvnet.hudson.test.junit.jupiter.RealJenkinsExtension;
-@RunWith(Parameterized.class)
-public class Security3501Test {
- // Workaround for https://github.com/jenkinsci/jenkins-test-harness/issues/933
- private final String contextPath;
+@ParameterizedClass
+@ValueSource(strings = { "/jenkins", "" })
+class Security3501Test {
- @Rule
- public RealJenkinsRule jj = new RealJenkinsRule().addSyntheticPlugin(new RealJenkinsRule.SyntheticPlugin(Security3501RootAction.class.getPackage()).shortName("Security3501RootAction"));
+ @Parameter
+ private String contextPath;
- @Parameterized.Parameters
- public static List contexts() {
- return List.of("/jenkins", "");
- }
+ @RegisterExtension
+ private final RealJenkinsExtension jj = new RealJenkinsExtension().addSyntheticPlugin(new RealJenkinsExtension.SyntheticPlugin(Security3501RootAction.class.getPackage()).shortName("Security3501RootAction"));
- public Security3501Test(String contextPath) {
+ @BeforeEach
+ void setUp() {
jj.withPrefix(contextPath);
- this.contextPath = contextPath;
}
@Test
- public void testRedirects() throws Throwable {
+ void testRedirects() throws Throwable {
jj.then(new TestRedirectsStep(contextPath));
}
- private record TestRedirectsStep(String context) implements RealJenkinsRule.Step {
+ private record TestRedirectsStep(String context) implements RealJenkinsExtension.Step {
public void run(JenkinsRule j) throws Exception {
List prohibitedPaths = List.of("%5C%5Cexample.org", "%5C/example.org", "/%5Cexample.org", "//example.org", "https://example.org", "\\example.org");
for (String path : prohibitedPaths) {
try (JenkinsRule.WebClient wc = j.createWebClient().withRedirectEnabled(false)) {
- final FailingHttpStatusCodeException fhsce = Assert.assertThrows(FailingHttpStatusCodeException.class, () -> wc.goTo("redirects/content?path=" + path));
+ final FailingHttpStatusCodeException fhsce = assertThrows(FailingHttpStatusCodeException.class, () -> wc.goTo("redirects/content?path=" + path));
assertThat(fhsce.getStatusCode(), is(404));
}
}
@@ -50,7 +49,7 @@ public class Security3501Test {
List allowedPaths = List.of("foo", "foo/bar");
for (String path : allowedPaths) {
try (JenkinsRule.WebClient wc = j.createWebClient().withRedirectEnabled(false)) {
- final FailingHttpStatusCodeException fhsce = Assert.assertThrows(FailingHttpStatusCodeException.class, () -> wc.goTo("redirects/content?path=" + path));
+ final FailingHttpStatusCodeException fhsce = assertThrows(FailingHttpStatusCodeException.class, () -> wc.goTo("redirects/content?path=" + path));
assertThat(fhsce.getStatusCode(), is(302));
assertThat(fhsce.getResponse().getResponseHeaderValue("Location"), is(context + "/redirects/" + path));
}
diff --git a/test/src/test/java/jenkins/security/Security637Test.java b/test/src/test/java/jenkins/security/Security637Test.java
index 71550b6423..1a170e62d9 100644
--- a/test/src/test/java/jenkins/security/Security637Test.java
+++ b/test/src/test/java/jenkins/security/Security637Test.java
@@ -28,9 +28,9 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assume.assumeNoException;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
import hudson.EnvVars;
import hudson.Launcher;
@@ -48,21 +48,21 @@ import java.net.URLStreamHandler;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
-import org.junit.Ignore;
-import org.junit.Rule;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
import org.jvnet.hudson.test.Issue;
-import org.jvnet.hudson.test.JenkinsSessionRule;
import org.jvnet.hudson.test.TestExtension;
+import org.jvnet.hudson.test.junit.jupiter.JenkinsSessionExtension;
-public class Security637Test {
+class Security637Test {
- @Rule
- public JenkinsSessionRule sessions = new JenkinsSessionRule();
+ @RegisterExtension
+ private final JenkinsSessionExtension sessions = new JenkinsSessionExtension();
@Test
@Issue("SECURITY-637")
- public void urlSafeDeserialization_handler_inSameJVMRemotingContext() throws Throwable {
+ void urlSafeDeserialization_handler_inSameJVMRemotingContext() throws Throwable {
sessions.then(j -> {
DumbSlave slave = j.createOnlineSlave(null, new EnvVars("JAVA_TOOL_OPTIONS", "--add-opens=java.base/java.net=ALL-UNNAMED"));
String unsafeHandlerClassName = slave.getChannel().call(new URLHandlerCallable(new URL("https://www.google.com/")));
@@ -89,23 +89,22 @@ public class Security637Test {
}
}
- @Ignore("TODO these map to different IPs now")
+ @Disabled("TODO these map to different IPs now")
@Test
@Issue("SECURITY-637")
- public void urlDnsEquivalence() throws Throwable {
- sessions.then(j -> {
+ void urlDnsEquivalence() throws Throwable {
+ sessions.then(j ->
// due to the DNS resolution they are equal
assertEquals(
new URI("https://jenkins.io").toURL(),
new URI("https://www.jenkins.io").toURL()
- );
- });
+ ));
}
- @Ignore("TODO these map to different IPs now")
+ @Disabled("TODO these map to different IPs now")
@Test
@Issue("SECURITY-637")
- public void urlSafeDeserialization_urlBuiltInAgent_inSameJVMRemotingContext() throws Throwable {
+ void urlSafeDeserialization_urlBuiltInAgent_inSameJVMRemotingContext() throws Throwable {
sessions.then(j -> {
DumbSlave slave = j.createOnlineSlave();
@@ -132,10 +131,10 @@ public class Security637Test {
}
}
- @Ignore("TODO these map to different IPs now")
+ @Disabled("TODO these map to different IPs now")
@Test
@Issue("SECURITY-637")
- public void urlSafeDeserialization_urlBuiltInMaster_inSameJVMRemotingContext() throws Throwable {
+ void urlSafeDeserialization_urlBuiltInMaster_inSameJVMRemotingContext() throws Throwable {
sessions.then(j -> {
DumbSlave slave = j.createOnlineSlave();
@@ -171,7 +170,7 @@ public class Security637Test {
@Test
@Issue("SECURITY-637")
- public void urlSafeDeserialization_inXStreamContext() throws Throwable {
+ void urlSafeDeserialization_inXStreamContext() throws Throwable {
sessions.then(j -> {
FreeStyleProject project = j.createFreeStyleProject("project-with-url");
URLJobProperty URLJobProperty = new URLJobProperty(
@@ -193,7 +192,7 @@ public class Security637Test {
try {
handlerField.setAccessible(true);
} catch (RuntimeException e) {
- assumeNoException(e);
+ assumeTrue(false, e.getMessage());
}
URLJobProperty urlJobProperty = project.getProperty(URLJobProperty.class);
@@ -212,6 +211,7 @@ public class Security637Test {
private Set urlSet;
+ @SuppressWarnings(value = "checkstyle:redundantmodifier")
public URLJobProperty(URL... urls) {
this.urlSet = new HashSet<>();
Collections.addAll(urlSet, urls);
diff --git a/test/src/test/java/jenkins/security/SecurityContextExecutorServiceTest.java b/test/src/test/java/jenkins/security/SecurityContextExecutorServiceTest.java
index ac9df83a2f..feaa2a7762 100644
--- a/test/src/test/java/jenkins/security/SecurityContextExecutorServiceTest.java
+++ b/test/src/test/java/jenkins/security/SecurityContextExecutorServiceTest.java
@@ -24,8 +24,8 @@
package jenkins.security;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
import hudson.model.User;
import hudson.security.ACL;
@@ -35,51 +35,57 @@ import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledThreadPoolExecutor;
-import org.junit.Rule;
-import org.junit.Test;
+import jenkins.model.Jenkins;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.jvnet.hudson.test.JenkinsRule;
-import org.jvnet.hudson.test.recipes.PresetData;
+import org.jvnet.hudson.test.MockAuthorizationStrategy;
+import org.jvnet.hudson.test.junit.jupiter.WithJenkins;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
/**
* @author Patrick McKeown
*/
-public class SecurityContextExecutorServiceTest {
+@WithJenkins
+class SecurityContextExecutorServiceTest {
- private final int NUM_THREADS = 10;
+ private static final int NUM_THREADS = 10;
private ExecutorService wrappedService = null;
private SecurityContext systemContext = null;
private SecurityContext userContext = null;
private SecurityContext nullContext = null;
- private volatile SecurityContext runnableThreadContext;
- @Rule
- public JenkinsRule j = new JenkinsRule() {
- @Override
- public void before() throws Throwable {
- setPluginManager(null);
- super.before();
+ private SecurityContext runnableThreadContext;
- ScheduledThreadPoolExecutor service = new ScheduledThreadPoolExecutor(NUM_THREADS);
- // Create a system level context with ACL.SYSTEM2
- systemContext = ACL.impersonate2(ACL.SYSTEM2);
+ private JenkinsRule j;
- User u = User.get("bob");
- // Create a sample user context
- userContext = new NonSerializableSecurityContext(u.impersonate2());
+ @BeforeEach
+ void setUp(JenkinsRule rule) {
+ j = rule;
- // Create a null context
- SecurityContextHolder.clearContext();
- nullContext = SecurityContextHolder.getContext();
+ JenkinsRule.DummySecurityRealm realm = j.createDummySecurityRealm();
+ j.jenkins.setSecurityRealm(realm);
+ j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy()
+ .grant(Jenkins.ADMINISTER).everywhere().toAuthenticated());
- // Create a wrapped service
- wrappedService = new SecurityContextExecutorService(service);
- }
- };
+ ScheduledThreadPoolExecutor service = new ScheduledThreadPoolExecutor(NUM_THREADS);
+ // Create a system level context with ACL.SYSTEM2
+ systemContext = ACL.impersonate2(ACL.SYSTEM2);
+
+ User u = User.get("bob");
+ // Create a sample user context
+ userContext = new NonSerializableSecurityContext(u.impersonate2());
+
+ // Create a null context
+ SecurityContextHolder.clearContext();
+ nullContext = SecurityContextHolder.getContext();
+
+ // Create a wrapped service
+ wrappedService = new SecurityContextExecutorService(service);
+ }
@Test
- @PresetData(PresetData.DataSet.NO_ANONYMOUS_READACCESS)
- public void testRunnableAgainstAllContexts() throws Exception {
+ void testRunnableAgainstAllContexts() throws Exception {
Runnable r = () -> runnableThreadContext = SecurityContextHolder.getContext();
SecurityContextHolder.setContext(systemContext);
Future systemResult = wrappedService.submit(r);
@@ -104,8 +110,7 @@ public class SecurityContextExecutorServiceTest {
}
@Test
- @PresetData(PresetData.DataSet.NO_ANONYMOUS_READACCESS)
- public void testCallableAgainstAllContexts() throws Exception {
+ void testCallableAgainstAllContexts() throws Exception {
Callable c = SecurityContextHolder::getContext;
SecurityContextHolder.setContext(systemContext);
Future result = wrappedService.submit(c);
@@ -124,8 +129,7 @@ public class SecurityContextExecutorServiceTest {
}
@Test
- @PresetData(PresetData.DataSet.NO_ANONYMOUS_READACCESS)
- public void testCallableCollectionAgainstAllContexts() throws Exception {
+ void testCallableCollectionAgainstAllContexts() throws Exception {
Collection> callables = new ArrayList<>();
Callable c = SecurityContextHolder::getContext;
callables.add(c);
@@ -156,8 +160,7 @@ public class SecurityContextExecutorServiceTest {
}
@Test
- @PresetData(PresetData.DataSet.NO_ANONYMOUS_READACCESS)
- public void testFailedRunnableResetsContext() {
+ void testFailedRunnableResetsContext() {
Runnable r = () -> {
SecurityContextHolder.setContext(nullContext);
throw new RuntimeException("Simulate a failure");
diff --git a/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsRestartTest.java b/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsRestartTest.java
index d76d382e10..e4dd015bbb 100644
--- a/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsRestartTest.java
+++ b/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsRestartTest.java
@@ -29,10 +29,10 @@ import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.xml.HasXPath.hasXPath;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import hudson.model.User;
import java.io.File;
@@ -50,23 +50,23 @@ import org.htmlunit.html.HtmlPage;
import org.htmlunit.html.HtmlSpan;
import org.htmlunit.util.NameValuePair;
import org.htmlunit.xml.XmlPage;
-import org.junit.Rule;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
import org.jvnet.hudson.test.For;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.JenkinsRule.WebClient;
-import org.jvnet.hudson.test.JenkinsSessionRule;
+import org.jvnet.hudson.test.junit.jupiter.JenkinsSessionExtension;
@For(ApiTokenStats.class)
-public class ApiTokenStatsRestartTest {
+class ApiTokenStatsRestartTest {
- @Rule
- public JenkinsSessionRule sessions = new JenkinsSessionRule();
+ @RegisterExtension
+ private final JenkinsSessionExtension sessions = new JenkinsSessionExtension();
@Test
@Issue("SECURITY-1072")
- public void roundtripWithRestart() throws Throwable {
+ void roundtripWithRestart() throws Throwable {
AtomicReference tokenValue = new AtomicReference<>();
AtomicReference tokenUuid = new AtomicReference<>();
String TOKEN_NAME = "New Token Name";
@@ -119,7 +119,7 @@ public class ApiTokenStatsRestartTest {
assertThat(useCounterSpan.getTextContent(), containsString("" + NUM_CALL_WITH_TOKEN));
File apiTokenStatsFile = new File(u.getUserFolder(), "apiTokenStats.xml");
- assertTrue("apiTokenStats.xml file should exist", apiTokenStatsFile.exists());
+ assertTrue(apiTokenStatsFile.exists(), "apiTokenStats.xml file should exist");
});
sessions.then(j -> {
@@ -159,7 +159,7 @@ public class ApiTokenStatsRestartTest {
assertThat(xmlPage, hasXPath("//authority", is("authenticated")));
}
- private static void checkUserIsNotConnected(WebClient wc) throws Exception {
+ private static void checkUserIsNotConnected(WebClient wc) {
FailingHttpStatusCodeException e = assertThrows(FailingHttpStatusCodeException.class, () -> wc.goToXml("whoAmI/api/xml"));
assertEquals(401, e.getStatusCode());
}
diff --git a/test/src/test/java/jenkins/security/seed/UserSeedPropertyRestartTest.java b/test/src/test/java/jenkins/security/seed/UserSeedPropertyRestartTest.java
index 0d44074d67..ecd8f79062 100644
--- a/test/src/test/java/jenkins/security/seed/UserSeedPropertyRestartTest.java
+++ b/test/src/test/java/jenkins/security/seed/UserSeedPropertyRestartTest.java
@@ -24,31 +24,31 @@
package jenkins.security.seed;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import hudson.model.User;
import java.net.URI;
import java.util.concurrent.atomic.AtomicReference;
import org.htmlunit.HttpMethod;
import org.htmlunit.WebRequest;
-import org.junit.Rule;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
import org.jvnet.hudson.test.For;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
-import org.jvnet.hudson.test.JenkinsSessionRule;
+import org.jvnet.hudson.test.junit.jupiter.JenkinsSessionExtension;
@For(UserSeedProperty.class)
-public class UserSeedPropertyRestartTest {
+class UserSeedPropertyRestartTest {
- @Rule
- public JenkinsSessionRule sessions = new JenkinsSessionRule();
+ @RegisterExtension
+ private final JenkinsSessionExtension sessions = new JenkinsSessionExtension();
@Test
@Issue("SECURITY-901")
- public void initialSeedIsSaved() throws Throwable {
+ void initialSeedIsSaved() throws Throwable {
AtomicReference initialSeedRef = new AtomicReference<>();
sessions.then(j -> {
@@ -68,7 +68,7 @@ public class UserSeedPropertyRestartTest {
@Test
@Issue("SECURITY-901")
- public void renewSeedSavesTheChange() throws Throwable {
+ void renewSeedSavesTheChange() throws Throwable {
AtomicReference initialSeedRef = new AtomicReference<>();
AtomicReference seedRef = new AtomicReference<>();
diff --git a/test/src/test/java/jenkins/security/stapler/JenkinsSupportAnnotationsTest.java b/test/src/test/java/jenkins/security/stapler/JenkinsSupportAnnotationsTest.java
index 6ddee5cf60..88fb00dbfe 100644
--- a/test/src/test/java/jenkins/security/stapler/JenkinsSupportAnnotationsTest.java
+++ b/test/src/test/java/jenkins/security/stapler/JenkinsSupportAnnotationsTest.java
@@ -1,26 +1,32 @@
package jenkins.security.stapler;
-import static org.junit.Assume.assumeFalse;
+import static org.junit.jupiter.api.Assumptions.assumeFalse;
import hudson.Functions;
-import org.junit.Rule;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.jvnet.hudson.test.For;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
+import org.jvnet.hudson.test.junit.jupiter.WithJenkins;
import org.jvnet.hudson.test.recipes.WithPlugin;
@Issue("SECURITY-400")
@For({StaplerDispatchable.class, StaplerAccessibleType.class})
-public class JenkinsSupportAnnotationsTest {
+@WithJenkins
+class JenkinsSupportAnnotationsTest {
- @Rule
- public JenkinsRule j = new JenkinsRule();
+ private JenkinsRule j;
+
+ @BeforeEach
+ void setUp(JenkinsRule rule) {
+ j = rule;
+ }
@Test
@WithPlugin("annotations-test.hpi")
- public void testPluginWithAnnotations() throws Exception {
- assumeFalse("TODO: Implement this test on Windows", Functions.isWindows());
+ void testPluginWithAnnotations() throws Exception {
+ assumeFalse(Functions.isWindows(), "TODO: Implement this test on Windows");
// test fails if TypedFilter ignores @StaplerDispatchable
j.createWebClient().goTo("annotationsTest/whatever", "");
diff --git a/test/src/test/java/jenkins/slaves/OldRemotingAgentTest.java b/test/src/test/java/jenkins/slaves/OldRemotingAgentTest.java
index 8362ed27cc..186ae014a8 100644
--- a/test/src/test/java/jenkins/slaves/OldRemotingAgentTest.java
+++ b/test/src/test/java/jenkins/slaves/OldRemotingAgentTest.java
@@ -57,80 +57,88 @@ import java.net.URISyntaxException;
import java.util.Collection;
import jenkins.security.MasterToSlaveCallable;
import org.apache.commons.io.FileUtils;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.jupiter.api.extension.RegisterExtension;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.runner.Description;
+import org.junit.runners.model.Statement;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.SimpleCommandLauncher;
import org.jvnet.hudson.test.TestBuilder;
import org.jvnet.hudson.test.TestExtension;
+import org.jvnet.hudson.test.junit.jupiter.JenkinsSessionExtension;
/**
* Tests for old Remoting agent versions
*/
-public class OldRemotingAgentTest {
+class OldRemotingAgentTest {
- @Rule
- public JenkinsRule j = new JenkinsRuleWithOldAgent();
+ @RegisterExtension
+ private final JenkinsSessionExtension session = new JenkinsExtensionWithOldAgent();
- @Rule
- public TemporaryFolder tmpDir = new TemporaryFolder();
+ @TempDir
+ private File tmpDir;
- private File agentJar;
+ private static File agentJar;
- @Before
- public void extractAgent() throws Exception {
- agentJar = new File(tmpDir.getRoot(), "old-agent.jar");
+ @BeforeEach
+ void extractAgent() throws Exception {
+ agentJar = new File(tmpDir, "old-agent.jar");
FileUtils.copyURLToFile(OldRemotingAgentTest.class.getResource("/old-remoting/remoting-minimum-supported.jar"), agentJar);
}
@Test
@Issue("JENKINS-48761")
- public void shouldBeAbleToConnectAgentWithMinimumSupportedVersion() throws Exception {
- Label agentLabel = new LabelAtom("old-agent");
- Slave agent = j.createOnlineSlave(agentLabel);
- boolean isUnix = agent.getComputer().isUnix();
- assertThat("Received wrong agent version. A minimum supported version is expected",
- agent.getComputer().getSlaveVersion(),
- equalTo(RemotingVersionInfo.getMinimumSupportedVersion().toString()));
+ void shouldBeAbleToConnectAgentWithMinimumSupportedVersion() throws Throwable {
+ session.then(j -> {
+ Label agentLabel = new LabelAtom("old-agent");
+ Slave agent = j.createOnlineSlave(agentLabel);
+ boolean isUnix = agent.getComputer().isUnix();
+ assertThat("Received wrong agent version. A minimum supported version is expected",
+ agent.getComputer().getSlaveVersion(),
+ equalTo(RemotingVersionInfo.getMinimumSupportedVersion().toString()));
- // Just ensure we are able to run something on the agent
- FreeStyleProject project = j.createFreeStyleProject("foo");
- project.setAssignedLabel(agentLabel);
- project.getBuildersList().add(isUnix ? new Shell("echo Hello") : new BatchFile("echo 'hello'"));
- j.buildAndAssertSuccess(project);
+ // Just ensure we are able to run something on the agent
+ FreeStyleProject project = j.createFreeStyleProject("foo");
+ project.setAssignedLabel(agentLabel);
+ project.getBuildersList().add(isUnix ? new Shell("echo Hello") : new BatchFile("echo 'hello'"));
+ j.buildAndAssertSuccess(project);
- // Run agent monitors
- NodeMonitorAssert.assertMonitors(NodeMonitor.getAll(), agent.getComputer());
+ // Run agent monitors
+ NodeMonitorAssert.assertMonitors(NodeMonitor.getAll(), agent.getComputer());
+ });
}
@Issue("JENKINS-55257")
@Test
- public void remoteConsoleNote() throws Exception {
- Slave agent = j.createOnlineSlave();
- FreeStyleProject project = j.createFreeStyleProject();
- project.setAssignedLabel(agent.getSelfLabel());
- project.getBuildersList().add(new TestBuilder() {
- @Override
- public boolean perform(AbstractBuild, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
- build.getWorkspace().act(new RemoteConsoleNotePrinter(listener));
- return true;
+ void remoteConsoleNote() throws Throwable {
+ session.then(j -> {
+ Slave agent = j.createOnlineSlave();
+ FreeStyleProject project = j.createFreeStyleProject();
+ project.setAssignedLabel(agent.getSelfLabel());
+ project.getBuildersList().add(new TestBuilder() {
+ @Override
+ public boolean perform(AbstractBuild, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
+ build.getWorkspace().act(new RemoteConsoleNotePrinter(listener));
+ return true;
+ }
+ });
+ FreeStyleBuild b = j.buildAndAssertSuccess(project);
+ StringWriter sw = new StringWriter();
+ // The note will not actually work by default; we just want to ensure that the attempt is ignored without breaking the build.
+ // But for purposes of testing, check that the note really made it into the log.
+ boolean insecureOriginal = ConsoleNote.INSECURE;
+ ConsoleNote.INSECURE = true;
+ try {
+ b.getLogText().writeHtmlTo(0, sw);
+ } finally {
+ ConsoleNote.INSECURE = insecureOriginal;
}
+ assertThat(sw.toString(), containsString("@@@ANNOTATED@@@"));
});
- FreeStyleBuild b = j.buildAndAssertSuccess(project);
- StringWriter sw = new StringWriter();
- // The note will not actually work by default; we just want to ensure that the attempt is ignored without breaking the build.
- // But for purposes of testing, check that the note really made it into the log.
- boolean insecureOriginal = ConsoleNote.INSECURE;
- ConsoleNote.INSECURE = true;
- try {
- b.getLogText().writeHtmlTo(0, sw);
- } finally {
- ConsoleNote.INSECURE = insecureOriginal;
- }
- assertThat(sw.toString(), containsString("@@@ANNOTATED@@@"));
}
private static final class RemoteConsoleNotePrinter extends MasterToSlaveCallable {
@@ -160,17 +168,56 @@ public class OldRemotingAgentTest {
}
//TODO: move the logic to JTH
- private class JenkinsRuleWithOldAgent extends JenkinsRule {
+ private static final class JenkinsExtensionWithOldAgent extends JenkinsSessionExtension {
+
+ private int port;
+ private Description description;
@Override
- public ComputerLauncher createComputerLauncher(EnvVars env) throws URISyntaxException, IOException {
+ public void beforeEach(ExtensionContext context) {
+ super.beforeEach(context);
+ description = Description.createTestDescription(
+ context.getTestClass().map(Class::getName).orElse(null),
+ context.getTestMethod().map(Method::getName).orElse(null),
+ context.getTestMethod().map(Method::getAnnotations).orElse(null));
+ }
- // EnvVars are ignored, simple Command Launcher does not offer this API in public
- int sz = this.jenkins.getNodes().size();
- return new SimpleCommandLauncher(String.format("\"%s/bin/java\" %s -jar \"%s\"",
- System.getProperty("java.home"),
- SLAVE_DEBUG_PORT > 0 ? " -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=" + (SLAVE_DEBUG_PORT + sz) : "",
- agentJar.getAbsolutePath()));
+ @Override
+ public void then(Step s) throws Throwable {
+ CustomJenkinsRule r = new CustomJenkinsRule(getHome(), port);
+ r.apply(
+ new Statement() {
+ @Override
+ public void evaluate() throws Throwable {
+ port = r.getPort();
+ s.run(r);
+ }
+ },
+ description
+ ).evaluate();
+ }
+
+ private static final class CustomJenkinsRule extends JenkinsRule {
+
+ CustomJenkinsRule(File home, int port) {
+ with(() -> home);
+ localPort = port;
+ }
+
+ int getPort() {
+ return localPort;
+ }
+
+ @Override
+ public ComputerLauncher createComputerLauncher(EnvVars env) throws URISyntaxException, IOException {
+
+ // EnvVars are ignored, simple Command Launcher does not offer this API in public
+ int sz = this.jenkins.getNodes().size();
+ return new SimpleCommandLauncher(String.format("\"%s/bin/java\" %s -jar \"%s\"",
+ System.getProperty("java.home"),
+ SLAVE_DEBUG_PORT > 0 ? " -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=" + (SLAVE_DEBUG_PORT + sz) : "",
+ agentJar.getAbsolutePath()));
+ }
}
}
diff --git a/test/src/test/java/jenkins/slaves/UnsupportedRemotingAgentEscapeHatchTest.java b/test/src/test/java/jenkins/slaves/UnsupportedRemotingAgentEscapeHatchTest.java
index b8ccb33b80..e1d5bd277d 100644
--- a/test/src/test/java/jenkins/slaves/UnsupportedRemotingAgentEscapeHatchTest.java
+++ b/test/src/test/java/jenkins/slaves/UnsupportedRemotingAgentEscapeHatchTest.java
@@ -12,69 +12,124 @@ import hudson.tasks.BatchFile;
import hudson.tasks.Shell;
import java.io.File;
import java.io.IOException;
+import java.lang.reflect.Method;
import java.net.URISyntaxException;
import org.apache.commons.io.FileUtils;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
-import org.junit.rules.TestRule;
-import org.jvnet.hudson.test.FlagRule;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.jupiter.api.extension.RegisterExtension;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.runner.Description;
+import org.junit.runners.model.Statement;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.SimpleCommandLauncher;
+import org.jvnet.hudson.test.junit.jupiter.JenkinsSessionExtension;
/**
* Test for the escape hatch for unsupported Remoting agent versions
*/
-public class UnsupportedRemotingAgentEscapeHatchTest {
+class UnsupportedRemotingAgentEscapeHatchTest {
- @Rule public JenkinsRule j = new JenkinsRuleWithUnsupportedAgent();
+ @RegisterExtension
+ private final JenkinsSessionExtension session = new JenkinsExtensionWithUnsupportedAgent();
- @Rule public TemporaryFolder tmpDir = new TemporaryFolder();
+ @TempDir
+ private File tmpDir;
- @Rule
- public TestRule allowUnsupportedRemotingVersions = FlagRule.systemProperty(
- SlaveComputer.class.getName() + ".allowUnsupportedRemotingVersions",
- Boolean.toString(true));
+ private String allowUnsupportedRemotingVersions;
- private File agentJar;
+ private static File agentJar;
- @Before
- public void extractAgent() throws Exception {
- agentJar = new File(tmpDir.getRoot(), "unsupported-agent.jar");
+ @BeforeEach
+ void setUp() throws Exception {
+ allowUnsupportedRemotingVersions = System.setProperty(SlaveComputer.class.getName() + ".allowUnsupportedRemotingVersions", "true");
+ agentJar = new File(tmpDir, "unsupported-agent.jar");
FileUtils.copyURLToFile(UnsupportedRemotingAgentEscapeHatchTest.class.getResource("/old-remoting/remoting-unsupported.jar"), agentJar);
}
+ @AfterEach
+ void tearDown() {
+ if (allowUnsupportedRemotingVersions != null) {
+ System.setProperty(SlaveComputer.class.getName() + ".allowUnsupportedRemotingVersions", allowUnsupportedRemotingVersions);
+ } else {
+ System.clearProperty(SlaveComputer.class.getName() + ".allowUnsupportedRemotingVersions");
+ }
+ }
+
@Issue("JENKINS-50211")
@Test
- public void shouldBeAbleToConnectAgentWithUnsupportedVersionWithEscapeHatch() throws Exception {
- Slave agent = j.createOnlineSlave();
- assertThat(agent.toComputer().getLog(), containsString("The Remoting version is older than the minimum required version"));
- assertThat(agent.toComputer().getLog(), containsString("The connection will be allowed, but compatibility is NOT guaranteed"));
+ void shouldBeAbleToConnectAgentWithUnsupportedVersionWithEscapeHatch() throws Throwable {
+ session.then(j -> {
+ Slave agent = j.createOnlineSlave();
+ assertThat(agent.toComputer().getLog(), containsString("The Remoting version is older than the minimum required version"));
+ assertThat(agent.toComputer().getLog(), containsString("The connection will be allowed, but compatibility is NOT guaranteed"));
- // Ensure we are able to run something on the agent
- FreeStyleProject project = j.createFreeStyleProject("foo");
- project.setAssignedLabel(agent.getSelfLabel());
- project.getBuildersList().add(agent.getComputer().isUnix()
- ? new Shell("echo Hello")
- : new BatchFile("echo 'hello'"));
- j.buildAndAssertSuccess(project);
+ // Ensure we are able to run something on the agent
+ FreeStyleProject project = j.createFreeStyleProject("foo");
+ project.setAssignedLabel(agent.getSelfLabel());
+ project.getBuildersList().add(agent.getComputer().isUnix()
+ ? new Shell("echo Hello")
+ : new BatchFile("echo 'hello'"));
+ j.buildAndAssertSuccess(project);
+ });
}
- private class JenkinsRuleWithUnsupportedAgent extends JenkinsRule {
+ private static class JenkinsExtensionWithUnsupportedAgent extends JenkinsSessionExtension {
+
+ private int port;
+ private Description description;
+
@Override
- public ComputerLauncher createComputerLauncher(EnvVars env) throws URISyntaxException, IOException {
- int sz = this.jenkins.getNodes().size();
- return new SimpleCommandLauncher(
- String.format(
- "\"%s/bin/java\" %s -jar \"%s\"",
- System.getProperty("java.home"),
- SLAVE_DEBUG_PORT > 0
- ? " -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address="
- + (SLAVE_DEBUG_PORT + sz)
- : "",
- agentJar.getAbsolutePath()));
+ public void beforeEach(ExtensionContext context) {
+ super.beforeEach(context);
+ description = Description.createTestDescription(
+ context.getTestClass().map(Class::getName).orElse(null),
+ context.getTestMethod().map(Method::getName).orElse(null),
+ context.getTestMethod().map(Method::getAnnotations).orElse(null));
+ }
+
+ @Override
+ public void then(Step s) throws Throwable {
+ CustomJenkinsRule r = new CustomJenkinsRule(getHome(), port);
+ r.apply(
+ new Statement() {
+ @Override
+ public void evaluate() throws Throwable {
+ port = r.getPort();
+ s.run(r);
+ }
+ },
+ description
+ ).evaluate();
+ }
+
+ private static final class CustomJenkinsRule extends JenkinsRule {
+
+ CustomJenkinsRule(File home, int port) {
+ with(() -> home);
+ localPort = port;
+ }
+
+ int getPort() {
+ return localPort;
+ }
+
+ @Override
+ public ComputerLauncher createComputerLauncher(EnvVars env) throws URISyntaxException, IOException {
+ int sz = this.jenkins.getNodes().size();
+ return new SimpleCommandLauncher(
+ String.format(
+ "\"%s/bin/java\" %s -jar \"%s\"",
+ System.getProperty("java.home"),
+ SLAVE_DEBUG_PORT > 0
+ ? " -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address="
+ + (SLAVE_DEBUG_PORT + sz)
+ : "",
+ agentJar.getAbsolutePath()));
+ }
}
}
}
diff --git a/test/src/test/java/jenkins/slaves/UnsupportedRemotingAgentTest.java b/test/src/test/java/jenkins/slaves/UnsupportedRemotingAgentTest.java
index feb6d6e84b..b5f2d68415 100644
--- a/test/src/test/java/jenkins/slaves/UnsupportedRemotingAgentTest.java
+++ b/test/src/test/java/jenkins/slaves/UnsupportedRemotingAgentTest.java
@@ -3,64 +3,113 @@ package jenkins.slaves;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.instanceOf;
-import static org.junit.Assert.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import hudson.EnvVars;
import hudson.model.Slave;
import hudson.slaves.ComputerLauncher;
import java.io.File;
import java.io.IOException;
+import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.util.concurrent.ExecutionException;
import org.apache.commons.io.FileUtils;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.jupiter.api.extension.RegisterExtension;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.runner.Description;
+import org.junit.runners.model.Statement;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.SimpleCommandLauncher;
+import org.jvnet.hudson.test.junit.jupiter.JenkinsSessionExtension;
/**
* Test for unsupported Remoting agent versions
*/
-public class UnsupportedRemotingAgentTest {
+class UnsupportedRemotingAgentTest {
- @Rule public JenkinsRule j = new JenkinsRuleWithUnsupportedAgent();
+ @RegisterExtension
+ private final JenkinsSessionExtension session = new JenkinsExtensionWithUnsupportedAgent();
- @Rule public TemporaryFolder tmpDir = new TemporaryFolder();
+ @TempDir
+ private File tmpDir;
- private File agentJar;
+ private static File agentJar;
- @Before
- public void extractAgent() throws Exception {
- agentJar = new File(tmpDir.getRoot(), "unsupported-agent.jar");
+ @BeforeEach
+ void extractAgent() throws Exception {
+ agentJar = new File(tmpDir, "unsupported-agent.jar");
FileUtils.copyURLToFile(UnsupportedRemotingAgentTest.class.getResource("/old-remoting/remoting-unsupported.jar"), agentJar);
}
@Issue("JENKINS-50211")
@Test
- public void shouldNotBeAbleToConnectAgentWithUnsupportedVersion() throws Exception {
- Slave agent = j.createSlave();
- ExecutionException e = assertThrows(ExecutionException.class, () -> agent.toComputer().connect(false).get());
- assertThat(e.getCause(), instanceOf(IOException.class));
- assertThat(e.getMessage(), containsString("Agent failed to connect"));
- assertThat(agent.toComputer().getLog(), containsString("Rejecting the connection because the Remoting version is older than the minimum required version"));
+ void shouldNotBeAbleToConnectAgentWithUnsupportedVersion() throws Throwable {
+ session.then(j -> {
+ Slave agent = j.createSlave();
+ ExecutionException e = assertThrows(ExecutionException.class, () -> agent.toComputer().connect(false).get());
+ assertThat(e.getCause(), instanceOf(IOException.class));
+ assertThat(e.getMessage(), containsString("Agent failed to connect"));
+ assertThat(agent.toComputer().getLog(), containsString("Rejecting the connection because the Remoting version is older than the minimum required version"));
+ });
}
- private class JenkinsRuleWithUnsupportedAgent extends JenkinsRule {
+ private static class JenkinsExtensionWithUnsupportedAgent extends JenkinsSessionExtension {
+
+ private int port;
+ private Description description;
+
@Override
- public ComputerLauncher createComputerLauncher(EnvVars env) throws URISyntaxException, IOException {
- int sz = this.jenkins.getNodes().size();
- return new SimpleCommandLauncher(
- String.format(
- "\"%s/bin/java\" %s -jar \"%s\"",
- System.getProperty("java.home"),
- SLAVE_DEBUG_PORT > 0
- ? " -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address="
- + (SLAVE_DEBUG_PORT + sz)
- : "",
- agentJar.getAbsolutePath()));
+ public void beforeEach(ExtensionContext context) {
+ super.beforeEach(context);
+ description = Description.createTestDescription(
+ context.getTestClass().map(Class::getName).orElse(null),
+ context.getTestMethod().map(Method::getName).orElse(null),
+ context.getTestMethod().map(Method::getAnnotations).orElse(null));
+ }
+
+ @Override
+ public void then(Step s) throws Throwable {
+ CustomJenkinsRule r = new CustomJenkinsRule(getHome(), port);
+ r.apply(
+ new Statement() {
+ @Override
+ public void evaluate() throws Throwable {
+ port = r.getPort();
+ s.run(r);
+ }
+ },
+ description
+ ).evaluate();
+ }
+
+ private static final class CustomJenkinsRule extends JenkinsRule {
+
+ CustomJenkinsRule(File home, int port) {
+ with(() -> home);
+ localPort = port;
+ }
+
+ int getPort() {
+ return localPort;
+ }
+
+ @Override
+ public ComputerLauncher createComputerLauncher(EnvVars env) throws URISyntaxException, IOException {
+ int sz = this.jenkins.getNodes().size();
+ return new SimpleCommandLauncher(
+ String.format(
+ "\"%s/bin/java\" %s -jar \"%s\"",
+ System.getProperty("java.home"),
+ SLAVE_DEBUG_PORT > 0
+ ? " -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address="
+ + (SLAVE_DEBUG_PORT + sz)
+ : "",
+ agentJar.getAbsolutePath()));
+ }
}
}
}
diff --git a/test/src/test/java/jenkins/slaves/restarter/JnlpSlaveRestarterInstallerTest.java b/test/src/test/java/jenkins/slaves/restarter/JnlpSlaveRestarterInstallerTest.java
index e79ae95902..6936043b1c 100644
--- a/test/src/test/java/jenkins/slaves/restarter/JnlpSlaveRestarterInstallerTest.java
+++ b/test/src/test/java/jenkins/slaves/restarter/JnlpSlaveRestarterInstallerTest.java
@@ -24,8 +24,8 @@
package jenkins.slaves.restarter;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assume.assumeFalse;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assumptions.assumeFalse;
import hudson.Functions;
import hudson.model.Slave;
@@ -33,52 +33,51 @@ import hudson.slaves.DumbSlave;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import jenkins.security.MasterToSlaveCallable;
-import org.junit.Rule;
-import org.junit.Test;
-import org.jvnet.hudson.test.InboundAgentRule;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
import org.jvnet.hudson.test.Issue;
-import org.jvnet.hudson.test.JenkinsSessionRule;
-import org.jvnet.hudson.test.LoggerRule;
+import org.jvnet.hudson.test.LogRecorder;
+import org.jvnet.hudson.test.junit.jupiter.InboundAgentExtension;
+import org.jvnet.hudson.test.junit.jupiter.JenkinsSessionExtension;
-public class JnlpSlaveRestarterInstallerTest {
+class JnlpSlaveRestarterInstallerTest {
- @Rule
- public JenkinsSessionRule rr = new JenkinsSessionRule();
+ @RegisterExtension
+ private final JenkinsSessionExtension rr = new JenkinsSessionExtension();
- @Rule
- public InboundAgentRule inboundAgents = new InboundAgentRule();
+ @RegisterExtension
+ private final InboundAgentExtension inboundAgents = new InboundAgentExtension();
- @Rule
- public LoggerRule logging = new LoggerRule().record(JnlpSlaveRestarterInstaller.class, Level.FINE).capture(10);
+ private final LogRecorder logging = new LogRecorder().record(JnlpSlaveRestarterInstaller.class, Level.FINE).capture(10);
@Issue("JENKINS-19055")
@Test
- public void tcpReconnection() throws Throwable {
+ void tcpReconnection() throws Throwable {
// TODO Enable when test is reliable on Windows agents of ci.jenkins.io
// When builds switched from ACI containers to virtual machines, this test consistently failed
// When the test is run on local Windows computers, it passes
// Disable the test on ci.jenkins.io and friends when running Windows
// Do not disable for Windows developers generally
- assumeFalse("TODO: Test fails on Windows VM", Functions.isWindows() && System.getenv("CI") != null);
+ assumeFalse(Functions.isWindows() && System.getenv("CI") != null, "TODO: Test fails on Windows VM");
reconnection(false);
}
@Issue("JENKINS-66446")
@Test
- public void webSocketReconnection() throws Throwable {
+ void webSocketReconnection() throws Throwable {
// TODO Enable when test is reliable on Windows agents of ci.jenkins.io
// When builds switched from ACI containers to virtual machines, this test consistently failed
// When the test is run on local Windows computers, it passes
// Disable the test on ci.jenkins.io and friends when running Windows
// Do not disable for Windows developers generally
- assumeFalse("TODO: Test fails on Windows VM", Functions.isWindows() && System.getenv("CI") != null);
+ assumeFalse(Functions.isWindows() && System.getenv("CI") != null, "TODO: Test fails on Windows VM");
reconnection(true);
}
private void reconnection(boolean webSocket) throws Throwable {
AtomicBoolean canWork = new AtomicBoolean();
rr.then(r -> {
- InboundAgentRule.Options.Builder builder = InboundAgentRule.Options.newBuilder().name("remote").secret();
+ InboundAgentExtension.Options.Builder builder = InboundAgentExtension.Options.newBuilder().name("remote");
if (webSocket) {
builder.webSocket();
}
diff --git a/test/src/test/java/jenkins/triggers/ReverseBuildTriggerAfterRestartTest.java b/test/src/test/java/jenkins/triggers/ReverseBuildTriggerAfterRestartTest.java
index 5694bc5700..57cc04b71c 100644
--- a/test/src/test/java/jenkins/triggers/ReverseBuildTriggerAfterRestartTest.java
+++ b/test/src/test/java/jenkins/triggers/ReverseBuildTriggerAfterRestartTest.java
@@ -1,21 +1,21 @@
package jenkins.triggers;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import hudson.model.FreeStyleProject;
-import org.junit.Rule;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
import org.jvnet.hudson.test.Issue;
-import org.jvnet.hudson.test.JenkinsSessionRule;
+import org.jvnet.hudson.test.junit.jupiter.JenkinsSessionExtension;
-public class ReverseBuildTriggerAfterRestartTest {
+class ReverseBuildTriggerAfterRestartTest {
- @Rule
- public JenkinsSessionRule rule = new JenkinsSessionRule();
+ @RegisterExtension
+ private final JenkinsSessionExtension rule = new JenkinsSessionExtension();
@Issue("JENKINS-67237")
@Test
- public void testExecutionOfReverseBuildTriggersAfterRestart() throws Throwable {
+ void testExecutionOfReverseBuildTriggersAfterRestart() throws Throwable {
String nameOfUpstreamProject = "upstreamProject";
String nameOfDownstreamProject = "downstreamProject";
diff --git a/test/src/test/java/jenkins/util/SetContextClassLoaderTest.java b/test/src/test/java/jenkins/util/SetContextClassLoaderTest.java
index 71cd6e9354..f7f4cddfc5 100644
--- a/test/src/test/java/jenkins/util/SetContextClassLoaderTest.java
+++ b/test/src/test/java/jenkins/util/SetContextClassLoaderTest.java
@@ -1,19 +1,21 @@
package jenkins.util;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
-import org.junit.Rule;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.RealJenkinsRule;
+import org.jvnet.hudson.test.junit.jupiter.RealJenkinsExtension;
-public class SetContextClassLoaderTest {
+class SetContextClassLoaderTest {
- @Rule public RealJenkinsRule rr = new RealJenkinsRule();
+ @RegisterExtension
+ private final RealJenkinsExtension rr = new RealJenkinsExtension();
@Test
- public void positive() throws Throwable {
+ void positive() throws Throwable {
rr.then(SetContextClassLoaderTest::_positive);
}
@@ -24,7 +26,7 @@ public class SetContextClassLoaderTest {
}
@Test
- public void negative() throws Throwable {
+ void negative() throws Throwable {
rr.then(SetContextClassLoaderTest::_negative);
}
diff --git a/test/src/test/java/jenkins/util/SystemPropertiesTest.java b/test/src/test/java/jenkins/util/SystemPropertiesTest.java
index 121886a754..2308058715 100644
--- a/test/src/test/java/jenkins/util/SystemPropertiesTest.java
+++ b/test/src/test/java/jenkins/util/SystemPropertiesTest.java
@@ -29,8 +29,8 @@ import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.nullValue;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assume.assumeTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
import jakarta.servlet.ServletContextEvent;
import java.time.Duration;
@@ -51,7 +51,9 @@ import org.jvnet.hudson.test.junit.jupiter.WithJenkins;
*/
@WithJenkins
class SystemPropertiesTest {
+
private final LogRecorder logging = new LogRecorder().record(SystemProperties.class, Level.WARNING);
+
private JenkinsRule j;
@BeforeEach
@@ -105,7 +107,7 @@ class SystemPropertiesTest {
}
@Test
- public void duration() {
+ void duration() {
System.setProperty("foo.bar", "1s");
assertEquals(Duration.ofSeconds(1), SystemProperties.getDuration("foo.bar"));
System.setProperty("foo.bar", "2m");
@@ -130,7 +132,7 @@ class SystemPropertiesTest {
}
@Test
- public void invalid() {
+ void invalid() {
logging.capture(10);
System.setProperty("abc.def", "invalid");
assertThat(SystemProperties.getDuration("abc.def"), Matchers.nullValue());
diff --git a/test/src/test/java/lib/form/NameRefTest.java b/test/src/test/java/lib/form/NameRefTest.java
index b198074593..06d1cf7d53 100644
--- a/test/src/test/java/lib/form/NameRefTest.java
+++ b/test/src/test/java/lib/form/NameRefTest.java
@@ -24,13 +24,16 @@
package lib.form;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import hudson.model.RootAction;
import net.sf.json.JSONObject;
import org.htmlunit.html.HtmlPage;
-import org.junit.Rule;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.jvnet.hudson.test.JenkinsRule;
+import org.jvnet.hudson.test.TestExtension;
+import org.jvnet.hudson.test.junit.jupiter.WithJenkins;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.StaplerRequest2;
@@ -38,17 +41,25 @@ import org.kohsuke.stapler.StaplerRequest2;
/**
* Tests the handling of @nameRef in the form tree.
*/
-public class NameRefTest {
+@WithJenkins
+class NameRefTest {
- @Rule public JenkinsRule r = new JenkinsRuleWithJelly();
+ private JenkinsRule r;
- @Test public void test() throws Exception {
+ @BeforeEach
+ void setUp(JenkinsRule rule) {
+ r = rule;
+ }
+
+ @Test
+ void test() throws Exception {
r.jenkins.setCrumbIssuer(null);
HtmlPage p = r.createWebClient().goTo("self/test1");
r.submit(p.getFormByName("config"));
}
- public static class JenkinsRuleWithJelly extends JenkinsRule {
+ @TestExtension
+ public static class RootActionImpl implements RootAction {
public HttpResponse doSubmitTest1(StaplerRequest2 req) throws Exception {
JSONObject f = req.getSubmittedForm();
@@ -58,6 +69,20 @@ public class NameRefTest {
return HttpResponses.ok();
}
+ @Override
+ public String getIconFileName() {
+ return null;
+ }
+
+ @Override
+ public String getDisplayName() {
+ return null;
+ }
+
+ @Override
+ public String getUrlName() {
+ return "self";
+ }
}
}
diff --git a/test/src/test/java/lib/layout/RenderOnDemandTest.java b/test/src/test/java/lib/layout/RenderOnDemandTest.java
index b17ef2fdf8..1f7b4d8383 100644
--- a/test/src/test/java/lib/layout/RenderOnDemandTest.java
+++ b/test/src/test/java/lib/layout/RenderOnDemandTest.java
@@ -56,7 +56,7 @@ import org.jvnet.hudson.test.junit.jupiter.WithJenkins;
class RenderOnDemandTest {
private JenkinsRule j;
- private LogRecorder logging = new LogRecorder().record(RenderOnDemandClosure.class, Level.FINE);
+ private final LogRecorder logging = new LogRecorder().record(RenderOnDemandClosure.class, Level.FINE);
@BeforeEach
void setUp(JenkinsRule rule) {
@@ -83,7 +83,7 @@ class RenderOnDemandTest {
@Disabled("just informational")
@Issue("JENKINS-16341")
@Test
- public void testMemoryConsumption() throws Exception {
+ void testMemoryConsumption() throws Exception {
var wc = j.createWebClient();
callTestBehaviour(wc); // prime caches
int total = 0;
diff --git a/test/src/test/java/org/jenkins/ui/symbol/SymbolJenkinsTest.java b/test/src/test/java/org/jenkins/ui/symbol/SymbolJenkinsTest.java
index 49aaa9cd4f..b7b9944c14 100644
--- a/test/src/test/java/org/jenkins/ui/symbol/SymbolJenkinsTest.java
+++ b/test/src/test/java/org/jenkins/ui/symbol/SymbolJenkinsTest.java
@@ -4,22 +4,23 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
-import org.junit.Rule;
-import org.junit.Test;
import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
-import org.jvnet.hudson.test.RealJenkinsRule;
+import org.jvnet.hudson.test.junit.jupiter.RealJenkinsExtension;
-public class SymbolJenkinsTest {
- @Rule
- public RealJenkinsRule rjr = new RealJenkinsRule()
+class SymbolJenkinsTest {
+
+ @RegisterExtension
+ private final RealJenkinsExtension rjr = new RealJenkinsExtension()
.addPlugins("plugins/design-library.jpi", "plugins/prism-api.jpi", "plugins/bootstrap5-api.jpi");
@Test
@Issue("JENKINS-73243")
@DisplayName("When resolving a symbol where the tooltip contains '$' no error is thrown")
- public void dollarInToolTipSucceeds() throws Throwable {
+ void dollarInToolTipSucceeds() throws Throwable {
rjr.then(SymbolJenkinsTest::_dollarInTooltipSucceeds);
}
@@ -34,7 +35,7 @@ public class SymbolJenkinsTest {
@Test
@DisplayName("When resolving a symbol from a missing plugin, the placeholder is generated instead")
- public void missingSymbolFromPluginDefaultsToPlaceholder() throws Throwable {
+ void missingSymbolFromPluginDefaultsToPlaceholder() throws Throwable {
rjr.then(SymbolJenkinsTest::_missingSymbolFromPluginDefaultsToPlaceholder);
}
@@ -49,7 +50,7 @@ public class SymbolJenkinsTest {
@Test
@DisplayName("Resolving a valid symbol from an installed plugin does not return the placeholder")
- public void resolvingSymbolFromPlugin() throws Throwable {
+ void resolvingSymbolFromPlugin() throws Throwable {
rjr.then(SymbolJenkinsTest::_resolvingSymbolFromPlugin);
}
diff --git a/test/src/test/java/org/kohsuke/stapler/BindTest.java b/test/src/test/java/org/kohsuke/stapler/BindTest.java
index 8ea7ab3d92..6d2eade0c8 100644
--- a/test/src/test/java/org/kohsuke/stapler/BindTest.java
+++ b/test/src/test/java/org/kohsuke/stapler/BindTest.java
@@ -5,42 +5,46 @@ import static org.hamcrest.CoreMatchers.endsWith;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import hudson.ExtensionList;
import hudson.model.InvisibleAction;
import hudson.model.RootAction;
-import java.util.Arrays;
-import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.htmlunit.Page;
import org.htmlunit.ScriptException;
import org.htmlunit.html.HtmlPage;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.Parameter;
+import org.junit.jupiter.params.ParameterizedClass;
+import org.junit.jupiter.params.provider.ValueSource;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.TestExtension;
+import org.jvnet.hudson.test.junit.jupiter.WithJenkins;
import org.kohsuke.stapler.bind.JavaScriptMethod;
import org.kohsuke.stapler.bind.WithWellKnownURL;
-@RunWith(Parameterized.class)
-public class BindTest {
- @Rule
- public JenkinsRule j = new JenkinsRule();
+@ParameterizedClass
+@ValueSource(strings = { "/jenkins", "" })
+@WithJenkins
+class BindTest {
- @Parameterized.Parameters
- public static List contexts() {
- return Arrays.asList("/jenkins", "");
- }
+ @Parameter
+ private String contextPath;
+
+ private JenkinsRule j;
+
+ @BeforeEach
+ void setUp(JenkinsRule rule) throws Throwable {
+ j = rule;
- public BindTest(String contextPath) {
j.contextPath = contextPath;
+ j.restart();
}
@Test
- public void bindNormal() throws Exception {
+ void bindNormal() throws Exception {
final RootActionImpl root = ExtensionList.lookupSingleton(RootActionImpl.class);
try (JenkinsRule.WebClient wc = j.createWebClient()) {
final HtmlPage htmlPage = wc.goTo(root.getUrlName());
@@ -61,7 +65,7 @@ public class BindTest {
}
@Test
- public void bindWithWellKnownURL() throws Exception {
+ void bindWithWellKnownURL() throws Exception {
final RootActionWithWellKnownURL root = ExtensionList.lookupSingleton(RootActionWithWellKnownURL.class);
try (JenkinsRule.WebClient wc = j.createWebClient()) {
final HtmlPage htmlPage = wc.goTo(root.getUrlName());
@@ -80,7 +84,7 @@ public class BindTest {
}
@Test
- public void bindWithWellKnownURLWithQuotes() throws Exception {
+ void bindWithWellKnownURLWithQuotes() throws Exception {
final RootActionWithWellKnownURLWithQuotes root = ExtensionList.lookupSingleton(RootActionWithWellKnownURLWithQuotes.class);
try (JenkinsRule.WebClient wc = j.createWebClient()) {
final HtmlPage htmlPage = wc.goTo(root.getUrlName());
@@ -99,7 +103,7 @@ public class BindTest {
}
@Test
- public void bindNull() throws Exception {
+ void bindNull() throws Exception {
final RootActionImpl root = ExtensionList.lookupSingleton(RootActionImpl.class);
try (JenkinsRule.WebClient wc = j.createWebClient()) {
final ScriptException exception = assertThrows(ScriptException.class, () -> wc.goTo(root.getUrlName() + "/null"));
@@ -118,7 +122,7 @@ public class BindTest {
}
@Test
- public void bindUnsafe() throws Exception {
+ void bindUnsafe() throws Exception {
final RootActionImpl root = ExtensionList.lookupSingleton(RootActionImpl.class);
try (JenkinsRule.WebClient wc = j.createWebClient()) {
final HtmlPage htmlPage = wc.goTo(root.getUrlName() + "/unsafe-var");
@@ -137,7 +141,7 @@ public class BindTest {
}
@Test
- public void bindInlineNull() throws Exception {
+ void bindInlineNull() throws Exception {
final RootActionImpl root = ExtensionList.lookupSingleton(RootActionImpl.class);
try (JenkinsRule.WebClient wc = j.createWebClient()) {
final HtmlPage htmlPage = wc.goTo(root.getUrlName() + "/inline-null");
diff --git a/test/src/test/resources/lib/form/NameRefTest/JenkinsRuleWithJelly/test1.jelly b/test/src/test/resources/lib/form/NameRefTest/RootActionImpl/test1.jelly
similarity index 100%
rename from test/src/test/resources/lib/form/NameRefTest/JenkinsRuleWithJelly/test1.jelly
rename to test/src/test/resources/lib/form/NameRefTest/RootActionImpl/test1.jelly