|
| 1 | +package org.junit.tests.running.core; |
| 2 | + |
| 3 | +import java.io.ByteArrayOutputStream; |
| 4 | +import java.io.PrintStream; |
| 5 | +import java.security.Permission; |
| 6 | + |
| 7 | +public class MainRunner { |
| 8 | + |
| 9 | + private static class ExitException extends SecurityException { |
| 10 | + private static final long serialVersionUID= -9104651568237766642L; |
| 11 | + |
| 12 | + private final int status; |
| 13 | + |
| 14 | + public ExitException(int status) { |
| 15 | + super(""); |
| 16 | + this.status= status; |
| 17 | + } |
| 18 | + |
| 19 | + public int getStatus() { |
| 20 | + return status; |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + private static class NoExitSecurityManager extends SecurityManager { |
| 25 | + @Override |
| 26 | + public void checkPermission(Permission perm) { |
| 27 | + // allow anything. |
| 28 | + } |
| 29 | + |
| 30 | + @Override |
| 31 | + public void checkPermission(Permission perm, Object context) { |
| 32 | + // allow anything. |
| 33 | + } |
| 34 | + |
| 35 | + @Override |
| 36 | + public void checkExit(int status) { |
| 37 | + super.checkExit(status); |
| 38 | + throw new ExitException(status); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * Execute runnable.run(), preventing System.exit(). If System.exit() is called |
| 44 | + * in runnable.run(), the value is returned. If System.exit() |
| 45 | + * is not called, null is returned. |
| 46 | + * |
| 47 | + * @param runnable |
| 48 | + * @return null if System.exit() is not called, Integer.valueof(status) if not |
| 49 | + */ |
| 50 | + public Integer runWithCheckForSystemExit(Runnable runnable) { |
| 51 | + SecurityManager oldSecurityManager = System.getSecurityManager(); |
| 52 | + System.setSecurityManager(new NoExitSecurityManager()); |
| 53 | + PrintStream oldPrintStream = System.out; |
| 54 | + |
| 55 | + System.setOut(new PrintStream(new ByteArrayOutputStream())); |
| 56 | + try { |
| 57 | + runnable.run(); |
| 58 | + System.out.println("System.exit() not called, return null"); |
| 59 | + return null; |
| 60 | + } catch (ExitException e) { |
| 61 | + System.out.println("System.exit() called, value=" + e.getStatus()); |
| 62 | + return e.getStatus(); |
| 63 | + } finally { |
| 64 | + System.setSecurityManager(oldSecurityManager); |
| 65 | + System.setOut(oldPrintStream); |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | +} |
0 commit comments