├── .editorconfig
├── .gitignore
├── .mvn
└── wrapper
│ ├── maven-wrapper.jar
│ └── maven-wrapper.properties
├── .travis.yml
├── LICENSE
├── README.md
├── appveyor.yml
├── findbugs-exclude.xml
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
├── main
└── java
│ └── org
│ └── junit
│ └── contrib
│ └── java
│ └── lang
│ └── system
│ ├── Assertion.java
│ ├── ClearSystemProperties.java
│ ├── DisallowWriteToSystemErr.java
│ ├── DisallowWriteToSystemOut.java
│ ├── EnvironmentVariables.java
│ ├── ExpectedSystemExit.java
│ ├── LogMode.java
│ ├── ProvideSecurityManager.java
│ ├── ProvideSystemProperty.java
│ ├── RestoreSystemProperties.java
│ ├── StandardErrorStreamLog.java
│ ├── StandardOutputStreamLog.java
│ ├── SystemErrRule.java
│ ├── SystemOutRule.java
│ ├── TextFromStandardInputStream.java
│ └── internal
│ ├── CheckExitCalled.java
│ ├── DisallowWrite.java
│ ├── LogPrintStream.java
│ ├── NoExitSecurityManager.java
│ ├── PrintStreamHandler.java
│ └── RestoreSpecificSystemProperties.java
└── test
├── java
└── org
│ └── junit
│ └── contrib
│ └── java
│ └── lang
│ └── system
│ ├── AcceptanceTestRunner.java
│ ├── ClearSystemPropertiesTest.java
│ ├── DisallowWriteToSystemErrTest.java
│ ├── DisallowWriteToSystemOutTest.java
│ ├── EnvironmentVariablesTest.java
│ ├── ExpectedSystemExitTest.java
│ ├── ProvideSecurityManagerTest.java
│ ├── ProvideSystemPropertyTest.java
│ ├── RestoreSystemPropertiesTest.java
│ ├── StandardErrorStreamLogTest.java
│ ├── StandardOutputStreamLogTest.java
│ ├── SystemErrRuleTest.java
│ ├── SystemOutRuleTest.java
│ ├── TextFromStandardInputStreamTest.java
│ ├── example
│ ├── AppWithExit.java
│ ├── AppWithExitTest.java
│ ├── Summarize.java
│ └── SummarizeTest.java
│ └── internal
│ └── NoExitSecurityManagerTest.java
└── resources
└── org
└── junit
└── contrib
└── java
└── lang
└── system
└── example.properties
/.editorconfig:
--------------------------------------------------------------------------------
1 | # Configuration file for EditorConfig: http://editorconfig.org
2 | root = true
3 |
4 | [*]
5 | charset = utf-8
6 | end_of_line = lf
7 | indent_style = tab
8 | insert_final_newline = true
9 | tab_width = 4
10 | trim_trailing_whitespace = true
11 |
12 | [travis.yml]
13 | indent_size = 2
14 | indent_style = space
15 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .flattened-pom.xml
2 | target
3 |
--------------------------------------------------------------------------------
/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stefanbirkner/system-rules/27f3eee0355f1ba753c035561211c96308a6a500/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.1.1/apache-maven-3.1.1-bin.zip
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | # openjdk-6-jdk is not available in more recent Ubuntu versions
2 | dist: trusty
3 | language: java
4 | install:
5 | # Download dependencies with JDK 8 because Maven Central supports
6 | # TLS 1.2 only but OpenJDK 6 does not.
7 | - export ORIGINAL_JAVA_HOME=$JAVA_HOME
8 | - jdk_switcher use oraclejdk8
9 | - ./mvnw test -DskipTests
10 | # Delete all files created with JDK 8
11 | - ./mvnw clean
12 | # Build with JDK 6 because we build the artifacts that are published
13 | # to Maven Central with OpenJDK 6, too.
14 | - jdk_switcher use openjdk6
15 | # Run original install command but without GPG signing
16 | - ./mvnw install -DskipTests=true -Dgpg.skip=true
17 | # Restore desired JDK
18 | - export JAVA_HOME=$ORIGINAL_JAVA_HOME
19 | addons:
20 | apt:
21 | packages:
22 | - openjdk-6-jdk
23 | jdk:
24 | - openjdk10
25 | - oraclejdk9
26 | - oraclejdk8
27 | - openjdk7
28 |
29 | # The jdk key does not work for openjdk6 in Travis CI any more, so
30 | # we manually install openjdk-6-jdk and set JAVA_HOME appropriately
31 | # (https://github.com/travis-ci/travis-ci/issues/9713)
32 | matrix:
33 | include:
34 | - env: JAVA_HOME=/usr/lib/jvm/java-6-openjdk-amd64
35 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Common Public License Version 1.0
2 |
3 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS COMMON PUBLIC
4 | LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM
5 | CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
6 |
7 | 1. DEFINITIONS
8 |
9 | "Contribution" means:
10 |
11 | a) in the case of the initial Contributor, the initial code and
12 | documentation distributed under this Agreement, and
13 |
14 | b) in the case of each subsequent Contributor:
15 |
16 | i) changes to the Program, and
17 |
18 | ii) additions to the Program;
19 |
20 | where such changes and/or additions to the Program originate from and are
21 | distributed by that particular Contributor. A Contribution 'originates' from a
22 | Contributor if it was added to the Program by such Contributor itself or anyone
23 | acting on such Contributor's behalf. Contributions do not include additions to
24 | the Program which: (i) are separate modules of software distributed in
25 | conjunction with the Program under their own license agreement, and (ii) are not
26 | derivative works of the Program.
27 |
28 | "Contributor" means any person or entity that distributes the Program.
29 |
30 | "Licensed Patents " mean patent claims licensable by a Contributor which are
31 | necessarily infringed by the use or sale of its Contribution alone or when
32 | combined with the Program.
33 |
34 | "Program" means the Contributions distributed in accordance with this Agreement.
35 |
36 | "Recipient" means anyone who receives the Program under this Agreement,
37 | including all Contributors.
38 |
39 | 2. GRANT OF RIGHTS
40 |
41 | a) Subject to the terms of this Agreement, each Contributor hereby grants
42 | Recipient a non-exclusive, worldwide, royalty-free copyright license to
43 | reproduce, prepare derivative works of, publicly display, publicly perform,
44 | distribute and sublicense the Contribution of such Contributor, if any, and such
45 | derivative works, in source code and object code form.
46 |
47 | b) Subject to the terms of this Agreement, each Contributor hereby grants
48 | Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed
49 | Patents to make, use, sell, offer to sell, import and otherwise transfer the
50 | Contribution of such Contributor, if any, in source code and object code form.
51 | This patent license shall apply to the combination of the Contribution and the
52 | Program if, at the time the Contribution is added by the Contributor, such
53 | addition of the Contribution causes such combination to be covered by the
54 | Licensed Patents. The patent license shall not apply to any other combinations
55 | which include the Contribution. No hardware per se is licensed hereunder.
56 |
57 | c) Recipient understands that although each Contributor grants the licenses
58 | to its Contributions set forth herein, no assurances are provided by any
59 | Contributor that the Program does not infringe the patent or other intellectual
60 | property rights of any other entity. Each Contributor disclaims any liability to
61 | Recipient for claims brought by any other entity based on infringement of
62 | intellectual property rights or otherwise. As a condition to exercising the
63 | rights and licenses granted hereunder, each Recipient hereby assumes sole
64 | responsibility to secure any other intellectual property rights needed, if any.
65 | For example, if a third party patent license is required to allow Recipient to
66 | distribute the Program, it is Recipient's responsibility to acquire that license
67 | before distributing the Program.
68 |
69 | d) Each Contributor represents that to its knowledge it has sufficient
70 | copyright rights in its Contribution, if any, to grant the copyright license set
71 | forth in this Agreement.
72 |
73 | 3. REQUIREMENTS
74 |
75 | A Contributor may choose to distribute the Program in object code form under its
76 | own license agreement, provided that:
77 |
78 | a) it complies with the terms and conditions of this Agreement; and
79 |
80 | b) its license agreement:
81 |
82 | i) effectively disclaims on behalf of all Contributors all warranties and
83 | conditions, express and implied, including warranties or conditions of title and
84 | non-infringement, and implied warranties or conditions of merchantability and
85 | fitness for a particular purpose;
86 |
87 | ii) effectively excludes on behalf of all Contributors all liability for
88 | damages, including direct, indirect, special, incidental and consequential
89 | damages, such as lost profits;
90 |
91 | iii) states that any provisions which differ from this Agreement are offered
92 | by that Contributor alone and not by any other party; and
93 |
94 | iv) states that source code for the Program is available from such
95 | Contributor, and informs licensees how to obtain it in a reasonable manner on or
96 | through a medium customarily used for software exchange.
97 |
98 | When the Program is made available in source code form:
99 |
100 | a) it must be made available under this Agreement; and
101 |
102 | b) a copy of this Agreement must be included with each copy of the Program.
103 |
104 | Contributors may not remove or alter any copyright notices contained within the
105 | Program.
106 |
107 | Each Contributor must identify itself as the originator of its Contribution, if
108 | any, in a manner that reasonably allows subsequent Recipients to identify the
109 | originator of the Contribution.
110 |
111 | 4. COMMERCIAL DISTRIBUTION
112 |
113 | Commercial distributors of software may accept certain responsibilities with
114 | respect to end users, business partners and the like. While this license is
115 | intended to facilitate the commercial use of the Program, the Contributor who
116 | includes the Program in a commercial product offering should do so in a manner
117 | which does not create potential liability for other Contributors. Therefore, if
118 | a Contributor includes the Program in a commercial product offering, such
119 | Contributor ("Commercial Contributor") hereby agrees to defend and indemnify
120 | every other Contributor ("Indemnified Contributor") against any losses, damages
121 | and costs (collectively "Losses") arising from claims, lawsuits and other legal
122 | actions brought by a third party against the Indemnified Contributor to the
123 | extent caused by the acts or omissions of such Commercial Contributor in
124 | connection with its distribution of the Program in a commercial product
125 | offering. The obligations in this section do not apply to any claims or Losses
126 | relating to any actual or alleged intellectual property infringement. In order
127 | to qualify, an Indemnified Contributor must: a) promptly notify the Commercial
128 | Contributor in writing of such claim, and b) allow the Commercial Contributor to
129 | control, and cooperate with the Commercial Contributor in, the defense and any
130 | related settlement negotiations. The Indemnified Contributor may participate in
131 | any such claim at its own expense.
132 |
133 | For example, a Contributor might include the Program in a commercial product
134 | offering, Product X. That Contributor is then a Commercial Contributor. If that
135 | Commercial Contributor then makes performance claims, or offers warranties
136 | related to Product X, those performance claims and warranties are such
137 | Commercial Contributor's responsibility alone. Under this section, the
138 | Commercial Contributor would have to defend claims against the other
139 | Contributors related to those performance claims and warranties, and if a court
140 | requires any other Contributor to pay any damages as a result, the Commercial
141 | Contributor must pay those damages.
142 |
143 | 5. NO WARRANTY
144 |
145 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN
146 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR
147 | IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE,
148 | NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each
149 | Recipient is solely responsible for determining the appropriateness of using and
150 | distributing the Program and assumes all risks associated with its exercise of
151 | rights under this Agreement, including but not limited to the risks and costs of
152 | program errors, compliance with applicable laws, damage to or loss of data,
153 | programs or equipment, and unavailability or interruption of operations.
154 |
155 | 6. DISCLAIMER OF LIABILITY
156 |
157 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY
158 | CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL,
159 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST
160 | PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
161 | STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
162 | OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS
163 | GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
164 |
165 | 7. GENERAL
166 |
167 | If any provision of this Agreement is invalid or unenforceable under applicable
168 | law, it shall not affect the validity or enforceability of the remainder of the
169 | terms of this Agreement, and without further action by the parties hereto, such
170 | provision shall be reformed to the minimum extent necessary to make such
171 | provision valid and enforceable.
172 |
173 | If Recipient institutes patent litigation against a Contributor with respect to
174 | a patent applicable to software (including a cross-claim or counterclaim in a
175 | lawsuit), then any patent licenses granted by that Contributor to such Recipient
176 | under this Agreement shall terminate as of the date such litigation is filed. In
177 | addition, if Recipient institutes patent litigation against any entity
178 | (including a cross-claim or counterclaim in a lawsuit) alleging that the Program
179 | itself (excluding combinations of the Program with other software or hardware)
180 | infringes such Recipient's patent(s), then such Recipient's rights granted under
181 | Section 2(b) shall terminate as of the date such litigation is filed.
182 |
183 | All Recipient's rights under this Agreement shall terminate if it fails to
184 | comply with any of the material terms or conditions of this Agreement and does
185 | not cure such failure in a reasonable period of time after becoming aware of
186 | such noncompliance. If all Recipient's rights under this Agreement terminate,
187 | Recipient agrees to cease use and distribution of the Program as soon as
188 | reasonably practicable. However, Recipient's obligations under this Agreement
189 | and any licenses granted by Recipient relating to the Program shall continue and
190 | survive.
191 |
192 | Everyone is permitted to copy and distribute copies of this Agreement, but in
193 | order to avoid inconsistency the Agreement is copyrighted and may only be
194 | modified in the following manner. The Agreement Steward reserves the right to
195 | publish new versions (including revisions) of this Agreement from time to time.
196 | No one other than the Agreement Steward has the right to modify this Agreement.
197 | IBM is the initial Agreement Steward. IBM may assign the responsibility to serve
198 | as the Agreement Steward to a suitable separate entity. Each new version of the
199 | Agreement will be given a distinguishing version number. The Program (including
200 | Contributions) may always be distributed subject to the version of the Agreement
201 | under which it was received. In addition, after a new version of the Agreement
202 | is published, Contributor may elect to distribute the Program (including its
203 | Contributions) under the new version. Except as expressly stated in Sections
204 | 2(a) and 2(b) above, Recipient receives no rights or licenses to the
205 | intellectual property of any Contributor under this Agreement, whether
206 | expressly, by implication, estoppel or otherwise. All rights in the Program not
207 | expressly granted under this Agreement are reserved.
208 |
209 | This Agreement is governed by the laws of the State of New York and the
210 | intellectual property laws of the United States of America. No party to this
211 | Agreement will bring a legal action under this Agreement more than one year
212 | after the cause of action arose. Each party waives its rights to a jury trial in
213 | any resulting litigation.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # System Rules
2 |
3 | [](https://travis-ci.org/stefanbirkner/system-rules) [](https://ci.appveyor.com/project/stefanbirkner/system-rules)
4 |
5 | System Rules is a collection of JUnit rules for testing code which uses
6 | `java.lang.System`.
7 |
8 | [System Lambda](https://github.com/stefanbirkner/system-lambda) is an
9 | alternative to System Rules that leverages the possibilities of Java 8. It is
10 | independent of the test framework. You can use it for example as a replacement
11 | for System Rules in [JUnit Jupiter](https://junit.org/junit5/) and
12 | [TestNG](https://testng.org/doc/index.html).
13 |
14 |
15 | ## Installation
16 |
17 | System Rules is available from
18 | [Maven Central](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.github.stefanbirkner%22%20AND%20a%3A%22system-rules%22).
19 |
20 |
21 | com.github.stefanbirkner
22 | system-rules
23 | 1.19.0
24 |
25 |
26 | Please don't forget to add the scope `test` if you're using System
27 | Rules for tests only.
28 |
29 |
30 | ## Usage
31 |
32 | System Rules' documentation is stored in the `gh-pages` branch and is
33 | available online at
34 | http://stefanbirkner.github.io/system-rules/index.html
35 |
36 |
37 | ## Contributing
38 |
39 | You have three options if you have a feature request, found a bug or
40 | simply have a question about System Rules.
41 |
42 | * [Write an issue.](https://github.com/stefanbirkner/system-rules/issues/new)
43 | * Create a pull request. (See [Understanding the GitHub Flow](https://guides.github.com/introduction/flow/index.html))
44 | * [Write a mail to mail@stefan-birkner.de](mailto:mail@stefan-birkner.de)
45 |
46 |
47 | ## Development Guide
48 |
49 | System Rules is build with [Maven](http://maven.apache.org/). If you
50 | want to contribute code than
51 |
52 | * Please write a test for your change.
53 | * Ensure that you didn't break the build by running `mvnw test`.
54 | * Fork the repo and create a pull request. (See [Understanding the GitHub Flow](https://guides.github.com/introduction/flow/index.html))
55 |
56 | The basic coding style is described in the
57 | [EditorConfig](http://editorconfig.org/) file `.editorconfig`.
58 |
59 | System Rules supports [Travis CI](https://travis-ci.org/) (Linux) and
60 | [AppVeyor](http://www.appveyor.com/) (Windows) for continuous
61 | integration. Your pull request will be automatically build by both CI
62 | servers. On Travis CI we build your pull request with OpenJDK 6 and run test
63 | with different JDKs (Java 6 to 10).
64 |
65 |
66 | ## Release Guide
67 |
68 | * Select a new version according to the
69 | [Semantic Versioning 2.0.0 Standard](http://semver.org/).
70 | * Set the new version in `pom.xml` and in the `Installation` section of
71 | this readme.
72 | * Commit the modified `pom.xml` and `README.md`.
73 | * Run `mvnw clean deploy` with JDK 6 or 7.
74 | * Add a tag for the release: `git tag system-rules-X.X.X`
75 |
--------------------------------------------------------------------------------
/appveyor.yml:
--------------------------------------------------------------------------------
1 | version: '{build}'
2 | image: Visual Studio 2017
3 | # Download dependencies with Maven 3.6.x because Maven 3.1.1 (which is used by
4 | # mvnw) does not use HTTPS but Maven Central requires HTTPS.
5 | install:
6 | - mvn clean verify -Dgpg.skip -Dmaven.test.failure.ignore
7 | build_script:
8 | - mvnw clean package -DskipTest -Dgpg.skip
9 | test_script:
10 | - mvnw clean verify -Dgpg.skip
11 | cache:
12 | - C:\Users\appveyor\.m2
13 |
--------------------------------------------------------------------------------
/findbugs-exclude.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/mvnw:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | # ----------------------------------------------------------------------------
3 | # Licensed to the Apache Software Foundation (ASF) under one
4 | # or more contributor license agreements. See the NOTICE file
5 | # distributed with this work for additional information
6 | # regarding copyright ownership. The ASF licenses this file
7 | # to you under the Apache License, Version 2.0 (the
8 | # "License"); you may not use this file except in compliance
9 | # with the License. You may obtain a copy of the License at
10 | #
11 | # http://www.apache.org/licenses/LICENSE-2.0
12 | #
13 | # Unless required by applicable law or agreed to in writing,
14 | # software distributed under the License is distributed on an
15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 | # KIND, either express or implied. See the License for the
17 | # specific language governing permissions and limitations
18 | # under the License.
19 | # ----------------------------------------------------------------------------
20 |
21 | # ----------------------------------------------------------------------------
22 | # Maven2 Start Up Batch script
23 | #
24 | # Required ENV vars:
25 | # ------------------
26 | # JAVA_HOME - location of a JDK home dir
27 | #
28 | # Optional ENV vars
29 | # -----------------
30 | # M2_HOME - location of maven2's installed home dir
31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven
32 | # e.g. to debug Maven itself, use
33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files
35 | # ----------------------------------------------------------------------------
36 |
37 | if [ -z "$MAVEN_SKIP_RC" ] ; then
38 |
39 | if [ -f /etc/mavenrc ] ; then
40 | . /etc/mavenrc
41 | fi
42 |
43 | if [ -f "$HOME/.mavenrc" ] ; then
44 | . "$HOME/.mavenrc"
45 | fi
46 |
47 | fi
48 |
49 | # OS specific support. $var _must_ be set to either true or false.
50 | cygwin=false;
51 | darwin=false;
52 | mingw=false
53 | case "`uname`" in
54 | CYGWIN*) cygwin=true ;;
55 | MINGW*) mingw=true;;
56 | Darwin*) darwin=true
57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
59 | if [ -z "$JAVA_HOME" ]; then
60 | if [ -x "/usr/libexec/java_home" ]; then
61 | export JAVA_HOME="`/usr/libexec/java_home`"
62 | else
63 | export JAVA_HOME="/Library/Java/Home"
64 | fi
65 | fi
66 | ;;
67 | esac
68 |
69 | if [ -z "$JAVA_HOME" ] ; then
70 | if [ -r /etc/gentoo-release ] ; then
71 | JAVA_HOME=`java-config --jre-home`
72 | fi
73 | fi
74 |
75 | if [ -z "$M2_HOME" ] ; then
76 | ## resolve links - $0 may be a link to maven's home
77 | PRG="$0"
78 |
79 | # need this for relative symlinks
80 | while [ -h "$PRG" ] ; do
81 | ls=`ls -ld "$PRG"`
82 | link=`expr "$ls" : '.*-> \(.*\)$'`
83 | if expr "$link" : '/.*' > /dev/null; then
84 | PRG="$link"
85 | else
86 | PRG="`dirname "$PRG"`/$link"
87 | fi
88 | done
89 |
90 | saveddir=`pwd`
91 |
92 | M2_HOME=`dirname "$PRG"`/..
93 |
94 | # make it fully qualified
95 | M2_HOME=`cd "$M2_HOME" && pwd`
96 |
97 | cd "$saveddir"
98 | # echo Using m2 at $M2_HOME
99 | fi
100 |
101 | # For Cygwin, ensure paths are in UNIX format before anything is touched
102 | if $cygwin ; then
103 | [ -n "$M2_HOME" ] &&
104 | M2_HOME=`cygpath --unix "$M2_HOME"`
105 | [ -n "$JAVA_HOME" ] &&
106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
107 | [ -n "$CLASSPATH" ] &&
108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
109 | fi
110 |
111 | # For Mingw, ensure paths are in UNIX format before anything is touched
112 | if $mingw ; then
113 | [ -n "$M2_HOME" ] &&
114 | M2_HOME="`(cd "$M2_HOME"; pwd)`"
115 | [ -n "$JAVA_HOME" ] &&
116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
117 | # TODO classpath?
118 | fi
119 |
120 | if [ -z "$JAVA_HOME" ]; then
121 | javaExecutable="`which javac`"
122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
123 | # readlink(1) is not available as standard on Solaris 10.
124 | readLink=`which readlink`
125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
126 | if $darwin ; then
127 | javaHome="`dirname \"$javaExecutable\"`"
128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
129 | else
130 | javaExecutable="`readlink -f \"$javaExecutable\"`"
131 | fi
132 | javaHome="`dirname \"$javaExecutable\"`"
133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'`
134 | JAVA_HOME="$javaHome"
135 | export JAVA_HOME
136 | fi
137 | fi
138 | fi
139 |
140 | if [ -z "$JAVACMD" ] ; then
141 | if [ -n "$JAVA_HOME" ] ; then
142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
143 | # IBM's JDK on AIX uses strange locations for the executables
144 | JAVACMD="$JAVA_HOME/jre/sh/java"
145 | else
146 | JAVACMD="$JAVA_HOME/bin/java"
147 | fi
148 | else
149 | JAVACMD="`which java`"
150 | fi
151 | fi
152 |
153 | if [ ! -x "$JAVACMD" ] ; then
154 | echo "Error: JAVA_HOME is not defined correctly." >&2
155 | echo " We cannot execute $JAVACMD" >&2
156 | exit 1
157 | fi
158 |
159 | if [ -z "$JAVA_HOME" ] ; then
160 | echo "Warning: JAVA_HOME environment variable is not set."
161 | fi
162 |
163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
164 |
165 | # traverses directory structure from process work directory to filesystem root
166 | # first directory with .mvn subdirectory is considered project base directory
167 | find_maven_basedir() {
168 |
169 | if [ -z "$1" ]
170 | then
171 | echo "Path not specified to find_maven_basedir"
172 | return 1
173 | fi
174 |
175 | basedir="$1"
176 | wdir="$1"
177 | while [ "$wdir" != '/' ] ; do
178 | if [ -d "$wdir"/.mvn ] ; then
179 | basedir=$wdir
180 | break
181 | fi
182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc)
183 | if [ -d "${wdir}" ]; then
184 | wdir=`cd "$wdir/.."; pwd`
185 | fi
186 | # end of workaround
187 | done
188 | echo "${basedir}"
189 | }
190 |
191 | # concatenates all lines of a file
192 | concat_lines() {
193 | if [ -f "$1" ]; then
194 | echo "$(tr -s '\n' ' ' < "$1")"
195 | fi
196 | }
197 |
198 | BASE_DIR=`find_maven_basedir "$(pwd)"`
199 | if [ -z "$BASE_DIR" ]; then
200 | exit 1;
201 | fi
202 |
203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
204 | if [ "$MVNW_VERBOSE" = true ]; then
205 | echo $MAVEN_PROJECTBASEDIR
206 | fi
207 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
208 |
209 | # For Cygwin, switch paths to Windows format before running java
210 | if $cygwin; then
211 | [ -n "$M2_HOME" ] &&
212 | M2_HOME=`cygpath --path --windows "$M2_HOME"`
213 | [ -n "$JAVA_HOME" ] &&
214 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
215 | [ -n "$CLASSPATH" ] &&
216 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
217 | [ -n "$MAVEN_PROJECTBASEDIR" ] &&
218 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
219 | fi
220 |
221 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
222 |
223 | exec "$JAVACMD" \
224 | $MAVEN_OPTS \
225 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
226 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
227 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
228 |
--------------------------------------------------------------------------------
/mvnw.cmd:
--------------------------------------------------------------------------------
1 | @REM ----------------------------------------------------------------------------
2 | @REM Licensed to the Apache Software Foundation (ASF) under one
3 | @REM or more contributor license agreements. See the NOTICE file
4 | @REM distributed with this work for additional information
5 | @REM regarding copyright ownership. The ASF licenses this file
6 | @REM to you under the Apache License, Version 2.0 (the
7 | @REM "License"); you may not use this file except in compliance
8 | @REM with the License. You may obtain a copy of the License at
9 | @REM
10 | @REM http://www.apache.org/licenses/LICENSE-2.0
11 | @REM
12 | @REM Unless required by applicable law or agreed to in writing,
13 | @REM software distributed under the License is distributed on an
14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | @REM KIND, either express or implied. See the License for the
16 | @REM specific language governing permissions and limitations
17 | @REM under the License.
18 | @REM ----------------------------------------------------------------------------
19 |
20 | @REM ----------------------------------------------------------------------------
21 | @REM Maven2 Start Up Batch script
22 | @REM
23 | @REM Required ENV vars:
24 | @REM JAVA_HOME - location of a JDK home dir
25 | @REM
26 | @REM Optional ENV vars
27 | @REM M2_HOME - location of maven2's installed home dir
28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
31 | @REM e.g. to debug Maven itself, use
32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
34 | @REM ----------------------------------------------------------------------------
35 |
36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
37 | @echo off
38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
40 |
41 | @REM set %HOME% to equivalent of $HOME
42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
43 |
44 | @REM Execute a user defined script before this one
45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending
47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
49 | :skipRcPre
50 |
51 | @setlocal
52 |
53 | set ERROR_CODE=0
54 |
55 | @REM To isolate internal variables from possible post scripts, we use another setlocal
56 | @setlocal
57 |
58 | @REM ==== START VALIDATION ====
59 | if not "%JAVA_HOME%" == "" goto OkJHome
60 |
61 | echo.
62 | echo Error: JAVA_HOME not found in your environment. >&2
63 | echo Please set the JAVA_HOME variable in your environment to match the >&2
64 | echo location of your Java installation. >&2
65 | echo.
66 | goto error
67 |
68 | :OkJHome
69 | if exist "%JAVA_HOME%\bin\java.exe" goto init
70 |
71 | echo.
72 | echo Error: JAVA_HOME is set to an invalid directory. >&2
73 | echo JAVA_HOME = "%JAVA_HOME%" >&2
74 | echo Please set the JAVA_HOME variable in your environment to match the >&2
75 | echo location of your Java installation. >&2
76 | echo.
77 | goto error
78 |
79 | @REM ==== END VALIDATION ====
80 |
81 | :init
82 |
83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
84 | @REM Fallback to current working directory if not found.
85 |
86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
88 |
89 | set EXEC_DIR=%CD%
90 | set WDIR=%EXEC_DIR%
91 | :findBaseDir
92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound
93 | cd ..
94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound
95 | set WDIR=%CD%
96 | goto findBaseDir
97 |
98 | :baseDirFound
99 | set MAVEN_PROJECTBASEDIR=%WDIR%
100 | cd "%EXEC_DIR%"
101 | goto endDetectBaseDir
102 |
103 | :baseDirNotFound
104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
105 | cd "%EXEC_DIR%"
106 |
107 | :endDetectBaseDir
108 |
109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
110 |
111 | @setlocal EnableExtensions EnableDelayedExpansion
112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
114 |
115 | :endReadAdditionalConfig
116 |
117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
118 |
119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
121 |
122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
123 | if ERRORLEVEL 1 goto error
124 | goto end
125 |
126 | :error
127 | set ERROR_CODE=1
128 |
129 | :end
130 | @endlocal & set ERROR_CODE=%ERROR_CODE%
131 |
132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending
134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
136 | :skipRcPost
137 |
138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause
140 |
141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
142 |
143 | exit /B %ERROR_CODE%
144 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 4.0.0
4 |
5 | com.github.stefanbirkner
6 | system-rules
7 | 1.20.0-SNAPSHOT
8 | jar
9 |
10 | System Rules
11 | A collection of JUnit rules for testing code which uses java.lang.System.
12 | http://stefanbirkner.github.io/system-rules/
13 | 2011
14 |
15 |
16 | Common Public License Version 1.0
17 | http://www.opensource.org/licenses/cpl1.0
18 | repo
19 |
20 |
21 |
22 |
23 |
24 | stefanbirkner
25 | Stefan Birkner
26 | mail@stefan-birkner.de
27 | http://www.stefan-birkner.de
28 | +1
29 |
30 |
31 | marcphilipp
32 | Marc Philipp
33 | mail@marcphilipp.de
34 | http://www.marcphilipp.de/
35 | +1
36 |
37 |
38 | Tobias Mühl
39 | +1
40 |
41 |
42 |
43 |
44 | 3.0.4
45 |
46 |
47 |
48 | scm:git:git://github.com/stefanbirkner/system-rules.git
49 | scm:git:git@github.com:stefanbirkner/system-rules.git
50 | https://github.com/stefanbirkner/system-rules/
51 |
52 |
53 |
54 | ossrh
55 | https://oss.sonatype.org/content/repositories/snapshots
56 |
57 |
58 | ossrh
59 | https://oss.sonatype.org/service/local/staging/deploy/maven2/
60 |
61 |
62 |
63 |
64 | findbugs-exclude.xml
65 |
66 |
67 |
68 |
69 | junit
70 | junit-dep
71 | [4.9,)
72 |
73 |
74 |
75 | com.github.stefanbirkner
76 | fishbowl
77 | [1.4.0]
78 | test
79 |
80 |
81 | commons-io
82 | commons-io
83 | [2.4]
84 | test
85 |
86 |
87 | org.assertj
88 | assertj-core
89 | [1.7.1]
90 | test
91 |
92 |
93 | org.mockito
94 | mockito-core
95 | [1.10.19]
96 | test
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 | maven-clean-plugin
105 | 2.6.1
106 |
107 |
108 | maven-compiler-plugin
109 | 3.3
110 |
111 |
112 | maven-dependency-plugin
113 | 2.10
114 |
115 |
116 | maven-deploy-plugin
117 | 2.8.2
118 |
119 |
120 | maven-enforcer-plugin
121 | 1.4
122 |
123 |
124 | maven-gpg-plugin
125 | 1.6
126 |
127 |
128 | maven-install-plugin
129 | 2.5.2
130 |
131 |
132 | maven-jar-plugin
133 | 2.6
134 |
135 |
136 | maven-javadoc-plugin
137 | 2.10.3
138 |
139 |
140 | maven-resources-plugin
141 | 2.7
142 |
143 |
144 | maven-site-plugin
145 | 3.4
146 |
147 |
148 | maven-source-plugin
149 | 2.4
150 |
151 |
152 | maven-surefire-plugin
153 | 2.18.1
154 |
155 |
156 | org.codehaus.mojo
157 | flatten-maven-plugin
158 | 1.0.0-beta-5
159 |
160 |
161 | org.codehaus.mojo
162 | findbugs-maven-plugin
163 | 3.0.5
164 |
165 |
166 | org.sonatype.plugins
167 | nexus-staging-maven-plugin
168 | 1.6.5
169 |
170 |
171 |
172 |
173 |
174 | maven-gpg-plugin
175 |
176 |
177 | sign-artifacts
178 | verify
179 |
180 | sign
181 |
182 |
183 |
184 |
185 |
186 | maven-javadoc-plugin
187 |
188 |
189 | attach-javadocs
190 |
191 | jar
192 |
193 |
194 |
195 |
196 |
197 | maven-source-plugin
198 |
199 |
200 | attach-sources
201 |
202 | jar-no-fork
203 |
204 |
205 |
206 |
207 |
208 | org.codehaus.mojo
209 | flatten-maven-plugin
210 | true
211 |
212 | ossrh
213 |
214 |
215 |
216 | flatten
217 | process-resources
218 |
219 | flatten
220 |
221 |
222 |
223 | flatten.clean
224 | clean
225 |
226 | clean
227 |
228 |
229 |
230 |
231 |
232 | org.sonatype.plugins
233 | nexus-staging-maven-plugin
234 | true
235 |
236 | ossrh
237 | https://oss.sonatype.org/
238 | true
239 |
240 |
241 |
242 | org.codehaus.mojo
243 | animal-sniffer-maven-plugin
244 | 1.14
245 |
246 |
247 | signature-check
248 | test
249 |
250 | check
251 |
252 |
253 |
254 | org.codehaus.mojo.signature
255 | java15
256 | 1.0
257 |
258 |
259 |
260 |
261 |
262 |
263 | maven-surefire-plugin
264 |
265 | always
266 |
267 |
268 |
269 |
270 |
271 |
272 |
273 | java9
274 |
275 | [1.9,)
276 |
277 |
278 |
279 | 1.6
280 | 1.6
281 |
282 |
283 |
284 |
285 |
286 |
287 |
288 | maven-jar-plugin
289 | 3.0.2
290 |
291 |
292 | maven-javadoc-plugin
293 | 3.0.0-M1
294 |
295 |
296 | maven-source-plugin
297 | 3.0.1
298 |
299 |
300 |
301 |
302 |
303 |
304 | findbugs
305 |
306 |
307 | [1.7,)
308 |
309 |
310 |
311 |
312 | org.codehaus.mojo
313 | findbugs-maven-plugin
314 |
315 | Max
316 | Low
317 |
318 |
319 |
320 |
321 | check
322 |
323 |
324 |
325 |
326 |
327 |
328 |
329 |
330 |
331 |
--------------------------------------------------------------------------------
/src/main/java/org/junit/contrib/java/lang/system/Assertion.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 | /**
4 | * An {@code Assertion} encapsulates the code of an assertion into an object.
5 | */
6 | public interface Assertion {
7 | void checkAssertion() throws Exception;
8 | }
9 |
--------------------------------------------------------------------------------
/src/main/java/org/junit/contrib/java/lang/system/ClearSystemProperties.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 | import org.junit.contrib.java.lang.system.internal.RestoreSpecificSystemProperties;
4 | import org.junit.rules.ExternalResource;
5 |
6 | /**
7 | * The {@code ClearSystemProperties} rule clears a set of system
8 | * properties when the test starts and restores their original values
9 | * when the test finishes (whether it passes or fails).
10 | *
Supposing that the system property {@code YourProperty} has the
11 | * value {@code YourValue}. Now run the test
12 | *
13 | * public void YourTest {
14 | * @Rule
15 | * public final TestRule clearSystemProperties
16 | * = new ClearSystemProperties("YourProperty");
17 | *
18 | * @Test
19 | * public void verifyProperty() {
20 | * assertNull(System.getProperty("YourProperty"));
21 | * }
22 | * }
23 | *
24 | * The test succeeds and afterwards the system property
25 | * {@code YourProperty} has the value {@code YourValue} again.
26 | * The {@code ClearSystemProperties} rule accepts a list of
27 | * properties in case you need to clear multiple properties:
28 | *
29 | * @Rule
30 | * public final TestRule clearSystemProperties
31 | * = new ClearSystemProperties("first", "second", "third");
32 | *
33 | * Clear property for a single test
34 | * If you want to clear a property for a single test then you can
35 | * use
36 | * {@link org.junit.contrib.java.lang.system.RestoreSystemProperties}
37 | * along with {@link System#clearProperty(String)}.
38 | *
39 | * @Rule
40 | * public final TestRule restoreSystemProperties
41 | * = new RestoreSystemProperties();
42 | *
43 | * @Test
44 | * public void test() {
45 | * System.clearProperty("YourProperty");
46 | * ...
47 | * }
48 | */
49 | public class ClearSystemProperties extends ExternalResource {
50 | private final RestoreSpecificSystemProperties restoreSystemProperty = new RestoreSpecificSystemProperties();
51 | private final String[] properties;
52 |
53 | /**
54 | * Creates a {@code ClearSystemProperties} rule that clears the specified
55 | * properties and restores their original values when the test finishes
56 | * (whether it passes or fails).
57 | *
58 | * @param properties the properties' names.
59 | */
60 | public ClearSystemProperties(String... properties) {
61 | this.properties = properties;
62 | }
63 |
64 | /**
65 | * Clears the property and restores the value of the property at the point
66 | * of clearing it.
67 | * This method is deprecated. If you're still using it, please replace your current code
68 | *
69 | * @Rule
70 | * public final ClearSystemProperties clearSystemProperties = new ClearSystemProperties();
71 | *
72 | * @Test
73 | * public void test() {
74 | * clearSystemProperties.clearProperty("YourProperty");
75 | * ...
76 | * }
77 | * with this code:
78 | *
79 | * @Rule
80 | * public final TestRule restoreSystemProperties = new RestoreSystemProperties();
81 | *
82 | * @Test
83 | * public void test() {
84 | * System.clearProperty("YourProperty");
85 | * ...
86 | * }
87 | *
88 | * @param property the name of the property.
89 | * @since 1.6.0
90 | * @deprecated Please use {@link org.junit.contrib.java.lang.system.RestoreSystemProperties}
91 | * along with {@link System#clearProperty(String)}.
92 | */
93 | @Deprecated
94 | public void clearProperty(String property) {
95 | restoreSystemProperty.add(property);
96 | System.clearProperty(property);
97 | }
98 |
99 | @Override
100 | protected void before() throws Throwable {
101 | clearProperties();
102 | }
103 |
104 | @Override
105 | protected void after() {
106 | restoreOriginalValue();
107 | }
108 |
109 | private void clearProperties() {
110 | for (String property : properties)
111 | clearProperty(property);
112 | }
113 |
114 | private void restoreOriginalValue() {
115 | restoreSystemProperty.restore();
116 | }
117 | }
118 |
--------------------------------------------------------------------------------
/src/main/java/org/junit/contrib/java/lang/system/DisallowWriteToSystemErr.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 | import org.junit.contrib.java.lang.system.internal.DisallowWrite;
4 | import org.junit.rules.TestRule;
5 | import org.junit.runner.Description;
6 | import org.junit.runners.model.Statement;
7 |
8 | import static org.junit.contrib.java.lang.system.internal.PrintStreamHandler.SYSTEM_ERR;
9 |
10 | /**
11 | * {@code DisallowWriteToSystemErr} lets a test fail if it tries to write
12 | * something to {@code System.err}.
13 | *
14 | * For that purpose you only have to add {@code DisallowWriteToSystemErr}
15 | * rule to your test class
16 | *
17 | * public class TestClass {
18 | * @Rule
19 | * public final DisallowWriteToSystemErr disallowWriteToSystemErr
20 | * = new DisallowWriteToSystemErr();
21 | *
22 | * @Test
23 | * public void this_test_fails() {
24 | * System.err.println("some text");
25 | * }
26 | * }
27 | *
28 | *
29 | * @see DisallowWriteToSystemOut
30 | * @since 1.14.0
31 | */
32 | public class DisallowWriteToSystemErr implements TestRule {
33 | private final DisallowWrite disallowWrite = new DisallowWrite(SYSTEM_ERR);
34 |
35 | public Statement apply(final Statement base, Description description) {
36 | return disallowWrite.createStatement(base);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/org/junit/contrib/java/lang/system/DisallowWriteToSystemOut.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 | import org.junit.contrib.java.lang.system.internal.DisallowWrite;
4 | import org.junit.rules.TestRule;
5 | import org.junit.runner.Description;
6 | import org.junit.runners.model.Statement;
7 |
8 | import static org.junit.contrib.java.lang.system.internal.PrintStreamHandler.SYSTEM_OUT;
9 |
10 | /**
11 | * {@code DisallowWriteToSystemOut} lets a test fail if it tries to write
12 | * something to {@code System.out}.
13 | *
14 | * For that purpose you only have to add {@code DisallowWriteToSystemOut}
15 | * rule to your test class
16 | *
17 | * public class TestClass {
18 | * @Rule
19 | * public final DisallowWriteToSystemOut disallowWriteToSystemOut
20 | * = new DisallowWriteToSystemOut();
21 | *
22 | * @Test
23 | * public void this_test_fails() {
24 | * System.out.println("some text");
25 | * }
26 | * }
27 | *
28 | *
29 | * @see DisallowWriteToSystemErr
30 | * @since 1.14.0
31 | */
32 | public class DisallowWriteToSystemOut implements TestRule {
33 | private final DisallowWrite disallowWrite = new DisallowWrite(SYSTEM_OUT);
34 |
35 | public Statement apply(final Statement base, Description description) {
36 | return disallowWrite.createStatement(base);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/org/junit/contrib/java/lang/system/EnvironmentVariables.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 | import org.junit.rules.TestRule;
4 | import org.junit.runner.Description;
5 | import org.junit.runners.model.Statement;
6 |
7 | import java.lang.reflect.Field;
8 | import java.util.HashMap;
9 | import java.util.Map;
10 |
11 | import static java.lang.Class.forName;
12 | import static java.lang.System.getenv;
13 |
14 | /**
15 | * The {@code EnvironmentVariables} rule allows you to set environment variables
16 | * for your test. All changes to environment variables are reverted after the
17 | * test.
18 | *
19 | * public class EnvironmentVariablesTest {
20 | * @Rule
21 | * public final EnvironmentVariables environmentVariables = new EnvironmentVariables();
22 | *
23 | * @Test
24 | * public void test() {
25 | * environmentVariables.set("name", "value");
26 | * assertEquals("value", System.getenv("name"));
27 | * }
28 | * }
29 | *
30 | * Common variables can be set directly after creating the rule
31 | *
32 | * public class EnvironmentVariablesTest {
33 | * @Rule
34 | * public final EnvironmentVariables environmentVariables = new EnvironmentVariables()
35 | * .set("name", "value");
36 | *
37 | * @Test
38 | * public void test() {
39 | * assertEquals("value", System.getenv("name"));
40 | * }
41 | * }
42 | *
43 | * You can ensure that some environment variables are not set by calling
44 | * {@link #clear(String...)}.
45 | *
Warning: This rule uses reflection for modifying internals of the
46 | * environment variables map. It fails if your {@code SecurityManager} forbids
47 | * such modifications.
48 | */
49 | public class EnvironmentVariables implements TestRule {
50 | private final Map buffer = new HashMap();
51 | private boolean statementIsExecuting = false;
52 |
53 | /**
54 | * Set the value of an environment variable.
55 | *
56 | * @param name the environment variable's name.
57 | * @param value the environment variable's new value. May be {@code null}.
58 | * @return the rule itself.
59 | */
60 | public EnvironmentVariables set(String name, String value) {
61 | if (statementIsExecuting)
62 | writeVariableToEnvMap(name, value);
63 | else
64 | writeVariableToBuffer(name, value);
65 | return this;
66 | }
67 |
68 | /**
69 | * Delete multiple environment variables.
70 | *
71 | * @param names the environment variables' names.
72 | * @return the rule itself.
73 | */
74 | public EnvironmentVariables clear(String... names) {
75 | for (String name: names)
76 | set(name, null);
77 | return this;
78 | }
79 |
80 | private void writeVariableToEnvMap(String name, String value) {
81 | set(getEditableMapOfVariables(), name, value);
82 | set(getTheCaseInsensitiveEnvironment(), name, value);
83 | }
84 |
85 | private void set(Map variables, String name, String value) {
86 | if (variables != null) //theCaseInsensitiveEnvironment may be null
87 | if (value == null)
88 | variables.remove(name);
89 | else
90 | variables.put(name, value);
91 | }
92 |
93 | private void writeVariableToBuffer(String name, String value) {
94 | buffer.put(name, value);
95 | }
96 |
97 | private void copyVariablesFromBufferToEnvMap() {
98 | for (Map.Entry nameAndValue: buffer.entrySet()) {
99 | writeVariableToEnvMap(
100 | nameAndValue.getKey(), nameAndValue.getValue());
101 | }
102 | }
103 |
104 | public Statement apply(Statement base, Description description) {
105 | return new EnvironmentVariablesStatement(base);
106 | }
107 |
108 | private class EnvironmentVariablesStatement extends Statement {
109 | final Statement baseStatement;
110 | Map originalVariables;
111 |
112 | EnvironmentVariablesStatement(Statement baseStatement) {
113 | this.baseStatement = baseStatement;
114 | }
115 |
116 | @Override
117 | public void evaluate() throws Throwable {
118 | saveCurrentState();
119 | EnvironmentVariables.this.statementIsExecuting = true;
120 | try {
121 | copyVariablesFromBufferToEnvMap();
122 | baseStatement.evaluate();
123 | } finally {
124 | EnvironmentVariables.this.statementIsExecuting = false;
125 | restoreOriginalVariables();
126 | }
127 | }
128 |
129 | void saveCurrentState() {
130 | originalVariables = new HashMap(getenv());
131 | }
132 |
133 | void restoreOriginalVariables() {
134 | restoreVariables(getEditableMapOfVariables());
135 | Map theCaseInsensitiveEnvironment
136 | = getTheCaseInsensitiveEnvironment();
137 | if (theCaseInsensitiveEnvironment != null)
138 | restoreVariables(theCaseInsensitiveEnvironment);
139 | }
140 |
141 | void restoreVariables(Map variables) {
142 | variables.clear();
143 | variables.putAll(originalVariables);
144 | }
145 | }
146 |
147 | private static Map getEditableMapOfVariables() {
148 | Class> classOfMap = getenv().getClass();
149 | try {
150 | return getFieldValue(classOfMap, getenv(), "m");
151 | } catch (IllegalAccessException e) {
152 | throw new RuntimeException("System Rules cannot access the field"
153 | + " 'm' of the map System.getenv().", e);
154 | } catch (NoSuchFieldException e) {
155 | throw new RuntimeException("System Rules expects System.getenv() to"
156 | + " have a field 'm' but it has not.", e);
157 | }
158 | }
159 |
160 | /*
161 | * The names of environment variables are case-insensitive in Windows.
162 | * Therefore it stores the variables in a TreeMap named
163 | * theCaseInsensitiveEnvironment.
164 | */
165 | private static Map getTheCaseInsensitiveEnvironment() {
166 | try {
167 | Class> processEnvironment = forName("java.lang.ProcessEnvironment");
168 | return getFieldValue(
169 | processEnvironment, null, "theCaseInsensitiveEnvironment");
170 | } catch (ClassNotFoundException e) {
171 | throw new RuntimeException("System Rules expects the existence of"
172 | + " the class java.lang.ProcessEnvironment but it does not"
173 | + " exist.", e);
174 | } catch (IllegalAccessException e) {
175 | throw new RuntimeException("System Rules cannot access the static"
176 | + " field 'theCaseInsensitiveEnvironment' of the class"
177 | + " java.lang.ProcessEnvironment.", e);
178 | } catch (NoSuchFieldException e) {
179 | //this field is only available for Windows
180 | return null;
181 | }
182 | }
183 |
184 | private static Map getFieldValue(Class> klass,
185 | Object object, String name)
186 | throws NoSuchFieldException, IllegalAccessException {
187 | Field field = klass.getDeclaredField(name);
188 | field.setAccessible(true);
189 | return (Map) field.get(object);
190 | }
191 | }
192 |
--------------------------------------------------------------------------------
/src/main/java/org/junit/contrib/java/lang/system/ExpectedSystemExit.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 | import static java.lang.System.getSecurityManager;
4 | import static org.junit.Assert.assertEquals;
5 | import static org.junit.Assert.fail;
6 |
7 | import java.util.ArrayList;
8 | import java.util.Collection;
9 |
10 | import org.junit.contrib.java.lang.system.internal.CheckExitCalled;
11 | import org.junit.contrib.java.lang.system.internal.NoExitSecurityManager;
12 | import org.junit.rules.TestRule;
13 | import org.junit.runner.Description;
14 | import org.junit.runners.model.Statement;
15 |
16 | /**
17 | * The {@code ExpectedSystemExit} allows in-test specification of expected
18 | * {@code System.exit(...)} calls.
19 | *
20 | *
21 | * If your code calls {@code System.exit(),} then your test stops and doesn't
22 | * finish. The {@code ExpectedSystemExit} rule allows in-test specification of
23 | * expected {@code System.exit()} calls. Furthermore you cannot use JUnit's
24 | * assert methods because of the abnormal termination of your code. As a
25 | * substitute you can provide an {@code Assertion} object to the
26 | * {@code ExpectedSystemExit} rule.
27 | *
28 | *
29 | * Some care must be taken if your system under test creates a new thread and
30 | * this thread calls {@code System.exit()}. In this case you have to ensure that
31 | * the test does not finish before {@code System.exit()} is called.
32 | *
33 | *
34 | * public class AppWithExit {
35 | * public static String message;
36 | *
37 | * public static int doSomethingAndExit() {
38 | * message = "exit ...";
39 | * System.exit(1);
40 | * }
41 | *
42 | * public static int doNothing() {
43 | * }
44 | * }
45 | *
46 | *
47 | *
48 | * public void AppWithExitTest {
49 | * @Rule
50 | * public final ExpectedSystemExit exit = ExpectedSystemExit.none();
51 | *
52 | * @Test
53 | * public void exits() {
54 | * exit.expectSystemExit();
55 | * AppWithExit.doSomethingAndExit();
56 | * }
57 | *
58 | * @Test
59 | * public void exitsWithStatusCode1() {
60 | * exit.expectSystemExitWithStatus(1);
61 | * AppWithExit.doSomethingAndExit();
62 | * }
63 | *
64 | * @Test
65 | * public void writesMessage() {
66 | * exit.checkAssertionAfterwards(new Assertion() {
67 | * public void checkAssertion() {
68 | * assertEquals("exit ...", AppWithExit.message);
69 | * }
70 | * });
71 | * AppWithExit.doSomethingAndExit();
72 | * }
73 | *
74 | * @Test
75 | * public void systemExitWithStatusCode1() {
76 | * exit.expectSystemExitWithStatus(1);
77 | * AppWithExit.doSomethingAndExit();
78 | * }
79 | *
80 | * @Test
81 | * public void noSystemExit() {
82 | * AppWithExit.doNothing();
83 | * //passes
84 | * }
85 | * }
86 | *
87 | */
88 | public class ExpectedSystemExit implements TestRule {
89 | public static ExpectedSystemExit none() {
90 | return new ExpectedSystemExit();
91 | }
92 |
93 | private final Collection assertions = new ArrayList();
94 | private boolean expectExit = false;
95 | private Integer expectedStatus = null;
96 |
97 | private ExpectedSystemExit() {
98 | }
99 |
100 | public void expectSystemExitWithStatus(int status) {
101 | expectSystemExit();
102 | expectedStatus = status;
103 | }
104 |
105 | public void expectSystemExit() {
106 | expectExit = true;
107 | }
108 |
109 | public void checkAssertionAfterwards(Assertion assertion) {
110 | assertions.add(assertion);
111 | }
112 |
113 | public Statement apply(final Statement base, Description description) {
114 | ProvideSecurityManager noExitSecurityManagerRule = createNoExitSecurityManagerRule();
115 | Statement statement = createStatement(base);
116 | return noExitSecurityManagerRule.apply(statement, description);
117 | }
118 |
119 | private ProvideSecurityManager createNoExitSecurityManagerRule() {
120 | NoExitSecurityManager noExitSecurityManager = new NoExitSecurityManager(
121 | getSecurityManager());
122 | return new ProvideSecurityManager(noExitSecurityManager);
123 | }
124 |
125 | private Statement createStatement(final Statement base) {
126 | return new Statement() {
127 | @Override
128 | public void evaluate() throws Throwable {
129 | try {
130 | base.evaluate();
131 | } catch (CheckExitCalled ignored) {
132 | }
133 | checkSystemExit();
134 | checkAssertions();
135 | }
136 | };
137 | }
138 |
139 | private void checkSystemExit() {
140 | NoExitSecurityManager securityManager = (NoExitSecurityManager) getSecurityManager();
141 | if (securityManager.isCheckExitCalled())
142 | handleSystemExitWithStatus(securityManager.getStatusOfFirstCheckExitCall());
143 | else
144 | handleMissingSystemExit();
145 | }
146 |
147 | private void handleMissingSystemExit() {
148 | if (expectExit)
149 | fail("System.exit has not been called.");
150 | }
151 |
152 | private void handleSystemExitWithStatus(int status) {
153 | if (!expectExit)
154 | fail("Unexpected call of System.exit(" + status + ").");
155 | else if (expectedStatus != null)
156 | assertEquals("Wrong exit status", expectedStatus, Integer.valueOf(status));
157 | }
158 |
159 | private void checkAssertions() throws Exception {
160 | for (Assertion assertion : assertions)
161 | assertion.checkAssertion();
162 | }
163 | }
164 |
--------------------------------------------------------------------------------
/src/main/java/org/junit/contrib/java/lang/system/LogMode.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 | /**
4 | * @deprecated This enum is no longer needed, because all rules that are using
5 | * it have been replaced with rules that don't need the enum.
6 | *
7 | * Mode of the
8 | * {@link org.junit.contrib.java.lang.system.StandardErrorStreamLog} and the
9 | * {@link org.junit.contrib.java.lang.system.StandardOutputStreamLog}.
10 | */
11 | @Deprecated
12 | public enum LogMode {
13 | /**
14 | * @deprecated Please use
15 | * {@link SystemErrRule#enableLog()}.{@link SystemErrRule#mute() mute()} or
16 | * {@link SystemOutRule#enableLog()}.{@link SystemOutRule#mute() mute()}.
17 | *
18 | *
Capture the writes to the stream. Nothing is written to the stream
19 | * itself.
20 | */
21 | LOG_ONLY,
22 |
23 | /**
24 | * @deprecated Please use {@link SystemErrRule#enableLog()} or
25 | * {@link SystemOutRule#enableLog()}.
26 | *
27 | *
Record the writes while they are still written to the stream.
28 | */
29 | LOG_AND_WRITE_TO_STREAM
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/org/junit/contrib/java/lang/system/ProvideSecurityManager.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 | import static java.lang.System.getSecurityManager;
4 | import static java.lang.System.setSecurityManager;
5 |
6 | import org.junit.rules.ExternalResource;
7 |
8 | /**
9 | * The {@code ProvideSecurityManager} rule provides an arbitrary security
10 | * manager to a test. After the test the original security manager is restored.
11 | *
12 | *
13 | * public void MyTest {
14 | * private final MySecurityManager securityManager
15 | * = new MySecurityManager();
16 | *
17 | * @Rule
18 | * public final ProvideSecurityManager provideSecurityManager
19 | * = new ProvideSecurityManager(securityManager);
20 | *
21 | * @Test
22 | * public void overrideProperty() {
23 | * assertEquals(securityManager, System.getSecurityManager());
24 | * }
25 | * }
26 | *
27 | */
28 | public class ProvideSecurityManager extends ExternalResource {
29 | private final SecurityManager manager;
30 | private SecurityManager originalManager;
31 |
32 | public ProvideSecurityManager(SecurityManager manager) {
33 | this.manager = manager;
34 | }
35 |
36 | @Override
37 | protected void before() throws Throwable {
38 | originalManager = getSecurityManager();
39 | setSecurityManager(manager);
40 | }
41 |
42 | @Override
43 | protected void after() {
44 | setSecurityManager(originalManager);
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/org/junit/contrib/java/lang/system/ProvideSystemProperty.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 | import static java.lang.System.clearProperty;
4 |
5 | import java.io.FileInputStream;
6 | import java.io.IOException;
7 | import java.io.InputStream;
8 | import java.util.LinkedHashMap;
9 | import java.util.Map;
10 | import java.util.Map.Entry;
11 | import java.util.Properties;
12 |
13 | import org.junit.contrib.java.lang.system.internal.RestoreSpecificSystemProperties;
14 | import org.junit.rules.ExternalResource;
15 |
16 | /**
17 | * The {@code ProvideSystemProperty} rule provides an arbitrary value for a
18 | * system property to a test. After the test the original value is restored. You
19 | * can ensure that a property is not set by providing {@code null} (or using
20 | * {@link org.junit.contrib.java.lang.system.ClearSystemProperties}).
21 | *
22 | * Let's assume the system property {@code MyProperty} is not set and the system
23 | * property {@code OtherProperty} has the value {@code OtherValue}. Now run the
24 | * test
25 | *
26 | *
27 | * public void MyTest {
28 | * @Rule
29 | * public final ProvideSystemProperty provideSystemProperty
30 | * = new ProvideSystemProperty("MyProperty", "MyValue")
31 | * .and("OtherProperty", null);
32 | *
33 | * @Test
34 | * public void overridesProperty() {
35 | * assertEquals("MyValue", System.getProperty("MyProperty"));
36 | * }
37 | *
38 | * @Test
39 | * public void deletesProperty() {
40 | * assertNull(System.getProperty("OtherProperty"));
41 | * }
42 | * }
43 | *
44 | *
45 | * Both tests succeed and after the tests, the system property
46 | * {@code MyProperty} is not set and the system property {@code OtherProperty}
47 | * has the value {@code OtherValue}.
48 | *
49 | * You can use a properties file to supply properties for the
50 | * ProvideSystemProperty rule. The file can be from the file system or the class
51 | * path. In the first case use
52 | *
53 | *
54 | * @Rule
55 | * public final ProvideSystemProperty properties = ProvideSystemProperty
56 | * .fromFile("/home/myself/example.properties");
57 | *
58 | *
59 | * and in the second case use
60 | *
61 | *
62 | * @Rule
63 | * public final ProvideSystemProperty properties = ProvideSystemProperty
64 | * .fromResource("example.properties");
65 | *
66 | * Set property for a single test
67 | * If you want to set a property for a single test then you can use
68 | * {@link org.junit.contrib.java.lang.system.RestoreSystemProperties}
69 | * along with {@link System#setProperty(String, String)}.
70 | *
71 | * @Rule
72 | * public final TestRule restoreSystemProperties
73 | * = new RestoreSystemProperties();
74 | *
75 | * @Test
76 | * public void test() {
77 | * System.setProperty("YourProperty", "YourValue");
78 | * ...
79 | * }
80 | */
81 | public class ProvideSystemProperty extends ExternalResource {
82 | private final Map properties = new LinkedHashMap();
83 | private final RestoreSpecificSystemProperties restoreSystemProperty = new RestoreSpecificSystemProperties();
84 |
85 | public static ProvideSystemProperty fromFile(String name) {
86 | try {
87 | FileInputStream fis = new FileInputStream(name);
88 | return fromInputStream(fis);
89 | } catch (IOException e) {
90 | throw new IllegalArgumentException(
91 | "Cannot create ProvideSystemProperty rule because file \""
92 | + name + "\" cannot be read.",
93 | e);
94 | }
95 | }
96 |
97 | public static ProvideSystemProperty fromResource(String name) {
98 | InputStream is = ProvideSystemProperty.class.getResourceAsStream(name);
99 | try {
100 | return fromInputStream(is);
101 | } catch (IOException e) {
102 | throw new IllegalArgumentException(
103 | "Cannot create ProvideSystemProperty rule because resource \""
104 | + name + "\" cannot be read.",
105 | e);
106 | }
107 | }
108 |
109 | private static ProvideSystemProperty fromInputStream(InputStream is)
110 | throws IOException {
111 | Properties p = new Properties();
112 | p.load(is);
113 | ProvideSystemProperty rule = new ProvideSystemProperty();
114 | for (Map.Entry property : p.entrySet())
115 | rule.addProperty((String) property.getKey(),
116 | (String) property.getValue());
117 | return rule;
118 | }
119 |
120 | /**
121 | * @deprecated see {@link #setProperty(String, String)}.
122 | */
123 | @Deprecated
124 | public ProvideSystemProperty() {
125 | }
126 |
127 | /**
128 | * Sets the property with the name to the specified value. After the test
129 | * the rule restores the value of the property at the point of setting it.
130 | *
131 | * This method is deprecated. If you're still using it, please replace your current code
132 | *
133 | * @Rule
134 | * public final ProvideSystemProperty provideSystemProperty = new ProvideSystemProperty();
135 | *
136 | * @Test
137 | * public void test() {
138 | * provideSystemProperty.setProperty("YourProperty", "YourValue");
139 | * ...
140 | * }
141 | * with this code:
142 | *
143 | * @Rule
144 | * public final TestRule restoreSystemProperties = new RestoreSystemProperties();
145 | *
146 | * @Test
147 | * public void test() {
148 | * System.setProperty("YourProperty", "YourValue");
149 | * ...
150 | * }
151 | *
152 | * @param name the name of the property.
153 | * @param value the new value of the property.
154 | * @since 1.6.0
155 | * @deprecated Please use {@link org.junit.contrib.java.lang.system.RestoreSystemProperties}
156 | * along with {@link System#setProperty(String, String)}.
157 | */
158 | @Deprecated
159 | public void setProperty(String name, String value) {
160 | restoreSystemProperty.add(name);
161 | if (value == null)
162 | clearProperty(name);
163 | else
164 | System.setProperty(name, value);
165 | }
166 |
167 | public ProvideSystemProperty(String name, String value) {
168 | addProperty(name, value);
169 | }
170 |
171 | public ProvideSystemProperty and(String name, String value) {
172 | addProperty(name, value);
173 | return this;
174 | }
175 |
176 | private void addProperty(String name, String value) {
177 | properties.put(name, value);
178 | }
179 |
180 | @Override
181 | protected void before() throws Throwable {
182 | setProperties();
183 | }
184 |
185 | private void setProperties() {
186 | for (Entry property : properties.entrySet()) {
187 | String name = property.getKey();
188 | String value = property.getValue();
189 | setProperty(name, value);
190 | }
191 | }
192 |
193 | @Override
194 | protected void after() {
195 | restoreSystemProperty.restore();
196 | }
197 | }
198 |
--------------------------------------------------------------------------------
/src/main/java/org/junit/contrib/java/lang/system/RestoreSystemProperties.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 | import static java.lang.System.getProperties;
4 | import static java.lang.System.setProperties;
5 |
6 | import java.util.Properties;
7 |
8 | import org.junit.rules.ExternalResource;
9 |
10 | /**
11 | * The {@code RestoreSystemProperties} rule undoes changes of system
12 | * properties when the test finishes (whether it passes or fails).
13 | * Let's assume the system property {@code YourProperty} has the
14 | * value {@code YourValue}. Now run the test
15 | *
16 | * public void YourTest {
17 | * @Rule
18 | * public final TestRule restoreSystemProperties = new RestoreSystemProperties();
19 | *
20 | * @Test
21 | * public void overrideProperty() {
22 | * System.setProperty("YourProperty", "other value");
23 | * assertEquals("other value", System.getProperty("YourProperty"));
24 | * }
25 | * }
26 | *
27 | * After running the test, the system property {@code YourProperty} has
28 | * the value {@code YourValue} again.
29 | */
30 | public class RestoreSystemProperties extends ExternalResource {
31 | private Properties originalProperties;
32 |
33 | /**
34 | * Creates a {@code RestoreSystemProperties} rule that restores all
35 | * system properties.
36 | *
37 | * @deprecated Please use {@link #RestoreSystemProperties()}. The
38 | * rule restores all properties. That's why you don't have to
39 | * specify the properties anymore.
40 | */
41 | @Deprecated
42 | public RestoreSystemProperties(String... properties) {
43 | }
44 |
45 | /**
46 | * Creates a {@code RestoreSystemProperties} rule that restores all
47 | * system properties.
48 | *
49 | * @since 1.8.0
50 | */
51 | public RestoreSystemProperties() {
52 | }
53 |
54 | /**
55 | * Does nothing.
56 | *
57 | * @since 1.6.0
58 | * @deprecated Simply remove all calls to this method.
59 | * {@code RestoreSystemProperties} restores all properties
60 | * automatically. That's why you don't have to add the properties
61 | * anymore.
62 | */
63 | @Deprecated
64 | public void add(String property) {
65 | }
66 |
67 | @Override
68 | protected void before() throws Throwable {
69 | originalProperties = getProperties();
70 | setProperties(copyOf(originalProperties));
71 | }
72 |
73 | private Properties copyOf(Properties source) {
74 | Properties copy = new Properties();
75 | copy.putAll(source);
76 | return copy;
77 | }
78 |
79 | @Override
80 | protected void after() {
81 | setProperties(originalProperties);
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/src/main/java/org/junit/contrib/java/lang/system/StandardErrorStreamLog.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 | import static org.junit.contrib.java.lang.system.LogMode.LOG_AND_WRITE_TO_STREAM;
4 | import static org.junit.contrib.java.lang.system.LogMode.LOG_ONLY;
5 |
6 | import org.junit.rules.TestRule;
7 | import org.junit.runner.Description;
8 | import org.junit.runners.model.Statement;
9 |
10 | /**
11 | * @deprecated Please use {@link SystemErrRule}.
12 | *
13 | * The {@code StandardErrorStreamLog} records writes to the standard error
14 | * stream. The text written is available via {@link #getLog()}.
15 | *
16 | *
17 | * public void MyTest {
18 | * @Rule
19 | * public final StandardErrorStreamLog log = new StandardErrorStreamLog();
20 | *
21 | * @Test
22 | * public void captureErrorStream() {
23 | * System.err.print("hello world");
24 | * assertEquals("hello world", log.getLog());
25 | * }
26 | * }
27 | *
28 | *
29 | * You can clear the log if you only want to test parts of the text written to
30 | * the standard error stream.
31 | *
32 | *
33 | * @Test
34 | * public void captureErrorStream() {
35 | * System.err.print("before");
36 | * log.clear();
37 | * System.err.print("afterwards");
38 | * assertEquals("afterwards", log.getLog());
39 | * }
40 | *
41 | *
42 | * Prevent output to the standard error stream
43 | * In general it is not necessary that a test writes to the standard error
44 | * stream. Avoiding this output may speed up the test and reduce the clutter
45 | * on the commandline.
46 | * The test does not write to the stream if the rule is created with the
47 | * {@link org.junit.contrib.java.lang.system.LogMode#LOG_ONLY} mode.
48 | *
49 | * @Rule
50 | * public final StandardErrorStreamLog log = new StandardErrorStreamLog(LOG_ONLY);
51 | */
52 | @Deprecated
53 | public class StandardErrorStreamLog implements TestRule {
54 | private final SystemErrRule systemErrRule = new SystemErrRule();
55 | /**
56 | * @deprecated Please use
57 | * {@link SystemErrRule#enableLog() new SystemErrRule().enableLog()}.
58 | *
59 | * Creates a rule that records writes while they are still written to the
60 | * standard error stream.
61 | */
62 | public StandardErrorStreamLog() {
63 | this(LOG_AND_WRITE_TO_STREAM);
64 | }
65 |
66 | /**
67 | * @deprecated Please use
68 | * {@link SystemErrRule#enableLog() new SystemErrRule().enableLog()}
69 | * instead of
70 | * {@code new StandardErrorStreamLog(LogMode.LOG_AND_WRITE_TO_STREAM)} or
71 | * {@link SystemErrRule#enableLog() new SystemErrRule().enableLog()}.{@link SystemErrRule#mute() mute()}
72 | * instead of {@code new StandardErrorStreamLog(LogMode.LOG_ONLY)}.
73 | *
74 | *
Creates a rule that records writes to the standard error stream
75 | * according to the specified {@code LogMode}.
76 | *
77 | * @param mode how the rule handles writes to the standard error stream.
78 | * @throws java.lang.NullPointerException if {@code mode} is null.
79 | */
80 | public StandardErrorStreamLog(LogMode mode) {
81 | if (mode == null)
82 | throw new NullPointerException("The LogMode is missing.");
83 | systemErrRule.enableLog();
84 | if (mode == LOG_ONLY)
85 | systemErrRule.mute();
86 | }
87 |
88 | /**
89 | * @deprecated Please use
90 | * {@link org.junit.contrib.java.lang.system.SystemErrRule#clearLog()}.
91 | *
92 | *
Clears the log. The log can be used again.
93 | */
94 | @Deprecated
95 | public void clear() {
96 | systemErrRule.clearLog();
97 | }
98 |
99 | /**
100 | * @deprecated Please use
101 | * {@link org.junit.contrib.java.lang.system.SystemErrRule#getLog()}.
102 | *
103 | *
Returns the text written to the standard error stream.
104 | *
105 | * @return the text written to the standard error stream.
106 | */
107 | @Deprecated
108 | public String getLog() {
109 | return systemErrRule.getLog();
110 | }
111 |
112 | public Statement apply(Statement base, Description description) {
113 | return systemErrRule.apply(base, description);
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/src/main/java/org/junit/contrib/java/lang/system/StandardOutputStreamLog.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 | import static org.junit.contrib.java.lang.system.LogMode.LOG_AND_WRITE_TO_STREAM;
4 | import static org.junit.contrib.java.lang.system.LogMode.LOG_ONLY;
5 |
6 | import org.junit.rules.TestRule;
7 | import org.junit.runner.Description;
8 | import org.junit.runners.model.Statement;
9 |
10 | /**
11 | * @deprecated Please use {@link SystemOutRule}.
12 | *
13 | *
The {@code StandardOutputStreamLog} records writes to the standard output
14 | * stream. The text written is available via {@link #getLog()}.
15 | *
16 | *
17 | * public void MyTest {
18 | * @Rule
19 | * public final StandardOutputStreamLog log = new StandardOutputStreamLog();
20 | *
21 | * @Test
22 | * public void captureOutputStream() {
23 | * System.out.print("hello world");
24 | * assertEquals("hello world", log.getLog());
25 | * }
26 | * }
27 | *
28 | *
29 | * You can clear the log if you only want to test parts of the text written to
30 | * the standard output stream.
31 | *
32 | *
33 | * @Test
34 | * public void captureOutputStream() {
35 | * System.out.print("before");
36 | * log.clear();
37 | * System.out.print("afterwards");
38 | * assertEquals("afterwards", log.getLog());
39 | * }
40 | *
41 | * Prevent output to the standard output stream
42 | * In general it is not necessary that a test writes to the standard output
43 | * stream. Avoiding this output may speed up the test and reduce the clutter
44 | * on the commandline.
45 | * The test does not write to the stream if the rule is created with the
46 | * {@link org.junit.contrib.java.lang.system.LogMode#LOG_ONLY} mode.
47 | *
48 | * @Rule
49 | * public final StandardOutputStreamLog log = new StandardOutputStreamLog(LOG_ONLY);
50 | */
51 | @Deprecated
52 | public class StandardOutputStreamLog implements TestRule {
53 | private final SystemOutRule systemOut = new SystemOutRule();
54 | /**
55 | * @deprecated Please use
56 | * {@link SystemOutRule#enableLog() new SystemOutRule().enableLog()}.
57 | *
58 | * Creates a rule that records writes while they are still written to
59 | * the standard output stream.
60 | */
61 | public StandardOutputStreamLog() {
62 | this(LOG_AND_WRITE_TO_STREAM);
63 | }
64 |
65 | /**
66 | * @deprecated Please use
67 | * {@link SystemOutRule#enableLog() new SystemOutRule().enableLog()}
68 | * instead of
69 | * {@code new StandardOutputStreamLog(LogMode.LOG_AND_WRITE_TO_STREAM)} or
70 | * {@link SystemOutRule#enableLog() new SystemOutRule().enableLog()}.{@link SystemOutRule#mute() mute()}
71 | * instead of {@code new StandardOutputStreamLog(LogMode.LOG_ONLY)}.
72 | *
73 | *
Creates a rule that records writes to the standard output stream
74 | * according to the specified {@code LogMode}.
75 | *
76 | * @param mode how the rule handles writes to the standard output stream.
77 | * @throws java.lang.NullPointerException if {@code mode} is null.
78 | */
79 | public StandardOutputStreamLog(LogMode mode) {
80 | if (mode == null)
81 | throw new NullPointerException("The LogMode is missing.");
82 | systemOut.enableLog();
83 | if (mode == LOG_ONLY)
84 | systemOut.mute();
85 | }
86 |
87 | /**
88 | * @deprecated Please use
89 | * {@link org.junit.contrib.java.lang.system.SystemOutRule#clearLog()}.
90 | *
91 | *
Clears the log. The log can be used again.
92 | */
93 | @Deprecated
94 | public void clear() {
95 | systemOut.clearLog();
96 | }
97 |
98 | /**
99 | * @deprecated Please use
100 | * {@link org.junit.contrib.java.lang.system.SystemOutRule#getLog()}.
101 | *
102 | *
Returns the text written to the standard output stream.
103 | *
104 | * @return the text written to the standard output stream.
105 | */
106 | @Deprecated
107 | public String getLog() {
108 | return systemOut.getLog();
109 | }
110 |
111 | public Statement apply(Statement base, Description description) {
112 | return systemOut.apply(base, description);
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/src/main/java/org/junit/contrib/java/lang/system/SystemErrRule.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 | import static org.junit.contrib.java.lang.system.internal.PrintStreamHandler.SYSTEM_ERR;
4 |
5 | import org.junit.contrib.java.lang.system.internal.LogPrintStream;
6 | import org.junit.rules.TestRule;
7 | import org.junit.runner.Description;
8 | import org.junit.runners.model.Statement;
9 |
10 | /**
11 | * The {@code SystemErrRule} intercepts the writes to
12 | * {@code System.err}. It is used to make assertions about the text
13 | * that is written to {@code System.err} or to mute {@code System.err}.
14 | *
15 | *
Assertions
16 | *
17 | * {@code SystemErrRule} may be used for verifying the text that is
18 | * written to {@code System.err}.
19 | *
20 | *
21 | * public class SystemErrTest {
22 | * @Rule
23 | * public final SystemErrRule systemErrRule = new SystemErrRule().enableLog();
24 | *
25 | * @Test
26 | * public void test() {
27 | * System.err.print("some text");
28 | * assertEquals("some text", systemErrRule.getLog());
29 | * }
30 | * }
31 | *
32 | *
33 | * If your code under test writes the correct new line characters to
34 | * {@code System.err} then the test output is different at different systems.
35 | * {@link #getLogWithNormalizedLineSeparator()} provides a log that always uses
36 | * {@code \n} as line separator. This makes it easy to write appropriate
37 | * assertions that work on all systems.
38 | *
39 | *
40 | * public class SystemErrTest {
41 | * @Rule
42 | * public final SystemErrRule systemErrRule = new SystemErrRule().enableLog();
43 | *
44 | * @Test
45 | * public void test() {
46 | * System.err.print(String.format("some text%n"));
47 | * assertEquals("some text\n", systemErrRule.getLogWithNormalizedLineSeparator());
48 | * }
49 | * }
50 | *
51 | *
52 | * If your code under test writes raw binary data to {@code System.err} then
53 | * you can read it by means of {@link #getLogAsBytes()}).
54 | *
55 | *
56 | * public class SystemErrTest {
57 | * @Rule
58 | * public final SystemErrRule systemErrRule = new SystemErrRule().enableLog();
59 | *
60 | * @Test
61 | * public void test() {
62 | * byte[] data = { 1, 2, 3, 4, 5 };
63 | * System.err.write(data, 0, data.length);
64 | * assertEquals(data, systemErrRule.{@link #getLogAsBytes()});
65 | * }
66 | * }
67 | *
68 | *
69 | * You don't have to enable logging for every test. It can be enabled for
70 | * specific tests only.
71 | *
72 | *
73 | * public class SystemErrTest {
74 | * @Rule
75 | * public final SystemErrRule systemErrRule = new SystemErrRule();
76 | *
77 | * @Test
78 | * public void testWithLogging() {
79 | * systemErrRule.enableLog()
80 | * System.err.print("some text");
81 | * assertEquals("some text", systemErrRule.getLog());
82 | * }
83 | *
84 | * @Test
85 | * public void testWithoutLogging() {
86 | * System.err.print("some text");
87 | * }
88 | * }
89 | *
90 | *
91 | * If you want to verify parts of the output only then you can clear the log
92 | * during a test.
93 | *
94 | *
95 | * public class SystemErrTest {
96 | * @Rule
97 | * public final SystemErrRule systemErrRule = new SystemErrRule().enableLog();
98 | *
99 | * @Test
100 | * public void test() {
101 | * System.err.print("uninteresting things");
102 | * systemErrRule.clearLog()
103 | * System.err.print("interesting things");
104 | * assertEquals("interesting things", systemErrRule.getLog());
105 | * }
106 | * }
107 | *
108 | *
109 | * Muting
110 | *
111 | * Usually the output of a test to {@code System.err} does not have to be
112 | * visible. It may even slowdown the test. {@code SystemErrRule} can
113 | * be used to suppress this output.
114 | *
115 | *
116 | * public class SystemErrTest {
117 | * @Rule
118 | * public final SystemErrRule systemErrRule = new SystemErrRule().mute();
119 | *
120 | * @Test
121 | * public void test() {
122 | * System.err.print("some text"); //is not visible on the console
123 | * }
124 | * }
125 | *
126 | *
127 | * You don't have to mute {@code System.err} for every test. It can be muted for
128 | * specific tests only.
129 | *
130 | *
131 | * public class SystemErrTest {
132 | * @Rule
133 | * public final SystemErrRule systemErrRule = new SystemErrRule();
134 | *
135 | * @Test
136 | * public void testWithSuppressedOutput() {
137 | * systemErrRule.mute()
138 | * System.err.print("some text");
139 | * }
140 | *
141 | * @Test
142 | * public void testWithNormalOutput() {
143 | * System.err.print("some text");
144 | * }
145 | * }
146 | *
147 | *
148 | * In case of a failed test it is sometimes helpful to see the output. This
149 | * is when the method {@link #muteForSuccessfulTests()} comes into play.
150 | *
151 | *
152 | * public class SystemErrTest {
153 | * @Rule
154 | * public final SystemErrRule systemErrRule = new SystemErrRule().muteForSuccessfulTests();
155 | *
156 | * @Test
157 | * public void testWithSuppressedOutput() {
158 | * System.err.print("some text");
159 | * }
160 | *
161 | * @Test
162 | * public void testWithNormalOutput() {
163 | * System.err.print("some text");
164 | * fail();
165 | * }
166 | * }
167 | *
168 | *
169 | * Combine Logging and Muting
170 | *
171 | * Logging and muting can be combined. No output is actually written to
172 | * {@code System.err} but everything that would have been written is available
173 | * from the log.
174 | *
175 | *
176 | * public class SystemErrTest {
177 | * @Rule
178 | * public final SystemErrRule systemErrRule = new SystemErrRule().mute().enableLog();
179 | *
180 | * @Test
181 | * public void test() {
182 | * System.err.print("some text"); //is not visible on the console
183 | * assertEquals("some text", systemErrRule.getLog()); //succeeds
184 | * }
185 | * }
186 | *
187 | */
188 | public class SystemErrRule implements TestRule {
189 | private LogPrintStream logPrintStream = new LogPrintStream(SYSTEM_ERR);
190 |
191 | /**
192 | * Suppress the output to {@code System.err}.
193 | *
194 | * @return the rule itself.
195 | */
196 | public SystemErrRule mute() {
197 | logPrintStream.mute();
198 | return this;
199 | }
200 |
201 | /**
202 | * Suppress the output to {@code System.err} for successful tests only.
203 | * The output is still written to {@code System.err} for failing tests.
204 | *
205 | * @return the rule itself.
206 | */
207 | public SystemErrRule muteForSuccessfulTests() {
208 | logPrintStream.muteForSuccessfulTests();
209 | return this;
210 | }
211 |
212 | /**
213 | * Clears the current log.
214 | */
215 | public void clearLog() {
216 | logPrintStream.clearLog();
217 | }
218 |
219 | /**
220 | * Returns the text that is written to {@code System.err} since
221 | * {@link #enableLog()} (respectively {@link #clearLog()} has been called.
222 | *
223 | * @return the text that is written to {@code System.err} since
224 | * {@link #enableLog} (respectively {@link #clearLog()} has been called.
225 | */
226 | public String getLog() {
227 | return logPrintStream.getLog();
228 | }
229 |
230 | /**
231 | * Returns the text that is written to {@code System.err} since
232 | * {@link #enableLog()} (respectively {@link #clearLog()} has been called.
233 | * New line characters are replaced with a single {@code \n}.
234 | *
235 | * @return the normalized log.
236 | */
237 | public String getLogWithNormalizedLineSeparator() {
238 | return logPrintStream.getLogWithNormalizedLineSeparator();
239 | }
240 |
241 | /**
242 | * Returns the raw bytes that are written to {@code System.err} since
243 | * {@link #enableLog()} (respectively {@link #clearLog()} has been called.
244 | *
245 | * @return the raw bytes that are written to {@code System.err} since
246 | * {@link #enableLog()} (respectively {@link #clearLog()} has been called.
247 | */
248 | public byte[] getLogAsBytes() {
249 | return logPrintStream.getLogAsBytes();
250 | }
251 |
252 | /**
253 | * Start logging of everything that is written to {@code System.err}.
254 | *
255 | * @return the rule itself.
256 | */
257 | public SystemErrRule enableLog() {
258 | logPrintStream.enableLog();
259 | return this;
260 | }
261 |
262 | public Statement apply(Statement base, Description description) {
263 | return logPrintStream.createStatement(base);
264 | }
265 | }
266 |
--------------------------------------------------------------------------------
/src/main/java/org/junit/contrib/java/lang/system/SystemOutRule.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 | import static org.junit.contrib.java.lang.system.internal.PrintStreamHandler.SYSTEM_OUT;
4 |
5 | import org.junit.contrib.java.lang.system.internal.LogPrintStream;
6 | import org.junit.rules.TestRule;
7 | import org.junit.runner.Description;
8 | import org.junit.runners.model.Statement;
9 |
10 | /**
11 | * The {@code SystemOutRule} intercepts the writes to
12 | * {@code System.out}. It is used to make assertions about the text
13 | * that is written to {@code System.out} or to mute {@code System.out}.
14 | *
15 | * Assertions
16 | *
17 | * {@code SystemOutRule} may be used for verifying the text that is
18 | * written to {@code System.out}.
19 | *
20 | *
21 | * public class SystemOutTest {
22 | * @Rule
23 | * public final SystemOutRule systemOutRule = new SystemOutRule().enableLog();
24 | *
25 | * @Test
26 | * public void test() {
27 | * System.out.print("some text");
28 | * assertEquals("some text", systemOutRule.getLog());
29 | * }
30 | * }
31 | *
32 | *
33 | * If your code under test writes the correct new line characters to
34 | * {@code System.out} then the test output is different at different systems.
35 | * {@link #getLogWithNormalizedLineSeparator()} provides a log that always uses
36 | * {@code \n} as line separator. This makes it easy to write appropriate
37 | * assertions that work on all systems.
38 | *
39 | *
40 | * public class SystemOutTest {
41 | * @Rule
42 | * public final SystemOutRule systemOutRule = new SystemOutRule().enableLog();
43 | *
44 | * @Test
45 | * public void test() {
46 | * System.out.print(String.format("some text%n"));
47 | * assertEquals("some text\n", systemOutRule.getLogWithNormalizedLineSeparator());
48 | * }
49 | * }
50 | *
51 | *
52 | * If your code under test writes raw binary data to {@code System.out} then
53 | * you can read it by means of {@link #getLogAsBytes()}).
54 | *
55 | *
56 | * public class SystemOutTest {
57 | * @Rule
58 | * public final SystemOutRule systemOutRule = new SystemOutRule().enableLog();
59 | *
60 | * @Test
61 | * public void test() {
62 | * byte[] data = { 1, 2, 3, 4, 5 };
63 | * System.out.write(data, 0, data.length);
64 | * assertEquals(data, systemOutRule.{@link #getLogAsBytes()});
65 | * }
66 | * }
67 | *
68 | *
69 | * You don't have to enable logging for every test. It can be enabled for
70 | * specific tests only.
71 | *
72 | *
73 | * public class SystemOutTest {
74 | * @Rule
75 | * public final SystemOutRule systemOutRule = new SystemOutRule();
76 | *
77 | * @Test
78 | * public void testWithLogging() {
79 | * systemOutRule.enableLog()
80 | * System.out.print("some text");
81 | * assertEquals("some text", systemOutRule.getLog());
82 | * }
83 | *
84 | * @Test
85 | * public void testWithoutLogging() {
86 | * System.out.print("some text");
87 | * }
88 | * }
89 | *
90 | *
91 | * If you want to verify parts of the output only then you can clear the log
92 | * during a test.
93 | *
94 | *
95 | * public class SystemOutTest {
96 | * @Rule
97 | * public final SystemOutRule systemOutRule = new SystemOutRule().enableLog();
98 | *
99 | * @Test
100 | * public void test() {
101 | * System.out.print("uninteresting things");
102 | * systemOutRule.clearLog()
103 | * System.out.print("interesting things");
104 | * assertEquals("interesting things", systemOutRule.getLog());
105 | * }
106 | * }
107 | *
108 | *
109 | * Muting
110 | *
111 | * Usually the output of a test to {@code System.out} does not have to be
112 | * visible. It may even slowdown the test. {@code SystemOutRule} can
113 | * be used to suppress this output.
114 | *
115 | *
116 | * public class SystemOutTest {
117 | * @Rule
118 | * public final SystemOutRule systemOutRule = new SystemOutRule().mute();
119 | *
120 | * @Test
121 | * public void test() {
122 | * System.out.print("some text"); //is not visible on the console
123 | * }
124 | * }
125 | *
126 | *
127 | * You don't have to mute {@code System.out} for every test. It can be muted for
128 | * specific tests only.
129 | *
130 | *
131 | * public class SystemOutTest {
132 | * @Rule
133 | * public final SystemOutRule systemOutRule = new SystemOutRule();
134 | *
135 | * @Test
136 | * public void testWithSuppressedOutput() {
137 | * systemOutRule.mute()
138 | * System.out.print("some text");
139 | * }
140 | *
141 | * @Test
142 | * public void testWithNormalOutput() {
143 | * System.out.print("some text");
144 | * }
145 | * }
146 | *
147 | *
148 | * In case of a failed test it is sometimes helpful to see the output. This
149 | * is when the method {@link #muteForSuccessfulTests()} comes into play.
150 | *
151 | *
152 | * public class SystemOutTest {
153 | * @Rule
154 | * public final SystemOutRule systemOutRule = new SystemOutRule().muteForSuccessfulTests();
155 | *
156 | * @Test
157 | * public void testWithSuppressedOutput() {
158 | * System.out.print("some text");
159 | * }
160 | *
161 | * @Test
162 | * public void testWithNormalOutput() {
163 | * System.out.print("some text");
164 | * fail();
165 | * }
166 | * }
167 | *
168 | *
169 | * Combine Logging and Muting
170 | *
171 | * Logging and muting can be combined. No output is actually written to
172 | * {@code System.out} but everything that would have been written is available
173 | * from the log.
174 | *
175 | *
176 | * public class SystemOutTest {
177 | * @Rule
178 | * public final SystemOutRule systemOutRule = new SystemOutRule().mute().enableLog();
179 | *
180 | * @Test
181 | * public void test() {
182 | * System.out.print("some text"); //is not visible on the console
183 | * assertEquals("some text", systemOutRule.getLog()); //succeeds
184 | * }
185 | * }
186 | *
187 | */
188 | public class SystemOutRule implements TestRule {
189 | private LogPrintStream logPrintStream = new LogPrintStream(SYSTEM_OUT);
190 |
191 | /**
192 | * Suppress the output to {@code System.out}.
193 | *
194 | * @return the rule itself.
195 | */
196 | public SystemOutRule mute() {
197 | logPrintStream.mute();
198 | return this;
199 | }
200 |
201 | /**
202 | * Suppress the output to {@code System.out} for successful tests only.
203 | * The output is still written to {@code System.out} for failing tests.
204 | *
205 | * @return the rule itself.
206 | */
207 | public SystemOutRule muteForSuccessfulTests() {
208 | logPrintStream.muteForSuccessfulTests();
209 | return this;
210 | }
211 |
212 | /**
213 | * Clears the current log.
214 | */
215 | public void clearLog() {
216 | logPrintStream.clearLog();
217 | }
218 |
219 | /**
220 | * Returns the text that is written to {@code System.out} since
221 | * {@link #enableLog()} (respectively {@link #clearLog()} has been called.
222 | *
223 | * @return the text that is written to {@code System.out} since
224 | * {@link #enableLog()} (respectively {@link #clearLog()} has been called.
225 | */
226 | public String getLog() {
227 | return logPrintStream.getLog();
228 | }
229 |
230 | /**
231 | * Returns the text that is written to {@code System.out} since
232 | * {@link #enableLog()} (respectively {@link #clearLog()} has been called.
233 | * New line characters are replaced with a single {@code \n}.
234 | *
235 | * @return the normalized log.
236 | */
237 | public String getLogWithNormalizedLineSeparator() {
238 | return logPrintStream.getLogWithNormalizedLineSeparator();
239 | }
240 |
241 | /**
242 | * Returns the raw bytes that are written to {@code System.out} since
243 | * {@link #enableLog()} (respectively {@link #clearLog()} has been called.
244 | *
245 | * @return the raw bytes that are written to {@code System.out} since
246 | * {@link #enableLog()} (respectively {@link #clearLog()} has been called.
247 | */
248 | public byte[] getLogAsBytes() {
249 | return logPrintStream.getLogAsBytes();
250 | }
251 |
252 | /**
253 | * Start logging of everything that is written to {@code System.out}.
254 | *
255 | * @return the rule itself.
256 | */
257 | public SystemOutRule enableLog() {
258 | logPrintStream.enableLog();
259 | return this;
260 | }
261 |
262 | public Statement apply(Statement base, Description description) {
263 | return logPrintStream.createStatement(base);
264 | }
265 | }
266 |
--------------------------------------------------------------------------------
/src/main/java/org/junit/contrib/java/lang/system/TextFromStandardInputStream.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 | import static java.lang.System.getProperty;
4 | import static java.lang.System.in;
5 | import static java.lang.System.setIn;
6 |
7 | import java.io.IOException;
8 | import java.io.InputStream;
9 | import java.io.StringReader;
10 |
11 | import org.junit.rules.ExternalResource;
12 |
13 | /**
14 | * The {@code TextFromStandardInputStream} rule replaces {@code System.in} with
15 | * another {@code InputStream}, which provides an arbitrary text. The original
16 | * {@code System.in} is restored after the test.
17 | *
18 | *
19 | * public void MyTest {
20 | * @Rule
21 | * public final TextFromStandardInputStream systemInMock
22 | * = emptyStandardInputStream();
23 | *
24 | * @Test
25 | * public void readTextFromStandardInputStream() {
26 | * systemInMock.provideLines("foo", "bar");
27 | * Scanner scanner = new Scanner(System.in);
28 | * scanner.nextLine();
29 | * assertEquals("bar", scanner.nextLine());
30 | * }
31 | * }
32 | *
33 | *
34 | * Throwing Exceptions
35 | * {@code TextFromStandardInputStream} can also simulate a {@code System.in}
36 | * that throws an {@code IOException} or {@code RuntimeException}. Use
37 | *
systemInMock.{@link #throwExceptionOnInputEnd(IOException)}
38 | * or
39 | *
systemInMock.{@link #throwExceptionOnInputEnd(RuntimeException)}
40 | * If you call {@link #provideLines(String...)} in addition then the
41 | * exception is thrown after the text has been read from {@code System.in}.
42 | */
43 | public class TextFromStandardInputStream extends ExternalResource {
44 | private final SystemInMock systemInMock = new SystemInMock();
45 | private InputStream originalIn;
46 |
47 | public static TextFromStandardInputStream emptyStandardInputStream() {
48 | return new TextFromStandardInputStream("");
49 | }
50 |
51 | /**
52 | * Create a new {@code TextFromStandardInputStream}, which provides the
53 | * specified text.
54 | *
55 | * @param text this text is return by {@code System.in}.
56 | * @deprecated use {@link #provideLines(String...)}
57 | */
58 | @Deprecated
59 | public TextFromStandardInputStream(String text) {
60 | provideText(text);
61 | }
62 |
63 | /**
64 | * Set the text that is returned by {@code System.in}. You can
65 | * provide multiple texts. In that case the texts are concatenated.
66 | *
67 | * @param texts a list of texts.
68 | * @deprecated please use {@link #provideLines(String...)}
69 | */
70 | @Deprecated
71 | public void provideText(String... texts) {
72 | systemInMock.provideText(join(texts));
73 | }
74 |
75 | /**
76 | * Set the lines that are returned by {@code System.in}.
77 | * {@code System.getProperty("line.separator")} is used for the end
78 | * of line.
79 | *
80 | * @param lines a list of lines.
81 | */
82 | public void provideLines(String... lines) {
83 | systemInMock.provideText(joinLines(lines));
84 | }
85 |
86 | /**
87 | * Specify an {@code IOException} that is thrown by {@code System.in}. If
88 | * you call {@link #provideLines(String...)} or
89 | * {@link #provideText(String...)} in addition then the exception is thrown
90 | * after the text has been read from {@code System.in}.
91 | *
92 | * @param exception the {@code IOException} that is thrown.
93 | * @see #throwExceptionOnInputEnd(RuntimeException)
94 | * @throws IllegalStateException if
95 | * {@link #throwExceptionOnInputEnd(RuntimeException)} has been called before.
96 | */
97 | public void throwExceptionOnInputEnd(IOException exception) {
98 | systemInMock.throwExceptionOnInputEnd(exception);
99 | }
100 |
101 | /**
102 | * Specify a {@code RuntimeException} that is thrown by {@code System.in}.
103 | * If you call {@link #provideLines(String...)} or
104 | * {@link #provideText(String...)} in addition then the exception is thrown
105 | * after the text has been read from {@code System.in}.
106 | *
107 | * @param exception the {@code RuntimeException} that is thrown.
108 | * @see #throwExceptionOnInputEnd(IOException)
109 | * @throws IllegalStateException if
110 | * {@link #throwExceptionOnInputEnd(IOException)} has been called before.
111 | */
112 | public void throwExceptionOnInputEnd(RuntimeException exception) {
113 | systemInMock.throwExceptionOnInputEnd(exception);
114 | }
115 |
116 | private String join(String[] texts) {
117 | StringBuilder sb = new StringBuilder();
118 | for (String text: texts)
119 | sb.append(text);
120 | return sb.toString();
121 | }
122 |
123 | private String joinLines(String[] lines) {
124 | StringBuilder sb = new StringBuilder();
125 | for (String line: lines)
126 | sb.append(line).append(getProperty("line.separator"));
127 | return sb.toString();
128 | }
129 |
130 | @Override
131 | protected void before() throws Throwable {
132 | originalIn = in;
133 | setIn(systemInMock);
134 | }
135 |
136 | @Override
137 | protected void after() {
138 | setIn(originalIn);
139 | }
140 |
141 | private static class SystemInMock extends InputStream {
142 | private StringReader currentReader;
143 | private IOException ioException;
144 | private RuntimeException runtimeException;
145 |
146 | void provideText(String text) {
147 | currentReader = new StringReader(text);
148 | }
149 |
150 | void throwExceptionOnInputEnd(IOException exception) {
151 | if (runtimeException != null)
152 | throw new IllegalStateException("You cannot call"
153 | + " throwExceptionOnInputEnd(IOException) because"
154 | + " throwExceptionOnInputEnd(RuntimeException) has already"
155 | + " been called.");
156 | ioException = exception;
157 | }
158 |
159 | void throwExceptionOnInputEnd(RuntimeException exception) {
160 | if (ioException != null)
161 | throw new IllegalStateException("You cannot call"
162 | + " throwExceptionOnInputEnd(RuntimeException) because"
163 | + " throwExceptionOnInputEnd(IOException) has already"
164 | + " been called.");
165 | runtimeException = exception;
166 | }
167 |
168 | @Override
169 | public int read() throws IOException {
170 | int character = currentReader.read();
171 | if (character == -1)
172 | handleEmptyReader();
173 | return character;
174 | }
175 |
176 | private void handleEmptyReader() throws IOException {
177 | if (ioException != null)
178 | throw ioException;
179 | else if (runtimeException != null)
180 | throw runtimeException;
181 | }
182 |
183 | @Override
184 | public int read(byte[] buffer, int offset, int len) throws IOException {
185 | if (buffer == null)
186 | throw new NullPointerException();
187 | else if (offset < 0 || len < 0 || len > buffer.length - offset)
188 | throw new IndexOutOfBoundsException();
189 | else if (len == 0)
190 | return 0;
191 | else
192 | return readNextLine(buffer, offset, len);
193 | }
194 |
195 | private int readNextLine(byte[] buffer, int offset, int len)
196 | throws IOException {
197 | int c = read();
198 | if (c == -1)
199 | return -1;
200 | buffer[offset] = (byte) c;
201 |
202 | int i = 1;
203 | for (; (i < len) && !isCompleteLineWritten(buffer, i - 1); ++i) {
204 | byte read = (byte) read();
205 | if (read == -1)
206 | break;
207 | else
208 | buffer[offset + i] = read;
209 | }
210 | return i;
211 | }
212 |
213 | private boolean isCompleteLineWritten(byte[] buffer,
214 | int indexLastByteWritten) {
215 | byte[] separator = getProperty("line.separator").getBytes();
216 | int indexFirstByteOfSeparator = indexLastByteWritten
217 | - separator.length + 1;
218 | return indexFirstByteOfSeparator >= 0
219 | && contains(buffer, separator, indexFirstByteOfSeparator);
220 | }
221 |
222 | private boolean contains(byte[] array, byte[] pattern, int indexStart) {
223 | for (int i = 0; i < pattern.length; ++i)
224 | if (array[indexStart + i] != pattern[i])
225 | return false;
226 | return true;
227 | }
228 | }
229 | }
230 |
--------------------------------------------------------------------------------
/src/main/java/org/junit/contrib/java/lang/system/internal/CheckExitCalled.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system.internal;
2 |
3 | public class CheckExitCalled extends SecurityException {
4 | private static final long serialVersionUID = 159678654L;
5 |
6 | private final Integer status;
7 |
8 | public CheckExitCalled(int status) {
9 | super("Tried to exit with status " + status + ".");
10 | this.status = status;
11 | }
12 |
13 | public Integer getStatus() {
14 | return status;
15 | }
16 | }
--------------------------------------------------------------------------------
/src/main/java/org/junit/contrib/java/lang/system/internal/DisallowWrite.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system.internal;
2 |
3 | import org.junit.runners.model.Statement;
4 |
5 | import java.io.IOException;
6 | import java.io.OutputStream;
7 |
8 | public class DisallowWrite {
9 | private final PrintStreamHandler printStreamHandler;
10 |
11 | public DisallowWrite(PrintStreamHandler printStreamHandler) {
12 | this.printStreamHandler = printStreamHandler;
13 | }
14 |
15 | public Statement createStatement(final Statement base) {
16 | return printStreamHandler.createRestoreStatement(new Statement() {
17 | @Override
18 | public void evaluate() throws Throwable {
19 | printStreamHandler.replaceCurrentStreamWithOutputStream(
20 | new DisallowWriteStream());
21 | base.evaluate();
22 | }
23 | });
24 | }
25 |
26 | private static class DisallowWriteStream extends OutputStream {
27 | @Override
28 | public void write(int b) throws IOException {
29 | throw new AssertionError("Tried to write '" + (char) b
30 | + "' although this is not allowed.");
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/org/junit/contrib/java/lang/system/internal/LogPrintStream.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system.internal;
2 |
3 | import java.io.ByteArrayOutputStream;
4 | import java.io.IOException;
5 | import java.io.OutputStream;
6 | import java.io.UnsupportedEncodingException;
7 |
8 | import org.junit.runners.model.Statement;
9 |
10 | import static java.lang.System.getProperty;
11 |
12 | public class LogPrintStream {
13 | private final PrintStreamHandler printStreamHandler;
14 | private final MuteableLogStream muteableLogStream;
15 |
16 | public LogPrintStream(PrintStreamHandler printStreamHandler) {
17 | this.printStreamHandler = printStreamHandler;
18 | this.muteableLogStream = new MuteableLogStream(printStreamHandler.getStream());
19 | }
20 |
21 | public Statement createStatement(final Statement base) {
22 | return new Statement() {
23 | @Override
24 | public void evaluate() throws Throwable {
25 | try {
26 | printStreamHandler.createRestoreStatement(new Statement() {
27 | @Override
28 | public void evaluate() throws Throwable {
29 | printStreamHandler.replaceCurrentStreamWithOutputStream(muteableLogStream);
30 | base.evaluate();
31 | }
32 | }).evaluate();
33 | } catch (Throwable e) {
34 | muteableLogStream.failureLog.writeTo(printStreamHandler.getStream());
35 | throw e;
36 | }
37 | }
38 | };
39 | }
40 |
41 | public void clearLog() {
42 | muteableLogStream.log.reset();
43 | }
44 |
45 | public void enableLog() {
46 | muteableLogStream.logMuted = false;
47 | }
48 |
49 | public String getLog() {
50 | /* The MuteableLogStream is created with the default encoding
51 | * because it writes to System.out or System.err if not muted and
52 | * System.out/System.err uses the default encoding. As a result all
53 | * other streams receive input that is encoded with the default
54 | * encoding.
55 | */
56 | String encoding = getProperty("file.encoding");
57 | try {
58 | return muteableLogStream.log.toString(encoding);
59 | } catch (UnsupportedEncodingException e) {
60 | throw new RuntimeException(e);
61 | }
62 | }
63 |
64 | public String getLogWithNormalizedLineSeparator() {
65 | String lineSeparator = getProperty("line.separator");
66 | return getLog().replace(lineSeparator, "\n");
67 | }
68 |
69 | public byte[] getLogAsBytes() {
70 | return muteableLogStream.log.toByteArray();
71 | }
72 |
73 | public void mute() {
74 | muteableLogStream.originalStreamMuted = true;
75 | }
76 |
77 | public void muteForSuccessfulTests() {
78 | mute();
79 | muteableLogStream.failureLogMuted = false;
80 | }
81 |
82 | private static class MuteableLogStream extends OutputStream {
83 | final OutputStream originalStream;
84 | final ByteArrayOutputStream failureLog = new ByteArrayOutputStream();
85 | final ByteArrayOutputStream log = new ByteArrayOutputStream();
86 | boolean originalStreamMuted = false;
87 | boolean failureLogMuted = true;
88 | boolean logMuted = true;
89 |
90 | MuteableLogStream(OutputStream originalStream) {
91 | this.originalStream = originalStream;
92 | }
93 |
94 | @Override
95 | public void write(int b) throws IOException {
96 | if (!originalStreamMuted)
97 | originalStream.write(b);
98 | if (!failureLogMuted)
99 | failureLog.write(b);
100 | if (!logMuted)
101 | log.write(b);
102 | }
103 |
104 | @Override
105 | public void flush() throws IOException {
106 | originalStream.flush();
107 | //ByteArrayOutputStreams don't have to be closed
108 | }
109 |
110 | @Override
111 | public void close() throws IOException {
112 | originalStream.close();
113 | //ByteArrayOutputStreams don't have to be closed
114 | }
115 | }
116 | }
117 |
--------------------------------------------------------------------------------
/src/main/java/org/junit/contrib/java/lang/system/internal/NoExitSecurityManager.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system.internal;
2 |
3 | import java.io.FileDescriptor;
4 | import java.net.InetAddress;
5 | import java.security.Permission;
6 |
7 | /**
8 | * A {@code NoExitSecurityManager} throws a {@link CheckExitCalled} exception
9 | * whenever {@link #checkExit(int)} is called. All other method calls are
10 | * delegated to the original security manager.
11 | */
12 | public class NoExitSecurityManager extends SecurityManager {
13 | private final SecurityManager originalSecurityManager;
14 | private Integer statusOfFirstExitCall = null;
15 |
16 | public NoExitSecurityManager(SecurityManager originalSecurityManager) {
17 | this.originalSecurityManager = originalSecurityManager;
18 | }
19 |
20 | @Override
21 | public void checkExit(int status) {
22 | if (statusOfFirstExitCall == null)
23 | statusOfFirstExitCall = status;
24 | throw new CheckExitCalled(status);
25 | }
26 |
27 | public boolean isCheckExitCalled() {
28 | return statusOfFirstExitCall != null;
29 | }
30 |
31 | public int getStatusOfFirstCheckExitCall() {
32 | if (isCheckExitCalled())
33 | return statusOfFirstExitCall;
34 | else
35 | throw new IllegalStateException(
36 | "checkExit(int) has not been called.");
37 | }
38 |
39 | @Override
40 | public boolean getInCheck() {
41 | return (originalSecurityManager != null)
42 | && originalSecurityManager.getInCheck();
43 | }
44 |
45 | @Override
46 | public Object getSecurityContext() {
47 | return (originalSecurityManager == null) ? super.getSecurityContext()
48 | : originalSecurityManager.getSecurityContext();
49 | }
50 |
51 | @Override
52 | public void checkPermission(Permission perm) {
53 | if (originalSecurityManager != null)
54 | originalSecurityManager.checkPermission(perm);
55 | }
56 |
57 | @Override
58 | public void checkPermission(Permission perm, Object context) {
59 | if (originalSecurityManager != null)
60 | originalSecurityManager.checkPermission(perm, context);
61 | }
62 |
63 | @Override
64 | public void checkCreateClassLoader() {
65 | if (originalSecurityManager != null)
66 | originalSecurityManager.checkCreateClassLoader();
67 | }
68 |
69 | @Override
70 | public void checkAccess(Thread t) {
71 | if (originalSecurityManager != null)
72 | originalSecurityManager.checkAccess(t);
73 | }
74 |
75 | @Override
76 | public void checkAccess(ThreadGroup g) {
77 | if (originalSecurityManager != null)
78 | originalSecurityManager.checkAccess(g);
79 | }
80 |
81 | @Override
82 | public void checkExec(String cmd) {
83 | if (originalSecurityManager != null)
84 | originalSecurityManager.checkExec(cmd);
85 | }
86 |
87 | @Override
88 | public void checkLink(String lib) {
89 | if (originalSecurityManager != null)
90 | originalSecurityManager.checkLink(lib);
91 | }
92 |
93 | @Override
94 | public void checkRead(FileDescriptor fd) {
95 | if (originalSecurityManager != null)
96 | originalSecurityManager.checkRead(fd);
97 | }
98 |
99 | @Override
100 | public void checkRead(String file) {
101 | if (originalSecurityManager != null)
102 | originalSecurityManager.checkRead(file);
103 | }
104 |
105 | @Override
106 | public void checkRead(String file, Object context) {
107 | if (originalSecurityManager != null)
108 | originalSecurityManager.checkRead(file, context);
109 | }
110 |
111 | @Override
112 | public void checkWrite(FileDescriptor fd) {
113 | if (originalSecurityManager != null)
114 | originalSecurityManager.checkWrite(fd);
115 | }
116 |
117 | @Override
118 | public void checkWrite(String file) {
119 | if (originalSecurityManager != null)
120 | originalSecurityManager.checkWrite(file);
121 | }
122 |
123 | @Override
124 | public void checkDelete(String file) {
125 | if (originalSecurityManager != null)
126 | originalSecurityManager.checkDelete(file);
127 | }
128 |
129 | @Override
130 | public void checkConnect(String host, int port) {
131 | if (originalSecurityManager != null)
132 | originalSecurityManager.checkConnect(host, port);
133 | }
134 |
135 | @Override
136 | public void checkConnect(String host, int port, Object context) {
137 | if (originalSecurityManager != null)
138 | originalSecurityManager.checkConnect(host, port, context);
139 | }
140 |
141 | @Override
142 | public void checkListen(int port) {
143 | if (originalSecurityManager != null)
144 | originalSecurityManager.checkListen(port);
145 | }
146 |
147 | @Override
148 | public void checkAccept(String host, int port) {
149 | if (originalSecurityManager != null)
150 | originalSecurityManager.checkAccept(host, port);
151 | }
152 |
153 | @Override
154 | public void checkMulticast(InetAddress maddr) {
155 | if (originalSecurityManager != null)
156 | originalSecurityManager.checkMulticast(maddr);
157 | }
158 |
159 | @Override
160 | public void checkMulticast(InetAddress maddr, byte ttl) {
161 | if (originalSecurityManager != null)
162 | originalSecurityManager.checkMulticast(maddr, ttl);
163 | }
164 |
165 | @Override
166 | public void checkPropertiesAccess() {
167 | if (originalSecurityManager != null)
168 | originalSecurityManager.checkPropertiesAccess();
169 | }
170 |
171 | @Override
172 | public void checkPropertyAccess(String key) {
173 | if (originalSecurityManager != null)
174 | originalSecurityManager.checkPropertyAccess(key);
175 | }
176 |
177 | @Override
178 | public boolean checkTopLevelWindow(Object window) {
179 | return (originalSecurityManager == null) ? super.checkTopLevelWindow(window)
180 | : originalSecurityManager.checkTopLevelWindow(window);
181 | }
182 |
183 | @Override
184 | public void checkPrintJobAccess() {
185 | if (originalSecurityManager != null)
186 | originalSecurityManager.checkPrintJobAccess();
187 | }
188 |
189 | @Override
190 | public void checkSystemClipboardAccess() {
191 | if (originalSecurityManager != null)
192 | originalSecurityManager.checkSystemClipboardAccess();
193 | }
194 |
195 | @Override
196 | public void checkAwtEventQueueAccess() {
197 | if (originalSecurityManager != null)
198 | originalSecurityManager.checkAwtEventQueueAccess();
199 | }
200 |
201 | @Override
202 | public void checkPackageAccess(String pkg) {
203 | if (originalSecurityManager != null)
204 | originalSecurityManager.checkPackageAccess(pkg);
205 | }
206 |
207 | @Override
208 | public void checkPackageDefinition(String pkg) {
209 | if (originalSecurityManager != null)
210 | originalSecurityManager.checkPackageDefinition(pkg);
211 | }
212 |
213 | @Override
214 | public void checkSetFactory() {
215 | if (originalSecurityManager != null)
216 | originalSecurityManager.checkSetFactory();
217 | }
218 |
219 | @Override
220 | public void checkMemberAccess(Class> clazz, int which) {
221 | if (originalSecurityManager != null)
222 | originalSecurityManager.checkMemberAccess(clazz, which);
223 | }
224 |
225 | @Override
226 | public void checkSecurityAccess(String target) {
227 | if (originalSecurityManager != null)
228 | originalSecurityManager.checkSecurityAccess(target);
229 | }
230 |
231 | @Override
232 | public ThreadGroup getThreadGroup() {
233 | return (originalSecurityManager == null) ? super.getThreadGroup()
234 | : originalSecurityManager.getThreadGroup();
235 | }
236 | }
237 |
--------------------------------------------------------------------------------
/src/main/java/org/junit/contrib/java/lang/system/internal/PrintStreamHandler.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system.internal;
2 |
3 | import static java.lang.System.err;
4 | import static java.lang.System.out;
5 | import static java.lang.System.setErr;
6 | import static java.lang.System.setOut;
7 |
8 | import java.io.OutputStream;
9 | import java.io.PrintStream;
10 | import java.io.UnsupportedEncodingException;
11 | import java.nio.charset.Charset;
12 |
13 | import org.junit.runners.model.Statement;
14 |
15 | public enum PrintStreamHandler {
16 | SYSTEM_OUT {
17 | @Override
18 | PrintStream getStream() {
19 | return out;
20 | }
21 |
22 | @Override
23 | void replaceCurrentStreamWithPrintStream(PrintStream stream) {
24 | setOut(stream);
25 | }
26 | },
27 | SYSTEM_ERR {
28 | @Override
29 | PrintStream getStream() {
30 | return err;
31 | }
32 |
33 | @Override
34 | void replaceCurrentStreamWithPrintStream(PrintStream stream) {
35 | setErr(stream);
36 | }
37 | };
38 |
39 | private static final boolean AUTO_FLUSH = true;
40 | private static final String DEFAULT_ENCODING = Charset.defaultCharset().name();
41 |
42 | Statement createRestoreStatement(final Statement base) {
43 | return new Statement() {
44 | @Override
45 | public void evaluate() throws Throwable {
46 | PrintStream originalStream = getStream();
47 | try {
48 | base.evaluate();
49 | } finally {
50 | replaceCurrentStreamWithPrintStream(originalStream);
51 | }
52 | }
53 | };
54 | }
55 |
56 | void replaceCurrentStreamWithOutputStream(OutputStream outputStream)
57 | throws UnsupportedEncodingException {
58 | PrintStream printStream = new PrintStream(
59 | outputStream, AUTO_FLUSH, DEFAULT_ENCODING);
60 | replaceCurrentStreamWithPrintStream(printStream);
61 | }
62 |
63 | abstract PrintStream getStream();
64 |
65 | abstract void replaceCurrentStreamWithPrintStream(PrintStream stream);
66 | }
67 |
--------------------------------------------------------------------------------
/src/main/java/org/junit/contrib/java/lang/system/internal/RestoreSpecificSystemProperties.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system.internal;
2 |
3 | import static java.lang.System.*;
4 |
5 | import java.util.ArrayList;
6 | import java.util.Iterator;
7 | import java.util.List;
8 |
9 |
10 | public class RestoreSpecificSystemProperties {
11 | private final List properties = new ArrayList();
12 | private final List originalValues = new ArrayList();
13 |
14 | public void add(String property) {
15 | properties.add(property);
16 | originalValues.add(getProperty(property));
17 | }
18 |
19 | public void restore() {
20 | Iterator itOriginalValues = originalValues.iterator();
21 | for (String property : properties)
22 | restore(property, itOriginalValues.next());
23 | }
24 |
25 | private void restore(String property, String originalValue) {
26 | if (originalValue == null)
27 | clearProperty(property);
28 | else
29 | setProperty(property, originalValue);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/test/java/org/junit/contrib/java/lang/system/AcceptanceTestRunner.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 | import org.junit.*;
4 | import org.junit.internal.AssumptionViolatedException;
5 | import org.junit.internal.runners.model.EachTestNotifier;
6 | import org.junit.internal.runners.statements.RunAfters;
7 | import org.junit.internal.runners.statements.RunBefores;
8 | import org.junit.rules.RunRules;
9 | import org.junit.rules.TestRule;
10 | import org.junit.runner.Description;
11 | import org.junit.runner.notification.Failure;
12 | import org.junit.runner.notification.RunNotifier;
13 | import org.junit.runners.BlockJUnit4ClassRunner;
14 | import org.junit.runners.model.*;
15 |
16 | import java.lang.reflect.InvocationTargetException;
17 | import java.lang.reflect.Method;
18 | import java.util.Collection;
19 | import java.util.List;
20 |
21 | import static java.util.Collections.emptyList;
22 | import static java.util.Collections.singleton;
23 |
24 | public class AcceptanceTestRunner extends BlockJUnit4ClassRunner {
25 | private static final Collection NO_FAILURES = emptyList();
26 | private final Method expectFailure;
27 | private final Method verifyStateAfterTest;
28 | private final Method verifyResult;
29 | private final TestClass testClass;
30 |
31 | public AcceptanceTestRunner(Class> testClass) throws InitializationError {
32 | super(extractInnerTestClass(testClass));
33 | expectFailure = extractMethod(testClass, "expectFailure", Failure.class);
34 | verifyResult = extractMethod(testClass, "verifyResult", Collection.class);
35 | verifyStateAfterTest = extractMethod(testClass, "verifyStateAfterTest");
36 | this.testClass = new TestClass(testClass);
37 | verifyCheckPresent();
38 | }
39 |
40 | private static Class> extractInnerTestClass(Class> testClass)
41 | throws InitializationError {
42 | Class>[] innerClasses = testClass.getClasses();
43 | if (innerClasses.length > 1)
44 | throw new InitializationError("The class " + testClass
45 | + " has " + innerClasses.length + " inner classes, but only"
46 | + " one inner class with name TestClass is expected.");
47 | else if (innerClasses.length == 0
48 | || !innerClasses[0].getSimpleName().equals("TestClass"))
49 | throw new InitializationError("The class " + testClass
50 | + " has no inner class with name TestClass.");
51 | else
52 | return innerClasses[0];
53 | }
54 |
55 | private void verifyCheckPresent() {
56 | boolean noCheck = expectFailure == null
57 | && verifyResult == null
58 | && verifyStateAfterTest == null;
59 | if (noCheck)
60 | throw new IllegalStateException(
61 | "No expectation is defined for the test " + getName()
62 | + ". It needs either a method expectFailure, verifyResult or verifyStateAfterTest.");
63 | }
64 |
65 | private static Method extractMethod(Class> testClass, String name, Class>... parameterTypes) {
66 | try {
67 | return testClass.getMethod(name, parameterTypes);
68 | } catch (NoSuchMethodException e) {
69 | return null;
70 | }
71 | }
72 |
73 | @Override
74 | protected void runChild(final FrameworkMethod method, RunNotifier notifier) {
75 | Description description = describeChild(method);
76 | if (method.getAnnotation(Ignore.class) != null)
77 | notifier.fireTestIgnored(description);
78 | else
79 | runTest(methodBlock(method), description, notifier);
80 | }
81 |
82 | protected Statement classBlock(final RunNotifier notifier) {
83 | Statement statement = super.classBlock(notifier);
84 | statement = withBeforeClasses(statement);
85 | statement = withAfterClasses(statement);
86 | statement = withClassRules(statement);
87 | return statement;
88 | }
89 |
90 | protected Statement withBeforeClasses(Statement statement) {
91 | List befores = testClass
92 | .getAnnotatedMethods(BeforeClass.class);
93 | return befores.isEmpty() ? statement :
94 | new RunBefores(statement, befores, null);
95 | }
96 |
97 | protected Statement withAfterClasses(Statement statement) {
98 | List afters = testClass
99 | .getAnnotatedMethods(AfterClass.class);
100 | return afters.isEmpty() ? statement :
101 | new RunAfters(statement, afters, null);
102 | }
103 |
104 | private Statement withClassRules(Statement statement) {
105 | List classRules = classRules();
106 | return classRules.isEmpty() ? statement :
107 | new RunRules(statement, classRules, getDescription());
108 | }
109 |
110 | protected List classRules() {
111 | return testClass.getAnnotatedFieldValues(
112 | null, ClassRule.class, TestRule.class);
113 | }
114 |
115 | private void runTest(Statement statement, Description description,
116 | RunNotifier notifier) {
117 | EachTestNotifier eachNotifier = new EachTestNotifier(notifier, description);
118 | eachNotifier.fireTestStarted();
119 | try {
120 | statement.evaluate();
121 | handleNoFailure(eachNotifier);
122 | } catch (AssumptionViolatedException e) {
123 | handleFailedAssumption(description, eachNotifier, e);
124 | } catch (Throwable e) {
125 | handleException(description, eachNotifier, e);
126 | } finally {
127 | invokeIfPresent(verifyStateAfterTest, eachNotifier);
128 | eachNotifier.fireTestFinished();
129 | }
130 | }
131 |
132 | private void handleNoFailure(EachTestNotifier eachNotifier) {
133 | if (expectFailure != null)
134 | eachNotifier.addFailure(new AssertionError("Test did not fail."));
135 | invokeIfPresent(verifyResult, eachNotifier, NO_FAILURES);
136 | }
137 |
138 | private void handleFailedAssumption(Description description, EachTestNotifier eachNotifier, AssumptionViolatedException e) {
139 | eachNotifier.addFailedAssumption(e);
140 | if (expectFailure != null)
141 | eachNotifier.addFailure(new AssertionError("Test did not fail."));
142 | invokeIfPresent(
143 | verifyResult, eachNotifier, singleton(new Failure(description, e)));
144 | }
145 |
146 | private void handleException(Description description, EachTestNotifier eachNotifier,
147 | Throwable e) {
148 | invokeIfPresent(
149 | verifyResult, eachNotifier, singleton(new Failure(description, e)));
150 | invokeIfPresent(
151 | expectFailure, eachNotifier, new Failure(description, e));
152 | if (expectFailure == null && verifyResult == null)
153 | eachNotifier.addFailure(e);
154 | }
155 |
156 | private void invokeIfPresent(Method method, EachTestNotifier notifier, Object... args) {
157 | if (method != null)
158 | try {
159 | method.invoke(null, args);
160 | } catch (IllegalAccessException e) {
161 | fail(notifier, e, "Failed to invoke '" + method.getName() + "'.");
162 | } catch (InvocationTargetException e) {
163 | fail(notifier, e, "Failed to invoke '" + method.getName() + "'.");
164 | } catch (Exception e) {
165 | notifier.addFailure(e);
166 | }
167 | }
168 |
169 | private void fail(EachTestNotifier eachNotifier, InvocationTargetException e, String message) {
170 | if (e.getCause() instanceof AssertionError)
171 | eachNotifier.addFailure(e.getCause());
172 | else
173 | fail(eachNotifier, (Exception) e, message);
174 | }
175 |
176 | private void fail(EachTestNotifier eachNotifier, Exception e, String message) {
177 | AssertionError error = new AssertionError(message);
178 | error.initCause(e);
179 | eachNotifier.addFailure(error);
180 | }
181 | }
182 |
--------------------------------------------------------------------------------
/src/test/java/org/junit/contrib/java/lang/system/ClearSystemPropertiesTest.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 | import static java.lang.System.*;
4 | import static org.assertj.core.api.Assertions.assertThat;
5 |
6 | import org.junit.*;
7 | import org.junit.experimental.runners.Enclosed;
8 | import org.junit.runner.RunWith;
9 | import org.junit.runner.notification.Failure;
10 |
11 | import java.util.Collection;
12 |
13 | @RunWith(Enclosed.class)
14 | public class ClearSystemPropertiesTest {
15 | @RunWith(AcceptanceTestRunner.class)
16 | public static class properties_are_cleared_at_start_of_test {
17 | @ClassRule
18 | public static final RestoreSystemProperties RESTORE
19 | = new RestoreSystemProperties();
20 |
21 | @BeforeClass
22 | public static void populateProperties() {
23 | setProperty("first property", "dummy value");
24 | setProperty("second property", "another dummy value");
25 | }
26 |
27 | public static class TestClass {
28 | @Rule
29 | public final ClearSystemProperties clearSystemProperties
30 | = new ClearSystemProperties("first property", "second property");
31 |
32 | @Test
33 | public void test() {
34 | assertThat(getProperty("first property")).isNull();
35 | assertThat(getProperty("second property")).isNull();
36 | }
37 | }
38 |
39 | public static void verifyResult(Collection failures) {
40 | assertThat(failures).isEmpty();
41 | }
42 | }
43 |
44 | @RunWith(AcceptanceTestRunner.class)
45 | public static class property_is_cleared_after_added_to_rule_within_test {
46 | @ClassRule
47 | public static final RestoreSystemProperties RESTORE
48 | = new RestoreSystemProperties();
49 |
50 | @BeforeClass
51 | public static void populateProperty() {
52 | setProperty("property", "dummy value");
53 | }
54 |
55 | public static class TestClass {
56 | @Rule
57 | public final ClearSystemProperties clearSystemProperties
58 | = new ClearSystemProperties();
59 |
60 | @Test
61 | public void test() {
62 | clearSystemProperties.clearProperty("property");
63 | assertThat(getProperty("property")).isNull();
64 | }
65 | }
66 |
67 | public static void verifyResult(Collection failures) {
68 | assertThat(failures).isEmpty();
69 | }
70 | }
71 |
72 | @RunWith(AcceptanceTestRunner.class)
73 | public static class after_test_properties_have_the_same_values_as_before {
74 | @ClassRule
75 | public static final RestoreSystemProperties RESTORE
76 | = new RestoreSystemProperties();
77 |
78 | @BeforeClass
79 | public static void populateProperty() {
80 | setProperty("first property", "dummy value");
81 | setProperty("second property", "another dummy value");
82 | setProperty("third property", "another dummy value");
83 | }
84 |
85 | public static class TestClass {
86 | @Rule
87 | public final ClearSystemProperties clearSystemProperties
88 | = new ClearSystemProperties("first property", "second property");
89 |
90 | @Test
91 | public void test() {
92 | clearSystemProperties.clearProperty("third property");
93 | }
94 | }
95 |
96 | public static void verifyStateAfterTest() {
97 | assertThat(getProperty("first property")).isEqualTo("dummy value");
98 | assertThat(getProperty("second property")).isEqualTo("another dummy value");
99 | assertThat(getProperty("third property")).isEqualTo("another dummy value");
100 | }
101 | }
102 |
103 | @RunWith(AcceptanceTestRunner.class)
104 | public static class property_that_is_not_present_does_not_cause_failure {
105 | @ClassRule
106 | public static final RestoreSystemProperties RESTORE
107 | = new RestoreSystemProperties();
108 |
109 | @BeforeClass
110 | public static void ensurePropertyIsNotPresent() {
111 | clearProperty("property");
112 | }
113 |
114 | public static class TestClass {
115 | @Rule
116 | public final ClearSystemProperties clearSystemProperties
117 | = new ClearSystemProperties("property");
118 |
119 | @Test
120 | public void test() {
121 | }
122 | }
123 |
124 | public static void verifyResult(Collection failures) {
125 | assertThat(failures).isEmpty();
126 | }
127 | }
128 | }
129 |
--------------------------------------------------------------------------------
/src/test/java/org/junit/contrib/java/lang/system/EnvironmentVariablesTest.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 |
4 | import org.junit.BeforeClass;
5 | import org.junit.Rule;
6 | import org.junit.Test;
7 | import org.junit.experimental.runners.Enclosed;
8 | import org.junit.runner.RunWith;
9 | import org.junit.runner.notification.Failure;
10 |
11 | import java.util.HashMap;
12 | import java.util.Map;
13 |
14 | import static java.lang.System.getenv;
15 | import static java.util.UUID.randomUUID;
16 | import static org.assertj.core.api.Assertions.assertThat;
17 |
18 | @RunWith(Enclosed.class)
19 | public class EnvironmentVariablesTest {
20 | @RunWith(Enclosed.class)
21 | public static class modification_before_the_test {
22 | @RunWith(AcceptanceTestRunner.class)
23 | public static class after_a_successful_test_environment_variables_map_contains_same_values_as_before {
24 | private static Map originalEnvironmentVariables;
25 |
26 | @BeforeClass
27 | public static void captureEnviromentVariables() {
28 | originalEnvironmentVariables = new HashMap(getenv());
29 | }
30 |
31 | public static class TestClass {
32 | @Rule
33 | public final EnvironmentVariables environmentVariables = new EnvironmentVariables()
34 | .set("dummy name", randomValue());
35 |
36 | @Test
37 | public void test() {
38 | }
39 | }
40 |
41 | public static void verifyStateAfterTest() {
42 | assertThat(getenv()).isEqualTo(originalEnvironmentVariables);
43 | }
44 | }
45 |
46 | @RunWith(AcceptanceTestRunner.class)
47 | public static class after_a_successful_test_environment_variables_are_the_same_as_before {
48 | private static String originalValue;
49 |
50 |
51 | @BeforeClass
52 | public static void captureValue() {
53 | originalValue = getenv("dummy name");
54 | }
55 |
56 | public static class TestClass {
57 | @Rule
58 | public final EnvironmentVariables environmentVariables = new EnvironmentVariables()
59 | .set("dummy name", randomValue());
60 |
61 | @Test
62 | public void test() {
63 | }
64 | }
65 |
66 | public static void verifyStateAfterTest() {
67 | assertThat(getenv("dummy name")).isEqualTo(originalValue);
68 | }
69 | }
70 |
71 | @RunWith(AcceptanceTestRunner.class)
72 | public static class after_a_test_that_throws_an_exception_environment_variables_map_contains_same_values_as_before {
73 | private static Map originalEnvironmentVariables;
74 |
75 | @BeforeClass
76 | public static void captureEnviromentVariables() {
77 | originalEnvironmentVariables = new HashMap(getenv());
78 | }
79 |
80 | public static class TestClass {
81 | @Rule
82 | public final EnvironmentVariables environmentVariables = new EnvironmentVariables()
83 | .set("dummy name", randomValue());
84 |
85 | @Test
86 | public void test() {
87 | throw new RuntimeException("dummy exception");
88 | }
89 | }
90 |
91 | public static void expectFailure(Failure failure) {
92 | assertThat(getenv()).isEqualTo(originalEnvironmentVariables);
93 | }
94 | }
95 |
96 | @RunWith(AcceptanceTestRunner.class)
97 | public static class after_a_test_that_throws_an_exception_environment_variables_are_the_same_as_before {
98 | private static String originalValue;
99 |
100 | @BeforeClass
101 | public static void captureValue() {
102 | originalValue = getenv("dummy name");
103 | }
104 |
105 | public static class TestClass {
106 | @Rule
107 | public final EnvironmentVariables environmentVariables = new EnvironmentVariables()
108 | .set("dummy name", randomValue());
109 |
110 | @Test
111 | public void test() {
112 | throw new RuntimeException("dummy exception");
113 | }
114 | }
115 |
116 | public static void expectFailure(Failure failure) {
117 | assertThat(getenv("dummy name")).isEqualTo(originalValue);
118 | }
119 | }
120 |
121 | public static class environment_variable_that_is_set_by_the_rule_is_available_in_the_test {
122 | @Rule
123 | public final EnvironmentVariables environmentVariables = new EnvironmentVariables()
124 | .set("dummy name", "dummy value");
125 |
126 | @Test
127 | public void test() {
128 | assertThat(getenv("dummy name")).isEqualTo("dummy value");
129 | }
130 | }
131 |
132 | public static class environment_variable_that_is_set_by_the_rule_is_available_from_environment_variables_map {
133 | @Rule
134 | public final EnvironmentVariables environmentVariables = new EnvironmentVariables()
135 | .set("dummy name", "dummy value");
136 |
137 | @Test
138 | public void test() {
139 | assertThat(getenv()).containsEntry("dummy name", "dummy value");
140 | }
141 | }
142 |
143 | public static class environment_variable_that_is_set_to_null_by_the_rule_is_null_in_the_test {
144 | @Rule
145 | public final EnvironmentVariables environmentVariables = new EnvironmentVariables()
146 | //we need to set a value because it is null by default
147 | .set("dummy name", randomValue())
148 | .set("dummy name", null);
149 |
150 | @Test
151 | public void test() {
152 | assertThat(getenv("dummy name")).isNull();
153 | }
154 | }
155 |
156 | public static class environment_variable_that_is_set_to_null_by_the_rule_is_not_stored_in_the_environment_variables_map {
157 | @Rule
158 | public final EnvironmentVariables environmentVariables = new EnvironmentVariables()
159 | //we need to set a value because it is null by default
160 | .set("dummy name", randomValue())
161 | .set("dummy name", null);
162 |
163 | @Test
164 | public void test() {
165 | assertThat(getenv()).doesNotContainKey("dummy name");
166 | }
167 | }
168 |
169 | public static class environment_variables_that_are_cleared_by_the_rule_are_null_in_the_test {
170 | @Rule
171 | public final EnvironmentVariables environmentVariables = new EnvironmentVariables()
172 | //we need to set a value because it is null by default
173 | .set("dummy name", randomValue())
174 | .set("another name", randomValue())
175 | .clear("dummy name", "another name");
176 |
177 | @Test
178 | public void test() {
179 | assertThat(getenv("dummy name")).isNull();
180 | assertThat(getenv("another name")).isNull();
181 | }
182 | }
183 |
184 | public static class environment_variables_that_are_cleared_by_the_rule_are_not_stored_in_the_environment_variables_map {
185 | @Rule
186 | public final EnvironmentVariables environmentVariables = new EnvironmentVariables()
187 | //we need to set a value because it is null by default
188 | .set("dummy name", randomValue())
189 | .set("another name", randomValue())
190 | .clear("dummy name", "another name");
191 |
192 | @Test
193 | public void test() {
194 | assertThat(getenv())
195 | .doesNotContainKey("dummy name")
196 | .doesNotContainKey("another name");
197 | }
198 | }
199 | }
200 |
201 | @RunWith(Enclosed.class)
202 | public static class modification_within_the_test {
203 | @RunWith(AcceptanceTestRunner.class)
204 | public static class after_a_successful_test_environment_variables_map_contains_same_values_as_before {
205 | private static Map originalEnvironmentVariables;
206 |
207 | @BeforeClass
208 | public static void captureEnviromentVariables() {
209 | originalEnvironmentVariables = new HashMap(getenv());
210 | }
211 |
212 | public static class TestClass {
213 | @Rule
214 | public final EnvironmentVariables environmentVariables = new EnvironmentVariables();
215 |
216 | @Test
217 | public void test() {
218 | environmentVariables.set("dummy name", randomValue());
219 | }
220 | }
221 |
222 | public static void verifyStateAfterTest() {
223 | assertThat(getenv()).isEqualTo(originalEnvironmentVariables);
224 | }
225 | }
226 |
227 | @RunWith(AcceptanceTestRunner.class)
228 | public static class after_a_successful_test_environment_variables_are_the_same_as_before {
229 | private static String originalValue;
230 |
231 | @BeforeClass
232 | public static void captureValue() {
233 | originalValue = getenv("dummy name");
234 | }
235 |
236 | public static class TestClass {
237 | @Rule
238 | public final EnvironmentVariables environmentVariables = new EnvironmentVariables();
239 |
240 | @Test
241 | public void test() {
242 | environmentVariables.set("dummy name", randomValue());
243 | }
244 | }
245 |
246 | public static void verifyStateAfterTest() {
247 | assertThat(getenv("dummy name")).isEqualTo(originalValue);
248 | }
249 | }
250 |
251 | @RunWith(AcceptanceTestRunner.class)
252 | public static class after_a_test_that_throws_an_exception_environment_variables_map_contains_same_values_as_before {
253 | private static Map originalEnvironmentVariables;
254 |
255 | @BeforeClass
256 | public static void captureEnviromentVariables() {
257 | originalEnvironmentVariables = new HashMap(getenv());
258 | }
259 |
260 | public static class TestClass {
261 | @Rule
262 | public final EnvironmentVariables environmentVariables = new EnvironmentVariables();
263 |
264 | @Test
265 | public void test() {
266 | environmentVariables.set("dummy name", randomValue());
267 | throw new RuntimeException("dummy exception");
268 | }
269 | }
270 |
271 | public static void expectFailure(Failure failure) {
272 | assertThat(getenv()).isEqualTo(originalEnvironmentVariables);
273 | }
274 | }
275 |
276 | @RunWith(AcceptanceTestRunner.class)
277 | public static class after_a_test_that_throws_an_exception_environment_variables_are_the_same_as_before {
278 | private static String originalValue;
279 |
280 | @BeforeClass
281 | public static void captureValue() {
282 | originalValue = getenv("dummy name");
283 | }
284 |
285 | public static class TestClass {
286 | @Rule
287 | public final EnvironmentVariables environmentVariables = new EnvironmentVariables();
288 |
289 | @Test
290 | public void test() {
291 | environmentVariables.set("dummy name", randomValue());
292 | throw new RuntimeException("dummy exception");
293 | }
294 | }
295 |
296 | public static void expectFailure(Failure failure) {
297 | assertThat(getenv("dummy name")).isEqualTo(originalValue);
298 | }
299 | }
300 |
301 | public static class environment_variable_that_is_set_by_the_rule_is_available_in_the_test {
302 | @Rule
303 | public final EnvironmentVariables environmentVariables = new EnvironmentVariables();
304 |
305 | @Test
306 | public void test() {
307 | environmentVariables.set("dummy name", "dummy value");
308 | assertThat(getenv("dummy name")).isEqualTo("dummy value");
309 | }
310 | }
311 |
312 | public static class environment_variable_that_is_set_by_the_rule_is_available_from_environment_variables_map {
313 | @Rule
314 | public final EnvironmentVariables environmentVariables = new EnvironmentVariables();
315 |
316 | @Test
317 | public void test() {
318 | environmentVariables.set("dummy name", "dummy value");
319 | assertThat(getenv()).containsEntry("dummy name", "dummy value");
320 | }
321 | }
322 |
323 | public static class environment_variable_that_is_set_to_null_by_the_rule_is_null_in_the_test {
324 | @Rule
325 | public final EnvironmentVariables environmentVariables = new EnvironmentVariables();
326 |
327 | @Test
328 | public void test() {
329 | //we need to set a value because it is null by default
330 | environmentVariables.set("dummy name", randomValue());
331 | environmentVariables.set("dummy name", null);
332 | assertThat(getenv("dummy name")).isNull();
333 | }
334 | }
335 |
336 | public static class environment_variable_that_is_set_to_null_by_the_rule_is_not_stored_in_the_environment_variables_map {
337 | @Rule
338 | public final EnvironmentVariables environmentVariables = new EnvironmentVariables();
339 |
340 | @Test
341 | public void test() {
342 | //we need to set a value because it is null by default
343 | environmentVariables.set("dummy name", randomValue());
344 | environmentVariables.set("dummy name", null);
345 | assertThat(getenv()).doesNotContainKey("dummy name");
346 | }
347 | }
348 |
349 | public static class environment_variables_that_are_cleared_by_the_rule_are_null_in_the_test {
350 | @Rule
351 | public final EnvironmentVariables environmentVariables = new EnvironmentVariables();
352 |
353 | @Test
354 | public void test() {
355 | //we need to set a value because it is null by default
356 | environmentVariables.set("dummy name", randomValue());
357 | environmentVariables.set("another name", randomValue());
358 | environmentVariables.clear("dummy name", "another name");
359 | assertThat(getenv("dummy name")).isNull();
360 | assertThat(getenv("another name")).isNull();
361 | }
362 | }
363 |
364 | public static class environment_variables_that_are_cleared_by_the_rule_are_not_stored_in_the_environment_variables_map {
365 | @Rule
366 | public final EnvironmentVariables environmentVariables = new EnvironmentVariables();
367 |
368 | @Test
369 | public void test() {
370 | //we need to set a value because it is null by default
371 | environmentVariables.set("dummy name", randomValue());
372 | environmentVariables.set("another name", randomValue());
373 | environmentVariables.clear("dummy name", "another name");
374 | assertThat(getenv())
375 | .doesNotContainKey("dummy name")
376 | .doesNotContainKey("another name");
377 | }
378 | }
379 | }
380 |
381 | private static String randomValue() {
382 | return randomUUID().toString();
383 | }
384 | }
385 |
--------------------------------------------------------------------------------
/src/test/java/org/junit/contrib/java/lang/system/ExpectedSystemExitTest.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 | import static java.lang.System.*;
4 | import static java.lang.Thread.sleep;
5 | import static org.assertj.core.api.Assertions.assertThat;
6 | import static org.junit.Assert.assertEquals;
7 | import static org.junit.Assert.assertTrue;
8 | import static org.junit.Assert.fail;
9 |
10 | import java.security.Permission;
11 | import java.util.Collection;
12 |
13 | import org.junit.BeforeClass;
14 | import org.junit.Rule;
15 | import org.junit.Test;
16 | import org.junit.experimental.runners.Enclosed;
17 | import org.junit.runner.RunWith;
18 | import org.junit.runner.notification.Failure;
19 |
20 |
21 | @RunWith(Enclosed.class)
22 | public class ExpectedSystemExitTest {
23 | private static final Object ARBITRARY_CONTEXT = new Object();
24 | private static final int ARBITRARY_EXIT_STATUS = 216843;
25 | private static final Assertion INVALID_ASSERTION = new Assertion() {
26 | public void checkAssertion() throws Exception {
27 | fail("Assertion failed.");
28 | }
29 | };
30 | private static final Assertion VALID_ASSERTION = new Assertion() {
31 | public void checkAssertion() throws Exception {
32 | }
33 | };
34 |
35 | public static class test_is_not_affected_by_rule_without_expectation {
36 | @Rule
37 | public final ExpectedSystemExit exit = ExpectedSystemExit.none();
38 |
39 | @Test
40 | public void test() {
41 | }
42 | }
43 |
44 | public static class test_is_successful_if_expected_exit_is_called {
45 | @Rule
46 | public final ExpectedSystemExit exit = ExpectedSystemExit.none();
47 |
48 | @Test
49 | public void test() {
50 | exit.expectSystemExit();
51 | System.exit(0);
52 | }
53 | }
54 |
55 | public static class test_is_successful_exit_is_called_with_expected_status_code {
56 | @Rule
57 | public final ExpectedSystemExit exit = ExpectedSystemExit.none();
58 |
59 | @Test
60 | public void test() {
61 | exit.expectSystemExitWithStatus(0);
62 | System.exit(0);
63 | }
64 | }
65 |
66 | @RunWith(AcceptanceTestRunner.class)
67 | public static class test_fails_if_exit_is_called_but_not_expected {
68 | public static class TestClass {
69 | @Rule
70 | public final ExpectedSystemExit exit = ExpectedSystemExit.none();
71 |
72 | @Test
73 | public void test() {
74 | System.exit(0);
75 | }
76 | }
77 |
78 | public static void expectFailure(Failure failure) {
79 | assertThat(failure.getMessage())
80 | .isEqualTo("Unexpected call of System.exit(0).");
81 | }
82 | }
83 |
84 | @RunWith(AcceptanceTestRunner.class)
85 | public static class test_fails_if_exit_is_expected_but_not_called {
86 | public static class TestClass {
87 | @Rule
88 | public final ExpectedSystemExit exit = ExpectedSystemExit.none();
89 |
90 | @Test
91 | public void test() {
92 | exit.expectSystemExit();
93 | }
94 | }
95 |
96 | public static void expectFailure(Failure failure) {
97 | assertThat(failure.getMessage())
98 | .isEqualTo("System.exit has not been called.");
99 | }
100 | }
101 |
102 | @RunWith(AcceptanceTestRunner.class)
103 | public static class test_fails_if_exit_is_called_with_wrong_status_code {
104 | public static class TestClass {
105 | @Rule
106 | public final ExpectedSystemExit exit = ExpectedSystemExit.none();
107 |
108 | @Test
109 | public void test() {
110 | exit.expectSystemExitWithStatus(1);
111 | System.exit(0);
112 | }
113 | }
114 |
115 | public static void expectFailure(Failure failure) {
116 | assertThat(failure.getMessage())
117 | .isEqualTo("Wrong exit status expected:<1> but was:<0>");
118 | }
119 | }
120 |
121 | public static class test_is_successful_if_assertion_is_met_after_exit_has_been_called {
122 | @Rule
123 | public final ExpectedSystemExit exit = ExpectedSystemExit.none();
124 |
125 | @Test
126 | public void test() {
127 | exit.expectSystemExit();
128 | exit.checkAssertionAfterwards(new Assertion() {
129 | public void checkAssertion() throws Exception {
130 | assertTrue(true);
131 | }
132 | });
133 | System.exit(0);
134 | }
135 | }
136 |
137 | @RunWith(AcceptanceTestRunner.class)
138 | public static class test_fails_if_assertion_is_not_met_after_exit_has_been_called {
139 | public static class TestClass {
140 | @Rule
141 | public final ExpectedSystemExit exit = ExpectedSystemExit.none();
142 |
143 | @Test
144 | public void test() {
145 | exit.expectSystemExit();
146 | exit.checkAssertionAfterwards(INVALID_ASSERTION);
147 | System.exit(0);
148 | }
149 | }
150 |
151 | public static void expectFailure(Failure failure) {
152 | assertThat(failure.getMessage())
153 | .isEqualTo("Assertion failed.");
154 | }
155 | }
156 |
157 | @RunWith(AcceptanceTestRunner.class)
158 | public static class test_fails_if_first_of_two_assertions_is_not_met {
159 | public static class TestClass {
160 | @Rule
161 | public final ExpectedSystemExit exit = ExpectedSystemExit.none();
162 |
163 | @Test
164 | public void test() {
165 | exit.checkAssertionAfterwards(INVALID_ASSERTION);
166 | exit.checkAssertionAfterwards(VALID_ASSERTION);
167 | }
168 | }
169 |
170 | public static void expectFailure(Failure failure) {
171 | assertThat(failure.getMessage())
172 | .isEqualTo("Assertion failed.");
173 | }
174 | }
175 |
176 | @RunWith(AcceptanceTestRunner.class)
177 | public static class test_fails_if_second_of_two_assertions_is_not_met {
178 | public static class TestClass {
179 | @Rule
180 | public final ExpectedSystemExit exit = ExpectedSystemExit.none();
181 |
182 | @Test
183 | public void test() {
184 | exit.checkAssertionAfterwards(VALID_ASSERTION);
185 | exit.checkAssertionAfterwards(INVALID_ASSERTION);
186 | }
187 | }
188 |
189 | public static void expectFailure(Failure failure) {
190 | assertThat(failure.getMessage())
191 | .isEqualTo("Assertion failed.");
192 | }
193 | }
194 |
195 | @RunWith(AcceptanceTestRunner.class)
196 | public static class after_test_security_manager_is_the_same_as_before {
197 | private static final SecurityManager MANAGER = new ArbitrarySecurityManager();
198 |
199 | @BeforeClass
200 | public static void setFixedSecurityManager() {
201 | setSecurityManager(MANAGER);
202 | }
203 |
204 | public static class TestClass {
205 | @Rule
206 | public final ExpectedSystemExit exit = ExpectedSystemExit.none();
207 |
208 | @Test
209 | public void test() {
210 | }
211 | }
212 |
213 | public static void verifyStateAfterTest() {
214 | assertThat(getSecurityManager()).isSameAs(MANAGER);
215 | }
216 | }
217 |
218 | @RunWith(AcceptanceTestRunner.class)
219 | public static class current_security_manager_is_used_for_anything_else_than_system_exit {
220 | private static final SecurityManager MANAGER = new ArbitrarySecurityManager();
221 |
222 | @BeforeClass
223 | public static void setFixedSecurityManager() {
224 | setSecurityManager(MANAGER);
225 | }
226 |
227 | public static class TestClass {
228 | @Rule
229 | public final ExpectedSystemExit exit = ExpectedSystemExit.none();
230 |
231 | @Test
232 | public void test() {
233 | assertEquals(ARBITRARY_CONTEXT, getSecurityManager().getSecurityContext());
234 | }
235 | }
236 |
237 | public static void verifyResult(Collection failures) {
238 | assertThat(failures).isEmpty();
239 | }
240 | }
241 |
242 | public static class test_is_successful_if_expected_exit_is_called_in_a_thread {
243 | @Rule
244 | public final ExpectedSystemExit exit = ExpectedSystemExit.none();
245 |
246 | @Test
247 | public void test() throws Throwable {
248 | exit.expectSystemExitWithStatus(ARBITRARY_EXIT_STATUS);
249 | Runnable callSystemExit = new Runnable() {
250 | public void run() {
251 | System.exit(ARBITRARY_EXIT_STATUS);
252 | }
253 | };
254 | Thread thread = new Thread(callSystemExit);
255 | thread.start();
256 | sleep(1000); // wait until the thread exits
257 | }
258 | }
259 |
260 | private static class ArbitrarySecurityManager extends SecurityManager {
261 | @Override
262 | public Object getSecurityContext() {
263 | return ARBITRARY_CONTEXT;
264 | }
265 |
266 | @Override
267 | public void checkPermission(Permission perm) {
268 | // allow anything.
269 | }
270 | }
271 | }
272 |
--------------------------------------------------------------------------------
/src/test/java/org/junit/contrib/java/lang/system/ProvideSecurityManagerTest.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 | import static java.lang.System.getSecurityManager;
4 | import static org.assertj.core.api.Assertions.assertThat;
5 |
6 | import java.security.Permission;
7 |
8 | import org.junit.Rule;
9 | import org.junit.Test;
10 | import org.junit.experimental.runners.Enclosed;
11 | import org.junit.runner.RunWith;
12 |
13 | @RunWith(Enclosed.class)
14 | public class ProvideSecurityManagerTest {
15 | private static final SecurityManager MANAGER = new SecurityManager() {
16 | @Override
17 | public void checkPermission(Permission perm) {
18 | // everything is allowed
19 | }
20 | };
21 |
22 | public static class provided_security_manager_is_present_during_test {
23 | @Rule
24 | public final ProvideSecurityManager rule = new ProvideSecurityManager(MANAGER);
25 |
26 | @Test
27 | public void test() {
28 | assertThat(getSecurityManager()).isSameAs(MANAGER);
29 | }
30 | }
31 |
32 | @RunWith(AcceptanceTestRunner.class)
33 | public static class after_test_security_manager_is_the_same_as_before {
34 | private static final SecurityManager ORIGINAL_MANAGER = getSecurityManager();
35 |
36 | public static class TestClass {
37 | @Rule
38 | public final ProvideSecurityManager rule = new ProvideSecurityManager(MANAGER);
39 |
40 | @Test
41 | public void test() {
42 | }
43 | }
44 |
45 | public static void verifyStateAfterTest() {
46 | assertThat(getSecurityManager()).isSameAs(ORIGINAL_MANAGER);
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/test/java/org/junit/contrib/java/lang/system/ProvideSystemPropertyTest.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 | import static java.lang.System.*;
4 | import static org.apache.commons.io.IOUtils.copy;
5 | import static org.assertj.core.api.Assertions.assertThat;
6 | import static org.junit.contrib.java.lang.system.ProvideSystemProperty.fromFile;
7 | import static org.junit.contrib.java.lang.system.ProvideSystemProperty.fromResource;
8 |
9 | import java.io.File;
10 | import java.io.FileOutputStream;
11 | import java.io.InputStream;
12 | import java.util.Collection;
13 |
14 | import org.junit.BeforeClass;
15 | import org.junit.ClassRule;
16 | import org.junit.Rule;
17 | import org.junit.Test;
18 | import org.junit.experimental.runners.Enclosed;
19 | import org.junit.rules.TemporaryFolder;
20 | import org.junit.runner.RunWith;
21 | import org.junit.runner.notification.Failure;
22 |
23 | @RunWith(Enclosed.class)
24 | public class ProvideSystemPropertyTest {
25 | private static final String EXAMPLE_PROPERTIES = "example.properties";
26 | private static final String ARBITRARY_KEY = "arbitrary property";
27 | private static final String ANOTHER_KEY = "another property";
28 | private static final String ARBITRARY_VALUE = "arbitrary value";
29 | private static final String A_DIFFERENT_VALUE = "different value";
30 |
31 | @RunWith(AcceptanceTestRunner.class)
32 | public static class provided_property_values_are_present_during_test {
33 | @ClassRule
34 | public static final RestoreSystemProperties restoreSystemProperty
35 | = new RestoreSystemProperties();
36 |
37 | public static class TestClass {
38 | @Rule
39 | public final ProvideSystemProperty provideSystemProperty =
40 | new ProvideSystemProperty(ARBITRARY_KEY, ARBITRARY_VALUE)
41 | .and(ANOTHER_KEY, A_DIFFERENT_VALUE);
42 |
43 | @Test
44 | public void test() {
45 | assertThat(getProperty(ARBITRARY_KEY)).isEqualTo(ARBITRARY_VALUE);
46 | assertThat(getProperty(ANOTHER_KEY)).isEqualTo(A_DIFFERENT_VALUE);
47 | }
48 | }
49 |
50 | public static void verifyResult(Collection failures) {
51 | assertThat(failures).isEmpty();
52 | }
53 | }
54 |
55 | @RunWith(AcceptanceTestRunner.class)
56 | public static class property_is_null_during_test_if_set_to_null {
57 | @ClassRule
58 | public static final RestoreSystemProperties restoreSystemProperty
59 | = new RestoreSystemProperties();
60 |
61 | @BeforeClass
62 | public static void populateProperty() {
63 | setProperty(ARBITRARY_KEY, "value before executing the rule");
64 | }
65 |
66 | public static class TestClass {
67 | @Rule
68 | public final ProvideSystemProperty provideSystemProperty =
69 | new ProvideSystemProperty(ARBITRARY_KEY, null);
70 |
71 | @Test
72 | public void test() {
73 | assertThat(getProperty(ARBITRARY_KEY)).isNull();
74 | }
75 | }
76 |
77 | public static void verifyResult(Collection failures) {
78 | assertThat(failures).isEmpty();
79 | }
80 | }
81 |
82 | @RunWith(AcceptanceTestRunner.class)
83 | public static class after_test_properties_have_the_same_values_as_before {
84 | @ClassRule
85 | public static final RestoreSystemProperties restoreSystemProperty
86 | = new RestoreSystemProperties();
87 |
88 | @BeforeClass
89 | public static void populateProperties() {
90 | setProperty(ARBITRARY_KEY, "value of first property");
91 | setProperty(ANOTHER_KEY, "value of second property");
92 | }
93 |
94 | public static class TestClass {
95 | @Rule
96 | public final ProvideSystemProperty provideSystemProperty =
97 | new ProvideSystemProperty(ARBITRARY_KEY, "different value")
98 | .and(ANOTHER_KEY, "another different value");
99 |
100 | @Test
101 | public void test() {
102 | }
103 | }
104 |
105 | public static void verifyStateAfterTest() {
106 | assertThat(getProperty(ARBITRARY_KEY))
107 | .isEqualTo("value of first property");
108 | assertThat(getProperty(ANOTHER_KEY))
109 | .isEqualTo("value of second property");
110 | }
111 | }
112 |
113 | @RunWith(AcceptanceTestRunner.class)
114 | public static class property_that_does_not_exist_before_the_test_does_not_exist_after_the_test {
115 | @ClassRule
116 | public static final RestoreSystemProperties restoreSystemProperty
117 | = new RestoreSystemProperties();
118 |
119 | @BeforeClass
120 | public static void ensurePropertyIsMissing() {
121 | clearProperty(ARBITRARY_KEY);
122 | }
123 |
124 | public static class TestClass {
125 | @Rule
126 | public final ProvideSystemProperty provideSystemProperty =
127 | new ProvideSystemProperty(ARBITRARY_KEY, "other value");
128 |
129 | @Test
130 | public void test() {
131 | }
132 | }
133 |
134 | public static void verifyStateAfterTest() {
135 | assertThat(getProperty(ARBITRARY_KEY)).isNull();
136 | }
137 | }
138 |
139 | @RunWith(AcceptanceTestRunner.class)
140 | public static class properties_from_resource_are_present_during_test {
141 | @ClassRule
142 | public static final RestoreSystemProperties restoreSystemProperty
143 | = new RestoreSystemProperties();
144 |
145 | public static class TestClass {
146 | @Rule
147 | public final ProvideSystemProperty provideSystemProperty = fromResource(EXAMPLE_PROPERTIES);
148 |
149 | @Test
150 | public void test() {
151 | assertThat(getProperty(ARBITRARY_KEY)).isEqualTo(ARBITRARY_VALUE);
152 | }
153 | }
154 |
155 | public static void verifyResult(Collection failures) {
156 | assertThat(failures).isEmpty();
157 | }
158 | }
159 |
160 | @RunWith(AcceptanceTestRunner.class)
161 | public static class properties_from_file_are_present_during_test {
162 | @ClassRule
163 | public static final RestoreSystemProperties restoreSystemProperty
164 | = new RestoreSystemProperties();
165 |
166 | @ClassRule
167 | public static final TemporaryFolder temporaryFolder = new TemporaryFolder();
168 |
169 | @BeforeClass
170 | public static void createFile() throws Exception {
171 | file = temporaryFolder.newFile();
172 | copyResourceToFile(EXAMPLE_PROPERTIES, file);
173 | }
174 |
175 | private static void copyResourceToFile(String name, File file) throws Exception {
176 | FileOutputStream fos = new FileOutputStream(file);
177 | InputStream is = ProvideSystemPropertyTest.class.getResourceAsStream(name);
178 | copy(is, fos);
179 | }
180 |
181 | private static File file;
182 |
183 | public static class TestClass {
184 | @Rule
185 | public final ProvideSystemProperty provideSystemProperty = fromFile(file.getAbsolutePath());
186 |
187 | @Test
188 | public void test() {
189 | assertThat(getProperty(ARBITRARY_KEY)).isEqualTo(ARBITRARY_VALUE);
190 | }
191 | }
192 |
193 | public static void verifyResult(Collection failures) {
194 | assertThat(failures).isEmpty();
195 | }
196 | }
197 |
198 | @RunWith(AcceptanceTestRunner.class)
199 | public static class property_has_value_that_is_set_within_the_test_using_the_rule {
200 | @ClassRule
201 | public static final RestoreSystemProperties restoreSystemProperty
202 | = new RestoreSystemProperties();
203 |
204 | @BeforeClass
205 | public static void populateProperty() {
206 | setProperty(ARBITRARY_KEY, "value before executing the rule");
207 | }
208 |
209 | public static class TestClass {
210 | @Rule
211 | public final ProvideSystemProperty provideSystemProperty = new ProvideSystemProperty();
212 |
213 | @Test
214 | public void test() {
215 | setProperty(ARBITRARY_KEY, "dummy value");
216 | assertThat(getProperty(ARBITRARY_KEY)).isEqualTo("dummy value");
217 | }
218 | }
219 |
220 | public static void verifyResult(Collection failures) {
221 | assertThat(failures).isEmpty();
222 | }
223 | }
224 |
225 | @RunWith(AcceptanceTestRunner.class)
226 | public static class after_test_property_has_the_same_values_as_before_if_set_within_test_using_the_rule {
227 | @ClassRule
228 | public static final RestoreSystemProperties restoreSystemProperty
229 | = new RestoreSystemProperties();
230 |
231 | @BeforeClass
232 | public static void populateProperty() {
233 | setProperty(ARBITRARY_KEY, "value before executing the rule");
234 | }
235 |
236 | public static class TestClass {
237 | @Rule
238 | public final ProvideSystemProperty provideSystemProperty = new ProvideSystemProperty();
239 |
240 | @Test
241 | public void test() {
242 | provideSystemProperty.setProperty(ARBITRARY_KEY, "dummy value");
243 | }
244 | }
245 |
246 | public static void verifyStateAfterTest() {
247 | assertThat(getProperty(ARBITRARY_KEY))
248 | .isEqualTo("value before executing the rule");
249 | }
250 | }
251 | }
252 |
--------------------------------------------------------------------------------
/src/test/java/org/junit/contrib/java/lang/system/RestoreSystemPropertiesTest.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 | import static org.assertj.core.api.Assertions.assertThat;
4 |
5 | import org.junit.*;
6 | import org.junit.experimental.runners.Enclosed;
7 | import org.junit.rules.TestRule;
8 | import org.junit.runner.RunWith;
9 | import org.junit.runner.notification.Failure;
10 |
11 | import java.util.Collection;
12 | import java.util.Properties;
13 |
14 | @RunWith(Enclosed.class)
15 | public class RestoreSystemPropertiesTest {
16 | //ensure that every test uses the same property, because this one is restored after the test
17 | private static final String PROPERTY_KEY = "dummy property";
18 |
19 | @RunWith(AcceptanceTestRunner.class)
20 | public static class after_test_properties_have_the_same_values_as_before {
21 | @BeforeClass
22 | public static void setProperty() {
23 | System.setProperty(PROPERTY_KEY, "dummy value");
24 | }
25 |
26 | public static class TestClass {
27 | @Rule
28 | public final TestRule restoreSystemProperties = new RestoreSystemProperties();
29 |
30 | @Test
31 | public void test() {
32 | System.setProperty(PROPERTY_KEY, "another value");
33 | }
34 | }
35 |
36 | public static void verifyStateAfterTest() {
37 | assertThat(System.getProperty(PROPERTY_KEY))
38 | .isEqualTo("dummy value");
39 | }
40 | }
41 |
42 | @RunWith(AcceptanceTestRunner.class)
43 | public static class property_that_does_not_exist_before_the_test_does_not_exist_after_the_test {
44 | @BeforeClass
45 | public static void clearProperty() {
46 | System.clearProperty(PROPERTY_KEY);
47 | }
48 |
49 | public static class TestClass {
50 | @Rule
51 | public final TestRule restoreSystemProperties = new RestoreSystemProperties();
52 |
53 | @Test
54 | public void test() {
55 | System.setProperty(PROPERTY_KEY, "another value");
56 | }
57 | }
58 |
59 | public static void verifyStateAfterTest() {
60 | assertThat(System.getProperty(PROPERTY_KEY))
61 | .isNull();
62 | }
63 | }
64 |
65 | @RunWith(AcceptanceTestRunner.class)
66 | public static class at_start_of_a_test_properties_are_equal_to_the_original_properties {
67 | private static Properties originalProperties;
68 |
69 | @BeforeClass
70 | public static void changeAndCaptureOriginalProperties() {
71 | //ensure at least one property is set
72 | System.setProperty(PROPERTY_KEY, "dummy value");
73 | originalProperties = System.getProperties();
74 | }
75 |
76 | public static class TestClass {
77 | @Rule
78 | public final TestRule restoreSystemProperties = new RestoreSystemProperties();
79 |
80 | @Test
81 | public void test() {
82 | assertThat(System.getProperties())
83 | .isEqualTo(originalProperties);
84 | }
85 | }
86 |
87 | public static void verifyResult(Collection failures) {
88 | assertThat(failures).isEmpty();
89 | }
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/src/test/java/org/junit/contrib/java/lang/system/StandardErrorStreamLogTest.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 | import static java.lang.System.setErr;
4 | import static org.assertj.core.api.Assertions.assertThat;
5 |
6 | import java.io.ByteArrayOutputStream;
7 | import java.io.PrintStream;
8 |
9 | import org.junit.AfterClass;
10 | import org.junit.BeforeClass;
11 | import org.junit.Rule;
12 | import org.junit.Test;
13 | import org.junit.experimental.runners.Enclosed;
14 | import org.junit.runner.RunWith;
15 | import org.junit.runner.notification.Failure;
16 |
17 | @RunWith(Enclosed.class)
18 | public class StandardErrorStreamLogTest {
19 |
20 | public static class log_contains_text_that_has_been_written_to_system_err {
21 | @Rule
22 | public final StandardErrorStreamLog log = new StandardErrorStreamLog();
23 |
24 | @Test
25 | public void test() {
26 | System.err.print("dummy text");
27 | assertThat(log.getLog()).isEqualTo("dummy text");
28 | }
29 | }
30 |
31 | @RunWith(AcceptanceTestRunner.class)
32 | public static class after_the_test_system_err_is_same_as_before {
33 | private static PrintStream originalStream;
34 |
35 | @BeforeClass
36 | public static void captureOriginalStream() {
37 | originalStream = System.err;
38 | }
39 |
40 | public static class TestClass {
41 | @Rule
42 | public final StandardErrorStreamLog log = new StandardErrorStreamLog();
43 |
44 | @Test
45 | public void test() {
46 | System.err.print("dummy text");
47 | }
48 | }
49 |
50 | public static void verifyStateAfterTest() {
51 | assertThat(originalStream).isSameAs(System.err);
52 | }
53 | }
54 |
55 | @RunWith(AcceptanceTestRunner.class)
56 | public static class text_is_still_written_to_system_err_if_no_log_mode_is_specified {
57 | private static PrintStream originalStream;
58 | private static ByteArrayOutputStream captureErrorStream;
59 |
60 | @BeforeClass
61 | public static void replaceSystemErr() {
62 | originalStream = System.err;
63 | captureErrorStream = new ByteArrayOutputStream();
64 | setErr(new PrintStream(captureErrorStream));
65 | }
66 |
67 | public static class TestClass {
68 | @Rule
69 | public final StandardErrorStreamLog log = new StandardErrorStreamLog();
70 |
71 | @Test
72 | public void test() {
73 | System.err.print("dummy text");
74 | }
75 | }
76 |
77 | public static void verifyStateAfterTest() {
78 | assertThat(captureErrorStream.toString()).isEqualTo("dummy text");
79 | }
80 |
81 | @AfterClass
82 | public static void restoreOriginalStream() {
83 | setErr(originalStream);
84 | }
85 | }
86 |
87 | @RunWith(AcceptanceTestRunner.class)
88 | public static class no_text_is_written_to_system_err_if_log_mode_is_log_only {
89 | private static PrintStream originalStream;
90 | private static ByteArrayOutputStream captureErrorStream;
91 |
92 | @BeforeClass
93 | public static void replaceSystemErr() {
94 | originalStream = System.err;
95 | captureErrorStream = new ByteArrayOutputStream();
96 | setErr(new PrintStream(captureErrorStream));
97 | }
98 |
99 | public static class TestClass {
100 | @Rule
101 | public final StandardErrorStreamLog log = new StandardErrorStreamLog(
102 | LogMode.LOG_ONLY);
103 |
104 | @Test
105 | public void test() {
106 | System.err.print("dummy text");
107 | }
108 | }
109 |
110 | public static void verifyStateAfterTest() {
111 | assertThat(captureErrorStream.toString()).isEmpty();
112 | }
113 |
114 | @AfterClass
115 | public static void restoreOriginalStream() {
116 | setErr(originalStream);
117 | }
118 | }
119 |
120 | public static class log_contains_only_text_that_has_been_written_after_log_was_cleared {
121 | @Rule
122 | public final StandardErrorStreamLog log = new StandardErrorStreamLog();
123 |
124 | @Test
125 | public void test() {
126 | System.err.print("text before clearing");
127 | log.clear();
128 | System.err.print("text after clearing");
129 | assertThat(log.getLog()).isEqualTo("text after clearing");
130 | }
131 | }
132 |
133 | @RunWith(AcceptanceTestRunner.class)
134 | public static class rule_cannot_be_created_without_log_mode {
135 | public static class TestClass {
136 | @Rule
137 | public final StandardErrorStreamLog log = new StandardErrorStreamLog(
138 | null);
139 |
140 | @Test
141 | public void test() {
142 | }
143 | }
144 |
145 | public static void expectFailure(Failure failure) {
146 | assertThat(failure.getException())
147 | .isInstanceOf(NullPointerException.class)
148 | .hasMessage("The LogMode is missing.");
149 | assertThat(failure.getMessage())
150 | .isEqualTo("The LogMode is missing.");
151 | }
152 | }
153 | }
154 |
--------------------------------------------------------------------------------
/src/test/java/org/junit/contrib/java/lang/system/StandardOutputStreamLogTest.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 | import static java.lang.System.*;
4 | import static org.assertj.core.api.Assertions.assertThat;
5 |
6 | import java.io.ByteArrayOutputStream;
7 | import java.io.PrintStream;
8 |
9 | import org.junit.AfterClass;
10 | import org.junit.BeforeClass;
11 | import org.junit.Rule;
12 | import org.junit.Test;
13 | import org.junit.experimental.runners.Enclosed;
14 | import org.junit.runner.RunWith;
15 | import org.junit.runner.notification.Failure;
16 |
17 | @RunWith(Enclosed.class)
18 | public class StandardOutputStreamLogTest {
19 |
20 | public static class log_contains_text_that_has_been_written_to_system_out {
21 | @Rule
22 | public final StandardOutputStreamLog log = new StandardOutputStreamLog();
23 |
24 | @Test
25 | public void test() {
26 | System.out.print("dummy text");
27 | assertThat(log.getLog()).isEqualTo("dummy text");
28 | }
29 | }
30 |
31 | @RunWith(AcceptanceTestRunner.class)
32 | public static class after_the_test_system_out_is_same_as_before {
33 | private static PrintStream originalStream;
34 |
35 | @BeforeClass
36 | public static void captureOriginalStream() {
37 | originalStream = System.out;
38 | }
39 |
40 | public static class TestClass {
41 | @Rule
42 | public final StandardOutputStreamLog log = new StandardOutputStreamLog();
43 |
44 | @Test
45 | public void test() {
46 | System.out.print("dummy text");
47 | }
48 | }
49 |
50 | public static void verifyStateAfterTest() {
51 | assertThat(originalStream).isSameAs(System.out);
52 | }
53 | }
54 |
55 | @RunWith(AcceptanceTestRunner.class)
56 | public static class text_is_still_written_to_system_out_if_no_log_mode_is_specified {
57 | private static PrintStream originalStream;
58 | private static ByteArrayOutputStream captureOutputStream;
59 |
60 | @BeforeClass
61 | public static void replaceSystemOut() {
62 | originalStream = System.out;
63 | captureOutputStream = new ByteArrayOutputStream();
64 | setOut(new PrintStream(captureOutputStream));
65 | }
66 |
67 | public static class TestClass {
68 | @Rule
69 | public final StandardOutputStreamLog log = new StandardOutputStreamLog();
70 |
71 | @Test
72 | public void test() {
73 | System.out.print("dummy text");
74 | }
75 | }
76 |
77 | public static void verifyStateAfterTest() {
78 | assertThat(captureOutputStream.toString()).isEqualTo("dummy text");
79 | }
80 |
81 | @AfterClass
82 | public static void restoreOriginalStream() {
83 | setOut(originalStream);
84 | }
85 | }
86 |
87 | @RunWith(AcceptanceTestRunner.class)
88 | public static class no_text_is_written_to_system_out_if_log_mode_is_log_only {
89 | private static PrintStream originalStream;
90 | private static ByteArrayOutputStream captureOutputStream;
91 |
92 | @BeforeClass
93 | public static void replaceSystemOut() {
94 | originalStream = System.out;
95 | captureOutputStream = new ByteArrayOutputStream();
96 | setOut(new PrintStream(captureOutputStream));
97 | }
98 |
99 | public static class TestClass {
100 | @Rule
101 | public final StandardOutputStreamLog log = new StandardOutputStreamLog(
102 | LogMode.LOG_ONLY);
103 |
104 | @Test
105 | public void test() {
106 | System.out.print("dummy text");
107 | }
108 | }
109 |
110 | public static void verifyStateAfterTest() {
111 | assertThat(captureOutputStream.toString()).isEmpty();
112 | }
113 |
114 | @AfterClass
115 | public static void restoreOriginalStream() {
116 | setOut(originalStream);
117 | }
118 | }
119 |
120 | public static class log_contains_only_text_that_has_been_written_after_log_was_cleared {
121 | @Rule
122 | public final StandardOutputStreamLog log = new StandardOutputStreamLog();
123 |
124 | @Test
125 | public void test() {
126 | System.out.print("text before clearing");
127 | log.clear();
128 | System.out.print("text after clearing");
129 | assertThat(log.getLog()).isEqualTo("text after clearing");
130 | }
131 | }
132 |
133 | @RunWith(AcceptanceTestRunner.class)
134 | public static class rule_cannot_be_created_without_log_mode {
135 | public static class TestClass {
136 | @Rule
137 | public final StandardOutputStreamLog log = new StandardOutputStreamLog(
138 | null);
139 |
140 | @Test
141 | public void test() {
142 | }
143 | }
144 |
145 | public static void expectFailure(Failure failure) {
146 | assertThat(failure.getException())
147 | .isInstanceOf(NullPointerException.class)
148 | .hasMessage("The LogMode is missing.");
149 | assertThat(failure.getMessage())
150 | .isEqualTo("The LogMode is missing.");
151 | }
152 | }
153 | }
154 |
--------------------------------------------------------------------------------
/src/test/java/org/junit/contrib/java/lang/system/SystemErrRuleTest.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 | import static java.lang.String.format;
4 | import static java.lang.System.setErr;
5 | import static java.lang.System.setProperty;
6 | import static org.assertj.core.api.Assertions.assertThat;
7 | import static org.junit.Assert.fail;
8 |
9 | import java.io.ByteArrayOutputStream;
10 | import java.io.PrintStream;
11 | import java.util.Collection;
12 |
13 | import org.junit.*;
14 | import org.junit.experimental.runners.Enclosed;
15 | import org.junit.runner.RunWith;
16 | import org.junit.runner.notification.Failure;
17 |
18 | @RunWith(Enclosed.class)
19 | public class SystemErrRuleTest {
20 |
21 | @RunWith(AcceptanceTestRunner.class)
22 | public static class after_the_test_system_err_is_same_as_before {
23 | private static PrintStream originalStream;
24 |
25 | @BeforeClass
26 | public static void captureOriginalStream() {
27 | originalStream = System.err;
28 | }
29 |
30 | public static class TestClass {
31 | @Rule
32 | public final SystemErrRule systemErrRule = new SystemErrRule();
33 |
34 | @Test
35 | public void test() {
36 | System.err.print("dummy text");
37 | }
38 | }
39 |
40 | public static void verifyStateAfterTest() {
41 | assertThat(System.err).isSameAs(originalStream);
42 | }
43 | }
44 |
45 | @RunWith(AcceptanceTestRunner.class)
46 | public static class text_is_still_written_to_system_err_if_no_log_mode_is_specified {
47 | private static PrintStream originalStream;
48 | private static ByteArrayOutputStream captureErrorStream;
49 |
50 | @BeforeClass
51 | public static void replaceSystemErr() {
52 | originalStream = System.err;
53 | captureErrorStream = new ByteArrayOutputStream();
54 | setErr(new PrintStream(captureErrorStream));
55 | }
56 |
57 | public static class TestClass {
58 | @Rule
59 | public final SystemErrRule systemErrRule = new SystemErrRule();
60 |
61 | @Test
62 | public void test() {
63 | System.err.print("dummy text");
64 | }
65 | }
66 |
67 | public static void verifyStateAfterTest() {
68 | assertThat(captureErrorStream.toString()).isEqualTo("dummy text");
69 | }
70 |
71 | @AfterClass
72 | public static void restoreOriginalStream() {
73 | setErr(originalStream);
74 | }
75 | }
76 |
77 | @RunWith(AcceptanceTestRunner.class)
78 | public static class no_text_is_written_to_system_err_if_muted_globally {
79 | private static PrintStream originalStream;
80 | private static ByteArrayOutputStream captureErrorStream;
81 |
82 | @BeforeClass
83 | public static void replaceSystemErr() {
84 | originalStream = System.err;
85 | captureErrorStream = new ByteArrayOutputStream();
86 | setErr(new PrintStream(captureErrorStream));
87 | }
88 |
89 | public static class TestClass {
90 | @Rule
91 | public final SystemErrRule systemErrRule = new SystemErrRule().mute();
92 |
93 | @Test
94 | public void test() {
95 | System.err.print("dummy text");
96 | }
97 | }
98 |
99 | public static void verifyStateAfterTest() {
100 | assertThat(captureErrorStream.toString()).isEmpty();
101 | }
102 |
103 | @AfterClass
104 | public static void restoreOriginalStream() {
105 | setErr(originalStream);
106 | }
107 | }
108 |
109 | @RunWith(AcceptanceTestRunner.class)
110 | public static class no_text_is_written_to_system_err_after_muted_locally {
111 | private static PrintStream originalStream;
112 | private static ByteArrayOutputStream captureErrorStream;
113 |
114 | @BeforeClass
115 | public static void replaceSystemErr() {
116 | originalStream = System.err;
117 | captureErrorStream = new ByteArrayOutputStream();
118 | setErr(new PrintStream(captureErrorStream));
119 | }
120 |
121 | public static class TestClass {
122 | @Rule
123 | public final SystemErrRule systemErrRule = new SystemErrRule();
124 |
125 | @Test
126 | public void test() {
127 | System.err.print("text before muting");
128 | systemErrRule.mute();
129 | System.err.print("text after muting");
130 | }
131 | }
132 |
133 | public static void verifyStateAfterTest() {
134 | assertThat(captureErrorStream.toString())
135 | .isEqualTo("text before muting");
136 | }
137 |
138 | @AfterClass
139 | public static void restoreOriginalStream() {
140 | setErr(originalStream);
141 | }
142 | }
143 |
144 | @RunWith(AcceptanceTestRunner.class)
145 | public static class no_text_is_written_to_system_err_for_successful_test_if_muted_globally_for_successful_tests {
146 | private static PrintStream originalStream;
147 | private static ByteArrayOutputStream captureErrorStream;
148 |
149 | @BeforeClass
150 | public static void replaceSystemErr() {
151 | originalStream = System.err;
152 | captureErrorStream = new ByteArrayOutputStream();
153 | setErr(new PrintStream(captureErrorStream));
154 | }
155 |
156 | public static class TestClass {
157 | @Rule
158 | public final SystemErrRule systemErrRule = new SystemErrRule()
159 | .muteForSuccessfulTests();
160 |
161 | @Test
162 | public void test() {
163 | System.err.print("dummy text");
164 | }
165 | }
166 |
167 | public static void verifyStateAfterTest() {
168 | assertThat(captureErrorStream.toString()).isEmpty();
169 | }
170 |
171 | @AfterClass
172 | public static void restoreOriginalStream() {
173 | setErr(originalStream);
174 | }
175 | }
176 |
177 | @RunWith(AcceptanceTestRunner.class)
178 | public static class text_is_written_to_system_err_for_failing_test_if_muted_globally_for_successful_tests {
179 | private static PrintStream originalStream;
180 | private static ByteArrayOutputStream captureErrorStream;
181 |
182 | @BeforeClass
183 | public static void replaceSystemErr() {
184 | originalStream = System.err;
185 | captureErrorStream = new ByteArrayOutputStream();
186 | setErr(new PrintStream(captureErrorStream));
187 | }
188 |
189 | public static class TestClass {
190 | @Rule
191 | public final SystemErrRule systemErrRule = new SystemErrRule()
192 | .muteForSuccessfulTests();
193 |
194 | @Test
195 | public void test() {
196 | System.err.print("dummy text");
197 | fail();
198 | }
199 | }
200 |
201 | public static void verifyStateAfterTest() {
202 | assertThat(captureErrorStream.toString()).isEqualTo("dummy text");
203 | }
204 |
205 | public static void expectFailure(Failure failure) {
206 | }
207 |
208 | @AfterClass
209 | public static void restoreOriginalStream() {
210 | setErr(originalStream);
211 | }
212 | }
213 |
214 | @RunWith(AcceptanceTestRunner.class)
215 | public static class no_text_is_written_to_system_err_for_successful_test_if_muted_locally_for_successful_tests {
216 | private static PrintStream originalStream;
217 | private static ByteArrayOutputStream captureErrorStream;
218 |
219 | @BeforeClass
220 | public static void replaceSystemErr() {
221 | originalStream = System.err;
222 | captureErrorStream = new ByteArrayOutputStream();
223 | setErr(new PrintStream(captureErrorStream));
224 | }
225 |
226 | public static class TestClass {
227 | @Rule
228 | public final SystemErrRule systemErrRule = new SystemErrRule();
229 |
230 | @Test
231 | public void test() {
232 | systemErrRule.muteForSuccessfulTests();
233 | System.err.print("dummy text");
234 | }
235 | }
236 |
237 | public static void verifyStateAfterTest() {
238 | assertThat(captureErrorStream.toString()).isEmpty();
239 | }
240 |
241 | @AfterClass
242 | public static void restoreOriginalStream() {
243 | setErr(originalStream);
244 | }
245 | }
246 |
247 | @RunWith(AcceptanceTestRunner.class)
248 | public static class text_is_written_to_system_err_for_failing_test_if_muted_locally_for_successful_tests {
249 | private static PrintStream originalStream;
250 | private static ByteArrayOutputStream captureErrorStream;
251 |
252 | @BeforeClass
253 | public static void replaceSystemErr() {
254 | originalStream = System.err;
255 | captureErrorStream = new ByteArrayOutputStream();
256 | setErr(new PrintStream(captureErrorStream));
257 | }
258 |
259 | public static class TestClass {
260 | @Rule
261 | public final SystemErrRule systemErrRule = new SystemErrRule();
262 |
263 | @Test
264 | public void test() {
265 | systemErrRule.muteForSuccessfulTests();
266 | System.err.print("dummy text");
267 | fail();
268 | }
269 | }
270 |
271 | public static void verifyStateAfterTest() {
272 | assertThat(captureErrorStream.toString()).isEqualTo("dummy text");
273 | }
274 |
275 | public static void expectFailure(Failure failure) {
276 | }
277 |
278 | @AfterClass
279 | public static void restoreOriginalStream() {
280 | setErr(originalStream);
281 | }
282 | }
283 |
284 | public static class no_text_is_logged_by_default {
285 | @Rule
286 | public final SystemErrRule systemErrRule = new SystemErrRule();
287 |
288 | @Test
289 | public void test() {
290 | System.err.print("dummy text");
291 | assertThat(systemErrRule.getLog()).isEmpty();
292 | }
293 | }
294 |
295 | public static class text_is_logged_if_log_has_been_enabled_globally {
296 | @Rule
297 | public final SystemErrRule systemErrRule = new SystemErrRule()
298 | .enableLog();
299 |
300 | @Test
301 | public void test() {
302 | System.err.print("dummy text");
303 | assertThat(systemErrRule.getLog()).isEqualTo("dummy text");
304 | }
305 | }
306 |
307 | public static class text_is_logged_after_log_has_been_enabled_locally {
308 | @Rule
309 | public final SystemErrRule systemErrRule = new SystemErrRule();
310 |
311 | @Test
312 | public void test() {
313 | System.err.print("text before enabling log");
314 | systemErrRule.enableLog();
315 | System.err.print("text after enabling log");
316 | assertThat(systemErrRule.getLog())
317 | .isEqualTo("text after enabling log");
318 | }
319 | }
320 |
321 | public static class log_contains_only_text_that_has_been_written_after_log_was_cleared {
322 | @Rule
323 | public final SystemErrRule systemErrRule = new SystemErrRule()
324 | .enableLog();
325 |
326 | @Test
327 | public void test() {
328 | System.err.print("text before clearing");
329 | systemErrRule.clearLog();
330 | System.err.print("text after clearing");
331 | assertThat(systemErrRule.getLog()).isEqualTo("text after clearing");
332 | }
333 | }
334 |
335 | public static class text_is_logged_if_rule_is_enabled_and_muted {
336 | @Rule
337 | public final SystemErrRule systemErrRule = new SystemErrRule()
338 | .enableLog()
339 | .mute();
340 |
341 | @Test
342 | public void test() {
343 | System.err.print("dummy text");
344 | assertThat(systemErrRule.getLog()).isEqualTo("dummy text");
345 | }
346 | }
347 |
348 | @RunWith(AcceptanceTestRunner.class)
349 | public static class log_is_provided_with_new_line_characters_only_if_requested {
350 | @ClassRule
351 | public static final RestoreSystemProperties RESTORE_SYSTEM_PROPERTIES
352 | = new RestoreSystemProperties();
353 |
354 | @BeforeClass
355 | public static void useWindowsLineSeparator() {
356 | setProperty("line.separator", "\r\n");
357 | }
358 |
359 | public static class TestClass {
360 | @Rule
361 | public final SystemErrRule systemErrRule = new SystemErrRule()
362 | .enableLog();
363 |
364 | @Test
365 | public void test() {
366 | System.err.print(format("dummy%ntext%n"));
367 | assertThat(systemErrRule.getLogWithNormalizedLineSeparator())
368 | .isEqualTo("dummy\ntext\n");
369 | }
370 | }
371 |
372 | public static void verifyResult(Collection failures) {
373 | assertThat(failures).isEmpty();
374 | }
375 | }
376 |
377 | public static class raw_bytes_of_output_are_available_when_logging_is_enabled {
378 | @Rule
379 | public final SystemErrRule systemErrRule = new SystemErrRule()
380 | .enableLog();
381 |
382 | @Test
383 | public void test() {
384 | byte[] data = { 1, 2, 3, 4, 5 };
385 | System.err.write(data, 0, data.length);
386 | assertThat(systemErrRule.getLogAsBytes()).isEqualTo(data);
387 | }
388 | }
389 | }
390 |
--------------------------------------------------------------------------------
/src/test/java/org/junit/contrib/java/lang/system/SystemOutRuleTest.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 | import static java.lang.String.format;
4 | import static java.lang.System.*;
5 | import static org.assertj.core.api.Assertions.assertThat;
6 | import static org.junit.Assert.fail;
7 |
8 | import java.io.ByteArrayOutputStream;
9 | import java.io.PrintStream;
10 | import java.util.Collection;
11 |
12 | import org.junit.*;
13 | import org.junit.experimental.runners.Enclosed;
14 | import org.junit.runner.RunWith;
15 | import org.junit.runner.notification.Failure;
16 |
17 | @RunWith(Enclosed.class)
18 | public class SystemOutRuleTest {
19 |
20 | @RunWith(AcceptanceTestRunner.class)
21 | public static class after_the_test_system_out_is_same_as_before {
22 | private static PrintStream originalStream;
23 |
24 | @BeforeClass
25 | public static void captureOriginalStream() {
26 | originalStream = System.out;
27 | }
28 |
29 | public static class TestClass {
30 | @Rule
31 | public final SystemOutRule systemOutRule = new SystemOutRule();
32 |
33 | @Test
34 | public void test() {
35 | System.out.print("dummy text");
36 | }
37 | }
38 |
39 | public static void verifyStateAfterTest() {
40 | assertThat(System.out).isSameAs(originalStream);
41 | }
42 | }
43 |
44 | @RunWith(AcceptanceTestRunner.class)
45 | public static class text_is_still_written_to_system_out_if_no_log_mode_is_specified {
46 | private static PrintStream originalStream;
47 | private static ByteArrayOutputStream captureOutputStream;
48 |
49 | @BeforeClass
50 | public static void replaceSystemOut() {
51 | originalStream = System.out;
52 | captureOutputStream = new ByteArrayOutputStream();
53 | setOut(new PrintStream(captureOutputStream));
54 | }
55 |
56 | public static class TestClass {
57 | @Rule
58 | public final SystemOutRule systemOutRule = new SystemOutRule();
59 |
60 | @Test
61 | public void test() {
62 | System.out.print("dummy text");
63 | }
64 | }
65 |
66 | public static void verifyStateAfterTest() {
67 | assertThat(captureOutputStream.toString()).isEqualTo("dummy text");
68 | }
69 |
70 | @AfterClass
71 | public static void restoreOriginalStream() {
72 | setOut(originalStream);
73 | }
74 | }
75 |
76 | @RunWith(AcceptanceTestRunner.class)
77 | public static class no_text_is_written_to_system_out_if_muted_globally {
78 | private static PrintStream originalStream;
79 | private static ByteArrayOutputStream captureOutputStream;
80 |
81 | @BeforeClass
82 | public static void replaceSystemOut() {
83 | originalStream = System.out;
84 | captureOutputStream = new ByteArrayOutputStream();
85 | setOut(new PrintStream(captureOutputStream));
86 | }
87 |
88 | public static class TestClass {
89 | @Rule
90 | public final SystemOutRule systemOutRule = new SystemOutRule().mute();
91 |
92 | @Test
93 | public void test() {
94 | System.out.print("dummy text");
95 | }
96 | }
97 |
98 | public static void verifyStateAfterTest() {
99 | assertThat(captureOutputStream.toString()).isEmpty();
100 | }
101 |
102 | @AfterClass
103 | public static void restoreOriginalStream() {
104 | setOut(originalStream);
105 | }
106 | }
107 |
108 | @RunWith(AcceptanceTestRunner.class)
109 | public static class no_text_is_written_to_system_out_after_muted_locally {
110 | private static PrintStream originalStream;
111 | private static ByteArrayOutputStream captureOutputStream;
112 |
113 | @BeforeClass
114 | public static void replaceSystemOut() {
115 | originalStream = System.out;
116 | captureOutputStream = new ByteArrayOutputStream();
117 | setOut(new PrintStream(captureOutputStream));
118 | }
119 |
120 | public static class TestClass {
121 | @Rule
122 | public final SystemOutRule systemOutRule = new SystemOutRule();
123 |
124 | @Test
125 | public void test() {
126 | System.out.print("text before muting");
127 | systemOutRule.mute();
128 | System.out.print("text after muting");
129 | }
130 | }
131 |
132 | public static void verifyStateAfterTest() {
133 | assertThat(captureOutputStream.toString())
134 | .isEqualTo("text before muting");
135 | }
136 |
137 | @AfterClass
138 | public static void restoreOriginalStream() {
139 | setOut(originalStream);
140 | }
141 | }
142 |
143 | @RunWith(AcceptanceTestRunner.class)
144 | public static class no_text_is_written_to_system_out_for_successful_test_if_muted_globally_for_successful_tests {
145 | private static PrintStream originalStream;
146 | private static ByteArrayOutputStream captureOutputStream;
147 |
148 | @BeforeClass
149 | public static void replaceSystemOut() {
150 | originalStream = System.out;
151 | captureOutputStream = new ByteArrayOutputStream();
152 | setOut(new PrintStream(captureOutputStream));
153 | }
154 |
155 | public static class TestClass {
156 | @Rule
157 | public final SystemOutRule systemOutRule = new SystemOutRule()
158 | .muteForSuccessfulTests();
159 |
160 | @Test
161 | public void test() {
162 | System.out.print("dummy text");
163 | }
164 | }
165 |
166 | public static void verifyStateAfterTest() {
167 | assertThat(captureOutputStream.toString()).isEmpty();
168 | }
169 |
170 | @AfterClass
171 | public static void restoreOriginalStream() {
172 | setOut(originalStream);
173 | }
174 | }
175 |
176 | @RunWith(AcceptanceTestRunner.class)
177 | public static class text_is_written_to_system_out_for_failing_test_if_muted_globally_for_successful_tests {
178 | private static PrintStream originalStream;
179 | private static ByteArrayOutputStream captureOutputStream;
180 |
181 | @BeforeClass
182 | public static void replaceSystemOut() {
183 | originalStream = System.out;
184 | captureOutputStream = new ByteArrayOutputStream();
185 | setOut(new PrintStream(captureOutputStream));
186 | }
187 |
188 | public static class TestClass {
189 | @Rule
190 | public final SystemOutRule systemOutRule = new SystemOutRule()
191 | .muteForSuccessfulTests();
192 |
193 | @Test
194 | public void test() {
195 | System.out.print("dummy text");
196 | fail();
197 | }
198 | }
199 |
200 | public static void verifyStateAfterTest() {
201 | assertThat(captureOutputStream.toString()).isEqualTo("dummy text");
202 | }
203 |
204 | public static void expectFailure(Failure failure) {
205 | }
206 |
207 | @AfterClass
208 | public static void restoreOriginalStream() {
209 | setOut(originalStream);
210 | }
211 | }
212 |
213 | @RunWith(AcceptanceTestRunner.class)
214 | public static class no_text_is_written_to_system_out_for_successful_test_if_muted_locally_for_successful_tests {
215 | private static PrintStream originalStream;
216 | private static ByteArrayOutputStream captureOutputStream;
217 |
218 | @BeforeClass
219 | public static void replaceSystemOut() {
220 | originalStream = System.out;
221 | captureOutputStream = new ByteArrayOutputStream();
222 | setOut(new PrintStream(captureOutputStream));
223 | }
224 |
225 | public static class TestClass {
226 | @Rule
227 | public final SystemOutRule systemOutRule = new SystemOutRule();
228 |
229 | @Test
230 | public void test() {
231 | systemOutRule.muteForSuccessfulTests();
232 | System.out.print("dummy text");
233 | }
234 | }
235 |
236 | public static void verifyStateAfterTest() {
237 | assertThat(captureOutputStream.toString()).isEmpty();
238 | }
239 |
240 | @AfterClass
241 | public static void restoreOriginalStream() {
242 | setOut(originalStream);
243 | }
244 | }
245 |
246 | @RunWith(AcceptanceTestRunner.class)
247 | public static class text_is_written_to_system_out_for_failing_test_if_muted_locally_for_successful_tests {
248 | private static PrintStream originalStream;
249 | private static ByteArrayOutputStream captureOutputStream;
250 |
251 | @BeforeClass
252 | public static void replaceSystemOut() {
253 | originalStream = System.out;
254 | captureOutputStream = new ByteArrayOutputStream();
255 | setOut(new PrintStream(captureOutputStream));
256 | }
257 |
258 | public static class TestClass {
259 | @Rule
260 | public final SystemOutRule systemOutRule = new SystemOutRule();
261 |
262 | @Test
263 | public void test() {
264 | systemOutRule.muteForSuccessfulTests();
265 | System.out.print("dummy text");
266 | fail();
267 | }
268 | }
269 |
270 | public static void verifyStateAfterTest() {
271 | assertThat(captureOutputStream.toString()).isEqualTo("dummy text");
272 | }
273 |
274 | public static void expectFailure(Failure failure) {
275 | }
276 |
277 | @AfterClass
278 | public static void restoreOriginalStream() {
279 | setOut(originalStream);
280 | }
281 | }
282 |
283 | public static class no_text_is_logged_by_default {
284 | @Rule
285 | public final SystemOutRule systemOutRule = new SystemOutRule();
286 |
287 | @Test
288 | public void test() {
289 | System.out.print("dummy text");
290 | assertThat(systemOutRule.getLog()).isEmpty();
291 | }
292 | }
293 |
294 | public static class text_is_logged_if_log_has_been_enabled_globally {
295 | @Rule
296 | public final SystemOutRule systemOutRule = new SystemOutRule()
297 | .enableLog();
298 |
299 | @Test
300 | public void test() {
301 | System.out.print("dummy text");
302 | assertThat(systemOutRule.getLog()).isEqualTo("dummy text");
303 | }
304 | }
305 |
306 | public static class text_is_logged_after_log_has_been_enabled_locally {
307 | @Rule
308 | public final SystemOutRule systemOutRule = new SystemOutRule();
309 |
310 | @Test
311 | public void test() {
312 | System.out.print("text before enabling log");
313 | systemOutRule.enableLog();
314 | System.out.print("text after enabling log");
315 | assertThat(systemOutRule.getLog())
316 | .isEqualTo("text after enabling log");
317 | }
318 | }
319 |
320 | public static class log_contains_only_text_that_has_been_written_after_log_was_cleared {
321 | @Rule
322 | public final SystemOutRule systemOutRule = new SystemOutRule()
323 | .enableLog();
324 |
325 | @Test
326 | public void test() {
327 | System.out.print("text before clearing");
328 | systemOutRule.clearLog();
329 | System.out.print("text after clearing");
330 | assertThat(systemOutRule.getLog()).isEqualTo("text after clearing");
331 | }
332 | }
333 |
334 | public static class text_is_logged_if_rule_is_enabled_and_muted {
335 | @Rule
336 | public final SystemOutRule systemOutRule = new SystemOutRule()
337 | .enableLog()
338 | .mute();
339 |
340 | @Test
341 | public void test() {
342 | System.out.print("dummy text");
343 | assertThat(systemOutRule.getLog()).isEqualTo("dummy text");
344 | }
345 | }
346 |
347 | @RunWith(AcceptanceTestRunner.class)
348 | public static class log_is_provided_with_new_line_characters_only_if_requested {
349 | @ClassRule
350 | public static final RestoreSystemProperties RESTORE_SYSTEM_PROPERTIES
351 | = new RestoreSystemProperties();
352 |
353 | @BeforeClass
354 | public static void useWindowsLineSeparator() {
355 | setProperty("line.separator", "\r\n");
356 | }
357 |
358 | public static class TestClass {
359 | @Rule
360 | public final SystemOutRule systemOutRule = new SystemOutRule()
361 | .enableLog();
362 |
363 | @Test
364 | public void test() {
365 | System.out.print(format("dummy%ntext%n"));
366 | assertThat(systemOutRule.getLogWithNormalizedLineSeparator())
367 | .isEqualTo("dummy\ntext\n");
368 | }
369 | }
370 |
371 | public static void verifyResult(Collection failures) {
372 | assertThat(failures).isEmpty();
373 | }
374 | }
375 |
376 | public static class raw_bytes_of_output_are_available_when_logging_is_enabled {
377 | @Rule
378 | public final SystemOutRule systemOutRule = new SystemOutRule()
379 | .enableLog();
380 |
381 | @Test
382 | public void test() {
383 | byte[] data = { 1, 2, 3, 4, 5 };
384 | System.out.write(data, 0, data.length);
385 | assertThat(systemOutRule.getLogAsBytes()).isEqualTo(data);
386 | }
387 | }
388 | }
389 |
--------------------------------------------------------------------------------
/src/test/java/org/junit/contrib/java/lang/system/TextFromStandardInputStreamTest.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system;
2 |
3 | import static com.github.stefanbirkner.fishbowl.Fishbowl.exceptionThrownBy;
4 | import static java.lang.System.getProperty;
5 | import static java.lang.System.in;
6 | import static org.assertj.core.api.Assertions.assertThat;
7 | import static org.junit.contrib.java.lang.system.TextFromStandardInputStream.emptyStandardInputStream;
8 |
9 | import java.io.IOException;
10 | import java.io.InputStream;
11 | import java.util.Scanner;
12 |
13 | import org.junit.BeforeClass;
14 | import org.junit.Rule;
15 | import org.junit.Test;
16 | import org.junit.experimental.runners.Enclosed;
17 | import org.junit.runner.RunWith;
18 | import org.junit.runner.notification.Failure;
19 |
20 | @RunWith(Enclosed.class)
21 | public class TextFromStandardInputStreamTest {
22 | private static final byte[] DUMMY_ARRAY = new byte[1024];
23 | private static final int VALID_OFFSET = 2;
24 | private static final int VALID_READ_LENGTH = 100;
25 | private static final IOException DUMMY_IO_EXCEPTION = new IOException();
26 | private static final RuntimeException DUMMY_RUNTIME_EXCEPTION = new RuntimeException();
27 | private static final com.github.stefanbirkner.fishbowl.Statement READ_NEXT_BYTE
28 | = new com.github.stefanbirkner.fishbowl.Statement() {
29 | public void evaluate() throws Throwable {
30 | System.in.read();
31 | }
32 | };
33 |
34 | @BeforeClass
35 | public static void checkArrayConstants() {
36 | assertThat(VALID_OFFSET).isBetween(0, DUMMY_ARRAY.length);
37 | assertThat(VALID_READ_LENGTH)
38 | .isBetween(0, DUMMY_ARRAY.length - VALID_OFFSET);
39 | }
40 |
41 | public static class provided_text_is_available_from_system_in {
42 | @Rule
43 | public final TextFromStandardInputStream systemInMock
44 | = emptyStandardInputStream();
45 |
46 | @Test
47 | public void test() {
48 | systemInMock.provideText("arbitrary text");
49 | Scanner scanner = new Scanner(in);
50 | String textFromSystemIn = scanner.nextLine();
51 | assertThat(textFromSystemIn).isEqualTo("arbitrary text");
52 | }
53 | }
54 |
55 | public static class specified_texts_are_available_from_system_in {
56 | @Rule
57 | public final TextFromStandardInputStream systemInMock
58 | = emptyStandardInputStream();
59 |
60 | @Test
61 | public void test() {
62 | String lineSeparator = getProperty("line.separator");
63 | systemInMock.provideText("first text" + lineSeparator,
64 | "second text" + lineSeparator);
65 | Scanner firstScanner = new Scanner(in);
66 | firstScanner.nextLine();
67 | Scanner secondScanner = new Scanner(in);
68 | String textFromSystemIn = secondScanner.nextLine();
69 | assertThat(textFromSystemIn).isEqualTo("second text");
70 | }
71 | }
72 |
73 | public static class no_text_is_available_from_system_in_if_no_text_has_been_provided {
74 | @Rule
75 | public final TextFromStandardInputStream systemInMock
76 | = emptyStandardInputStream();
77 |
78 | @Test
79 | public void test() throws Exception {
80 | systemInMock.provideText();
81 | int character = in.read();
82 | assertThat(character).isEqualTo(-1);
83 | }
84 | }
85 |
86 | public static class specified_lines_are_available_from_system_in {
87 | @Rule
88 | public final TextFromStandardInputStream systemInMock
89 | = emptyStandardInputStream();
90 |
91 | @Test
92 | public void test() {
93 | systemInMock.provideLines("first text", "second text");
94 | Scanner firstScanner = new Scanner(in);
95 | firstScanner.nextLine();
96 | Scanner secondScanner = new Scanner(in);
97 | String textFromSystemIn = secondScanner.nextLine();
98 | assertThat(textFromSystemIn).isEqualTo("second text");
99 | }
100 | }
101 |
102 | public static class no_text_is_available_from_system_in_if_no_line_has_been_provided {
103 | @Rule
104 | public final TextFromStandardInputStream systemInMock
105 | = emptyStandardInputStream();
106 |
107 | @Test
108 | public void test() throws Exception {
109 | systemInMock.provideLines();
110 | int character = in.read();
111 | assertThat(character).isEqualTo(-1);
112 | }
113 | }
114 |
115 | public static class system_in_provides_specified_text_and_throws_requested_IOException_afterwards {
116 | @Rule
117 | public final TextFromStandardInputStream systemInMock
118 | = emptyStandardInputStream();
119 |
120 | @Test
121 | public void test() throws Exception {
122 | systemInMock.provideText("arbitrary text");
123 | systemInMock.throwExceptionOnInputEnd(DUMMY_IO_EXCEPTION);
124 | assertSystemInProvidesText("arbitrary text");
125 | Throwable exception = exceptionThrownBy(READ_NEXT_BYTE);
126 | assertThat(exception).isSameAs(DUMMY_IO_EXCEPTION);
127 | }
128 | }
129 |
130 | public static class system_in_throws_requested_IOException_on_first_read_if_no_text_has_been_specified {
131 | @Rule
132 | public final TextFromStandardInputStream systemInMock
133 | = emptyStandardInputStream();
134 |
135 | @Test
136 | public void test() {
137 | systemInMock.throwExceptionOnInputEnd(DUMMY_IO_EXCEPTION);
138 | Throwable exception = exceptionThrownBy(READ_NEXT_BYTE);
139 | assertThat(exception).isSameAs(DUMMY_IO_EXCEPTION);
140 | }
141 | }
142 |
143 | public static class system_in_provides_specified_text_and_throws_requested_RuntimeException_afterwards {
144 | @Rule
145 | public final TextFromStandardInputStream systemInMock
146 | = emptyStandardInputStream();
147 |
148 | @Test
149 | public void test() throws Exception {
150 | systemInMock.provideText("arbitrary text");
151 | systemInMock.throwExceptionOnInputEnd(DUMMY_RUNTIME_EXCEPTION);
152 | assertSystemInProvidesText("arbitrary text");
153 | Throwable exception = exceptionThrownBy(READ_NEXT_BYTE);
154 | assertThat(exception).isSameAs(DUMMY_RUNTIME_EXCEPTION);
155 | }
156 | }
157 |
158 | public static class system_in_throws_requested_RuntimeException_on_first_read_if_no_text_has_been_specified {
159 | @Rule
160 | public final TextFromStandardInputStream systemInMock
161 | = emptyStandardInputStream();
162 |
163 | @Test
164 | public void test() {
165 | systemInMock.throwExceptionOnInputEnd(DUMMY_RUNTIME_EXCEPTION);
166 | Throwable exception = exceptionThrownBy(READ_NEXT_BYTE);
167 | assertThat(exception).isSameAs(DUMMY_RUNTIME_EXCEPTION);
168 | }
169 | }
170 |
171 | @RunWith(AcceptanceTestRunner.class)
172 | public static class an_IOException_cannot_be_requested_if_a_RuntimeException_has_already_been_requested {
173 | public static class TestClass {
174 | @Rule
175 | public final TextFromStandardInputStream systemInMock
176 | = emptyStandardInputStream();
177 |
178 | @Test
179 | public void test() {
180 | systemInMock.throwExceptionOnInputEnd(DUMMY_RUNTIME_EXCEPTION);
181 | systemInMock.throwExceptionOnInputEnd(DUMMY_IO_EXCEPTION);
182 | }
183 | }
184 |
185 | public static void expectFailure(Failure failure) {
186 | assertThat(failure.getMessage())
187 | .isEqualTo("You cannot call throwExceptionOnInputEnd(IOException)"
188 | + " because throwExceptionOnInputEnd(RuntimeException) has"
189 | + " already been called.");
190 | }
191 | }
192 |
193 | @RunWith(AcceptanceTestRunner.class)
194 | public static class a_RuntimeException_cannot_be_requested_if_an_IOException_has_already_been_requested {
195 | public static class TestClass {
196 | @Rule
197 | public final TextFromStandardInputStream systemInMock
198 | = emptyStandardInputStream();
199 |
200 | @Test
201 | public void test() {
202 | systemInMock.throwExceptionOnInputEnd(DUMMY_IO_EXCEPTION);
203 | systemInMock.throwExceptionOnInputEnd(DUMMY_RUNTIME_EXCEPTION);
204 | }
205 | }
206 |
207 | public static void expectFailure(Failure failure) {
208 | assertThat(failure.getMessage())
209 | .isEqualTo("You cannot call"
210 | + " throwExceptionOnInputEnd(RuntimeException) because"
211 | + " throwExceptionOnInputEnd(IOException) has already been"
212 | + " called.");
213 | }
214 | }
215 |
216 | @RunWith(AcceptanceTestRunner.class)
217 | public static class after_the_test_system_in_is_same_as_before {
218 | private static InputStream originalSystemIn;
219 |
220 | @BeforeClass
221 | public static void captureSystemIn() {
222 | originalSystemIn = System.in;
223 | }
224 |
225 | public static class TestClass {
226 | @Rule
227 | public final TextFromStandardInputStream systemInMock
228 | = emptyStandardInputStream();
229 |
230 | @Test
231 | public void test() {
232 | }
233 | }
234 |
235 | public static void verifyStateAfterTest() {
236 | assertThat(System.in).isSameAs(originalSystemIn);
237 | }
238 | }
239 |
240 | @RunWith(AcceptanceTestRunner.class)
241 | //this is default behaviour of an InputStream according to its JavaDoc
242 | public static class system_in_throws_NullPointerException_when_read_is_called_with_null_array {
243 | public static class TestClass {
244 | @Rule
245 | public final TextFromStandardInputStream systemInMock
246 | = emptyStandardInputStream();
247 |
248 | @Test
249 | public void test() throws Exception {
250 | System.in.read(null);
251 | }
252 | }
253 |
254 | public static void expectFailure(Failure failure) {
255 | assertThat(failure.getException())
256 | .isInstanceOf(NullPointerException.class);
257 | }
258 | }
259 |
260 | @RunWith(AcceptanceTestRunner.class)
261 | //this is default behaviour of an InputStream according to its JavaDoc
262 | public static class system_in_throws_IndexOutOfBoundsException_when_read_is_called_with_negative_offset {
263 | public static class TestClass {
264 | @Rule
265 | public final TextFromStandardInputStream systemInMock
266 | = emptyStandardInputStream();
267 |
268 | @Test
269 | public void test() throws Exception {
270 | System.in.read(DUMMY_ARRAY, -1, VALID_READ_LENGTH);
271 | }
272 | }
273 |
274 | public static void expectFailure(Failure failure) {
275 | assertThat(failure.getException())
276 | .isInstanceOf(IndexOutOfBoundsException.class);
277 | }
278 | }
279 |
280 | @RunWith(AcceptanceTestRunner.class)
281 | //this is default behaviour of an InputStream according to its JavaDoc
282 | public static class system_in_throws_IndexOutOfBoundsException_when_read_is_called_with_negative_length {
283 | public static class TestClass {
284 | @Rule
285 | public final TextFromStandardInputStream systemInMock
286 | = emptyStandardInputStream();
287 |
288 | @Test
289 | public void test() throws Exception {
290 | System.in.read(DUMMY_ARRAY, VALID_OFFSET, -1);
291 | }
292 | }
293 |
294 | public static void expectFailure(Failure failure) {
295 | assertThat(failure.getException())
296 | .isInstanceOf(IndexOutOfBoundsException.class);
297 | }
298 | }
299 |
300 | @RunWith(AcceptanceTestRunner.class)
301 | //this is default behaviour of an InputStream according to its JavaDoc
302 | public static class system_in_throws_IndexOutOfBoundsException_when_read_is_called_with_oversized_length {
303 | public static class TestClass {
304 | @Rule
305 | public final TextFromStandardInputStream systemInMock
306 | = emptyStandardInputStream();
307 |
308 | @Test
309 | public void test() throws Exception {
310 | int oversizedLength = DUMMY_ARRAY.length - VALID_OFFSET + 1;
311 | System.in.read(DUMMY_ARRAY, VALID_OFFSET, oversizedLength);
312 | }
313 | }
314 |
315 | public static void expectFailure(Failure failure) {
316 | assertThat(failure.getException())
317 | .isInstanceOf(IndexOutOfBoundsException.class);
318 | }
319 | }
320 |
321 | public static class system_in_reads_zero_bytes_even_if_mock_should_throw_IOException_on_input_end {
322 | @Rule
323 | public final TextFromStandardInputStream systemInMock
324 | = emptyStandardInputStream();
325 |
326 | @Test
327 | public void test() throws Exception {
328 | systemInMock.throwExceptionOnInputEnd(DUMMY_IO_EXCEPTION);
329 | int numBytesRead = System.in.read(DUMMY_ARRAY, VALID_OFFSET, 0);
330 | assertThat(numBytesRead).isZero();
331 | }
332 | }
333 |
334 | public static class system_in_reads_zero_bytes_even_if_mock_should_throw_RuntimeException_on_input_end {
335 | @Rule
336 | public final TextFromStandardInputStream systemInMock
337 | = emptyStandardInputStream();
338 |
339 | @Test
340 | public void test() throws Exception {
341 | systemInMock.throwExceptionOnInputEnd(DUMMY_RUNTIME_EXCEPTION);
342 | int numBytesRead = System.in.read(DUMMY_ARRAY, VALID_OFFSET, 0);
343 | assertThat(numBytesRead).isZero();
344 | }
345 | }
346 |
347 | @RunWith(AcceptanceTestRunner.class)
348 | public static class system_in_read_bytes_throws_specified_IOException_on_input_end {
349 | public static class TestClass {
350 | @Rule
351 | public final TextFromStandardInputStream systemInMock
352 | = emptyStandardInputStream();
353 |
354 | @Test
355 | public void test() throws Exception {
356 | systemInMock.throwExceptionOnInputEnd(DUMMY_IO_EXCEPTION);
357 | System.in.read(DUMMY_ARRAY, VALID_OFFSET, VALID_READ_LENGTH);
358 | }
359 | }
360 |
361 | public static void expectFailure(Failure failure) {
362 | assertThat(failure.getException())
363 | .isSameAs(DUMMY_IO_EXCEPTION);
364 | }
365 | }
366 |
367 | @RunWith(AcceptanceTestRunner.class)
368 | public static class system_in_read_bytes_throws_specified_RuntimeException_on_input_end {
369 | public static class TestClass {
370 | @Rule
371 | public final TextFromStandardInputStream systemInMock
372 | = emptyStandardInputStream();
373 |
374 | @Test
375 | public void test() throws Exception {
376 | systemInMock.throwExceptionOnInputEnd(DUMMY_RUNTIME_EXCEPTION);
377 | System.in.read(DUMMY_ARRAY, VALID_OFFSET, VALID_READ_LENGTH);
378 | }
379 | }
380 |
381 | public static void expectFailure(Failure failure) {
382 | assertThat(failure.getException())
383 | .isSameAs(DUMMY_RUNTIME_EXCEPTION);
384 | }
385 | }
386 |
387 | private static void assertSystemInProvidesText(String text) throws IOException {
388 | for (char c : text.toCharArray())
389 | assertThat((char) System.in.read()).isSameAs(c);
390 | }
391 | }
392 |
--------------------------------------------------------------------------------
/src/test/java/org/junit/contrib/java/lang/system/example/AppWithExit.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system.example;
2 |
3 | public class AppWithExit {
4 | public static String message;
5 |
6 | public static void doSomethingAndExit() {
7 | message = "exit ...";
8 | System.exit(1);
9 | }
10 |
11 | public static void doNothing() {
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/test/java/org/junit/contrib/java/lang/system/example/AppWithExitTest.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system.example;
2 |
3 | import static org.junit.Assert.assertEquals;
4 |
5 | import org.junit.Rule;
6 | import org.junit.Test;
7 | import org.junit.contrib.java.lang.system.Assertion;
8 | import org.junit.contrib.java.lang.system.ExpectedSystemExit;
9 |
10 | public class AppWithExitTest {
11 | @Rule
12 | public final ExpectedSystemExit exit = ExpectedSystemExit.none();
13 |
14 | @Test
15 | public void exits() {
16 | exit.expectSystemExit();
17 | AppWithExit.doSomethingAndExit();
18 | }
19 |
20 | @Test
21 | public void exitsWithStatusCode1() {
22 | exit.expectSystemExitWithStatus(1);
23 | AppWithExit.doSomethingAndExit();
24 | }
25 |
26 | @Test
27 | public void writesMessage() {
28 | exit.expectSystemExitWithStatus(1);
29 | exit.checkAssertionAfterwards(new Assertion() {
30 | public void checkAssertion() {
31 | assertEquals("exit ...", AppWithExit.message);
32 | }
33 | });
34 | AppWithExit.doSomethingAndExit();
35 | }
36 |
37 | @Test
38 | public void systemExitWithStatusCode1() {
39 | exit.expectSystemExitWithStatus(1);
40 | AppWithExit.doSomethingAndExit();
41 | }
42 |
43 | @Test
44 | public void noSystemExit() {
45 | AppWithExit.doNothing();
46 | // passes
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/test/java/org/junit/contrib/java/lang/system/example/Summarize.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system.example;
2 |
3 | import java.util.Scanner;
4 |
5 | public class Summarize {
6 | public static int sumOfNumbersFromSystemIn() {
7 | Scanner scanner = new Scanner(System.in);
8 | int firstSummand = scanner.nextInt();
9 | int secondSummand = scanner.nextInt();
10 | return firstSummand + secondSummand;
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/test/java/org/junit/contrib/java/lang/system/example/SummarizeTest.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system.example;
2 |
3 | import static org.junit.Assert.assertEquals;
4 | import static org.junit.contrib.java.lang.system.TextFromStandardInputStream.emptyStandardInputStream;
5 | import static org.junit.contrib.java.lang.system.example.Summarize.sumOfNumbersFromSystemIn;
6 |
7 | import org.junit.Rule;
8 | import org.junit.Test;
9 | import org.junit.contrib.java.lang.system.TextFromStandardInputStream;
10 |
11 | public class SummarizeTest {
12 | @Rule
13 | public final TextFromStandardInputStream systemInMock = emptyStandardInputStream();
14 |
15 | @Test
16 | public void summarizesTwoNumbers() {
17 | systemInMock.provideText("1\n2\n");
18 | assertEquals(3, sumOfNumbersFromSystemIn());
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/test/java/org/junit/contrib/java/lang/system/internal/NoExitSecurityManagerTest.java:
--------------------------------------------------------------------------------
1 | package org.junit.contrib.java.lang.system.internal;
2 |
3 | import static com.github.stefanbirkner.fishbowl.Fishbowl.exceptionThrownBy;
4 | import static java.util.Arrays.asList;
5 | import static org.assertj.core.api.Assertions.assertThat;
6 | import static org.junit.Assume.assumeTrue;
7 | import static org.mockito.Mockito.mock;
8 | import static org.mockito.Mockito.mockingDetails;
9 | import static org.mockito.Mockito.when;
10 |
11 | import java.io.FileDescriptor;
12 | import java.lang.reflect.Method;
13 | import java.util.*;
14 |
15 | import com.github.stefanbirkner.fishbowl.Statement;
16 | import org.junit.Test;
17 | import org.junit.experimental.runners.Enclosed;
18 | import org.junit.runner.RunWith;
19 | import org.junit.runners.Parameterized;
20 | import org.junit.runners.Parameterized.Parameter;
21 | import org.junit.runners.Parameterized.Parameters;
22 | import org.mockito.invocation.Invocation;
23 |
24 | @RunWith(Enclosed.class)
25 | public class NoExitSecurityManagerTest {
26 |
27 | @RunWith(Parameterized.class)
28 | public static class tests_common_to_both_scenarios {
29 | private static final int DUMMY_STATUS = 1;
30 |
31 | @Parameters(name = "{0}")
32 | public static List data() {
33 | return asList(
34 | new Object[] {
35 | "with_original_SecurityManager",
36 | mock(SecurityManager.class)
37 | },
38 | new Object[] {
39 | "without_original_SecurityManager",
40 | null
41 | }
42 | );
43 | }
44 |
45 | private final NoExitSecurityManager securityManager;
46 |
47 | public tests_common_to_both_scenarios(
48 | String name, SecurityManager originalManager) {
49 | securityManager = new NoExitSecurityManager(originalManager);
50 | }
51 |
52 | @Test
53 | public void an_exception_with_the_status_is_thrown_when_checkExit_is_called() {
54 | CheckExitCalled exception = exceptionThrownBy(new Statement() {
55 | public void evaluate() {
56 | securityManager.checkExit(DUMMY_STATUS);
57 | }
58 | }, CheckExitCalled.class);
59 | assertThat(exception.getStatus()).isEqualTo(DUMMY_STATUS);
60 | }
61 |
62 | @Test
63 | public void information_about_a_missing_checkExit_call_is_available() {
64 | assertThat(securityManager.isCheckExitCalled()).isFalse();
65 | }
66 |
67 | @Test
68 | public void information_about_a_checkExit_call_is_available() {
69 | safeCallCheckExitWithStatus(DUMMY_STATUS);
70 | assertThat(securityManager.isCheckExitCalled()).isTrue();
71 | }
72 |
73 | @Test
74 | public void status_of_first_call_of_checkExit_is_available() {
75 | safeCallCheckExitWithStatus(DUMMY_STATUS);
76 | safeCallCheckExitWithStatus(DUMMY_STATUS + 1);
77 | assertThat(securityManager.getStatusOfFirstCheckExitCall())
78 | .isEqualTo(DUMMY_STATUS);
79 | }
80 |
81 | private void safeCallCheckExitWithStatus(int status) {
82 | try {
83 | securityManager.checkExit(status);
84 | } catch (CheckExitCalled ignored) {
85 | }
86 | }
87 |
88 | @Test
89 | public void fails_to_provide_status_of_first_checkExit_call_if_this_call_did_not_happen() {
90 | Throwable exception = exceptionThrownBy(new Statement() {
91 | public void evaluate() {
92 | securityManager.getStatusOfFirstCheckExitCall();
93 | }
94 | });
95 | assertThat(exception)
96 | .isInstanceOf(IllegalStateException.class)
97 | .hasMessage("checkExit(int) has not been called.");
98 | }
99 | }
100 |
101 | @RunWith(Parameterized.class)
102 | public static class public_non_void_methods {
103 |
104 | @Parameters(name = "{0}")
105 | public static List data() {
106 | List methods = new ArrayList();
107 | for (Method method : NoExitSecurityManager.class.getMethods())
108 | if (!voidMethod(method) && notDeclaredByObjectClass(method))
109 | methods.add(new Object[] { testName(method), method });
110 | return methods;
111 | }
112 |
113 | @Parameter(0)
114 | public String methodName;
115 |
116 | @Parameter(1)
117 | public Method method;
118 |
119 | @Test
120 | public void is_implemented_by_NoExitSecurityManager() {
121 | assertThat(method.getDeclaringClass())
122 | .isEqualTo(NoExitSecurityManager.class);
123 | }
124 | }
125 |
126 | @RunWith(Parameterized.class)
127 | public static class public_void_methods {
128 | @Parameters(name = "{0}")
129 | public static List data() {
130 | List methods = new ArrayList();
131 | for (Method method : NoExitSecurityManager.class.getMethods()) {
132 | if (voidMethod(method)
133 | && notDeclaredByObjectClass(method)
134 | && notChangedByNoExitSecurityManager(method))
135 | methods.add(new Object[] { testName(method), method });
136 | }
137 | return methods;
138 | }
139 |
140 | @Parameter(0)
141 | public String testName;
142 |
143 | @Parameter(1)
144 | public Method method;
145 |
146 | @Test
147 | public void is_implemented_by_NoExitSecurityManager() {
148 | assertThat(method.getDeclaringClass())
149 | .isEqualTo(NoExitSecurityManager.class);
150 | }
151 |
152 | @Test
153 | public void may_be_called_when_original_security_manager_is_missing(
154 | ) throws Exception {
155 | SecurityManager manager = new NoExitSecurityManager(null);
156 | method.invoke(manager, dummyArguments());
157 | }
158 |
159 | @Test
160 | public void is_delegated_to_original_security_manager_when_it_is_present(
161 | ) throws Exception {
162 | SecurityManager originalManager = mock(SecurityManager.class);
163 | SecurityManager manager = new NoExitSecurityManager(
164 | originalManager);
165 | Object[] arguments = dummyArguments();
166 | method.invoke(manager, arguments);
167 | assertCallIsDelegated(originalManager, arguments);
168 | }
169 |
170 | private Object[] dummyArguments() {
171 | Class>[] parameterTypes = method.getParameterTypes();
172 | Object[] args = new Object[parameterTypes.length];
173 | for (int i = 0; i < args.length; ++i)
174 | args[i] = dummy(parameterTypes[i]);
175 | return args;
176 | }
177 |
178 | private Object dummy(Class> type) {
179 | if (type.getName().equals("int"))
180 | return new Random().nextInt();
181 | else if (type.getName().equals("byte"))
182 | return (byte) new Random().nextInt();
183 | else if (type.equals(String.class))
184 | return UUID.randomUUID().toString();
185 | else if (type.equals(Class.class))
186 | return String.class;
187 | else if (type.equals(FileDescriptor.class))
188 | return new FileDescriptor();
189 | else
190 | return mock(type);
191 | }
192 |
193 | private void assertCallIsDelegated(
194 | SecurityManager target, Object[] arguments) {
195 | Collection invocations = mockingDetails(target)
196 | .getInvocations();
197 | assertThat(invocations).hasSize(1);
198 | Invocation invocation = invocations.iterator().next();
199 | assertThat(invocation.getMethod())
200 | .isEqualToComparingOnlyGivenFields(
201 | method, "name", "parameterTypes", "returnType");
202 | assertThat(invocation.getRawArguments()).containsExactly(arguments);
203 | }
204 | }
205 |
206 | public static class with_original_SecurityManager {
207 | private final SecurityManager originalSecurityManager = mock(SecurityManager.class);
208 | private final NoExitSecurityManager managerWithOriginal = new NoExitSecurityManager(
209 | originalSecurityManager);
210 |
211 | @Test
212 | public void getInCheck_is_delegated_to_original_security_manager() {
213 | //method "getInCheck" was removed in JDK 10
214 | skipOnJavaGreaterThan9();
215 | when(originalSecurityManager.getInCheck()).thenReturn(true);
216 | assertThat(managerWithOriginal.getInCheck()).isTrue();
217 | }
218 |
219 | @Test
220 | public void security_context_of_original_security_manager_is_provided() {
221 | Object context = new Object();
222 | when(originalSecurityManager.getSecurityContext()).thenReturn(context);
223 | assertThat(managerWithOriginal.getSecurityContext()).isSameAs(context);
224 | }
225 |
226 | @Test
227 | public void checkTopLevelWindow_is_delegated_to_original_security_manager() {
228 | Object window = new Object();
229 | when(originalSecurityManager.checkTopLevelWindow(window)).thenReturn(true);
230 | assertThat(managerWithOriginal.checkTopLevelWindow(window)).isTrue();
231 | }
232 |
233 | @Test
234 | public void thread_group_of_original_security_manager_is_provided() {
235 | ThreadGroup threadGroup = new ThreadGroup("dummy name");
236 | when(originalSecurityManager.getThreadGroup()).thenReturn(threadGroup);
237 | assertThat(managerWithOriginal.getThreadGroup()).isSameAs(threadGroup);
238 | }
239 |
240 | private void skipOnJavaGreaterThan9() {
241 | String version = System.getProperty("java.version");
242 | assumeTrue(
243 | version.startsWith("1.") || version.equals("9")
244 | );
245 | }
246 | }
247 |
248 | public static class without_original_SecurityManager {
249 | private final NoExitSecurityManager managerWithoutOriginal = new NoExitSecurityManager(null);
250 |
251 | @Test
252 | public void getInCheck_returns_false() {
253 | assertThat(managerWithoutOriginal.getInCheck()).isFalse();
254 | }
255 |
256 | @Test
257 | public void getSecurityContext_may_be_called() {
258 | managerWithoutOriginal.getSecurityContext();
259 | }
260 |
261 | @Test
262 | public void checkTopLevelWindow_may_be_called() {
263 | Object window = new Object();
264 | managerWithoutOriginal.checkTopLevelWindow(window);
265 | }
266 |
267 | @Test
268 | public void getThreadGroup_may_be_called() {
269 | managerWithoutOriginal.getThreadGroup();
270 | }
271 | }
272 |
273 | private static boolean notChangedByNoExitSecurityManager(Method method) {
274 | return !method.getName().equals("checkExit");
275 | }
276 |
277 | private static boolean notDeclaredByObjectClass(Method method) {
278 | return !method.getDeclaringClass().equals(Object.class);
279 | }
280 |
281 | private static boolean voidMethod(Method method) {
282 | return method.getReturnType().getName().equals("void");
283 | }
284 |
285 | private static String testName(Method method) {
286 | return method.getName()
287 | + "(" + join(method.getParameterTypes()) + ")";
288 | }
289 |
290 | private static String join(Class>[] types) {
291 | StringBuilder sb = new StringBuilder();
292 | for (int i = 0; i < types.length; i++) {
293 | if (i != 0)
294 | sb.append(",");
295 | sb.append(types[i].getSimpleName());
296 | }
297 | return sb.toString();
298 | }
299 | }
300 |
--------------------------------------------------------------------------------
/src/test/resources/org/junit/contrib/java/lang/system/example.properties:
--------------------------------------------------------------------------------
1 | arbitrary\ property=arbitrary value
--------------------------------------------------------------------------------