Merge pull request #8125 from eugenp/revert-8119-BAEL-3275-2

Revert "BAEL-3275: Using blocking queue for pub-sub"
This commit is contained in:
Eric Martin
2019-10-31 20:43:47 -05:00
committed by GitHub
parent db85c8f275
commit 3225470df5
20543 changed files with 1642750 additions and 0 deletions
@@ -0,0 +1,34 @@
package com.baeldung.core.pwd;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class CurrentDirectoryFetcherTest {
private static final String CURRENT_DIR = "core-java-os";
@Test
public void whenUsingSystemProperties_thenReturnCurrentDirectory() {
assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingSystemProperties()
.endsWith(CURRENT_DIR));
}
@Test
public void whenUsingJavaNioPaths_thenReturnCurrentDirectory() {
assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingPaths()
.endsWith(CURRENT_DIR));
}
@Test
public void whenUsingJavaNioFileSystems_thenReturnCurrentDirectory() {
assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingFileSystems()
.endsWith(CURRENT_DIR));
}
@Test
public void whenUsingJavaIoFile_thenReturnCurrentDirectory() {
assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingFile()
.endsWith(CURRENT_DIR));
}
}
@@ -0,0 +1,55 @@
package com.baeldung.grep;
import java.io.File;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.unix4j.Unix4j;
import static org.unix4j.Unix4j.*;
import static org.junit.Assert.assertEquals;
import org.unix4j.line.Line;
import static org.unix4j.unix.Grep.*;
import static org.unix4j.unix.cut.CutOption.*;
public class GrepWithUnix4JIntegrationTest {
private File fileToGrep;
@Before
public void init() {
final String separator = File.separator;
final String filePath = String.join(separator, new String[] { "src", "test", "resources", "dictionary.in" });
fileToGrep = new File(filePath);
}
@Test
public void whenGrepWithSimpleString_thenCorrect() {
int expectedLineCount = 4;
// grep "NINETEEN" dictionary.txt
List<Line> lines = Unix4j.grep("NINETEEN", fileToGrep).toLineList();
assertEquals(expectedLineCount, lines.size());
}
@Test
public void whenInverseGrepWithSimpleString_thenCorrect() {
int expectedLineCount = 178687;
// grep -v "NINETEEN" dictionary.txt
List<Line> lines = grep(Options.v, "NINETEEN", fileToGrep).toLineList();
assertEquals(expectedLineCount, lines.size());
}
@Test
public void whenGrepWithRegex_thenCorrect() {
int expectedLineCount = 151;
// grep -c ".*?NINE.*?" dictionary.txt
String patternCount = grep(Options.c, ".*?NINE.*?", fileToGrep).cut(fields, ":", 1).toStringResult();
assertEquals(expectedLineCount, Integer.parseInt(patternCount));
}
}
@@ -0,0 +1,133 @@
package com.baeldung.java9.process;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by sanaulla on 2/23/2017.
*/
public class ProcessAPIEnhancementsUnitTest {
Logger log = LoggerFactory.getLogger(ProcessAPIEnhancementsUnitTest.class);
@Test
public void givenCurrentProcess_whenInvokeGetInfo_thenSuccess() throws IOException {
ProcessHandle processHandle = ProcessHandle.current();
ProcessHandle.Info processInfo = processHandle.info();
assertNotNull(processHandle.pid());
assertEquals(false, processInfo.arguments()
.isPresent());
assertEquals(true, processInfo.command()
.isPresent());
assertTrue(processInfo.command()
.get()
.contains("java"));
assertEquals(true, processInfo.startInstant()
.isPresent());
assertEquals(true, processInfo.totalCpuDuration()
.isPresent());
assertEquals(true, processInfo.user()
.isPresent());
}
@Test
public void givenSpawnProcess_whenInvokeGetInfo_thenSuccess() throws IOException {
String javaCmd = ProcessUtils.getJavaCmd()
.getAbsolutePath();
ProcessBuilder processBuilder = new ProcessBuilder(javaCmd, "-version");
Process process = processBuilder.inheritIO()
.start();
ProcessHandle processHandle = process.toHandle();
ProcessHandle.Info processInfo = processHandle.info();
assertNotNull(processHandle.pid());
assertEquals(false, processInfo.arguments()
.isPresent());
assertEquals(true, processInfo.command()
.isPresent());
assertTrue(processInfo.command()
.get()
.contains("java"));
assertEquals(true, processInfo.startInstant()
.isPresent());
assertEquals(true, processInfo.totalCpuDuration()
.isPresent());
assertEquals(true, processInfo.user()
.isPresent());
}
@Test
public void givenLiveProcesses_whenInvokeGetInfo_thenSuccess() {
Stream<ProcessHandle> liveProcesses = ProcessHandle.allProcesses();
liveProcesses.filter(ProcessHandle::isAlive)
.forEach(ph -> {
assertNotNull(ph.pid());
assertEquals(true, ph.info()
.command()
.isPresent());
assertEquals(true, ph.info()
.startInstant()
.isPresent());
assertEquals(true, ph.info()
.totalCpuDuration()
.isPresent());
assertEquals(true, ph.info()
.user()
.isPresent());
});
}
@Test
public void givenProcess_whenGetChildProcess_thenSuccess() throws IOException {
int childProcessCount = 5;
for (int i = 0; i < childProcessCount; i++) {
String javaCmd = ProcessUtils.getJavaCmd()
.getAbsolutePath();
ProcessBuilder processBuilder
= new ProcessBuilder(javaCmd, "-version");
processBuilder.inheritIO().start();
}
Stream<ProcessHandle> children = ProcessHandle.current()
.children();
children.filter(ProcessHandle::isAlive)
.forEach(ph -> log.info("PID: {}, Cmd: {}", ph.pid(), ph.info()
.command()));
Stream<ProcessHandle> descendants = ProcessHandle.current()
.descendants();
descendants.filter(ProcessHandle::isAlive)
.forEach(ph -> log.info("PID: {}, Cmd: {}", ph.pid(), ph.info()
.command()));
}
@Test
public void givenProcess_whenAddExitCallback_thenSuccess() throws Exception {
String javaCmd = ProcessUtils.getJavaCmd()
.getAbsolutePath();
ProcessBuilder processBuilder
= new ProcessBuilder(javaCmd, "-version");
Process process = processBuilder.inheritIO()
.start();
ProcessHandle processHandle = process.toHandle();
log.info("PID: {} has started", processHandle.pid());
CompletableFuture<ProcessHandle> onProcessExit = processHandle.onExit();
onProcessExit.get();
assertEquals(false, processHandle.isAlive());
onProcessExit.thenAccept(ph -> {
log.info("PID: {} has stopped", ph.pid());
});
}
}
@@ -0,0 +1,111 @@
package com.baeldung.java9.process;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Test;
import junit.framework.Assert;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ProcessApiUnitTest {
@Before
public void init() {
}
@Test
public void processInfoExample() throws NoSuchAlgorithmException {
ProcessHandle self = ProcessHandle.current();
long PID = self.pid();
ProcessHandle.Info procInfo = self.info();
Optional<String[]> args = procInfo.arguments();
Optional<String> cmd = procInfo.commandLine();
Optional<Instant> startTime = procInfo.startInstant();
Optional<Duration> cpuUsage = procInfo.totalCpuDuration();
waistCPU();
System.out.println("Args " + args);
System.out.println("Command " + cmd.orElse("EmptyCmd"));
System.out.println("Start time: " + startTime.get().toString());
System.out.println(cpuUsage.get().toMillis());
Stream<ProcessHandle> allProc = ProcessHandle.current().children();
allProc.forEach(p -> {
System.out.println("Proc " + p.pid());
});
}
@Test
public void createAndDestroyProcess() throws IOException, InterruptedException {
int numberOfChildProcesses = 5;
for (int i = 0; i < numberOfChildProcesses; i++) {
createNewJVM(ServiceMain.class, i).pid();
}
Stream<ProcessHandle> childProc = ProcessHandle.current().children();
assertEquals(childProc.count(), numberOfChildProcesses);
childProc = ProcessHandle.current().children();
childProc.forEach(processHandle -> {
assertTrue("Process " + processHandle.pid() + " should be alive!", processHandle.isAlive());
CompletableFuture<ProcessHandle> onProcExit = processHandle.onExit();
onProcExit.thenAccept(procHandle -> {
System.out.println("Process with PID " + procHandle.pid() + " has stopped");
});
});
Thread.sleep(10000);
childProc = ProcessHandle.current().children();
childProc.forEach(procHandle -> {
assertTrue("Could not kill process " + procHandle.pid(), procHandle.destroy());
});
Thread.sleep(5000);
childProc = ProcessHandle.current().children();
childProc.forEach(procHandle -> {
assertFalse("Process " + procHandle.pid() + " should not be alive!", procHandle.isAlive());
});
}
private Process createNewJVM(Class mainClass, int number) throws IOException {
ArrayList<String> cmdParams = new ArrayList<String>(5);
cmdParams.add(ProcessUtils.getJavaCmd().getAbsolutePath());
cmdParams.add("-cp");
cmdParams.add(ProcessUtils.getClassPath());
cmdParams.add(mainClass.getName());
cmdParams.add("Service " + number);
ProcessBuilder myService = new ProcessBuilder(cmdParams);
myService.inheritIO();
return myService.start();
}
private void waistCPU() throws NoSuchAlgorithmException {
ArrayList<Integer> randArr = new ArrayList<Integer>(4096);
SecureRandom sr = SecureRandom.getInstanceStrong();
Duration somecpu = Duration.ofMillis(4200L);
Instant end = Instant.now().plus(somecpu);
while (Instant.now().isBefore(end)) {
// System.out.println(sr.nextInt());
randArr.add(sr.nextInt());
}
}
}
@@ -0,0 +1,121 @@
package com.baeldung.java9.process;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.String;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.lang.Integer;
import org.junit.jupiter.api.Test;
class ProcessUnderstandingUnitTest {
@Test
public void givenSourceProgram_whenExecutedFromAnotherProgram_thenSourceProgramOutput3() throws IOException {
Process process = Runtime.getRuntime()
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java");
process = Runtime.getRuntime()
.exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample");
BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
int value = Integer.parseInt(output.readLine());
assertEquals(3, value);
}
@Test
public void givenSourceProgram_whenReadingInputStream_thenFirstLineEquals3() throws IOException {
Process process = Runtime.getRuntime()
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java");
process = Runtime.getRuntime()
.exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample");
BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
int value = Integer.parseInt(output.readLine());
assertEquals(3, value);
}
@Test
public void givenSubProcess_whenEncounteringError_thenErrorStreamNotNull() throws IOException {
Process process = Runtime.getRuntime()
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ProcessCompilationError.java");
BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String errorString = error.readLine();
assertNotNull(errorString);
}
//@Test - windows specific
public void givenSubProcess_whenStarted_thenStartSuccessIsAlive() throws IOException {
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
assertTrue(builder.start().isAlive());
}
//@Test - windows specific
public void givenSubProcess_whenDestroying_thenProcessNotAlive() throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
Process process = builder.start();
Thread.sleep(10000);
process.destroy();
assertFalse(process.isAlive());
}
//@Test - windows specific
public void givenSubProcess_whenAlive_thenDestroyForcibly() throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
Process process = builder.start();
Thread.sleep(10000);
process.destroy();
if (process.isAlive()) {
process.destroyForcibly();
}
assertFalse(process.isAlive());
}
//@Test - windows specific
public void givenSubProcess_whenDestroyed_thenCheckIfAlive() throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
Process process = builder.start();
Thread.sleep(10000);
process.destroy();
assertFalse(process.isAlive());
}
@Test
public void givenProcessNotCreated_fromWithinJavaApplicationDestroying_thenProcessNotAlive() {
Optional<ProcessHandle> optionalProcessHandle = ProcessHandle.of(5232);
ProcessHandle processHandle = optionalProcessHandle.get();
processHandle.destroy();
assertFalse(processHandle.isAlive());
}
//@Test - windows specific
public void givenSubProcess_whenCurrentThreadWaitsIndefinitelyuntilSubProcessEnds_thenProcessWaitForReturnsGrt0() throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
Process process = builder.start();
assertThat(process.waitFor() >= 0);
}
//@Test - windows specific
public void givenSubProcess_whenCurrentThreadWaitsAndSubProcessNotTerminated_thenProcessWaitForReturnsFalse() throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
Process process = builder.start();
assertFalse(process.waitFor(1, TimeUnit.SECONDS));
}
//@Test - windows specific
public void givenSubProcess_whenCurrentThreadWillNotWaitIndefinitelyforSubProcessToEnd_thenProcessExitValueReturnsGrt0() throws IOException {
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
Process process = builder.start();
assertThat(process.exitValue() >= 0);
}
@Test
public void givenRunningProcesses_whenFilterOnProcessIdRange_thenGetSelectedProcessPid() {
assertThat(((int) ProcessHandle.allProcesses()
.filter(ph -> (ph.pid() > 10000 && ph.pid() < 50000))
.count()) > 0);
}
}
@@ -0,0 +1,25 @@
package com.baeldung.printscreen;
import org.junit.After;
import org.junit.Test;
import java.io.File;
import static org.junit.Assert.assertTrue;
public class ScreenshotLiveTest {
private Screenshot screenshot = new Screenshot("Screenshot.jpg");
private File file = new File("Screenshot.jpg");
@Test
public void testGetScreenshot() throws Exception {
screenshot.getScreenshot(2000);
assertTrue(file.exists());
}
@After
public void tearDown() throws Exception {
file.delete();
}
}
@@ -0,0 +1,182 @@
package com.baeldung.processbuilder;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ProcessBuilder.Redirect;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
public class ProcessBuilderUnitTest {
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
@Test
public void givenProcessBuilder_whenInvokeStart_thenSuccess() throws IOException, InterruptedException, ExecutionException {
ProcessBuilder processBuilder = new ProcessBuilder("java", "-version");
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
List<String> results = readOutput(process.getInputStream());
assertThat("Results should not be empty", results, is(not(empty())));
assertThat("Results should contain java version: ", results, hasItem(containsString("java version")));
int exitCode = process.waitFor();
assertEquals("No errors should be detected", 0, exitCode);
}
@Test
public void givenProcessBuilder_whenModifyEnvironment_thenSuccess() throws IOException, InterruptedException {
ProcessBuilder processBuilder = new ProcessBuilder();
Map<String, String> environment = processBuilder.environment();
environment.forEach((key, value) -> System.out.println(key + value));
environment.put("GREETING", "Hola Mundo");
List<String> command = getGreetingCommand();
processBuilder.command(command);
Process process = processBuilder.start();
List<String> results = readOutput(process.getInputStream());
assertThat("Results should not be empty", results, is(not(empty())));
assertThat("Results should contain a greeting ", results, hasItem(containsString("Hola Mundo")));
int exitCode = process.waitFor();
assertEquals("No errors should be detected", 0, exitCode);
}
@Test
public void givenProcessBuilder_whenModifyWorkingDir_thenSuccess() throws IOException, InterruptedException {
List<String> command = getDirectoryListingCommand();
ProcessBuilder processBuilder = new ProcessBuilder(command);
processBuilder.directory(new File("src"));
Process process = processBuilder.start();
List<String> results = readOutput(process.getInputStream());
assertThat("Results should not be empty", results, is(not(empty())));
assertThat("Results should contain directory listing: ", results, hasItems(containsString("main"), containsString("test")));
int exitCode = process.waitFor();
assertEquals("No errors should be detected", 0, exitCode);
}
@Test
public void givenProcessBuilder_whenRedirectStandardOutput_thenSuccessWriting() throws IOException, InterruptedException {
ProcessBuilder processBuilder = new ProcessBuilder("java", "-version");
processBuilder.redirectErrorStream(true);
File log = tempFolder.newFile("java-version.log");
processBuilder.redirectOutput(log);
Process process = processBuilder.start();
assertEquals("If redirected, should be -1 ", -1, process.getInputStream()
.read());
int exitCode = process.waitFor();
assertEquals("No errors should be detected", 0, exitCode);
List<String> lines = Files.lines(log.toPath())
.collect(Collectors.toList());
assertThat("Results should not be empty", lines, is(not(empty())));
assertThat("Results should contain java version: ", lines, hasItem(containsString("java version")));
}
@Test
public void givenProcessBuilder_whenRedirectStandardOutput_thenSuccessAppending() throws IOException, InterruptedException {
ProcessBuilder processBuilder = new ProcessBuilder("java", "-version");
File log = tempFolder.newFile("java-version-append.log");
processBuilder.redirectErrorStream(true);
processBuilder.redirectOutput(Redirect.appendTo(log));
Process process = processBuilder.start();
assertEquals("If redirected output, should be -1 ", -1, process.getInputStream()
.read());
int exitCode = process.waitFor();
assertEquals("No errors should be detected", 0, exitCode);
List<String> lines = Files.lines(log.toPath())
.collect(Collectors.toList());
assertThat("Results should not be empty", lines, is(not(empty())));
assertThat("Results should contain java version: ", lines, hasItem(containsString("java version")));
}
@Test
public void givenProcessBuilder_whenStartingPipeline_thenSuccess() throws IOException, InterruptedException {
if (!isWindows()) {
List<ProcessBuilder> builders = Arrays.asList(
new ProcessBuilder("find", "src", "-name", "*.java", "-type", "f"),
new ProcessBuilder("wc", "-l"));
List<Process> processes = ProcessBuilder.startPipeline(builders);
Process last = processes.get(processes.size() - 1);
List<String> output = readOutput(last.getInputStream());
assertThat("Results should not be empty", output, is(not(empty())));
}
}
@Test
public void givenProcessBuilder_whenInheritIO_thenSuccess() throws IOException, InterruptedException {
List<String> command = getEchoCommand();
ProcessBuilder processBuilder = new ProcessBuilder(command);
processBuilder.inheritIO();
Process process = processBuilder.start();
int exitCode = process.waitFor();
assertEquals("No errors should be detected", 0, exitCode);
}
private List<String> readOutput(InputStream inputStream) throws IOException {
try (BufferedReader output = new BufferedReader(new InputStreamReader(inputStream))) {
return output.lines()
.collect(Collectors.toList());
}
}
private List<String> getDirectoryListingCommand() {
return isWindows() ? Arrays.asList("cmd.exe", "/c", "dir") : Arrays.asList("/bin/sh", "-c", "ls");
}
private List<String> getGreetingCommand() {
return isWindows() ? Arrays.asList("cmd.exe", "/c", "echo %GREETING%") : Arrays.asList("/bin/bash", "-c", "echo $GREETING");
}
private List<String> getEchoCommand() {
return isWindows() ? Arrays.asList("cmd.exe", "/c", "echo hello") : Arrays.asList("/bin/sh", "-c", "echo hello");
}
private boolean isWindows() {
return System.getProperty("os.name")
.toLowerCase()
.startsWith("windows");
}
}
@@ -0,0 +1,61 @@
package com.baeldung.java.shell;
import org.junit.Assert;
import org.junit.Test;
import java.io.*;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
public class JavaProcessUnitIntegrationTest {
private static final boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().startsWith("windows");
private static class StreamGobbler implements Runnable {
private InputStream inputStream;
private Consumer<String> consumer;
public StreamGobbler(InputStream inputStream, Consumer<String> consumer) {
this.inputStream = inputStream;
this.consumer = consumer;
}
@Override
public void run() {
new BufferedReader(new InputStreamReader(inputStream)).lines().forEach(consumer);
}
}
private Consumer<String> consumer = Assert::assertNotNull;
private String homeDirectory = System.getProperty("user.home");
@Test
public void givenProcess_whenCreatingViaRuntime_shouldSucceed() throws Exception {
Process process;
if (IS_WINDOWS) {
process = Runtime.getRuntime().exec(String.format("cmd.exe /c dir %s", homeDirectory));
} else {
process = Runtime.getRuntime().exec(String.format("sh -c ls %s", homeDirectory));
}
StreamGobbler streamGobbler = new StreamGobbler(process.getInputStream(), consumer);
Executors.newSingleThreadExecutor().submit(streamGobbler);
int exitCode = process.waitFor();
Assert.assertEquals(0, exitCode);
}
@Test
public void givenProcess_whenCreatingViaProcessBuilder_shouldSucceed() throws Exception {
ProcessBuilder builder = new ProcessBuilder();
if (IS_WINDOWS) {
builder.command("cmd.exe", "/c", "dir");
} else {
builder.command("sh", "-c", "ls");
}
builder.directory(new File(homeDirectory));
Process process = builder.start();
StreamGobbler streamGobbler = new StreamGobbler(process.getInputStream(), consumer);
Executors.newSingleThreadExecutor().submit(streamGobbler);
int exitCode = process.waitFor();
Assert.assertEquals(0, exitCode);
}
}
@@ -0,0 +1,25 @@
package com.baeldung.system;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
@Ignore
public class WhenDetectingOSUnitTest {
private DetectOS os = new DetectOS();
@Test
public void whenUsingSystemProperty_shouldReturnOS() {
String expected = "Windows 10";
String actual = os.getOperatingSystem();
Assert.assertEquals(expected, actual);
}
@Test
public void whenUsingSystemUtils_shouldReturnOS() {
String expected = "Windows 10";
String actual = os.getOperatingSystemSystemUtils();
Assert.assertEquals(expected, actual);
}
}
@@ -0,0 +1,63 @@
package com.baeldung.system.exit;
import static org.junit.Assert.assertEquals;
import java.security.Permission;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class SystemExitUnitTest {
protected static class ExitException extends SecurityException {
private static final long serialVersionUID = 1L;
public final int status;
public ExitException(int status) {
this.status = status;
}
}
private static class NoExitSecurityManager extends SecurityManager {
@Override
public void checkPermission(Permission perm) {
}
@Override
public void checkPermission(Permission perm, Object context) {
}
@Override
public void checkExit(int status) {
super.checkExit(status);
throw new ExitException(status);
}
}
private SecurityManager securityManager;
private SystemExitExample example;
@Before
public void setUp() throws Exception {
example = new SystemExitExample();
securityManager = System.getSecurityManager();
System.setSecurityManager(new NoExitSecurityManager());
}
@After
public void tearDown() throws Exception {
System.setSecurityManager(securityManager);
}
@Test
public void testExit() throws Exception {
try {
example.readFile();
} catch (ExitException e) {
assertEquals("Exit status", 2, e.status);
}
}
}
@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear