下面列出了怎么用org.junit.jupiter.api.condition.EnabledOnOs的API类实例代码及写法,或者点击链接到github查看源代码。
@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
@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
@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
@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
@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");
}
@Test
@EnabledOnOs(WINDOWS) // Path is more forgiving of whitespace on Unix systems.
public void testWhitespacePath() {
final TildeInPathResolver resolver = new TildeInPathResolver("/Users/ekerwin");
Assertions.assertThrows(InvalidPathException.class, () -> {
resolver.resolvePath(" ");
});
}
@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
@EnabledOnOs({MAC, LINUX})
void nativeIntegrityCheck() throws DataFormatException {
VelocityCompressor compressor = Natives.compress.get().create(Deflater.DEFAULT_COMPRESSION);
if (compressor instanceof JavaVelocityCompressor) {
compressor.dispose();
fail("Loaded regular compressor");
}
check(compressor, () -> Unpooled.directBuffer(TEST_DATA.length + 32));
}
@Test
@EnabledOnOs(OS.WINDOWS)
void stopOnWindows() throws InterruptedException {
assertNotFinishesIn(TIMEOUT, () -> {
makeLifecycle();
// Should not respond after stop
status();
});
}
@Test
@Deployment
@EnabledOnOs(OS.WINDOWS)
public void testEchoShellWindows() {
if (osType == OsType.WINDOWS) {
ProcessInstance pi = runtimeService.startProcessInstanceByKey("echoShellWindows");
String st = (String) runtimeService.getVariable(pi.getId(), "resultVar");
assertThat(st).isNotNull();
assertThat(st).startsWith("EchoTest");
}
}
@Test
@Deployment
@EnabledOnOs(OS.LINUX)
public void testEchoShellLinux() {
if (osType == OsType.LINUX) {
ProcessInstance pi = runtimeService.startProcessInstanceByKey("echoShellLinux");
String st = (String) runtimeService.getVariable(pi.getId(), "resultVar");
assertThat(st).isNotNull();
assertThat(st).startsWith("EchoTest");
}
}
@Test
@Deployment
@EnabledOnOs(OS.MAC)
public void testEchoShellMac() {
if (osType == OsType.MAC) {
ProcessInstance pi = runtimeService.startProcessInstanceByKey("echoShellMac");
String st = (String) runtimeService.getVariable(pi.getId(), "resultVar");
assertThat(st).isNotNull();
assertThat(st).startsWith("EchoTest");
}
}
@EnabledOnOs(LINUX)
@ParameterizedTest
@CsvSource({
"dir/a.json , file:///home/dir/a.json",
"./dir/a.json , file:///home/dir/a.json",
"././dir/a.json, file:///home/dir/a.json",
"../dir/a.json, file:///dir/a.json",
})
void toFileUriLinux(String file, String expectedUri) {
Path basePathFile = new File("/home/peter.json").toPath();
assertThat(SchemaDereferencer.toFileUri(basePathFile, file), is(expectedUri));
}
@EnabledOnOs(WINDOWS)
@ParameterizedTest
@CsvSource({
"dir\\a.json, file:///C:/Users/dir/a.json",
".\\dir\\a.json, file:///C:/Users/dir/a.json",
".\\.\\dir\\a.json, file:///C:/Users/dir/a.json",
"..\\dir\\a.json, file:///C:/dir/a.json",
})
void toFileUriWin(String file, String expectedUri) {
Path basePathFile = new File("C:\\Users\\peter.json").toPath();
assertThat(SchemaDereferencer.toFileUri(basePathFile, file), is(expectedUri));
}
@Test
@EnabledOnOs(OS.WINDOWS)
@DisabledIfEnvironmentVariable(named = "CI", matches = "true")
void canInstantiateInternetExplorerDriverWithInternetExplorerOptions() {
driver = provider.createDriver(new InternetExplorerOptions());
assertTrue(driver instanceof InternetExplorerDriver);
}
@Test
@EnabledOnOs(OS.WINDOWS)
@DisabledIfEnvironmentVariable(named = "CI", matches = "true")
void canInstantiateEdgeDriverWithEdgeOptions() {
driver = provider.createDriver(new EdgeOptions());
assertTrue(driver instanceof EdgeDriver);
}
@Test
@EnabledOnOs(OS.MAC)
@DisabledIfEnvironmentVariable(named = "CI", matches = "true")
void canInstantiateSafariDriverWithSafariOptions() {
driver = provider.createDriver(new SafariOptions());
assertTrue(driver instanceof SafariDriver);
}
@Test
@EnabledOnOs(OS.LINUX)
void shouldZipFileWhoseNameHasSpecialCharactersOnLinux() throws IOException {
File specialFile = new File(srcDir, "$`#[email protected]!()?-_{}^'~.+=[];,a.txt");
FileUtils.writeStringToFile(specialFile, "specialFile", UTF_8);
zipFile = zipUtil.zip(srcDir, temporaryFolder.newFile(), Deflater.NO_COMPRESSION);
zipUtil.unzip(zipFile, destDir);
File baseDir = new File(destDir, srcDir.getName());
File actualSpecialFile = new File(baseDir, specialFile.getName());
assertThat(actualSpecialFile.isFile()).isTrue();
assertThat(fileContent(actualSpecialFile)).isEqualTo(fileContent(specialFile));
}
@Test
@EnabledOnOs(OS.WINDOWS)
void shouldProvideArtifactRootForAJobOnWindows() throws Exception {
assumeArtifactsRoot(fakeRoot);
ArtifactsService artifactsService = new ArtifactsService(resolverService, stageService, artifactsDirHolder, zipUtil);
artifactsService.initialize();
JobIdentifier oldId = new JobIdentifier("cruise", 1, "1.1", "dev", "2", "linux-firefox", null);
when(resolverService.actualJobIdentifier(oldId)).thenReturn(new JobIdentifier("cruise", 1, "1.1", "dev", "2", "linux-firefox", null));
String artifactRoot = artifactsService.findArtifactRoot(oldId);
assertThat(artifactRoot).isEqualTo("pipelines\\cruise\\1\\dev\\2\\linux-firefox");
}
@Test
@EnabledOnOs(OS.WINDOWS)
void shouldUseAbsoluteNantPathIfAbsoluteNantPathIsSpecifiedOnWindows() {
NantTask nantTask = new NantTask();
nantTask.setNantPath("c:\\nantdir");
CommandBuilder builder = (CommandBuilder) nantTaskBuilder.createBuilder(builderFactory, nantTask, pipeline, resolver);
assertThat(new File(builder.getCommand())).isEqualTo(new File("c:\\nantdir\\nant"));
}
@Test
@EnabledOnOs(OS.WINDOWS)
void shouldReportErrorWhenComandIsNotExistOnWindows() throws Exception {
buildWork = (BuildWork) getWork(CMD_NOT_EXIST, PIPELINE_NAME);
buildWork.doWork(environmentVariableContext, new AgentWorkContext(agentIdentifier, buildRepository, artifactManipulator, new AgentRuntimeInfo(agentIdentifier, AgentRuntimeStatus.Idle, currentWorkingDirectory(), "cookie"), packageRepositoryExtension, scmExtension, taskExtension, null, pluginRequestProcessorRegistry));
assertConsoleOut(artifactManipulator.consoleOut()).printedAppsMissingInfoOnWindows(SOMETHING_NOT_EXIST);
assertThat(buildRepository.results).contains(Failed);
}
@Test
@EnabledOnOs(OS.WINDOWS)
void nantTest() throws Exception {
buildWork = (BuildWork) getWork(NANT, PIPELINE_NAME);
buildWork.doWork(environmentVariableContext, new AgentWorkContext(agentIdentifier, buildRepository, artifactManipulator, new AgentRuntimeInfo(agentIdentifier, AgentRuntimeStatus.Idle, currentWorkingDirectory(), "cookie"), packageRepositoryExtension, scmExtension, taskExtension, null, pluginRequestProcessorRegistry));
assertThat(artifactManipulator.consoleOut()).contains("Usage : NAnt [options] <target> <target> ...");
}