下面列出了org.junit.jupiter.api.condition.DisabledOnOs 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
@DisabledOnOs(WINDOWS)
public void testExtractImageReturningContainerFileSystem() throws ExecutableRunnerException {
final String image = "ubuntu:latest";
final String imageId = null;
final String tar = null;
final ExecutableRunner executableRunner = Mockito.mock(ExecutableRunner.class);
final Extraction extraction = extract(image, imageId, tar, fakeContainerFileSystemFile, null, executableRunner);
assertEquals("ubuntu:latest", extraction.getMetaData(DockerExtractor.DOCKER_IMAGE_NAME_META_DATA).get());
assertTrue(extraction.getMetaData(DockerExtractor.DOCKER_TAR_META_DATA).get().getName().endsWith("_containerfilesystem.tar.gz"));
final ArgumentCaptor<Executable> executableArgumentCaptor = ArgumentCaptor.forClass(Executable.class);
Mockito.verify(executableRunner).execute(executableArgumentCaptor.capture());
final Executable executableToVerify = executableArgumentCaptor.getValue();
final List<String> command = executableToVerify.getCommand();
assertTrue(command.get(0).endsWith("/fake/test/java"));
assertEquals("-jar", command.get(1));
assertTrue(command.get(2).endsWith("/fake/test/dockerinspector.jar"));
assertTrue(command.get(3).startsWith("--spring.config.location="));
assertTrue(command.get(3).endsWith("/application.properties"));
assertEquals("--docker.image=ubuntu:latest", command.get(4));
}
@Test
@DisabledOnOs(WINDOWS)
public void testExtractImageReturningSquashedImage() throws ExecutableRunnerException {
final String image = "ubuntu:latest";
final String imageId = null;
final String tar = null;
final ExecutableRunner executableRunner = Mockito.mock(ExecutableRunner.class);
final Extraction extraction = extract(image, imageId, tar, fakeContainerFileSystemFile, fakeSquashedImageFile, executableRunner);
assertEquals("ubuntu:latest", extraction.getMetaData(DockerExtractor.DOCKER_IMAGE_NAME_META_DATA).get());
// When Detect gets both .tar.gz files back, should prefer the squashed image
assertTrue(extraction.getMetaData(DockerExtractor.DOCKER_TAR_META_DATA).get().getName().endsWith("_squashedimage.tar.gz"));
final ArgumentCaptor<Executable> executableArgumentCaptor = ArgumentCaptor.forClass(Executable.class);
Mockito.verify(executableRunner).execute(executableArgumentCaptor.capture());
final Executable executableToVerify = executableArgumentCaptor.getValue();
final List<String> command = executableToVerify.getCommand();
assertTrue(command.get(0).endsWith("/fake/test/java"));
assertEquals("-jar", command.get(1));
assertTrue(command.get(2).endsWith("/fake/test/dockerinspector.jar"));
assertTrue(command.get(3).startsWith("--spring.config.location="));
assertTrue(command.get(3).endsWith("/application.properties"));
assertEquals("--docker.image=ubuntu:latest", command.get(4));
}
@Test
@DisabledOnOs(WINDOWS)
public void testExtractTarReturningContainerFileSystem() throws ExecutableRunnerException {
final String image = null;
final String imageId = null;
final String tar = fakeDockerTarFile.getAbsolutePath();
final ExecutableRunner executableRunner = Mockito.mock(ExecutableRunner.class);
final Extraction extraction = extract(image, imageId, tar, fakeContainerFileSystemFile, null, executableRunner);
assertTrue(extraction.getMetaData(DockerExtractor.DOCKER_IMAGE_NAME_META_DATA).get().endsWith("testDockerTarfile.tar"));
assertTrue(extraction.getMetaData(DockerExtractor.DOCKER_TAR_META_DATA).get().getName().endsWith("_containerfilesystem.tar.gz"));
final ArgumentCaptor<Executable> executableArgumentCaptor = ArgumentCaptor.forClass(Executable.class);
Mockito.verify(executableRunner).execute(executableArgumentCaptor.capture());
final Executable executableToVerify = executableArgumentCaptor.getValue();
final List<String> command = executableToVerify.getCommand();
assertTrue(command.get(0).endsWith("/fake/test/java"));
assertEquals("-jar", command.get(1));
assertTrue(command.get(2).endsWith("/fake/test/dockerinspector.jar"));
assertTrue(command.get(3).startsWith("--spring.config.location="));
assertTrue(command.get(3).endsWith("/application.properties"));
assertTrue(command.get(4).startsWith("--docker.tar="));
assertTrue(command.get(4).endsWith("testDockerTarfile.tar"));
}
@Test
@DisabledOnOs(WINDOWS)
public void testGetImageIdentifierFromOutputDirectoryIfImageIdPresent() throws URISyntaxException {
String testString = "test";
String imageIdArgument = "--docker.image.id=";
String imageName = "ubuntu:latest";
final File outputDirectoryWithPopulatedResultsFile = new File(DockerExtractorTest.class.getClassLoader().getSystemResource("detectables/functional/docker/unit/outputDirectoryWithPopulatedResultsFile").toURI());
final File outputDirectoryWithNonPopulatedResultsFile = new File(DockerExtractorTest.class.getClassLoader().getSystemResource("detectables/functional/docker/unit/outputDirectoryWithNonPopulatedResultsFile").toURI());
ExecutableRunner executableRunner = Mockito.mock(ExecutableRunner.class);
FileFinder fileFinder = Mockito.mock(FileFinder.class);
Mockito.when(fileFinder.findFile(outputDirectoryWithPopulatedResultsFile, DockerExtractor.RESULTS_FILENAME_PATTERN)).thenReturn(new File(outputDirectoryWithPopulatedResultsFile, "results.json"));
Mockito.when(fileFinder.findFile(outputDirectoryWithNonPopulatedResultsFile, DockerExtractor.RESULTS_FILENAME_PATTERN)).thenReturn(new File(outputDirectoryWithNonPopulatedResultsFile, "results.json"));
DockerExtractor dockerExtractor = getMockDockerExtractor(executableRunner, fileFinder);
assertEquals(imageName, dockerExtractor.getImageIdentifierFromOutputDirectoryIfImageIdPresent(outputDirectoryWithPopulatedResultsFile, testString, ImageIdentifierType.IMAGE_ID));
assertEquals(testString, dockerExtractor.getImageIdentifierFromOutputDirectoryIfImageIdPresent(outputDirectoryWithPopulatedResultsFile, testString, ImageIdentifierType.IMAGE_NAME));
assertEquals(testString, dockerExtractor.getImageIdentifierFromOutputDirectoryIfImageIdPresent(outputDirectoryWithNonPopulatedResultsFile, testString, ImageIdentifierType.IMAGE_ID));
}
@UnitTest
@DisabledOnOs(WINDOWS)
public void testSymlinksNotFollowed() throws IOException {
// Create a subDir with a symlink that loops back to its parent
final File initialDirectory = initialDirectoryPath.toFile();
final File subDir = new File(initialDirectory, "sub");
subDir.mkdirs();
final File link = new File(subDir, "linkToInitial");
final Path linkPath = link.toPath();
Files.createSymbolicLink(linkPath, initialDirectoryPath);
final File regularDir = new File(subDir, "regularDir");
regularDir.mkdir();
final File regularFile = new File(subDir, "regularFile");
regularFile.createNewFile();
final SimpleFileFinder finder = new SimpleFileFinder();
final List<String> filenamePatterns = Arrays.asList("sub", "linkToInitial", "regularDir", "regularFile");
final List<File> foundFiles = finder.findFiles(initialDirectoryPath.toFile(), filenamePatterns, 10);
// make sure symlink not followed during dir traversal
assertEquals(4, foundFiles.size());
}
@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
@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
@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 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
@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
@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
@DisabledOnOs(WINDOWS) //TODO: See if we can fix on windows.
public void testSimple() throws DetectorFinderDirectoryListException {
Assumptions.assumeFalse(SystemUtils.IS_OS_WINDOWS);
final File initialDirectory = initialDirectoryPath.toFile();
final File subDir = new File(initialDirectory, "testSimple");
subDir.mkdirs();
final File subSubDir1 = new File(subDir, "subSubDir1");
subSubDir1.mkdir();
final File subSubDir2 = new File(subDir, "subSubDir2");
subSubDir2.mkdir();
final DetectorRuleSet detectorRuleSet = new DetectorRuleSet(new ArrayList<>(0), new HashMap<>(0), new HashMap<>());
final Predicate<File> fileFilter = f -> true;
final int maximumDepth = 10;
final DetectorFinderOptions options = new DetectorFinderOptions(fileFilter, maximumDepth);
final DetectorFinder finder = new DetectorFinder();
final Optional<DetectorEvaluationTree> tree = finder.findDetectors(initialDirectory, detectorRuleSet, options);
// make sure both dirs were found
final Set<DetectorEvaluationTree> testDirs = tree.get().getChildren();
DetectorEvaluationTree simpleTestDir = null;
for (final DetectorEvaluationTree testDir : testDirs) {
if (testDir.getDirectory().getName().equals("testSimple")) {
simpleTestDir = testDir;
break;
}
}
final Set<DetectorEvaluationTree> subDirResults = simpleTestDir.getChildren();
assertEquals(2, subDirResults.size());
final String subDirContentsName = subDirResults.iterator().next().getDirectory().getName();
assertTrue(subDirContentsName.startsWith("subSubDir"));
}
@Test
@DisabledOnOs(WINDOWS)
public void testExtractTarReturningOriginalTar() throws ExecutableRunnerException {
final String image = null;
final String imageId = null;
final String tar = fakeDockerTarFile.getAbsolutePath();
final ExecutableRunner executableRunner = Mockito.mock(ExecutableRunner.class);
final Extraction extraction = extract(image, imageId, tar, null, null, executableRunner);
// No returned .tar.gz: scan given docker tar instead
assertTrue(extraction.getMetaData(DockerExtractor.DOCKER_IMAGE_NAME_META_DATA).get().endsWith("testDockerTarfile.tar"));
assertTrue(extraction.getMetaData(DockerExtractor.DOCKER_TAR_META_DATA).get().getName().endsWith("testDockerTarfile.tar"));
final ArgumentCaptor<Executable> executableArgumentCaptor = ArgumentCaptor.forClass(Executable.class);
Mockito.verify(executableRunner).execute(executableArgumentCaptor.capture());
final Executable executableToVerify = executableArgumentCaptor.getValue();
final List<String> command = executableToVerify.getCommand();
assertTrue(command.get(0).endsWith("/fake/test/java"));
assertEquals("-jar", command.get(1));
assertTrue(command.get(2).endsWith("/fake/test/dockerinspector.jar"));
assertTrue(command.get(3).startsWith("--spring.config.location="));
assertTrue(command.get(3).endsWith("/application.properties"));
assertTrue(command.get(4).startsWith("--docker.tar="));
assertTrue(command.get(4).endsWith("testDockerTarfile.tar"));
}
@Test
@DisabledOnOs(WINDOWS) // Due to backslashes being flipped.
public void testResolvingTilde() {
final TildeInPathResolver resolver = new TildeInPathResolver("/Users/ekerwin");
final Path resolved = resolver.resolvePath("~/Documents/source/funtional/detect");
Assertions.assertNotNull(resolved, "Resolved path should not be null.");
Assertions.assertEquals("/Users/ekerwin/Documents/source/funtional/detect", resolved.toString(), "Tilde's should be resolved on Unix operating systems.");
}
@Test
@DisabledOnOs(WINDOWS) // Due to backslashes being flipped.
public void testResolvingTildeInTheMiddleOfAPath() {
final TildeInPathResolver resolver = new TildeInPathResolver("/Users/ekerwin");
final String filePath = "/Documents/~source/~/funtional/detect";
final Path resolved = resolver.resolvePath(filePath);
Assertions.assertNotNull(resolved, "Resolved path should not be null.");
Assertions.assertEquals(filePath, resolved.toString(), "Tilde's in the middle of the path should not be resolved.");
}
@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
@DisabledOnOs(OS.WINDOWS)
void testRootAllowed() {
this.cassandraFactory.setRootAllowed(true);
Cassandra cassandra = this.cassandraFactory.create();
Object node = ReflectionTestUtils.getField(ReflectionTestUtils.getField(cassandra, "database"), "node");
assertThat(node).hasFieldOrPropertyWithValue("rootAllowed", true);
}
@Test
@DisabledOnOs(OS.WINDOWS)
void create() {
assertTimeoutPreemptively(TIMEOUT, () -> {
assertThrows(PoolException.class, this::status);
});
}
@Test
@DisabledOnOs(OS.WINDOWS)
void stop() {
assertTimeoutPreemptively(TIMEOUT, () -> {
makeLifecycle();
// Should not respond after stop
assertThrows(PoolException.class, this::status);
});
}
@DisabledOnOs(OS.WINDOWS)
@Test
void permissions() throws IOException {
File file = createTempFile();
Path path = file.toPath();
boolean result = FileUtil.configurePermissions(file, true);
assertSoftly(softly -> {
softly.assertThat(path.toFile())
.canRead()
.canWrite();
softly.assertThat(path.toFile()
.canExecute())
.isTrue();
softly.assertThat(result)
.isTrue();
});
boolean result2 = FileUtil.configurePermissions(file, false);
assertSoftly(softly -> {
softly.assertThat(path.toFile())
.canRead()
.canWrite();
softly.assertThat(path.toFile()
.canExecute())
.isFalse();
softly.assertThat(result2)
.isTrue();
});
}
@Test
@DisabledOnOs(OS.WINDOWS)
void shouldNotLogPasswordsFromStream() {
try (LogFixture logFixture = logFixtureFor(CommandLine.class, Level.DEBUG)) {
CommandLine line = CommandLine.createCommandLine("/bin/echo").withArg("=>").withArg(new PasswordArgument("secret")).withEncoding("utf-8");
line.runOrBomb(null);
assertThat(logFixture.getLog(), not(containsString("secret")));
assertThat(logFixture.getLog(), containsString("=> ******"));
}
}
@Test
@DisabledOnOs(OS.WINDOWS)
void shouldLogPasswordsOnOutputAsStarsUnderLinux() throws IOException {
CommandLine line = CommandLine.createCommandLine("echo")
.withArg("My Password is:")
.withArg(new PasswordArgument("secret"))
.withEncoding("utf-8");
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 shouldBeAbleToSpecifyEncoding() {
String chrisWasHere = "?????";
CommandLine line = CommandLine.createCommandLine("echo")
.withArg(chrisWasHere)
.withEncoding("UTF-8");
InMemoryStreamConsumer output = new InMemoryStreamConsumer();
ProcessWrapper processWrapper = line.execute(output, new EnvironmentVariableContext(), null);
processWrapper.waitForExit();
assertThat(output.getAllOutput(), containsString(chrisWasHere));
}
@Test
@DisabledOnOs(OS.WINDOWS)
void shouldBeAbleToRunCommandsInSubdirectories() throws IOException {
File shellScript = createScript("hello-world.sh", "echo ${PWD}");
assertThat(shellScript.setExecutable(true), is(true));
CommandLine line = CommandLine.createCommandLine("./hello-world.sh").withWorkingDir(subFolder).withEncoding("utf-8");
InMemoryStreamConsumer out = new InMemoryStreamConsumer();
line.execute(out, new EnvironmentVariableContext(), null).waitForExit();
assertThat(out.getAllOutput().trim(), endsWith("subFolder"));
}
@Test
@DisabledOnOs(OS.WINDOWS)
void shouldBeAbleToRunCommandsInSubdirectoriesWithNoWorkingDir() throws IOException {
File shellScript = createScript("hello-world.sh", "echo 'Hello World!'");
assertThat(shellScript.setExecutable(true), is(true));
CommandLine line = CommandLine.createCommandLine("subFolder/hello-world.sh").withWorkingDir(temporaryFolder.getRoot()).withEncoding("utf-8");
InMemoryStreamConsumer out = new InMemoryStreamConsumer();
line.execute(out, new EnvironmentVariableContext(), null).waitForExit();
assertThat(out.getAllOutput(), containsString("Hello World!"));
}
@Test
@DisabledOnOs(OS.WINDOWS)
void shouldNotRunLocalCommandsThatAreNotExecutable() throws IOException {
createScript("echo", "echo 'this should not be here'");
CommandLine line = CommandLine.createCommandLine("echo")
.withArg("Using the REAL echo")
.withWorkingDir(subFolder)
.withEncoding("utf-8");
InMemoryStreamConsumer out = new InMemoryStreamConsumer();
line.execute(out, new EnvironmentVariableContext(), null).waitForExit();
assertThat(out.getAllOutput(), containsString("Using the REAL echo"));
}
@Test
@DisabledOnOs(OS.WINDOWS)
void shouldBeAbleToRunCommandsFromRelativeDirectories() throws IOException {
File shellScript = temporaryFolder.newFile("hello-world.sh");
FileUtils.writeStringToFile(shellScript, "echo ${PWD}", UTF_8);
assertThat(shellScript.setExecutable(true), is(true));
CommandLine line = CommandLine.createCommandLine("../hello-world.sh").withWorkingDir(subFolder).withEncoding("utf-8");
InMemoryStreamConsumer out = new InMemoryStreamConsumer();
line.execute(out, new EnvironmentVariableContext(), null).waitForExit();
assertThat(out.getAllOutput().trim(), endsWith("subFolder"));
}