下面列出了org.junit.Assume#assumeNoException ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testGetLocationFromLink_triggerException() throws IOException {
Assume.assumeNoException(symlinkException);
LogStoringHandler testHandler = LogStoringHandler.getForLogger(PathResolver.class.getName());
Path exceptionForcingPath = Mockito.mock(Path.class);
IOException exception = Mockito.mock(IOException.class);
Mockito.when(exceptionForcingPath.toRealPath()).thenThrow(exception);
List<String> possiblePaths = new ArrayList<>();
PathResolver.getLocationsFromLink(possiblePaths, exceptionForcingPath);
Assert.assertEquals(1, testHandler.getLogs().size());
LogRecord logRecord = testHandler.getLogs().get(0);
Assert.assertEquals(
"Non-critical exception when searching for cloud-sdk", logRecord.getMessage());
Assert.assertEquals(exception, logRecord.getThrown());
}
@Fuzz
public void testLocalDateTimeSerialization(@InRange(minInt=0) int year,
@InRange(minInt=1, maxInt=12) int month,
@InRange(minInt=1, maxInt=31) int dayOfMonth,
@InRange(minInt=0, maxInt=23) int hour,
@InRange(minInt=0, maxInt=59) int minute,
@InRange(minInt=0, maxInt=59) int second) {
LocalDateTime ldt1 = null, ldt2;
String s1, s2;
try {
ldt1 = LocalDateTime.of(year, month, dayOfMonth, hour, minute, second);
} catch (DateTimeException e) {
Assume.assumeNoException(e);
}
s1 = ldt1.format(DateTimeFormatter.ISO_DATE_TIME);
ldt2 = LocalDateTime.parse(s1);
s2 = ldt2.format(DateTimeFormatter.ISO_DATE_TIME);
Assert.assertEquals(s1, s2);
}
/**
* Spy on the Java DNS infrastructure.
* This likely only works on Sun-derived JDKs, but uses JUnit's
* Assume functionality so that any tests using it are skipped on
* incompatible JDKs.
*/
private NameService spyOnNameService() {
try {
Field f = InetAddress.class.getDeclaredField("nameServices");
f.setAccessible(true);
Assume.assumeNotNull(f);
@SuppressWarnings("unchecked")
List<NameService> nsList = (List<NameService>) f.get(null);
NameService ns = nsList.get(0);
Log log = LogFactory.getLog("NameServiceSpy");
ns = Mockito.mock(NameService.class,
new GenericTestUtils.DelegateAnswer(log, ns));
nsList.set(0, ns);
return ns;
} catch (Throwable t) {
LOG.info("Unable to spy on DNS. Skipping test.", t);
// In case the JDK we're testing on doesn't work like Sun's, just
// skip the test.
Assume.assumeNoException(t);
throw new RuntimeException(t);
}
}
@Before
public void setUp() throws Exception {
var defaultCredentials = GoogleCredentials.getApplicationDefault();
var serviceCredentials = ImpersonatedCredentials.create(
defaultCredentials, SERVICE_ACCOUNT,
List.of(), List.of("https://www.googleapis.com/auth/cloud-platform"), 300);
try {
serviceCredentials.refreshAccessToken();
} catch (IOException e) {
// Do not run this test if we do not have permission to impersonate the test user.
Assume.assumeNoException(e);
}
iam = new Iam.Builder(
Utils.getDefaultTransport(), Utils.getDefaultJsonFactory(),
new HttpCredentialsAdapter(serviceCredentials.createScoped(IamScopes.all())))
.setApplicationName("styx-test")
.build();
}
/**
* Spy on the Java DNS infrastructure.
* This likely only works on Sun-derived JDKs, but uses JUnit's
* Assume functionality so that any tests using it are skipped on
* incompatible JDKs.
*/
private NameService spyOnNameService() {
try {
Field f = InetAddress.class.getDeclaredField("nameServices");
f.setAccessible(true);
Assume.assumeNotNull(f);
@SuppressWarnings("unchecked")
List<NameService> nsList = (List<NameService>) f.get(null);
NameService ns = nsList.get(0);
Log log = LogFactory.getLog("NameServiceSpy");
ns = Mockito.mock(NameService.class,
new GenericTestUtils.DelegateAnswer(log, ns));
nsList.set(0, ns);
return ns;
} catch (Throwable t) {
LOG.info("Unable to spy on DNS. Skipping test.", t);
// In case the JDK we're testing on doesn't work like Sun's, just
// skip the test.
Assume.assumeNoException(t);
throw new RuntimeException(t);
}
}
@Test
public void testGetLocationFromLink_valid() throws IOException {
Assume.assumeNoException(symlinkException);
Path sdkHome = temporaryFolder.newFolder().toPath().toRealPath();
Path bin = Files.createDirectory(sdkHome.resolve("bin"));
Path gcloud = Files.createFile(bin.resolve("gcloud"));
Files.createSymbolicLink(temporaryFolder.getRoot().toPath().resolve("gcloud"), gcloud);
List<String> possiblePaths = new ArrayList<>();
PathResolver.getLocationsFromLink(possiblePaths, gcloud);
Assert.assertEquals(1, possiblePaths.size());
Assert.assertEquals(gcloud.getParent().getParent().toString(), possiblePaths.get(0));
}
private void makeJarDirReadOnly() {
try {
Files.setPosixFilePermissions(jarDir, new HashSet<>(Arrays.asList(
PosixFilePermission.OTHERS_READ,
PosixFilePermission.GROUP_READ,
PosixFilePermission.OWNER_READ,
PosixFilePermission.OTHERS_EXECUTE,
PosixFilePermission.GROUP_EXECUTE,
PosixFilePermission.OWNER_EXECUTE)));
} catch (final Exception e) {
Assume.assumeNoException(e);
}
}
/**
* "Assumes" that the specified list of currency codes are
* supported in this JVM
*/
public static void assumeCurrencySupport(String... codes) {
try {
// each JDK might have a diff list of supported currencies,
// these are the ones needed for this test to work.
for (String code : codes) {
Currency obj = Currency.getInstance(code);
assertNotNull(code, obj);
}
} catch (IllegalArgumentException e) {
Assume.assumeNoException(e);
}
}
@Test
public void testGetLocationFromLink_notValid() throws IOException {
Assume.assumeNoException(symlinkException);
Path invalidPath = temporaryFolder.newFolder().toPath();
Files.createSymbolicLink(temporaryFolder.getRoot().toPath().resolve("gcloud"), invalidPath);
List<String> possiblePaths = new ArrayList<>();
PathResolver.getLocationsFromLink(possiblePaths, invalidPath);
Assert.assertEquals(0, possiblePaths.size());
}
private void testWrapWithDifferentSizes(String protocol, String cipher) throws Exception {
assumeTrue(OpenSsl.SUPPORTED_PROTOCOLS_SET.contains(protocol));
if (!OpenSsl.isCipherSuiteAvailable(cipher)) {
return;
}
SSLEngine clientEngine = null;
SSLEngine serverEngine = null;
try {
clientEngine = clientSslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);
serverEngine = serverSslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);
clientEngine.setEnabledCipherSuites(new String[] { cipher });
clientEngine.setEnabledProtocols(new String[] { protocol });
serverEngine.setEnabledCipherSuites(new String[] { cipher });
serverEngine.setEnabledProtocols(new String[] { protocol });
try {
handshake(clientEngine, serverEngine);
} catch (SSLException e) {
if (e.getMessage().contains("unsupported protocol")) {
Assume.assumeNoException(protocol + " not supported with cipher " + cipher, e);
}
throw e;
}
int srcLen = 64;
do {
testWrapDstBigEnough(clientEngine, srcLen);
srcLen += 64;
} while (srcLen < MAX_PLAINTEXT_LENGTH);
testWrapDstBigEnough(clientEngine, MAX_PLAINTEXT_LENGTH);
} finally {
cleanupClientSslEngine(clientEngine);
cleanupServerSslEngine(serverEngine);
}
}
@BeforeClass
public static void checkSupported() throws Throwable {
Throwable error = null;
try {
Marshalling.getProvidedMarshallerFactory(SERIAL_FACTORY);
} catch (Throwable cause) {
// This may fail on Java 9+ depending on which command-line arguments are used when building.
if (PlatformDependent.javaVersion() < 9) {
throw cause;
}
error = cause;
}
Assume.assumeNoException(error);
}
@Fuzz
public void testWithString(@From(AsciiStringGenerator.class) String input) {
try {
Script script = context.compileString(input, "input", 0, null);
} catch (EvaluatorException e) {
Assume.assumeNoException(e);
}
}
@Fuzz
public void testWithInputStream(InputStream in) throws IOException {
try {
Script script = context.compileReader(new InputStreamReader(in), "input", 0, null);
} catch (EvaluatorException e) {
Assume.assumeNoException(e);
}
}
@Fuzz
public void bzip2(byte @Size(min=100, max=100)[] bytes){
OutputStream o = new ByteArrayOutputStream();
try {
BZip2CompressorOutputStream bo = new BZip2CompressorOutputStream(o);
bo.write(bytes);
bo.finish();
} catch (IOException e){
Assume.assumeNoException(e);
}
}
@Fuzz
public void testWithInputStream(InputStream in) {
ModelReader reader = new DefaultModelReader();
try {
Model model = reader.read(in, null);
Assert.assertNotNull(model);
} catch (IOException e) {
Assume.assumeNoException(e);
}
}
@Fuzz
public void patternGenerationTest(@From(ArbitraryLengthStringGenerator.class) String pattern) {
try {
Pattern.matches(pattern, "aaaaaa");
} catch (PatternSyntaxException e) {
Assume.assumeNoException(e);
}
}
@Fuzz
public void fuzzSimple(Date date, String format) throws IllegalArgumentException {
// Create a formatter using the input format
DateFormat df = new SimpleDateFormat(format);
// Serialize a Date object to a String
try {
df.format(date);
} catch (ArrayIndexOutOfBoundsException e) {
Assume.assumeNoException(e);
}
}
@Fuzz
public void fuzzValidMetadata(@From(PngKaitaiGenerator.class) @Size(max = 256) InputStream input) {
// Decode image from input stream
try {
reader.setInput(ImageIO.createImageInputStream(input));
reader.getImageMetadata(0);
} catch (IOException e) {
Assume.assumeNoException(e);
}
}
@Fuzz
public void fuzzValidImage(@From(PngKaitaiGenerator.class) @Size(max = 2048) InputStream input) {
// Decode image from input stream
try {
reader.setInput(ImageIO.createImageInputStream(input));
reader.getImageMetadata(0);
Assume.assumeTrue(reader.getHeight(0) < 1024);
Assume.assumeTrue(reader.getWidth(0) < 1024);
} catch (IOException e) {
Assume.assumeNoException(e);
}
}
@Fuzz
public void testWithInputStream(InputStream inputStream) throws IOException {
JavaClass clazz;
try {
clazz = new ClassParser(inputStream, "Hello.class").parse();
} catch (ClassFormatException e) {
// ClassFormatException thrown by the parser is just invalid input
Assume.assumeNoException(e);
return;
}
// Any non-IOException thrown here should be marked a failure
// (including ClassFormatException)
verifyJavaClass(clazz);
}