Merge pull request #5602 from offa/dev

Exception test modernization / clean up
This commit is contained in:
Raihaan Shouhell authored and GitHub committed 2021-07-10 00:38:12 +08:00
commit bf01f36e75
40 files changed
+123 -357

No files matched your search

+36 -45
View File
@@ -164,49 +164,44 @@ public class FilePathTest {
private List<Future<Integer>> whenFileIsCopied100TimesConcurrently(final File file) throws InterruptedException {
List<Callable<Integer>> r = new ArrayList<>();
for (int i=0; i<100; i++) {
r.add(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
class Sink extends OutputStream {
private Exception closed;
private final AtomicInteger count = new AtomicInteger();
r.add(() -> {
class Sink extends OutputStream {
private Exception closed;
private final AtomicInteger count = new AtomicInteger();
private void checkNotClosed() throws IOException {
if (closed != null)
throw new IOException(closed);
}
@Override
public void write(int b) throws IOException {
count.incrementAndGet();
checkNotClosed();
}
@Override
public void write(byte[] b) throws IOException {
count.addAndGet(b.length);
checkNotClosed();
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
count.addAndGet(len);
checkNotClosed();
}
@Override
public void close() throws IOException {
closed = new Exception();
//if (size!=count)
// fail();
}
private void checkNotClosed() throws IOException {
if (closed != null)
throw new IOException(closed);
}
FilePath f = new FilePath(channels.french, file.getPath());
Sink sink = new Sink();
f.copyTo(sink);
return sink.count.get();
@Override
public void write(int b) throws IOException {
count.incrementAndGet();
checkNotClosed();
}
@Override
public void write(byte[] b) throws IOException {
count.addAndGet(b.length);
checkNotClosed();
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
count.addAndGet(len);
checkNotClosed();
}
@Override
public void close() throws IOException {
closed = new Exception();
}
}
FilePath f = new FilePath(channels.french, file.getPath());
Sink sink = new Sink();
f.copyTo(sink);
return sink.count.get();
});
}
@@ -789,12 +784,8 @@ public class FilePathTest {
File f = temp.newFolder("folder");
FilePath fp = new FilePath(f);
int invalidMode = 01770; // Full permissions for owner and group plus sticky bit.
try {
chmodAndMode(fp, invalidMode);
fail("Setting sticky bit should fail");
} catch (IOException e) {
assertEquals("Invalid mode: " + invalidMode, e.getMessage());
}
final IOException e = assertThrows("Setting sticky bit should fail", IOException.class, () -> chmodAndMode(fp, invalidMode));
assertEquals("Invalid mode: " + invalidMode, e.getMessage());
}
private int chmodAndMode(FilePath path, int mode) throws Exception {
@@ -48,7 +48,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.hamcrest.core.StringContains.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* Tests of {@link PluginManager}.
@@ -81,14 +81,11 @@ public class PluginManagerTest {
"</root>\n";
PluginManager pluginManager = new LocalPluginManager(Util.createTempDir());
try {
pluginManager.parseRequestedPlugins(new StringInputStream(evilXML));
fail("XML contains an external entity, but no exception was thrown.");
}
catch (IOException ex) {
assertThat(ex.getCause(), instanceOf(SAXException.class));
assertThat(ex.getCause().getMessage(), containsString("Refusing to resolve entity with publicId(null) and systemId (file:///)"));
}
final IOException ex = assertThrows(IOException.class,
() -> pluginManager.parseRequestedPlugins(new StringInputStream(evilXML)),
"XML contains an external entity, but no exception was thrown.");
assertThat(ex.getCause(), instanceOf(SAXException.class));
assertThat(ex.getCause().getMessage(), containsString("Refusing to resolve entity with publicId(null) and systemId (file:///)"));
}
@Test
@@ -13,7 +13,6 @@ import jenkins.model.Jenkins;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.jvnet.hudson.test.Issue;
@@ -22,8 +21,8 @@ import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -65,47 +64,35 @@ public class PluginWrapperTest {
@Test
public void jenkinsCoreTooOld() {
PluginWrapper pw = pluginWrapper("fake").requiredCoreVersion("3.0").buildLoaded();
try {
pw.resolvePluginDependencies();
fail();
} catch (IOException ex) {
assertContains(ex, "Failed to load: fake (42)", "Jenkins (3.0) or higher required");
}
final IOException ex = assertThrows(IOException.class, pw::resolvePluginDependencies);
assertContains(ex, "Failed to load: fake (42)", "Jenkins (3.0) or higher required");
}
@Test
public void dependencyNotInstalled() {
PluginWrapper pw = pluginWrapper("dependee").deps("dependency:42").buildLoaded();
try {
pw.resolvePluginDependencies();
fail();
} catch (IOException ex) {
assertContains(ex, "Failed to load: dependee (42)", "Plugin is missing: dependency (42)");
}
final IOException ex = assertThrows(IOException.class, pw::resolvePluginDependencies);
assertContains(ex, "Failed to load: dependee (42)", "Plugin is missing: dependency (42)");
}
@Test
public void dependencyOutdated() {
pluginWrapper("dependency").version("3").buildLoaded();
PluginWrapper pw = pluginWrapper("dependee").deps("dependency:5").buildLoaded();
try {
pw.resolvePluginDependencies();
fail();
} catch (IOException ex) {
assertContains(ex, "Failed to load: dependee (42)", "Update required: dependency (3) to be updated to 5 or higher");
}
final IOException ex = assertThrows(IOException.class, pw::resolvePluginDependencies);
assertContains(ex, "Failed to load: dependee (42)", "Update required: dependency (3) to be updated to 5 or higher");
}
@Test
public void dependencyFailedToLoad() {
pluginWrapper("dependency").version("5").buildFailed();
PluginWrapper pw = pluginWrapper("dependee").deps("dependency:3").buildLoaded();
try {
pw.resolvePluginDependencies();
fail();
} catch (IOException ex) {
assertContains(ex, "Failed to load: dependee (42)", "Failed to load: dependency (5)");
}
final IOException ex = assertThrows(IOException.class, pw::resolvePluginDependencies);
assertContains(ex, "Failed to load: dependee (42)", "Failed to load: dependency (5)");
}
private void assertContains(Throwable ex, String... patterns) {
@@ -123,18 +110,15 @@ public class PluginWrapperTest {
private final HashMap<String, PluginWrapper> plugins = new HashMap<>();
private final PluginManager pm = mock(PluginManager.class);
{
when(pm.getPlugin(any(String.class))).thenAnswer(new Answer<PluginWrapper>() {
@Override public PluginWrapper answer(InvocationOnMock invocation) throws Throwable {
return plugins.get(invocation.getArguments()[0]);
}
});
when(pm.getPlugin(any(String.class))).thenAnswer((Answer<PluginWrapper>) invocation -> plugins.get(invocation.getArguments()[0]));
}
private final class PluginWrapperBuilder {
private String name;
private final String name;
private String version = "42";
private String requiredCoreVersion = "1.0";
private List<PluginWrapper.Dependency> deps = new ArrayList<>();
private List<PluginWrapper.Dependency> optDeps = new ArrayList<>();
private final List<PluginWrapper.Dependency> deps = new ArrayList<>();
private final List<PluginWrapper.Dependency> optDeps = new ArrayList<>();
private PluginWrapperBuilder(String name) {
this.name = name;
@@ -157,13 +141,6 @@ public class PluginWrapperTest {
return this;
}
public PluginWrapperBuilder optDeps(String... optDeps) {
for (String dep: optDeps) {
this.optDeps.add(new PluginWrapper.Dependency(dep));
}
return this;
}
private PluginWrapper buildLoaded() {
PluginWrapper pw = build();
plugins.put(name, pw);
+1 -3
View File
@@ -599,9 +599,7 @@ public class UtilTest {
@Test
public void ifOverriddenFailure() {
AbstractMethodError error = Assert.assertThrows(AbstractMethodError.class, () -> {
Util.ifOverridden(() -> true, BaseClass.class, DerivedClassFailure.class, "method");
});
AbstractMethodError error = Assert.assertThrows(AbstractMethodError.class, () -> Util.ifOverridden(() -> true, BaseClass.class, DerivedClassFailure.class, "method"));
assertEquals("The class " + DerivedClassFailure.class.getName() + " must override at least one of the BaseClass.method methods", error.getMessage());
}
+1 -1
View File
@@ -42,7 +42,7 @@ public class XmlFileTest {
XmlFile xmlFile = new XmlFile(xs, new File(configUrl.getFile()));
if (xmlFile.exists()) {
assertThrows(SAXParseException.class, () -> xmlFile.read());
assertThrows(SAXParseException.class, xmlFile::read);
}
}
+10 -23
View File
@@ -5,7 +5,7 @@ import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -14,9 +14,9 @@ import static org.mockito.Mockito.when;
*/
public class ItemsTest {
private static ItemGroup root;
private static ItemGroup foo;
private static ItemGroup foo_bar;
private static ItemGroup<?> root;
private static ItemGroup<?> foo;
private static ItemGroup<?> foo_bar;
@BeforeClass
public static void itemGroups() {
@@ -28,7 +28,6 @@ public class ItemsTest {
foo_bar = mock(ItemGroup.class);
when(foo_bar.getFullName()).thenReturn("foo/bar");
}
@Test
@@ -43,26 +42,14 @@ public class ItemsTest {
assertEquals("foo/bar/baz/qux", Items.getCanonicalName(foo_bar, "baz/qux"));
assertEquals("foo/baz/qux", Items.getCanonicalName(foo_bar, "../baz/qux"));
try {
Items.getCanonicalName(root, "..");
fail();
} catch (IllegalArgumentException ex) {
assertEquals("Illegal relative path '..' within context ''", ex.getMessage());
}
final IllegalArgumentException ex0 = assertThrows(IllegalArgumentException.class, () -> Items.getCanonicalName(root, ".."));
assertEquals("Illegal relative path '..' within context ''", ex0.getMessage());
try {
Items.getCanonicalName(foo, "../..");
fail();
} catch (IllegalArgumentException ex) {
assertEquals("Illegal relative path '../..' within context 'foo'", ex.getMessage());
}
final IllegalArgumentException ex1 = assertThrows(IllegalArgumentException.class, () -> Items.getCanonicalName(foo, "../.."));
assertEquals("Illegal relative path '../..' within context 'foo'", ex1.getMessage());
try {
Items.getCanonicalName(root, "foo/../..");
fail();
} catch (IllegalArgumentException ex) {
assertEquals("Illegal relative path 'foo/../..' within context ''", ex.getMessage());
}
final IllegalArgumentException ex2 = assertThrows(IllegalArgumentException.class, () -> Items.getCanonicalName(root, "foo/../.."));
assertEquals("Illegal relative path 'foo/../..' within context ''", ex2.getMessage());
}
@Test
@@ -10,8 +10,8 @@ import java.util.Locale;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class UpdateCenterTest {
@@ -52,12 +52,10 @@ public class UpdateCenterTest {
@Test
public void noChecksums() {
try {
UpdateCenter.verifyChecksums(new MockDownloadJob(null, null, null), buildEntryWithExpectedChecksums(null, null, null), new File("example"));
fail();
} catch (IOException ex) {
assertEquals("Unable to confirm integrity of downloaded file, refusing installation", ex.getMessage());
}
final IOException ex = assertThrows(IOException.class,
() -> UpdateCenter.verifyChecksums(new MockDownloadJob(null, null, null),
buildEntryWithExpectedChecksums(null, null, null), new File("example")));
assertEquals("Unable to confirm integrity of downloaded file, refusing installation", ex.getMessage());
}
@Test
@@ -69,14 +67,10 @@ public class UpdateCenterTest {
@Test
public void sha1Mismatch() {
try {
UpdateCenter.verifyChecksums(
new MockDownloadJob(EMPTY_SHA1.replace('k', 'f'), null, null),
buildEntryWithExpectedChecksums(EMPTY_SHA1, null, null), new File("example"));
fail();
} catch (IOException ex) {
assertTrue(ex.getMessage().contains("does not match expected SHA-1, expected '2jmj7l5rSw0yVb/vlWAYkK/YBwk=', actual '2jmj7l5rSw0yVb/vlWAYfK/YBwf='"));
}
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")));
assertTrue(ex.getMessage().contains("does not match expected SHA-1, expected '2jmj7l5rSw0yVb/vlWAYkK/YBwk=', actual '2jmj7l5rSw0yVb/vlWAYfK/YBwf='"));
}
@Test
@@ -95,45 +89,32 @@ public class UpdateCenterTest {
@Test
public void sha1DoesNotIgnoreCase() {
try {
UpdateCenter.verifyChecksums(
new MockDownloadJob(EMPTY_SHA1, EMPTY_SHA256, EMPTY_SHA512),
buildEntryWithExpectedChecksums(EMPTY_SHA1.toUpperCase(Locale.US), null, null), new File("example"));
fail();
} catch (Exception e) {
assertTrue(e.getMessage().contains("does not match expected SHA-1, expected '2JMJ7L5RSW0YVB/VLWAYKK/YBWK=', actual '2jmj7l5rSw0yVb/vlWAYkK/YBwk='"));
}
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")));
assertTrue(ex.getMessage().contains("does not match expected SHA-1, expected '2JMJ7L5RSW0YVB/VLWAYKK/YBWK=', actual '2jmj7l5rSw0yVb/vlWAYkK/YBwk='"));
}
@Test
public void noOverlapForComputedAndProvidedChecksums() {
try {
UpdateCenter.verifyChecksums(
new MockDownloadJob(EMPTY_SHA1, EMPTY_SHA256, null),
buildEntryWithExpectedChecksums(null, null, EMPTY_SHA512), new File("example"));
fail();
} catch (Exception e) {
assertEquals("Unable to confirm integrity of downloaded file, refusing installation", e.getMessage());
}
final Exception ex = assertThrows(Exception.class, () -> UpdateCenter.verifyChecksums(
new MockDownloadJob(EMPTY_SHA1, EMPTY_SHA256, null),
buildEntryWithExpectedChecksums(null, null, EMPTY_SHA512), new File("example")));
assertEquals("Unable to confirm integrity of downloaded file, refusing installation", ex.getMessage());
}
@Test
public void noOverlapForComputedAndProvidedChecksumsForSpecIncompliantJVM() {
try {
UpdateCenter.verifyChecksums(
new MockDownloadJob(EMPTY_SHA1, null, null),
buildEntryWithExpectedChecksums(null, EMPTY_SHA256, EMPTY_SHA512), new File("example"));
fail();
} catch (Exception e) {
assertEquals("Unable to confirm integrity of downloaded file, refusing installation", e.getMessage());
}
final Exception ex = assertThrows(Exception.class, () -> UpdateCenter.verifyChecksums(
new MockDownloadJob(EMPTY_SHA1, null, null),
buildEntryWithExpectedChecksums(null, EMPTY_SHA256, EMPTY_SHA512), new File("example")));
assertEquals("Unable to confirm integrity of downloaded file, refusing installation", ex.getMessage());
}
private static String EMPTY_SHA1 = "2jmj7l5rSw0yVb/vlWAYkK/YBwk=";
private static String EMPTY_SHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
private static String EMPTY_SHA512 = "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e";
private static final String EMPTY_SHA1 = "2jmj7l5rSw0yVb/vlWAYkK/YBwk=";
private static final String EMPTY_SHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
private static final String EMPTY_SHA512 = "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e";
private static UpdateSite.Entry buildEntryWithExpectedChecksums(String expectedSHA1, String expectedSHA256, String expectedSHA512) {
JSONObject o = new JSONObject();
@@ -33,7 +33,7 @@ import java.util.TimeZone;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import static org.junit.Assert.assertThrows;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
@@ -265,12 +265,8 @@ public class CronTabTest {
compare(new GregorianCalendar(2013, 2, 21, 0, 2), new CronTab("H(0-15)/3 * * * *", Hash.from("junk")).ceil(new GregorianCalendar(2013, 2, 21, 0, 0)));
compare(new GregorianCalendar(2013, 2, 21, 0, 2), new CronTab("H(0-3)/4 * * * *", Hash.from("junk")).ceil(new GregorianCalendar(2013, 2, 21, 0, 0)));
compare(new GregorianCalendar(2013, 2, 21, 1, 2), new CronTab("H(0-3)/4 * * * *", Hash.from("junk")).ceil(new GregorianCalendar(2013, 2, 21, 0, 5)));
try {
compare(new GregorianCalendar(2013, 2, 21, 0, 0), new CronTab("H(0-3)/15 * * * *", Hash.from("junk")).ceil(new GregorianCalendar(2013, 2, 21, 0, 0)));
fail();
} catch (ANTLRException x) {
// good
}
assertThrows(ANTLRException.class, () -> compare(new GregorianCalendar(2013, 2, 21, 0, 0), new CronTab("H(0-3)/15 * * * *", Hash.from("junk")).ceil(new GregorianCalendar(2013, 2, 21, 0, 0))));
}
@Test public void repeatedHash() throws Exception {
@@ -289,21 +285,11 @@ public class CronTabTest {
}
@Test public void rangeBoundsCheckFailHour() {
try {
new CronTab("H H(12-24) * * *");
fail();
} catch (ANTLRException e) {
// ok
}
assertThrows(ANTLRException.class, () -> new CronTab("H H(12-24) * * *"));
}
@Test public void rangeBoundsCheckFailMinute() {
try {
new CronTab("H(33-66) * * * *");
fail();
} catch (ANTLRException e) {
// ok
}
assertThrows(ANTLRException.class, () -> new CronTab("H(33-66) * * * *"));
}
@Issue("JENKINS-9283")
@@ -1,6 +1,6 @@
package jenkins;
import static org.junit.Assert.fail;
import static org.junit.Assert.assertNotNull;
import hudson.remoting.Channel;
import hudson.remoting.Which;
@@ -23,8 +23,6 @@ public class RemotingJarSignatureTest {
@Test
public void testSignature() throws Exception {
File jar = Which.jarFile(Channel.class);
// File jar = new File("/home/kohsuke/.m2/repository/org/jenkins-ci/main/remoting/1.421/remoting-1.421.jar");
// File jar = new File("/home/kohsuke/.m2/repository/org/jenkins-ci/main/remoting/2.0/remoting-2.0.jar");
System.out.println("Verifying "+jar);
JarFile myJar = new JarFile(jar,true);
@@ -43,9 +41,7 @@ public class RemotingJarSignatureTest {
// make sure bits are signed
IOUtils.copy(myJar.getInputStream(entry), NullOutputStream.NULL_OUTPUT_STREAM);
if (entry.getCodeSigners()==null) {
fail("No signature for " + name);
}
assertNotNull("No signature for " + name, entry.getCodeSigners());
}
}
}
@@ -13,14 +13,14 @@ public class JenkinsJVMTest {
@Test
public void checkJenkinsJVM_WhenNotInAJenkinsJVM() {
assertThrows(IllegalStateException.class, () -> JenkinsJVM.checkJenkinsJVM());
assertThrows(IllegalStateException.class, JenkinsJVM::checkJenkinsJVM);
}
@Test
public void checkNotJenkinsJVM_WhenInAJenkinsJVM() {
JenkinsJVM.setJenkinsJVM(true);
try {
assertThrows(IllegalStateException.class, () -> JenkinsJVM.checkNotJenkinsJVM());
assertThrows(IllegalStateException.class, JenkinsJVM::checkNotJenkinsJVM);
} finally {
JenkinsJVM.setJenkinsJVM(false);
}
@@ -100,7 +100,7 @@ public class VirtualFileTest {
VirtualFile hack = root.child("hack");
assertFalse(hack.isFile());
assertFalse(hack.exists());
assertThrows(FileNotFoundException.class, () -> hack.open());
assertThrows(FileNotFoundException.class, hack::open);
}
@Issue("JENKINS-26810")