Skip to content

Commit

Permalink
ExpectedSystemExit restores SecurityManager.
Browse files Browse the repository at this point in the history
After each test the original SecurityManager is restored.

Signed-off-by: Stefan Birkner <mail@stefan-birkner.de>
  • Loading branch information
stefanbirkner committed Nov 29, 2011
1 parent c1e127b commit a96b501
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 7 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package org.junit.contrib.java.lang.system;

import static java.lang.System.setSecurityManager;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

Expand Down Expand Up @@ -61,21 +60,21 @@ public void expectSystemExit() {
expectExit = true;
}

public Statement apply(final Statement base, final Description description) {
return new Statement() {
public Statement apply(final Statement base, Description description) {
ProvideSecurityManager provideNoExitSecurityManager = new ProvideSecurityManager(
new NoExitSecurityManager());
Statement statement = new Statement() {
@Override
public void evaluate() throws Throwable {
setSecurityManager(new NoExitSecurityManager());
try {
base.evaluate();
handleMissingSystemExit();
} catch (TryToExitException e) {
handleSystemExit(e);
} finally {
setSecurityManager(null);
}
}
};
return provideNoExitSecurityManager.apply(statement, description);
}

private void handleMissingSystemExit() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package org.junit.contrib.java.lang.system;

import static java.lang.System.getSecurityManager;
import static java.lang.System.setSecurityManager;
import static org.hamcrest.core.IsSame.sameInstance;
import static org.junit.Assert.assertThat;
import static org.junit.rules.ExpectedException.none;

import java.security.Permission;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
Expand Down Expand Up @@ -56,7 +59,8 @@ public void failForWrongStatus() throws Throwable {

@Test
public void restoreOldSecurityManager() throws Throwable {
SecurityManager manager = getSecurityManager();
SecurityManager manager = new ArbitrarySecurityManager();
setSecurityManager(manager);
executeRuleWithoutExitCall();
assertThat(getSecurityManager(), sameInstance(manager));
}
Expand All @@ -79,4 +83,11 @@ public void evaluate() throws Throwable {
System.exit(0);
}
}

private static class ArbitrarySecurityManager extends SecurityManager {
@Override
public void checkPermission(Permission perm) {
// allow anything.
}
}
}

0 comments on commit a96b501

Please sign in to comment.