下面列出了怎么用org.junit.jupiter.api.condition.OS的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
@DisabledOnOs(OS.WINDOWS)
void shouldRecogniseSvnAsTheSameIfURLContainsChineseCharacters() throws Exception {
File working = temporaryFolder.newFolder("shouldRecogniseSvnAsTheSameIfURLContainsSpaces");
SvnTestRepo repo = new SvnTestRepo(temporaryFolder, "a directory with 司徒空在此");
SvnMaterial material = repo.material();
assertThat(material.getUrl()).contains("%20");
InMemoryStreamConsumer output = new InMemoryStreamConsumer();
material.freshCheckout(output, new SubversionRevision("3"), working);
assertThat(output.getAllOutput()).contains("Checked out revision 3");
InMemoryStreamConsumer output2 = new InMemoryStreamConsumer();
updateMaterial(material, new SubversionRevision("4"), working, output2);
assertThat(output2.getAllOutput()).contains("Updated to revision 4");
}
@Test
@EnabledOnOs(OS.WINDOWS)
void shouldMaskOutOccuranceOfSecureEnvironmentVariablesValuesInTheScriptOutput() throws CheckedCommandLineException {
EnvironmentVariableContext environmentVariableContext = new EnvironmentVariableContext();
environmentVariableContext.setProperty("secret", "the_secret_password", true);
CommandLine command = CommandLine.createCommandLine("cmd")
.withArg("/c")
.withArg("echo")
.withArg("the_secret_password")
.withEncoding("utf-8");
InMemoryConsumer output = new InMemoryConsumer();
ExecScript script = new ExecScript("ERROR_STRING");
command.runScript(script, output, environmentVariableContext, null);
assertThat(script.getExitCode()).isEqualTo(0);
assertThat(output.contains("the_secret_password")).as(output.toString()).isFalse();
}
@Test
@DisabledOnOs(OS.WINDOWS)
void shouldRecogniseSvnAsTheSameIfURLContainsSpaces() throws Exception {
File working = temporaryFolder.newFolder("shouldRecogniseSvnAsTheSameIfURLContainsSpaces");
SvnTestRepo repo = new SvnTestRepo(temporaryFolder, "a directory with spaces");
SvnMaterial material = repo.material();
assertThat(material.getUrl()).contains("%20");
InMemoryStreamConsumer output = new InMemoryStreamConsumer();
material.freshCheckout(output, new SubversionRevision("3"), working);
assertThat(output.getAllOutput()).contains("Checked out revision 3");
InMemoryStreamConsumer output2 = new InMemoryStreamConsumer();
material.updateTo(output2, working, new RevisionContext(new SubversionRevision("4")), new TestSubprocessExecutionContext());
assertThat(output2.getAllOutput()).contains("Updated to revision 4");
}
@Test
void bundleWithExistingOtherComponent(@TempDir final File temporaryFolder) throws Exception {
final CarBundler.Configuration configuration = prepareBundle(temporaryFolder);
// try to execute the main now in a fake studio
final File fakeStudio = temporaryFolder;
final File fakeConfig = new File(fakeStudio, "configuration/config.ini");
fakeConfig.getParentFile().mkdirs();
try (final Writer writer = new FileWriter(fakeConfig)) {
writer.write("component.java.coordinates = a.bar:dummy:1.3,a.bar:h:2.2");
}
final File fakeM2 = new File(fakeStudio, "configuration/.m2/repository/");
fakeM2.mkdirs();
assertEquals(0,
new ProcessBuilder(
new File(System.getProperty("java.home"),
"/bin/java" + (OS.WINDOWS.isCurrentOs() ? ".exe" : "")).getAbsolutePath(),
"-jar", configuration.getOutput().getAbsolutePath(), "studio-deploy",
fakeStudio.getAbsolutePath()).inheritIO().start().waitFor());
assertEquals("component.java.coordinates = foo.bar:dummy:1.2,a.bar:dummy:1.3,a.bar:h:2.2",
String.join("\n", Files.readAllLines(fakeConfig.toPath())).trim());
}
@Test
void bundleWithExistingSameComponentOtherVersion(@TempDir final File temporaryFolder) throws Exception {
final CarBundler.Configuration configuration = prepareBundle(temporaryFolder);
// try to execute the main now in a fake studio
final File fakeStudio = temporaryFolder;
final File fakeConfig = new File(fakeStudio, "configuration/config.ini");
fakeConfig.getParentFile().mkdirs();
try (final Writer writer = new FileWriter(fakeConfig)) {
writer.write("component.java.coordinates = foo.bar:dummy:1.1");
}
final File fakeM2 = new File(fakeStudio, "configuration/.m2/repository/");
fakeM2.mkdirs();
assertEquals(0,
new ProcessBuilder(
new File(System.getProperty("java.home"),
"/bin/java" + (OS.WINDOWS.isCurrentOs() ? ".exe" : "")).getAbsolutePath(),
"-jar", configuration.getOutput().getAbsolutePath(), "studio-deploy",
fakeStudio.getAbsolutePath()).inheritIO().start().waitFor());
assertEquals("component.java.coordinates = foo.bar:dummy:1.2",
String.join("\n", Files.readAllLines(fakeConfig.toPath())).trim());
}
@Test
void bundleWithExistingSameComponentOtherVersionAndOtherComponents(@TempDir final File temporaryFolder)
throws Exception {
final CarBundler.Configuration configuration = prepareBundle(temporaryFolder);
// try to execute the main now in a fake studio
final File fakeStudio = temporaryFolder;
final File fakeConfig = new File(fakeStudio, "configuration/config.ini");
fakeConfig.getParentFile().mkdirs();
try (final Writer writer = new FileWriter(fakeConfig)) {
writer.write("component.java.coordinates = a:b:1,foo.bar:dummy:1.1,d:e:3");
}
final File fakeM2 = new File(fakeStudio, "configuration/.m2/repository/");
fakeM2.mkdirs();
assertEquals(0,
new ProcessBuilder(
new File(System.getProperty("java.home"),
"/bin/java" + (OS.WINDOWS.isCurrentOs() ? ".exe" : "")).getAbsolutePath(),
"-jar", configuration.getOutput().getAbsolutePath(), "studio-deploy",
fakeStudio.getAbsolutePath()).inheritIO().start().waitFor());
assertEquals("component.java.coordinates = foo.bar:dummy:1.2,a:b:1,d:e:3",
String.join("\n", Files.readAllLines(fakeConfig.toPath())).trim());
}
@Test
void bundle(@TempDir final File temporaryFolder) throws Exception {
final CarBundler.Configuration configuration = prepareBundle(temporaryFolder);
// try to execute the main now in a fake studio
final File fakeStudio = temporaryFolder;
final File fakeConfig = new File(fakeStudio, "configuration/config.ini");
fakeConfig.getParentFile().mkdirs();
try (final Writer writer = new FileWriter(fakeConfig)) {
// no-op, just create the file
}
final File fakeM2 = new File(fakeStudio, "configuration/.m2/repository/");
fakeM2.mkdirs();
assertEquals(0,
new ProcessBuilder(
new File(System.getProperty("java.home"),
"/bin/java" + (OS.WINDOWS.isCurrentOs() ? ".exe" : "")).getAbsolutePath(),
"-jar", configuration.getOutput().getAbsolutePath(), "studio-deploy",
fakeStudio.getAbsolutePath()).inheritIO().start().waitFor());
// asserts the jar was installed and the component registered
assertTrue(new File(fakeM2, "foo/bar/dummy/1.2/dummy-1.2.jar").exists());
assertEquals("component.java.coordinates = foo.bar:dummy:1.2",
Files.readAllLines(fakeConfig.toPath()).stream().collect(joining("\n")).trim());
}
@Test
@EnabledOnOs(OS.LINUX)
public void defaultNoPropertiesSet() {
this.contextRunner
.withUserConfiguration(Config1.class)
.run((context) -> {
LocalDeployerProperties properties = context.getBean(LocalDeployerProperties.class);
assertThat(properties.getDebugPort()).isNull();
assertThat(properties.getDebugSuspend()).isNull();
assertThat(properties.isDeleteFilesOnExit()).isTrue();
assertThat(properties.getEnvVarsToInherit()).containsExactly("TMP", "LANG", "LANGUAGE", "LC_.*",
"PATH", "SPRING_APPLICATION_JSON");
assertThat(properties.isInheritLogging()).isFalse();
assertThat(properties.getJavaCmd()).contains("java");
assertThat(properties.getJavaOpts()).isNull();
assertThat(properties.getMaximumConcurrentTasks()).isEqualTo(20);
assertThat(properties.getPortRange()).isNotNull();
assertThat(properties.getPortRange().getLow()).isEqualTo(20000);
assertThat(properties.getPortRange().getHigh()).isEqualTo(61000);
assertThat(properties.getShutdownTimeout()).isEqualTo(30);
assertThat(properties.isUseSpringApplicationJson()).isTrue();
assertThat(properties.getDocker().getNetwork()).isEqualTo("bridge");
});
}
@Test
@EnabledOnOs(OS.WINDOWS)
public void testOnWindows() {
this.contextRunner
.withInitializer(context -> {
Map<String, Object> map = new HashMap<>();
map.put("spring.cloud.deployer.local.working-directories-root", "file:/C:/tmp");
context.getEnvironment().getPropertySources().addLast(new SystemEnvironmentPropertySource(
StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, map));
})
.withUserConfiguration(Config1.class)
.run((context) -> {
LocalDeployerProperties properties = context.getBean(LocalDeployerProperties.class);
assertThat(properties.getWorkingDirectoriesRoot()).isNotNull();
assertThat(properties.getWorkingDirectoriesRoot().toString()).isEqualTo("C:\\tmp");
});
}
@Test
@EnabledOnOs(OS.LINUX)
public void testOnLinux() {
this.contextRunner
.withInitializer(context -> {
Map<String, Object> map = new HashMap<>();
map.put("spring.cloud.deployer.local.working-directories-root", "/tmp");
context.getEnvironment().getPropertySources().addLast(new SystemEnvironmentPropertySource(
StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, map));
})
.withUserConfiguration(Config1.class)
.run((context) -> {
LocalDeployerProperties properties = context.getBean(LocalDeployerProperties.class);
assertThat(properties.getWorkingDirectoriesRoot()).isNotNull();
assertThat(properties.getWorkingDirectoriesRoot().toString()).isEqualTo("/tmp");
});
}
@Test
@EnabledOnOs({ OS.LINUX, OS.MAC })
void throwsIllegalArgumentExceptionIfOutputDirectoryIsNotWriteable(final @TempDir Path tempDir) throws IOException
{
final Path outputDirectory = Files.createDirectory(tempDir.resolve("read-only"),
PosixFilePermissions.asFileAttribute(EnumSet.of(PosixFilePermission.OWNER_READ)));
final Builder builder = new Builder()
.numberOfMessages(4)
.messageTransceiverClass(InMemoryMessageTransceiver.class)
.outputDirectory(outputDirectory);
final IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, builder::build);
assertEquals("output directory is not writeable: " + outputDirectory, ex.getMessage());
}
@Test
@EnabledOnOs({ OS.LINUX, OS.MAC })
void throwsIllegalArgumentExceptionIfOutputDirectoryCannotBeCreated(final @TempDir Path tempDir) throws IOException
{
final Path rootDirectory = Files.createDirectory(tempDir.resolve("read-only"),
PosixFilePermissions.asFileAttribute(EnumSet.of(PosixFilePermission.OWNER_READ)));
final Path outputDirectory = rootDirectory.resolve("actual-dir");
final Builder builder = new Builder()
.numberOfMessages(4)
.messageTransceiverClass(InMemoryMessageTransceiver.class)
.outputDirectory(outputDirectory);
final IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, builder::build);
assertEquals("failed to create output directory: " + outputDirectory, ex.getMessage());
}
@Test
@EnabledOnOs(OS.WINDOWS)
void windowsServersContainedInJndi() throws InitializationException {
JndiContextResolverConfigProvider jndi = new JndiContextResolverConfigProvider();
jndi.initialize();
WindowsResolverConfigProvider win = new WindowsResolverConfigProvider();
win.initialize();
// the servers returned via Windows API must be in the JNDI list, but not necessarily the other
// way round. Unless there IPv6 servers which are not in the registry and Java <= 15 does not
// find.
for (InetSocketAddress winServer : win.servers()) {
assertTrue(
jndi.servers().contains(winServer),
winServer + " not found in JNDI, " + win.servers() + "; " + jndi.servers());
}
}
@Test
@DisabledOnOs(OS.WINDOWS)
void shouldNotLogPasswordsOnExceptionThrown() throws IOException {
File dir = temporaryFolder.newFolder();
File file = new File(dir, "test.sh");
FileOutputStream out = new FileOutputStream(file);
out.write("echo $1 && exit 10".getBytes());
out.close();
CommandLine line = CommandLine.createCommandLine("/bin/sh").withArg(file.getAbsolutePath()).withArg(new PasswordArgument("secret")).withEncoding("utf-8");
try {
line.runOrBomb(null);
} catch (CommandLineException e) {
assertThat(e.getMessage(), not(containsString("secret")));
}
}
@Test
@EnabledOnOs(OS.WINDOWS)
void shouldLogPasswordsOnOutputAsStarsUnderWindows() {
CommandLine line = CommandLine.createCommandLine("cmd")
.withEncoding("utf-8")
.withArg("/c")
.withArg("echo")
.withArg("My Password is:")
.withArg(new PasswordArgument("secret"));
InMemoryStreamConsumer output = new InMemoryStreamConsumer();
InMemoryStreamConsumer displayOutputStreamConsumer = InMemoryStreamConsumer.inMemoryConsumer();
ProcessWrapper processWrapper = line.execute(output, new EnvironmentVariableContext(), null);
processWrapper.waitForExit();
assertThat(output.getAllOutput(), containsString("secret"));
assertThat(displayOutputStreamConsumer.getAllOutput(), not(containsString("secret")));
}
@Test
@DisabledOnOs(OS.WINDOWS)
void shouldLogPasswordsOnEnvironemntAsStarsUnderLinux() {
CommandLine line = CommandLine.createCommandLine("echo")
.withArg("My Password is:")
.withArg("secret")
.withArg(new PasswordArgument("secret"))
.withEncoding("utf-8");
EnvironmentVariableContext environmentVariableContext = new EnvironmentVariableContext();
environmentVariableContext.setProperty("ENV_PASSWORD", "secret", false);
InMemoryStreamConsumer output = new InMemoryStreamConsumer();
InMemoryStreamConsumer forDisplay = InMemoryStreamConsumer.inMemoryConsumer();
ProcessWrapper processWrapper = line.execute(output, environmentVariableContext, null);
processWrapper.waitForExit();
assertThat(forDisplay.getAllOutput(), not(containsString("secret")));
assertThat(output.getAllOutput(), containsString("secret"));
}
@Test
@EnabledOnOs({OS.WINDOWS})
void shouldThrowExceptionWhenWorkingDirectoryIsNotGitRepoAndItsUnableToDeleteIt() throws IOException {
File fileToBeLocked = new File(workingDir, "file");
RandomAccessFile lockedFile = new RandomAccessFile(fileToBeLocked, "rw");
FileLock lock = lockedFile.getChannel().lock();
try {
git.latestModification(workingDir, new TestSubprocessExecutionContext());
fail("Should have failed to check modifications since the file is locked and cannot be removed.");
} catch (Exception e) {
assertThat("Failed to delete directory: " + workingDir.getAbsolutePath().trim()).isEqualTo(e.getMessage().trim());
assertThat(fileToBeLocked.exists()).isTrue();
} finally {
lock.release();
}
}
@Test
@DisabledOnOs(OS.WINDOWS)
void shouldUpdateServerHealthServiceIfACommandSnippetXMLIsUnReadableAndRemoveItOnceItsReadable() throws IOException {
File dirWithUnreadableFile = temporaryFolder.newFolder("dirWithUnreadableFile");
File unreadableFile = new File(dirWithUnreadableFile, "unreadable.xml");
FileUtils.copyFile(xmlFile, unreadableFile);
unreadableFile.setReadable(false);
walker.getAllCommandSnippets(dirWithUnreadableFile.getPath());
verify(serverHealthService).update(serverHealthWarningMessageWhichContains("Failed to access command snippet XML file located in Go Server Directory at " + unreadableFile.getPath() +
". Go does not have sufficient permissions to access it."));
unreadableFile.setReadable(true);
walker.getAllCommandSnippets(dirWithUnreadableFile.getPath());
verify(serverHealthService, times(2)).update(serverHealthMessageWhichSaysItsOk());
verifyNoMoreInteractions(serverHealthService);
}
@Test
@DisabledOnOs(OS.WINDOWS)
void shouldReportErrorWhenCancelCommandDoesNotExist() {
StubBuilder stubBuilder = new StubBuilder();
CommandBuilder cancelBuilder = new CommandBuilder("echo2", "cancel task", new File("."),
new RunIfConfigs(FAILED), stubBuilder,
"");
CommandBuilder builder = new CommandBuilder("echo", "normal task", new File("."), new RunIfConfigs(FAILED),
cancelBuilder,
"");
builder.cancel(goPublisher, new EnvironmentVariableContext(), null, null, "utf-8");
assertThat(goPublisher.getMessage()).contains("Error happened while attempting to execute 'echo2 cancel task'");
}
@Test
@DisabledOnOs(OS.WINDOWS)
void shouldFailIfMultipleMaterialsHaveSameFolderNameSet_CaseInSensitive() {
HgMaterialConfig materialOne = hg("http://url1", null);
materialOne.setConfigAttributes(Collections.singletonMap(ScmMaterialConfig.FOLDER, "folder"));
HgMaterialConfig materialTwo = hg("http://url2", null);
materialTwo.setConfigAttributes(Collections.singletonMap(ScmMaterialConfig.FOLDER, "foLder"));
CruiseConfig config = GoConfigMother.configWithPipelines("one");
PipelineConfig pipelineOne = config.pipelineConfigByName(new CaseInsensitiveString("one"));
pipelineOne.setMaterialConfigs(new MaterialConfigs(materialOne, materialTwo));
MaterialConfigs materials = pipelineOne.materialConfigs();
materials.validate(ConfigSaveValidationContext.forChain(config));
assertThat(materials.get(0).errors().isEmpty()).isFalse();
assertThat(materials.get(1).errors().isEmpty()).isFalse();
assertThat(materials.get(0).errors().on(ScmMaterialConfig.FOLDER)).isEqualTo("The destination directory must be unique across materials.");
assertThat(materials.get(1).errors().on(ScmMaterialConfig.FOLDER)).isEqualTo("The destination directory must be unique across materials.");
}
@Test
@EnabledOnOs(OS.MAC)
public void testMacOSLibraryLoading() {
MacOSLibrary library = new TestMacOsLibrary();
Assertions.assertNotNull(getClass().getResource(library.getLibraryPath()),
"macOS library doesn't exist");
Assertions.assertDoesNotThrow(library::updateLibrary);
Assertions.assertTrue(library.isLoaded(), "MacOS library isn't loaded");
}
@Test
@EnabledOnOs(OS.WINDOWS)
public void testWindowsLibraryLoading() {
WindowsLibrary library = new TestWindowsLibrary();
Assertions.assertNotNull(getClass().getResource(library.getX64Path() + library.getLibraryName()),
"x64 library doesn't exist");
Assertions.assertNotNull(getClass().getResource(library.getX86Path() + library.getLibraryName()),
"x86 library doesn't exist");
// Assertions.assertDoesNotThrow(library::updateLibrary);
// Assertions.assertTrue(library.isLoaded(), "Windows library isn't loaded");
}
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
if (!OS.WINDOWS.isCurrentOs()) {
return enabled("Non-Windows OS");
}
var test = context.getRequiredTestClass();
var bots = test.getPackageName().startsWith("org.openjdk.skara.bots.");
return bots ? disabled("All bots tests are disabled on Windows") : enabled("Non-bots test");
}
@Test
@DisabledOnOs(OS.MAC)
void testSystemMetrics() throws InterruptedException {
systemMetrics.bindTo(metricRegistry);
// makes sure system.cpu.total.norm.pct does not return NaN
consumeCpu();
Thread.sleep(1000);
assertThat(metricRegistry.getGaugeValue("system.cpu.total.norm.pct", Labels.EMPTY)).isBetween(0.0, 1.0);
assertThat(metricRegistry.getGaugeValue("system.process.cpu.total.norm.pct", Labels.EMPTY)).isBetween(0.0, 1.0);
assertThat(metricRegistry.getGaugeValue("system.memory.total", Labels.EMPTY)).isGreaterThan(0.0);
assertThat(metricRegistry.getGaugeValue("system.memory.actual.free", Labels.EMPTY)).isGreaterThan(0.0);
assertThat(metricRegistry.getGaugeValue("system.process.memory.size", Labels.EMPTY)).isGreaterThan(0.0);
}
@Test
@DisabledOnOs(OS.WINDOWS)
void testRootAllowed() {
this.builder.withRootAllowed(true);
Cassandra cassandra = this.builder.create();
Object node = ReflectionTestUtils.getField(ReflectionTestUtils.getField(cassandra, "database"), "node");
assertThat(node).hasFieldOrPropertyWithValue("rootAllowed", true);
}
@Test
@DisabledOnOs(OS.WINDOWS)
void shouldRunProcessUnix(@TempDir Path temporaryFolder) throws Exception {
StringBuilder output = new StringBuilder();
int exit = runProcess(temporaryFolder, "bash", "-c", command("echo", "$RUN_PROCESS_TEST")).run(output::append);
assertThat(output.toString()).isEqualTo("TEST");
assertThat(exit).isEqualTo(0);
}
@Test
@EnabledOnOs(OS.WINDOWS)
@DisabledOnJre(JRE.JAVA_8)
void constructProcessIdWindowsJava9() throws IOException {
Process process = new ProcessBuilder("echo", "Hello world").start();
assertThat(Pid.get(process)).isGreaterThan(0);
}
@Test
@EnabledOnJre(JRE.JAVA_8)
@EnabledOnOs(OS.WINDOWS)
void constructProcessIdWindowsJava8() throws IOException {
Process process = new ProcessBuilder("echo", "Hello world").start();
assertThat(Pid.get(process)).isEqualTo(-1);
}
@Test
@EnabledOnOs(OS.WINDOWS)
@Disabled("Only run manually")
void cameraConnectedIsSeenWithUser32() throws InterruptedException {
// This test demonstrate how to get events from library using User32 but better to use EdsGetEvent of library
final User32 lib = User32.INSTANCE;
final AtomicBoolean cameraEventCalled = new AtomicBoolean(false);
TestShortcutUtil.registerCameraAddedHandler(inContext -> {
log.warn("Camera added called {}", inContext);
cameraEventCalled.set(true);
return new NativeLong(0);
});
final WinUser.MSG msg = new WinUser.MSG();
for (int i = 0; i < 100; i++) {
Thread.sleep(50);
final boolean hasMessage = lib.PeekMessage(msg, null, 0, 0, 1);
if (hasMessage) {
log.warn("Had message");
lib.TranslateMessage(msg);
lib.DispatchMessage(msg);
}
}
Assertions.assertTrue(cameraEventCalled.get());
}
@Test
@DisabledOnOs(OS.WINDOWS)
void create() {
assertTimeoutPreemptively(TIMEOUT, () -> {
assertThrows(PoolException.class, this::status);
});
}