Migrate tests to JUnit5 (core / hudson / 1) (#10576)

* Migrate annotations and imports
* Migrate assertions
* Remove public visibility for test classes and methods
* Minor code cleanup

Co-authored-by: Mark Waite <mark.earl.waite@gmail.com>
This commit is contained in:
strangelookingnerdandMark Waite authored and GitHub committed 2025-05-27 16:53:24 +02:00
1 parent 4cd3ecaa23
commit ae9d1f9f64
51 files changed
+928 -815

No files matched your search

+1 -1
View File
@@ -453,7 +453,7 @@ THE SOFTWARE.
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<artifactId>mockito-junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
@@ -1,5 +1,6 @@
package jenkins.security;
import com.google.common.annotations.VisibleForTesting;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
@@ -19,6 +20,8 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.model.Jenkins;
import org.kohsuke.MetaInfServices;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
/**
* The actual storage for the data held by {@link ConfidentialKey}s, and the holder
@@ -98,9 +101,11 @@ public abstract class ConfidentialStore {
return cs;
}
static final class Mock extends ConfidentialStore {
@Restricted(NoExternalUse.class)
@VisibleForTesting
public static final class Mock extends ConfidentialStore {
static final Mock INSTANCE = new Mock();
public static final Mock INSTANCE = new Mock();
private final SecureRandom rand;
@@ -116,7 +121,7 @@ public abstract class ConfidentialStore {
rand.setSeed(new byte[] {1, 2, 3, 4});
}
void clear() {
public void clear() {
data.clear();
}
@@ -4,7 +4,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThrows;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.when;
@@ -25,26 +25,26 @@ import java.util.Set;
import jenkins.model.Jenkins;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
public class ListJobsCommandTest {
class ListJobsCommandTest {
private /*final*/ ListJobsCommand command;
private final ByteArrayOutputStream stdout = new ByteArrayOutputStream();
private final ByteArrayOutputStream stderr = new ByteArrayOutputStream();
@Before
public void setUp() {
@BeforeEach
void setUp() {
command = mock(ListJobsCommand.class, Mockito.CALLS_REAL_METHODS);
command.stdout = new PrintStream(stdout);
command.stderr = new PrintStream(stderr);
}
@Test
public void failForNonexistentName() {
void failForNonexistentName() {
Jenkins jenkins = mock(Jenkins.class);
try (MockedStatic<Jenkins> mocked = mockStatic(Jenkins.class)) {
@@ -59,7 +59,7 @@ public class ListJobsCommandTest {
}
@Test
public void getAllJobsForEmptyName() throws Exception {
void getAllJobsForEmptyName() throws Exception {
final List<TopLevelItem> jenkinsJobs = Arrays.asList(
job("some-job"), job("some-other-job")
@@ -76,7 +76,7 @@ public class ListJobsCommandTest {
}
@Test
public void getJobsFromView() throws Exception {
void getJobsFromView() throws Exception {
final Collection<TopLevelItem> viewJobs = Arrays.asList(
job("some-job"), job("some-other-job")
@@ -97,7 +97,7 @@ public class ListJobsCommandTest {
}
@Test
public void getJobsRecursivelyFromViewGroup() throws Exception {
void getJobsRecursivelyFromViewGroup() throws Exception {
final CompositeView rootView = mock(CompositeView.class);
when(rootView.getAllItems()).thenCallRealMethod();
@@ -24,9 +24,9 @@
package hudson.cli.handlers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
@@ -40,9 +40,9 @@ import hudson.model.ViewGroup;
import hudson.security.ACL;
import hudson.security.Permission;
import jenkins.model.Jenkins;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.spi.Parameters;
import org.kohsuke.args4j.spi.Setter;
@@ -52,7 +52,7 @@ import org.mockito.MockitoAnnotations;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
public class ViewOptionHandlerTest {
class ViewOptionHandlerTest {
@Mock private Setter<View> setter;
private ViewOptionHandler handler;
@@ -65,12 +65,13 @@ public class ViewOptionHandlerTest {
private AutoCloseable mocks;
@After
public void tearDown() throws Exception {
@AfterEach
void tearDown() throws Exception {
mocks.close();
}
@Before public void setUp() {
@BeforeEach
void setUp() {
mocks = MockitoAnnotations.openMocks(this);
@@ -88,7 +89,8 @@ public class ViewOptionHandlerTest {
when(outer.getView("nested")).thenReturn(nested);
}
@Test public void resolveTopLevelView() throws Exception {
@Test
void resolveTopLevelView() throws Exception {
Jenkins jenkins = mock(Jenkins.class);
try (MockedStatic<Jenkins> mocked = mockStatic(Jenkins.class)) {
mockJenkins(mocked, jenkins);
@@ -110,7 +112,8 @@ public class ViewOptionHandlerTest {
});
}
@Test public void resolveNestedView() throws Exception {
@Test
void resolveNestedView() throws Exception {
Jenkins jenkins = mock(Jenkins.class);
try (MockedStatic<Jenkins> mocked = mockStatic(Jenkins.class)) {
mockJenkins(mocked, jenkins);
@@ -120,7 +123,8 @@ public class ViewOptionHandlerTest {
}
}
@Test public void resolveOuterView() throws Exception {
@Test
void resolveOuterView() throws Exception {
Jenkins jenkins = mock(Jenkins.class);
try (MockedStatic<Jenkins> mocked = mockStatic(Jenkins.class)) {
mockJenkins(mocked, jenkins);
@@ -130,7 +134,8 @@ public class ViewOptionHandlerTest {
}
}
@Test public void ignoreLeadingAndTrailingSlashes() throws Exception {
@Test
void ignoreLeadingAndTrailingSlashes() throws Exception {
Jenkins jenkins = mock(Jenkins.class);
try (MockedStatic<Jenkins> mocked = mockStatic(Jenkins.class)) {
mockJenkins(mocked, jenkins);
@@ -140,7 +145,8 @@ public class ViewOptionHandlerTest {
}
}
@Test public void reportNonexistentTopLevelView() throws Exception {
@Test
void reportNonexistentTopLevelView() {
Jenkins jenkins = mock(Jenkins.class);
try (MockedStatic<Jenkins> mocked = mockStatic(Jenkins.class)) {
mockJenkins(mocked, jenkins);
@@ -154,7 +160,8 @@ public class ViewOptionHandlerTest {
}
}
@Test public void reportNonexistentNestedView() throws Exception {
@Test
void reportNonexistentNestedView() {
Jenkins jenkins = mock(Jenkins.class);
try (MockedStatic<Jenkins> mocked = mockStatic(Jenkins.class)) {
mockJenkins(mocked, jenkins);
@@ -168,7 +175,8 @@ public class ViewOptionHandlerTest {
}
}
@Test public void reportNonexistentInnerView() throws Exception {
@Test
void reportNonexistentInnerView() {
Jenkins jenkins = mock(Jenkins.class);
try (MockedStatic<Jenkins> mocked = mockStatic(Jenkins.class)) {
mockJenkins(mocked, jenkins);
@@ -182,7 +190,8 @@ public class ViewOptionHandlerTest {
}
}
@Test public void reportTraversingViewThatIsNotAViewGroup() throws Exception {
@Test
void reportTraversingViewThatIsNotAViewGroup() {
Jenkins jenkins = mock(Jenkins.class);
try (MockedStatic<Jenkins> mocked = mockStatic(Jenkins.class)) {
mockJenkins(mocked, jenkins);
@@ -196,7 +205,8 @@ public class ViewOptionHandlerTest {
}
}
@Test public void reportEmptyViewNameRequestAsNull() {
@Test
void reportEmptyViewNameRequestAsNull() {
Jenkins jenkins = mock(Jenkins.class);
try (MockedStatic<Jenkins> mocked = mockStatic(Jenkins.class)) {
mockJenkins(mocked, jenkins);
@@ -205,18 +215,19 @@ public class ViewOptionHandlerTest {
}
}
@Test public void reportViewSpaceNameRequestAsIAE() {
@Test
void reportViewSpaceNameRequestAsIAE() {
Jenkins jenkins = mock(Jenkins.class);
try (MockedStatic<Jenkins> mocked = mockStatic(Jenkins.class)) {
mockJenkins(mocked, jenkins);
final IllegalArgumentException e = assertThrows("No exception thrown. Expected IllegalArgumentException",
IllegalArgumentException.class, () -> assertNull(handler.getView(" ")));
final IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> assertNull(handler.getView(" ")), "No exception thrown. Expected IllegalArgumentException");
assertEquals("No view named inside view Jenkins", e.getMessage());
verifyNoInteractions(setter);
}
}
@Test public void reportNullViewAsNPE() {
@Test
void reportNullViewAsNPE() {
Jenkins jenkins = mock(Jenkins.class);
try (MockedStatic<Jenkins> mocked = mockStatic(Jenkins.class)) {
mockJenkins(mocked, jenkins);
@@ -225,7 +236,8 @@ public class ViewOptionHandlerTest {
}
}
@Test public void refuseToReadOuterView() throws Exception {
@Test
void refuseToReadOuterView() {
Jenkins jenkins = mock(Jenkins.class);
try (MockedStatic<Jenkins> mocked = mockStatic(Jenkins.class)) {
mockJenkins(mocked, jenkins);
@@ -245,7 +257,8 @@ public class ViewOptionHandlerTest {
}
}
@Test public void refuseToReadNestedView() throws Exception {
@Test
void refuseToReadNestedView() {
Jenkins jenkins = mock(Jenkins.class);
try (MockedStatic<Jenkins> mocked = mockStatic(Jenkins.class)) {
mockJenkins(mocked, jenkins);
@@ -264,7 +277,8 @@ public class ViewOptionHandlerTest {
}
}
@Test public void refuseToReadInnerView() throws Exception {
@Test
void refuseToReadInnerView() {
Jenkins jenkins = mock(Jenkins.class);
try (MockedStatic<Jenkins> mocked = mockStatic(Jenkins.class)) {
mockJenkins(mocked, jenkins);
@@ -31,19 +31,22 @@ import static org.hamcrest.Matchers.is;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public final class LineTransformationOutputStreamTest {
final class LineTransformationOutputStreamTest {
@Test public void nl() throws Exception {
@Test
void nl() throws Exception {
test("\n");
}
@Test public void crnl() throws Exception {
@Test
void crnl() throws Exception {
test("\r\n");
}
@Test public void cr() throws Exception {
@Test
void cr() throws Exception {
test("\r");
}
@@ -33,12 +33,12 @@ import org.jvnet.hudson.test.Issue;
/**
* @author Alan Harder
*/
public class UrlAnnotatorTest {
class UrlAnnotatorTest {
private ConsoleAnnotator<?> ca = new UrlAnnotator().newInstance(null);
@Test
public void testAnnotate() {
void testAnnotate() {
assertEquals("Hello &lt;foo&gt;<a href='http://foo/'>http://foo/</a>&lt;/foo&gt; Bye",
annotate("Hello <foo>http://foo/</foo> Bye"));
@@ -60,7 +60,7 @@ public class UrlAnnotatorTest {
@Test
@Issue("JENKINS-19866")
public void annotateFileScheme() {
void annotateFileScheme() {
assertEquals(
"Get this <a href='file://here/in/this/folder/'>file://here/in/this/folder/</a>.",
annotate("Get this file://here/in/this/folder/.")
@@ -26,10 +26,10 @@ package hudson.logging;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
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 java.io.IOException;
import java.util.Arrays;
@@ -38,15 +38,16 @@ import java.util.Set;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import jenkins.model.Jenkins;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.jvnet.hudson.test.Issue;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
public class LogRecorderTest {
class LogRecorderTest {
@Issue("JENKINS-17983")
@Test public void targetIncludes() {
@Test
void targetIncludes() {
assertTrue(includes("hudson", "hudson"));
assertFalse(includes("hudson", "hudsone"));
assertFalse(includes("hudson", "hudso"));
@@ -55,7 +56,8 @@ public class LogRecorderTest {
assertTrue(includes("", "hudson.model.Hudson"));
}
@Test public void targetMatches() {
@Test
void targetMatches() {
assertTrue(matches("hudson", "hudson"));
assertFalse(matches("hudson", "hudson", Level.FINE));
assertNull(matches("hudson", "hudsone"));
@@ -67,7 +69,8 @@ public class LogRecorderTest {
assertFalse(matches("", "hudson.model.Hudson", Level.FINE));
}
@Test public void testClearing() throws IOException {
@Test
void testClearing() throws IOException {
LogRecorder lr = new LogRecorder("foo");
LogRecorder.Target t = new LogRecorder.Target("", Level.FINE);
lr.getLoggers().add(t);
@@ -87,7 +90,8 @@ public class LogRecorderTest {
}
}
@Test public void testSpecificExclusion() {
@Test
void testSpecificExclusion() {
LogRecorder lr = new LogRecorder("foo");
LogRecorder.Target targetLevel0 = new LogRecorder.Target("", Level.FINE);
@@ -140,7 +144,7 @@ public class LogRecorderTest {
}
@Test
public void autocompletionTest() {
void autocompletionTest() {
List<String> loggers = Arrays.asList(
"com.company.whatever.Foo", "com.foo.Bar", "com.foo.Baz",
"org.example.app.Main", "org.example.app.impl.xml.Parser", "org.example.app.impl.xml.Validator");
@@ -161,15 +165,15 @@ public class LogRecorderTest {
isNotCandidate(candidates, "org");
isNotCandidate(candidates, "org.example");
assertEquals("expected number of items", 10, candidates.size());
assertEquals(10, candidates.size(), "expected number of items");
}
private static void isCandidate(Set<String> candidates, String candidate) {
assertTrue(candidate, candidates.contains(candidate));
assertTrue(candidates.contains(candidate), candidate);
}
private static void isNotCandidate(Set<String> candidates, String candidate) {
assertFalse(candidate, candidates.contains(candidate));
assertFalse(candidates.contains(candidate), candidate);
}
}
@@ -1,18 +1,18 @@
package hudson.model;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import java.util.Collection;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.jvnet.hudson.test.Issue;
/**
* @author kingfai
*/
public class AbstractItemTest {
class AbstractItemTest {
private static class StubAbstractItem extends AbstractItem {
@@ -37,7 +37,7 @@ public class AbstractItemTest {
}
@Test
public void testSetDisplayName() throws Exception {
void testSetDisplayName() throws Exception {
final String displayName = "testDisplayName";
StubAbstractItem i = new StubAbstractItem();
i.setDisplayName(displayName);
@@ -45,7 +45,7 @@ public class AbstractItemTest {
}
@Test
public void testGetDefaultDisplayName() {
void testGetDefaultDisplayName() {
final String name = "the item name";
StubAbstractItem i = new StubAbstractItem();
i.doSetName(name);
@@ -55,7 +55,7 @@ public class AbstractItemTest {
}
@Test
public void testSearchNameIsName() {
void testSearchNameIsName() {
final String name = "the item name jlrtlekjtekrjkjr";
StubAbstractItem i = new StubAbstractItem();
i.doSetName(name);
@@ -64,7 +64,7 @@ public class AbstractItemTest {
}
@Test
public void testGetDisplayNameOrNull() throws Exception {
void testGetDisplayNameOrNull() throws Exception {
final String projectName = "projectName";
final String displayName = "displayName";
StubAbstractItem i = new StubAbstractItem();
@@ -77,7 +77,7 @@ public class AbstractItemTest {
}
@Test
public void testSetDisplayNameOrNull() throws Exception {
void testSetDisplayNameOrNull() throws Exception {
final String projectName = "projectName";
final String displayName = "displayName";
StubAbstractItem i = new StubAbstractItem();
@@ -108,14 +108,13 @@ public class AbstractItemTest {
@Test
@Issue("JENKINS-58571")
public void renameMethodShouldThrowExceptionWhenNotIsNameEditable() {
void renameMethodShouldThrowExceptionWhenNotIsNameEditable() {
//GIVEN
NameNotEditableItem item = new NameNotEditableItem(null, "NameNotEditableItem");
//WHEN
final IOException e = assertThrows("An item with isNameEditable false must throw exception when trying to rename it.",
IOException.class, () -> item.renameTo("NewName"));
final IOException e = assertThrows(IOException.class, () -> item.renameTo("NewName"), "An item with isNameEditable false must throw exception when trying to rename it.");
assertEquals("Trying to rename an item that does not support this operation.", e.getMessage());
assertEquals("NameNotEditableItem", item.getName());
@@ -123,14 +122,13 @@ public class AbstractItemTest {
@Test
@Issue("JENKINS-58571")
public void doConfirmRenameMustThrowFormFailureWhenNotIsNameEditable() {
void doConfirmRenameMustThrowFormFailureWhenNotIsNameEditable() {
//GIVEN
NameNotEditableItem item = new NameNotEditableItem(null, "NameNotEditableItem");
//WHEN
final Failure f = assertThrows("An item with isNameEditable false must throw exception when trying to call doConfirmRename.",
Failure.class, () -> item.doConfirmRename("MyNewName"));
final Failure f = assertThrows(Failure.class, () -> item.doConfirmRename("MyNewName"), "An item with isNameEditable false must throw exception when trying to call doConfirmRename.");
assertEquals("Trying to rename an item that does not support this operation.", f.getMessage());
assertEquals("NameNotEditableItem", item.getName());
}
@@ -26,27 +26,27 @@ package hudson.model;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
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.jupiter.api.Assertions.assertArrayEquals;
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 edu.umd.cs.findbugs.annotations.NonNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.jvnet.hudson.test.Issue;
public class ActionableTest {
class ActionableTest {
private final Actionable thing = new ActionableImpl();
@SuppressWarnings("deprecation")
@Test
public void replaceAction() {
void replaceAction() {
CauseAction a1 = new CauseAction();
ParametersAction a2 = new ParametersAction();
thing.addAction(a1);
@@ -79,37 +79,37 @@ public class ActionableTest {
@Issue("JENKINS-39555")
@Test
public void testExtensionOverrides() {
void testExtensionOverrides() {
ActionableOverride myOverridden = new ActionableOverride();
InvisibleAction invis = new InvisibleAction() {
};
myOverridden.addAction(invis);
Assert.assertArrayEquals(new Object[]{invis}, myOverridden.specialActions.toArray());
Assert.assertArrayEquals(new Object[]{invis}, myOverridden.getActions().toArray());
assertArrayEquals(new Object[]{invis}, myOverridden.specialActions.toArray());
assertArrayEquals(new Object[]{invis}, myOverridden.getActions().toArray());
myOverridden.getActions().remove(invis);
Assert.assertArrayEquals(new Object[]{}, myOverridden.specialActions.toArray());
Assert.assertArrayEquals(new Object[]{}, myOverridden.getActions().toArray());
assertArrayEquals(new Object[]{}, myOverridden.specialActions.toArray());
assertArrayEquals(new Object[]{}, myOverridden.getActions().toArray());
myOverridden.addAction(invis);
myOverridden.removeAction(invis);
Assert.assertArrayEquals(new Object[]{}, myOverridden.specialActions.toArray());
Assert.assertArrayEquals(new Object[]{}, myOverridden.getActions().toArray());
assertArrayEquals(new Object[]{}, myOverridden.specialActions.toArray());
assertArrayEquals(new Object[]{}, myOverridden.getActions().toArray());
InvisibleAction invis2 = new InvisibleAction() {};
myOverridden.addOrReplaceAction(invis2);
Assert.assertArrayEquals(new Object[]{invis2}, myOverridden.specialActions.toArray());
Assert.assertArrayEquals(new Object[]{invis2}, myOverridden.getActions().toArray());
assertArrayEquals(new Object[]{invis2}, myOverridden.specialActions.toArray());
assertArrayEquals(new Object[]{invis2}, myOverridden.getActions().toArray());
myOverridden.addOrReplaceAction(invis);
myOverridden.addOrReplaceAction(invis);
Assert.assertArrayEquals(new Object[]{invis2, invis}, myOverridden.specialActions.toArray());
Assert.assertArrayEquals(new Object[]{invis2, invis}, myOverridden.getActions().toArray());
assertArrayEquals(new Object[]{invis2, invis}, myOverridden.specialActions.toArray());
assertArrayEquals(new Object[]{invis2, invis}, myOverridden.getActions().toArray());
}
@SuppressWarnings("deprecation")
@Test
public void addOrReplaceAction() {
void addOrReplaceAction() {
CauseAction a1 = new CauseAction();
ParametersAction a2 = new ParametersAction();
thing.addAction(a1);
@@ -127,7 +127,7 @@ public class ActionableTest {
@SuppressWarnings("deprecation")
@Test
public void replaceActions() {
void replaceActions() {
CauseAction a1 = new CauseAction();
ParametersAction a2 = new ParametersAction();
thing.addAction(a1);
@@ -141,7 +141,7 @@ public class ActionableTest {
@SuppressWarnings("deprecation")
@Test
public void removeAction() {
void removeAction() {
CauseAction a1 = new CauseAction();
ParametersAction a2 = new ParametersAction();
thing.addAction(a1);
@@ -157,7 +157,7 @@ public class ActionableTest {
@SuppressWarnings("deprecation")
@Test
public void removeActions() {
void removeActions() {
CauseAction a1 = new CauseAction();
ParametersAction a2 = new ParametersAction();
thing.addAction(a1);
@@ -171,7 +171,7 @@ public class ActionableTest {
@SuppressWarnings("deprecation")
@Test
public void addAction() {
void addAction() {
CauseAction a1 = new CauseAction();
ParametersAction a2 = new ParametersAction();
assertEquals(Collections.<Action>emptyList(), thing.getActions());
@@ -182,37 +182,37 @@ public class ActionableTest {
}
@Test
public void addAction_null() {
void addAction_null() {
assertThrows(IllegalArgumentException.class, () -> thing.addAction(null));
}
@Test
public void replaceAction_null() {
void replaceAction_null() {
assertThrows(IllegalArgumentException.class, () -> thing.replaceAction(null));
}
@Test
public void replaceActions_null() {
void replaceActions_null() {
assertThrows(IllegalArgumentException.class, () -> thing.replaceActions(CauseAction.class, null));
}
@Test
public void replaceActions_null_null() {
void replaceActions_null_null() {
assertThrows(IllegalArgumentException.class, () -> thing.replaceActions(null, null));
}
@Test
public void addOrReplaceAction_null() {
void addOrReplaceAction_null() {
assertThrows(IllegalArgumentException.class, () -> thing.addOrReplaceAction(null));
}
@Test
public void removeAction_null() {
void removeAction_null() {
assertFalse(thing.removeAction(null));
}
@Test
public void removeActions_null() {
void removeActions_null() {
assertThrows(IllegalArgumentException.class, () -> thing.removeActions(null));
}
@@ -1,16 +1,16 @@
package hudson.model;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* @author Kohsuke Kawaguchi
*/
public class BallColorTest {
class BallColorTest {
@Test
public void iconClassName() {
void iconClassName() {
assertEquals("icon-red", BallColor.RED.getIconClassName());
assertEquals("icon-aborted-anime", BallColor.ABORTED_ANIME.getIconClassName());
}
@@ -1,14 +1,14 @@
package hudson.model;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
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.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import hudson.model.Run.Summary;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Tests {@link Run#getBuildStatusSummary()}.
@@ -16,13 +16,13 @@ import org.junit.Test;
* @author kutzi
*/
@SuppressWarnings("rawtypes")
public class BuildStatusSummaryTest {
class BuildStatusSummaryTest {
private Run build;
private Run prevBuild;
@Before
public void before() {
@BeforeEach
void before() {
mockBuilds(Run.class);
}
@@ -36,7 +36,7 @@ public class BuildStatusSummaryTest {
}
@Test
public void testStatusUnknownIfRunIsStillBuilding() {
void testStatusUnknownIfRunIsStillBuilding() {
when(this.build.getResult()).thenReturn(null);
when(this.build.isBuilding()).thenReturn(true);
@@ -45,7 +45,7 @@ public class BuildStatusSummaryTest {
}
@Test
public void testSuccess() {
void testSuccess() {
when(this.build.getResult()).thenReturn(Result.SUCCESS);
when(this.prevBuild.getResult()).thenReturn(Result.SUCCESS);
@@ -76,7 +76,7 @@ public class BuildStatusSummaryTest {
}
@Test
public void testFixed() {
void testFixed() {
when(this.build.getResult()).thenReturn(Result.SUCCESS);
when(this.prevBuild.getResult()).thenReturn(Result.FAILURE);
@@ -95,7 +95,7 @@ public class BuildStatusSummaryTest {
}
@Test
public void testFailure() {
void testFailure() {
when(this.build.getResult()).thenReturn(Result.FAILURE);
when(this.prevBuild.getResult()).thenReturn(Result.FAILURE);
@@ -106,7 +106,7 @@ public class BuildStatusSummaryTest {
}
@Test
public void testBecameFailure() {
void testBecameFailure() {
when(this.build.getResult()).thenReturn(Result.FAILURE);
when(this.prevBuild.getResult()).thenReturn(Result.SUCCESS);
when(this.build.getPreviousNotFailedBuild()).thenReturn(this.prevBuild);
@@ -118,7 +118,7 @@ public class BuildStatusSummaryTest {
}
@Test
public void testFailureSince() {
void testFailureSince() {
when(this.build.getResult()).thenReturn(Result.FAILURE);
when(this.prevBuild.getResult()).thenReturn(Result.FAILURE);
when(this.prevBuild.getDisplayName()).thenReturn("prevBuild");
@@ -134,7 +134,7 @@ public class BuildStatusSummaryTest {
}
@Test
public void testBecameUnstable() {
void testBecameUnstable() {
when(this.build.getResult()).thenReturn(Result.UNSTABLE);
when(this.prevBuild.getResult()).thenReturn(Result.SUCCESS);
@@ -145,7 +145,7 @@ public class BuildStatusSummaryTest {
}
@Test
public void testUnstableAfterFailure() {
void testUnstableAfterFailure() {
when(this.build.getResult()).thenReturn(Result.UNSTABLE);
when(this.prevBuild.getResult()).thenReturn(Result.FAILURE);
@@ -156,7 +156,7 @@ public class BuildStatusSummaryTest {
}
@Test
public void testNonTestRelatedUnstable() {
void testNonTestRelatedUnstable() {
when(this.build.getResult()).thenReturn(Result.UNSTABLE);
when(this.prevBuild.getResult()).thenReturn(Result.UNSTABLE);
@@ -167,7 +167,7 @@ public class BuildStatusSummaryTest {
}
@Test
public void testNonTestRelatedBecameUnstable() {
void testNonTestRelatedBecameUnstable() {
when(this.build.getResult()).thenReturn(Result.UNSTABLE);
when(this.prevBuild.getResult()).thenReturn(Result.SUCCESS);
@@ -178,7 +178,7 @@ public class BuildStatusSummaryTest {
}
@Test
public void testAborted() {
void testAborted() {
when(this.build.getResult()).thenReturn(Result.ABORTED);
Summary summary = this.build.getBuildStatusSummary();
@@ -187,7 +187,7 @@ public class BuildStatusSummaryTest {
}
@Test
public void testNotBuilt() {
void testNotBuilt() {
when(this.build.getResult()).thenReturn(Result.NOT_BUILT);
Summary summary = this.build.getBuildStatusSummary();
@@ -2,19 +2,20 @@ package hudson.model;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
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.assertFalse;
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 hudson.util.FormValidation;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.jvnet.hudson.test.Issue;
public class ChoiceParameterDefinitionTest {
class ChoiceParameterDefinitionTest {
@Test
public void shouldValidateChoices() {
void shouldValidateChoices() {
assertFalse(ChoiceParameterDefinition.areValidChoices(""));
assertFalse(ChoiceParameterDefinition.areValidChoices(" "));
assertTrue(ChoiceParameterDefinition.areValidChoices("abc"));
@@ -23,7 +24,7 @@ public class ChoiceParameterDefinitionTest {
}
@Test
public void testCheckChoices() {
void testCheckChoices() {
ChoiceParameterDefinition.DescriptorImpl descriptorImpl = new ChoiceParameterDefinition.DescriptorImpl();
assertEquals(FormValidation.Kind.OK, descriptorImpl.doCheckChoices("abc\ndef").kind);
@@ -32,13 +33,13 @@ public class ChoiceParameterDefinitionTest {
@Test
@Issue("JENKINS-60721")
public void testNullDefaultParameter() {
void testNullDefaultParameter() {
ChoiceParameterDefinition param = new ChoiceParameterDefinition("name", new String[0], null);
assertNull(param.getDefaultParameterValue());
}
@Test
public void createNullChoice() {
void createNullChoice() {
String stringValue = null;
String[] choices = new String[]{stringValue};
assertCreation(stringValue, choices, true);
@@ -46,14 +47,14 @@ public class ChoiceParameterDefinitionTest {
@Test
@Issue("JENKINS-62889")
public void checkValue_Null() {
void checkValue_Null() {
String stringValue = null;
String[] choices = new String[]{stringValue};
assertCheckValue(stringValue, choices, true);
}
@Test
public void createBlankChoice() {
void createBlankChoice() {
String stringValue = "";
String[] choices = new String[]{stringValue};
assertCreation(stringValue, choices, true);
@@ -61,14 +62,14 @@ public class ChoiceParameterDefinitionTest {
@Test
@Issue("JENKINS-62889")
public void checkValue_Blank() {
void checkValue_Blank() {
String stringValue = "";
String[] choices = new String[]{stringValue};
assertCheckValue(stringValue, choices, true);
}
@Test
public void createEmptyChoice() {
void createEmptyChoice() {
String stringValue = " ";
String[] choices = new String[]{stringValue};
assertCreation(stringValue, choices, true);
@@ -76,7 +77,7 @@ public class ChoiceParameterDefinitionTest {
@Test
@Issue("JENKINS-62889")
public void checkValue_Empty() {
void checkValue_Empty() {
String stringValue = "";
String[] choices = new String[]{stringValue};
assertCheckValue(stringValue, choices, true);
@@ -84,7 +85,7 @@ public class ChoiceParameterDefinitionTest {
@Test
@Issue("JENKINS-62889")
public void checkValue_Single() {
void checkValue_Single() {
String stringValue = "single";
String[] choices = new String[]{stringValue};
assertCheckValue(stringValue, choices, true);
@@ -92,7 +93,7 @@ public class ChoiceParameterDefinitionTest {
@Test
@Issue("JENKINS-62889")
public void checkValue_Multiple() {
void checkValue_Multiple() {
String[] choices = new String[]{"one", "two", "three"};
ChoiceParameterDefinition parameterDefinition = new ChoiceParameterDefinition("name", choices, "description");
for (String choiceValue : choices) {
@@ -103,7 +104,7 @@ public class ChoiceParameterDefinitionTest {
@Test
@Issue("JENKINS-62889")
public void checkValue_Invalid() {
void checkValue_Invalid() {
String stringValue = "single";
String[] choices = new String[]{stringValue};
ChoiceParameterDefinition parameterDefinition = new ChoiceParameterDefinition("name", choices, "description");
@@ -113,7 +114,7 @@ public class ChoiceParameterDefinitionTest {
@Test
@Issue("JENKINS-62889")
public void checkValue_WrongValueType() {
void checkValue_WrongValueType() {
String stringValue = "single";
String[] choices = new String[]{stringValue};
ChoiceParameterDefinition parameterDefinition = new ChoiceParameterDefinition("name", choices, "description");
@@ -123,7 +124,7 @@ public class ChoiceParameterDefinitionTest {
@Test
@Issue("JENKINS-62889")
public void createValue_Invalid() {
void createValue_Invalid() {
String stringValue = "single";
String[] choices = new String[]{stringValue};
ChoiceParameterDefinition parameterDefinition = new ChoiceParameterDefinition("name", choices, "description");
@@ -2,8 +2,8 @@ package hudson.model;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
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.FilePath;
import hudson.security.ACL;
@@ -13,16 +13,17 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import jenkins.model.Jenkins;
import jenkins.util.SetContextClassLoader;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.jvnet.hudson.test.Issue;
import org.springframework.security.core.Authentication;
/**
* @author Kohsuke Kawaguchi
*/
public class ComputerTest {
class ComputerTest {
@Test
public void testRelocate() throws Exception {
void testRelocate() throws Exception {
File d = File.createTempFile("jenkins", "test");
FilePath dir = new FilePath(d);
try {
@@ -43,14 +44,14 @@ public class ComputerTest {
@Issue("JENKINS-50296")
@Test
public void testThreadPoolForRemotingActsAsSystemUser() throws InterruptedException, ExecutionException {
void testThreadPoolForRemotingActsAsSystemUser() throws InterruptedException, ExecutionException {
Future<Authentication> job = Computer.threadPoolForRemoting.submit(Jenkins::getAuthentication2);
assertThat(job.get(), is(ACL.SYSTEM2));
}
@Issue("JENKINS-72796")
@Test
public void testThreadPoolForRemotingContextClassLoaderIsSet() throws Exception {
void testThreadPoolForRemotingContextClassLoaderIsSet() throws Exception {
// as the threadpool is cached, any other tests here pollute this test so we need enough threads to
// avoid any cached.
final int numThreads = 5;
@@ -24,15 +24,15 @@
package hudson.model;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class DisplayNameListenerTest {
class DisplayNameListenerTest {
@Test
public void testOnCopied() throws Exception {
void testOnCopied() throws Exception {
DisplayNameListener listener = new DisplayNameListener();
StubJob src = new StubJob();
src.doSetName("src");
@@ -49,7 +49,7 @@ public class DisplayNameListenerTest {
}
@Test
public void testOnRenamedOldNameEqualsDisplayName() throws Exception {
void testOnRenamedOldNameEqualsDisplayName() throws Exception {
DisplayNameListener listener = new DisplayNameListener();
final String oldName = "old job name";
final String newName = "new job name";
@@ -63,7 +63,7 @@ public class DisplayNameListenerTest {
}
@Test
public void testOnRenamedOldNameNotEqualDisplayName() throws Exception {
void testOnRenamedOldNameNotEqualDisplayName() throws Exception {
DisplayNameListener listener = new DisplayNameListener();
final String oldName = "old job name";
final String newName = "new job name";
@@ -1,15 +1,15 @@
package hudson.model;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.EnvVars;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class EnvironmentContributingActionTest {
class EnvironmentContributingActionTest {
static class OverrideRun extends InvisibleAction implements EnvironmentContributingAction {
private boolean wasCalled = false;
@@ -64,7 +64,7 @@ public class EnvironmentContributingActionTest {
private final EnvVars envVars = mock(EnvVars.class);
@Test
public void testOverrideRunMethodAndCallNewMethod() {
void testOverrideRunMethodAndCallNewMethod() {
Run<?, ?> run = mock(Run.class);
OverrideRun overrideRun = new OverrideRun();
@@ -78,7 +78,7 @@ public class EnvironmentContributingActionTest {
*/
@Test
@SuppressWarnings("deprecation")
public void testOverrideRunMethodAndCallDeprecatedMethod() {
void testOverrideRunMethodAndCallDeprecatedMethod() {
AbstractBuild<?, ?> abstractBuild = mock(AbstractBuild.class);
when(abstractBuild.getBuiltOn()).thenReturn(mock(Node.class));
@@ -92,7 +92,7 @@ public class EnvironmentContributingActionTest {
* {@link AbstractBuild} should work as before.
*/
@Test
public void testOverrideAbstractBuildAndCallNewMethodWithAbstractBuild() {
void testOverrideAbstractBuildAndCallNewMethodWithAbstractBuild() {
AbstractBuild<?, ?> abstractBuild = mock(AbstractBuild.class);
OverrideAbstractBuild action = new OverrideAbstractBuild();
@@ -105,7 +105,7 @@ public class EnvironmentContributingActionTest {
* {@link Run} should not execute method that was overridden for {@link AbstractBuild}.
*/
@Test
public void testOverrideAbstractBuildAndCallNewMethodWithRun() {
void testOverrideAbstractBuildAndCallNewMethodWithRun() {
Run<?, ?> run = mock(Run.class);
OverrideAbstractBuild action = new OverrideAbstractBuild();
@@ -118,7 +118,7 @@ public class EnvironmentContributingActionTest {
* If someone wants to use overridden deprecated method, it would still work.
*/
@Test
public void testOverrideAbstractBuildAndCallDeprecatedMethod() {
void testOverrideAbstractBuildAndCallDeprecatedMethod() {
AbstractBuild<?, ?> abstractBuild = mock(AbstractBuild.class);
OverrideAbstractBuild overrideRun = new OverrideAbstractBuild();
@@ -128,7 +128,7 @@ public class EnvironmentContributingActionTest {
}
@Test
public void testOverrideBothAndCallNewMethod() {
void testOverrideBothAndCallNewMethod() {
Run<?, ?> run = mock(Run.class);
OverrideBoth overrideRun = new OverrideBoth();
@@ -138,7 +138,7 @@ public class EnvironmentContributingActionTest {
}
@Test
public void testOverrideBothAndCallDeprecatedMethod() {
void testOverrideBothAndCallDeprecatedMethod() {
AbstractBuild<?, ?> abstractBuild = mock(AbstractBuild.class);
OverrideBoth overrideRun = new OverrideBoth();
@@ -24,30 +24,32 @@
package hudson.model;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.io.File;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.jvnet.hudson.test.Issue;
/**
* Test for {@link FileParameterValue}.
* @author Oleg Nenashev
*/
public class FileParameterValueTest {
class FileParameterValueTest {
@Issue("JENKINS-19017")
@Test public void compareParamsWithSameName() {
@Test
void compareParamsWithSameName() {
final String paramName = "MY_FILE_PARAM"; // Same paramName (location) reproduces the bug
final FileParameterValue param1 = new FileParameterValue(paramName, new File("ws_param1.txt"), "param1.txt");
final FileParameterValue param2 = new FileParameterValue(paramName, new File("ws_param2.txt"), "param2.txt");
assertNotEquals("Files with same locations should be considered as different", param1, param2);
assertNotEquals("Files with same locations should be considered as different", param2, param1);
assertNotEquals(param1, param2, "Files with same locations should be considered as different");
assertNotEquals(param2, param1, "Files with same locations should be considered as different");
}
@Test public void compareNullParams() {
@Test
void compareNullParams() {
final String paramName = "MY_FILE_PARAM";
FileParameterValue nonNullParam = new FileParameterValue(paramName, new File("ws_param1.txt"), "param1.txt");
FileParameterValue nullParam1 = new FileParameterValue(null, new File("null_param1.txt"), "null_param1.txt");
@@ -27,27 +27,24 @@ package hudson.model;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals;
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.assertEquals;
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.model.Fingerprint.RangeSet;
import java.io.File;
import jenkins.fingerprints.FileFingerprintStorage;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.Test;
/**
* @author Kohsuke Kawaguchi
*/
public class FingerprintTest {
class FingerprintTest {
@Rule public TemporaryFolder tmp = new TemporaryFolder();
@Test public void rangeSet() {
@Test
void rangeSet() {
RangeSet rs = new RangeSet();
assertFalse(rs.includes(0));
assertFalse(rs.includes(3));
@@ -79,7 +76,8 @@ public class FingerprintTest {
assertEquals("[3,7),[9,11)", rs.toString());
}
@Test public void merge() {
@Test
void merge() {
RangeSet x = new RangeSet();
x.add(1);
x.add(2);
@@ -98,7 +96,8 @@ public class FingerprintTest {
assertEquals("[1,7)", x.toString());
}
@Test public void merge2() {
@Test
void merge2() {
RangeSet x = new RangeSet();
x.add(1);
x.add(2);
@@ -115,7 +114,8 @@ public class FingerprintTest {
assertEquals("[1,7)", x.toString());
}
@Test public void merge3() {
@Test
void merge3() {
RangeSet x = new RangeSet();
x.add(1);
x.add(5);
@@ -132,7 +132,7 @@ public class FingerprintTest {
}
@Test
public void retainAll1() {
void retainAll1() {
RangeSet x = new RangeSet();
RangeSet y = new RangeSet();
@@ -148,7 +148,7 @@ public class FingerprintTest {
}
@Test
public void retainAll2() {
void retainAll2() {
RangeSet x = new RangeSet();
RangeSet y = new RangeSet();
@@ -164,7 +164,7 @@ public class FingerprintTest {
}
@Test
public void retainAll3() {
void retainAll3() {
RangeSet x = new RangeSet();
RangeSet y = new RangeSet();
@@ -175,7 +175,7 @@ public class FingerprintTest {
}
@Test
public void removeAll1() {
void removeAll1() {
RangeSet x = new RangeSet();
RangeSet y = new RangeSet();
@@ -191,7 +191,7 @@ public class FingerprintTest {
}
@Test
public void removeAll2() {
void removeAll2() {
RangeSet x = new RangeSet();
RangeSet y = new RangeSet();
@@ -207,7 +207,7 @@ public class FingerprintTest {
}
@Test
public void removeAll3() {
void removeAll3() {
RangeSet x = new RangeSet();
RangeSet y = new RangeSet();
@@ -216,7 +216,8 @@ public class FingerprintTest {
assertFalse(x.removeAll(y));
}
@Test public void deserialize() throws Exception {
@Test
void deserialize() throws Exception {
assertEquals("Fingerprint["
+ "original=stapler/org.kohsuke.stapler:stapler-jelly #123,"
+ "hash=069484c9e963cc615c51278327da8eab,"
@@ -227,14 +228,16 @@ public class FingerprintTest {
FileFingerprintStorage.load(new File(FingerprintTest.class.getResource("fingerprint.xml").toURI())).toString());
}
@Test public void loadFingerprintWithoutUsages() throws Exception {
@Test
void loadFingerprintWithoutUsages() throws Exception {
Fingerprint fp = FileFingerprintStorage.load(new File(FingerprintTest.class.getResource("fingerprintWithoutUsages.xml").toURI()));
assertNotNull(fp);
assertEquals("test:jenkinsfile-example-1.0-SNAPSHOT.jar", fp.getFileName());
assertNotNull(fp.getUsages());
}
@Test public void fromString() {
@Test
void fromString() {
//
// Single
//
+11 -10
View File
@@ -1,24 +1,24 @@
package hudson.model;
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 static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
/**
* @author <a href="mailto:nicolas.deloof@gmail.com">Nicolas De Loof</a>
*/
public class ItemsTest {
class ItemsTest {
private static ItemGroup<?> root;
private static ItemGroup<?> foo;
private static ItemGroup<?> foo_bar;
@BeforeClass
public static void itemGroups() {
@BeforeAll
static void itemGroups() {
root = mock(ItemGroup.class);
when(root.getFullName()).thenReturn("");
@@ -30,7 +30,7 @@ public class ItemsTest {
}
@Test
public void getCanonicalName() {
void getCanonicalName() {
assertEquals("foo", Items.getCanonicalName(root, "foo"));
assertEquals("foo", Items.getCanonicalName(root, "/foo"));
assertEquals("foo/bar", Items.getCanonicalName(root, "foo/bar"));
@@ -52,7 +52,7 @@ public class ItemsTest {
}
@Test
public void computeRelativeNamesAfterRenaming() {
void computeRelativeNamesAfterRenaming() {
assertEquals("meu,bu,zo", Items.computeRelativeNamesAfterRenaming("ga", "meu", "ga,bu,zo", root));
assertEquals("ga,bu,zo", Items.computeRelativeNamesAfterRenaming("ga", "meu", "ga,bu,zo", foo_bar));
assertEquals("meu,bu,zo", Items.computeRelativeNamesAfterRenaming("foo/ga", "foo/meu", "ga,bu,zo", foo));
@@ -79,7 +79,8 @@ public class ItemsTest {
assertEquals("/foo/sister", Items.computeRelativeNamesAfterRenaming("fooq", "foo", "/fooq/sister", foo));
}
@Test public void getRelativeNameFrom() {
@Test
void getRelativeNameFrom() {
assertEquals("foo", Items.getRelativeNameFrom("foo", ""));
assertEquals("foo/bar", Items.getRelativeNameFrom("foo/bar", ""));
assertEquals("../bar", Items.getRelativeNameFrom("bar", "foo"));
+8 -8
View File
@@ -2,22 +2,22 @@ package hudson.model;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mockStatic;
import hudson.EnvVars;
import hudson.Platform;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.jvnet.hudson.test.Issue;
import org.mockito.ArgumentMatchers;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
public class JobTest {
class JobTest {
@Test
public void testSetDisplayName() throws Exception {
void testSetDisplayName() throws Exception {
final String displayName = "testSetDisplayName";
StubJob j = new StubJob();
@@ -29,7 +29,7 @@ public class JobTest {
}
@Test
public void testSetDisplayNameZeroLength() throws Exception {
void testSetDisplayNameZeroLength() throws Exception {
StubJob j = new StubJob();
// call setDisplayNameFromRequest
j.setDisplayNameOrNull("");
@@ -40,8 +40,8 @@ public class JobTest {
@Issue("JENKINS-14807")
@Test
@Ignore("Test doesn't work with static state, needs rethinking / removing")
public void use_agent_platform_path_separator_when_contribute_path() throws Throwable {
@Disabled("Test doesn't work with static state, needs rethinking / removing")
void use_agent_platform_path_separator_when_contribute_path() throws Throwable {
// mock environment to simulate EnvVars of agent node with different platform than master
Platform agentPlatform = Platform.current() == Platform.UNIX ? Platform.WINDOWS : Platform.UNIX;
EnvVars emptyEnv;
@@ -24,7 +24,7 @@
package hudson.model;
import static org.junit.Assume.assumeFalse;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import hudson.Functions;
import hudson.model.MultiStageTimeSeries.TimeScale;
@@ -37,16 +37,16 @@ import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import javax.imageio.ImageIO;
import org.jfree.chart.JFreeChart;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* @author Kohsuke Kawaguchi
*/
public class LoadStatisticsTest {
class LoadStatisticsTest {
@Test
public void graph() throws IOException {
assumeFalse("TODO: Implement this test on Windows", Functions.isWindows());
void graph() throws IOException {
assumeFalse(Functions.isWindows(), "TODO: Implement this test on Windows");
LoadStatistics ls = new LoadStatistics(0, 0) {
@Override
protected Iterable<Node> getNodes() {
@@ -1,15 +1,15 @@
package hudson.model;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import hudson.util.Secret;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class ParameterDefinitionTest {
class ParameterDefinitionTest {
@Test
public void compareStringParameterDefinition() {
void compareStringParameterDefinition() {
StringParameterDefinition spd = new StringParameterDefinition("spd", "default");
StringParameterDefinition spdSame = new StringParameterDefinition("spd", "default");
StringParameterDefinition spdOther = new StringParameterDefinition("spdOther", "default");
@@ -46,7 +46,7 @@ public class ParameterDefinitionTest {
}
@Test
public void compareBooleanParameterDefinition() {
void compareBooleanParameterDefinition() {
BooleanParameterDefinition bpd = new BooleanParameterDefinition("bpd", false, "desc");
BooleanParameterDefinition bpdSame = new BooleanParameterDefinition("bpd", false, "desc");
BooleanParameterDefinition bpdOther = new BooleanParameterDefinition("bpd", true, "desc");
@@ -63,7 +63,7 @@ public class ParameterDefinitionTest {
}
@Test
public void compareChoiceParameterDefinition() {
void compareChoiceParameterDefinition() {
ChoiceParameterDefinition cpd = new ChoiceParameterDefinition("bpd", new String[]{"1", "2", "3"}, "desc");
ChoiceParameterDefinition cpdSame = new ChoiceParameterDefinition("bpd", new String[]{"1", "2", "3"}, "desc");
ChoiceParameterDefinition cpdOther = new ChoiceParameterDefinition("bpd", new String[]{"1", "3", "2"}, "desc");
@@ -80,7 +80,7 @@ public class ParameterDefinitionTest {
}
@Test
public void comparePasswordParameterDefinition() {
void comparePasswordParameterDefinition() {
PasswordParameterDefinition ppd = new PasswordParameterDefinition("ppd", Secret.fromString("password"), "desc");
PasswordParameterDefinition ppdSame = new PasswordParameterDefinition("ppd", Secret.fromString("password"), "desc");
PasswordParameterDefinition ppdOther = new PasswordParameterDefinition("ppd", Secret.fromString("password1"), "desc");
@@ -97,7 +97,7 @@ public class ParameterDefinitionTest {
}
@Test
public void compareFileParameterDefinition() {
void compareFileParameterDefinition() {
FileParameterDefinition fpd = new FileParameterDefinition("fpd", "desc");
FileParameterDefinition fpdSame = new FileParameterDefinition("fpd", "desc");
FileParameterDefinition fpdOther = new FileParameterDefinition("fpdOther", "desc");
@@ -114,7 +114,7 @@ public class ParameterDefinitionTest {
}
@Test
public void compareRunParameterDefinition() {
void compareRunParameterDefinition() {
RunParameterDefinition rpd = new RunParameterDefinition("rpd", "project", "desc", RunParameterDefinition.RunParameterFilter.ALL);
RunParameterDefinition rpdSame = new RunParameterDefinition("rpd", "project", "desc", RunParameterDefinition.RunParameterFilter.ALL);
RunParameterDefinition rpdOther = new RunParameterDefinition("rpd", "project1", "desc", RunParameterDefinition.RunParameterFilter.STABLE);
@@ -132,7 +132,7 @@ public class ParameterDefinitionTest {
}
@Test
public void compareChildsWithoutEqualsAndHashCode() {
void compareChildsWithoutEqualsAndHashCode() {
ExtendStringParameterDefinition epd = new ExtendStringParameterDefinition("epd", "default", "desc");
ExtendStringParameterDefinition epdSame = new ExtendStringParameterDefinition("epd", "default", "desc");
ExtendStringParameterDefinition epdOther = new ExtendStringParameterDefinition("epd", "default1", "desc");
@@ -1,8 +1,8 @@
package hudson.model;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
import hudson.EnvVars;
@@ -10,24 +10,24 @@ import hudson.model.queue.SubTask;
import hudson.tasks.BuildWrapper;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.jvnet.hudson.test.Issue;
public class ParametersActionTest {
class ParametersActionTest {
private ParametersAction baseParamsAB;
private StringParameterValue baseA;
@Before
public void setUp() {
@BeforeEach
void setUp() {
baseA = new StringParameterValue("a", "base-a");
StringParameterValue baseB = new StringParameterValue("b", "base-b");
baseParamsAB = new ParametersAction(baseA, baseB);
}
@Test
public void mergeShouldOverrideParameters() {
void mergeShouldOverrideParameters() {
StringParameterValue overrideB = new StringParameterValue("b", "override-b");
ParametersAction extraParams = new ParametersAction(overrideB);
@@ -40,7 +40,7 @@ public class ParametersActionTest {
}
@Test
public void mergeShouldCombineDisparateParameters() {
void mergeShouldCombineDisparateParameters() {
StringParameterValue overrideB = new StringParameterValue("b", "override-b");
ParametersAction extraParams = new ParametersAction(overrideB);
@@ -53,7 +53,7 @@ public class ParametersActionTest {
}
@Test
public void mergeShouldHandleEmptyOverrides() {
void mergeShouldHandleEmptyOverrides() {
ParametersAction params = baseParamsAB.merge(new ParametersAction());
StringParameterValue a = (StringParameterValue) params.getParameter("a");
@@ -61,7 +61,7 @@ public class ParametersActionTest {
}
@Test
public void mergeShouldHandleNullOverrides() {
void mergeShouldHandleNullOverrides() {
ParametersAction params = baseParamsAB.merge(null);
StringParameterValue a = (StringParameterValue) params.getParameter("a");
@@ -69,7 +69,7 @@ public class ParametersActionTest {
}
@Test
public void mergeShouldReturnNewInstanceWithOverride() {
void mergeShouldReturnNewInstanceWithOverride() {
StringParameterValue overrideA = new StringParameterValue("a", "override-a");
ParametersAction overrideParams = new ParametersAction(overrideA);
@@ -79,7 +79,7 @@ public class ParametersActionTest {
}
@Test
public void createUpdatedShouldReturnNewInstanceWithNullOverride() {
void createUpdatedShouldReturnNewInstanceWithNullOverride() {
ParametersAction params = baseParamsAB.createUpdated(null);
assertNotSame(baseParamsAB, params);
@@ -87,7 +87,7 @@ public class ParametersActionTest {
@Test
@Issue("JENKINS-15094")
public void checkNullParameterValues() {
void checkNullParameterValues() {
SubTask subtask = mock(SubTask.class);
Build build = mock(Build.class);
+17 -14
View File
@@ -7,33 +7,36 @@ import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.jvnet.hudson.test.Issue;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.StaplerResponse2;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
@RunWith(MockitoJUnitRunner.class)
public class QueueTest {
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class QueueTest {
@Mock
StaplerResponse2 resp;
private StaplerResponse2 resp;
@Mock
Queue.Task task;
private Queue.Task task;
@Mock
PrintWriter writer;
private PrintWriter writer;
@Before
public void setup() throws IOException {
@BeforeEach
void setup() throws IOException {
when(resp.getWriter()).thenReturn(writer);
}
@Issue("JENKINS-21311")
@Test
public void cancelItemOnaValidItemShouldReturnA204() throws IOException, ServletException {
void cancelItemOnaValidItemShouldReturnA204() throws IOException, ServletException {
when(task.hasAbortPermission()).thenReturn(true);
Queue queue = new Queue(LoadBalancer.CONSISTENT_HASH);
long id = queue.schedule(task, 6000).getId();
@@ -46,7 +49,7 @@ public class QueueTest {
@Issue("JENKINS-21311")
@Test
public void cancelItemOnANonExistingItemShouldReturnA404() throws IOException, ServletException {
void cancelItemOnANonExistingItemShouldReturnA404() throws IOException, ServletException {
Queue queue = new Queue(LoadBalancer.CONSISTENT_HASH);
long id = queue.schedule(task, 6000).getId();
@@ -58,7 +61,7 @@ public class QueueTest {
@Issue("JENKINS-21311")
@Test
public void cancelItemOnANonCancellableItemShouldReturnA422() throws IOException, ServletException {
void cancelItemOnANonCancellableItemShouldReturnA422() throws IOException, ServletException {
when(task.hasAbortPermission()).thenReturn(false);
Queue queue = new Queue(LoadBalancer.CONSISTENT_HASH);
long id = queue.schedule(task, 6000).getId();
@@ -24,17 +24,17 @@
package hudson.model;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Random;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* @author Stephen Connolly
*/
public class ResourceListTest {
class ResourceListTest {
private Resource a1, a2, a3, a4, a;
private Resource b1, b2, b3, b4, b;
@@ -46,8 +46,8 @@ public class ResourceListTest {
private ResourceList y;
private ResourceList z;
@Before
public void setUp() {
@BeforeEach
void setUp() {
entropy = new Random(0);
a = new Resource("A" + entropy.nextLong());
a1 = new Resource(a, "A" + entropy.nextLong());
@@ -74,48 +74,48 @@ public class ResourceListTest {
}
@Test
public void emptyLists() {
void emptyLists() {
z.r(a);
ResourceList w = new ResourceList();
w.w(a);
assertFalse("Empty vs Empty", x.isCollidingWith(y));
assertFalse("Empty vs Empty", y.isCollidingWith(x));
assertFalse("Empty vs Read", x.isCollidingWith(z));
assertFalse("Read vs Empty", z.isCollidingWith(x));
assertFalse("Empty vs Write", x.isCollidingWith(w));
assertFalse("Write vs Empty", w.isCollidingWith(x));
assertFalse(x.isCollidingWith(y), "Empty vs Empty");
assertFalse(y.isCollidingWith(x), "Empty vs Empty");
assertFalse(x.isCollidingWith(z), "Empty vs Read");
assertFalse(z.isCollidingWith(x), "Read vs Empty");
assertFalse(x.isCollidingWith(w), "Empty vs Write");
assertFalse(w.isCollidingWith(x), "Write vs Empty");
}
@Test
public void simpleR() {
void simpleR() {
x.r(a);
y.r(b);
z.r(a);
assertFalse("Read-Read", x.isCollidingWith(y));
assertFalse("Read-Read", y.isCollidingWith(x));
assertFalse("Read-Read", x.isCollidingWith(z));
assertFalse("Read-Read", z.isCollidingWith(x));
assertFalse("Read-Read", z.isCollidingWith(y));
assertFalse("Read-Read", y.isCollidingWith(z));
assertFalse(x.isCollidingWith(y), "Read-Read");
assertFalse(y.isCollidingWith(x), "Read-Read");
assertFalse(x.isCollidingWith(z), "Read-Read");
assertFalse(z.isCollidingWith(x), "Read-Read");
assertFalse(z.isCollidingWith(y), "Read-Read");
assertFalse(y.isCollidingWith(z), "Read-Read");
}
@Test
public void simpleRW() {
void simpleRW() {
x.r(a);
y.r(b);
z.w(a);
assertFalse("Read-Read different resources", x.isCollidingWith(y));
assertFalse("Read-Read different resources", y.isCollidingWith(x));
assertTrue("Read-Write same resource", x.isCollidingWith(z));
assertTrue("Read-Write same resource", z.isCollidingWith(x));
assertFalse("Read-Write different resources", z.isCollidingWith(y));
assertFalse("Read-Write different resources", y.isCollidingWith(z));
assertFalse(x.isCollidingWith(y), "Read-Read different resources");
assertFalse(y.isCollidingWith(x), "Read-Read different resources");
assertTrue(x.isCollidingWith(z), "Read-Write same resource");
assertTrue(z.isCollidingWith(x), "Read-Write same resource");
assertFalse(z.isCollidingWith(y), "Read-Write different resources");
assertFalse(y.isCollidingWith(z), "Read-Write different resources");
}
@Test
public void simpleW() {
void simpleW() {
x.w(a);
y.w(b);
z.w(a);
@@ -138,144 +138,144 @@ public class ResourceListTest {
}
@Test
public void parentChildR() {
void parentChildR() {
x.r(a1);
x.r(a2);
y.r(a3);
y.r(a4);
z.r(a);
assertFalse("Reads should never conflict", x.isCollidingWith(y));
assertFalse("Reads should never conflict", y.isCollidingWith(x));
assertFalse("Reads should never conflict", x.isCollidingWith(z));
assertFalse("Reads should never conflict", z.isCollidingWith(x));
assertFalse("Reads should never conflict", z.isCollidingWith(y));
assertFalse("Reads should never conflict", y.isCollidingWith(z));
assertFalse(x.isCollidingWith(y), "Reads should never conflict");
assertFalse(y.isCollidingWith(x), "Reads should never conflict");
assertFalse(x.isCollidingWith(z), "Reads should never conflict");
assertFalse(z.isCollidingWith(x), "Reads should never conflict");
assertFalse(z.isCollidingWith(y), "Reads should never conflict");
assertFalse(y.isCollidingWith(z), "Reads should never conflict");
}
@Test
public void parentChildW() {
void parentChildW() {
x.w(a1);
x.w(a2);
y.w(a3);
y.w(a4);
z.w(a);
assertFalse("Sibling resources should not conflict", x.isCollidingWith(y));
assertFalse("Sibling resources should not conflict", y.isCollidingWith(x));
assertTrue("Taking parent resource assumes all children are taken too", x.isCollidingWith(z));
assertTrue("Taking parent resource assumes all children are taken too", z.isCollidingWith(x));
assertTrue("Taking parent resource assumes all children are taken too", z.isCollidingWith(y));
assertTrue("Taking parent resource assumes all children are taken too", y.isCollidingWith(z));
assertFalse(x.isCollidingWith(y), "Sibling resources should not conflict");
assertFalse(y.isCollidingWith(x), "Sibling resources should not conflict");
assertTrue(x.isCollidingWith(z), "Taking parent resource assumes all children are taken too");
assertTrue(z.isCollidingWith(x), "Taking parent resource assumes all children are taken too");
assertTrue(z.isCollidingWith(y), "Taking parent resource assumes all children are taken too");
assertTrue(y.isCollidingWith(z), "Taking parent resource assumes all children are taken too");
}
@Test
public void parentChildR3() {
void parentChildR3() {
x.r(c1);
x.r(c2);
y.r(c3);
y.r(c4);
z.r(c);
assertFalse("Reads should never conflict", x.isCollidingWith(y));
assertFalse("Reads should never conflict", y.isCollidingWith(x));
assertFalse("Reads should never conflict", x.isCollidingWith(z));
assertFalse("Reads should never conflict", z.isCollidingWith(x));
assertFalse("Reads should never conflict", z.isCollidingWith(y));
assertFalse("Reads should never conflict", y.isCollidingWith(z));
assertFalse(x.isCollidingWith(y), "Reads should never conflict");
assertFalse(y.isCollidingWith(x), "Reads should never conflict");
assertFalse(x.isCollidingWith(z), "Reads should never conflict");
assertFalse(z.isCollidingWith(x), "Reads should never conflict");
assertFalse(z.isCollidingWith(y), "Reads should never conflict");
assertFalse(y.isCollidingWith(z), "Reads should never conflict");
}
@Test
public void parentChildW3() {
void parentChildW3() {
x.w(c1);
x.w(c2);
y.w(c3);
y.w(c4);
z.w(c);
assertFalse("Sibling resources should not conflict", x.isCollidingWith(y));
assertFalse("Sibling resources should not conflict", y.isCollidingWith(x));
assertFalse("Using less than the limit of child resources should not be a problem", x.isCollidingWith(z));
assertFalse("Using less than the limit of child resources should not be a problem", z.isCollidingWith(x));
assertFalse("Using less than the limit of child resources should not be a problem", z.isCollidingWith(y));
assertFalse("Using less than the limit of child resources should not be a problem", y.isCollidingWith(z));
assertFalse(x.isCollidingWith(y), "Sibling resources should not conflict");
assertFalse(y.isCollidingWith(x), "Sibling resources should not conflict");
assertFalse(x.isCollidingWith(z), "Using less than the limit of child resources should not be a problem");
assertFalse(z.isCollidingWith(x), "Using less than the limit of child resources should not be a problem");
assertFalse(z.isCollidingWith(y), "Using less than the limit of child resources should not be a problem");
assertFalse(y.isCollidingWith(z), "Using less than the limit of child resources should not be a problem");
ResourceList w = ResourceList.union(x, y);
assertFalse("Using less than the limit of child resources should not be a problem", w.isCollidingWith(z));
assertFalse("Using less than the limit of child resources should not be a problem", z.isCollidingWith(w));
assertFalse(w.isCollidingWith(z), "Using less than the limit of child resources should not be a problem");
assertFalse(z.isCollidingWith(w), "Using less than the limit of child resources should not be a problem");
assertFalse("Total count = 2, limit is 3", w.isCollidingWith(x));
assertFalse("Total count = 2, limit is 3", x.isCollidingWith(w));
assertFalse(w.isCollidingWith(x), "Total count = 2, limit is 3");
assertFalse(x.isCollidingWith(w), "Total count = 2, limit is 3");
ResourceList v = ResourceList.union(x, x); // write count is two
assertFalse("Total count = 3, limit is 3", v.isCollidingWith(x));
assertFalse("Total count = 3, limit is 3", x.isCollidingWith(v));
assertFalse(v.isCollidingWith(x), "Total count = 3, limit is 3");
assertFalse(x.isCollidingWith(v), "Total count = 3, limit is 3");
v = ResourceList.union(v, x); // write count is three
assertTrue("Total count = 4, limit is 3", v.isCollidingWith(x));
assertTrue("Total count = 4, limit is 3", x.isCollidingWith(v));
assertTrue(v.isCollidingWith(x), "Total count = 4, limit is 3");
assertTrue(x.isCollidingWith(v), "Total count = 4, limit is 3");
}
@Test
public void multiWrite1() {
void multiWrite1() {
y.w(e);
assertFalse(x.isCollidingWith(y));
assertFalse(y.isCollidingWith(x));
for (int i = 0; i < fWriteCount; i++) {
x.w(e);
assertTrue("Total = W" + (i + 1) + ", Limit = W1", x.isCollidingWith(y));
assertTrue("Total = W" + (i + 1) + ", Limit = W1", y.isCollidingWith(x));
assertTrue(x.isCollidingWith(y), "Total = W" + (i + 1) + ", Limit = W1");
assertTrue(y.isCollidingWith(x), "Total = W" + (i + 1) + ", Limit = W1");
}
int j = entropy.nextInt(50) + 3;
for (int i = 1; i < j; i++) {
assertTrue("Total = W" + (i + fWriteCount) + ", Limit = W1", x.isCollidingWith(y));
assertTrue("Total = W" + (i + fWriteCount) + ", Limit = W1", y.isCollidingWith(x));
assertTrue(x.isCollidingWith(y), "Total = W" + (i + fWriteCount) + ", Limit = W1");
assertTrue(y.isCollidingWith(x), "Total = W" + (i + fWriteCount) + ", Limit = W1");
x.w(e);
}
}
@Test
public void multiWriteN() {
void multiWriteN() {
y.w(f);
for (int i = 0; i < f.numConcurrentWrite; i++) {
assertFalse("Total = W" + i + ", Limit = W" + f.numConcurrentWrite, x.isCollidingWith(y));
assertFalse("Total = W" + i + ", Limit = W" + f.numConcurrentWrite, y.isCollidingWith(x));
assertFalse(x.isCollidingWith(y), "Total = W" + i + ", Limit = W" + f.numConcurrentWrite);
assertFalse(y.isCollidingWith(x), "Total = W" + i + ", Limit = W" + f.numConcurrentWrite);
x.w(f);
}
int j = entropy.nextInt(50) + 3;
for (int i = 1; i < j; i++) {
assertTrue("Total = W" + (fWriteCount + i) + ", Limit = W" + fWriteCount, x.isCollidingWith(y));
assertTrue("Total = W" + (fWriteCount + i) + ", Limit = W" + fWriteCount, y.isCollidingWith(x));
assertTrue(x.isCollidingWith(y), "Total = W" + (fWriteCount + i) + ", Limit = W" + fWriteCount);
assertTrue(y.isCollidingWith(x), "Total = W" + (fWriteCount + i) + ", Limit = W" + fWriteCount);
x.w(f);
}
}
@Test
public void multiRead1() {
void multiRead1() {
y.r(e);
for (int i = 0; i < fWriteCount; i++) {
assertFalse("Total = R" + (i + 1) + ", Limit = W1", x.isCollidingWith(y));
assertFalse("Total = R" + (i + 1) + ", Limit = W1", y.isCollidingWith(x));
assertFalse(x.isCollidingWith(y), "Total = R" + (i + 1) + ", Limit = W1");
assertFalse(y.isCollidingWith(x), "Total = R" + (i + 1) + ", Limit = W1");
x.r(e);
}
int j = entropy.nextInt(50) + 3;
for (int i = 1; i < j; i++) {
assertFalse("Total = R" + (i + fWriteCount) + ", Limit = W1", x.isCollidingWith(y));
assertFalse("Total = R" + (i + fWriteCount) + ", Limit = W1", y.isCollidingWith(x));
assertFalse(x.isCollidingWith(y), "Total = R" + (i + fWriteCount) + ", Limit = W1");
assertFalse(y.isCollidingWith(x), "Total = R" + (i + fWriteCount) + ", Limit = W1");
x.r(e);
}
}
@Test
public void multiReadN() {
void multiReadN() {
y.r(f);
for (int i = 0; i < fWriteCount; i++) {
assertFalse("Total = R" + (i + 1) + ", Limit = W" + fWriteCount, x.isCollidingWith(y));
assertFalse("Total = R" + (i + 1) + ", Limit = W" + fWriteCount, y.isCollidingWith(x));
assertFalse(x.isCollidingWith(y), "Total = R" + (i + 1) + ", Limit = W" + fWriteCount);
assertFalse(y.isCollidingWith(x), "Total = R" + (i + 1) + ", Limit = W" + fWriteCount);
x.r(f);
}
int j = entropy.nextInt(50) + 3;
for (int i = 1; i < j; i++) {
assertFalse("Total = R" + (fWriteCount + i) + ", Limit = W" + fWriteCount, x.isCollidingWith(y));
assertFalse("Total = R" + (fWriteCount + i) + ", Limit = W" + fWriteCount, y.isCollidingWith(x));
assertFalse(x.isCollidingWith(y), "Total = R" + (fWriteCount + i) + ", Limit = W" + fWriteCount);
assertFalse(y.isCollidingWith(x), "Total = R" + (fWriteCount + i) + ", Limit = W" + fWriteCount);
x.r(f);
}
}
@@ -24,16 +24,17 @@
package hudson.model;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class RunParameterValueTest {
class RunParameterValueTest {
@SuppressWarnings("ResultOfObjectAllocationIgnored")
@Test public void robustness() {
@Test
void robustness() {
RunParameterValue rpv = new RunParameterValue("whatever", "folder/job#57");
assertEquals("whatever", rpv.getName());
assertEquals("folder/job", rpv.getJobName());
+39 -33
View File
@@ -24,14 +24,15 @@
package hudson.model;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
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.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.console.AnnotatedLargeText;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
@@ -47,23 +48,23 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import jenkins.model.Jenkins;
import org.apache.commons.jelly.XMLOutput;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.jvnet.hudson.test.Issue;
import org.jvnet.localizer.LocaleProvider;
import org.kohsuke.stapler.framework.io.ByteBuffer;
import org.mockito.Mockito;
public class RunTest {
class RunTest {
private static final String SAMPLE_BUILD_OUTPUT = "Sample build output abc123.\n";
@Rule public TemporaryFolder tmp = new TemporaryFolder();
@TempDir
private File tmp;
@Issue("JENKINS-15816")
@SuppressWarnings({"unchecked", "rawtypes"})
@Test
public void timezoneOfID() throws Exception {
void timezoneOfID() throws Exception {
TimeZone origTZ = TimeZone.getDefault();
try {
final Run r;
@@ -71,11 +72,7 @@ public class RunTest {
TimeZone.setDefault(TimeZone.getTimeZone("America/Chicago"));
ExecutorService svc = Executors.newSingleThreadExecutor();
try {
r = svc.submit(new Callable<Run>() {
@Override public Run call() {
return new Run(new StubJob(), 1234567890) {};
}
}).get();
r = svc.submit((Callable<Run>) () -> new Run(new StubJob(), 1234567890) {}).get();
TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
id = r.getId();
// explicitly cast to callable to make the Eclipse compiler happy
@@ -109,7 +106,7 @@ public class RunTest {
}
@Test
public void artifactListDisambiguation1() throws Exception {
void artifactListDisambiguation1() {
List<? extends Run<?, ?>.Artifact> a = createArtifactList("a/b/c.xml", "d/f/g.xml", "h/i/j.xml");
assertEquals("c.xml", a.get(0).getDisplayPath());
assertEquals("g.xml", a.get(1).getDisplayPath());
@@ -117,7 +114,7 @@ public class RunTest {
}
@Test
public void artifactListDisambiguation2() throws Exception {
void artifactListDisambiguation2() {
List<? extends Run<?, ?>.Artifact> a = createArtifactList("a/b/c.xml", "d/f/g.xml", "h/i/g.xml");
assertEquals("c.xml", a.get(0).getDisplayPath());
assertEquals("f/g.xml", a.get(1).getDisplayPath());
@@ -125,7 +122,7 @@ public class RunTest {
}
@Test
public void artifactListDisambiguation3() throws Exception {
void artifactListDisambiguation3() {
List<? extends Run<?, ?>.Artifact> a = createArtifactList("a.xml", "a/a.xml");
assertEquals("a.xml", a.get(0).getDisplayPath());
assertEquals("a/a.xml", a.get(1).getDisplayPath());
@@ -134,7 +131,7 @@ public class RunTest {
@Issue("JENKINS-26777")
@SuppressWarnings({"unchecked", "rawtypes", "deprecation"})
@Test
public void getDurationString() {
void getDurationString() {
LocaleProvider providerToRestore = LocaleProvider.getProvider();
try {
// This test expects English texts.
@@ -150,10 +147,10 @@ public class RunTest {
r.onStartBuilding();
String msg;
msg = r.getDurationString();
assertTrue(msg, msg.endsWith(" and counting"));
assertTrue(msg.endsWith(" and counting"), msg);
r.onEndBuilding();
msg = r.getDurationString();
assertFalse(msg, msg.endsWith(" and counting"));
assertFalse(msg.endsWith(" and counting"), msg);
} finally {
LocaleProvider.setProvider(providerToRestore);
}
@@ -162,9 +159,9 @@ public class RunTest {
@Issue("JENKINS-27441")
@SuppressWarnings("deprecation")
@Test
public void getLogReturnsAnEmptyListWhenCalledWith0() throws Exception {
void getLogReturnsAnEmptyListWhenCalledWith0() throws Exception {
Job j = Mockito.mock(Job.class);
File tempBuildDir = tmp.newFolder();
File tempBuildDir = newFolder(tmp, "junit");
Mockito.when(j.getBuildDir()).thenReturn(tempBuildDir);
Run<? extends Job<?, ?>, ? extends Run<?, ?>> r = new Run(j, 0) {};
File f = r.getLogFile();
@@ -178,9 +175,9 @@ public class RunTest {
@SuppressWarnings("deprecation")
@Test
public void getLogReturnsAnRightOrder() throws Exception {
void getLogReturnsAnRightOrder() throws Exception {
Job j = Mockito.mock(Job.class);
File tempBuildDir = tmp.newFolder();
File tempBuildDir = newFolder(tmp, "junit");
Mockito.when(j.getBuildDir()).thenReturn(tempBuildDir);
Run<? extends Job<?, ?>, ? extends Run<?, ?>> r = new Run(j, 0) {};
File f = r.getLogFile();
@@ -203,9 +200,9 @@ public class RunTest {
@SuppressWarnings("deprecation")
@Test
public void getLogReturnsAllLines() throws Exception {
void getLogReturnsAllLines() throws Exception {
Job j = Mockito.mock(Job.class);
File tempBuildDir = tmp.newFolder();
File tempBuildDir = newFolder(tmp, "junit");
Mockito.when(j.getBuildDir()).thenReturn(tempBuildDir);
Run<? extends Job<?, ?>, ? extends Run<?, ?>> r = new Run(j, 0) {};
File f = r.getLogFile();
@@ -223,7 +220,7 @@ public class RunTest {
}
@Test
public void compareRunsFromSameJobWithDifferentNumbers() throws Exception {
void compareRunsFromSameJobWithDifferentNumbers() throws Exception {
final Jenkins group = Mockito.mock(Jenkins.class);
Mockito.when(group.getFullName()).thenReturn("j");
final Job j = Mockito.mock(Job.class);
@@ -245,7 +242,7 @@ public class RunTest {
@Issue("JENKINS-42319")
@Test
public void compareRunsFromDifferentParentsWithSameNumber() throws Exception {
void compareRunsFromDifferentParentsWithSameNumber() throws Exception {
final Jenkins group1 = Mockito.mock(Jenkins.class);
final Jenkins group2 = Mockito.mock(Jenkins.class);
final Job j1 = Mockito.mock(Job.class);
@@ -271,22 +268,22 @@ public class RunTest {
}
@Test
public void willTriggerLogToStartWithNextFullLine() throws Exception {
void willTriggerLogToStartWithNextFullLine() throws Exception {
assertWriteLogToEquals(new String(new char[2]).replace("\0", SAMPLE_BUILD_OUTPUT) + "Finished: SUCCESS.\n", 2 * SAMPLE_BUILD_OUTPUT.length() + 10);
}
@Test
public void wontPushOffsetOnRenderingFromBeginning() throws Exception {
void wontPushOffsetOnRenderingFromBeginning() throws Exception {
assertWriteLogToEquals(new String(new char[5]).replace("\0", SAMPLE_BUILD_OUTPUT) + "Finished: SUCCESS.\n", 0);
}
@Test
public void wontPushOffsetOnRenderingFromBeginningOfLine() throws Exception {
void wontPushOffsetOnRenderingFromBeginningOfLine() throws Exception {
assertWriteLogToEquals(new String(new char[3]).replace("\0", SAMPLE_BUILD_OUTPUT) + "Finished: SUCCESS.\n", 2 * SAMPLE_BUILD_OUTPUT.length());
}
@Test
public void willRenderNothingIfOffsetSetOnLastLine() throws Exception {
void willRenderNothingIfOffsetSetOnLastLine() throws Exception {
assertWriteLogToEquals("", 5 * SAMPLE_BUILD_OUTPUT.length() + 6);
}
@@ -320,4 +317,13 @@ public class RunTest {
assertEquals(expectedOutput, writer.toString());
}
}
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;
}
}
@@ -1,18 +1,18 @@
package hudson.model;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertTrue;
import hudson.console.AnnotatedLargeText;
import hudson.security.ACL;
import hudson.security.Permission;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* @author Jerome Lacoste
*/
public class TaskActionTest {
class TaskActionTest {
private static class MyTaskThread extends TaskThread {
MyTaskThread(TaskAction taskAction) {
@@ -58,7 +58,7 @@ public class TaskActionTest {
}
@Test
public void annotatedText() throws Exception {
void annotatedText() throws Exception {
MyTaskAction action = new MyTaskAction();
action.start();
AnnotatedLargeText annotatedText = action.obtainLog();
@@ -68,7 +68,7 @@ public class TaskActionTest {
ByteArrayOutputStream os = new ByteArrayOutputStream();
final long length = annotatedText.writeLogTo(0, os);
// Windows based systems will be 220, linux base 219
assertTrue("length should be longer or even 219", length >= 219);
assertTrue(length >= 219, "length should be longer or even 219");
assertTrue(os.toString(StandardCharsets.UTF_8).startsWith("a linkCompleted"));
}
}
@@ -24,18 +24,18 @@
package hudson.model;
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 org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* @author Kohsuke Kawaguchi
*/
public class TimeSeriesTest {
class TimeSeriesTest {
@Test
public void test1() {
void test1() {
TimeSeries ts = new TimeSeries(0, 1 - 0.1f, 100);
float last = ts.getLatest();
assertEquals(0f, last, 0f);
@@ -2,55 +2,55 @@ package hudson.model;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
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.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Locale;
import net.sf.json.JSONObject;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class UpdateCenterTest {
class UpdateCenterTest {
@Test
public void toUpdateCenterCheckUrl_http_noQuery() throws Exception {
void toUpdateCenterCheckUrl_http_noQuery() throws Exception {
assertThat(UpdateCenter.UpdateCenterConfiguration.toUpdateCenterCheckUrl(
"http://updates.jenkins-ci.org/update-center.json").toExternalForm(),
is("http://updates.jenkins-ci.org/update-center.json?uctest"));
}
@Test
public void toUpdateCenterCheckUrl_https_noQuery() throws Exception {
void toUpdateCenterCheckUrl_https_noQuery() throws Exception {
assertThat(UpdateCenter.UpdateCenterConfiguration.toUpdateCenterCheckUrl(
"https://updates.jenkins-ci.org/update-center.json").toExternalForm(),
is("https://updates.jenkins-ci.org/update-center.json?uctest"));
}
@Test
public void toUpdateCenterCheckUrl_http_query() throws Exception {
void toUpdateCenterCheckUrl_http_query() throws Exception {
assertThat(UpdateCenter.UpdateCenterConfiguration.toUpdateCenterCheckUrl(
"http://updates.jenkins-ci.org/update-center.json?version=2.7").toExternalForm(),
is("http://updates.jenkins-ci.org/update-center.json?version=2.7&uctest"));
}
@Test
public void toUpdateCenterCheckUrl_https_query() throws Exception {
void toUpdateCenterCheckUrl_https_query() throws Exception {
assertThat(UpdateCenter.UpdateCenterConfiguration.toUpdateCenterCheckUrl(
"https://updates.jenkins-ci.org/update-center.json?version=2.7").toExternalForm(),
is("https://updates.jenkins-ci.org/update-center.json?version=2.7&uctest"));
}
@Test
public void toUpdateCenterCheckUrl_file() throws Exception {
void toUpdateCenterCheckUrl_file() throws Exception {
assertThat(UpdateCenter.UpdateCenterConfiguration.toUpdateCenterCheckUrl(
"file://./foo.jar!update-center.json").toExternalForm(),
is("file://./foo.jar!update-center.json"));
}
@Test
public void noChecksums() {
void noChecksums() {
final IOException ex = assertThrows(IOException.class,
() -> UpdateCenter.verifyChecksums(new MockDownloadJob(null, null, null),
buildEntryWithExpectedChecksums(null, null, null), new File("example")));
@@ -58,14 +58,14 @@ public class UpdateCenterTest {
}
@Test
public void sha1Match() throws Exception {
void sha1Match() throws Exception {
UpdateCenter.verifyChecksums(
new MockDownloadJob(EMPTY_SHA1, null, null),
buildEntryWithExpectedChecksums(EMPTY_SHA1, null, null), new File("example"));
}
@Test
public void sha1Mismatch() {
void sha1Mismatch() {
final IOException ex = assertThrows(IOException.class, () -> UpdateCenter.verifyChecksums(
new MockDownloadJob(EMPTY_SHA1.replace('k', 'f'), null, null),
buildEntryWithExpectedChecksums(EMPTY_SHA1, null, null), new File("example")));
@@ -73,21 +73,21 @@ public class UpdateCenterTest {
}
@Test
public void sha512ProvidedOnly() throws IOException {
void sha512ProvidedOnly() throws IOException {
UpdateCenter.verifyChecksums(
new MockDownloadJob(EMPTY_SHA1, EMPTY_SHA256, EMPTY_SHA512),
buildEntryWithExpectedChecksums(null, null, EMPTY_SHA512), new File("example"));
}
@Test
public void sha512and256IgnoreCase() throws IOException {
void sha512and256IgnoreCase() throws IOException {
UpdateCenter.verifyChecksums(
new MockDownloadJob(EMPTY_SHA1, EMPTY_SHA256.toUpperCase(Locale.US), EMPTY_SHA512.toUpperCase(Locale.US)),
buildEntryWithExpectedChecksums(null, EMPTY_SHA256, EMPTY_SHA512), new File("example"));
}
@Test
public void sha1DoesNotIgnoreCase() {
void sha1DoesNotIgnoreCase() {
final Exception ex = assertThrows(Exception.class, () -> UpdateCenter.verifyChecksums(
new MockDownloadJob(EMPTY_SHA1, EMPTY_SHA256, EMPTY_SHA512),
buildEntryWithExpectedChecksums(EMPTY_SHA1.toUpperCase(Locale.US), null, null), new File("example")));
@@ -95,7 +95,7 @@ public class UpdateCenterTest {
}
@Test
public void noOverlapForComputedAndProvidedChecksums() {
void noOverlapForComputedAndProvidedChecksums() {
final Exception ex = assertThrows(Exception.class, () -> UpdateCenter.verifyChecksums(
new MockDownloadJob(EMPTY_SHA1, EMPTY_SHA256, null),
buildEntryWithExpectedChecksums(null, null, EMPTY_SHA512), new File("example")));
@@ -103,7 +103,7 @@ public class UpdateCenterTest {
}
@Test
public void noOverlapForComputedAndProvidedChecksumsForSpecIncompliantJVM() {
void noOverlapForComputedAndProvidedChecksumsForSpecIncompliantJVM() {
final Exception ex = assertThrows(Exception.class, () -> UpdateCenter.verifyChecksums(
new MockDownloadJob(EMPTY_SHA1, null, null),
buildEntryWithExpectedChecksums(null, EMPTY_SHA256, EMPTY_SHA512), new File("example")));
@@ -32,33 +32,37 @@ import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertThrows;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.File;
import java.io.IOException;
import jenkins.model.IdStrategy;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
public class UserIdMapperTest {
class UserIdMapperTest {
@Rule
public TestName name = new TestName();
private TestInfo info;
@BeforeEach
void setUp(TestInfo testInfo) {
info = testInfo;
}
@Test
public void testNonexistentFileLoads() throws IOException {
void testNonexistentFileLoads() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
}
@Test
public void testEmptyGet() throws IOException {
void testEmptyGet() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
assertThat(mapper.getDirectory("anything"), nullValue());
}
@Test
public void testSimplePutGet() throws IOException {
void testSimplePutGet() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
String user1 = "user1";
File directory = mapper.putIfAbsent(user1, true);
@@ -66,7 +70,7 @@ public class UserIdMapperTest {
}
@Test
public void testMultiple() throws IOException {
void testMultiple() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
String user1 = "user1";
File directory1 = mapper.putIfAbsent(user1, true);
@@ -80,8 +84,8 @@ public class UserIdMapperTest {
}
@Test
public void testMultipleSaved() throws IOException {
File usersDirectory = UserIdMigratorTest.createTestDirectory(getClass(), name);
void testMultipleSaved() throws IOException {
File usersDirectory = UserIdMigratorTest.createTestDirectory(getClass(), info);
IdStrategy idStrategy = IdStrategy.CASE_INSENSITIVE;
UserIdMapper mapper = new TestUserIdMapper(usersDirectory, idStrategy);
mapper.init();
@@ -99,7 +103,7 @@ public class UserIdMapperTest {
}
@Test
public void testRepeatPut() throws IOException {
void testRepeatPut() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
String user1 = "user1";
File directory1 = mapper.putIfAbsent(user1, true);
@@ -108,13 +112,13 @@ public class UserIdMapperTest {
}
@Test
public void testIsNotMapped() throws IOException {
void testIsNotMapped() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
assertThat(mapper.isMapped("anything"), is(false));
}
@Test
public void testIsMapped() throws IOException {
void testIsMapped() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
String user1 = "user1";
File directory = mapper.putIfAbsent(user1, true);
@@ -122,13 +126,13 @@ public class UserIdMapperTest {
}
@Test
public void testInitialUserIds() throws IOException {
void testInitialUserIds() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
assertThat(mapper.getConvertedUserIds(), empty());
}
@Test
public void testSingleUserIds() throws IOException {
void testSingleUserIds() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
String user1 = "user1";
File directory = mapper.putIfAbsent(user1, true);
@@ -137,7 +141,7 @@ public class UserIdMapperTest {
}
@Test
public void testMultipleUserIds() throws IOException {
void testMultipleUserIds() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
String user1 = "user1";
File directory = mapper.putIfAbsent(user1, true);
@@ -148,7 +152,7 @@ public class UserIdMapperTest {
}
@Test
public void testRemove() throws IOException {
void testRemove() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
String user1 = "user1";
File directory = mapper.putIfAbsent(user1, true);
@@ -157,8 +161,8 @@ public class UserIdMapperTest {
}
@Test
public void testRemoveAfterSave() throws IOException {
File usersDirectory = UserIdMigratorTest.createTestDirectory(getClass(), name);
void testRemoveAfterSave() throws IOException {
File usersDirectory = UserIdMigratorTest.createTestDirectory(getClass(), info);
IdStrategy idStrategy = IdStrategy.CASE_INSENSITIVE;
UserIdMapper mapper = new TestUserIdMapper(usersDirectory, idStrategy);
mapper.init();
@@ -172,7 +176,7 @@ public class UserIdMapperTest {
}
@Test
public void testPutGetCaseInsensitive() throws IOException {
void testPutGetCaseInsensitive() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
String user1 = "user1";
File directory = mapper.putIfAbsent(user1, true);
@@ -180,7 +184,7 @@ public class UserIdMapperTest {
}
@Test
public void testPutGetCaseSensitive() throws IOException {
void testPutGetCaseSensitive() throws IOException {
IdStrategy idStrategy = new IdStrategy.CaseSensitive();
UserIdMapper mapper = createUserIdMapper(idStrategy);
String user1 = "user1";
@@ -189,7 +193,7 @@ public class UserIdMapperTest {
}
@Test
public void testIsMappedCaseInsensitive() throws IOException {
void testIsMappedCaseInsensitive() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
String user1 = "user1";
File directory = mapper.putIfAbsent(user1, true);
@@ -197,7 +201,7 @@ public class UserIdMapperTest {
}
@Test
public void testIsMappedCaseSensitive() throws IOException {
void testIsMappedCaseSensitive() throws IOException {
IdStrategy idStrategy = new IdStrategy.CaseSensitive();
UserIdMapper mapper = createUserIdMapper(idStrategy);
String user1 = "user1";
@@ -206,7 +210,7 @@ public class UserIdMapperTest {
}
@Test
public void testRemoveCaseInsensitive() throws IOException {
void testRemoveCaseInsensitive() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
String user1 = "user1";
File directory = mapper.putIfAbsent(user1, true);
@@ -215,7 +219,7 @@ public class UserIdMapperTest {
}
@Test
public void testRemoveCaseSensitive() throws IOException {
void testRemoveCaseSensitive() throws IOException {
IdStrategy idStrategy = new IdStrategy.CaseSensitive();
UserIdMapper mapper = createUserIdMapper(idStrategy);
String user1 = "user1";
@@ -225,7 +229,7 @@ public class UserIdMapperTest {
}
@Test
public void testRepeatRemove() throws IOException {
void testRepeatRemove() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
String user1 = "user1";
File directory1 = mapper.putIfAbsent(user1, true);
@@ -235,7 +239,7 @@ public class UserIdMapperTest {
}
@Test
public void testClear() throws IOException {
void testClear() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
String user1 = "user1";
File directory1 = mapper.putIfAbsent(user1, true);
@@ -245,7 +249,7 @@ public class UserIdMapperTest {
}
@Test
public void testReload() throws IOException {
void testReload() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
String user1 = "user1";
File directory1 = mapper.putIfAbsent(user1, true);
@@ -255,7 +259,7 @@ public class UserIdMapperTest {
}
@Test
public void testDirectoryFormatBasic() throws IOException {
void testDirectoryFormatBasic() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
String user1 = "1user";
File directory1 = mapper.putIfAbsent(user1, true);
@@ -263,7 +267,7 @@ public class UserIdMapperTest {
}
@Test
public void testDirectoryFormatLongerUserId() throws IOException {
void testDirectoryFormatLongerUserId() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
String user1 = "muchlongeruserid";
File directory1 = mapper.putIfAbsent(user1, true);
@@ -271,7 +275,7 @@ public class UserIdMapperTest {
}
@Test
public void testDirectoryFormatAllSuppressedCharacters() throws IOException {
void testDirectoryFormatAllSuppressedCharacters() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
String user1 = "!@#$%^";
File directory1 = mapper.putIfAbsent(user1, true);
@@ -279,7 +283,7 @@ public class UserIdMapperTest {
}
@Test
public void testDirectoryFormatSingleCharacter() throws IOException {
void testDirectoryFormatSingleCharacter() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
String user1 = ".";
File directory1 = mapper.putIfAbsent(user1, true);
@@ -287,7 +291,7 @@ public class UserIdMapperTest {
}
@Test
public void testDirectoryFormatMixed() throws IOException {
void testDirectoryFormatMixed() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
String user1 = "a$b!c^d~e@f";
File directory1 = mapper.putIfAbsent(user1, true);
@@ -295,19 +299,19 @@ public class UserIdMapperTest {
}
@Test
public void testXmlFileCorrupted() {
void testXmlFileCorrupted() {
assertThrows(IOException.class, () -> createUserIdMapper(IdStrategy.CASE_INSENSITIVE));
}
@Test
public void testDuplicatedUserId() throws IOException {
void testDuplicatedUserId() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
assertThat(mapper.isMapped("user2"), is(true));
assertThat(mapper.isMapped("user1"), is(true));
}
private UserIdMapper createUserIdMapper(IdStrategy idStrategy) throws IOException {
File usersDirectory = UserIdMigratorTest.createTestDirectory(getClass(), name);
File usersDirectory = UserIdMigratorTest.createTestDirectory(getClass(), info);
TestUserIdMapper mapper = new TestUserIdMapper(usersDirectory, idStrategy);
mapper.init();
return mapper;
@@ -37,58 +37,63 @@ import java.nio.file.Paths;
import java.util.Map;
import jenkins.model.IdStrategy;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
public class UserIdMigratorTest {
class UserIdMigratorTest {
private static final String BASE_RESOURCE_PATH = "src/test/resources/hudson/model/";
@Rule
public TestName name = new TestName();
private TestInfo info;
@BeforeEach
void setUp(TestInfo testInfo) {
info = testInfo;
}
@Test
public void needsMigrationBasic() throws IOException {
void needsMigrationBasic() throws IOException {
UserIdMigrator migrator = createUserIdMigrator();
assertThat(migrator.needsMigration(), is(true));
}
@Test
public void needsMigrationFalse() throws IOException {
void needsMigrationFalse() throws IOException {
UserIdMigrator migrator = createUserIdMigrator();
assertThat(migrator.needsMigration(), is(false));
}
@Test
public void needsMigrationNoneExisting() throws IOException {
void needsMigrationNoneExisting() throws IOException {
UserIdMigrator migrator = createUserIdMigrator();
assertThat(migrator.needsMigration(), is(false));
}
@Test
public void needsMigrationNoUserConfigFiles() throws IOException {
void needsMigrationNoUserConfigFiles() throws IOException {
UserIdMigrator migrator = createUserIdMigrator();
assertThat(migrator.needsMigration(), is(false));
}
@Test
public void scanExistingUsersNone() throws IOException {
File usersDirectory = createTestDirectory(getClass(), name);
void scanExistingUsersNone() throws IOException {
File usersDirectory = createTestDirectory(getClass(), info);
UserIdMigrator migrator = new UserIdMigrator(usersDirectory, IdStrategy.CASE_INSENSITIVE);
Map<String, File> userMappings = migrator.scanExistingUsers();
assertThat(userMappings.keySet(), empty());
}
@Test
public void scanExistingUsersNoUsersDirectory() throws IOException {
void scanExistingUsersNoUsersDirectory() throws IOException {
UserIdMigrator migrator = createUserIdMigrator();
Map<String, File> userMappings = migrator.scanExistingUsers();
assertThat(userMappings.keySet(), empty());
}
@Test
public void scanExistingUsersBasic() throws IOException {
void scanExistingUsersBasic() throws IOException {
UserIdMigrator migrator = createUserIdMigrator();
Map<String, File> userMappings = migrator.scanExistingUsers();
assertThat(userMappings.keySet(), hasSize(2));
@@ -96,7 +101,7 @@ public class UserIdMigratorTest {
}
@Test
public void scanExistingUsersLegacy() throws IOException {
void scanExistingUsersLegacy() throws IOException {
UserIdMigrator migrator = createUserIdMigrator();
Map<String, File> userMappings = migrator.scanExistingUsers();
assertThat(userMappings.keySet(), hasSize(8));
@@ -104,7 +109,7 @@ public class UserIdMigratorTest {
}
@Test
public void scanExistingUsersOldLegacy() throws IOException {
void scanExistingUsersOldLegacy() throws IOException {
UserIdMigrator migrator = createUserIdMigrator();
Map<String, File> userMappings = migrator.scanExistingUsers();
assertThat(userMappings.keySet(), hasSize(4));
@@ -112,7 +117,7 @@ public class UserIdMigratorTest {
}
@Test
public void emptyUsernameConfigScanned() throws IOException {
void emptyUsernameConfigScanned() throws IOException {
UserIdMigrator migrator = createUserIdMigrator();
Map<String, File> userMappings = migrator.scanExistingUsers();
assertThat(userMappings.keySet(), hasSize(2));
@@ -120,8 +125,8 @@ public class UserIdMigratorTest {
}
@Test
public void scanExistingUsersCaseSensitive() throws IOException {
File usersDirectory = createTestDirectory(getClass(), name);
void scanExistingUsersCaseSensitive() throws IOException {
File usersDirectory = createTestDirectory(getClass(), info);
UserIdMigrator migrator = new UserIdMigrator(usersDirectory, new IdStrategy.CaseSensitive());
Map<String, File> userMappings = migrator.scanExistingUsers();
assertThat(userMappings.keySet(), hasSize(3));
@@ -129,8 +134,8 @@ public class UserIdMigratorTest {
}
@Test
public void migrateSimpleUser() throws IOException {
File usersDirectory = createTestDirectory(getClass(), name);
void migrateSimpleUser() throws IOException {
File usersDirectory = createTestDirectory(getClass(), info);
IdStrategy idStrategy = IdStrategy.CASE_INSENSITIVE;
UserIdMigrator migrator = new UserIdMigrator(usersDirectory, idStrategy);
TestUserIdMapper mapper = new TestUserIdMapper(usersDirectory, idStrategy);
@@ -143,8 +148,8 @@ public class UserIdMigratorTest {
}
@Test
public void migrateMultipleUsers() throws IOException {
File usersDirectory = createTestDirectory(getClass(), name);
void migrateMultipleUsers() throws IOException {
File usersDirectory = createTestDirectory(getClass(), info);
IdStrategy idStrategy = IdStrategy.CASE_INSENSITIVE;
UserIdMigrator migrator = new UserIdMigrator(usersDirectory, idStrategy);
TestUserIdMapper mapper = new TestUserIdMapper(usersDirectory, idStrategy);
@@ -159,8 +164,8 @@ public class UserIdMigratorTest {
}
@Test
public void migrateUsersXml() throws IOException {
File usersDirectory = createTestDirectory(getClass(), name);
void migrateUsersXml() throws IOException {
File usersDirectory = createTestDirectory(getClass(), info);
IdStrategy idStrategy = IdStrategy.CASE_INSENSITIVE;
UserIdMigrator migrator = new UserIdMigrator(usersDirectory, idStrategy);
TestUserIdMapper mapper = new TestUserIdMapper(usersDirectory, idStrategy);
@@ -173,8 +178,8 @@ public class UserIdMigratorTest {
}
@Test
public void migrateEntireDirectory() throws IOException {
File usersDirectory = createTestDirectory(getClass(), name);
void migrateEntireDirectory() throws IOException {
File usersDirectory = createTestDirectory(getClass(), info);
IdStrategy idStrategy = IdStrategy.CASE_INSENSITIVE;
UserIdMigrator migrator = new UserIdMigrator(usersDirectory, idStrategy);
TestUserIdMapper mapper = new TestUserIdMapper(usersDirectory, idStrategy);
@@ -186,22 +191,22 @@ public class UserIdMigratorTest {
assertThat(originalFredDirectory.exists(), is(false));
}
static File createTestDirectory(Class clazz, TestName testName) throws IOException {
static File createTestDirectory(Class clazz, TestInfo info) throws IOException {
File tempDirectory = Files.createTempDirectory(Paths.get("target"), "userIdMigratorTest").toFile();
tempDirectory.deleteOnExit();
copyTestDataIfExists(clazz, testName, tempDirectory);
copyTestDataIfExists(clazz, info, tempDirectory);
return new File(tempDirectory, "users");
}
static void copyTestDataIfExists(Class clazz, TestName testName, File tempDirectory) throws IOException {
File resourcesDirectory = new File(BASE_RESOURCE_PATH + clazz.getSimpleName(), testName.getMethodName());
static void copyTestDataIfExists(Class clazz, TestInfo info, File tempDirectory) throws IOException {
File resourcesDirectory = new File(BASE_RESOURCE_PATH + clazz.getSimpleName(), info.getTestMethod().orElseThrow().getName());
if (resourcesDirectory.exists()) {
FileUtils.copyDirectory(resourcesDirectory, tempDirectory);
}
}
private UserIdMigrator createUserIdMigrator() throws IOException {
File usersDirectory = createTestDirectory(getClass(), name);
File usersDirectory = createTestDirectory(getClass(), info);
return new UserIdMigrator(usersDirectory, IdStrategy.CASE_INSENSITIVE);
}
+27 -27
View File
@@ -3,42 +3,42 @@ package hudson.model;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.jvnet.hudson.test.Issue;
/*
* The MIT License
*
* Copyright (c) 2016 Oleg Nenashev.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
* The MIT License
*
* Copyright (c) 2016 Oleg Nenashev.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* Unit tests for the {@link User} class.
* @author Oleg Nenashev
*/
public class UserTest {
class UserTest {
@Test
@Issue("JENKINS-33600")
public void blankIdsOrFullNamesShouldNotBeAllowed() {
void blankIdsOrFullNamesShouldNotBeAllowed() {
assertThat("Null user IDs should not be allowed", User.isIdOrFullnameAllowed(null), is(false));
assertThat("Empty user IDs should not be allowed", User.isIdOrFullnameAllowed(""), is(false));
assertThat("Blank user IDs should not be allowed", User.isIdOrFullnameAllowed(" "), is(false));
@@ -46,7 +46,7 @@ public class UserTest {
@Test
@Issue("JENKINS-35967")
public void shouldNotAllowIllegalRestrictedNamesInWrongCase() {
void shouldNotAllowIllegalRestrictedNamesInWrongCase() {
assertIdOrFullNameNotAllowed("system");
assertIdOrFullNameNotAllowed("System");
assertIdOrFullNameNotAllowed("SYSTEM");
@@ -56,7 +56,7 @@ public class UserTest {
@Test
@Issue("JENKINS-35967")
public void shouldNotAllowIllegalRestrictedNamesEvenIfTrimmed() {
void shouldNotAllowIllegalRestrictedNamesEvenIfTrimmed() {
for (String username : User.getIllegalPersistedUsernames()) {
assertIdOrFullNameNotAllowed(username);
assertIdOrFullNameNotAllowed(" " + username);
@@ -1,7 +1,7 @@
package hudson.model;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import hudson.search.SearchIndex;
import hudson.search.SearchIndexBuilder;
@@ -11,7 +11,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.jvnet.hudson.test.Issue;
import org.kohsuke.stapler.StaplerRequest2;
import org.kohsuke.stapler.StaplerResponse2;
@@ -24,7 +24,7 @@ public class ViewTest {
* are added to the SearchIndexBuilder
*/
@Test
public void testAddDisplayNamesToSearchIndex() {
void testAddDisplayNamesToSearchIndex() {
final String url1 = "url1";
final String displayName1 = "displayName1";
final String url2 = "url2";
@@ -75,7 +75,7 @@ public class ViewTest {
* Get all items recursively when View implements ViewGroup at the same time
*/
@Test
public void getAllItems() {
void getAllItems() {
final View leftView = Mockito.mock(View.class);
final View rightView = Mockito.mock(View.class);
@@ -102,7 +102,7 @@ public class ViewTest {
@Test
@Issue("JENKINS-43322")
public void getAllViewsRecursively() {
void getAllViewsRecursively() {
//given
View left2ndNestedView = Mockito.mock(View.class);
View right2ndNestedView = Mockito.mock(View.class);
@@ -24,7 +24,7 @@
package hudson.model.listeners;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
@@ -33,16 +33,17 @@ import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.scm.ChangeLogSet;
import hudson.scm.SCM;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.jvnet.hudson.test.Issue;
import org.mockito.Mockito;
@SuppressWarnings("deprecation")
public class SCMListenerTest {
class SCMListenerTest {
@Issue("JENKINS-23522")
@SuppressWarnings("rawtypes")
@Test public void onChangeLogParsed() throws Exception {
@Test
void onChangeLogParsed() throws Exception {
SCM scm = Mockito.mock(SCM.class);
BuildListener bl = Mockito.mock(BuildListener.class);
ChangeLogSet cls = Mockito.mock(ChangeLogSet.class);
@@ -61,13 +62,13 @@ public class SCMListenerTest {
TaskListener tl = Mockito.mock(TaskListener.class);
L l = new L1();
l.onChangeLogParsed(r, scm, tl, cls);
assertEquals("cannot handle this", 0, l.cnt);
assertEquals(0, l.cnt, "cannot handle this");
l = new L2();
l.onChangeLogParsed(r, scm, tl, cls);
assertEquals("does handle this", 1, l.cnt);
assertEquals(1, l.cnt, "does handle this");
l = new L3();
l.onChangeLogParsed(r, scm, tl, cls);
assertEquals("cannot handle this", 0, l.cnt);
assertEquals(0, l.cnt, "cannot handle this");
}
private static class L extends SCMListener {
@@ -24,20 +24,20 @@
package hudson.model.queue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import hudson.model.Queue;
import java.io.IOException;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.jvnet.hudson.test.Issue;
@SuppressWarnings("deprecation")
public class AbstractQueueTaskTest {
class AbstractQueueTaskTest {
@Issue("JENKINS-47517")
@Test
public void causeOfBlockageOverrides() {
void causeOfBlockageOverrides() {
Queue.Task t = new LegacyTask();
assertFalse(t.isBuildBlocked());
assertNull(t.getWhyBlocked());
@@ -24,17 +24,18 @@
package hudson.os;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* Test the test utility code, too!
*/
public class WindowsUtilTest {
class WindowsUtilTest {
@Test
public void testQuoteArgument() {
void testQuoteArgument() {
String input = "C:\\Programs and \"Settings\"\\System32\\\\";
String expected = "\"C:\\Programs and \\\"Settings\\\"\\System32\\\\\\\\\"";
String actual = WindowsUtil.quoteArgument(input);
@@ -42,14 +43,14 @@ public class WindowsUtilTest {
}
@Test
public void testQuoteArgument_OnlyQuotesWhenNecessary() {
void testQuoteArgument_OnlyQuotesWhenNecessary() {
for (String arg : Arrays.asList("", "foo", "foo-bar", "C:\\test\\path", "http://www.example.com/")) {
assertEquals(arg, WindowsUtil.quoteArgument(arg));
}
}
@Test
public void testQuoteArgumentForCmd() {
void testQuoteArgumentForCmd() {
String input = "hello \"\\world&";
String expected = "^\"hello \\^\"\\world^&^\"";
String actual = WindowsUtil.quoteArgumentForCmd(input);
@@ -57,7 +58,7 @@ public class WindowsUtilTest {
}
@Test
public void testQuoteArgumentForCmd_OnlyQuotesWhenNecessary() {
void testQuoteArgumentForCmd_OnlyQuotesWhenNecessary() {
for (String arg : Arrays.asList("", "foo", "foo-bar", "C:\\test\\path", "http://www.example.com/")) {
assertEquals(arg, WindowsUtil.quoteArgumentForCmd(arg));
}
@@ -1,6 +1,6 @@
package hudson.scheduler;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.text.DateFormat;
import java.util.ArrayList;
@@ -8,10 +8,8 @@ import java.util.Calendar;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.Locale;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.jvnet.hudson.test.For;
import org.jvnet.hudson.test.Issue;
@@ -22,10 +20,9 @@ import org.jvnet.hudson.test.Issue;
* {@link CronTab#floor(Calendar)} and {@link CronTab#ceil(Calendar)} methods.
*/
@For(CronTab.class)
@RunWith(Parameterized.class)
public class CronTabDayOfWeekLocaleTest {
@Parameters
public static Collection<Object[]> parameters() {
class CronTabDayOfWeekLocaleTest {
static Collection<Object[]> parameters() {
final Locale[] locales = Locale.getAvailableLocales();
final Collection<Object[]> parameters = new ArrayList<>();
for (final Locale locale : locales) {
@@ -37,19 +34,15 @@ public class CronTabDayOfWeekLocaleTest {
return parameters;
}
private final Locale locale;
public CronTabDayOfWeekLocaleTest(Locale locale) {
this.locale = locale;
}
/**
* This unit test is an slight adaptation of the unit test found in
* HUDSON-8656.
*/
@Test
@Issue("HUDSON-8656") // This is _not_ JENKINS-8656
public void hudson8656() throws Exception {
// This is _not_ JENKINS-8656
@ParameterizedTest
@MethodSource("parameters")
@Issue("HUDSON-8656")
void hudson8656(Locale locale) {
final Calendar cal = Calendar.getInstance(locale);
cal.set(2011, Calendar.JANUARY, 16, 0, 0, 0); // Sunday, Jan 16th 2011, 00:00
final String cronStr = "0 23 * * 1-5"; // execute on weekdays @23:00
@@ -57,14 +50,15 @@ public class CronTabDayOfWeekLocaleTest {
final CronTab cron = new CronTab(cronStr);
final Calendar next = cron.ceil(cal);
final Calendar expectedDate = Calendar.getInstance();
final Calendar expected = Calendar.getInstance();
// Expected next: Monday, Jan 17th 2011, 23:00
expectedDate.set(2011, Calendar.JANUARY, 17, 23, 0, 0);
compare(expectedDate, next);
expected.set(2011, Calendar.JANUARY, 17, 23, 0, 0);
compare(locale, expected, next);
}
@Test
public void isSundayAndNextRunIsMonday() throws Exception {
@ParameterizedTest
@MethodSource("parameters")
void isSundayAndNextRunIsMonday(Locale locale) {
final Calendar cal = Calendar.getInstance(locale);
cal.set(2011, Calendar.JANUARY, 16, 0, 0, 0); // Sunday, Jan 16th 2011, 00:00
final String cronStr = "0 0 * * 1"; // Mondays @00:00
@@ -75,11 +69,12 @@ public class CronTabDayOfWeekLocaleTest {
final Calendar expected = Calendar.getInstance();
// Expected next: Monday, Jan 17th 2011, 00:00
expected.set(2011, Calendar.JANUARY, 17, 0, 0, 0);
compare(expected, actual);
compare(locale, expected, actual);
}
@Test
public void isSundayAndPreviousRunIsMonday() throws Exception {
@ParameterizedTest
@MethodSource("parameters")
void isSundayAndPreviousRunIsMonday(Locale locale) {
final Calendar cal = Calendar.getInstance(locale);
cal.set(2011, Calendar.JANUARY, 16, 0, 0, 0); // Sunday, Jan 16th 2011, 00:00
final String cronStr = "0 0 * * 1"; // Mondays @00:00
@@ -90,11 +85,12 @@ public class CronTabDayOfWeekLocaleTest {
final Calendar expected = Calendar.getInstance();
// Expected next: Monday, Jan 10th 2011, 00:00
expected.set(2011, Calendar.JANUARY, 10, 0, 0, 0);
compare(expected, actual);
compare(locale, expected, actual);
}
@Test
public void isSundayAndNextRunIsTuesday() throws Exception {
@ParameterizedTest
@MethodSource("parameters")
void isSundayAndNextRunIsTuesday(Locale locale) {
final Calendar cal = Calendar.getInstance(locale);
cal.set(2011, Calendar.JANUARY, 16, 0, 0, 0); // Sunday, Jan 16th 2011, 00:00
final String cronStr = "0 0 * * 2"; // Tuesdays @00:00
@@ -105,11 +101,12 @@ public class CronTabDayOfWeekLocaleTest {
final Calendar expected = Calendar.getInstance();
// Expected next: Tuesday, Jan 18th 2011, 00:00
expected.set(2011, Calendar.JANUARY, 18, 0, 0, 0);
compare(expected, actual);
compare(locale, expected, actual);
}
@Test
public void isSundayAndPreviousRunIsTuesday() throws Exception {
@ParameterizedTest
@MethodSource("parameters")
void isSundayAndPreviousRunIsTuesday(Locale locale) {
final Calendar cal = Calendar.getInstance(locale);
cal.set(2011, Calendar.JANUARY, 16, 0, 0, 0); // Sunday, Jan 16th 2011, 00:00
final String cronStr = "0 0 * * 2"; // Tuesdays @00:00
@@ -120,11 +117,12 @@ public class CronTabDayOfWeekLocaleTest {
final Calendar expected = Calendar.getInstance();
// Expected next: Tuesday, Jan 11th 2011, 00:00
expected.set(2011, Calendar.JANUARY, 11, 0, 0, 0);
compare(expected, actual);
compare(locale, expected, actual);
}
@Test
public void isSundayAndNextRunIsWednesday() throws Exception {
@ParameterizedTest
@MethodSource("parameters")
void isSundayAndNextRunIsWednesday(Locale locale) {
final Calendar cal = Calendar.getInstance(locale);
cal.set(2011, Calendar.JANUARY, 16, 0, 0, 0); // Sunday, Jan 16th 2011, 00:00
final String cronStr = "0 0 * * 3"; // Wednesdays @00:00
@@ -135,11 +133,12 @@ public class CronTabDayOfWeekLocaleTest {
final Calendar expected = Calendar.getInstance();
// Expected next: Wednesday, Jan 19th 2011, 00:00
expected.set(2011, Calendar.JANUARY, 19, 0, 0, 0);
compare(expected, actual);
compare(locale, expected, actual);
}
@Test
public void isSundayAndPreviousRunIsWednesday() throws Exception {
@ParameterizedTest
@MethodSource("parameters")
void isSundayAndPreviousRunIsWednesday(Locale locale) {
final Calendar cal = Calendar.getInstance(locale);
cal.set(2011, Calendar.JANUARY, 16, 0, 0, 0); // Sunday, Jan 16th 2011, 00:00
final String cronStr = "0 0 * * 3"; // Wednesdays @00:00
@@ -150,11 +149,12 @@ public class CronTabDayOfWeekLocaleTest {
final Calendar expected = Calendar.getInstance();
// Expected next: Wednesday, Jan 12th 2011, 00:00
expected.set(2011, Calendar.JANUARY, 12, 0, 0, 0);
compare(expected, actual);
compare(locale, expected, actual);
}
@Test
public void isSundayAndNextRunIsThursday() throws Exception {
@ParameterizedTest
@MethodSource("parameters")
void isSundayAndNextRunIsThursday(Locale locale) {
final Calendar cal = Calendar.getInstance(locale);
cal.set(2011, Calendar.JANUARY, 16, 0, 0, 0); // Sunday, Jan 16th 2011, 00:00
final String cronStr = "0 0 * * 4"; // Thursdays @00:00
@@ -165,11 +165,12 @@ public class CronTabDayOfWeekLocaleTest {
final Calendar expected = Calendar.getInstance();
// Expected next: Thursday, Jan 20th 2011, 00:00
expected.set(2011, Calendar.JANUARY, 20, 0, 0, 0);
compare(expected, actual);
compare(locale, expected, actual);
}
@Test
public void isSundayAndPreviousRunIsThursday() throws Exception {
@ParameterizedTest
@MethodSource("parameters")
void isSundayAndPreviousRunIsThursday(Locale locale) {
final Calendar cal = Calendar.getInstance(locale);
cal.set(2011, Calendar.JANUARY, 16, 0, 0, 0); // Sunday, Jan 16th 2011, 00:00
final String cronStr = "0 0 * * 4"; // Thursdays @00:00
@@ -180,11 +181,12 @@ public class CronTabDayOfWeekLocaleTest {
final Calendar expected = Calendar.getInstance();
// Expected next: Thursday, Jan 13th 2011, 00:00
expected.set(2011, Calendar.JANUARY, 13, 0, 0, 0);
compare(expected, actual);
compare(locale, expected, actual);
}
@Test
public void isSundayAndNextRunIsFriday() throws Exception {
@ParameterizedTest
@MethodSource("parameters")
void isSundayAndNextRunIsFriday(Locale locale) {
final Calendar cal = Calendar.getInstance(locale);
cal.set(2011, Calendar.JANUARY, 16, 0, 0, 0); // Sunday, Jan 16th 2011, 00:00
final String cronStr = "0 0 * * 5"; // Fridays @00:00
@@ -195,11 +197,12 @@ public class CronTabDayOfWeekLocaleTest {
final Calendar expected = Calendar.getInstance();
// Expected next: Friday, Jan 21th 2011, 00:00
expected.set(2011, Calendar.JANUARY, 21, 0, 0, 0);
compare(expected, actual);
compare(locale, expected, actual);
}
@Test
public void isSundayAndPreviousRunIsFriday() throws Exception {
@ParameterizedTest
@MethodSource("parameters")
void isSundayAndPreviousRunIsFriday(Locale locale) {
final Calendar cal = Calendar.getInstance(locale);
cal.set(2011, Calendar.JANUARY, 16, 0, 0, 0); // Sunday, Jan 16th 2011, 00:00
final String cronStr = "0 0 * * 5"; // Fridays @00:00
@@ -210,11 +213,12 @@ public class CronTabDayOfWeekLocaleTest {
final Calendar expected = Calendar.getInstance();
// Expected next: Friday, Jan 14th 2011, 00:00
expected.set(2011, Calendar.JANUARY, 14, 0, 0, 0);
compare(expected, actual);
compare(locale, expected, actual);
}
@Test
public void isSundayAndNextRunIsSaturday() throws Exception {
@ParameterizedTest
@MethodSource("parameters")
void isSundayAndNextRunIsSaturday(Locale locale) {
final Calendar cal = Calendar.getInstance(locale);
cal.set(2011, Calendar.JANUARY, 16, 0, 0, 0); // Sunday, Jan 16th 2011, 00:00
final String cronStr = "0 0 * * 6"; // Saturdays @00:00
@@ -225,11 +229,12 @@ public class CronTabDayOfWeekLocaleTest {
final Calendar expected = Calendar.getInstance();
// Expected next: Saturday, Jan 22th 2011, 00:00
expected.set(2011, Calendar.JANUARY, 22, 0, 0, 0);
compare(expected, actual);
compare(locale, expected, actual);
}
@Test
public void isSundayAndPreviousRunIsSaturday() throws Exception {
@ParameterizedTest
@MethodSource("parameters")
void isSundayAndPreviousRunIsSaturday(Locale locale) {
final Calendar cal = Calendar.getInstance(locale);
cal.set(2011, Calendar.JANUARY, 16, 0, 0, 0); // Sunday, Jan 16th 2011, 00:00
final String cronStr = "0 0 * * 6"; // Saturdays @00:00
@@ -240,11 +245,12 @@ public class CronTabDayOfWeekLocaleTest {
final Calendar expected = Calendar.getInstance();
// Expected next: Saturday, Jan 15th 2011, 00:00
expected.set(2011, Calendar.JANUARY, 15, 0, 0, 0);
compare(expected, actual);
compare(locale, expected, actual);
}
@Test
public void isSundayAndNextRunIsNextSunday() throws Exception {
@ParameterizedTest
@MethodSource("parameters")
void isSundayAndNextRunIsNextSunday(Locale locale) {
final Calendar cal = Calendar.getInstance(locale);
cal.set(2011, Calendar.JANUARY, 16, 1, 0, 0); // Sunday, Jan 16th 2011, 01:00
final String cronStr = "0 0 * * 0"; // Sundays @00:00
@@ -255,11 +261,12 @@ public class CronTabDayOfWeekLocaleTest {
final Calendar expected = Calendar.getInstance();
// Expected next: Sunday, Jan 22th 2011, 00:00
expected.set(2011, Calendar.JANUARY, 23, 0, 0, 0);
compare(expected, actual);
compare(locale, expected, actual);
}
@Test
public void isSundayAndPreviousRunIsPreviousSunday() throws Exception {
@ParameterizedTest
@MethodSource("parameters")
void isSundayAndPreviousRunIsPreviousSunday(Locale locale) {
final Calendar cal = Calendar.getInstance(locale);
cal.set(2011, Calendar.JANUARY, 16, 0, 0, 0); // Sunday, Jan 16th 2011, 00:00
final String cronStr = "0 1 * * 0"; // Sundays @01:00
@@ -270,12 +277,13 @@ public class CronTabDayOfWeekLocaleTest {
final Calendar expected = Calendar.getInstance();
// Expected next: Sunday, Jan 9th 2011, 01:00
expected.set(2011, Calendar.JANUARY, 9, 1, 0, 0);
compare(expected, actual);
compare(locale, expected, actual);
}
@Test
@ParameterizedTest
@MethodSource("parameters")
@Issue("JENKINS-12357")
public void isSundayAndNextRunIsNextSunday7() throws Exception {
void isSundayAndNextRunIsNextSunday7(Locale locale) {
final Calendar cal = Calendar.getInstance(locale);
cal.set(2011, Calendar.JANUARY, 16, 1, 0, 0); // Sunday, Jan 16th 2011, 01:00
final String cronStr = "0 0 * * 7"; // Sundays(7 not 0) @00:00
@@ -286,11 +294,12 @@ public class CronTabDayOfWeekLocaleTest {
final Calendar expected = Calendar.getInstance();
// Expected next: Sunday, Jan 22th 2011, 00:00
expected.set(2011, Calendar.JANUARY, 23, 0, 0, 0);
compare(expected, actual);
compare(locale, expected, actual);
}
@Test
public void isSundayAndPreviousRunIsPreviousSunday7() throws Exception {
@ParameterizedTest
@MethodSource("parameters")
void isSundayAndPreviousRunIsPreviousSunday7(Locale locale) {
final Calendar cal = Calendar.getInstance(locale);
cal.set(2011, Calendar.JANUARY, 16, 0, 0, 0); // Sunday, Jan 16th 2011, 00:00
final String cronStr = "0 1 * * 7"; // Sundays(7 not 0) @01:00
@@ -301,11 +310,12 @@ public class CronTabDayOfWeekLocaleTest {
final Calendar expected = Calendar.getInstance();
// Expected next: Sunday, Jan 9th 2011, 01:00
expected.set(2011, Calendar.JANUARY, 9, 1, 0, 0);
compare(expected, actual);
compare(locale, expected, actual);
}
@Test
public void isSaturdayAndNextRunIsSundayAsterisk() throws Exception {
@ParameterizedTest
@MethodSource("parameters")
void isSaturdayAndNextRunIsSundayAsterisk(Locale locale) {
final Calendar cal = Calendar.getInstance(locale);
cal.set(2011, Calendar.JANUARY, 15, 1, 0, 0); // Saturday, Jan 15th 2011, 01:00
final String cronStr = "0 0 * * *"; // Everyday @00:00
@@ -316,11 +326,12 @@ public class CronTabDayOfWeekLocaleTest {
final Calendar expected = Calendar.getInstance();
// Expected next: Sunday, Jan 16th 2011, 00:00
expected.set(2011, Calendar.JANUARY, 16, 0, 0, 0);
compare(expected, actual);
compare(locale, expected, actual);
}
@Test
public void isSundayAndPreviousRunIsSaturdayAsterisk() throws Exception {
@ParameterizedTest
@MethodSource("parameters")
void isSundayAndPreviousRunIsSaturdayAsterisk(Locale locale) {
final Calendar cal = Calendar.getInstance(locale);
cal.set(2011, Calendar.JANUARY, 16, 0, 0, 0); // Sunday, Jan 16th 2011, 00:00
final String cronStr = "0 23 * * *"; // Everyday @23:00
@@ -331,17 +342,17 @@ public class CronTabDayOfWeekLocaleTest {
final Calendar expected = Calendar.getInstance();
// Expected next: Saturday, Jan 15th 2011, 23:00
expected.set(2011, Calendar.JANUARY, 15, 23, 0, 0);
compare(expected, actual);
compare(locale, expected, actual);
}
private void compare(final Calendar expected, final Calendar actual) {
private void compare(final Locale locale, final Calendar expected, final Calendar actual) {
final DateFormat f = DateFormat.getDateTimeInstance();
final String msg = "Locale: " + locale + " FirstDayOfWeek: " + actual.getFirstDayOfWeek() + " Expected: "
+ f.format(expected.getTime()) + " Actual: " + f.format(actual.getTime());
assertEquals(msg, expected.get(Calendar.YEAR), actual.get(Calendar.YEAR));
assertEquals(msg, expected.get(Calendar.MONTH), actual.get(Calendar.MONTH));
assertEquals(msg, expected.get(Calendar.DAY_OF_MONTH), actual.get(Calendar.DAY_OF_MONTH));
assertEquals(msg, expected.get(Calendar.HOUR), actual.get(Calendar.HOUR));
assertEquals(msg, expected.get(Calendar.MINUTE), actual.get(Calendar.MINUTE));
assertEquals(expected.get(java.util.Calendar.YEAR), actual.get(java.util.Calendar.YEAR), msg);
assertEquals(expected.get(java.util.Calendar.MONTH), actual.get(java.util.Calendar.MONTH), msg);
assertEquals(expected.get(java.util.Calendar.DAY_OF_MONTH), actual.get(Calendar.DAY_OF_MONTH), msg);
assertEquals(expected.get(Calendar.HOUR), actual.get(Calendar.HOUR), msg);
assertEquals(expected.get(Calendar.MINUTE), actual.get(Calendar.MINUTE), msg);
}
}
@@ -1,23 +1,21 @@
package hudson.scheduler;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.fail;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.GregorianCalendar;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.jvnet.hudson.test.For;
import org.jvnet.hudson.test.Issue;
@RunWith(Parameterized.class)
@For({CronTab.class, Hash.class})
public class CronTabEventualityTest {
@Parameterized.Parameters
public static Collection<Object[]> parameters() {
class CronTabEventualityTest {
static Collection<Object[]> parameters() {
Collection<Object[]> parameters = new ArrayList<>();
parameters.add(new Object[]{"zero", Hash.zero()});
parameters.add(new Object[]{"seed1", Hash.from("seed1")});
@@ -31,83 +29,84 @@ public class CronTabEventualityTest {
return limit;
}
private String name;
private Hash hash;
public CronTabEventualityTest(String name, Hash hash) {
this.name = name;
this.hash = hash;
}
@Test
@ParameterizedTest
@MethodSource("parameters")
@Issue("JENKINS-12388")
public void testYearlyWillBeEventuallyTriggeredWithinOneYear() {
void testYearlyWillBeEventuallyTriggeredWithinOneYear(String name, Hash hash) {
Calendar start = new GregorianCalendar(2012, Calendar.JANUARY, 11, 22, 33); // Jan 11th 2012 22:33
Calendar limit = createLimit(start, Calendar.YEAR, 1);
checkEventuality(start, "@yearly", limit);
checkEventuality(name, hash, start, "@yearly", limit);
}
@Test
@ParameterizedTest
@MethodSource("parameters")
@Issue("JENKINS-12388")
public void testAnnuallyWillBeEventuallyTriggeredWithinOneYear() {
void testAnnuallyWillBeEventuallyTriggeredWithinOneYear(String name, Hash hash) {
Calendar start = new GregorianCalendar(2012, Calendar.JANUARY, 11, 22, 33); // Jan 11th 2012 22:33
Calendar limit = createLimit(start, Calendar.YEAR, 1);
checkEventuality(start, "@annually", limit);
checkEventuality(name, hash, start, "@annually", limit);
}
@Test
public void testMonthlyWillBeEventuallyTriggeredWithinOneMonth() {
@ParameterizedTest
@MethodSource("parameters")
void testMonthlyWillBeEventuallyTriggeredWithinOneMonth(String name, Hash hash) {
Calendar start = new GregorianCalendar(2012, Calendar.JANUARY, 11, 22, 33); // Jan 11th 2012 22:33
Calendar limit = createLimit(start, Calendar.MONTH, 1);
checkEventuality(start, "@monthly", limit);
checkEventuality(name, hash, start, "@monthly", limit);
}
@Test
public void testWeeklyWillBeEventuallyTriggeredWithinOneWeek() {
@ParameterizedTest
@MethodSource("parameters")
void testWeeklyWillBeEventuallyTriggeredWithinOneWeek(String name, Hash hash) {
Calendar start = new GregorianCalendar(2012, Calendar.JANUARY, 11, 22, 33); // Jan 11th 2012 22:33
Calendar limit = createLimit(start, Calendar.WEEK_OF_YEAR, 1);
checkEventuality(start, "@weekly", limit);
checkEventuality(name, hash, start, "@weekly", limit);
}
@Test
public void testDailyWillBeEventuallyTriggeredWithinOneDay() {
@ParameterizedTest
@MethodSource("parameters")
void testDailyWillBeEventuallyTriggeredWithinOneDay(String name, Hash hash) {
Calendar start = new GregorianCalendar(2012, Calendar.JANUARY, 11, 22, 33); // Jan 11th 2012 22:33
Calendar limit = createLimit(start, Calendar.DAY_OF_MONTH, 1);
checkEventuality(start, "@daily", limit);
checkEventuality(name, hash, start, "@daily", limit);
}
@Test
public void testMidnightWillBeEventuallyTriggeredWithinOneDay() {
@ParameterizedTest
@MethodSource("parameters")
void testMidnightWillBeEventuallyTriggeredWithinOneDay(String name, Hash hash) {
Calendar start = new GregorianCalendar(2012, Calendar.JANUARY, 11, 22, 33); // Jan 11th 2012 22:33
Calendar limit = createLimit(start, Calendar.DAY_OF_MONTH, 1);
checkEventuality(start, "@midnight", limit);
checkEventuality(name, hash, start, "@midnight", limit);
}
@Test
public void testHourlyWillBeEventuallyTriggeredWithinOneHour() {
@ParameterizedTest
@MethodSource("parameters")
void testHourlyWillBeEventuallyTriggeredWithinOneHour(String name, Hash hash) {
Calendar start = new GregorianCalendar(2012, Calendar.JANUARY, 11, 22, 33); // Jan 11th 2012 22:33
Calendar limit = createLimit(start, Calendar.HOUR, 1);
checkEventuality(start, "@hourly", limit);
checkEventuality(name, hash, start, "@hourly", limit);
}
@Test
public void testFirstDayOfMonthWillBeEventuallyTriggeredWithinOneMonth() {
@ParameterizedTest
@MethodSource("parameters")
void testFirstDayOfMonthWillBeEventuallyTriggeredWithinOneMonth(String name, Hash hash) {
Calendar start = new GregorianCalendar(2012, Calendar.JANUARY, 11, 22, 33); // Jan 11th 2012 22:33
Calendar limit = createLimit(start, Calendar.MONTH, 1);
checkEventuality(start, "H H 1 * *", limit);
checkEventuality(name, hash, start, "H H 1 * *", limit);
}
@Test
public void testFirstSundayOfMonthWillBeEventuallyTriggeredWithinOneMonthAndOneWeek() {
@ParameterizedTest
@MethodSource("parameters")
void testFirstSundayOfMonthWillBeEventuallyTriggeredWithinOneMonthAndOneWeek(String name, Hash hash) {
Calendar start = new GregorianCalendar(2012, Calendar.JANUARY, 11, 22, 33); // Jan 11th 2012 22:33
Calendar limit = createLimit(start, Calendar.DAY_OF_MONTH, 31 + 7);
// If both day of month and day of week are specified:
// UNIX: triggered when either matches
// Jenkins: triggered when both match
checkEventuality(start, "H H 1-7 * 0", limit);
checkEventuality(name, hash, start, "H H 1-7 * 0", limit);
}
private void checkEventuality(Calendar start, String crontabFormat, Calendar limit) {
private void checkEventuality(String name, Hash hash, Calendar start, String crontabFormat, Calendar limit) {
CronTab cron = new CronTab(crontabFormat, hash);
Calendar next = cron.ceil(start);
if (next.after(limit)) {
@@ -28,9 +28,9 @@ import static java.util.Calendar.MONDAY;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import antlr.ANTLRException;
import java.text.DateFormat;
@@ -42,17 +42,19 @@ import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.jvnet.hudson.test.Issue;
/**
* @author Kohsuke Kawaguchi
*/
public class CronTabTest {
class CronTabTest {
@Test
public void test1() {
void test1() {
new CronTab("@yearly");
new CronTab("@weekly");
new CronTab("@midnight");
@@ -61,7 +63,7 @@ public class CronTabTest {
}
@Test
public void testCeil1() throws Exception {
void testCeil1() {
CronTab x = new CronTab("0,30 * * * *");
Calendar c = new GregorianCalendar(2000, Calendar.MARCH, 1, 1, 10);
compare(new GregorianCalendar(2000, Calendar.MARCH, 1, 1, 30), x.ceil(c));
@@ -72,7 +74,7 @@ public class CronTabTest {
}
@Test
public void testCeil2() throws Exception {
void testCeil2() {
// make sure that lower fields are really reset correctly
CronTab x = new CronTab("15,45 3 * * *");
Calendar c = new GregorianCalendar(2000, Calendar.MARCH, 1, 2, 30);
@@ -80,7 +82,7 @@ public class CronTabTest {
}
@Test
public void testCeil3() throws Exception {
void testCeil3() {
// conflict between DoM and DoW. In this we need to find a day that's the first day of a month and Sunday
CronTab x = new CronTab("0 0 1 * 0");
Calendar c = new GregorianCalendar(2010, Calendar.JANUARY, 1, 15, 55);
@@ -88,9 +90,10 @@ public class CronTabTest {
compare(new GregorianCalendar(2010, Calendar.AUGUST, 1, 0, 0), x.ceil(c));
}
@Test(timeout = 1000)
@Test
@Timeout(value = 1000, unit = TimeUnit.MILLISECONDS)
@Issue("JENKINS-12357")
public void testCeil3_DoW7() throws Exception {
void testCeil3_DoW7() {
// similar to testCeil3, but DoW=7 may stuck in an infinite loop
CronTab x = new CronTab("0 0 1 * 7");
Calendar c = new GregorianCalendar(2010, Calendar.JANUARY, 1, 15, 55);
@@ -103,7 +106,7 @@ public class CronTabTest {
*/
@Issue("HUDSON-8656") // This is _not_ JENKINS-8656
@Test
public void testCeil4() {
void testCeil4() {
final Calendar cal = Calendar.getInstance(new Locale("de", "de"));
cal.set(2011, Calendar.JANUARY, 16, 0, 0, 0); // Sunday, Jan 16th 2011, 00:00
final String cronStr = "0 23 * * 1-5"; // execute on weekdays @23:00
@@ -125,7 +128,7 @@ public class CronTabTest {
*/
@Issue("HUDSON-8656") // This is _not_ JENKINS-8656
@Test
public void testCeil5() {
void testCeil5() {
final Calendar cal = Calendar.getInstance(new Locale("de", "at"));
cal.set(2011, Calendar.JANUARY, 16, 0, 0, 0); // Sunday, Jan 16th 2011, 00:00
final String cronStr = "0 23 * * 1-5"; // execute on weekdays @23:00
@@ -143,7 +146,7 @@ public class CronTabTest {
}
@Test
public void testFloor1() throws Exception {
void testFloor1() {
CronTab x = new CronTab("30 * * * *");
Calendar c = new GregorianCalendar(2000, Calendar.MARCH, 1, 1, 40);
compare(new GregorianCalendar(2000, Calendar.MARCH, 1, 1, 30), x.floor(c));
@@ -154,7 +157,7 @@ public class CronTabTest {
}
@Test
public void testFloor2() throws Exception {
void testFloor2() {
// make sure that lower fields are really reset correctly
CronTab x = new CronTab("15,45 3 * * *");
Calendar c = new GregorianCalendar(2000, Calendar.MARCH, 1, 4, 30);
@@ -162,7 +165,7 @@ public class CronTabTest {
}
@Test
public void testFloor3() throws Exception {
void testFloor3() {
// conflict between DoM and DoW. In this we need to find a day that's the first day of a month and Sunday in 2010
CronTab x = new CronTab("0 0 1 * 0");
Calendar c = new GregorianCalendar(2011, Calendar.JANUARY, 1, 15, 55);
@@ -172,7 +175,7 @@ public class CronTabTest {
@Issue("JENKINS-8401")
@Test
public void testFloor4() throws Exception {
void testFloor4() {
// conflict between DoM and DoW. In this we need to find a day that's the first day of a month and Sunday in 2010
CronTab x = new CronTab("0 0 1 * 0");
Calendar c = new GregorianCalendar(2011, Calendar.JANUARY, 1, 15, 55);
@@ -183,7 +186,8 @@ public class CronTabTest {
compare(answer, x.floor(c));
}
@Test public void checkSanity() throws Exception {
@Test
void checkSanity() {
assertNull(new CronTab("@hourly").checkSanity());
assertEquals(Messages.CronTab_do_you_really_mean_every_minute_when_you("* * * * *", "H * * * *"), new CronTab("* * * * *").checkSanity());
assertEquals(Messages.CronTab_do_you_really_mean_every_minute_when_you("*/1 * * * *", "H * * * *"), new CronTab("*/1 * * * *").checkSanity());
@@ -215,7 +219,7 @@ public class CronTabTest {
}
@Test
public void testHash1() throws Exception {
void testHash1() {
CronTab x = new CronTab("H H(5-8) H/3 H(1-10)/4 *", new Hash() {
@Override
public int next(int n) {
@@ -240,7 +244,7 @@ public class CronTabTest {
}
@Test
public void testHash2() throws Exception {
void testHash2() {
CronTab x = new CronTab("H H(5-8) H/3 H(1-10)/4 *", new Hash() {
@Override
public int next(int n) {
@@ -254,7 +258,8 @@ public class CronTabTest {
assertEquals("2;6;10;", bitset(x.bits[3]));
}
@Test public void hashedMinute() throws Exception {
@Test
void hashedMinute() {
long t = new GregorianCalendar(2013, Calendar.MARCH, 21, 16, 21).getTimeInMillis();
compare(new GregorianCalendar(2013, Calendar.MARCH, 21, 17, 56), new CronTab("H 17 * * *", Hash.from("stuff")).ceil(t));
compare(new GregorianCalendar(2013, Calendar.MARCH, 21, 16, 56), new CronTab("H * * * *", Hash.from("stuff")).ceil(t));
@@ -263,7 +268,8 @@ public class CronTabTest {
compare(new GregorianCalendar(2013, Calendar.MARCH, 22, 13, 56), new CronTab("H H(12-13) * * *", Hash.from("stuff")).ceil(t));
}
@Test public void hashSkips() throws Exception {
@Test
void hashSkips() {
compare(new GregorianCalendar(2013, Calendar.MARCH, 21, 16, 26), new CronTab("H/15 * * * *", Hash.from("stuff")).ceil(new GregorianCalendar(2013, Calendar.MARCH, 21, 16, 21)));
compare(new GregorianCalendar(2013, Calendar.MARCH, 21, 16, 41), new CronTab("H/15 * * * *", Hash.from("stuff")).ceil(new GregorianCalendar(2013, Calendar.MARCH, 21, 16, 31)));
compare(new GregorianCalendar(2013, Calendar.MARCH, 21, 16, 56), new CronTab("H/15 * * * *", Hash.from("stuff")).ceil(new GregorianCalendar(2013, Calendar.MARCH, 21, 16, 42)));
@@ -287,7 +293,8 @@ public class CronTabTest {
}
@Test public void repeatedHash() throws Exception {
@Test
void repeatedHash() {
CronTabList tabs = CronTabList.create("H * * * *\nH * * * *", Hash.from("seed"));
List<Integer> times = new ArrayList<>();
for (int i = 0; i < 60; i++) {
@@ -298,11 +305,13 @@ public class CronTabTest {
assertEquals("[35, 56]", times.toString());
}
@Test public void rangeBoundsCheckOK() throws Exception {
@Test
void rangeBoundsCheckOK() {
new CronTab("H(0-59) H(0-23) H(1-31) H(1-12) H(0-7)");
}
@Test public void rangeBoundsCheckFailHour() {
@Test
void rangeBoundsCheckFailHour() {
Locale saveLocale = Locale.getDefault();
Locale.setDefault(Locale.ENGLISH);
@@ -316,7 +325,8 @@ public class CronTabTest {
}
}
@Test public void rangeBoundsCheckFailMinute() {
@Test
void rangeBoundsCheckFailMinute() {
Locale saveLocale = Locale.getDefault();
Locale.setDefault(Locale.ENGLISH);
@@ -331,7 +341,8 @@ public class CronTabTest {
}
@Issue("JENKINS-9283")
@Test public void testTimezone() throws Exception {
@Test
void testTimezone() {
CronTabList tabs = CronTabList.create("TZ=Australia/Sydney\nH * * * *\nH * * * *", Hash.from("seed"));
List<Integer> times = new ArrayList<>();
for (int i = 0; i < 60; i++) {
@@ -344,7 +355,8 @@ public class CronTabTest {
assertEquals("[35, 56]", times.toString());
}
@Test public void floorCeilMinuteGranularity() throws Exception {
@Test
void floorCeilMinuteGranularity() {
var tab = new CronTab("*/5 * * * *");
assertFloorCeil(tab, new GregorianCalendar(2025, 2, 4, 14, 15, 23), "2025-03-04T14:15:00", "2025-03-04T14:20:00");
assertFloorCeil(tab, new GregorianCalendar(2025, 2, 4, 14, 19, 23), "2025-03-04T14:15:00", "2025-03-04T14:20:00");
@@ -363,14 +375,18 @@ public class CronTabTest {
}
@Issue("SECURITY-790")
@Test(timeout = 1000L) public void testLongMonths() throws Exception {
@Test
@Timeout(value = 1000L, unit = TimeUnit.MILLISECONDS)
void testLongMonths() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, Calendar.JULY);
new CronTab("0 0 31 7 *").floor(cal); // would infinite loop
}
@Issue("SECURITY-1193")
@Test(timeout = 1000L) public void testCeilLongMonths() throws Exception {
@Test
@Timeout(value = 1000L, unit = TimeUnit.MILLISECONDS)
void testCeilLongMonths() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, Calendar.NOVEMBER);
new CronTab("0 0 31 * *").ceil(cal); // would infinite loop
@@ -24,21 +24,21 @@
package hudson.search;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import hudson.Util;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* @author Kohsuke Kawaguchi
*/
public class SearchTest {
class SearchTest {
@Test
public void findAndSuggest() {
void findAndSuggest() {
SearchIndex si = new SearchIndexBuilder()
.add("abc-def-ghi", "abc def ghi")
.add(SearchItems.create("abc", "abc",
@@ -62,7 +62,7 @@ public class SearchTest {
* search name, that the one with the search query in the url is returned
*/
@Test
public void findClosestSuggestedItem() {
void findClosestSuggestedItem() {
final String query = "foobar 123";
final String searchName = "sameDisplayName";
@@ -79,7 +79,7 @@ public class HudsonPrivateSecurityRealmTest {
}
@Test
public void testPBKDF2RegExp() {
void testPBKDF2RegExp() {
PBKDF2PasswordEncoder encoder = new PBKDF2PasswordEncoder();
String encoded = encoder.encode("thisIsMyPassword");
assertTrue(encoder.isHashValid(encoded));
@@ -115,7 +115,7 @@ public class HudsonPrivateSecurityRealmTest {
}
@Test
public void testPBKDF2PasswordMatching() {
void testPBKDF2PasswordMatching() {
PBKDF2PasswordEncoder encoder = new PBKDF2PasswordEncoder();
String encoded = encoder.encode("thisIsMyPassword");
assertTrue(encoder.matches("thisIsMyPassword", encoded));
@@ -123,7 +123,7 @@ public class HudsonPrivateSecurityRealmTest {
}
@Test
public void passwordPBKDF2WithMissingAgorithm() throws Exception {
void passwordPBKDF2WithMissingAgorithm() throws Exception {
HudsonPrivateSecurityRealm.PBKDF2PasswordEncoder pbkdf2PasswordEncoder = new HudsonPrivateSecurityRealm.PBKDF2PasswordEncoder();
try (var ignored = mockStatic(SecretKeyFactory.class)) {
when(SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512")).thenThrow(NoSuchAlgorithmException.class);
@@ -135,7 +135,7 @@ public class HudsonPrivateSecurityRealmTest {
}
@Test
public void passwordPBKDF2HashWithInvalidKeySpec() throws Exception {
void passwordPBKDF2HashWithInvalidKeySpec() throws Exception {
HudsonPrivateSecurityRealm.PBKDF2PasswordEncoder pbkdf2PasswordEncoder = new HudsonPrivateSecurityRealm.PBKDF2PasswordEncoder();
try (var ignored = mockStatic(SecretKeyFactory.class)) {
SecretKeyFactory skf = mock(SecretKeyFactory.class);
@@ -149,7 +149,7 @@ public class HudsonPrivateSecurityRealmTest {
}
@Test
public void testJBCryptPasswordMatching() {
void testJBCryptPasswordMatching() {
JBCryptEncoder encoder = new JBCryptEncoder();
String encoded = encoder.encode("thisIsMyPassword");
assertTrue(encoder.matches("thisIsMyPassword", encoded));
@@ -1,7 +1,7 @@
package hudson.slaves;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
@@ -10,13 +10,13 @@ import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
public class ChannelPingerTest {
class ChannelPingerTest {
@Mock private Channel mockChannel;
@@ -24,25 +24,25 @@ public class ChannelPingerTest {
private AutoCloseable mocks;
@After
public void tearDown() throws Exception {
@AfterEach
void tearDown() throws Exception {
mocks.close();
}
@Before
public void setUp() {
@BeforeEach
void setUp() {
mocks = MockitoAnnotations.openMocks(this);
}
@Before
public void preserveSystemProperties() {
@BeforeEach
void preserveSystemProperties() {
preserveSystemProperty("hudson.slaves.ChannelPinger.pingInterval");
preserveSystemProperty("hudson.slaves.ChannelPinger.pingIntervalSeconds");
preserveSystemProperty("hudson.slaves.ChannelPinger.pingTimeoutSeconds");
}
@After
public void restoreSystemProperties() {
@AfterEach
void restoreSystemProperties() {
for (Map.Entry<String, String> entry : savedSystemProperties.entrySet()) {
if (entry.getValue() != null) {
System.setProperty(entry.getKey(), entry.getValue());
@@ -58,7 +58,7 @@ public class ChannelPingerTest {
}
@Test
public void testDefaults() throws IOException, InterruptedException {
void testDefaults() throws IOException, InterruptedException {
ChannelPinger channelPinger = new ChannelPinger();
channelPinger.install(mockChannel, null);
@@ -69,7 +69,7 @@ public class ChannelPingerTest {
}
@Test
public void testFromSystemProperties() throws IOException, InterruptedException {
void testFromSystemProperties() throws IOException, InterruptedException {
System.setProperty("hudson.slaves.ChannelPinger.pingTimeoutSeconds", "42");
System.setProperty("hudson.slaves.ChannelPinger.pingIntervalSeconds", "73");
@@ -81,7 +81,7 @@ public class ChannelPingerTest {
}
@Test
public void testFromOldSystemProperty() throws IOException, InterruptedException {
void testFromOldSystemProperty() throws IOException, InterruptedException {
System.setProperty("hudson.slaves.ChannelPinger.pingInterval", "7");
ChannelPinger channelPinger = new ChannelPinger();
@@ -92,7 +92,7 @@ public class ChannelPingerTest {
}
@Test
public void testNewSystemPropertyTrumpsOld() throws IOException, InterruptedException {
void testNewSystemPropertyTrumpsOld() throws IOException, InterruptedException {
System.setProperty("hudson.slaves.ChannelPinger.pingIntervalSeconds", "73");
System.setProperty("hudson.slaves.ChannelPinger.pingInterval", "7");
@@ -104,7 +104,7 @@ public class ChannelPingerTest {
}
@Test
public void testSetUpRemotePingEquality() {
void testSetUpRemotePingEquality() {
ChannelPinger.SetUpRemotePing pinger1a = new ChannelPinger.SetUpRemotePing(1, 2);
ChannelPinger.SetUpRemotePing pinger1b = new ChannelPinger.SetUpRemotePing(1, 2);
ChannelPinger.SetUpRemotePing pinger2a = new ChannelPinger.SetUpRemotePing(2, 3);
@@ -1,14 +1,14 @@
package hudson.slaves;
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.model.Messages;
import hudson.model.queue.CauseOfBlockage;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.jvnet.hudson.test.Issue;
public class CloudProvisioningListenerTest {
class CloudProvisioningListenerTest {
public static class CloudProvisioningListenerNoOverride extends CloudProvisioningListener {}
public static class CloudProvisioningListenerOverride extends CloudProvisioningListener {
@@ -20,14 +20,14 @@ public class CloudProvisioningListenerTest {
@Issue("JENKINS-63828")
@Test
public void noOverride() {
void noOverride() {
Cloud.CloudState state = new Cloud.CloudState(null, 0);
assertNull(new CloudProvisioningListenerNoOverride().canProvision(null, state, 0));
}
@Issue("JENKINS-63828")
@Test
public void override() {
void override() {
Cloud.CloudState state = new Cloud.CloudState(null, 0);
assertNotNull(new CloudProvisioningListenerOverride().canProvision(null, state, 0));
}
@@ -37,43 +37,53 @@ import java.nio.charset.Charset;
import org.junit.jupiter.api.Test;
import org.jvnet.hudson.test.Issue;
public class ComputerLauncherTest {
class ComputerLauncherTest {
@Test public void jdk7() {
@Test
void jdk7() {
assertThrows(
IOException.class,
() ->
assertChecked(
"java version \"1.7.0_05\"\n"
+ "Java(TM) SE Runtime Environment (build 1.7.0_05-b05)\n"
+ "Java HotSpot(TM) Server VM (build 23.1-b03, mixed mode)\n",
"""
java version "1.7.0_05"
Java(TM) SE Runtime Environment (build 1.7.0_05-b05)
Java HotSpot(TM) Server VM (build 23.1-b03, mixed mode)
""",
"1.7.0"));
}
@Test public void openJDK7() {
@Test
void openJDK7() {
assertThrows(
IOException.class,
() ->
assertChecked(
"openjdk version \"1.7.0-internal\"\n"
+ "OpenJDK Runtime Environment (build"
+ " 1.7.0-internal-pkgsrc_2010_01_03_06_54-b00)\n"
+ "OpenJDK 64-Bit Server VM (build 17.0-b04, mixed mode)\n",
"""
openjdk version "1.7.0-internal"
OpenJDK Runtime Environment (build\
1.7.0-internal-pkgsrc_2010_01_03_06_54-b00)
OpenJDK 64-Bit Server VM (build 17.0-b04, mixed mode)
""",
"1.7.0"));
}
@Test public void jdk6() {
@Test
void jdk6() {
assertThrows(
IOException.class,
() ->
assertChecked(
"java version \"1.6.0_33\"\n"
+ "Java(TM) SE Runtime Environment (build 1.6.0_33-b03)\n"
+ "Java HotSpot(TM) Server VM (build 20.8-b03, mixed mode)\n",
"""
java version "1.6.0_33"
Java(TM) SE Runtime Environment (build 1.6.0_33-b03)
Java HotSpot(TM) Server VM (build 20.8-b03, mixed mode)
""",
"1.6.0"));
}
@Test public void jdk5() {
@Test
void jdk5() {
assertThrows(
IOException.class,
() ->
@@ -82,12 +92,15 @@ public class ComputerLauncherTest {
"-",
new BufferedReader(
new StringReader(
"java version \"1.5.0_22\"\n"
+ "Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_22-b03)\n"
+ "Java HotSpot(TM) Server VM (build 1.5.0_22-b03, mixed mode)\n"))));
"""
java version "1.5.0_22"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_22-b03)
Java HotSpot(TM) Server VM (build 1.5.0_22-b03, mixed mode)
"""))));
}
@Test public void j2sdk4() {
@Test
void j2sdk4() {
assertThrows(
IOException.class,
() ->
@@ -96,49 +109,62 @@ public class ComputerLauncherTest {
"-",
new BufferedReader(
new StringReader(
"java version \"1.4.2_19\"\n"
+ "Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_19-b04)\n"
+ "Java HotSpot(TM) Client VM (build 1.4.2_19-b04, mixed mode)\n"))));
"""
java version "1.4.2_19"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_19-b04)
Java HotSpot(TM) Client VM (build 1.4.2_19-b04, mixed mode)
"""))));
}
@Test public void jdk8() throws IOException {
@Test
void jdk8() throws IOException {
assertChecked("java version \"1.8.0_05\"\nJava(TM) SE Runtime Environment (build 1.8.0_05-b05)\nJava HotSpot(TM) Server VM (build 23.1-b03, mixed mode)\n", "1.8.0");
}
@Test public void openJDK8() throws IOException {
@Test
void openJDK8() throws IOException {
assertChecked("openjdk version \"1.8.0-internal\"\nOpenJDK Runtime Environment (build 1.8.0-internal-pkgsrc_2015_01_03_06_54-b00)\nOpenJDK 64-Bit Server VM (build 17.0-b04, mixed mode)\n", "1.8.0");
}
@Test public void jdk10() throws IOException { // predicted
@Test
void jdk10() throws IOException { // predicted
assertChecked("java version \"1.10.0_02\"\nJava(TM) SE Runtime Environment (build 1.10.0_02-b01)\nJava HotSpot(TM) Server VM (build 23.1-b03, mixed mode)\n", "1.10.0");
}
@Issue("JENKINS-60678")
@Test public void adoptOpenJDK11() throws IOException {
assertChecked("openjdk version \"11.0.5\" 2019-10-15\n" +
"OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.5+10)\n" +
"OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.5+10, mixed mode)", "11.0.5");
@Test
void adoptOpenJDK11() throws IOException {
assertChecked("""
openjdk version "11.0.5" 2019-10-15
OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.5+10)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.5+10, mixed mode)""", "11.0.5");
}
@Issue("JENKINS-60678")
@Test public void amazonCorrettoJDK11() throws IOException {
assertChecked("openjdk version \"11.0.6\" 2020-01-14 LTS\n" +
"OpenJDK Runtime Environment Corretto-11.0.6.10.1 (build 11.0.6+10-LTS)\n" +
"OpenJDK 64-Bit Server VM Corretto-11.0.6.10.1 (build 11.0.6+10-LTS, mixed mode)", "11.0.6");
@Test
void amazonCorrettoJDK11() throws IOException {
assertChecked("""
openjdk version "11.0.6" 2020-01-14 LTS
OpenJDK Runtime Environment Corretto-11.0.6.10.1 (build 11.0.6+10-LTS)
OpenJDK 64-Bit Server VM Corretto-11.0.6.10.1 (build 11.0.6+10-LTS, mixed mode)""", "11.0.6");
}
@Issue("JENKINS-60678")
@Test public void openJDK1106() throws IOException {
assertChecked("openjdk version \"11.0.6\" 2020-01-14\n" +
"OpenJDK Runtime Environment 18.9 (build 11.0.6+10)\n" +
"OpenJDK 64-Bit Server VM 18.9 (build 11.0.6+10, mixed mode)", "11.0.6");
@Test
void openJDK1106() throws IOException {
assertChecked("""
openjdk version "11.0.6" 2020-01-14
OpenJDK Runtime Environment 18.9 (build 11.0.6+10)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.6+10, mixed mode)""", "11.0.6");
}
@Issue("JENKINS-60678")
@Test public void azulZuluOpenJDK11() throws IOException {
assertChecked("openjdk version \"11.0.5\" 2019-10-15 LTS\n" +
"OpenJDK Runtime Environment Zulu11.35+15-CA (build 11.0.5+10-LTS)\n" +
"OpenJDK 64-Bit Server VM Zulu11.35+15-CA (build 11.0.5+10-LTS, mixed mode)", "11.0.5");
@Test
void azulZuluOpenJDK11() throws IOException {
assertChecked("""
openjdk version "11.0.5" 2019-10-15 LTS
OpenJDK Runtime Environment Zulu11.35+15-CA (build 11.0.5+10-LTS)
OpenJDK 64-Bit Server VM Zulu11.35+15-CA (build 11.0.5+10-LTS, mixed mode)""", "11.0.5");
}
private static void assertChecked(String text, String spec) throws IOException {
@@ -1,6 +1,6 @@
package hudson.slaves;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
@@ -11,16 +11,17 @@ import hudson.DescriptorExtensionList;
import hudson.model.Descriptor;
import java.util.ArrayList;
import jenkins.model.Jenkins;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
/**
* @author peppelan
*/
public class DelegatingComputerLauncherTest {
class DelegatingComputerLauncherTest {
public static class DummyOne extends DelegatingComputerLauncher {
@SuppressWarnings("checkstyle:redundantmodifier")
public DummyOne() {
super(null);
}
@@ -32,6 +33,7 @@ public class DelegatingComputerLauncherTest {
public static class DummyTwo extends DelegatingComputerLauncher {
@SuppressWarnings("checkstyle:redundantmodifier")
public DummyTwo() {
super(null);
}
@@ -43,7 +45,7 @@ public class DelegatingComputerLauncherTest {
// Ensure that by default a DelegatingComputerLauncher subclass doesn't advertise the option to delegate another
// DelegatingComputerLauncher
@Test
public void testRecursionAvoidance() {
void testRecursionAvoidance() {
Jenkins jenkins = mock(Jenkins.class);
try (MockedStatic<Jenkins> mocked = mockStatic(Jenkins.class)) {
mocked.when(Jenkins::get).thenReturn(jenkins);
@@ -58,9 +60,9 @@ public class DelegatingComputerLauncherTest {
when(mockList.iterator()).thenReturn(returnedList.iterator());
assertTrue("DelegatingComputerLauncher should filter out other DelegatingComputerLauncher instances " +
"from its descriptor's getApplicableDescriptors() method",
new DummyTwo.DummyTwoDescriptor().applicableDescriptors(null, new DumbSlave.DescriptorImpl()).isEmpty());
assertTrue(new DummyTwo.DummyTwoDescriptor().applicableDescriptors(null, new DumbSlave.DescriptorImpl()).isEmpty(),
"DelegatingComputerLauncher should filter out other DelegatingComputerLauncher instances " +
"from its descriptor's getApplicableDescriptors() method");
}
}
@@ -4,12 +4,12 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class OfflineCauseTest {
class OfflineCauseTest {
@Test
public void testChannelTermination_NoStacktrace() {
void testChannelTermination_NoStacktrace() {
String exceptionMessage = "exception message";
OfflineCause.ChannelTermination cause = new OfflineCause.ChannelTermination(new RuntimeException(exceptionMessage));
assertThat(cause.toString(), not(containsString(exceptionMessage)));
@@ -1,23 +1,24 @@
package hudson.tasks;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.model.FreeStyleBuild;
import java.io.IOException;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.jvnet.hudson.test.Issue;
import org.mockito.Mockito;
public class BuildStepCompatibilityLayerTest {
class BuildStepCompatibilityLayerTest {
/* testing deprecated variant */
@Issue("JENKINS-18734")
@Test
@SuppressWarnings("deprecation") /* testing deprecated variant */
public void testPerformExpectAbstractMethodError() {
@SuppressWarnings("deprecation")
void testPerformExpectAbstractMethodError() {
FreeStyleBuild mock = Mockito.mock(FreeStyleBuild.class, Mockito.CALLS_REAL_METHODS);
BuildStepCompatibilityLayer bscl = new BuildStepCompatibilityLayer() {};
@@ -28,7 +29,7 @@ public class BuildStepCompatibilityLayerTest {
@Issue("JENKINS-18734")
@Test
@SuppressWarnings("deprecation")
public void testPerform() throws InterruptedException, IOException {
void testPerform() throws InterruptedException, IOException {
FreeStyleBuild mock = Mockito.mock(FreeStyleBuild.class, Mockito.CALLS_REAL_METHODS);
BuildStepCompatibilityLayer bscl = new BuildStepCompatibilityLayer() {
@@ -1,31 +1,31 @@
package hudson.tasks._maven;
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.MarkupText;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class Maven3MojoNoteTest {
class Maven3MojoNoteTest {
@Test
public void testAnnotateMavenPlugin() {
void testAnnotateMavenPlugin() {
check("[INFO] <b class=maven-mojo>--- maven-clean-plugin:2.4.1:clean (default-clean) @ jobConfigHistory ---</b>", "[INFO] --- maven-clean-plugin:2.4.1:clean (default-clean) @ jobConfigHistory ---");
}
@Test
public void testAnnotateCodehausPlugin() {
void testAnnotateCodehausPlugin() {
check("[INFO] <b class=maven-mojo>--- cobertura-maven-plugin:2.4:instrument (report:cobertura) @ sardine ---</b>", "[INFO] --- cobertura-maven-plugin:2.4:instrument (report:cobertura) @ sardine ---");
}
@Test
public void testAnnotateOtherPlugin() {
void testAnnotateOtherPlugin() {
check("[INFO] <b class=maven-mojo>--- gmaven-plugin:1.0-rc-5:generateTestStubs (test-in-groovy) @ jobConfigHistory ---</b>", "[INFO] --- gmaven-plugin:1.0-rc-5:generateTestStubs (test-in-groovy) @ jobConfigHistory ---");
}
private void check(final String decorated, final String input) {
assertTrue(input + " does not match" + Maven3MojoNote.PATTERN, Maven3MojoNote.PATTERN.matcher(input).matches());
assertTrue(Maven3MojoNote.PATTERN.matcher(input).matches(), input + " does not match" + Maven3MojoNote.PATTERN);
assertEquals(decorated, annotate(input));
}
@@ -30,10 +30,11 @@ import org.jvnet.hudson.test.Issue;
/**
* @author Kanstantsin Shautsou
*/
public class SCMTriggerTest {
class SCMTriggerTest {
@Issue({"JENKINS-29790", "JENKINS-29945"})
@Test
public void testNoNPE() throws Exception {
void testNoNPE() {
final SCMTrigger scmTrigger = new SCMTrigger("");
scmTrigger.run();
@@ -24,36 +24,38 @@
package hudson.triggers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import hudson.scheduler.CronTabList;
import hudson.scheduler.Hash;
import java.util.TimeZone;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.jvnet.hudson.test.Issue;
/**
* @author Kanstantsin Shautsou
*/
public class TimerTriggerTest {
class TimerTriggerTest {
@Issue("JENKINS-29790")
@Test
public void testNoNPE() {
void testNoNPE() {
new TimerTrigger("").run();
}
@Issue("JENKINS-43328")
@Test
public void testTimeZoneOffset() throws Exception {
void testTimeZoneOffset() {
TimeZone defaultTz = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone("Europe/Berlin"));
try {
String cron = "TZ=GMT\nH 0 * * *";
CronTabList ctl = CronTabList.create(cron, Hash.from("whatever"));
Assert.assertEquals("previous occurrence is in GMT", "GMT", ctl.previous().getTimeZone().getID());
assertEquals("GMT", ctl.previous().getTimeZone().getID(), "previous occurrence is in GMT");
cron = "TZ=America/Denver\nH 0 * * *";
ctl = CronTabList.create(cron, Hash.from("whatever"));
Assert.assertEquals("next occurrence is in America/Denver", "America/Denver", ctl.next().getTimeZone().getID());
assertEquals("America/Denver", ctl.next().getTimeZone().getID(), "next occurrence is in America/Denver");
} finally {
TimeZone.setDefault(defaultTz);
}
@@ -10,6 +10,7 @@
<property name="max" value="240"/>
<property name="ignorePattern" value="^package.*|^import.*|a href|href|http://|https://|ftp://"/>
</module>
<module name="SuppressWarningsFilter" />
<module name="TreeWalker">
<!--
Annotations: https://checkstyle.sourceforge.io/config_annotation.html
@@ -38,6 +39,7 @@
<module name="StringLiteralEquality"/>
<module name="SuperClone"/>
<module name="SuperFinalize"/>
<module name="SuppressWarningsHolder" />
<module name="UnnecessarySemicolonAfterOuterTypeDeclaration"/>
<module name="UnnecessarySemicolonAfterTypeMemberDeclaration"/>
<module name="UnnecessarySemicolonInEnumeration"/>